// Social Media Image Resizer — resize & center-crop to popular dimensions.
// Each preset card shows a live crop preview after upload.

const SOCIAL_PRESETS = [
  { id: 'ig-post',      platform: 'Instagram', label: 'Post',      w: 1080, h: 1080, color: '#E1306C' },
  { id: 'ig-story',     platform: 'Instagram', label: 'Story',     w: 1080, h: 1920, color: '#E1306C' },
  { id: 'ig-landscape', platform: 'Instagram', label: 'Landscape', w: 1080, h: 566,  color: '#E1306C' },
  { id: 'x-post',       platform: 'X / Twitter', label: 'Post',    w: 1600, h: 900,  color: '#1DA1F2' },
  { id: 'x-header',     platform: 'X / Twitter', label: 'Header',  w: 1500, h: 500,  color: '#1DA1F2' },
  { id: 'fb-post',      platform: 'Facebook', label: 'Post',       w: 1200, h: 630,  color: '#1877F2' },
  { id: 'fb-cover',     platform: 'Facebook', label: 'Cover',      w: 820,  h: 312,  color: '#1877F2' },
  { id: 'li-post',      platform: 'LinkedIn', label: 'Post',       w: 1200, h: 627,  color: '#0A66C2' },
  { id: 'li-banner',    platform: 'LinkedIn', label: 'Banner',     w: 1584, h: 396,  color: '#0A66C2' },
  { id: 'yt-thumb',     platform: 'YouTube',  label: 'Thumbnail',  w: 1280, h: 720,  color: '#FF0000' },
  { id: 'yt-banner',    platform: 'YouTube',  label: 'Banner',     w: 2560, h: 1440, color: '#FF0000' },
  { id: 'pin',          platform: 'Pinterest', label: 'Pin',       w: 1000, h: 1500, color: '#E60023' },
  { id: 'tiktok',       platform: 'TikTok',   label: 'Video',     w: 1080, h: 1920, color: '#010101' },
];

function coverCrop(img, w, h) {
  const c = document.createElement('canvas');
  c.width = w; c.height = h;
  const ctx = c.getContext('2d');
  ctx.imageSmoothingQuality = 'high';
  const scale = Math.max(w / img.width, h / img.height);
  const sw = img.width * scale, sh = img.height * scale;
  ctx.drawImage(img, (w - sw) / 2, (h - sh) / 2, sw, sh);
  return new Promise((resolve) => c.toBlob(resolve, 'image/png'));
}

