// Strip GPS Metadata — remove EXIF GPS tags from JPEG photos before sharing.
// We re-encode the image through a canvas, which discards all metadata,
// including GPS, camera, owner. Output is JPEG/PNG depending on input.

window.TOOL_HANDLERS['strip-gps-metadata'] = function StripGpsTool() {
  const S = window.MMSports;
  const [items, setItems] = React.useState([]); // [{ name, beforeUrl, afterBlob, afterUrl, beforeSize, afterSize, hadExif }]
  const [busy, setBusy] = React.useState(false);

  const processOne = (file) => new Promise(async (resolve) => {
    const beforeUrl = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      const c = document.createElement('canvas');
      c.width = img.naturalWidth; c.height = img.naturalHeight;
      const ctx = c.getContext('2d');
      ctx.drawImage(img, 0, 0);
      const mime = /png/i.test(file.type) ? 'image/png' : 'image/jpeg';
      c.toBlob((blob) => {
        const afterUrl = URL.createObjectURL(blob);
        resolve({
          name: file.name,
          beforeUrl, afterUrl, afterBlob: blob,
          beforeSize: file.size, afterSize: blob.size,
        });
      }, mime, 0.92);
    };
    img.onerror = () => resolve(null);
    img.src = beforeUrl;
  });

  const onFile = async (files) => {
    setBusy(true);
    const fs = Array.isArray(files) ? files : [files];
    const out = [];
    for (const f of fs) {
      const r = await processOne(f);
      if (r) out.push(r);
    }
    setItems((prev) => [...prev, ...out]);
    setBusy(false);
  };

  const downloadOne = (it) => window.downloadBlob(it.afterBlob, it.name.replace(/\.([^.]+)$/, '-clean.$1'));
  const downloadAll = async () => {
    if (items.length === 1) return downloadOne(items[0]);
    await window.loadScript('https://cdn.jsdelivr.net/npm/fflate@0.8.2/umd/index.js');
    const f = window.fflate;
    const files = {};
    for (const it of items) {
      const buf = new Uint8Array(await it.afterBlob.arrayBuffer());
      files[it.name.replace(/\.([^.]+)$/, '-clean.$1')] = buf;
    }
    const zipped = f.zipSync(files);
    window.downloadBlob(new Blob([zipped]), 'photos-no-gps.zip');
  };

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="Strip GPS Metadata" sub="Remove EXIF location and camera data from photos before sharing." icon="lock" accent="#dc2626" />

      <window.Dropzone onFile={onFile} multiple
                       title={items.length ? 'Add more photos' : 'Drop photos here'}
                       hint="JPG / PNG · we strip EXIF, GPS, camera info" accept="image/*" />

      {busy && <window.LoadingCard label="Cleaning photos…" />}

      {items.length > 0 && (
        <>
          <div className="strip-gallery">
            {items.map((it, i) => (
              <div key={i} className="strip-card">
                <img src={it.afterUrl} alt={it.name} />
                <div className="strip-meta">
                  <div className="strip-name">{it.name}</div>
                  <div className="strip-size">
                    {window.fmtBytes(it.beforeSize)} → {window.fmtBytes(it.afterSize)}
                  </div>
                </div>
                <button className="icon-btn strip-dl" onClick={() => downloadOne(it)} aria-label="Download">
                  <window.Icon name="download" size={14} />
                </button>
              </div>
            ))}
          </div>

          <div className="cmp-actions">
            <button className="btn btn-secondary" onClick={() => setItems([])}>Clear</button>
            <button className="btn btn-primary" onClick={downloadAll}>
              <window.Icon name="download" size={16} /> Download {items.length === 1 ? 'photo' : `${items.length} photos (zip)`}
            </button>
          </div>

          <div className="sport-helper">
            We re-encode each image through a canvas, which discards all EXIF — including the GPS coordinates of where the photo was taken, the camera serial, and the date taken. The pixels themselves are unchanged.
          </div>
        </>
      )}
    </div>
  );
};
