// Merge Excel — combine every sheet from several workbooks into one .xlsx.

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

window.TOOL_HANDLERS['merge-excel'] = function MergeExcelTool() {
  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) => /\.(xlsx|xls)$/i.test(f.name))]);
  };
  const removeAt = (i) => setFiles((prev) => prev.filter((_, idx) => idx !== i));

  const run = async () => {
    setBusy(true); setErr('');
    try {
      await window.loadScript(XLSX_URL);
      const out = window.XLSX.utils.book_new();
      const seen = new Set();
      for (const f of files) {
        const wb = window.XLSX.read(await f.arrayBuffer(), { type: 'array' });
        const base = f.name.replace(/\.(xlsx|xls)$/i, '');
        for (const name of wb.SheetNames) {
          let candidate = wb.SheetNames.length === 1 ? base : `${base}__${name}`;
          candidate = candidate.slice(0, 31).replace(/[/\\?%*:|"<>]/g, '_');
          let n = candidate, k = 2;
          while (seen.has(n)) { n = (candidate.slice(0, 28) + '_' + k).slice(0, 31); k++; }
          seen.add(n);
          window.XLSX.utils.book_append_sheet(out, wb.Sheets[name], n);
        }
      }
      const bytes = window.XLSX.write(out, { bookType: 'xlsx', type: 'array' });
      window.downloadBlob(new Blob([bytes], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'merged.xlsx');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (files.length === 0) return <window.Dropzone onFile={addFiles} multiple title="Drop Excel files here" hint=".xlsx / .xls — 2 or more" accept=".xlsx,.xls" />;

  return (
    <div className="mini-tool">
      <div className="mini-label">{files.length} workbook{files.length === 1 ? '' : 's'}</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="table" 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={() => removeAt(i)}><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=".xlsx,.xls" multiple hidden onChange={(e) => addFiles(Array.from(e.target.files))} />
        </label>
        <button className="btn btn-primary" onClick={run} disabled={busy || files.length < 2}>
          <window.Icon name="merge" size={16} /> {busy ? 'Merging…' : `Merge ${files.length} workbooks`}
        </button>
      </div>
    </div>
  );
};
