// site-watch-now.jsx — Watch Now section for homepage (streaming week only)
// Inserted in site-home.jsx when festival.streaming.enabled === true

const WN_STRAND_COLORS = {
  Fiction:      { color:"#ff5c70", grad:"linear-gradient(150deg,#611f2f 0%,#2d1019 100%)" },
  Documentary:  { color:"#9b6fc0", grad:"linear-gradient(150deg,#42295f 0%,#241646 100%)" },
  Animation:    { color:"#ffc436", grad:"linear-gradient(150deg,#634b1a 0%,#2d230c 100%)" },
  Experimental: { color:"#5fd0d8", grad:"linear-gradient(150deg,#13444a 0%,#0b2126 100%)" },
};
const WN_STRAND_DESC = {
  Fiction:      "Narratives that reimagine the short form — intimate, precise, and formally adventurous.",
  Documentary:  "Films that find the extraordinary inside ordinary lives and overlooked corners of the world.",
  Animation:    "Hand-drawn, painted, and crafted frame by frame — every second a work of craft.",
  Experimental: "Work that pushes at the boundaries of what film can be.",
};

function wnStrandFallback(sc) {
  return `radial-gradient(120% 85% at 80% 16%,${sc.color}4d 0%,transparent 50%),radial-gradient(90% 70% at 8% 98%,${sc.color}26 0%,transparent 52%),${sc.grad}`;
}


// ── LiveHeroSection — shown when festival.streaming.live.enabled === true ──
function LiveHeroSection({ live }) {
  const items  = live.items || {};
  const item   = items[live.activeItem] || {};
  const isAwards = live.activeItem === 'Awards';
  const sc     = WN_STRAND_COLORS[live.activeItem];
  const color  = sc ? sc.color : '#ffc436';

  const getYtId = url => {
    if (!url) return null;
    const m = url.match(/(?:v=|youtu\.be\/|embed\/)([^&?/]+)/);
    return m ? m[1] : null;
  };
  const ytId = getYtId(item.url);

  return (
    <section className="dark section" style={{ paddingBlock:"clamp(48px,7vh,80px)" }}>
      <div className="wrap">
        <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:20 }}>
          <span style={{ width:8, height:8, borderRadius:"50%", background:"#ef4444",
            display:"inline-block", animation:"wn-live-dot 1.5s ease-in-out infinite" }}></span>
          <span style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".22em",
            textTransform:"uppercase", color:"#ef4444" }}>
            Live Now &middot; {isAwards ? "Paper Bird Awards" : live.activeItem}
          </span>
        </div>
        <h2 style={{ fontFamily:"var(--display)", fontSize:"clamp(28px,6vw,80px)",
          textTransform:"uppercase", letterSpacing:"-.02em", color:"#f0eee9",
          marginBottom:"clamp(24px,3vh,40px)", lineHeight:.9 }}>
          {item.title || (isAwards ? "Paper Bird Awards Ceremony" : live.activeItem + " · Live")}
        </h2>
        {ytId ? (
          <div style={{ width:"100%", aspectRatio:"16/9", background:"#000", overflow:"hidden" }}>
            <iframe
              src={"https://www.youtube.com/embed/" + ytId + "?autoplay=0"}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              style={{ width:"100%", height:"100%", border:"none", display:"block" }} />
          </div>
        ) : (
          <div style={{ width:"100%", aspectRatio:"16/9", background:"#141318",
            display:"flex", alignItems:"center", justifyContent:"center",
            border:"1px solid rgba(240,238,233,.08)" }}>
            <span style={{ fontFamily:"monospace", fontSize:11, letterSpacing:".18em",
              textTransform:"uppercase", color:"rgba(240,238,233,.3)" }}>
              Live stream URL not set in CMS
            </span>
          </div>
        )}
      </div>
      <style>{`@keyframes wn-live-dot{0%,100%{opacity:1;box-shadow:0 0 0 0 rgba(239,68,68,.5)}50%{opacity:.85;box-shadow:0 0 0 7px rgba(239,68,68,0)}}`}</style>
    </section>
  );
}

