// Pixelate Image — downscale then upscale with nearest-neighbor to get a blocky look.

window.TOOL_HANDLERS['pixelate'] = function PixelateTool() {
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [block, setBlock] = React.useState(14);
  const [outUrl, setOutUrl] = React.useState('');
  const imgRef = React.useRef(null);

  const handleFile = async (f) => {
    if (!f || !f.type.startsWith('image/')) return;
    const { img, url } = await window.loadImageFromFile(f);
    imgRef.current = img;
    setFile(f); setSrc(url);
  };

  React.useEffect(() => {
    if (!imgRef.current) return;
    const img = imgRef.current;
    const w = img.width, h = img.height;
    const small = document.createElement('canvas');
    const sw = Math.max(1, Math.round(w / block));
    const sh = Math.max(1, Math.round(h / block));
    small.width = sw; small.height = sh;
    small.getContext('2d').drawImage(img, 0, 0, sw, sh);

    const c = document.createElement('canvas');
    c.width = w; c.height = h;
    const ctx = c.getContext('2d');
    ctx.imageSmoothingEnabled = false;
    ctx.drawImage(small, 0, 0, w, h);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/png');
  }, [block, src]);

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

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop an image here" hint="choose pixel size below" accept="image/*" />;

  return (
    <div>
      <window.BeforeAfterSlider
        before={src}
        after={outUrl || src}
        labelBefore="Original"
        labelAfter={`Pixelated · ${block}px`}
      />
      <div className="cmp-slider-row">
        <div className="cmp-label"><span>Block size</span><span className="val">{block}px</span></div>
        <input type="range" min="2" max="40" step="1" value={block} onChange={(e) => setBlock(+e.target.value)} className="cmp-slider" />
      </div>
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setFile(null); setSrc(''); 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>
  );
};
