// Quicksnap · "Çektikleriniz" — çiftin yüklediği fotoğraf galerisi.
//
// Fotoğraflar window.QUICKSNAP_PHOTOS listesinden gelir (src/quicksnap-data.js).
// Misafirler buraya yükleme yapmaz; sadece görüntüler ve dilediklerini yüksek
// çözünürlükte indirir. Görüntüleyici: parmakla kaydırma, klavyede sağ/sol ok,
// ekrandaki oklar ve indir düğmesi.
//
// Not: hook'lar global kapsamı paylaştığı için (Babel standalone) benzersiz
// takma adlarla alınır — login.jsx'teki global useState/useEffect ile çakışmasın.
const {
  useState: useStateQs,
  useEffect: useEffectQs,
  useRef: useRefQs,
  useCallback: useCallbackQs,
} = React;

// Manifest'i tek tip {src, full, thumb, caption} nesnelerine normalize eder.
function qsNormalize() {
  const raw =
    typeof window !== 'undefined' && Array.isArray(window.QUICKSNAP_PHOTOS)
      ? window.QUICKSNAP_PHOTOS
      : [];
  return raw
    .map((p) => {
      if (typeof p === 'string') return { thumb: p, full: p, caption: '' };
      if (!p || typeof p !== 'object') return null;
      const base = p.src || p.url || p.full || p.thumb || '';
      const full = p.full || p.src || p.url || p.thumb || '';
      const thumb = p.thumb || base || full;
      if (!thumb && !full) return null;
      return { thumb: thumb || full, full: full || thumb, caption: p.caption || '' };
    })
    .filter(Boolean);
}

function qsFileName(url, i) {
  try {
    const clean = String(url).split('?')[0].split('#')[0];
    const base = clean.substring(clean.lastIndexOf('/') + 1);
    if (base && /\.[a-z0-9]{2,5}$/i.test(base)) return decodeURIComponent(base);
  } catch (e) {}
  return `beyza-emin-${String(i + 1).padStart(2, '0')}.jpg`;
}

// Yüksek çözünürlüklü indirme. Önce fetch → blob (gerçek "indir" davranışı);
// CORS vb. engellerse doğrudan indirme bağlantısına / yeni sekmeye düşer.
async function qsDownload(url, filename) {
  try {
    const res = await fetch(url, { mode: 'cors' });
    if (!res.ok) throw new Error('http ' + res.status);
    const blob = await res.blob();
    const obj = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = obj;
    a.download = filename || 'foto.jpg';
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(obj), 10000);
    return true;
  } catch (e) {
    try {
      const a = document.createElement('a');
      a.href = url;
      a.download = filename || 'foto.jpg';
      a.target = '_blank';
      a.rel = 'noopener';
      document.body.appendChild(a);
      a.click();
      a.remove();
      return true;
    } catch (e2) {
      window.open(url, '_blank', 'noopener');
      return false;
    }
  }
}

