/* SUPERMEDIA storefront — Lightbox: fullscreen image viewer with zoom + browsing.
 * Works on both desktop (arrows + click-to-zoom) and mobile (swipe + tap).
 * Usage:  <Lightbox images={[url, ...]} index={n} onClose={fn} /> — render only when open. */
const { useState: useStateLB, useEffect: useEffectLB, useRef: useRefLB } = React;

function Lightbox({ images, index = 0, onClose }) {
  const list = (images && images.length) ? images : [];
  const [i, setI] = useStateLB(index);
  const [zoom, setZoom] = useStateLB(false);
  const [pan, setPan] = useStateLB({ x: 0, y: 0 });
  const touch = useRefLB({ x: 0, y: 0, t: 0 });

  const n = list.length;
  const go = (d) => { setZoom(false); setPan({ x: 0, y: 0 }); setI(v => (v + d + n) % n); };

  useEffectLB(() => {
    if (window.lucide) window.lucide.createIcons();
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
    };
    document.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [n]);
  useEffectLB(() => { if (window.lucide) window.lucide.createIcons(); }, [i, zoom]);

  const onImgClick = (e) => {
    e.stopPropagation();
    if (!zoom) {
      const r = e.currentTarget.getBoundingClientRect();
      const cx = ((e.clientX - r.left) / r.width - 0.5) * -100;
      const cy = ((e.clientY - r.top) / r.height - 0.5) * -100;
      setPan({ x: cx, y: cy });
      setZoom(true);
    } else { setZoom(false); setPan({ x: 0, y: 0 }); }
  };
  const onTouchStart = (e) => { const t = e.touches[0]; touch.current = { x: t.clientX, y: t.clientY, t: Date.now() }; };
  const onTouchEnd = (e) => {
    const t = e.changedTouches[0];
    const dx = t.clientX - touch.current.x, dy = t.clientY - touch.current.y;
    if (Math.abs(dx) > 45 && Math.abs(dx) > Math.abs(dy) && !zoom) { go(dx < 0 ? 1 : -1); }
  };

  const ctrl = { position: 'absolute', top: '50%', transform: 'translateY(-50%)', width: 52, height: 52, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'rgba(255,255,255,.14)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', zIndex: 3 };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 4000, background: 'rgba(16,12,22,.93)', display: 'flex', flexDirection: 'column', animation: 'sm-pop .2s ease-out' }}>
      {/* top bar */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px', flex: 'none' }}>
        <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, color: 'rgba(255,255,255,.85)' }}>{n > 1 ? (i + 1) + ' / ' + n : ''}</span>
        <button onClick={onClose} aria-label="Zatvori" style={{ width: 46, height: 46, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'rgba(255,255,255,.14)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)' }}>{I('x', 24)}</button>
      </div>

      {/* stage */}
      <div style={{ position: 'relative', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}
        onClick={e => e.stopPropagation()} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
        <img src={list[i]} alt="" onClick={onImgClick} style={{
          maxWidth: '92%', maxHeight: '100%', objectFit: 'contain', userSelect: 'none',
          cursor: zoom ? 'zoom-out' : 'zoom-in',
          transform: zoom ? `scale(2.2) translate(${pan.x}%, ${pan.y}%)` : 'scale(1)',
          transition: 'transform .28s cubic-bezier(.4,0,.2,1)',
        }} />
        {n > 1 && (
          <React.Fragment>
            <button onClick={() => go(-1)} aria-label="Prethodna" style={{ ...ctrl, left: 14 }}>{I('chevron-left', 26)}</button>
            <button onClick={() => go(1)} aria-label="Sledeća" style={{ ...ctrl, right: 14 }}>{I('chevron-right', 26)}</button>
          </React.Fragment>
        )}
      </div>

      {/* thumbnails */}
      {n > 1 && (
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', padding: '16px', flex: 'none', flexWrap: 'wrap' }} onClick={e => e.stopPropagation()}>
          {list.map((src, k) => (
            <button key={k} onClick={() => { setZoom(false); setPan({ x: 0, y: 0 }); setI(k); }} style={{
              width: 58, height: 58, borderRadius: 'var(--sm-radius-sm)', cursor: 'pointer', padding: 4,
              background: '#fff', border: k === i ? '2px solid var(--sm-primary)' : '2px solid transparent',
              opacity: k === i ? 1 : .55, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'opacity .15s',
            }}><img src={src} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} /></button>
          ))}
        </div>
      )}
      <div style={{ textAlign: 'center', paddingBottom: 14, fontSize: 12.5, color: 'rgba(255,255,255,.5)', flex: 'none' }}>
        {zoom ? 'Klikni za smanjivanje' : 'Klikni na sliku za uvećanje'}
      </div>
    </div>
  );
}

Object.assign(window, { Lightbox });
