// Resize Image — scale an image to a chosen width (optionally locking aspect ratio).
// Supports single-file and batch mode.

async function resizeBlob(file, opts) {
  const { img } = await window.loadImageFromFile(file);
  const w = opts.width || img.width;
  const h = opts.lock ? Math.round(w * (img.height / img.width)) : (opts.height || img.height);
  const c = document.createElement('canvas');
  c.width = w; c.height = h;
  const ctx = c.getContext('2d');
  ctx.imageSmoothingQuality = 'high';
  ctx.drawImage(img, 0, 0, w, h);
  return new Promise((resolve) => c.toBlob((b) => resolve({ blob: b, ext: 'png' }), 'image/png'));
}

window.TOOL_HANDLERS['resize-image'] = function ResizeImageTool() {
  const [mode, setMode] = React.useState('single');
  const [batchOpts, setBatchOpts] = React.useState({ width: 1080, lock: true });
  const [file, setFile] = React.useState(null);
  const [src, setSrc] = React.useState('');
  const [dims, setDims] = React.useState({ w: 0, h: 0 });
  const [width, setWidth] = React.useState(0);
  const [height, setHeight] = React.useState(0);
  const [lock, setLock] = React.useState(true);
  const [outUrl, setOutUrl] = React.useState('');
  const [outSize, setOutSize] = React.useState(0);
  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);
    setDims({ w: img.width, h: img.height });
    setWidth(img.width); setHeight(img.height);
    render(img, img.width, img.height);
  };

  const render = (img, w, h) => {
    const c = document.createElement('canvas');
    c.width = w; c.height = h;
    const ctx = c.getContext('2d');
    ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(img, 0, 0, w, h);
    c.toBlob((blob) => {
      if (!blob) return;
      if (outUrl) URL.revokeObjectURL(outUrl);
      setOutUrl(URL.createObjectURL(blob)); setOutSize(blob.size);
    }, 'image/png');
  };

  const setW = (w) => {
    setWidth(w);
    const h = lock ? Math.round(w * (dims.h / dims.w)) : height;
    if (lock) setHeight(h);
    if (imgRef.current && w > 0 && h > 0) render(imgRef.current, w, h);
  };
  const setH = (h) => {
    setHeight(h);
    const w = lock ? Math.round(h * (dims.w / dims.h)) : width;
    if (lock) setWidth(w);
    if (imgRef.current && w > 0 && h > 0) render(imgRef.current, w, h);
  };

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

  if (mode === 'batch') {
    return (
      <window.BatchMode
        onExit={() => setMode('single')}
        process={resizeBlob} opts={batchOpts} setOpts={setBatchOpts}
        accept="image/*" title="Drop images here" hint="same width applied to all"
        defaultExt="png" zipName="resized"
        renderControls={({ opts, setOpts }) => (
          <div className="mini-row" style={{ marginBottom: 8 }}>
            <div className="mini-field" style={{ maxWidth: 160 }}>
              <label className="mini-label">Target width (px)</label>
              <input type="number" className="mini-input" min={1} value={opts.width}
                     onChange={(e) => setOpts({ ...opts, width: +e.target.value })} />
            </div>
            <label className="pw-opt" style={{ alignSelf: 'end' }}>
              <input type="checkbox" checked={opts.lock}
                     onChange={(e) => setOpts({ ...opts, lock: e.target.checked })} /> Lock ratio
            </label>
          </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">
        <div className="cmp-side">
          <div className="cmp-ttl">Original</div>
          <img src={src} alt="" />
          <div className="cmp-meta">{dims.w} × {dims.h} px</div>
        </div>
        <div className="cmp-side after">
          <div className="cmp-ttl">Resized</div>
          <img src={outUrl || src} alt="" />
          <div className="cmp-meta">{width} × {height} px · {window.fmtBytes(outSize)}</div>
        </div>
      </div>
      <div className="mini-row" style={{ marginTop: 18 }}>
        <div className="mini-field">
          <label className="mini-label">Width (px)</label>
          <input type="number" className="mini-input" value={width} min={1} onChange={(e) => setW(+e.target.value)} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Height (px)</label>
          <input type="number" className="mini-input" value={height} min={1} onChange={(e) => setH(+e.target.value)} />
        </div>
        <label className="pw-opt" style={{ alignSelf: 'end' }}>
          <input type="checkbox" checked={lock} onChange={(e) => setLock(e.target.checked)} /> Lock ratio
        </label>
      </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>
  );
};
