// CSV to Excel — parse CSV with SheetJS, emit a real .xlsx workbook.

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

window.TOOL_HANDLERS['csv-to-excel'] = function CsvToExcelTool() {
  const [file, setFile] = React.useState(null);
  const [preview, setPreview] = React.useState(null);
  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 text = await f.text();
      const wb = window.XLSX.read(text, { type: 'string' });
      const sheet = wb.Sheets[wb.SheetNames[0]];
      const rows = window.XLSX.utils.sheet_to_json(sheet, { header: 1 });
      setPreview({ rows: rows.slice(0, 6), total: rows.length });
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const convert = async () => {
    setBusy(true); setErr('');
    try {
      const text = await file.text();
      const wb = window.XLSX.read(text, { type: 'string' });
      const out = window.XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      window.downloadBlob(new Blob([out], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
        file.name.replace(/\.csv$/i, '') + '.xlsx');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop a CSV here" hint=".csv / .tsv — produces .xlsx" accept=".csv,.tsv,text/csv" />;

  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)}{preview ? ` · ${preview.total} rows` : ''}</div>
      </div>

      {preview && (
        <div style={{ overflow: 'auto', border: '1px solid var(--id-border)', borderRadius: 10, marginBottom: 14 }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <tbody>
              {preview.rows.map((row, i) => (
                <tr key={i}>
                  {row.map((cell, j) => (
                    <td key={j} style={{
                      padding: '6px 10px', borderBottom: '1px solid var(--id-border)',
                      background: i === 0 ? 'var(--id-surface-alt)' : 'transparent',
                      fontWeight: i === 0 ? 700 : 400,
                    }}>{String(cell ?? '')}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
          {preview.total > 6 && <div className="cmp-meta" style={{ padding: 8 }}>… and {preview.total - 6} more</div>}
        </div>
      )}

      {err && <div style={{ color: '#c8321f' }}>{err}</div>}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setPreview(null); }}><window.Icon name="upload" size={16} /> Another CSV</button>
        <button className="btn btn-primary" onClick={convert} disabled={busy}><window.Icon name="download" size={16} /> Download XLSX</button>
      </div>
    </div>
  );
};
