// Crop Image — drag a selection rectangle on the preview and export the crop.

window.TOOL_HANDLERS['crop-image'] = function CropImageTool() {
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [dims, setDims] = React.useState({ w: 0, h: 0 });
  const [sel, setSel] = React.useState(null);
  const [drag, setDrag] = React.useState(null);
  const [outUrl, setOutUrl] = React.useState('');
  const imgRef = React.useRef(null);
  const wrapRef = 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);
    setDims({ w: img.width, h: img.height });
    const inset = Math.round(Math.min(img.width, img.height) * 0.1);
    setSel({ x: inset, y: inset, w: img.width - inset * 2, h: img.height - inset * 2 });
  };

  React.useEffect(() => {
    if (!imgRef.current || !sel) return;
    const { x, y, w, h } = sel;
    if (w <= 0 || h <= 0) return;
    const c = document.createElement('canvas');
    c.width = w; c.height = h;
    c.getContext('2d').drawImage(imgRef.current, x, y, w, h, 0, 0, w, h);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/png');
  }, [sel]);

  const toImageCoords = (clientX, clientY) => {
    const rect = wrapRef.current.getBoundingClientRect();
    const sx = dims.w / rect.width;
    return { x: (clientX - rect.left) * sx, y: (clientY - rect.top) * sx };
  };
  const onDown = (e) => {
    const p = toImageCoords(e.clientX, e.clientY);
    setDrag({ x0: p.x, y0: p.y });
  };
  const onMove = (e) => {
    if (!drag) return;
    const p = toImageCoords(e.clientX, e.clientY);
    const x = Math.max(0, Math.min(drag.x0, p.x));
    const y = Math.max(0, Math.min(drag.y0, p.y));
    const w = Math.min(dims.w - x, Math.abs(p.x - drag.x0));
    const h = Math.min(dims.h - y, Math.abs(p.y - drag.y0));
    setSel({ x, y, w, h });
  };
  const onUp = () => setDrag(null);

  const download = () => {
    if (!outUrl) return;
    const a = document.createElement('a'); a.href = outUrl;
    a.download = file.name.replace(/\.[^.]+$/, '') + '-crop.png'; a.click();
  };
  const reset = () => {
    if (src) URL.revokeObjectURL(src);
    if (outUrl) URL.revokeObjectURL(outUrl);
    setFile(null); setSrc(''); setOutUrl(''); setSel(null);
  };

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop an image here" hint="click and drag on the image to crop" accept="image/*" />;

  const pct = sel ? {
    left: (sel.x / dims.w) * 100 + '%',
    top: (sel.y / dims.h) * 100 + '%',
    width: (sel.w / dims.w) * 100 + '%',
    height: (sel.h / dims.h) * 100 + '%',
  } : null;

  return (
    <div>
      <div ref={wrapRef} className="cp-stage" style={{ position: 'relative', userSelect: 'none', cursor: 'crosshair' }}
           onMouseDown={onDown} onMouseMove={onMove} onMouseUp={onUp} onMouseLeave={onUp}>
        <img src={src} alt="" draggable={false} style={{ width: '100%', display: 'block', pointerEvents: 'none' }} />
        {pct && (
          <div style={{
            position: 'absolute', ...pct,
            border: '2px dashed var(--id-brand-blue)',
            background: 'color-mix(in oklab, var(--id-brand-blue) 15%, transparent)',
            pointerEvents: 'none',
          }} />
        )}
      </div>
      <div className="cmp-meta" style={{ textAlign: 'center', marginTop: 10 }}>
        {sel ? `Crop: ${Math.round(sel.w)} × ${Math.round(sel.h)} px` : 'Drag on the image'}
      </div>
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={reset}><window.Icon name="upload" size={16} /> Choose another</button>
        <button className="btn btn-primary" onClick={download} disabled={!outUrl}><window.Icon name="download" size={16} /> Download crop</button>
      </div>
    </div>
  );
};
