// Color Picker — click any pixel in an uploaded image to grab its hex, plus a mini extracted palette.

window.TOOL_HANDLERS['color-picker'] = function ColorPickerTool() {
  const [src, setSrc] = React.useState('');
  const [picked, setPicked] = React.useState(null);
  const [palette, setPalette] = React.useState([]);
  const canvasRef = React.useRef(null);

  const handleFile = async (f) => {
    if (!f || !f.type.startsWith('image/')) return;
    const { img, url } = await window.loadImageFromFile(f);
    setSrc(url); setPicked(null);
    const c = canvasRef.current; if (!c) return;
    const maxW = 520; const scale = Math.min(1, maxW / img.width);
    c.width = img.width * scale; c.height = img.height * scale;
    const ctx = c.getContext('2d');
    ctx.drawImage(img, 0, 0, c.width, c.height);
    // bucket sample for a 6-color palette
    const data = ctx.getImageData(0, 0, c.width, c.height).data;
    const buckets = {};
    for (let i = 0; i < data.length; i += 16) {
      const r = data[i] >> 5, g = data[i+1] >> 5, b = data[i+2] >> 5;
      const k = r*64 + g*8 + b;
      buckets[k] = (buckets[k] || 0) + 1;
    }
    const top = Object.entries(buckets).sort((a, b) => b[1] - a[1]).slice(0, 6);
    setPalette(top.map(([k]) => {
      const n = +k;
      const r = (n >> 6) << 5, g = ((n >> 3) & 7) << 5, b = (n & 7) << 5;
      return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
    }));
  };

  const pick = (e) => {
    const c = canvasRef.current; if (!c) return;
    const rect = c.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * c.width;
    const y = ((e.clientY - rect.top) / rect.height) * c.height;
    const d = c.getContext('2d').getImageData(x, y, 1, 1).data;
    const hex = '#' + [d[0], d[1], d[2]].map(v => v.toString(16).padStart(2, '0')).join('');
    setPicked(hex);
  };

  if (!src) return <window.Dropzone onFile={handleFile} title="Drop an image here" hint="click to pick any color from it" accept="image/*" />;

  return (
    <div className="mini-tool">
      <div className="cp-stage">
        <canvas ref={canvasRef} className="cp-canvas" onClick={pick} />
      </div>
      {picked && (
        <div className="cp-picked">
          <div className="cp-swatch" style={{ background: picked }} />
          <div><div className="cp-hex">{picked.toUpperCase()}</div><div className="cp-hint">Click on image to pick</div></div>
          <button className="btn btn-secondary" onClick={() => navigator.clipboard.writeText(picked)} style={{ marginLeft: 'auto' }}>Copy hex</button>
        </div>
      )}
      {palette.length > 0 && (
        <>
          <div className="mini-label" style={{ marginTop: 16 }}>Extracted palette</div>
          <div className="cp-palette">{palette.map(h => (
            <button key={h} className="cp-chip" style={{ background: h }} onClick={() => { setPicked(h); navigator.clipboard.writeText(h); }}>
              <span>{h.toUpperCase()}</span>
            </button>
          ))}</div>
        </>
      )}
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => { setSrc(''); setPicked(null); setPalette([]); }}>
          <window.Icon name="upload" size={16} /> Another image
        </button>
      </div>
    </div>
  );
};
