// HEIC to PNG — same libheif decode as HEIC to JPG, PNG output for transparency.

const HEIC2ANY_URL = 'https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js';

window.TOOL_HANDLERS['heic-to-png'] = function HeicToPngTool() {
  const [file, setFile] = React.useState(null);
  const [outUrl, setOutUrl] = React.useState('');
  const [outSize, setOutSize] = React.useState(0);
  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(HEIC2ANY_URL);
      const blob = await window.heic2any({ blob: f, toType: 'image/png' });
      setOutUrl(URL.createObjectURL(blob)); setOutSize(blob.size);
    } catch (e) { setErr('Decode failed: ' + e.message); }
    finally { setBusy(false); }
  };

  const download = () => {
    if (!outUrl) return;
    const a = document.createElement('a'); a.href = outUrl;
    a.download = file.name.replace(/\.(heic|heif)$/i, '') + '.png'; a.click();
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop a HEIC file here" hint="exports lossless PNG" accept=".heic,.heif,image/heic,image/heif" />;

  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)}</div>
      </div>
      {busy && <div className="cmp-meta" style={{ textAlign: 'center', padding: 20 }}>Decoding HEIC…</div>}
      {err && <div style={{ color: '#c8321f' }}>{err}</div>}
      {outUrl && (
        <div className="cmp-preview" style={{ gridTemplateColumns: '1fr' }}>
          <div className="cmp-side after">
            <div className="cmp-ttl">PNG output</div>
            <img src={outUrl} alt="" />
            <div className="cmp-meta">{window.fmtBytes(outSize)}</div>
          </div>
        </div>
      )}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setOutUrl(''); setErr(''); }}><window.Icon name="upload" size={16} /> Another</button>
        <button className="btn btn-primary" onClick={download} disabled={!outUrl}><window.Icon name="download" size={16} /> Download PNG</button>
      </div>
    </div>
  );
};