window.TOOL_HANDLERS['social-image-resizer'] = function SocialImageResizerTool() {
  const [file, setFile] = React.useState(null);
  const [img, setImg] = React.useState(null);
  const [srcUrl, setSrcUrl] = React.useState('');
  const [srcDims, setSrcDims] = React.useState({ w: 0, h: 0 });
  const [selected, setSelected] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const handleFile = async (f) => {
    if (!f || !f.type.startsWith('image/')) return;
    try {
      const { img: loaded, url } = await window.loadImageFromFile(f);
      if (srcUrl) URL.revokeObjectURL(srcUrl);
      setFile(f); setImg(loaded); setSrcUrl(url);
      setSrcDims({ w: loaded.width, h: loaded.height });
      setSelected({}); setErr('');
    } catch { setErr('Could not load image.'); }
  };

  const toggle = (id) => setSelected((prev) => {
    const next = { ...prev };
    if (next[id]) delete next[id]; else next[id] = true;
    return next;
  });

  const selectedIds = Object.keys(selected);
  const selectedCount = selectedIds.length;

  const download = async () => {
    if (!img || selectedCount === 0) return;
    setBusy(true); setErr('');
    try {
      const baseName = file.name.replace(/\.[^.]+$/, '');
      if (selectedCount === 1) {
        const p = SOCIAL_PRESETS.find((x) => x.id === selectedIds[0]);
        const blob = await coverCrop(img, p.w, p.h);
        window.downloadBlob(blob, `${baseName}-${p.id}-${p.w}x${p.h}.png`);
      } else {
        await window.loadScript('https://cdn.jsdelivr.net/npm/fflate@0.8.2/umd/index.js');
        const entries = {};
        for (const id of selectedIds) {
          const p = SOCIAL_PRESETS.find((x) => x.id === id);
          const blob = await coverCrop(img, p.w, p.h);
          entries[`${baseName}-${p.id}-${p.w}x${p.h}.png`] = new Uint8Array(await blob.arrayBuffer());
        }
        await new Promise((resolve, reject) => {
          window.fflate.zip(entries, { level: 0 }, (e, data) => {
            if (e) return reject(e);
            window.downloadBlob(new Blob([data], { type: 'application/zip' }), `${baseName}-social.zip`);
            resolve();
          });
        });
      }
    } catch (e) { setErr(e.message || 'Export failed'); }
    finally { setBusy(false); }
  };

  const reset = () => {
    if (srcUrl) URL.revokeObjectURL(srcUrl);
    setFile(null); setImg(null); setSrcUrl(''); setSrcDims({ w: 0, h: 0 });
    setSelected({}); setErr('');
  };

  if (!file) {
    return <window.Dropzone onFile={handleFile} title="Drop an image here" hint="PNG, JPG, WebP — resized locally" accept="image/*" />;
  }

  return (
    <div className="mini-tool">
      {/* Source info */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <img src={srcUrl} alt="" style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 8, border: '1px solid var(--id-border)' }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{file.name}</div>
          <div className="cmp-meta">{srcDims.w} × {srcDims.h} px · {window.fmtBytes(file.size)}</div>
        </div>
        <button className="icon-btn" onClick={reset} title="Choose another"><window.Icon name="x" size={14} /></button>
      </div>

      {/* Bulk toggles */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <span className="mini-label" style={{ margin: 0 }}>Choose sizes ({selectedCount} selected)</span>
        <span style={{ display: 'flex', gap: 6 }}>
          <button className="filter-pill" style={{ fontSize: 11, padding: '2px 8px' }}
            onClick={() => { const all = {}; SOCIAL_PRESETS.forEach((p) => { all[p.id] = true; }); setSelected(all); }}>All</button>
          <button className="filter-pill" style={{ fontSize: 11, padding: '2px 8px' }}
            onClick={() => setSelected({})}>None</button>
        </span>
      </div>

      {/* Preset cards with live crop preview */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))', gap: 10 }}>
        {SOCIAL_PRESETS.map((p) => {
          const isSel = !!selected[p.id];
          return (
            <div key={p.id} onClick={() => toggle(p.id)} style={{
              position: 'relative', borderRadius: 12, overflow: 'hidden', cursor: 'pointer',
              border: isSel ? `2.5px solid ${p.color}` : '2px solid var(--id-border)',
              background: 'var(--id-surface)', transition: 'all 150ms ease', userSelect: 'none',
            }}>
              {/* Crop preview — uses CSS object-fit to simulate center-crop */}
              <div style={{
                width: '100%', aspectRatio: p.w + '/' + p.h, maxHeight: 120, overflow: 'hidden',
                background: '#f0f0f0',
              }}>
                <img src={srcUrl} alt="" style={{
                  width: '100%', height: '100%', objectFit: 'cover', display: 'block',
                }} />
              </div>

              {/* Check badge */}
              {isSel && (
                <div style={{
                  position: 'absolute', top: 6, right: 6, width: 22, height: 22, borderRadius: '50%',
                  background: p.color, color: '#fff', display: 'grid', placeItems: 'center',
                  boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
                }}>
                  <window.Icon name="check" size={12} strokeWidth={2.5} />
                </div>
              )}

              {/* Info bar */}
              <div style={{ padding: '8px 10px' }}>
                <div style={{ fontWeight: 700, fontSize: 12, lineHeight: 1.2, color: isSel ? p.color : 'var(--id-text)' }}>
                  {p.platform}
                </div>
                <div style={{ fontSize: 11, color: 'var(--id-text-muted)', display: 'flex', justifyContent: 'space-between', marginTop: 2 }}>
                  <span>{p.label}</span>
                  <span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{p.w}×{p.h}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {err && <div style={{ color: '#c8321f', marginTop: 10, fontSize: 13 }}>{err}</div>}

      <div className="cmp-actions" style={{ marginTop: 16 }}>
        <button className="btn btn-secondary" onClick={reset}>
          <window.Icon name="upload" size={16} /> Choose another
        </button>
        <button className="btn btn-primary" disabled={selectedCount === 0 || busy} onClick={download}>
          <window.Icon name="download" size={16} />{' '}
          {busy ? 'Exporting…' : selectedCount <= 1 ? 'Download PNG' : `Download ${selectedCount} as ZIP`}
        </button>
      </div>
    </div>
  );
};
