// site-awards.jsx — Awards Night page. Visible in nav only when awardsPage.live === true.

const AW_COLORS = { Fiction: "var(--pink)", Documentary: "var(--purple)", Animation: "var(--yellow)", Experimental: "var(--cyan)", Audience: "#F0EEE9" };
const AW_TEXT   = { Fiction: "#fff", Documentary: "#fff", Animation: "#16151a", Experimental: "#16151a", Audience: "#16151a" };
const AW_TROPHY = { Purple: "#784c95", Yellow: "#ffc823", Cyan: "#65c8d0", Pink: "#ff5c70", White: "#f0eee9", Red: "#d6394c", Green: "#3f7d52" };
const AW_LIGHT  = new Set(["Yellow", "Cyan", "White"]);

function AwardsPage({ navigate }) {
  const d = useSite();
  const f = d.festival;
  const ap = f.awardsPage || {};
  const awards = d.awards || [];
  const films = usePublishedFilms();
  const people = d.people || [];

  const audienceWinner = films.find(fi => fi.prize === "Audience");

  // Order jury winners by strand order from the schedule
  const _schedStrands = [];
  const _seen = new Set();
  for (const day of (d.schedule || [])) {
    if (day.strand && day.strand !== "Off-night" && day.strand !== "Awards" && !_seen.has(day.strand)) {
      _schedStrands.push(day.strand);
      _seen.add(day.strand);
    }
  }
  // Fall back to default order if schedule is empty
  const _strandOrder = _schedStrands.length ? _schedStrands : ["Documentary","Animation","Experimental","Fiction"];
  const juryWinners = _strandOrder
    .map(strand => films.find(fi => fi.prize === "Jury" && fi.strand === strand))
    .filter(Boolean);
  const allWinners = audienceWinner ? [...juryWinners, audienceWinner] : juryWinners;

  const gallery     = ap.gallery     || [];
  const winnerDescs = ap.winnerDescs || {};
  const juryPeople  = people.filter(p => p.group === "jury");

  return (
    <Page k="awards">

      {/* ── HERO — full-bleed image ── */}
      <section style={{
        position: "relative", overflow: "hidden",
        display: "flex", flexDirection: "column",
        background: "var(--ink)",
      }}>
        {/* String lights image */}
        <div style={{ position: "absolute", inset: 0, zIndex: 0 }}>
          <img
            src="uploads/pasted-1780964306159-0.png"
            alt=""
            style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 40%", display: "block" }}
          />
        </div>
        {/* Gradient: image visible at top → fades to ink at bottom */}
        <div style={{
          position: "absolute", inset: 0, zIndex: 1, pointerEvents: "none",
          background: "linear-gradient(to bottom, rgba(22,21,26,0.05) 0%, rgba(22,21,26,0.02) 15%, rgba(22,21,26,0.5) 48%, #16151a 70%)",
        }} />
        {/* Pixel texture overlay */}
        <div style={{
          position: "absolute", inset: 0, zIndex: 2, pointerEvents: "none",
          backgroundImage: "url('uploads/pixel-effect.png')",
          backgroundRepeat: "repeat", backgroundSize: "51px 51px",
          opacity: 0.85,
        }} />
        {/* Content — anchored to the bottom */}
        <div className="wrap" style={{
          position: "relative", zIndex: 3,
          paddingTop: "clamp(54px, 8vw, 110px)",
          paddingBottom: "clamp(40px, 5vw, 64px)",
        }}>
          <div style={{
            display: "inline-block", fontSize: 11, letterSpacing: "0.16em",
            fontWeight: 700, textTransform: "uppercase",
            color: "var(--yellow)", marginBottom: 20,
          }}>
            {ap.eveningLabel || ("Paper Bird Awards \u00b7 " + f.edition + " Edition")}
          </div>
          <h1 className="display" style={{
            fontSize: "clamp(52px,9vw,130px)", color: "var(--paper)",
            margin: "0", lineHeight: 0.88,
          }}>
            {ap.heading || "Awards Night."}
          </h1>
          {(ap.pageDesc || f.awardsDesc) && (
            <p style={{ maxWidth: 640, marginTop: "clamp(20px,2vw,32px)", marginBottom: 0, fontSize: "clamp(15px,1.4vw,18px)", lineHeight: 1.8, color: "rgba(240,238,233,0.72)" }}>
              {ap.pageDesc || f.awardsDesc}
            </p>
          )}
          {(ap.eveningDate || ap.eveningTime || ap.venueName) && (
            <div style={{
              display: "flex", gap: "clamp(28px,5vw,64px)", marginTop: 40,
              flexWrap: "wrap", borderTop: "1px solid rgba(240,238,233,0.15)", paddingTop: 28,
            }}>
              {ap.eveningDate && (
                <div>
                  <div style={{ fontSize: 9, letterSpacing: "0.18em", fontWeight: 700, textTransform: "uppercase", color: "var(--yellow)", marginBottom: 6 }}>Date</div>
                  <div className="display" style={{ fontSize: "clamp(18px,2vw,28px)", color: "var(--paper)" }}>{ap.eveningDate}</div>
                </div>
              )}
              {ap.eveningTime && (
                <div>
                  <div style={{ fontSize: 9, letterSpacing: "0.18em", fontWeight: 700, textTransform: "uppercase", color: "var(--yellow)", marginBottom: 6 }}>Time</div>
                  <div className="display" style={{ fontSize: "clamp(18px,2vw,28px)", color: "var(--paper)" }}>{ap.eveningTime}</div>
                </div>
              )}
              {ap.venueName && (
                <div>
                  <div style={{ fontSize: 9, letterSpacing: "0.18em", fontWeight: 700, textTransform: "uppercase", color: "var(--yellow)", marginBottom: 6 }}>Venue</div>
                  <div className="display" style={{ fontSize: "clamp(18px,2vw,28px)", color: "var(--paper)" }}>{ap.venueName}</div>
                </div>
              )}
            </div>
          )}
        </div>
      </section>

      {/* ── EVENING DESC — yellow splash ── */}
      {ap.eveningDesc && (
        <section style={{ background: "var(--yellow)", padding: "clamp(40px,6vw,80px) 0" }}>
          <div className="wrap" style={{ maxWidth: 940 }}>
            <p className="display" style={{ fontSize: "clamp(22px,3.2vw,44px)", color: "var(--ink)", margin: 0, lineHeight: 1.15, fontWeight: 400 }}>
              {ap.eveningDesc}
            </p>
          </div>
        </section>
      )}

      {/* ── WINNERS CAROUSEL ── */}
      {allWinners.length > 0 && (
        <WinnersCarousel winners={allWinners} winnerDescs={winnerDescs} navigate={navigate} />
      )}

      {/* ── GALLERY ── */}
      {gallery.filter(im => im.url).length > 0 && (
        <PhotoCarousel images={gallery} />
      )}

      {/* ── VIDEO ── */}
      {(() => {
        const vids = (ap.videos || []).filter(v => v.youTubeId);
        const legacy = ap.videoYouTube ? [{ id: "legacy", youTubeId: ap.videoYouTube, label: ap.videoLabel || "Awards Evening · Highlights", desc: "" }] : [];
        const allVids = vids.length ? vids : legacy;
        return allVids.length > 0 ? <AwardsVideoCarousel videos={allVids} ap={ap} /> : null;
      })()}

            {/* ── VENUE ── */}
      {(ap.venueName || ap.venueDesc) && (
        <section className="section" style={{ background: "var(--paper)" }}>
          <div className="wrap">
            <Kicker n="§" color="var(--coral)">The Venue</Kicker>
            <div style={{ display: "grid", gridTemplateColumns: ap.venuePhoto ? "1fr 1fr" : "1fr", gap: "clamp(28px,4vw,64px)", alignItems: "start" }}>
              <div>
                <h2 className="display" style={{ fontSize: "clamp(32px,4.5vw,68px)", margin: "0 0 clamp(16px,2vw,28px)" }}>
                  {ap.venueName || "The venue."}
                </h2>
                {ap.venueAddress && (
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 20 }}>
                    <SIcon name="pin" style={{ width: 16, height: 16, color: "var(--muted)", flexShrink: 0 }} />
                    <span style={{ fontSize: 14, color: "var(--muted)" }}>{ap.venueAddress}</span>
                  </div>
                )}
                {ap.venueDesc && (
                  <p style={{ fontSize: "clamp(15px,1.4vw,17px)", lineHeight: 1.75, color: "var(--muted)", margin: 0 }}>
                    {ap.venueDesc}
                  </p>
                )}
              </div>
              {ap.venuePhoto && (
                <div style={{ overflow: "hidden", aspectRatio: "4/3", cursor: "pointer" }}
                  onClick={() => openLightbox([{ url: ap.venuePhoto, caption: ap.venueName }])}>
                  <img src={ap.venuePhoto} alt={ap.venueName || ""} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
                </div>
              )}
            </div>
          </div>
        </section>
      )}

    </Page>
  );
}

