// Photo Filter — apply a CSS-filter preset to an image via canvas.

const PHOTO_FILTERS = {
  none:     'none',
  mono:     'grayscale(100%)',
  sepia:    'sepia(80%) saturate(120%)',
  vivid:    'saturate(170%) contrast(110%)',
  cool:     'hue-rotate(-20deg) saturate(110%) brightness(102%)',
  warm:     'hue-rotate(20deg) saturate(120%) brightness(102%)',
  fade:     'contrast(80%) brightness(110%) saturate(70%)',
  noir:     'grayscale(100%) contrast(140%) brightness(95%)',
  dreamy:   'blur(1px) saturate(130%) brightness(108%)',
};

window.TOOL_HANDLERS['photo-filter'] = function PhotoFilterTool() {
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [filter, setFilter] = React.useState('vivid');
  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 c = document.createElement('canvas');
    c.width = img.width; c.height = img.height;
    const ctx = c.getContext('2d');
    ctx.filter = PHOTO_FILTERS[filter];
    ctx.drawImage(img, 0, 0);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/jpeg', 0.92);
  }, [filter, src]);

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

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop an image here" hint="apply a vintage or vivid look" accept="image/*" />;

  return (
    <div>
      <window.BeforeAfterSlider
        before={src}
        after={outUrl || src}
        labelBefore="Original"
        labelAfter={`Filter · ${filter}`}
      />
      <div className="mini-row" style={{ flexWrap: 'wrap', marginTop: 16 }}>
        {Object.keys(PHOTO_FILTERS).map(name => (
          <button key={name} className={`filter-pill ${filter === name ? 'active' : ''}`} onClick={() => setFilter(name)}>
            {name}
          </button>
        ))}
      </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 JPG</button>
      </div>
    </div>
  );
};
