// Resolve a Wistia share URL (https://*.wistia.com/s/<token>) to its real media
// ID via oembed. Direct media IDs are returned as-is.
const __workWistiaCache = new Map();
const __workWistiaInflight = new Map();
function resolveWistiaId(key) {
  if (!key) return Promise.resolve(null);
  if (!/^https?:\/\//i.test(key)) return Promise.resolve(key);
  if (__workWistiaCache.has(key)) return Promise.resolve(__workWistiaCache.get(key));
  if (__workWistiaInflight.has(key)) return __workWistiaInflight.get(key);
  const p = fetch(`https://fast.wistia.com/oembed.json?url=${encodeURIComponent(key)}`)
    .then(r => r.ok ? r.json() : Promise.reject(new Error('oembed ' + r.status)))
    .then(j => {
      let mediaId = null;
      if (typeof j.html === 'string') {
        const m =
          j.html.match(/embed\/iframe\/([a-z0-9]+)/i) ||
          j.html.match(/wistia_async_([a-z0-9]+)/i) ||
          j.html.match(/medias\/([a-z0-9]+)/i);
        if (m) mediaId = m[1];
      }
      __workWistiaCache.set(key, mediaId);
      return mediaId;
    })
    .catch(() => { __workWistiaCache.set(key, null); return null; });
  __workWistiaInflight.set(key, p);
  return p;
}

function Work() {
  // 5 vertical reels, one line. `wistia` may be either a 10-char media ID
  // or a https://<acct>.wistia.com/s/<token> share URL — the resolver above
  // turns share URLs into media IDs at runtime.
  const reels = [
    { id: 'anik-1', title: 'Featured Reel', audience: 'Featured', kind: 'Vertical Reel', wistia: 'wbv79niu02' },
    { id: 'siam-featured-1', title: 'Siam — Featured Reel', audience: 'Personal Brand', kind: 'Vertical Reel', wistia: 'r862hqp8sm' },
    { id: 'misc-2nj', title: 'Vertical Reel', audience: 'Featured', kind: 'Vertical Reel', wistia: '2nj977dche' },
    { id: 'ad-xses', title: 'Paid Social Ad', audience: 'Founders', kind: 'Performance Ad', wistia: 'https://arafat5nexcutmedia.wistia.com/s/xsesjkiysrd2vym' },
    { id: 'b7uz',  title: 'Keaton — Fitness', audience: 'Fitness Coach', kind: 'Vertical Reel', wistia: 'b7uzkvsztd' },
    { id: 'adam-4', title: 'Adam — Business Reel', audience: 'Founders', kind: 'Vertical Reel', wistia: 'mgdr07w6w2' },
    { id: 'aron-1', title: 'Aron Thomas — Pro', audience: 'Professionals', kind: 'Vertical Reel', wistia: 'm6eoqxnes5' },
  ];

  // Map each reel id → resolved media ID. Direct IDs land in the map
  // immediately; share URLs fill in once oembed responds.
  const [resolvedIds, setResolvedIds] = useState(() => {
    const m = {};
    for (const r of reels) {
      if (r.wistia && !/^https?:\/\//i.test(r.wistia)) m[r.id] = r.wistia;
    }
    return m;
  });

  useEffect(() => {
    let cancelled = false;
    reels.forEach((r) => {
      if (r.wistia && /^https?:\/\//i.test(r.wistia)) {
        resolveWistiaId(r.wistia).then((id) => {
          if (cancelled || !id) return;
          setResolvedIds((prev) => prev[r.id] === id ? prev : { ...prev, [r.id]: id });
        });
      }
    });
    return () => { cancelled = true; };
  }, []);

  const [playing, setPlaying] = useState(null);

  // Load Wistia player script once
  useEffect(() => {
    if (document.getElementById('wistia-script')) return;
    const s = document.createElement('script');
    s.id = 'wistia-script';
    s.src = 'https://fast.wistia.com/assets/external/E-v1.js';
    s.async = true;
    document.body.appendChild(s);
  }, []);

  return (
    <section id="work" style={{ padding: '72px 0', position: 'relative', overflow: 'hidden' }}>
      {/* Horizon glow rising from the bottom of the section */}
      <div aria-hidden style={{
        position: 'absolute',
        left: '50%', bottom: -100,
        transform: 'translateX(-50%)',
        width: '140%', height: 520,
        background: 'radial-gradient(ellipse 55% 100% at 50% 100%, rgba(225,238,255,0.45) 0%, rgba(110,167,255,0.3) 22%, rgba(74,142,255,0.12) 45%, transparent 70%)',
        filter: 'blur(40px)',
        pointerEvents: 'none',
        zIndex: 0,
      }} />

      <div className="container" style={{ textAlign: 'center', marginBottom: 36, position: 'relative', zIndex: 2 }}>
        <Reveal><SectionEyebrow label="Our Work" /></Reveal>
        <Reveal delay={80}>
          <h2 className="display" style={{ fontSize: 'clamp(36px, 5vw, 56px)', marginTop: 22, lineHeight: 1.05 }}>
            <span className="serif-italic" style={{ color: 'var(--ink-dim)' }}>Some Of Our</span><br />
            Featured Projects
          </h2>
        </Reveal>
        <Reveal delay={160}>
          <p style={{
            marginTop: 12,
            fontSize: 14,
            color: 'var(--ink-muted)',
            maxWidth: 520,
            marginInline: 'auto',
            lineHeight: 1.5,
          }}>
            Reels, VSLs, long-form and ads — four formats, five industries, one studio.
          </p>
        </Reveal>
      </div>

      <div className="container container-wide" style={{ position: 'relative', zIndex: 2 }}>
        <div className="work-reels">
          {reels.map((p, idx) => {
            const mediaId = resolvedIds[p.id];
            const isPlaying = !!mediaId && playing === mediaId;
            return (
              <WorkTile
                key={p.id}
                p={p}
                idx={idx}
                mediaId={mediaId}
                isPlaying={isPlaying}
                onPlay={() => mediaId && !isPlaying && setPlaying(mediaId)}
              />
            );
          })}
        </div>

        {/* Stronger CTA */}
        <div style={{
          textAlign: 'center',
          marginTop: 40,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          gap: 10,
        }}>
          <a href="portfolio.html" target="_blank" rel="noopener" className="portfolio-cta">
            <span className="portfolio-cta-glow" aria-hidden></span>
            <span className="portfolio-cta-inner">
              <span className="portfolio-cta-dot" aria-hidden></span>
              <span>See the full portfolio</span>
              <span className="portfolio-cta-arrow" aria-hidden>
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                  <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </span>
            </span>
          </a>
          <div style={{
            fontSize: 11.5,
            color: 'var(--ink-muted)',
            fontFamily: "'Geist Mono', ui-monospace, monospace",
            letterSpacing: '0.04em',
          }}>
            24+ more cuts inside · Reels · VSL · Ads · Long-Form
          </div>
        </div>
      </div>

      <style>{`
        .work-reels {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          gap: 10px;
          max-width: 1280px;
          margin: 0 auto;
        }
        @media (max-width: 1200px) {
          .work-reels { grid-template-columns: repeat(4, 1fr); max-width: 880px; }
        }
        @media (max-width: 720px) {
          .work-reels { grid-template-columns: repeat(3, 1fr); max-width: 560px; }
        }
        @media (max-width: 480px) {
          .work-reels { grid-template-columns: repeat(2, 1fr); }
        }

        /* Portfolio CTA — glowing pill with sheen + animated arrow */
        .portfolio-cta {
          position: relative;
          display: inline-flex;
          isolation: isolate;
          padding: 1px;
          border-radius: 999px;
          text-decoration: none;
          background: conic-gradient(from 0deg, #2949E5, #6EA8FE, #2949E5, #1a2b8a, #2949E5);
          background-size: 200% 200%;
          animation: portfolioCtaSpin 6s linear infinite;
          box-shadow:
            0 10px 30px -10px rgba(41,73,229,0.65),
            0 0 0 1px rgba(110,168,254,0.25);
          transition: transform .25s ease, box-shadow .25s ease;
        }
        .portfolio-cta:hover {
          transform: translateY(-2px);
          box-shadow:
            0 18px 40px -12px rgba(41,73,229,0.85),
            0 0 0 1px rgba(110,168,254,0.45);
        }
        .portfolio-cta-glow {
          position: absolute;
          inset: -14px;
          border-radius: 999px;
          background: radial-gradient(closest-side, rgba(41,73,229,0.55), transparent 70%);
          filter: blur(18px);
          z-index: -1;
          opacity: .8;
          pointer-events: none;
        }
        .portfolio-cta-inner {
          position: relative;
          display: inline-flex;
          align-items: center;
          gap: 10px;
          padding: 12px 22px 12px 18px;
          border-radius: 999px;
          background: linear-gradient(180deg, #0d1326 0%, #070a14 100%);
          color: #fff;
          font-size: 13.5px;
          font-weight: 500;
          letter-spacing: -0.005em;
          overflow: hidden;
        }
        .portfolio-cta-inner::before {
          content: '';
          position: absolute;
          top: 0; bottom: 0;
          left: -60%;
          width: 50%;
          background: linear-gradient(110deg, transparent 0%, rgba(255,255,255,0.12) 50%, transparent 100%);
          transform: skewX(-20deg);
          transition: left .7s ease;
          pointer-events: none;
        }
        .portfolio-cta:hover .portfolio-cta-inner::before {
          left: 130%;
        }
        .portfolio-cta-dot {
          width: 7px; height: 7px; border-radius: 50%;
          background: #6EA8FE;
          box-shadow: 0 0 0 3px rgba(110,168,254,0.18), 0 0 12px rgba(110,168,254,0.9);
          animation: portfolioCtaPulse 1.6s ease-in-out infinite;
        }
        .portfolio-cta-arrow {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 22px; height: 22px;
          border-radius: 50%;
          background: rgba(255,255,255,0.08);
          color: #fff;
          transition: transform .25s ease, background .25s ease;
        }
        .portfolio-cta:hover .portfolio-cta-arrow {
          transform: translateX(3px);
          background: rgba(110,168,254,0.25);
        }
        @keyframes portfolioCtaSpin {
          to { background-position: 200% 0; }
        }
        @keyframes portfolioCtaPulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.55; transform: scale(0.85); }
        }
      `}</style>
    </section>
  );
}

function WorkTile({ p, idx, mediaId, isPlaying, onPlay }) {
  const ref = useReveal();
  const canPlay = !!mediaId;
  return (
    <div
      ref={ref}
      className="lift work-tile reveal"
      onClick={onPlay}
      style={{
        position: 'relative',
        aspectRatio: '9 / 16',
        borderRadius: 18,
        overflow: 'hidden',
        border: '1px solid var(--line)',
        background: '#0a0e18',
        cursor: canPlay && !isPlaying ? 'pointer' : 'default',
        transitionDelay: `${idx * 70}ms`,
      }}
    >
      {isPlaying ? (
        <div
          className={`wistia_embed wistia_async_${mediaId} autoPlay=true videoFoam=true playerColor=2949E5`}
          style={{ width: '100%', height: '100%', position: 'absolute', inset: 0 }}
        >&nbsp;</div>
      ) : (
        <>
          {p.gif ? (
            <img src={p.gif} alt={p.title} loading="lazy"
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          ) : mediaId ? (
            <img
              src={`https://embed-ssl.wistia.com/deliveries/${mediaId}.jpg?image_crop_resized=1280x720`}
              alt={p.title}
              loading="lazy"
              onError={(e) => { e.currentTarget.src = `https://fast.wistia.com/embed/medias/${mediaId}/swatch`; }}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
            />
          ) : null}
          {canPlay && (
            <div style={{
              position: 'absolute', top: '50%', left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 52, height: 52, borderRadius: '50%',
              background: 'rgba(255,255,255,0.95)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#000',
              boxShadow: '0 6px 24px rgba(0,0,0,0.4)',
            }}>
              <svg width={16} height={16} viewBox="0 0 20 20"><path d="M5 3 L17 10 L5 17 Z" fill="currentColor" /></svg>
            </div>
          )}
        </>
      )}
    </div>
  );
}

Object.assign(window, { Work });