function PhotoCarousel({ images }) {
  const items = (images || []).filter(im => im.url);
  const total = items.length;

  const [cur, setCur]               = React.useState(0);
  const [deltaX, setDeltaX]         = React.useState(0);
  const [sliding, setSliding]       = React.useState(false);
  const [slideDir, setSlideDir]             = React.useState(null);
  const [incomingCenter, setIncomingCenter] = React.useState(null);
  const [exitingCenter,  setExitingCenter]  = React.useState(null);
  const [mobileMode, setMobileMode] = React.useState(() => window.innerWidth < 640);
  const trackRef    = React.useRef(null);
  const pendingRef  = React.useRef(null);
  const touchStartX = React.useRef(null);

  const onTouchStart = (e) => { touchStartX.current = e.touches[0].clientX; };
  const onTouchEnd   = (e) => {
    if (touchStartX.current === null) return;
    const delta = e.changedTouches[0].clientX - touchStartX.current;
    touchStartX.current = null;
    if (Math.abs(delta) < 40) return;
    navigate(delta < 0 ? 'next' : 'prev');
  };

  React.useEffect(() => {
    const check = () => setMobileMode(window.innerWidth < 640);
    window.addEventListener('resize', check, { passive: true });
    return () => window.removeEventListener('resize', check);
  }, []);

  if (!total) return null;

  const lbItems = items.map(im => ({ url: im.url, caption: im.caption }));
  const idxAt   = n => ((n % total) + total) % total;

  // Desktop: 3 cards (33.33% each). Mobile: 80% center with 10% peeks.
  const CARD_W = mobileMode ? 80 : 100 / 3;
  // BASE_X centers the middle slot (index 2 of 5) in the viewport
  const BASE_X = 50 - 2.5 * CARD_W;

  const navigate = (dir) => {
    if (sliding || total < 2) return;
    setSliding(true);
    setSlideDir(dir);
    const nextIdx = idxAt(cur + (dir === 'next' ? 1 : -1));
    setIncomingCenter(nextIdx);
    setExitingCenter(cur);
    pendingRef.current = nextIdx;
    setDeltaX(dir === 'next' ? -CARD_W : CARD_W);
  };

  const onTransitionEnd = () => {
    const track = trackRef.current;
    if (!track || pendingRef.current === null) return;
    track.style.transition = 'none';
    setCur(pendingRef.current);
    setDeltaX(0);
    setSliding(false);
    setSlideDir(null);
    setIncomingCenter(null);
    setExitingCenter(null);
    pendingRef.current = null;
    requestAnimationFrame(() => requestAnimationFrame(() => {
      if (trackRef.current) trackRef.current.style.transition = '';
    }));
  };

  const slots = [-2, -1, 0, 1, 2].map(offset => ({
    idx: idxAt(cur + offset), offset,
    isCenter: offset === 0,
    isSide:   Math.abs(offset) === 1,
  }));

  const cardStyle = (slot) => {
    let op;
    if (slot.idx === exitingCenter && sliding)          { op = 0.5; }
    else if (slot.idx === incomingCenter || slot.isCenter) { op = 1; }
    else if (Math.abs(slot.offset) === 2) {
      const entering = sliding && (
        (slideDir === 'next' && slot.offset === 2) ||
        (slideDir === 'prev' && slot.offset === -2)
      );
      op = entering ? 0.5 : 0;
    } else { op = 0.5; }
    return {
      flexShrink: 0, width: CARD_W + '%', position: 'relative',
      padding: '0 clamp(4px,0.6vw,8px)',
      opacity: op, transition: 'opacity 0.55s cubic-bezier(0.16,1,0.3,1)',
    };
  };

  const arrowBase = {
    position: 'absolute', top: '50%', transform: 'translateY(-50%)',
    zIndex: 10, border: 'none', outline: 'none',
    background: 'var(--accent)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', transition: 'background 0.15s',
    boxShadow: '0 2px 12px rgba(0,0,0,0.3)',
  };

  // Arrow positions relative to outer wrapper (outside overflow:hidden)
  const prevX = mobileMode ? -12 : (CARD_W + '%');
  const nextX = mobileMode ? -12 : ((CARD_W * 2) + '%');
  const arwSz = mobileMode ? 36 : 48;
  const icnSz = mobileMode ? 14 : 18;

  return (
    <section style={{ background: 'var(--paper)', padding: 'clamp(48px,6vw,80px) 0' }}>
      <div className="wrap">
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 'clamp(20px,3vw,36px)' }}>
          <div>
            <Kicker n="§">The Evening</Kicker>
            <h2 className="display" style={{ fontSize: 'clamp(32px,4.5vw,64px)', color: 'var(--ink)', margin: 0 }}>In pictures.</h2>
          </div>
          {total > 1 && (
            <span style={{ fontSize: 10, fontFamily: 'var(--mono)', color: 'var(--muted)', letterSpacing: '0.1em', paddingBottom: 6 }}>
              {String(cur + 1).padStart(2,'0')} / {String(total).padStart(2,'0')}
            </span>
          )}
        </div>

        {/* Outer wrapper: position:relative for arrows, NO overflow:hidden */}
        <div style={{ position: 'relative' }} onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
          {/* Track clip: overflow:hidden only on this inner div */}
          <div style={{ overflow: 'hidden' }}>
            <div ref={trackRef} onTransitionEnd={onTransitionEnd}
              style={{
                display: 'flex',
                transform: `translateX(${BASE_X + deltaX}%)`,
                transition: sliding ? 'transform 0.55s cubic-bezier(0.16,1,0.3,1)' : 'none',
                willChange: 'transform',
              }}>
              {slots.map((slot) => (
                <div key={slot.offset} style={cardStyle(slot)}>
                  <div
                    onClick={() => slot.isCenter ? openLightbox(lbItems, slot.idx) : navigate(slot.offset > 0 ? 'next' : 'prev')}
                    style={{
                      aspectRatio: '3/4', overflow: 'hidden',
                      cursor: slot.isCenter ? 'zoom-in' : 'pointer',
                      transform: (slot.idx === exitingCenter && sliding) ? 'scale(0.92)' : (slot.idx === incomingCenter || slot.isCenter) ? 'scale(1)' : 'scale(0.92)',
                      transition: 'transform 0.55s cubic-bezier(0.16,1,0.3,1)',
                    }}>
                    <img src={items[slot.idx].url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, transparent 40%, rgba(22,21,26,0.88) 100%)', pointerEvents: 'none' }} />
                    {slot.isCenter && items[slot.idx].caption && (
                      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '20px 18px 16px', fontSize: 12, color: 'rgba(240,238,233,0.85)', fontFamily: 'var(--mono)', letterSpacing: '0.06em', pointerEvents: 'none' }}>
                        {items[slot.idx].caption}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Arrows — outside overflow:hidden, never clipped */}
          {total > 1 && (
            <>
              <button onClick={() => navigate('prev')}
                onMouseEnter={e => { e.currentTarget.style.background='#fff'; e.currentTarget.querySelector('svg').style.stroke='#16151a'; }}
                onMouseLeave={e => { e.currentTarget.style.background='var(--accent)'; e.currentTarget.querySelector('svg').style.stroke='#fff'; }}
                style={{
                  ...arrowBase, width: arwSz, height: arwSz, borderRadius: 0,
                  ...(mobileMode ? { left: prevX } : { left: prevX, transform: 'translate(-50%, -50%)' }),
                }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: icnSz, height: icnSz }}><path d="M15 18l-6-6 6-6"/></svg>
              </button>
              <button onClick={() => navigate('next')}
                onMouseEnter={e => { e.currentTarget.style.background='#fff'; e.currentTarget.querySelector('svg').style.stroke='#16151a'; }}
                onMouseLeave={e => { e.currentTarget.style.background='var(--accent)'; e.currentTarget.querySelector('svg').style.stroke='#fff'; }}
                style={{
                  ...arrowBase, width: arwSz, height: arwSz, borderRadius: 0,
                  ...(mobileMode ? { right: nextX } : { left: nextX, transform: 'translate(-50%, -50%)' }),
                }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: icnSz, height: icnSz }}><path d="M9 18l6-6-6-6"/></svg>
              </button>
            </>
          )}
        </div>

        {total > 1 && (
          <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 20 }}>
            {items.map((_, i) => (
              <button key={i} onClick={() => { const d = i > cur ? 'next' : 'prev'; navigate(d); }} style={{
                width: i === cur ? 20 : 5, height: 5, border: 'none', cursor: 'pointer', padding: 0,
                background: i === cur ? 'var(--ink)' : 'rgba(22,21,26,0.18)', transition: 'all 0.22s',
              }} />
            ))}
          </div>
        )}
      </div>
    </section>
  );
}


