// site-film-hotpage.jsx — Cinematic hotpage for streaming week
// Replaces FilmDetail when festival.streaming.enabled && videoUrl is set

const HP_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%)" },
};

function hpFallback(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}`;
}

// NOTE: film hotpage playback (both the main video and the trailer) is rendered via the
// shared, analytics-wired window.VideoPlayer (site-video-player.jsx) — see usages below.
// A duplicate local VideoPlayer used to live here, shadowing window.VideoPlayer for the
// trailer JSX tag (<VideoPlayer .../> resolves to same-file declarations before window.*),
// and it only ever called window.trackEvent — a function that is never defined anywhere in
// the app (only sketched in STATS_EXPANSION_PLAN.md). That silently dropped 100% of trailer
// play/completion analytics. Removed; trailer now explicitly uses window.VideoPlayer too.

function FilmHotpage({ filmId, navigate }) {
  const d  = useSite();
  const f  = d.festival || {};
  const str = f.streaming || {};
  const ovr = (str.filmOverrides || {})[filmId] || {};
  const currentYear = (f.dates?.year) || new Date().getFullYear().toString();

  const film = (d.films || []).find(fl => fl.id === filmId);
  if (!film) {
    return (
      <div style={{ padding:80, textAlign:"center", color:"var(--muted)" }}>
        Film not found. <button onClick={() => navigate("/programme")}
          style={{ background:"none", border:"none", color:"var(--accent-bright)", cursor:"pointer", textDecoration:"underline" }}>Back</button>
      </div>
    );
  }

  const sc         = HP_STRAND_COLORS[film.strand] || HP_STRAND_COLORS.Fiction;
  const still      = ovr.stillOverride || film.stillsImages?.[0]?.url || film.bannerUrl || film.poster || "";
  const statement  = ovr.directorStatement || film.directorBios?.[0]?.bio || "";
  const videoUrl   = ovr.videoUrl || "";
  const trailerUrl = ovr.trailerUrl || "";

  // More in strand (excluding this film)
  const more = (d.films || []).filter(fl =>
    fl.strand === film.strand &&
    fl.id !== filmId &&
    fl.year === currentYear &&
    fl.status === "published"
  ).slice(0, 6);

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

  // Track impression
  React.useEffect(() => {
    if (window.trackEvent) window.trackEvent("film_hotpage_view", { filmId, strand: film.strand });
  }, [filmId]);

  return (
    <div style={{ background:"#141318", minHeight:"100vh", color:"#f0eee9" }}>

      {/* ── Hero ──────────────────────────────────── */}
      <div style={{ position:"relative", height:"100vh", minHeight:600, overflow:"hidden" }}>
        {/* Background */}
        <div style={{ position:"absolute", inset:0, zIndex:0, background: hpFallback(sc) }}></div>
        {still && <img src={still} alt={film.title} style={{ position:"absolute", inset:0,
          width:"100%", height:"100%", objectFit:"cover", zIndex:1, opacity:.72 }} />}
        {/* Scrims */}
        <div style={{ position:"absolute", inset:0, zIndex:2, pointerEvents:"none",
          background:"linear-gradient(0deg,#141318 0%,rgba(20,19,24,.6) 30%,rgba(20,19,24,.1) 62%,rgba(20,19,24,.5) 100%)" }}></div>

        {/* Back */}
        <button onClick={() => navigate("/programme")}
          style={{ position:"absolute", top:26, left:34, zIndex:10, display:"flex", alignItems:"center",
            gap:9, fontFamily:"monospace", fontSize:10, letterSpacing:".14em", textTransform:"uppercase",
            color:"rgba(240,238,233,.7)", background:"none", border:"none", cursor:"pointer", transition:"color .15s" }}
          onMouseEnter={e=>e.currentTarget.style.color="#f0eee9"}
          onMouseLeave={e=>e.currentTarget.style.color="rgba(240,238,233,.7)"}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="16" height="16"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
          All Films
        </button>
        {/* Logo */}
        <div style={{ position:"absolute", top:24, right:34, zIndex:10,
          fontFamily:"var(--display)", fontSize:10, letterSpacing:".02em", textTransform:"uppercase",
          opacity:.7, textAlign:"right", lineHeight:1.3 }}>LJMU MA<br/>Short Film Festival</div>

        {/* Content */}
        <div style={{ position:"absolute", zIndex:5, left:0, bottom:0,
          padding:"0 clamp(28px,5vw,60px) clamp(44px,7vh,64px)", maxWidth:860 }}>
          <div style={{ fontFamily:"monospace", fontSize:10, letterSpacing:".2em", textTransform:"uppercase",
            marginBottom:20, display:"flex", alignItems:"center", gap:10, color:"rgba(240,238,233,.8)" }}>
            <span style={{ width:9, height:9, borderRadius:"50%", background:sc.color, display:"inline-block" }}></span>
            {film.strand} · Sixth Edition {currentYear}
          </div>
          <h1 style={{ fontFamily:"var(--display)", fontSize:"clamp(56px,9.5vw,128px)", lineHeight:.86,
            letterSpacing:"-.03em", textTransform:"uppercase", marginBottom:28, textWrap:"balance" }}>
            {film.title}
          </h1>
          <div style={{ display:"flex", alignItems:"center", gap:18, marginBottom:34, flexWrap:"wrap" }}>
            {film.runtime && <span style={{ fontFamily:"monospace", fontSize:11, letterSpacing:".08em", color:"rgba(240,238,233,.66)" }}>{film.runtime}′</span>}
            <span style={{ width:3, height:3, borderRadius:"50%", background:"rgba(240,238,233,.3)", display:"inline-block" }}></span>
            {film.directors && <span style={{ fontFamily:"monospace", fontSize:11, letterSpacing:".08em", color:"rgba(240,238,233,.66)" }}>dir. {film.directors}</span>}
            {film.country && <>
              <span style={{ width:3, height:3, borderRadius:"50%", background:"rgba(240,238,233,.3)", display:"inline-block" }}></span>
              <span style={{ fontFamily:"monospace", fontSize:11, letterSpacing:".08em", color:"rgba(240,238,233,.66)" }}>{film.country}</span>
            </>}
            <span style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".16em", textTransform:"uppercase",
              padding:"5px 11px", fontWeight:700, color:"#141318", background:sc.color }}>
              {film.strand}
            </span>
          </div>
          <div style={{ display:"flex", gap:11, alignItems:"center", flexWrap:"wrap" }}>
            {videoUrl && (
              <button onClick={() => document.getElementById("hp-player")?.scrollIntoView({ behavior:"smooth", block:"center" })}
                style={{ display:"flex", alignItems:"center", gap:10, fontFamily:"monospace", fontSize:11,
                  letterSpacing:".12em", textTransform:"uppercase", padding:"15px 28px",
                  background:"#ff5c70", color:"#fff", border:"none", cursor:"pointer" }}>
                <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>
                Watch Film
              </button>
            )}
            {trailerUrl && (
              <button onClick={() => document.getElementById("hp-trailer")?.scrollIntoView({ behavior:"smooth", block:"center" })}
                style={{ display:"flex", alignItems:"center", gap:10, fontFamily:"monospace", fontSize:11,
                  letterSpacing:".12em", textTransform:"uppercase", padding:"14px 26px",
                  background:"transparent", color:"#f0eee9", border:"1px solid rgba(240,238,233,.3)", cursor:"pointer" }}>
                Trailer
              </button>
            )}
            {(() => {
              const votingMode = f.voting?.mode || "internal";
              const showVote = f.votingOpen && String(film.year) === String(currentYear) && (votingMode === "internal" ? film.voteEnabled : film.voteLink);
              return showVote && window.VoteButton && React.createElement(window.VoteButton, {
                film, mode: votingMode, hex: sc.color, textOn: "#141318", size: "lg",
                style: { background: "transparent", color: "#f0eee9", border: "1px solid rgba(240,238,233,.3)" },
              });
            })()}
          </div>
        </div>
      </div>

      {/* ── Details ────────────────────────────────── */}
      <div style={{ maxWidth:1180, margin:"0 auto", padding:"clamp(48px,8vw,72px) clamp(24px,5vw,60px) clamp(60px,8vw,90px)" }}>

        {/* Full film player */}
        <div id="hp-player" style={{ width:"100%", aspectRatio:"16/9", overflow:"hidden",
            border:"1px solid rgba(240,238,233,.08)", marginBottom:16, background:"#0c0b0f" }}>
          {window.VideoPlayer
            ? React.createElement(window.VideoPlayer, { videoUrl, posterSrc:still, filmId, autoplay:false })
            : <div onClick={() => document.getElementById("hp-player-fallback")?.click()}
                style={{ width:"100%", height:"100%", display:"flex", alignItems:"center", justifyContent:"center",
                  cursor:"pointer", background:sc.grad }}>
                <div id="hp-player-fallback" style={{ width:80, height:80, background:"rgba(255,92,112,.9)",
                  display:"flex", alignItems:"center", justifyContent:"center" }}>
                  <svg viewBox="0 0 24 24" fill="#fff" width="30" height="30" style={{ marginLeft:4 }}><path d="M8 5v14l11-7z"/></svg>
                </div>
              </div>}
        </div>

        {/* Poster + Metadata grid */}
        <div style={{ display:"grid", gridTemplateColumns: film.poster ? "200px 1fr" : "1fr", gap:40, marginBottom:56, marginTop:videoUrl?0:0 }}>
          {film.poster && (
            <div style={{ flexShrink:0 }}>
              <img src={film.poster} alt={film.title + " poster"} style={{ width:"100%", display:"block", boxShadow:"0 8px 32px rgba(0,0,0,.5)" }} />
            </div>
          )}
          <div>
            {/* Synopsis */}
            {film.synopsis && (
              <>
                <div style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".24em", textTransform:"uppercase",
                  color:"#8a857c", marginBottom:14 }}>Synopsis</div>
                <p style={{ fontSize:17, lineHeight:1.78, color:"rgba(240,238,233,.84)", marginBottom:36 }}>
                  {film.synopsis}
                </p>
              </>
            )}
            {/* Director statement */}
            {statement && (
              <>
                <div style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".24em", textTransform:"uppercase",
                  color:"#8a857c", marginBottom:14 }}>Director's Statement</div>
                <div style={{ borderLeft:"2px solid #ff5c70", paddingLeft:22, marginBottom:8 }}>
                  <p style={{ fontSize:15, lineHeight:1.7, fontStyle:"italic", color:"rgba(240,238,233,.72)" }}>
                    "{statement}"
                  </p>
                  <div style={{ fontFamily:"monospace", fontStyle:"normal", fontSize:10, letterSpacing:".12em",
                    textTransform:"uppercase", color:"#8a857c", marginTop:12 }}>
                    {film.directors}, Director
                  </div>
                </div>
              </>
            )}
          </div>
        </div>

        {/* Credits + selection */}
        <div style={{ display:"grid", gridTemplateColumns:"1.7fr 1fr", gap:60, alignItems:"start" }}>
          <div>
            <div style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".24em", textTransform:"uppercase",
              color:"#8a857c", marginBottom:14 }}>Credits</div>
            {[
              ["Director",  film.directors],
              ["Country",   film.country],
              ["Language",  film.language],
              ["Runtime",   film.runtime ? film.runtime + "′" : ""],
              ["Strand",    film.strand],
              ["Format",    "Short film · DCP / ProRes"],
              film.premiere && ["Premiere", film.premiere],
            ].filter(Boolean).filter(([,v])=>v).map(([role, val]) => (
              <div key={role} style={{ borderTop:"1px solid rgba(240,238,233,.1)", padding:"14px 0" }}>
                <div style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".18em",
                  textTransform:"uppercase", color:"#8a857c", marginBottom:5 }}>{role}</div>
                <div style={{ fontSize:15, fontWeight:600 }}>{val}</div>
              </div>
            ))}
          </div>
          <div>
            {/* Official selection badge */}
            <div style={{ border:"1px solid rgba(240,238,233,.14)", padding:"18px 20px",
              display:"flex", gap:14, alignItems:"center", marginBottom:20 }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="#ffc436" strokeWidth="1.6" width="30" height="30">
                <path d="M12 2l2.4 6.5H21l-5.3 4 2 6.5L12 15l-5.7 4 2-6.5L3 8.5h6.6z"/>
              </svg>
              <div>
                <div style={{ fontFamily:"var(--display)", fontSize:13, textTransform:"uppercase",
                  letterSpacing:"-.01em", marginBottom:3 }}>Official Selection</div>
                <div style={{ fontFamily:"monospace", fontSize:9.5, letterSpacing:".1em", color:"#8a857c" }}>
                  Sixth Edition · {currentYear}
                </div>
              </div>
            </div>
            {/* Trailer player */}
            {trailerUrl && (
              <>
                <div id="hp-trailer" style={{ fontFamily:"monospace", fontSize:9, letterSpacing:".24em",
                  textTransform:"uppercase", color:"#8a857c", marginBottom:10 }}>Trailer</div>
                <div style={{ width:"100%", aspectRatio:"16/9", overflow:"hidden",
                  border:"1px solid rgba(240,238,233,.08)", background:"#0c0b0f" }}>
                  {window.VideoPlayer && React.createElement(window.VideoPlayer, { videoUrl: trailerUrl, posterSrc: still, filmId: filmId + "-trailer", autoplay:false })}
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* ── More in strand ─────────────────────────── */}
      {more.length > 0 && (
        <div style={{ paddingBottom:60 }}>
          <div style={{ display:"flex", alignItems:"center", gap:12,
            padding:"0 clamp(24px,5vw,60px)", marginBottom:22 }}>
            <span style={{ width:4, height:26, background:sc.color, display:"inline-block" }}></span>
            <span style={{ fontFamily:"var(--display)", fontSize:18, textTransform:"uppercase",
              letterSpacing:"-.01em" }}>More in {film.strand}</span>
          </div>
          <div style={{ display:"flex", gap:16, overflowX:"auto",
            padding:"6px clamp(24px,5vw,60px) 18px", scrollbarWidth:"none" }}>
            {more.map(fl => {
              const nsc = HP_STRAND_COLORS[fl.strand] || sc;
              const flStill = (str.filmOverrides?.[fl.id]?.stillOverride) || fl.stillsImages?.[0]?.url || fl.bannerUrl || fl.poster || "";
              return (
                <div key={fl.id} onClick={() => goFilm(fl.id)}
                  style={{ flex:"none", width:200, cursor:"pointer", 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)"}>
                  <div style={{ position:"relative", width:"100%", aspectRatio:"2/3",
                    overflow:"hidden", background:"#141318" }}>
                    <div style={{ position:"absolute", inset:0, zIndex:0, background: hpFallback(nsc) }}></div>
                    {flStill && <img src={flStill} alt={fl.title} style={{ position:"absolute", inset:0,
                      width:"100%", height:"100%", objectFit:"cover", zIndex:1 }} />}
                    <div style={{ position:"absolute", inset:0, zIndex:2,
                      background:"linear-gradient(0deg,rgba(18,17,22,.95) 0%,rgba(18,17,22,.1) 45%,transparent 65%)" }}></div>
                    <div style={{ position:"absolute", top:0, left:0, right:0, height:3, zIndex:3, background:nsc.color }}></div>
                    <div style={{ position:"absolute", left:13, right:13, bottom:13, zIndex:3,
                      fontFamily:"var(--display)", fontSize:16, lineHeight:.96, textTransform:"uppercase",
                      letterSpacing:"-.015em", color:"#f0eee9", textWrap:"balance" }}>{fl.title}</div>
                  </div>
                  <div style={{ display:"flex", justifyContent:"space-between", gap:8,
                    marginTop:10, padding:"0 2px" }}>
                    <span style={{ fontSize:12, 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>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { FilmHotpage });
