/* global React */
const { useEffect, useRef, useState } = React;

function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
        }
      });
    }, { threshold: 0.12 });
    el.querySelectorAll('.reveal').forEach(n => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

function Arrow({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14" /><path d="m13 5 7 7-7 7" />
    </svg>
  );
}

function Play({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
      <path d="M8 5v14l11-7z" />
    </svg>
  );
}

function VideoPH({ label = 'Ваше відео', aspect = '16 / 9', className = '', style = {}, children }) {
  return (
    <div className={`video-ph ${className}`} style={{ aspectRatio: aspect, borderRadius: 'var(--radius)', ...style }}>
      <div className="ph-label"><span className="rec" /> {label}</div>
      {children}
    </div>
  );
}

function PhotoPH({ label, hue = 280, tall = false, className = '', style = {}, src = null }) {
  const px = 30 + Math.random() * 40;
  const py = 20 + Math.random() * 60;

  if (src) {
    return (
      <div
        className={`photo-ph ${className}`}
        style={{
          aspectRatio: tall ? '3 / 4' : '4 / 3',
          borderRadius: 'var(--radius)',
          position: 'relative',
          overflow: 'hidden',
          background: `oklch(20% 0.06 ${hue})`,
          ...style,
        }}
      >
        <img
          src={src}
          alt={label || ''}
          loading="lazy"
          decoding="async"
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}
        />
        {label && <div className="ph-tag" style={{ position: 'absolute', bottom: 12, left: 12, zIndex: 2 }}>{label}</div>}
      </div>
    );
  }

  return (
    <div
      className={`photo-ph gradient ${className}`}
      style={{
        aspectRatio: tall ? '3 / 4' : '4 / 3',
        borderRadius: 'var(--radius)',
        '--px': px + '%',
        '--py': py + '%',
        '--violet-soft': `oklch(60% 0.18 ${hue})`,
        ...style,
      }}
    >
      {label && <div className="ph-tag">{label}</div>}
    </div>
  );
}

function MagneticBtn({ children, className = 'btn btn-primary', onClick, ...rest }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = e.clientX - r.left - r.width / 2;
    const y = e.clientY - r.top - r.height / 2;
    ref.current.style.transform = `translate(${x * 0.15}px, ${y * 0.25}px)`;
  };
  const onLeave = () => { ref.current.style.transform = ''; };
  return (
    <button ref={ref} className={className} onClick={onClick} onMouseMove={onMove} onMouseLeave={onLeave} {...rest}>
      {children}
    </button>
  );
}

function Marquee({ items, speed = 40 }) {
  const doubled = [...items, ...items];
  return (
    <div style={{ overflow: 'hidden', mask: 'linear-gradient(90deg, transparent, #000 6%, #000 94%, transparent)' }}>
      <div className="marquee" style={{ animationDuration: speed + 's' }}>
        {doubled.map((it, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 20, fontFamily: 'Unbounded', fontWeight: 600, fontSize: 'clamp(28px, 5vw, 64px)', color: 'var(--fg-2)', letterSpacing: '-0.02em' }}>
            {it}
            <span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--violet)' }} />
          </span>
        ))}
      </div>
    </div>
  );
}

