/* studio.pdfimport.parts.jsx - bring a PDF in as an editable sheet.
 *
 * This is the merge point. The converter runs entirely in the browser: pdf.js
 * renders the page (so it looks like the PDF, in the PDF's own fonts), lifts
 * every text run, and emits one .html carrying an embedded sitm-document. That
 * script tag is the only thing the Cheat Sheet Editor reads.
 *
 * Loaded as <script type="text/babel">, so no imports: convert() is fetched as a
 * module at click time and the page registers itself on window like every other
 * part file.
 */

function PdfImportPage({ go, toast, onSaveFile }) {
  const [busy, setBusy] = React.useState(false);
  const [note, setNote] = React.useState('');
  const [err, setErr] = React.useState('');
  const [result, setResult] = React.useState(null);
  const input = React.useRef(null);
  const [over, setOver] = React.useState(false);

  async function run(file) {
    if (!file) return;
    if (!/\.pdf$/i.test(file.name)) { setErr('That file is not a PDF.'); return; }
    setErr(''); setResult(null); setBusy(true); setNote('Reading the PDF…');
    try {
      // convert.js is loaded as a real ES module by index.html and handed over
      // on window. Importing it here instead would be compiled by Babel
      // Standalone into require(), which a browser has no answer for.
      if (!window.PdfConvert) throw new Error('the converter is still loading, try again in a moment');
      const out = await window.PdfConvert(file, setNote);
      setResult(out);
      setNote('');
      toast && toast('Converted "' + out.title + '".');
    } catch (e) {
      setErr('Could not convert this PDF: ' + (e && e.message ? e.message : String(e)));
    } finally {
      setBusy(false);
    }
  }

  function download() {
    const blob = new Blob([result.html], { type: 'text/html' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = result.title + '.html';
    a.click();
    setTimeout(() => URL.revokeObjectURL(a.href), 1000);
    onSaveFile && onSaveFile({ name: result.title + '.html', type: 'Worksheet', kind: 'pdf' });
    toast && toast('Saved to My files.');
  }

  // The exact payload EditorPage reads (studio.editor.parts.jsx: payload.pdfUpload).
  function openInEditor() {
    onSaveFile && onSaveFile({ name: result.title + '.html', type: 'Worksheet', kind: 'pdf' });
    go('editor', { pdfUpload: true, pdfName: result.title + '.pdf', converted: result });
  }

  const s = result && result.stats;

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: '28px 24px 80px' }}>
      <PageHead
        title="Import a PDF"
        sub="Turn one of your existing cheat sheet PDFs into a sheet you can edit. The fonts, diagrams and layout come across as they are."
      />

      {/* A div with a hidden input is unreachable by keyboard and announces
          nothing. Given a button role, a tab stop, and Enter/Space it behaves
          like the control it looks like. */}
      <div
        role="button"
        tabIndex={busy ? -1 : 0}
        aria-label="Choose a PDF to import, or drop one here"
        aria-busy={busy}
        onClick={() => !busy && input.current && input.current.click()}
        onKeyDown={(e) => {
          if (busy) return;
          if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.current && input.current.click(); }
        }}
        onFocus={() => setOver(true)}
        onBlur={() => setOver(false)}
        onDragOver={(e) => { e.preventDefault(); setOver(true); }}
        onDragLeave={(e) => { e.preventDefault(); setOver(false); }}
        onDrop={(e) => { e.preventDefault(); setOver(false); run(e.dataTransfer.files[0]); }}
        style={{
          border: '2px dashed ' + (over ? 'var(--sitm-teal)' : 'var(--sitm-border)'),
          background: over ? 'rgba(97,189,183,.08)' : '#fff',
          borderRadius: 14, padding: '52px 24px', textAlign: 'center',
          cursor: busy ? 'default' : 'pointer', transition: 'border-color .15s, background .15s',
        }}
      >
        <div style={{ fontFamily: 'var(--sitm-font-heading)', fontSize: 19, marginBottom: 6 }}>
          {busy ? (note || 'Working…') : 'Choose a PDF'}
        </div>
        <div style={{ color: 'var(--sitm-text-muted, #6b7a80)', fontSize: 13.5 }}>
          {busy ? 'This runs on your computer — nothing is uploaded.' : 'or drop one here'}
        </div>
        <input ref={input} type="file" accept="application/pdf,.pdf" style={{ display: 'none' }}
          onChange={(e) => { run(e.target.files[0]); e.target.value = ''; }} />
      </div>

      {err && (
        <div style={{
          marginTop: 16, padding: '12px 14px', borderRadius: 10, fontSize: 13.5,
          background: '#fdf3f2', border: '1px solid #df534b', color: '#a3312b',
        }}>{err}</div>
      )}

      {result && (
        <div style={{ marginTop: 22 }}>
          <div style={{ display: 'flex', gap: 22, flexWrap: 'wrap', fontSize: 13.5, marginBottom: 14 }}>
            <span><b>{s.pages}</b> page{s.pages === 1 ? '' : 's'}</span>
            <span><b>{s.fonts}</b> fonts kept</span>
            <span><b>{s.runs}</b> lines of text</span>
            <span><b>{s.blocks}</b> editable blocks</span>
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 18 }}>
            <Btn primary onClick={openInEditor}>Open in the editor</Btn>
            <Btn icon="download" onClick={download}>Download .html</Btn>
          </div>
          <iframe
            title="Converted sheet"
            srcDoc={result.html}
            style={{
              width: '100%', height: 720, border: '1px solid var(--sitm-border)',
              borderRadius: 12, background: '#fff',
            }}
          />
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PdfImportPage });