function WatchNowSection({ navigate }) {
  const d = useSite();
  const f = d.festival || {};
  const str = f.streaming || {};
  const ovr = str.filmOverrides || {};
  const currentYear = String(f.year || new Date().getFullYear());
  const films = (d.films || []).filter(fl =>
    String(fl.year || f.year) === currentYear
  );

  // Active strands that have films — order follows the CMS-configurable strand order
  const wnOrder = window.getStrandOrder(f);
  const activeStrands = wnOrder.filter(s => films.some(fl => fl.strand === s));

  // Single source of truth for the active strand — driven by the tabs below the
  // spotlight (or a swipe on the spotlight itself on touch devices). The banner no
  // longer auto-rotates or carries its own "Browse" control: two sets of strand
  // buttons doing the same job was confusing, and auto-advancing the banner while
  // someone's mid-browse in the reel below was disorienting. One control, one state.
  const [activeIdx, setActiveIdx] = React.useState(0);
  const [reelPrev, setReelPrev] = React.useState(false);
  const [reelNext, setReelNext] = React.useState(true);
  const [spotAnim, setSpotAnim] = React.useState(false);
  const trackRef = React.useRef(null);
  const reelRef  = React.useRef(null);
  const touchX   = React.useRef(null);

  const goToIdx = i => {
    const clamped = ((i % activeStrands.length) + activeStrands.length) % activeStrands.length;
    if (clamped === activeIdx) return;
    setSpotAnim(true);
    setTimeout(() => { setActiveIdx(clamped); setSpotAnim(false); }, 220);
  };

  // Swipe the spotlight banner (mobile) to move to the neighbouring strand
  const onSpotTouchStart = e => { touchX.current = e.touches[0].clientX; };
  const onSpotTouchEnd = e => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (Math.abs(dx) < 40) return;
    goToIdx(activeIdx + (dx < 0 ? 1 : -1));
  };

  const filmStill = fl => ovr[fl.id]?.stillOverride || fl.stillsImages?.[0]?.url || fl.bannerUrl || fl.poster || "";

  // Spotlight + reel both read off the same active strand now
  const featStrand  = activeStrands[activeIdx] || wnOrder[0];
  const sc          = WN_STRAND_COLORS[featStrand] || WN_STRAND_COLORS.Fiction;
  const strandFilms = films.filter(fl => fl.strand === featStrand);
  // Use first available still from any film in the strand — muted, just atmosphere
  const strandBg    = strandFilms.map(filmStill).find(u => u) || "";

  const reelFilms = strandFilms;
  const reelSc    = sc;

  const scrollReel = dir => {
    if (trackRef.current) trackRef.current.scrollBy({ left: dir * 640, behavior:"smooth" });
  };

  // Tabs below select a strand directly (no crossfade needed, they're not the banner)
  const switchStrand = s => {
    const i = activeStrands.indexOf(s);
    if (i >= 0) setActiveIdx(i);
  };

  const updateReelFog = () => {
    const t = trackRef.current; if (!t) return;
    setReelPrev(t.scrollLeft > 4);
    setReelNext(t.scrollLeft < t.scrollWidth - t.clientWidth - 4);
  };

  // Recompute the fade state whenever the strand (and therefore the film list/scrollWidth)
  // changes — reset scroll to start and re-measure both edges.
  React.useEffect(() => {
    if (trackRef.current) trackRef.current.scrollLeft = 0;
    requestAnimationFrame(updateReelFog);
  }, [featStrand]);

  const goFilm = fl => navigate("/film/" + fl.id);

  if (!films.length) return null;

  return (
    <section className="dark section" style={{ paddingBlock:"clamp(56px,8vw,96px) 0" }}>

      {/* ── Heading ── */}
      <div className="wrap">
        <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:"clamp(10px,1.5vw,16px)" }}>
          <span style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".22em", textTransform:"uppercase",
            color:"#ff5c70", display:"flex", alignItems:"center", gap:8 }}>
            <span style={{ width:7, height:7, borderRadius:"50%", background:"#ff5c70",
              boxShadow:"0 0 0 0 rgba(255,92,112,.6)", animation:"wn-pulse 2s infinite", display:"inline-block" }}></span>
            Festival Week · Streaming Now
          </span>
        </div>
        <div style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:"20px 40px",
          marginBottom:"clamp(28px,4vw,44px)", flexWrap:"wrap" }}>
          <h2 className="display" style={{ fontSize:"clamp(36px,5.5vw,68px)" }}>Watch the Festival.</h2>
          <p className="wn-subhead" style={{ color:"var(--muted-d)", fontSize:14, lineHeight:1.65, maxWidth:280, textAlign:"right" }}>
            All {films.length} selected films, free to stream. Pick a strand, press play.
          </p>
        </div>
      </div>

      {/* ── Spotlight (strands) — full-bleed, no border-radius ── */}
      <div className="wn-spotlight" style={{ position:"relative", height:"min(60vh,580px)", minHeight:360,
        overflow:"hidden", opacity: spotAnim ? 0 : 1, transition:"opacity .26s ease" }}
        onTouchStart={onSpotTouchStart} onTouchEnd={onSpotTouchEnd}>

        {/* Background gradient */}
        <div style={{ position:"absolute", inset:0, zIndex:0, transition:"background .6s",
          background: wnStrandFallback(sc) }}></div>

        {/* Neutral still — heavily muted, just atmosphere */}
        {strandBg && (
          <img src={strandBg} alt={featStrand}
            style={{ position:"absolute", inset:0, width:"100%", height:"100%",
              objectFit:"cover", zIndex:1, opacity:.28, filter:"saturate(.35) brightness(.6)" }} />
        )}

        {/* Scrims */}
        <div style={{ position:"absolute", inset:0, zIndex:2, pointerEvents:"none",
          background:"linear-gradient(90deg,rgba(20,19,24,.97) 0%,rgba(20,19,24,.74) 38%,rgba(20,19,24,.28) 70%,transparent 100%),linear-gradient(0deg,rgba(20,19,24,.88) 0%,transparent 48%)" }}></div>

        {/* Content */}
        <div style={{ position:"absolute", zIndex:3, left:0, right:0, bottom:0 }}>
          <div className="wrap" style={{ paddingBottom:"clamp(32px,5vh,52px)" }}>
          <div style={{ fontFamily:"monospace", fontSize:10, letterSpacing:".2em", textTransform:"uppercase",
            marginBottom:16, display:"flex", alignItems:"center", gap:10, color:"rgba(240,238,233,.85)" }}>
            <span style={{ width:8, height:8, borderRadius:"50%", background:sc.color, display:"inline-block" }}></span>
            Sixth Edition {currentYear} &middot; {strandFilms.length} film{strandFilms.length !== 1 ? "s" : ""}
          </div>
          <h2 style={{ fontFamily:"var(--display)", fontSize:"clamp(28px,7vw,96px)", lineHeight:.88,
            letterSpacing:"-.025em", textTransform:"uppercase", marginBottom:20,
            textWrap:"balance", color:"#f0eee9" }}>
            {featStrand}
          </h2>
          <p style={{ fontSize:"clamp(13px,1.15vw,15px)", color:"rgba(240,238,233,.68)", marginBottom:30,
            maxWidth:500, lineHeight:1.7 }}>
            {WN_STRAND_DESC[featStrand]}
          </p>
          <div style={{ display:"flex", justifyContent:"flex-end", gap:8 }}>
            {activeStrands.map((_, i) => (
              <span key={i}
                style={{ width:28, height:3, transition:"background .2s",
                  background: i === activeIdx ? sc.color : "rgba(240,238,233,.22)" }}></span>
            ))}
          </div>
          </div>{/* close wrap */}
        </div>
      </div>

      {/* ── Carousel reel ── */}
      <div ref={reelRef} style={{ padding:"clamp(32px,4vw,48px) 0 clamp(40px,5vw,70px)" }}>

        {/* Reel head */}
        <div className="wrap" style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between",
          gap:"20px 28px", marginBottom:24, flexWrap:"wrap" }}>
          <div>
            <div style={{ fontFamily:"monospace", fontSize:10, letterSpacing:".22em", textTransform:"uppercase",
              color:"var(--muted-d)", marginBottom:14, display:"flex", alignItems:"center", gap:10 }}>
              <span style={{ width:22, height:1, background:"rgba(240,238,233,.28)", display:"inline-block" }}></span>
              Browse all {films.length} films
            </div>
            {/* Strand tabs — no border-radius */}
            <div className="wn-strand-tabs" style={{ display:"flex", gap:7, flexWrap:"wrap" }}>
              {wnOrder.filter(s => films.some(fl => fl.strand === s)).map(s => {
                const active = s === featStrand;
                const nsc = WN_STRAND_COLORS[s];
                const n = films.filter(fl => fl.strand === s).length;
                return (
                  <button key={s} onClick={() => switchStrand(s)}
                    style={{ fontFamily:"monospace", fontSize:11, letterSpacing:".1em",
                      textTransform:"uppercase", padding:"10px 16px", borderRadius:0,
                      border: active ? "1px solid transparent" : "1px solid rgba(240,238,233,.16)",
                      cursor:"pointer", display:"flex", alignItems:"center", gap:8,
                      background: active ? nsc.color : "transparent",
                      color: active ? "#141318" : "rgba(240,238,233,.55)",
                      fontWeight: active ? 700 : 400, transition:".16s" }}>
                    {s}
                    <span style={{ fontSize:9, opacity:.7 }}>{String(n).padStart(2,"0")}</span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Arrows (circular nav controls — intentionally round) */}
          <div style={{ display:"flex", alignItems:"center", gap:12 }}>
            <span style={{ fontFamily:"monospace", fontSize:10, letterSpacing:".14em",
              textTransform:"uppercase", color:"var(--muted-d)" }}>
              {reelFilms.length} films
            </span>
            <div style={{ display:"flex", gap:8 }}>
              {[-1, 1].map(dir => (
                <button key={dir} onClick={() => scrollReel(dir)}
                  style={{ width:44, height:44, borderRadius:"50%", background:"transparent",
                    border:"1px solid rgba(240,238,233,.22)", cursor:"pointer",
                    display:"flex", alignItems:"center", justifyContent:"center",
                    color:"#f0eee9", transition:".16s" }}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="18" height="18">
                    {dir === -1 ? <path d="M15 18l-6-6 6-6"/> : <path d="M9 18l6-6-6-6"/>}
                  </svg>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Track */}
        <div className="wrap">
          <div style={{ position:"relative" }}>
          <div ref={trackRef} onScroll={updateReelFog}
            style={{ display:"flex", gap:18, overflowX:"auto",
              padding:"6px 0 8px",
              scrollSnapType:"x proximity", scrollBehavior:"smooth",
              msOverflowStyle:"none", scrollbarWidth:"none" }}>
          {reelFilms.map(fl => {
            const nsc   = WN_STRAND_COLORS[fl.strand] || reelSc;
            const still = filmStill(fl);
            return (
              <div key={fl.id} onClick={() => goFilm(fl)}
                style={{ flex:"none", width:"clamp(240px,22vw,306px)", cursor:"pointer",
                  scrollSnapAlign:"start", transition:"transform .26s cubic-bezier(.2,.7,.3,1)" }}
                onMouseEnter={e => e.currentTarget.style.transform = "translateY(-6px)"}
                onMouseLeave={e => e.currentTarget.style.transform = "translateY(0)"}>

                {/* Thumb — no border-radius */}
                <div style={{ position:"relative", width:"100%", aspectRatio:"16/9",
                  overflow:"hidden", background:"#141318" }}>
                  <div style={{ position:"absolute", inset:0, zIndex:0,
                    background: wnStrandFallback(nsc) }}></div>
                  {still && (
                    <img src={still} alt={fl.title}
                      style={{ position:"absolute", inset:0, width:"100%", height:"100%",
                        objectFit:"cover", zIndex:1 }} />
                  )}
                  {/* Bottom scrim */}
                  <div style={{ position:"absolute", inset:0, zIndex:2, pointerEvents:"none",
                    background:"linear-gradient(0deg,rgba(18,17,22,.92) 0%,rgba(18,17,22,.1) 52%,transparent 72%)" }}></div>
                  {/* Strand colour tick */}
                  <div style={{ position:"absolute", top:0, left:0, right:0, height:3, zIndex:3,
                    background:nsc.color }}></div>
                  {/* Play overlay */}
                  <div className="wn-play-hover"
                    style={{ position:"absolute", inset:0, zIndex:3,
                      display:"flex", alignItems:"center", justifyContent:"center",
                      opacity:0, background:"rgba(18,17,22,.34)", transition:".2s" }}>
                    <span style={{ width:54, height:54,
                      background:"rgba(255,255,255,.14)", border:"1.5px solid rgba(255,255,255,.85)",
                      backdropFilter:"blur(6px)", display:"flex", alignItems:"center", justifyContent:"center" }}>
                      <svg viewBox="0 0 24 24" fill="#fff" width="20" height="20" style={{ marginLeft:3 }}>
                        <path d="M8 5v14l11-7z"/>
                      </svg>
                    </span>
                  </div>
                  {/* Title */}
                  <div style={{ position:"absolute", left:15, right:15, bottom:13, zIndex:3,
                    fontFamily:"var(--display)", fontSize:18, lineHeight:.96,
                    textTransform:"uppercase", letterSpacing:"-.015em",
                    color:"#f0eee9", textWrap:"balance" }}>{fl.title}</div>
                </div>

                {/* Caption */}
                <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between",
                  gap:10, marginTop:10, padding:"0 2px" }}>
                  <span style={{ fontSize:12.5, color:"rgba(240,238,233,.62)", overflow:"hidden",
                    textOverflow:"ellipsis", whiteSpace:"nowrap" }}>dir. {fl.directors}</span>
                  {fl.runtime && (
                    <span style={{ fontFamily:"monospace", fontSize:10,
                      color:"rgba(240,238,233,.5)", whiteSpace:"nowrap" }}>{fl.runtime}′</span>
                  )}
                </div>
              </div>
            );
          })}
          </div>
          {/* Edge fades — separate overlay layers so opacity can transition smoothly;
              CSS mask-image swaps don't animate reliably across browsers. */}
          <div style={{ position:"absolute", top:0, bottom:8, left:0, width:90, pointerEvents:"none", zIndex:5,
            background:"linear-gradient(to right, var(--ink), transparent)",
            opacity: reelPrev ? 1 : 0, transition:"opacity .35s ease", willChange:"opacity", transform:"translateZ(0)" }} />
          <div style={{ position:"absolute", top:0, bottom:8, right:0, width:90, pointerEvents:"none", zIndex:5,
            background:"linear-gradient(to left, var(--ink), transparent)",
            opacity: reelNext ? 1 : 0, transition:"opacity .35s ease", willChange:"opacity", transform:"translateZ(0)" }} />
          </div>
        </div>{/* close wrap */}
      </div>

      <style>{`
        @keyframes wn-pulse {
          0%  { box-shadow: 0 0 0 0 rgba(255,92,112,.55); }
          70% { box-shadow: 0 0 0 9px rgba(255,92,112,0); }
          100%{ box-shadow: 0 0 0 0 rgba(255,92,112,0); }
        }
        .wn-play-hover { opacity:0 !important; }
        div:hover > div > .wn-play-hover { opacity:1 !important; }
      `}</style>
    </section>
  );
}

Object.assign(window, { WatchNowSection });
