// File Hash — compute SHA-1 / SHA-256 / SHA-384 / SHA-512 via Web Crypto.

window.TOOL_HANDLERS['file-hash'] = function FileHashTool() {
  const [file, setFile] = React.useState(null);
  const [hashes, setHashes] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const toHex = (buf) => Array.from(new Uint8Array(buf))
    .map(b => b.toString(16).padStart(2, '0')).join('');

  const handleFile = async (f) => {
    setFile(f); setBusy(true); setHashes(null);
    const buf = await f.arrayBuffer();
    const [h1, h256, h384, h512] = await Promise.all([
      crypto.subtle.digest('SHA-1', buf),
      crypto.subtle.digest('SHA-256', buf),
      crypto.subtle.digest('SHA-384', buf),
      crypto.subtle.digest('SHA-512', buf),
    ]);
    setHashes({
      'SHA-1': toHex(h1),
      'SHA-256': toHex(h256),
      'SHA-384': toHex(h384),
      'SHA-512': toHex(h512),
    });
    setBusy(false);
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop any file here" hint="we'll compute SHA-1, 256, 384, 512" accept="*/*" />;

  return (
    <div className="mini-tool">
      <div style={{ padding: 12, background: 'var(--id-surface-alt)', borderRadius: 10, marginBottom: 16 }}>
        <div style={{ fontWeight: 600 }}>{file.name}</div>
        <div className="cmp-meta">{window.fmtBytes(file.size)} · {file.type || 'unknown'}</div>
      </div>
      {busy && <div className="cmp-meta">Hashing…</div>}
      {hashes && Object.entries(hashes).map(([algo, hex]) => (
        <div key={algo} style={{ marginBottom: 10 }}>
          <div className="mini-label">{algo}</div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <code className="pw-text" style={{ flex: 1, fontSize: 12, wordBreak: 'break-all' }}>{hex}</code>
            <button className="icon-btn" onClick={() => navigator.clipboard.writeText(hex)} aria-label="Copy">
              <window.Icon name="doc" size={14} />
            </button>
          </div>
        </div>
      ))}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setHashes(null); }}><window.Icon name="upload" size={16} /> Another file</button>
      </div>
    </div>
  );
};