function DirectorCarousel({ bios }) {
  const [idx2, setIdx2] = React.useState(0);
  if (!bios || !bios.length) return null;
  const dir  = bios[idx2];
  const prev = () => setIdx2(i => (i - 1 + bios.length) % bios.length);
  const next = () => setIdx2(i => (i + 1) % bios.length);

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
        <div style={{ fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(240,238,233,0.35)", fontFamily: "var(--mono)" }}>
          {bios.length > 1 ? "Directors" : "Director"}
        </div>
        {bios.length > 1 && (
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 9, fontFamily: "var(--mono)", color: "rgba(240,238,233,0.30)", letterSpacing: "0.1em" }}>
              {String(idx2 + 1).padStart(2,"0")} / {String(bios.length).padStart(2,"0")}
            </span>
            <button onClick={prev} style={{ width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--accent)", border: "none", cursor: "pointer", color: "#fff", transition: "background 0.15s, color 0.15s" }}
              onMouseEnter={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.querySelector("svg").style.stroke = "#16151a"; }}
              onMouseLeave={e => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.querySelector("svg").style.stroke = "#fff"; }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 12, height: 12 }}><path d="M15 18l-6-6 6-6"/></svg>
            </button>
            <button onClick={next} style={{ width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--accent)", border: "none", cursor: "pointer", color: "#fff", transition: "background 0.15s, color 0.15s" }}
              onMouseEnter={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.querySelector("svg").style.stroke = "#16151a"; }}
              onMouseLeave={e => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.querySelector("svg").style.stroke = "#fff"; }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 12, height: 12 }}><path d="M9 18l6-6-6-6"/></svg>
            </button>
          </div>
        )}
      </div>
      <div className="display" style={{ fontSize: "clamp(20px,2.5vw,38px)", color: "var(--paper)", lineHeight: 1.0, letterSpacing: "-0.01em", marginBottom: 12 }}>
        {dir.name}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "88px 1fr", gap: 16, alignItems: "start" }}>
        <div style={{ width: 88, height: 117, overflow: "hidden", flexShrink: 0, background: "var(--ink-2)" }}>
          <img
            src={dir.photo || "uploads/pasted-1780971499388-0.png"}
            alt={dir.name}
            style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 20%", display: "block" }}
          />
        </div>
        {dir.bio && (
          <p style={{ fontSize: 12, lineHeight: 1.75, color: "rgba(240,238,233,0.50)", margin: 0 }}>{dir.bio}</p>
        )}
      </div>
    </div>
  );
}


