// EYEQ — Featured Work + Gallery (filmstrip + masonry + filter + cursor preview)

const { useState: useStateG, useEffect: useEffectG, useRef: useRefG } = React;

// ── Featured work card (one massive piece) ────────────────────────
function FeaturedWork() {
  const videoRef = useRefG(null);
  const [playing, setPlaying] = useStateG(false);
  const [tc, setTc] = useStateG('00:00:00:00');

  const toggle = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) { v.play().catch(()=>{}); } else { v.pause(); }
  };

  useEffectG(() => {
    const v = videoRef.current;
    if (!v) return;
    const onPlay = () => setPlaying(true);
    const onPause = () => setPlaying(false);
    const onTime = () => {
      const t = v.currentTime || 0;
      const h = Math.floor(t / 3600);
      const m = Math.floor((t % 3600) / 60);
      const s = Math.floor(t % 60);
      const f = Math.floor((t * 24) % 24);
      const pad = (n) => String(n).padStart(2, '0');
      setTc(`${pad(h)}:${pad(m)}:${pad(s)}:${pad(f)}`);
    };
    v.addEventListener('play', onPlay);
    v.addEventListener('pause', onPause);
    v.addEventListener('timeupdate', onTime);
    return () => {
      v.removeEventListener('play', onPlay);
      v.removeEventListener('pause', onPause);
      v.removeEventListener('timeupdate', onTime);
    };
  }, []);

  // Auto-pause when scrolled out of view
  useEffectG(() => {
    const v = videoRef.current;
    if (!v || !('IntersectionObserver' in window)) return;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting && !v.paused) v.pause();
    }, { threshold: 0.15 });
    io.observe(v);
    return () => io.disconnect();
  }, []);

  return (
    <section className="section" id="work" style={{ paddingTop: 'clamp(80px, 12vh, 120px)' }}>
      <div className="section-head">
        <div>
          <div className="section-idx">03 — FEATURED WORK · CASE STUDY №21</div>
          <h2 className="section-title">A film for <em>Vahl,</em><br />measured in heartbeats.</h2>
        </div>
        <div className="section-sub">
          A 90-second product film for House of Vahl's Solstice collection, shot on Alexa 35 across three
          continents, color-graded for theatrical release before being down-rezzed for the boutique.
        </div>
      </div>

      <div className="featured">
        <div className={`featured-visual ${playing ? 'is-playing' : ''}`} onClick={toggle}>
          <video
            ref={videoRef}
            data-camera-zoom
            className="featured-video"
            src="https://download.blender.org/durian/trailer/sintel_trailer-1080p.mp4"
            poster="https://images.unsplash.com/photo-1485846234645-a62644f84728?w=2000&q=85&auto=format&fit=crop"
            playsInline
            muted
            loop
            preload="metadata"
          />
          <div className="featured-stamp">
            <span className="dot" />
            <span>SCENE 14 · TAKE 03 · {playing ? 'PLAYING' : 'MASTER'}</span>
          </div>
          <div className="featured-corner-tc">
            A001_C014_0721 · 23.976 fps · TC {tc}
          </div>
          <div className="featured-play ">
            <button
              className="featured-play-btn"
              aria-label={playing ? 'Pause reel' : 'Play reel'}
              onClick={(e) => { e.stopPropagation(); toggle(); }}
            >
              {playing ? <>❚❚ &nbsp;PAUSE</> : <>▷ &nbsp;PLAY</>}
            </button>
          </div>
          <div className="featured-scanline" aria-hidden />
        </div>

        <div className="featured-body">
          <div>
            <div className="featured-client">House of Vahl · Munich</div>
            <h3 className="featured-title">Solstice — <em>A Watch</em><br />for the Long Hours.</h3>
            <p className="featured-desc">
              Three months in development. Six days of capture across Munich, Tokyo, and the Atacama.
              One uninterrupted master take that anchored the entire edit. Shortlisted at Cannes Lions
              2025 for Film Craft.
            </p>
          </div>

          <div className="featured-credits">
            <div className="fc-row"><span className="fc-label">Client</span><span className="fc-val">House of <em>Vahl</em></span></div>
            <div className="fc-row"><span className="fc-label">Director</span><span className="fc-val">Aria <em>Shah</em></span></div>
            <div className="fc-row"><span className="fc-label">DP</span><span className="fc-val">Marcus <em>Vey</em></span></div>
            <div className="fc-row"><span className="fc-label">Colorist</span><span className="fc-val">Iris <em>Tanaka</em></span></div>
            <div className="fc-row"><span className="fc-label">Format</span><span className="fc-val">6.5K · Alexa 35</span></div>
            <div className="fc-row"><span className="fc-label">Runtime</span><span className="fc-val">02:14 master · 00:30 cut</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Filter bar ────────────────────────────────────────────────────
const FILTERS = [
  { key: 'all',         label: 'All Work' },
  { key: 'corporate',   label: 'Corporate' },
  { key: '3d',          label: '3D / Animation' },
  { key: 'weddings',    label: 'Weddings' },
  { key: 'documentary', label: 'Documentary' },
];

// ── Cursor-tracked preview ────────────────────────────────────────
function CursorPreview({ item, x, y, visible }) {
  return (
    <div
      className={`cursor-preview ${visible ? 'show' : ''}`}
      style={{
        left: x + 'px',
        top: y + 'px',
        backgroundImage: item ? `url(${item.img})` : 'none',
      }}
      data-label={item ? `${item.name} · ${item.duration}` : ''}
      aria-hidden
    />
  );
}

// ── Filmstrip + masonry gallery ───────────────────────────────────
function Gallery({ hoverStyle = 'zoom' }) {
  const [filter, setFilter] = useStateG('all');
  const [aperture, setAperture] = useStateG(false);
  const [cursor, setCursor] = useStateG({ x: 0, y: 0, visible: false, item: null });

  const all = window.GALLERY;
  const filtered = filter === 'all' ? all : all.filter(g => g.cat === filter);

  const counts = useMemo(() => {
    const c = { all: all.length };
    for (const g of all) c[g.cat] = (c[g.cat] || 0) + 1;
    return c;
  }, [all]);

  const handleFilter = (k) => {
    if (k === filter) return;
    setAperture(true);
    setTimeout(() => setFilter(k), 220);
    setTimeout(() => setAperture(false), 700);
  };

  const onItemMove = (e, item) => {
    setCursor({ x: e.clientX, y: e.clientY, visible: true, item });
  };
  const onItemLeave = () => setCursor(c => ({ ...c, visible: false }));

  return (
    <section className="section" id="gallery" style={{ paddingTop: 'clamp(60px, 8vh, 100px)' }}>
      <div className="section-head">
        <div>
          <div className="section-idx">04 — GALLERY · 124 SELECTS</div>
          <h2 className="section-title">A scroll <em>through</em><br />the archive.</h2>
        </div>
        <div className="section-sub">
          The work, organized the way our editors think about it. Hover any frame to preview.
          Drag horizontally on the filmstrip or scroll down for the masonry.
        </div>
      </div>

      <div className="filterbar">
        <div className="filterbar-tabs">
          {FILTERS.map(f => (
            <button
              key={f.key}
              className={`filter-tab ${filter === f.key ? 'active' : ''}`}
              onClick={() => handleFilter(f.key)}
            >
              <span>{f.label}</span>
              <span className="count">{String(counts[f.key] || 0).padStart(2, '0')}</span>
            </button>
          ))}
        </div>
        <div className="filterbar-meta">
          SHOWING <b>{String(filtered.length).padStart(2, '0')}</b> OF {String(all.length).padStart(2, '0')} · SORT: <b>RECENT</b>
        </div>
      </div>

      {/* Filmstrip */}
      <div className="filmstrip-wrap" style={{ opacity: aperture ? 0.15 : 1, filter: aperture ? 'blur(8px)' : 'none', transition: 'opacity .35s, filter .35s' }}>
        <div className="filmstrip">
          {filtered.map((g, i) => (
            <div
              key={g.id}
              className={`fs-item ${i % 4 === 1 ? 'tall' : ''}`}
              data-hover={hoverStyle}
              onMouseMove={(e) => onItemMove(e, g)}
              onMouseLeave={onItemLeave}
            >
              <div className="fs-img" style={{ backgroundImage: `url(${g.img})` }} />
              <div className="fs-overlay" />
              <div className="fs-num">№ {String(g.id).padStart(2, '0')} / {String(all.length).padStart(2, '0')}</div>
              <div className="fs-duration">{g.duration}</div>
              <div className="fs-meta">
                <div>
                  <div className="fs-cat">{g.cat === '3d' ? '3D' : g.cat}</div>
                  <div className="fs-name">{g.name}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="filmstrip-scrollhint">
          <span>← DRAG · SCROLL HORIZONTALLY</span>
          <span>{String(filtered.length).padStart(2, '0')} CLIPS</span>
        </div>
      </div>

      {/* Masonry */}
      <div className="masonry-wrap">
        <div className="masonry-head">
          <div>
            <div className="section-idx">04b — STILLS · MASONRY</div>
            <h3 className="serif" style={{ fontSize: 'clamp(28px, 3vw, 44px)', letterSpacing: '-0.02em', lineHeight: 1, marginTop: 6 }}>
              The <em style={{ fontStyle: 'italic', color: 'var(--gold)' }}>edge</em>-to-edge cut.
            </h3>
          </div>
          <div className="filterbar-meta">
            PRESS <b>F</b> TO ENTER FULLSCREEN
          </div>
        </div>
        <div className="masonry">
          {window.MASONRY.map((m, i) => (
            <div
              key={i}
              className="masonry-item"
              onMouseMove={(e) => onItemMove(e, { ...m, duration: 'STILL' })}
              onMouseLeave={onItemLeave}
            >
              <img src={m.img} alt={m.name} loading="lazy" />
              <div className="masonry-meta">
                <div>
                  <div className="masonry-cat">{m.cat === '3d' ? '3D' : m.cat}</div>
                  <div className="masonry-name">{m.name}</div>
                </div>
                <div className="masonry-cat" style={{ color: 'var(--text-dim)' }}>VIEW →</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Aperture overlay during filter change */}
      {aperture && <ApertureFlash />}
      <CursorPreview x={cursor.x} y={cursor.y} item={cursor.item} visible={cursor.visible && hoverStyle === 'play'} />
    </section>
  );
}

function ApertureFlash() {
  return (
    <div style={{
      position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 9000,
      background: '#000',
      maskImage: 'radial-gradient(circle at center, transparent 0%, transparent var(--ap, 0%), black calc(var(--ap, 0%) + 4%))',
      WebkitMaskImage: 'radial-gradient(circle at center, transparent 0%, transparent var(--ap, 0%), black calc(var(--ap, 0%) + 4%))',
      animation: 'apFlash 0.7s ease-in-out forwards',
    }}>
      <style>{`
        @keyframes apFlash {
          0%   { -webkit-mask-image: radial-gradient(circle at center, transparent 0%, transparent 5%, black 9%); }
          50%  { -webkit-mask-image: radial-gradient(circle at center, transparent 0%, transparent 80%, black 84%); }
          100% { -webkit-mask-image: radial-gradient(circle at center, transparent 0%, transparent 100%, black 104%); }
        }
      `}</style>
    </div>
  );
}

const { useMemo } = React;

Object.assign(window, { FeaturedWork, Gallery });