function Quicksnap({ onBack }) {
  const staticPhotos = qsNormalize(); // repo/manifest yedeği (Blob yoksa)
  const [photos, setPhotos] = useStateQs(staticPhotos);
  const [state, setState] = useStateQs('loading'); // loading | ready
  const [viewer, setViewer] = useStateQs(null); // açık fotoğrafın index'i | null
  const [toast, setToast] = useStateQs(null);
  const toastTimer = useRefQs(null);

  const showToast = (m) => {
    if (toastTimer.current) clearTimeout(toastTimer.current);
    setToast(m);
    toastTimer.current = setTimeout(() => setToast(null), 2600);
  };

  // Bu galerinin paylaşılabilir bağlantısını paylaş: mobilde yerel paylaşım
  // menüsü (Web Share), yoksa panoya kopyala.
  const shareGallery = async () => {
    let url = '';
    try { url = window.location.origin + window.location.pathname + '#quicksnap'; } catch (e) {}
    const data = { title: 'Beyza & Emin · Çektikleriniz', text: 'Düğün fotoğrafları', url };
    try {
      if (navigator.share) { await navigator.share(data); return; }
    } catch (e) { return; } // kullanıcı iptal etti / desteklenmiyor
    try {
      await navigator.clipboard.writeText(url);
      showToast('Bağlantı kopyalandı');
    } catch (e) {
      showToast(url);
    }
  };

  // Fotoğrafları önce Vercel Blob'dan (quicksnap/ öneki) çek; yoksa yedeğe düş.
  useEffectQs(() => {
    let alive = true;
    fetch('/api/quicksnap', { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error('http ' + r.status))))
      .then((data) => {
        if (!alive) return;
        const apiItems = (Array.isArray(data.items) ? data.items : []).map((it) => ({
          thumb: it.thumb || it.url, // ızgarada optimize önizleme
          full: it.url, // görüntüleyicide tam çözünürlük
          downloadUrl: it.downloadUrl || `${it.url}?download=1`,
          caption: '',
          name: it.name || '',
        }));
        setPhotos(apiItems.length ? apiItems : staticPhotos);
        setState('ready');
      })
      .catch(() => {
        if (!alive) return;
        setPhotos(staticPhotos); // Blob bağlı değil / hata → repo listesine düş
        setState('ready');
      });
    return () => { alive = false; };
  }, []); // eslint-disable-line

  return (
    <ScreenShell onBack={onBack} kicker="Quicksnap" title="çektikleriniz">
      <p className="body-sm" style={{ opacity: 0.85, margin: '2px 0 16px' }}>
        Düğünde çekilen karelerin hepsi burada. Bir fotoğrafa dokun, parmağınla
        ya da klavyede sağ/sol ok ile gez, beğendiğini yüksek çözünürlükte indir.
      </p>

      <div style={{ marginBottom: 20 }}>
        <button onClick={shareGallery} style={qsStyles.shareBtn} aria-label="Bağlantıyı paylaş">
          <Icons.Share size={15} />
          <span className="label">Bağlantıyı paylaş</span>
        </button>
      </div>

      {state === 'loading' ? (
        <div style={qsStyles.empty}>
          <div className="body-sm" style={{ opacity: 0.85 }}>Yükleniyor…</div>
        </div>
      ) : photos.length === 0 ? (
        <div style={qsStyles.empty}>
          <div style={qsStyles.emptyIcon}>
            <Icons.Images size={30} />
          </div>
          <div className="hand" style={{ fontSize: 28, lineHeight: 1.1, marginBottom: 8 }}>
            çok yakında
          </div>
          <div className="body-sm" style={{ opacity: 0.85 }}>
            Fotoğraflar hazırlanıyor, birazdan burada olacak.
          </div>
        </div>
      ) : (
        <div style={qsStyles.grid}>
          {photos.map((p, i) => (
            <button
              key={i}
              onClick={() => setViewer(i)}
              style={qsStyles.cell}
              aria-label={`Fotoğraf ${i + 1}`}>
              <img
                src={p.thumb}
                alt={p.caption || `foto ${i + 1}`}
                loading="lazy"
                draggable={false}
                style={qsStyles.cellImg}
                onError={(e) => {
                  // Optimize önizleme (/_vercel/image) bir sebeple yüklenemezse
                  // tam görsele düş — grid asla bozuk görünmesin.
                  const img = e.currentTarget;
                  if (p.full && !img.dataset.fb && img.src !== p.full) {
                    img.dataset.fb = '1';
                    img.src = p.full;
                  }
                }}
              />
            </button>
          ))}
        </div>
      )}

      {viewer !== null && photos.length > 0 && (
        <PhotoViewer photos={photos} startIndex={viewer} onClose={() => setViewer(null)} />
      )}

      {toast && (
        <div role="status" aria-live="polite" style={qsStyles.toast}>{toast}</div>
      )}
      <style>{`@keyframes qsToastIn{from{opacity:0;transform:translate(-50%,10px)}to{opacity:1;transform:translate(-50%,0)}}`}</style>
    </ScreenShell>
  );
}

