// Photo Collage — arrange 2–4 images on a square canvas in grid layouts.

window.TOOL_HANDLERS['collage'] = function CollageTool() {
  const [files, setFiles] = React.useState([]);
  const [gap, setGap] = React.useState(10);
  const [outUrl, setOutUrl] = React.useState('');

  const handleFiles = async (picked) => {
    const list = Array.isArray(picked) ? picked : [picked];
    const loaded = await Promise.all(list.filter(f => f.type.startsWith('image/'))
      .slice(0, 4).map(f => window.loadImageFromFile(f).then(r => r.img)));
    setFiles(loaded);
  };

  React.useEffect(() => {
    if (files.length < 2) return;
    const size = 1200;
    const c = document.createElement('canvas');
    c.width = size; c.height = size;
    const ctx = c.getContext('2d');
    ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, size, size);

    const cells = [];
    if (files.length === 2) {
      cells.push({ x: 0, y: 0, w: size / 2, h: size });
      cells.push({ x: size / 2, y: 0, w: size / 2, h: size });
    } else if (files.length === 3) {
      cells.push({ x: 0, y: 0, w: size, h: size / 2 });
      cells.push({ x: 0, y: size / 2, w: size / 2, h: size / 2 });
      cells.push({ x: size / 2, y: size / 2, w: size / 2, h: size / 2 });
    } else {
      cells.push({ x: 0, y: 0, w: size / 2, h: size / 2 });
      cells.push({ x: size / 2, y: 0, w: size / 2, h: size / 2 });
      cells.push({ x: 0, y: size / 2, w: size / 2, h: size / 2 });
      cells.push({ x: size / 2, y: size / 2, w: size / 2, h: size / 2 });
    }
    files.forEach((img, i) => {
      const cell = cells[i];
      const pad = gap / 2;
      const { x, y, w, h } = { x: cell.x + pad, y: cell.y + pad, w: cell.w - gap, h: cell.h - gap };
      // cover fit
      const scale = Math.max(w / img.width, h / img.height);
      const iw = img.width * scale, ih = img.height * scale;
      const dx = x + (w - iw) / 2, dy = y + (h - ih) / 2;
      ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
      ctx.drawImage(img, dx, dy, iw, ih);
      ctx.restore();
    });

    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/jpeg', 0.92);
  }, [files, gap]);

  const download = () => {
    if (!outUrl) return;
    const a = document.createElement('a'); a.href = outUrl;
    a.download = 'collage.jpg'; a.click();
  };

  if (files.length === 0) return <window.Dropzone onFile={handleFiles} multiple title="Drop 2–4 images here" hint="we'll arrange them in a grid" accept="image/*" />;

  return (
    <div>
      <div className="cmp-preview" style={{ gridTemplateColumns: '1fr' }}>
        <div className="cmp-side after">
          <div className="cmp-ttl">Collage · {files.length} photos</div>
          <img src={outUrl} alt="" />
        </div>
      </div>
      <div className="cmp-slider-row">
        <div className="cmp-label"><span>Gap</span><span className="val">{gap}px</span></div>
        <input type="range" min="0" max="40" value={gap} onChange={(e) => setGap(+e.target.value)} className="cmp-slider" />
      </div>
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={() => setFiles([])}><window.Icon name="upload" size={16} /> Start over</button>
        <button className="btn btn-primary" onClick={download}><window.Icon name="download" size={16} /> Download JPG</button>
      </div>
    </div>
  );
};
