// Rotate Image — 90° rotate, horizontal flip, vertical flip. Batch supported.

async function rotateBlob(file, opts) {
  const { img } = await window.loadImageFromFile(file);
  const a = opts.angle || 0;
  const h = !!opts.flipH, v = !!opts.flipV;
  const rotated = a % 180 !== 0;
  const c = document.createElement('canvas');
  c.width = rotated ? img.height : img.width;
  c.height = rotated ? img.width : img.height;
  const ctx = c.getContext('2d');
  ctx.translate(c.width / 2, c.height / 2);
  ctx.rotate((a * Math.PI) / 180);
  ctx.scale(h ? -1 : 1, v ? -1 : 1);
  ctx.drawImage(img, -img.width / 2, -img.height / 2);
  return new Promise((resolve) => c.toBlob((b) => resolve({ blob: b, ext: 'png' }), 'image/png'));
}

window.TOOL_HANDLERS['rotate-image'] = function RotateImageTool() {
  const [mode, setMode] = React.useState('single');
  const [batchOpts, setBatchOpts] = React.useState({ angle: 90, flipH: false, flipV: false });
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [angle, setAngle] = React.useState(0);
  const [flipH, setFlipH] = React.useState(false);
  const [flipV, setFlipV] = React.useState(false);
  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);
    render(img, 0, false, false);
  };

  const render = (img, a, h, v) => {
    const c = document.createElement('canvas');
    const rotated = a % 180 !== 0;
    c.width = rotated ? img.height : img.width;
    c.height = rotated ? img.width : img.height;
    const ctx = c.getContext('2d');
    ctx.translate(c.width / 2, c.height / 2);
    ctx.rotate((a * Math.PI) / 180);
    ctx.scale(h ? -1 : 1, v ? -1 : 1);
    ctx.drawImage(img, -img.width / 2, -img.height / 2);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob));
    }, 'image/png');
  };

  React.useEffect(() => {
    if (imgRef.current) render(imgRef.current, angle, flipH, flipV);
  }, [angle, flipH, flipV]);

  const rotate = (by) => setAngle((a) => (a + by + 360) % 360);
  const download = () => {
    if (!outUrl) return;
    const a = document.createElement('a'); a.href = outUrl;
    a.download = file.name.replace(/\.[^.]+$/, '') + '-rotated.png'; a.click();
  };
  const reset = () => {
    if (src) URL.revokeObjectURL(src);
    if (outUrl) URL.revokeObjectURL(outUrl);
    setFile(null); setSrc(''); setOutUrl(''); setAngle(0); setFlipH(false); setFlipV(false);
  };

  if (mode === 'batch') {
    return (
      <window.BatchMode
        onExit={() => setMode('single')}
        process={rotateBlob} opts={batchOpts} setOpts={setBatchOpts}
        accept="image/*" title="Drop images here" hint="same rotation applied to all"
        defaultExt="png" zipName="rotated"
        renderControls={({ opts, setOpts }) => (
          <div className="mini-row" style={{ flexWrap: 'wrap', marginBottom: 8 }}>
            {[0, 90, 180, 270].map((a) => (
              <button key={a} className={`filter-pill ${opts.angle === a ? 'active' : ''}`}
                      onClick={() => setOpts({ ...opts, angle: a })}>{a}°</button>
            ))}
            <button className={`filter-pill ${opts.flipH ? 'active' : ''}`}
                    onClick={() => setOpts({ ...opts, flipH: !opts.flipH })}>Flip H</button>
            <button className={`filter-pill ${opts.flipV ? 'active' : ''}`}
                    onClick={() => setOpts({ ...opts, flipV: !opts.flipV })}>Flip V</button>
          </div>
        )}
      />
    );
  }

  if (!file) return (
    <>
      <window.Dropzone onFile={handleFile} title="Drop an image here" hint="PNG, JPG, WebP" accept="image/*" />
      <div style={{ textAlign: 'center', marginTop: 10 }}>
        <button className="filter-pill" onClick={() => setMode('batch')}><window.Icon name="grid" size={12} /> Batch mode</button>
      </div>
    </>
  );

  return (
    <div>
      <div className="cmp-preview" style={{ gridTemplateColumns: '1fr' }}>
        <div className="cmp-side after">
          <div className="cmp-ttl">Preview</div>
          <img src={outUrl || src} alt="" />
          <div className="cmp-meta">{angle}° {flipH ? '· flip H' : ''} {flipV ? '· flip V' : ''}</div>
        </div>
      </div>
      <div className="mini-row" style={{ marginTop: 18, flexWrap: 'wrap' }}>
        <button className="btn btn-secondary" onClick={() => rotate(-90)}><window.Icon name="rotate" size={16} /> −90°</button>
        <button className="btn btn-secondary" onClick={() => rotate(90)}><window.Icon name="rotate" size={16} /> +90°</button>
        <button className="btn btn-secondary" onClick={() => setFlipH(!flipH)}>Flip H</button>
        <button className="btn btn-secondary" onClick={() => setFlipV(!flipV)}>Flip V</button>
      </div>
      <div className="cmp-actions">
        <button className="btn btn-secondary" onClick={reset}><window.Icon name="upload" size={16} /> Choose another</button>
        <button className="filter-pill" onClick={() => setMode('batch')}><window.Icon name="grid" size={14} /> Batch mode</button>
        <button className="btn btn-primary" onClick={download}><window.Icon name="download" size={16} /> Download PNG</button>
      </div>
    </div>
  );
};
