// Pledge photos viewer — Komek Lombard v2
// Full-screen first photo + thumbnail strip; tap a thumb or swipe to switch.

const PV_TEAL = '#1B7F70';
const PV_TEAL_DEEP = '#176A5D';
const PV_BG = '#EBEBEC';
const PV_PANEL = '#FFFFFF';
const PV_PHOTO_BG = '#F4F4F6';
const PV_LABEL = '#0B0B0C';
const PV_SUBTLE = '#8A8A8E';

// The photo list the backend returns for a ticket. `src` is the real photo URL.
const PHOTOS = [
  { id: 'p1', label: 'Кольцо, фото 1', src: 'uploads/ring-1.jpg' },
  { id: 'p2', label: 'Кольцо, фото 2', src: 'uploads/ring-2.jpg' },
  { id: 'p3', label: 'Кольцо, фото 3', src: 'uploads/ring-3.jpg' },
];

function PhotoFrame({ photo, big }) {
  // Real backend photo (object-fit: cover for thumbs, contain for the big view).
  return (
    <div style={{
      position: 'absolute', inset: 0, background: '#111',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <img
        src={photo.src}
        alt={photo.label}
        draggable={false}
        style={{
          width: '100%', height: '100%',
          objectFit: big ? 'contain' : 'cover',
          userSelect: 'none', pointerEvents: 'none',
        }}
      />
    </div>
  );
}

function PhotoGalleryScreen({ onBack, photos = PHOTOS }) {
  const [idx, setIdx] = React.useState(0);
  const count = photos.length;
  const go = (n) => setIdx((prev) => (n + count) % count);
  const stripRef = React.useRef(null);
  const drag = React.useRef({ x: 0, dx: 0, active: false });

  // keep the active thumbnail in view
  React.useEffect(() => {
    const strip = stripRef.current;
    if (!strip) return;
    const el = strip.children[idx];
    if (el) {
      const left = el.offsetLeft - (strip.clientWidth - el.clientWidth) / 2;
      strip.scrollTo({ left, behavior: 'smooth' });
    }
  }, [idx]);

  const onStart = (x) => { drag.current = { x, dx: 0, active: true }; };
  const onMove = (x) => { if (drag.current.active) drag.current.dx = x - drag.current.x; };
  const onEnd = () => {
    if (!drag.current.active) return;
    const dx = drag.current.dx;
    drag.current.active = false;
    if (dx <= -44) go(idx + 1);
    else if (dx >= 44) go(idx - 1);
  };

  return (
    <div style={{
      height: '100%', background: PV_BG, display: 'flex', flexDirection: 'column',
      fontFamily: '-apple-system, "SF Pro Text", system-ui, sans-serif',
      WebkitFontSmoothing: 'antialiased',
    }}>
      {/* top bar */}
      <div style={{
        flexShrink: 0,
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '52px 16px 12px',
      }}>
        <button onClick={onBack} aria-label="Назад" style={{
          width: 38, height: 38, borderRadius: 19, border: 'none',
          background: 'rgba(0,0,0,0.06)', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M15 5l-7 7 7 7" stroke={PV_LABEL} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: PV_LABEL, fontSize: 17, fontWeight: 700 }}>Фотографии</div>
          <div style={{ color: PV_SUBTLE, fontSize: 12.5, marginTop: 1 }}>
            № VV000000082
          </div>
        </div>
        <div style={{
          color: PV_TEAL_DEEP, fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap',
          background: '#E4F1EE', padding: '5px 11px', borderRadius: 13,
        }}>{idx + 1} / {count}</div>
      </div>

      {/* full-size photo (swipeable) */}
      <div
        style={{
          flex: 1, minHeight: 0, position: 'relative', overflow: 'hidden',
          margin: '0 16px', borderRadius: 18, background: '#111',
          touchAction: 'pan-y',
        }}
        onTouchStart={(e) => onStart(e.touches[0].clientX)}
        onTouchMove={(e) => onMove(e.touches[0].clientX)}
        onTouchEnd={onEnd}
        onMouseDown={(e) => onStart(e.clientX)}
        onMouseMove={(e) => drag.current.active && onMove(e.clientX)}
        onMouseUp={onEnd}
        onMouseLeave={onEnd}
      >
        {/* sliding track */}
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          transform: `translateX(-${idx * 100}%)`,
          transition: 'transform 260ms cubic-bezier(0.4,0,0.2,1)',
        }}>
          {photos.map((p) => (
            <div key={p.id} style={{ position: 'relative', flex: '0 0 100%', height: '100%' }}>
              <PhotoFrame photo={p} big/>
            </div>
          ))}
        </div>

        {/* edge arrows (desktop affordance) */}
        {count > 1 && (
          <React.Fragment>
            <NavArrow side="left" onClick={() => go(idx - 1)}/>
            <NavArrow side="right" onClick={() => go(idx + 1)}/>
          </React.Fragment>
        )}

        {/* dots */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 12,
          display: 'flex', justifyContent: 'center', gap: 6,
        }}>
          {photos.map((p, i) => (
            <span key={p.id} style={{
              width: i === idx ? 18 : 6, height: 6, borderRadius: 3,
              background: i === idx ? '#fff' : 'rgba(255,255,255,0.45)',
              transition: 'width 200ms ease, background 200ms ease',
            }}/>
          ))}
        </div>
      </div>

      {/* thumbnail strip */}
      <div style={{ flexShrink: 0, background: PV_PANEL, padding: '14px 0 24px', marginTop: 14, borderTopLeftRadius: 22, borderTopRightRadius: 22, boxShadow: '0 -4px 18px rgba(0,0,0,0.06)' }}>
        <div ref={stripRef} style={{
          display: 'flex', gap: 10, overflowX: 'auto', padding: '0 16px',
          scrollbarWidth: 'none',
        }}>
          {photos.map((p, i) => {
            const active = i === idx;
            return (
              <button key={p.id} onClick={() => setIdx(i)} aria-label={p.label} style={{
                flex: '0 0 auto', width: 64, height: 64, borderRadius: 12,
                position: 'relative', overflow: 'hidden', cursor: 'pointer', padding: 0,
                border: active ? `2.5px solid ${PV_TEAL}` : '2.5px solid #E4E4E7',
                boxShadow: 'none',
                transition: 'border-color 150ms ease',
              }}>
                <PhotoFrame photo={p}/>
                {!active && <div style={{ position: 'absolute', inset: 0, background: 'rgba(255,255,255,0.28)' }}/>}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function NavArrow({ side, onClick }) {
  return (
    <button onClick={onClick} aria-label={side === 'left' ? 'Предыдущая' : 'Следующая'} style={{
      position: 'absolute', top: '50%', transform: 'translateY(-50%)',
      [side]: 10, width: 36, height: 36, borderRadius: 18, border: 'none',
      background: 'rgba(0,0,0,0.32)', cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" style={{ transform: side === 'right' ? 'scaleX(-1)' : 'none' }}>
        <path d="M15 5l-7 7 7 7" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </button>
  );
}

Object.assign(window, { PhotoGalleryScreen });