function Lightbox({ open, items, index, onIndex, onClose, labelPrefix = 'GALLERY' }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') onIndex((index + 1) % items.length);
      if (e.key === 'ArrowLeft') onIndex((index - 1 + items.length) % items.length);
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, index, items.length, onIndex, onClose]);

  if (!open) return null;
  const it = items[index];
  const src = it?.src || null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 500,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        animation: 'pageFade .25s var(--ease)',
      }}
    >
      {/* Blurred background */}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 0,
        background: src
          ? `url(${src}) center/cover no-repeat`
          : 'rgba(5,5,8,1)',
        filter: 'blur(28px) brightness(0.35) saturate(1.4)',
        transform: 'scale(1.08)',
      }} />
      <div style={{ position: 'absolute', inset: 0, zIndex: 1, background: 'rgba(0,0,0,0.55)' }} />

      {/* Close button */}
      <button
        onClick={(e) => { e.stopPropagation(); onClose(); }}
        style={{
          position: 'absolute', top: 24, right: 24, zIndex: 10,
          color: '#fff', fontSize: 13, fontFamily: 'JetBrains Mono', letterSpacing: 0.1,
          padding: '9px 16px', border: '1px solid rgba(255,255,255,.25)', borderRadius: 999,
          background: 'rgba(0,0,0,.4)', backdropFilter: 'blur(10px)',
        }}
      >ESC ✕</button>

      {/* Counter */}
      <div style={{
        position: 'absolute', top: 28, left: '50%', transform: 'translateX(-50%)', zIndex: 10,
        fontFamily: 'JetBrains Mono', fontSize: 11, color: 'rgba(255,255,255,.6)', letterSpacing: '0.1em',
      }}>
        {String(index + 1).padStart(2, '0')} / {String(items.length).padStart(2, '0')}
      </div>

      {/* Main image */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative', zIndex: 5,
          maxWidth: 'min(1100px, 90vw)', maxHeight: 'calc(100vh - 160px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        {src ? (
          <img
            key={src}
            src={src}
            alt={it?.label || ''}
            style={{
              maxWidth: '100%', maxHeight: 'calc(100vh - 160px)',
              objectFit: 'contain', borderRadius: 14,
              boxShadow: '0 32px 80px rgba(0,0,0,.7)',
              animation: 'pageFade .2s var(--ease)',
            }}
          />
        ) : (
          <PhotoPH label={it?.label || ''} hue={it?.hue ?? 285}
            style={{ width: 'min(900px, 80vw)', aspectRatio: '16/10', borderRadius: 14 }} />
        )}

        {/* Prev arrow */}
        <button
          onClick={(e) => { e.stopPropagation(); onIndex((index - 1 + items.length) % items.length); }}
          style={{
            position: 'fixed', left: 20, top: '50%', transform: 'translateY(-50%)',
            color: '#fff', width: 52, height: 52, borderRadius: 999,
            border: '1px solid rgba(255,255,255,.25)', background: 'rgba(0,0,0,.45)',
            backdropFilter: 'blur(10px)', fontSize: 20, cursor: 'pointer', zIndex: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background .2s, border-color .2s',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,.15)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(0,0,0,.45)'; }}
        >←</button>

        {/* Next arrow */}
        <button
          onClick={(e) => { e.stopPropagation(); onIndex((index + 1) % items.length); }}
          style={{
            position: 'fixed', right: 20, top: '50%', transform: 'translateY(-50%)',
            color: '#fff', width: 52, height: 52, borderRadius: 999,
            border: '1px solid rgba(255,255,255,.25)', background: 'rgba(0,0,0,.45)',
            backdropFilter: 'blur(10px)', fontSize: 20, cursor: 'pointer', zIndex: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background .2s',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,.15)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'rgba(0,0,0,.45)'; }}
        >→</button>
      </div>

      {/* Label */}
      {it?.label && (
        <div style={{
          position: 'relative', zIndex: 5, marginTop: 14,
          color: 'rgba(255,255,255,.75)', fontFamily: 'JetBrains Mono',
          fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>{it.label}</div>
      )}

      {/* Thumbnail strip */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative', zIndex: 5, marginTop: 16,
          display: 'flex', gap: 8, maxWidth: 'min(1100px, 90vw)',
          overflowX: 'auto', paddingBottom: 4,
        }}
      >
        {items.map((thumb, i) => (
          <button
            key={i}
            onClick={(e) => { e.stopPropagation(); onIndex(i); }}
            style={{
              flexShrink: 0, width: 64, height: 48, padding: 0, cursor: 'pointer',
              borderRadius: 8, overflow: 'hidden',
              border: i === index ? '2px solid #fff' : '2px solid rgba(255,255,255,.2)',
              opacity: i === index ? 1 : 0.55,
              transition: 'opacity .2s, border-color .2s',
            }}
          >
            {thumb.src
              ? <img src={thumb.src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              : <div style={{ width: '100%', height: '100%', background: `oklch(30% 0.1 ${thumb.hue || 285})` }} />
            }
          </button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { useReveal, Arrow, Play, VideoPH, PhotoPH, MagneticBtn, Marquee, Lightbox });