function WinnersCarousel({ winners, winnerDescs, navigate }) {
  const [active, setActive] = React.useState(0);

    if (!winners || !winners.length) return null;

  const film       = winners[Math.min(active, winners.length - 1)];
  const strandKey  = film.prize === "Audience" ? "Audience" : film.strand;
  const accentHex  = { Fiction: "var(--pink)", Documentary: "var(--purple)", Animation: "var(--yellow)", Experimental: "var(--cyan)", Audience: "var(--paper)" }[strandKey] || "var(--yellow)";
  const juryDesc   = winnerDescs[strandKey] || "";
  const dirBios    = film.directorBios || [];
  // Build carousel entries from the directors string, merging bio data where available
  const _dirNames  = (film.directors || "").split(",").map(n => n.trim()).filter(Boolean);
  const _bioMap    = {};
  dirBios.forEach(b => { _bioMap[b.name] = b; });
  const dirEntries = _dirNames.length > 1
    ? _dirNames.map(name => _bioMap[name] || { name, bio: "", photo: "" })
    : dirBios;
  const credits    = film.credits || {};
  const creditRows = Object.entries(credits).filter(([, v]) => v);

  return (
    <section style={{ background: "var(--ink)" }}>

      {/* heading */}
      <div className="wrap" style={{ paddingTop: "clamp(48px,6vw,80px)", paddingBottom: "clamp(24px,3vw,40px)" }}>
        <Kicker n="§ 01">This Year’s Winners</Kicker>
        <h2 className="display" style={{ fontSize: "clamp(36px,5vw,72px)", color: "var(--paper)", margin: "0" }}>
          The Paper Bird goes to.
        </h2>
      </div>

      {/* tab bar */}
      <div style={{ borderTop: "1px solid var(--line-d)", overflowX: "auto" }}>
        <div style={{ display: "flex", minWidth: "max-content", width: "100%" }}>
          {winners.map((w, i) => {
            const sk  = w.prize === "Audience" ? "Audience" : w.strand;
            const on  = i === active;
            const tbg = on ? ({ Fiction: "var(--pink)", Documentary: "var(--purple)", Animation: "var(--yellow)", Experimental: "var(--cyan)", Audience: "var(--paper)" }[sk] || "var(--yellow)") : "transparent";
            const tfg = on ? ({ Fiction: "#fff", Documentary: "#fff", Animation: "#16151a", Experimental: "#16151a", Audience: "#16151a" }[sk] || "#fff") : "rgba(240,238,233,0.42)";
            const tsub = on ? (tfg === "#16151a" ? "rgba(22,21,26,0.55)" : "rgba(240,238,233,0.65)") : "rgba(240,238,233,0.25)";
            return (
              <button key={w.id || i} onClick={() => setActive(i)} style={{
                flex: "1 1 0", minWidth: 140, background: tbg, border: "none",
                borderRight: i < winners.length - 1 ? "1px solid var(--line-d)" : "none",
                borderBottom: on ? "none" : "1px solid var(--line-d)",
                cursor: "pointer", padding: "20px clamp(16px,2vw,28px)",
                display: "flex", flexDirection: "column", gap: 5, alignItems: "flex-start",
                transition: "background 0.18s",
              }}>
                <span style={{ fontSize: 10, letterSpacing: "0.14em", fontFamily: "var(--mono)", color: tsub, textTransform: "uppercase" }}>{String(i + 1).padStart(2, "0")}</span>
                <span style={{ fontSize: "clamp(12px,1.4vw,16px)", fontWeight: 800, fontFamily: "var(--display)", letterSpacing: "0.03em", textTransform: "uppercase", color: tfg, lineHeight: 1 }}>{sk}</span>
                <span style={{ fontSize: 9, fontFamily: "var(--mono)", color: tsub, textTransform: "uppercase", letterSpacing: "0.08em" }}>Paper Bird — {sk}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* film panel */}
      <div className="wrap" style={{ paddingBottom: "clamp(56px,7vw,96px)" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "minmax(160px,3fr) 5fr",
          gap: "clamp(28px,4vw,64px)", alignItems: "center",
          paddingTop: "clamp(32px,4vw,56px)",
        }} className="winners-grid">

          {/* poster 2:3 */}
          <div className="winners-poster" style={{ position: "relative" }}>
            <img
              src={film.poster || "uploads/pasted-1780971346302-0.png"}
              alt={film.title}
              style={{ width: "100%", display: "block", aspectRatio: "2/3", objectFit: "cover" }}
            />
            <div style={{ position: "absolute", inset: "40% 0 0 0", background: "linear-gradient(to top, rgba(22,21,26,0.72) 0%, transparent 100%)", pointerEvents: "none" }} />
            <img
              src={film.prize === "Special Mention" ? "uploads/laurel special mention.svg" : "uploads/laurel winner.svg"}
              alt={film.prize}
              style={{ position: "absolute", bottom: "5%", right: "4%", width: "33%", filter: "brightness(0) invert(1)", opacity: 0.92, pointerEvents: "none" }}
            />
          </div>

          {/* credits panel */}
          <div>

            {/* award kicker */}
            <div style={{ fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", fontFamily: "var(--mono)", color: accentHex, marginBottom: 12 }}>
              Paper Bird · {strandKey === "Audience" ? "Audience Award" : strandKey + " · Jury Award"}
            </div>

            {/* film title */}
            <h3 className="display" style={{ fontSize: "clamp(28px,4.5vw,64px)", color: "var(--paper)", margin: "0 0 10px", lineHeight: 0.9, letterSpacing: "-0.01em" }}>{film.title}</h3>

            {/* meta strip */}
            <div style={{ display: "flex", gap: 16, flexWrap: "wrap", marginTop: 10, paddingBottom: 14, borderBottom: "1px solid var(--line-d)" }}>
              {film.country && <span style={{ fontSize: 10, color: "rgba(240,238,233,0.38)", fontFamily: "var(--mono)", textTransform: "uppercase", letterSpacing: "0.12em" }}>{film.country}</span>}
              {film.runtime && <span style={{ fontSize: 10, color: "rgba(240,238,233,0.38)", fontFamily: "var(--mono)" }}>{film.runtime}'{String(film.runtimeSecs || "0").padStart(2,"0")}"</span>}
              {film.school  && <span style={{ fontSize: 10, color: "rgba(240,238,233,0.38)", fontFamily: "var(--mono)", textTransform: "uppercase", letterSpacing: "0.12em" }}>{film.school}</span>}
            </div>

            {/* jury statement OR synopsis */}
            {(juryDesc || film.synopsis) && (
              <div style={{ padding: "16px 0", borderBottom: "1px solid var(--line-d)" }}>
                <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(240,238,233,0.38)", fontFamily: "var(--mono)", marginBottom: 8 }}>Jury Statement</div>
                <p style={{ fontSize: "clamp(13px,1.2vw,15px)", lineHeight: 1.9, color: "rgba(240,238,233,0.65)", margin: 0, fontStyle: juryDesc ? "italic" : "normal" }}>
                  {juryDesc ? ("“" + juryDesc + "”") : film.synopsis}
                </p>
              </div>
            )}

            {/* credits grid — film-credits style */}
            {creditRows.length > 0 && (
              <div style={{ borderBottom: "1px solid var(--line-d)", padding: "16px 0" }}>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 0 }}>
                  {creditRows.map(([role, name], i) => (
                    <div key={role} style={{
                      padding: "10px 16px 10px 0",
                      borderRight: (i + 1) % 3 !== 0 ? "1px solid var(--line-d)" : "none",
                      paddingRight: (i + 1) % 3 !== 0 ? 16 : 0,
                      paddingLeft: i % 3 !== 0 ? 16 : 0,
                    }}>
                      <div style={{ fontSize: 8, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(240,238,233,0.28)", fontFamily: "var(--mono)", marginBottom: 4 }}>{role}</div>
                      <div style={{ fontSize: "clamp(12px,1.1vw,14px)", color: "var(--paper)", fontWeight: 700, fontFamily: "var(--display)", letterSpacing: "0.02em", lineHeight: 1.2 }}>{name}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* director carousel */}
            {dirEntries.length > 0 && (
              <div style={{ padding: "16px 0", borderBottom: "1px solid var(--line-d)" }}>
                <DirectorCarousel bios={dirEntries} />
              </div>
            )}

            {/* view film */}
            <button onClick={() => navigate("/film/" + film.id)}
              style={{ marginTop: 16, background: "none", border: "1px solid var(--line-d)", color: "rgba(240,238,233,0.50)", fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", padding: "12px 22px", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8, transition: "all 0.15s" }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--paper)"; e.currentTarget.style.color = "var(--paper)"; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line-d)"; e.currentTarget.style.color = "rgba(240,238,233,0.50)"; }}>
              View film <SIcon name="arrowR" style={{ width: 12, height: 12 }} />
            </button>

          </div>
        </div>
      </div>
    </section>
  );
}


function AwardsVideoCarousel({ videos, ap }) {
  const [active, setActive]     = React.useState(0);
  const [shown, setShown]       = React.useState(0);
  const [videoKey, setVideoKey] = React.useState(0);
  const [exitStyle, setExitStyle] = React.useState(null);
  const [enterAnim, setEnterAnim] = React.useState(null);
  const [textVisible, setTextVisible] = React.useState(true);
  const inFlight = React.useRef(false);

  const navigate = (dir) => {
    if (inFlight.current) return;
    inFlight.current = true;
    const next = (active + (dir === 'next' ? 1 : -1) + videos.length) % videos.length;
    const exitTo    = dir === 'next' ? 'left' : 'right';
    const enterFrom = dir === 'next' ? 'from-right' : 'from-left';
    setTextVisible(false);
    setExitStyle(exitTo);
    setTimeout(() => {
      setActive(next);
      setShown(next);
      setVideoKey(k => k + 1);
      setExitStyle(null);
      setEnterAnim(enterFrom);
      setTimeout(() => setTextVisible(true), 80);
      setTimeout(() => { setEnterAnim(null); inFlight.current = false; }, 550);
    }, 390);
  };

  const vid = videos[shown];
  const hasMultiple = videos.length > 1;
  const vidTouchX = React.useRef(null);
  const onVidTouchStart = (e) => { vidTouchX.current = e.touches[0].clientX; };
  const onVidTouchEnd   = (e) => {
    if (vidTouchX.current === null) return;
    const delta = e.changedTouches[0].clientX - vidTouchX.current;
    vidTouchX.current = null;
    if (Math.abs(delta) < 40 || !hasMultiple) return;
    navigate(delta < 0 ? 'next' : 'prev');
  };

  const videoWrapStyle = exitStyle
    ? { transform: exitStyle === 'right' ? "translateX(55%)" : "translateX(-55%)", opacity: 0, transition: "transform 0.39s ease, opacity 0.33s ease" }
    : { transform: "translateX(0)", opacity: 1 };

  const enterAnimStyle = enterAnim
    ? { animation: enterAnim === 'from-left' ? "awards-from-left 0.47s ease forwards" : "awards-from-right 0.47s ease forwards" }
    : {};

  const arrowBtn = {
    width: 48, height: 48, borderRadius: 0,
    background: "var(--accent)",
    border: "none", outline: "none",
    display: "flex", alignItems: "center", justifyContent: "center",
    cursor: "pointer", overflow: "hidden",
    position: "absolute", top: "50%", transform: "translateY(-50%)",
    zIndex: 4, transition: "background 0.15s",
  };

  return (
    <section className="section dark tight">
      <style>{`
        @keyframes awards-from-left  { from { transform: translateX(-55%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        @keyframes awards-from-right { from { transform: translateX(55%);  opacity: 0; } to { transform: translateX(0); opacity: 1; } }
      `}</style>
      <div className="wrap">
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: "clamp(57px,5vw,81px)", alignItems: "center" }} className="awards-video-grid">

          {/* Video + arrows */}
          <div className="awards-vid-wrap" style={{ position: "relative" }} onTouchStart={onVidTouchStart} onTouchEnd={onVidTouchEnd}>
            <div style={{ overflow: "hidden", background: "var(--ink)" }}>
              <div key={videoKey} style={{ position: "relative", paddingBottom: "56.25%", ...videoWrapStyle, ...enterAnimStyle }}>
                <YouTubeThumb id={vid.youTubeId} title={vid.title || vid.label || "Awards Evening"} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} />
              </div>
            </div>
            {hasMultiple && (
              <button onClick={() => navigate('prev')}
                onMouseEnter={e => { e.currentTarget.style.background="#fff"; e.currentTarget.querySelector("svg").style.stroke="#16151a"; }}
                onMouseLeave={e => { e.currentTarget.style.background="var(--accent)"; e.currentTarget.querySelector("svg").style.stroke="#fff"; }}
                className="av-arrow av-arrow-prev" style={{ ...arrowBtn, left: -43 }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 18, height: 18 }}><path d="M15 18l-6-6 6-6"/></svg>
              </button>
            )}
            {hasMultiple && (
              <button onClick={() => navigate('next')}
                onMouseEnter={e => { e.currentTarget.style.background="#fff"; e.currentTarget.querySelector("svg").style.stroke="#16151a"; }}
                onMouseLeave={e => { e.currentTarget.style.background="var(--accent)"; e.currentTarget.querySelector("svg").style.stroke="#fff"; }}
                className="av-arrow av-arrow-next" style={{ ...arrowBtn, right: -43 }}>
                <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 18, height: 18 }}><path d="M9 18l6-6-6-6"/></svg>
              </button>
            )}
          </div>

          {/* Text */}
          <div style={{ opacity: textVisible ? 1 : 0, transform: textVisible ? "translateY(0)" : "translateY(5px)", transition: "opacity 0.3s ease, transform 0.3s ease" }}>
            {(vid.eyebrow || ap.eveningLabel) && (
              <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", fontFamily: "var(--mono)", color: "var(--yellow)", marginBottom: 14 }}>
                {vid.eyebrow || ap.eveningLabel}
              </div>
            )}
            <p className="display" style={{ fontSize: "clamp(26px,4vw,56px)", color: "var(--paper)", lineHeight: 0.95, margin: "0 0 clamp(14px,2vw,24px)", letterSpacing: "-0.01em" }}>
              {vid.title || vid.label || "Awards Evening Highlights."}
            </p>
            {vid.desc && (
              <p style={{ fontSize: "clamp(13px,1.2vw,15px)", lineHeight: 1.75, color: "rgba(240,238,233,0.62)", margin: "0 0 clamp(16px,2vw,28px)" }}>{vid.desc}</p>
            )}
            {vid.buttonLabel && (
              <a href={vid.buttonUrl || "#"} target={vid.buttonUrl ? "_blank" : "_self"} rel="noopener noreferrer"
                style={{ display: "inline-flex", alignItems: "center", gap: 10, background: "var(--accent)", color: "#fff", padding: "15px 26px", fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", textDecoration: "none", transition: "filter 0.14s" }}
                onMouseEnter={e => { e.currentTarget.style.background = "#fff"; e.currentTarget.style.color = "var(--ink)"; }}
                onMouseLeave={e => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.style.color = "#fff"; }}>
                {vid.buttonLabel}
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 15, height: 15 }}><path d="M5 12h14M12 5l7 7-7 7"/></svg>
              </a>
            )}
            {hasMultiple && (
              <div style={{ marginTop: 24, fontSize: 10, fontFamily: "var(--mono)", color: "rgba(240,238,233,0.28)", letterSpacing: "0.12em" }}>
                {String(active + 1).padStart(2,"0")} / {String(videos.length).padStart(2,"0")}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}


Object.assign(window, { AwardsPage });
