// Converts a dropped PDF and hands the result to the caller to store and open.
function ImportPage({ onConverted, toast }) {
  const [busy, setBusy] = React.useState(false);
  const [note, setNote] = React.useState('');
  const [err, setErr] = React.useState('');
  const [scale, setScale] = React.useState(2);
  const [raster, setRaster] = React.useState('png');
  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(''); setBusy(true); setNote('Reading the PDF…');
    try {
      if (!window.PdfConvert) throw new Error('the converter is still loading, try again in a moment');
      const out = await window.PdfConvert(file, setNote, { scale: Number(scale), raster });
      setNote('');
      toast(`Converted "${out.title}".`);
      onConverted(out);
    } catch (e) {
      setErr('Could not convert this PDF: ' + (e && e.message ? e.message : String(e)));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="stage-in">
      <Head
        kicker="Import"
        title="Turn a PDF into a document you can edit"
        sub="One file comes out carrying two things: the page exactly as it prints, and the text
             rebuilt into blocks you can edit. The fonts are the document's own. Nothing is
             uploaded and there is no server to upload it to."
      />

      <div
        className={'drop' + (over ? ' over' : '')}
        role="button"
        tabIndex={busy ? -1 : 0}
        aria-label="Choose a PDF to convert, 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.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]); }}
      >
        <div className="h2" style={{ marginBottom: 6 }}>{busy ? (note || 'Working…') : 'Choose a PDF'}</div>
        <div className="sub" style={{ fontSize: 'var(--fs-300)', color: 'var(--muted)' }}>
          {busy ? 'Converting in this browser. 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>

      <div style={{ display: 'flex', gap: 'var(--s-5)', flexWrap: 'wrap', marginTop: 'var(--s-4)' }}>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span className="label">Raster resolution</span>
          <select className="btn" value={scale} disabled={busy}
            onChange={(e) => setScale(e.target.value)}>
            <option value="1">72 DPI, smallest file</option>
            <option value="2">144 DPI, default</option>
            <option value="3">216 DPI, print review</option>
          </select>
        </label>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span className="label">Page image</span>
          <select className="btn" value={raster} disabled={busy}
            onChange={(e) => setRaster(e.target.value)}>
            <option value="png">PNG, exact</option>
            <option value="jpeg">JPEG, smaller</option>
            <option value="none">None, text only</option>
          </select>
        </label>
      </div>

      {err && <div className="notice notice-err" style={{ marginTop: 'var(--s-4)' }}>{err}</div>}

      <div className="card" style={{ marginTop: 'var(--s-6)', padding: 'var(--s-5)' }}>
        <div className="label" style={{ marginBottom: 'var(--s-3)' }}>What each layer can and cannot do</div>
        <div style={{ display: 'grid', gap: 'var(--s-4)', gridTemplateColumns: 'repeat(auto-fit,minmax(260px,1fr))' }}>
          {[
            ['Replica', 'chip-fixed', 'The page exactly as it prints, with the text sitting on it as real, selectable HTML in the PDF’s own fonts. Faithful to the pixel. It does not reflow, and editing a word does not repaint the picture underneath it.'],
            ['Structure', 'chip-recon', 'Headings, paragraphs and bullets rebuilt from the text runs. Edits, reflows and exports as clean HTML. It carries no layout, so a two-column page comes back as one column of blocks in reading order.'],
          ].map(([name, cls, body]) => (
            <div key={name}>
              <span className={'chip ' + cls}>{name}</span>
              <p className="sub" style={{ fontSize: 'var(--fs-300)', marginTop: 'var(--s-2)' }}>{body}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ImportPage });