/* ---------- Tam ekran görüntüleyici ---------- */
function PhotoViewer({ photos, startIndex, onClose }) {
  const n = photos.length;
  const [i, setI] = useStateQs(startIndex);
  const [drag, setDrag] = useStateQs(0);
  const [animating, setAnimating] = useStateQs(false);
  const [busy, setBusy] = useStateQs(false);

  const startX = useRefQs(null);
  const startY = useRefQs(null);
  const axis = useRefQs(null); // 'x' | 'y' | null
  const width = useRefQs(1);
  const lockRef = useRefQs(false); // animasyon sırasında yeni geçişi engelle
  const viewportRef = useRefQs(null);

  const wrap = (k) => ((k % n) + n) % n;
  const prevI = wrap(i - 1);
  const nextI = wrap(i + 1);

  const go = useCallbackQs(
    (dir) => {
      if (n < 2 || lockRef.current) return;
      lockRef.current = true;
      setAnimating(true);
      setDrag(dir === 1 ? -width.current : width.current);
      setTimeout(() => {
        setI((cur) => wrap(cur + dir));
        setAnimating(false);
        setDrag(0);
        lockRef.current = false;
      }, 280);
    },
    [n]
  );

  // Klavye ok/Escape + arka planda kaydırmayı kilitle
  useEffectQs(() => {
    const onKey = (e) => {
      if (e.key === 'ArrowRight') { e.preventDefault(); go(1); }
      else if (e.key === 'ArrowLeft') { e.preventDefault(); go(-1); }
      else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
    };
    window.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [go, onClose]);

  // Viewport genişliğini ölç (px cinsinden sürükleme için)
  useEffectQs(() => {
    const measure = () => {
      width.current =
        (viewportRef.current && viewportRef.current.clientWidth) || window.innerWidth || 1;
    };
    measure();
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, []);

  // Komşu kareleri önceden yükle → geçiş anında hazır olsun
  useEffectQs(() => {
    [prevI, nextI].forEach((k) => {
      const im = new Image();
      im.src = photos[k].full;
    });
  }, [i]); // eslint-disable-line

  const onTouchStart = (e) => {
    if (animating || n < 2) return;
    const t = e.touches[0];
    startX.current = t.clientX;
    startY.current = t.clientY;
    axis.current = null;
  };
  const onTouchMove = (e) => {
    if (startX.current == null) return;
    const t = e.touches[0];
    const dx = t.clientX - startX.current;
    const dy = t.clientY - startY.current;
    if (axis.current == null && (Math.abs(dx) > 8 || Math.abs(dy) > 8)) {
      axis.current = Math.abs(dx) > Math.abs(dy) ? 'x' : 'y';
    }
    if (axis.current === 'x') {
      if (e.cancelable) e.preventDefault();
      setDrag(dx);
    }
  };
  const onTouchEnd = () => {
    if (startX.current == null) return;
    const threshold = Math.min(80, width.current * 0.18);
    if (axis.current === 'x' && Math.abs(drag) > threshold) {
      go(drag < 0 ? 1 : -1);
    } else if (drag !== 0) {
      setAnimating(true);
      setDrag(0);
      setTimeout(() => setAnimating(false), 200);
    }
    startX.current = null;
    startY.current = null;
    axis.current = null;
  };

  const download = async () => {
    if (busy) return;
    const item = photos[i];
    // Blob fotoğrafı: ?download=1 bağlantısı tarayıcıya tam çözünürlükte indirtir
    // (CORS/fetch derdi yok). Yerel/manifest fotoğrafı: fetch→blob ile indir.
    if (item.downloadUrl) {
      const a = document.createElement('a');
      a.href = item.downloadUrl;
      a.rel = 'noopener';
      if (item.name) a.download = item.name;
      document.body.appendChild(a);
      a.click();
      a.remove();
      return;
    }
    setBusy(true);
    try {
      await qsDownload(item.full, qsFileName(item.full, i));
    } finally {
      setBusy(false);
    }
  };

  const trackStyle = {
    display: 'flex',
    width: '300%',
    height: '100%',
    transform: `translateX(calc(-33.3333% + ${drag}px))`,
    transition: animating ? 'transform 0.28s cubic-bezier(0.22,0.61,0.36,1)' : 'none',
    willChange: 'transform',
  };

  const slides = n < 2 ? [i] : [prevI, i, nextI];
  const caption = photos[i].caption;

  return (
    <div style={viewerStyles.overlay} role="dialog" aria-modal="true" aria-label="Fotoğraf görüntüleyici">
      {/* Kaydırma alanı */}
      <div
        ref={viewportRef}
        style={viewerStyles.viewport}
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
        onTouchCancel={onTouchEnd}>
        <div style={n < 2 ? viewerStyles.single : trackStyle}>
          {slides.map((k, s) => (
            <div key={`${k}-${s}`} style={viewerStyles.slide}>
              <img
                src={photos[k].full}
                alt={photos[k].caption || `foto ${k + 1}`}
                draggable={false}
                style={viewerStyles.img}
              />
            </div>
          ))}
        </div>
      </div>

      {/* Üst bar: sayaç · indir · kapat */}
      <div style={viewerStyles.topbar}>
        <div className="label-sm" style={viewerStyles.counter}>
          {i + 1} / {n}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button
            onClick={download}
            disabled={busy}
            style={{ ...viewerStyles.roundBtn, opacity: busy ? 0.6 : 1 }}
            aria-label="Yüksek çözünürlükte indir">
            <Icons.Download size={20} />
          </button>
          <button onClick={onClose} style={viewerStyles.roundBtn} aria-label="Kapat">
            <Icons.Close size={20} />
          </button>
        </div>
      </div>

      {/* Yan oklar (birden fazla foto varsa) */}
      {n > 1 && (
        <React.Fragment>
          <button
            onClick={() => go(-1)}
            style={{ ...viewerStyles.nav, left: 'max(10px, env(safe-area-inset-left))' }}
            aria-label="Önceki">
            <Icons.ChevronLeft size={26} />
          </button>
          <button
            onClick={() => go(1)}
            style={{ ...viewerStyles.nav, right: 'max(10px, env(safe-area-inset-right))' }}
            aria-label="Sonraki">
            <Icons.ChevronRight size={26} />
          </button>
        </React.Fragment>
      )}

      {/* Alt: başlık + indir kısayolu */}
      <div style={viewerStyles.bottombar}>
        {caption ? (
          <div className="body-sm" style={viewerStyles.caption}>{caption}</div>
        ) : null}
        <button onClick={download} disabled={busy} style={{ ...viewerStyles.downloadPill, opacity: busy ? 0.7 : 1 }}>
          <Icons.Download size={16} />
          <span className="label">{busy ? 'İndiriliyor…' : 'Yüksek çözünürlükte indir'}</span>
        </button>
      </div>

      <style>{`
        @keyframes qsFade { from { opacity: 0; } to { opacity: 1; } }
      `}</style>
    </div>
  );
}

const qsStyles = {
  grid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(3, 1fr)',
    gap: 6,
  },
  cell: {
    padding: 0,
    borderRadius: 10,
    overflow: 'hidden',
    aspectRatio: '1',
    background: 'rgba(150,40,64,0.06)',
    border: '1px solid rgba(150,40,64,0.12)',
  },
  cellImg: {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
  },
  empty: {
    textAlign: 'center',
    padding: '48px 20px',
    border: '1px dashed rgba(150,40,64,0.25)',
    borderRadius: 18,
    color: 'var(--burgundy)',
    background: 'rgba(150,40,64,0.03)',
  },
  emptyIcon: {
    width: 60,
    height: 60,
    borderRadius: 999,
    border: '1.5px solid rgba(150,40,64,0.3)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: '0 auto 16px',
  },
  shareBtn: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    padding: '9px 16px',
    borderRadius: 999,
    background: 'transparent',
    border: '1.5px solid rgba(150,40,64,0.3)',
    color: 'var(--burgundy)',
  },
  toast: {
    position: 'fixed',
    left: '50%',
    bottom: 'max(24px, env(safe-area-inset-bottom))',
    transform: 'translateX(-50%)',
    background: 'var(--burgundy)',
    color: 'var(--bg)',
    padding: '12px 20px',
    borderRadius: 999,
    fontFamily: "'Pilea',sans-serif",
    fontSize: 13,
    fontWeight: 500,
    letterSpacing: '0.02em',
    maxWidth: 'min(420px, calc(100vw - 32px))',
    textAlign: 'center',
    boxShadow: '0 12px 32px rgba(150,40,64,0.28)',
    zIndex: 1000,
    animation: 'qsToastIn 0.22s ease-out',
    pointerEvents: 'none',
  },
};

