// Split PDF — extract chosen pages (or every page) as a new PDF via pdf-lib.

const PDFLIB_URL = 'https://cdn.jsdelivr.net/npm/pdf-lib@1.17.1/dist/pdf-lib.min.js';

window.TOOL_HANDLERS['split-pdf'] = function SplitPdfTool() {
  const [file, setFile] = React.useState(null);
  const [pageCount, setPageCount] = React.useState(0);
  const [mode, setMode] = React.useState('range');  // 'range' | 'each'
  const [range, setRange] = React.useState('');     // e.g. "1-3, 5, 7-8"
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const handleFile = async (f) => {
    setErr('');
    if (!f) return;
    await window.loadScript(PDFLIB_URL);
    const { PDFDocument } = window.PDFLib;
    const bytes = new Uint8Array(await f.arrayBuffer());
    const doc = await PDFDocument.load(bytes);
    setFile(f); setPageCount(doc.getPageCount());
    setRange(`1-${doc.getPageCount()}`);
  };

  const parseRange = (text, total) => {
    const out = [];
    for (const part of text.split(',').map((s) => s.trim()).filter(Boolean)) {
      const m = /^(\d+)\s*-\s*(\d+)$/.exec(part);
      if (m) {
        let [a, b] = [+m[1], +m[2]]; if (a > b) [a, b] = [b, a];
        for (let i = a; i <= b; i++) if (i >= 1 && i <= total) out.push(i - 1);
      } else if (/^\d+$/.test(part)) {
        const i = +part; if (i >= 1 && i <= total) out.push(i - 1);
      }
    }
    return [...new Set(out)];
  };

  const run = async () => {
    setBusy(true); setErr('');
    try {
      const { PDFDocument } = window.PDFLib;
      const bytes = new Uint8Array(await file.arrayBuffer());
      const src = await PDFDocument.load(bytes);
      const baseName = file.name.replace(/\.pdf$/i, '');

      if (mode === 'each') {
        for (let i = 0; i < src.getPageCount(); i++) {
          const out = await PDFDocument.create();
          const [p] = await out.copyPages(src, [i]); out.addPage(p);
          const saved = await out.save();
          window.downloadBlob(new Blob([saved], { type: 'application/pdf' }),
            `${baseName}-p${String(i + 1).padStart(3, '0')}.pdf`);
        }
      } else {
        const indices = parseRange(range, src.getPageCount());
        if (indices.length === 0) throw new Error('No valid pages in range');
        const out = await PDFDocument.create();
        const pages = await out.copyPages(src, indices);
        pages.forEach((p) => out.addPage(p));
        const saved = await out.save();
        window.downloadBlob(new Blob([saved], { type: 'application/pdf' }), `${baseName}-split.pdf`);
      }
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop a PDF here" hint="we'll show its page count" accept="application/pdf,.pdf" />;

  return (
    <div className="mini-tool">
      <div style={{ padding: 12, background: 'var(--id-surface-alt)', borderRadius: 10, marginBottom: 14 }}>
        <strong>{file.name}</strong>
        <div className="cmp-meta">{pageCount} pages · {window.fmtBytes(file.size)}</div>
      </div>

      <div className="mini-row">
        <button className={`filter-pill ${mode === 'range' ? 'active' : ''}`} onClick={() => setMode('range')}>Extract a range</button>
        <button className={`filter-pill ${mode === 'each' ? 'active' : ''}`} onClick={() => setMode('each')}>One PDF per page</button>
      </div>

      {mode === 'range' && (
        <>
          <label className="mini-label" style={{ marginTop: 14 }}>Pages (e.g. 1-3, 5, 7-{pageCount})</label>
          <input className="mini-input" value={range} onChange={(e) => setRange(e.target.value)} />
        </>
      )}

      {err && <div style={{ color: '#c8321f', marginTop: 10 }}>{err}</div>}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => setFile(null)}><window.Icon name="upload" size={16} /> Another PDF</button>
        <button className="btn btn-primary" onClick={run} disabled={busy}><window.Icon name="split" size={16} /> {busy ? 'Splitting…' : 'Split'}</button>
      </div>
    </div>
  );
};
