// Meme Generator — top/bottom Impact-style text on an uploaded image.

window.TOOL_HANDLERS['meme-generator'] = function MemeTool() {
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [top, setTop] = React.useState('WHEN YOU SHIP');
  const [bottom, setBottom] = React.useState('AT 4:59 PM FRIDAY');
  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);
  };

  const drawText = (ctx, text, x, y) => {
    ctx.fillStyle = '#fff'; ctx.strokeStyle = '#000';
    ctx.fillText(text, x, y); ctx.strokeText(text, x, y);
  };

  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.drawImage(img, 0, 0);
    const fontSize = Math.max(28, Math.round(img.width / 12));
    ctx.font = `bold ${fontSize}px Impact, Arial Black, sans-serif`;
    ctx.textAlign = 'center';
    ctx.lineWidth = Math.max(4, fontSize / 12);
    ctx.textBaseline = 'top';
    if (top) drawText(ctx, top.toUpperCase(), img.width / 2, fontSize * 0.4);
    ctx.textBaseline = 'bottom';
    if (bottom) drawText(ctx, bottom.toUpperCase(), img.width / 2, img.height - fontSize * 0.4);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/jpeg', 0.92);
  }, [top, bottom, src]);

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

  if (!file) return <window.Dropzone onFile={handleFile} title="Drop a photo here" hint="we'll slap text on it" accept="image/*" />;

  return (
    <div>
      <div className="cmp-preview" style={{ gridTemplateColumns: '1fr' }}>
        <div className="cmp-side after">
          <div className="cmp-ttl">Meme</div>
          <img src={outUrl || src} alt="" />
        </div>
      </div>
      <div className="mini-row" style={{ marginTop: 16 }}>
        <div className="mini-field">
          <label className="mini-label">Top text</label>
          <input className="mini-input" value={top} onChange={(e) => setTop(e.target.value)} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Bottom text</label>
          <input className="mini-input" value={bottom} onChange={(e) => setBottom(e.target.value)} />
        </div>
      </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>
  );
};
