// SVG to PNG — rasterize an SVG file at chosen pixel width.

window.TOOL_HANDLERS['svg-to-png'] = function SvgToPngTool() {
  const [file, setFile] = React.useState(null);
  const [svgText, setSvgText] = React.useState('');
  const [outUrl, setOutUrl] = React.useState('');
  const [size, setSize] = React.useState(512);

  const handleFile = async (f) => {
    if (!f) return;
    const txt = await f.text();
    setFile(f); setSvgText(txt);
    render(txt, size);
  };

  const render = (txt, w) => {
    const blob = new Blob([txt], { type: 'image/svg+xml;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const img = new Image();
    img.onload = () => {
      const ratio = img.height / img.width || 1;
      const c = document.createElement('canvas');
      c.width = w; c.height = Math.round(w * ratio);
      c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
      c.toBlob((pngBlob) => {
        if (!pngBlob) return;
        if (outUrl) URL.revokeObjectURL(outUrl);
        setOutUrl(URL.createObjectURL(pngBlob));
      }, 'image/png');
      URL.revokeObjectURL(url);
    };
    img.src = url;
  };

  React.useEffect(() => { if (svgText) render(svgText, size); }, [size]);

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

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop an SVG here" hint=".svg files only" accept="image/svg+xml,.svg" />;

  return (
    <div>
      <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">{size} px wide</div>
        </div>
      </div>
      <div className="cmp-slider-row">
        <div className="cmp-label"><span>Output width</span><span className="val">{size}px</span></div>
        <input type="range" min="128" max="2048" step="64" value={size} onChange={(e) => setSize(+e.target.value)} className="cmp-slider" />
      </div>
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setSvgText(''); setOutUrl(''); }}><window.Icon name="upload" size={16} /> Another</button>
        <button className="btn btn-primary" onClick={download}><window.Icon name="download" size={16} /> Download PNG</button>
      </div>
    </div>
  );
};