const viewerStyles = {
  overlay: {
    position: 'fixed',
    inset: 0,
    zIndex: 90,
    background: '#12060b',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    color: '#fff',
    animation: 'qsFade 0.2s ease-out',
    overscrollBehavior: 'contain',
  },
  viewport: {
    position: 'absolute',
    inset: 0,
    overflow: 'hidden',
    touchAction: 'pan-y',
  },
  single: {
    width: '100%',
    height: '100%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  slide: {
    flex: '0 0 33.3333%',
    width: '33.3333%',
    height: '100%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 'clamp(12px, 4vw, 40px)',
    boxSizing: 'border-box',
  },
  img: {
    maxWidth: '100%',
    maxHeight: '100%',
    width: 'auto',
    height: 'auto',
    objectFit: 'contain',
    userSelect: 'none',
    pointerEvents: 'none',
    borderRadius: 4,
    boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
  },
  topbar: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 'max(14px, env(safe-area-inset-top)) 14px 14px',
    background: 'linear-gradient(rgba(0,0,0,0.45), transparent)',
    zIndex: 2,
  },
  counter: {
    letterSpacing: '0.08em',
    opacity: 0.9,
    padding: '6px 12px',
    borderRadius: 999,
    background: 'rgba(0,0,0,0.35)',
  },
  roundBtn: {
    width: 42,
    height: 42,
    borderRadius: 999,
    background: 'rgba(255,255,255,0.14)',
    border: '1px solid rgba(255,255,255,0.22)',
    color: '#fff',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backdropFilter: 'blur(6px)',
  },
  nav: {
    position: 'absolute',
    top: '50%',
    transform: 'translateY(-50%)',
    width: 46,
    height: 46,
    borderRadius: 999,
    background: 'rgba(0,0,0,0.32)',
    border: '1px solid rgba(255,255,255,0.18)',
    color: '#fff',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 2,
    backdropFilter: 'blur(4px)',
  },
  bottombar: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 12,
    padding: '20px 16px max(18px, env(safe-area-inset-bottom))',
    background: 'linear-gradient(transparent, rgba(0,0,0,0.5))',
    zIndex: 2,
  },
  caption: {
    textAlign: 'center',
    opacity: 0.92,
    maxWidth: 520,
  },
  downloadPill: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    padding: '11px 20px',
    borderRadius: 999,
    background: 'rgba(255,255,255,0.16)',
    border: '1px solid rgba(255,255,255,0.28)',
    color: '#fff',
    backdropFilter: 'blur(6px)',
  },
};

window.Quicksnap = Quicksnap;
