// Merge PDF — combine multiple PDFs into one using pdf-lib (CDN).

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

window.TOOL_HANDLERS['merge-pdf'] = function MergePdfTool() {
  const [files, setFiles] = React.useState([]);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const addFiles = (picked) => {
    const list = Array.isArray(picked) ? picked : [picked];
    setFiles((prev) => [...prev, ...list.filter((f) => f.type === 'application/pdf' || f.name.toLowerCase().endsWith('.pdf'))]);
  };
  const removeAt = (i) => setFiles((prev) => prev.filter((_, idx) => idx !== i));
  const move = (i, dir) => setFiles((prev) => {
    const next = [...prev]; const j = i + dir;
    if (j < 0 || j >= next.length) return prev;
    [next[i], next[j]] = [next[j], next[i]]; return next;
  });

  const merge = async () => {
    setBusy(true); setErr('');
    try {
      await window.loadScript(PDFLIB_URL);
      const { PDFDocument } = window.PDFLib;
      const out = await PDFDocument.create();
      for (const f of files) {
        const bytes = new Uint8Array(await f.arrayBuffer());
        const src = await PDFDocument.load(bytes);
        const pages = await out.copyPages(src, src.getPageIndices());
        pages.forEach((p) => out.addPage(p));
      }
      const merged = await out.save();
      window.downloadBlob(new Blob([merged], { type: 'application/pdf' }), 'merged.pdf');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (files.length === 0) return <window.Dropzone onFile={addFiles} multiple title="Drop PDFs here" hint="2 or more files, in order" accept="application/pdf,.pdf" />;

  return (
    <div className="mini-tool">
      <div className="mini-label">{files.length} file{files.length === 1 ? '' : 's'} · drag-reorder with arrows</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
        {files.map((f, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 10, background: 'var(--id-surface-alt)', borderRadius: 10 }}>
            <window.Icon name="doc" size={18} />
            <div style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
            <span className="cmp-meta">{window.fmtBytes(f.size)}</span>
            <button className="icon-btn" onClick={() => move(i, -1)} disabled={i === 0} aria-label="Up">↑</button>
            <button className="icon-btn" onClick={() => move(i, 1)} disabled={i === files.length - 1} aria-label="Down">↓</button>
            <button className="icon-btn" onClick={() => removeAt(i)} aria-label="Remove"><window.Icon name="x" size={14} /></button>
          </div>
        ))}
      </div>
      {err && <div style={{ color: '#c8321f', marginTop: 10 }}>{err}</div>}
      <div className="cmp-actions">
        <label className="btn btn-secondary">
          <window.Icon name="upload" size={16} /> Add more
          <input type="file" accept="application/pdf,.pdf" multiple hidden onChange={(e) => addFiles(Array.from(e.target.files))} />
        </label>
        <button className="btn btn-primary" onClick={merge} disabled={busy || files.length < 2}>
          <window.Icon name="merge" size={16} /> {busy ? 'Merging…' : `Merge ${files.length} PDFs`}
        </button>
      </div>
    </div>
  );
};
