// Split Excel — open a workbook, emit one .xlsx per sheet, bundle as zip.

const XLSX_URL = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
const FFLATE_URL = 'https://cdn.jsdelivr.net/npm/fflate@0.8.2/umd/index.js';

window.TOOL_HANDLERS['split-excel'] = function SplitExcelTool() {
  const [file, setFile] = React.useState(null);
  const [sheets, setSheets] = React.useState([]);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const handleFile = async (f) => {
    if (!f) return;
    setBusy(true); setErr(''); setFile(f);
    try {
      await window.loadScript(XLSX_URL);
      const buf = await f.arrayBuffer();
      const wb = window.XLSX.read(buf, { type: 'array' });
      setSheets(wb.SheetNames);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const run = async () => {
    setBusy(true); setErr('');
    try {
      await window.loadScript(FFLATE_URL);
      const buf = await file.arrayBuffer();
      const wb = window.XLSX.read(buf, { type: 'array' });
      const zip = {};
      const base = file.name.replace(/\.(xlsx|xls)$/i, '');
      for (const name of wb.SheetNames) {
        const sub = window.XLSX.utils.book_new();
        window.XLSX.utils.book_append_sheet(sub, wb.Sheets[name], name);
        const bytes = window.XLSX.write(sub, { bookType: 'xlsx', type: 'array' });
        const safe = name.replace(/[/\\?%*:|"<>]/g, '_');
        zip[`${base}-${safe}.xlsx`] = new Uint8Array(bytes);
      }
      window.fflate.zip(zip, (zerr, data) => {
        if (zerr) return setErr(zerr.message);
        window.downloadBlob(new Blob([data], { type: 'application/zip' }), `${base}-sheets.zip`);
      });
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop an Excel file here" hint=".xlsx / .xls — one file per sheet" accept=".xlsx,.xls" />;

  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)} · {sheets.length} sheet{sheets.length === 1 ? '' : 's'}</div>
      </div>
      {sheets.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
          {sheets.map((n) => <span key={n} className="filter-pill active" style={{ pointerEvents: 'none' }}>{n}</span>)}
        </div>
      )}
      {err && <div style={{ color: '#c8321f' }}>{err}</div>}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setSheets([]); }}><window.Icon name="upload" size={16} /> Another file</button>
        <button className="btn btn-primary" onClick={run} disabled={busy || sheets.length === 0}>
          <window.Icon name="split" size={16} /> {busy ? 'Splitting…' : `Download ${sheets.length} files as ZIP`}
        </button>
      </div>
    </div>
  );
};
