// Unzip File — list entries of a .zip archive and download them individually.

const FFLATE_URL = 'https://cdn.jsdelivr.net/npm/fflate@0.8.2/umd/index.js';

window.TOOL_HANDLERS['unzip'] = function UnzipTool() {
  const [file, setFile] = React.useState(null);
  const [entries, setEntries] = React.useState([]);  // { name, u8 }
  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(FFLATE_URL);
      const u8 = new Uint8Array(await f.arrayBuffer());
      const unzipped = window.fflate.unzipSync(u8);
      const list = Object.entries(unzipped)
        .filter(([name]) => !name.endsWith('/'))
        .map(([name, data]) => ({ name, u8: data }));
      setEntries(list);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const mimeFor = (name) => {
    const ext = name.toLowerCase().split('.').pop();
    return ({ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif',
              pdf: 'application/pdf', txt: 'text/plain', json: 'application/json', csv: 'text/csv',
              html: 'text/html', md: 'text/markdown' })[ext] || 'application/octet-stream';
  };

  const saveOne = (e) => {
    window.downloadBlob(new Blob([e.u8], { type: mimeFor(e.name) }), e.name.split('/').pop());
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop a .zip here" hint="we'll list its entries" accept=".zip,application/zip" />;

  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)} · {entries.length} file{entries.length === 1 ? '' : 's'}</div>
      </div>
      {busy && <div className="cmp-meta" style={{ textAlign: 'center', padding: 20 }}>Extracting…</div>}
      {err && <div style={{ color: '#c8321f' }}>{err}</div>}
      {entries.length > 0 && (
        <div style={{ maxHeight: 360, overflowY: 'auto', border: '1px solid var(--id-border)', borderRadius: 10 }}>
          {entries.map((e, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: '1px solid var(--id-border)' }}>
              <window.Icon name="doc" size={14} />
              <div style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 13 }}>{e.name}</div>
              <span className="cmp-meta">{window.fmtBytes(e.u8.length)}</span>
              <button className="icon-btn" onClick={() => saveOne(e)} title="Download"><window.Icon name="download" size={12} /></button>
            </div>
          ))}
        </div>
      )}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setEntries([]); }}><window.Icon name="upload" size={16} /> Another zip</button>
      </div>
    </div>
  );
};
