// Rotate PDF — apply 90/180/270° rotation to every page via pdf-lib.

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

window.TOOL_HANDLERS['rotate-pdf'] = function RotatePdfTool() {
  const [file, setFile] = React.useState(null);
  const [angle, setAngle] = React.useState(90);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const run = async () => {
    setBusy(true); setErr('');
    try {
      await window.loadScript(PDFLIB_URL);
      const { PDFDocument, degrees } = window.PDFLib;
      const bytes = new Uint8Array(await file.arrayBuffer());
      const doc = await PDFDocument.load(bytes);
      for (const p of doc.getPages()) {
        const current = p.getRotation().angle;
        p.setRotation(degrees((current + angle) % 360));
      }
      const saved = await doc.save();
      window.downloadBlob(new Blob([saved], { type: 'application/pdf' }),
        file.name.replace(/\.pdf$/i, '') + `-rotated.pdf`);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (!file) return <window.Dropzone onFile={setFile} title="Drop a PDF here" hint="rotate every page" 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">{window.fmtBytes(file.size)}</div>
      </div>
      <div className="mini-label">Rotation</div>
      <div className="mini-row">
        {[90, 180, 270].map((a) => (
          <button key={a} className={`filter-pill ${angle === a ? 'active' : ''}`} onClick={() => setAngle(a)}>{a}°</button>
        ))}
      </div>
      {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="rotate" size={16} /> {busy ? 'Rotating…' : 'Download rotated'}
        </button>
      </div>
    </div>
  );
};
