// site-home.jsx — hi-fi V2 homepage.

// Award colours by strand
const AWARD_COLORS = { Fiction: "var(--pink)", Documentary: "var(--purple)", Animation: "var(--yellow)", Experimental: "var(--cyan)", Audience: "#F0EEE9" };
const AWARD_TEXT   = { Fiction: "#fff", Documentary: "#fff", Animation: "#16151a", Experimental: "#16151a", Audience: "#16151a" };
const STRAND_ORDER = ["Fiction", "Documentary", "Animation", "Experimental"];

// Abbreviate director names: "Charlie Ledwidge, Harley Hunt" → "C. Ledwidge, H. Hunt"
const abbrevName = (n) => {
  const p = n.trim().split(/\s+/);
  return p.length <= 1 ? n.trim() : p[0][0] + ". " + p.slice(1).join(" ");
};
const abbrevDirectors = (str) => {
  if (!str) return "";
  return str.split(/,\s*|\s+and\s+/).map(abbrevName).join(", ");
};

function fmtFilmRuntime(film) {
  const m = parseInt(film.runtime) || 0;
  const s = parseInt(film.runtimeSecs) || 0;
  if (!m && !s) return "";
  return s ? m + "′" + String(s).padStart(2, "0") + "″" : m + "′";
}

function Home({ navigate }) {
  const d = useSite();
  const f = d.festival;
  const films = usePublishedFilms();
  const news = usePublishedNews();
  const schedule = d.schedule || [];

  // Winners derived from prize field on current-edition films
  const currentFilms   = films.filter(film => film.year === f.year);
  const audienceWinner = currentFilms.find(film => film.prize === "Audience");
  const strandWinners  = STRAND_ORDER
    .map(strand => currentFilms.find(film => film.prize === "Jury" && film.strand === strand))
    .filter(Boolean);

  // Homepage copy with graceful fallbacks for older data
  const quote          = f.quote || "Short film is the cinema of attention — what you can hold, completely, in twenty minutes.";
  const winnersHeading = f.pastWinnersHeading || "Past Winners.";
  const awardsDesc     = f.awardsDesc || "The Paper Bird Awards honour the best short films across five categories — Fiction, Documentary, Animation, Experimental, and Audience Choice. Each winner receives a handmade Paper Bird trophy, colour-coded to their strand, created by artist Dave Treadwell.";
  const ctaTickets     = { enabled: true, eyebrow: "For audiences",  title: "Reserve your seat.",    body: "All eight nights are free with RSVP. Awards Night at SCALE is ticketed.",              cta: "Get tickets",          ...(f.ctaTickets || {}) };
  const ctaSubmit      = { enabled: true, eyebrow: "For filmmakers", title: "Submit for Edition VII.", body: "We accept short films across all four strands from students at film schools worldwide.", cta: "Submission guidelines", ...(f.ctaSubmit || {}) };

  return (
    <Page k="home">
      {/* ── HERO — full-bleed video, text overlaid ── */}
      <section className="dark hero-cine">
        <div className="hero-cine-media">
          <video
            className="hero-cine-vid"
            autoPlay muted loop playsInline preload="metadata"
            poster={"https://picsum.photos/seed/" + encodeURIComponent("ljmu-hero-" + f.year) + "/1920/1080"}
            src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
            style={{ transform: "scale(1.42)", transformOrigin: "center" }} />
          <div className="hero-cine-scrim" />
        </div>
        <div className="wrap hero-cine-inner">
          <div className="hero-cine-center">
            <h1 className="display" style={{ fontSize: "clamp(56px, 10vw, 168px)", color: "#fff", textShadow: "0 2px 24px rgba(0,0,0,0.4)" }}>{f.tagline}</h1>
            <p className="lead" style={{ maxWidth: 540, margin: "28px 0 0", color: "rgba(255,255,255,0.88)", textShadow: "0 1px 8px rgba(0,0,0,0.5)" }}>{f.intro}</p>
          </div>
          <div className="hero-cine-bottom">
            <div className="hero-cine-actions">
              <button className="btn coral" onClick={() => navigate("/programme")}>Browse the programme <SIcon name="arrowR" /></button>
              <button className="btn outline" onClick={() => navigate("/tickets")} style={{ display: f.ticketsEnabled === false ? "none" : "" }}>Tickets</button>
            </div>
            <div className="hero-cine-dates">
              <div className="display" style={{ fontSize: "clamp(40px,5vw,72px)", color: "var(--yellow)" }}>20—27</div>
              <div className="label" style={{ color: "rgba(255,255,255,0.78)" }}>March 2026</div>
            </div>
          </div>
        </div>
      </section>

      {/* ── VOTING BANNER ── shown only when voting is open */}
      {f.votingOpen && (
        <section className="section tight" style={{ paddingBottom: "clamp(28px,4vw,48px)" }}>          <div className="wrap">
            <div style={{ position: "relative", background: "var(--ink)", overflow: "hidden", borderTop: "3px solid #22c55e" }}>
              {/* pixel texture overlay */}
              <div style={{ position: "absolute", inset: 0, backgroundImage: "url('uploads/pixel-effect.png')", backgroundRepeat: "repeat", opacity: 0.5, pointerEvents: "none", mixBlendMode: "overlay" }} />
              <div style={{ position: "relative", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: "clamp(28px,5vw,72px)", alignItems: "center", padding: "clamp(36px,5vw,68px) clamp(28px,4vw,64px)" }} className="voting-grid">
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: "clamp(14px,2vw,22px)" }}>
                    <span style={{ width: 9, height: 9, borderRadius: "50%", background: "#22c55e", display: "inline-block", boxShadow: "0 0 0 4px rgba(34,197,94,0.2)" }} className="voting-dot" />
                    <span style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: ".16em", textTransform: "uppercase", color: "#22c55e", fontWeight: 600 }}>
                      {f.votingBannerLabel || "Audience Award \u00b7 Voting Open"}
                    </span>
                  </div>
                  <h2 className="display" style={{ fontSize: "clamp(32px,5vw,68px)", color: "var(--paper)", margin: 0, lineHeight: 0.98 }}>
                    {f.votingBannerHeading || "Cast your vote."}
                  </h2>
                </div>
                <div style={{ borderLeft: "1px solid var(--line-d)", paddingLeft: "clamp(24px,3vw,40px)" }} className="voting-aside">
                  {f.votingBannerBody && (
                    <p style={{ fontSize: "clamp(15px,1.4vw,18px)", color: "rgba(240,238,233,0.75)", margin: "0 0 clamp(20px,2.5vw,28px)", lineHeight: 1.7 }}>
                      {f.votingBannerBody}
                    </p>
                  )}
                  <a href={f.votingBannerButtonUrl || "#/programme"}
                      style={{ display: "inline-flex", alignItems: "center", gap: 10, background: "var(--accent)", color: "#fff", padding: "14px 28px", textDecoration: "none", fontFamily: "var(--mono)", fontSize: 11.5, letterSpacing: ".12em", textTransform: "uppercase", fontWeight: 600, transition: "background .15s, color .15s" }}
                      onMouseEnter={e => { e.currentTarget.style.background = "var(--paper)"; e.currentTarget.style.color = "#16151a"; }}
                      onMouseLeave={e => { e.currentTarget.style.background = "var(--accent)"; e.currentTarget.style.color = "#fff"; }}
                      onClick={e => { if (!f.votingBannerButtonUrl) { e.preventDefault(); navigate("/programme"); } }}>
                      {f.votingBannerButtonLabel || "Check out the Selected Films"}
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ width: 14, height: 14 }}><path d="M5 12h14M12 5l7 7-7 7" /></svg>
                    </a>
                </div>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* ── SIX NIGHTS ── */}
      <section className="section tight">
        <div className="wrap">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 28, flexWrap: "wrap", gap: 16 }}>
            <h2 className="display" style={{ fontSize: "clamp(30px,4vw,52px)" }}>The schedule.</h2>
            {f.ticketsEnabled !== false && <span className="textlink" onClick={() => navigate("/tickets")}>Venues &amp; tickets <SIcon name="arrowR" /></span>}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${schedule.length || 8}, 1fr)`, borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }} className="dayrow">
            {schedule.map((day, i) => {
              const isOff = day.strand === "Off-night";
              const accent = { Opening: "var(--yellow)", Documentary: "var(--purple)", Animation: "var(--yellow)", Experimental: "var(--cyan)", Fiction: "var(--pink)", Awards: "var(--pink)" }[day.strand] || "var(--ink)";
              return (
                <div key={day.id} style={{ padding: "20px 14px", borderRight: i < schedule.length - 1 ? "1px solid var(--line)" : "none", minWidth: 0, opacity: isOff ? 0.55 : 1 }}>
                  <div className="label muted" style={{ fontSize: 10 }}>{day.date}</div>
                  <div className="display" style={{ fontSize: 14, marginTop: 8, lineHeight: 1.15, color: isOff ? "var(--muted)" : "var(--ink)" }}>{day.title}</div>
                  {!isOff && <div className="label" style={{ fontSize: 10, marginTop: 6, color: accent }}>{day.time} · {day.strand}</div>}
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── EDITION TRAILER ── */}
      {f.trailerYouTube &&
      <section className="section dark tight">
        <div className="wrap">
          <Kicker n="§">{f.trailerSectionLabel || "Sixth Edition · Official Trailer"}</Kicker>
          <div className="trailer-grid" style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: "clamp(24px,4vw,56px)", alignItems: "center", marginTop: 16 }}>
            <div style={{ position: "relative", paddingBottom: "56.25%", overflow: "hidden", background: "#000" }}>
              <YouTubeThumb id={f.trailerYouTube} title={f.trailerSectionLabel || "Edition VI Official Trailer"} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }} />
            </div>
            <div>
              <span className="eyebrow" style={{ color: "var(--yellow)" }}>{f.trailerEyebrow || "LJMUMASFF · 2026"}</span>
              <h2 className="display" style={{ fontSize: "clamp(32px,4vw,58px)", color: "var(--paper)", marginTop: 14, marginBottom: 20 }}>{f.trailerHeading || "Watch the trailer."}</h2>
              <p style={{ color: "rgba(240,238,233,0.8)", lineHeight: 1.65, fontSize: 16, marginBottom: 24 }}>{f.trailerBody || "Four strands. Forty-one films. Six nights across Liverpool. The sixth edition of the LJMU MA Short Film Festival."}</p>
              <button className="btn coral" onClick={() => {
                const url = f.trailerButtonUrl || "/programme";
                if (url.startsWith("http")) { window.open(url, "_blank", "noopener"); } else { navigate(url); }
              }}>{f.trailerButtonLabel || "Browse all films"} <SIcon name="arrowR" /></button>
            </div>
          </div>
        </div>
      </section>
      }

      {/* ── PAST WINNERS ── */}
      <section className="section dark">
        <div className="wrap">
          <Kicker n="§ 01">Paper Bird Award Sixth Edition</Kicker>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 40, flexWrap: "wrap", gap: 16 }}>
            <h2 className="display" style={{ fontSize: "clamp(38px,6vw,86px)" }}>{winnersHeading}</h2>
            <span className="textlink" onClick={() => navigate("/programme")} style={{ color: "var(--paper)" }}>All {films.length} films <SIcon name="arrowR" /></span>
          </div>

          {audienceWinner &&
          <div style={{ display: "grid", gridTemplateColumns: "5fr 7fr", gap: "clamp(20px,3vw,40px)", alignItems: "start" }} className="home-selection">
              {/* Audience Award — large card */}
              <div>
                <div className="film-card" onClick={() => navigate("/film/" + audienceWinner.id)}>
                  <div style={{ position: "relative" }}>
                  <Frame seed={audienceWinner.title} src={audienceWinner.poster || undefined} ratio="2/3" style={{ borderRadius: 12 }} corner="01" />
                  <div style={{ position: "absolute", inset: "35% 0 0 0", background: "linear-gradient(to top, rgba(22,21,26,0.72) 0%, transparent 100%)", borderRadius: "0 0 12px 12px", pointerEvents: "none" }} />
                  <img src="uploads/laurel winner.svg" alt="Audience Award Winner" style={{ position: "absolute", bottom: "5%", right: "4%", width: "33%", filter: "brightness(0) invert(1)", opacity: 0.92, pointerEvents: "none" }} />
                  </div>
                  <div className="meta">
                    <div className="toprow">
                      <span className="tag solid" style={{ background: AWARD_COLORS.Audience, color: AWARD_TEXT.Audience, borderColor: AWARD_COLORS.Audience }}>Audience Award Winner</span>
                      <span className="label muted">{fmtFilmRuntime(audienceWinner)}</span>
                    </div>
                    <div className="title" style={{ fontSize: "clamp(26px,3vw,40px)", color: "var(--paper)" }}>{audienceWinner.title}</div>
                    <div className="sub muted">{audienceWinner.directors} · {audienceWinner.country}</div>
                  </div>
                </div>
                {/* Awards description block */}
                <div style={{ background: "#F0EEE9", padding: "clamp(20px,3vw,32px)", marginTop: 16 }}>
                  <p style={{ color: "#16151a", fontSize: 15, lineHeight: 1.65, margin: 0 }}>{awardsDesc}</p>
                </div>
              </div>

              {/* Strand winners — grid */}
              <div className="grid cols-2">
                {strandWinners.map((film, i) =>
                <div className="film-card" key={film.id} onClick={() => navigate("/film/" + film.id)}>
                  <div style={{ position: "relative" }}>
                  <Frame seed={film.title} src={film.poster || undefined} ratio="2/3" style={{ borderRadius: 10 }} corner={String(i + 2).padStart(2, "0")} />
                  <div style={{ position: "absolute", inset: "35% 0 0 0", background: "linear-gradient(to top, rgba(22,21,26,0.72) 0%, transparent 100%)", borderRadius: "0 0 10px 10px", pointerEvents: "none" }} />
                  <img src="uploads/laurel winner.svg" alt={film.strand + " Winner"} style={{ position: "absolute", bottom: "5%", right: "4%", width: "33%", filter: "brightness(0) invert(1)", opacity: 0.92, pointerEvents: "none" }} />
                  </div>
                  <div className="meta">
                    <div className="toprow">
                      <span className="tag" style={{ background: AWARD_COLORS[film.strand] || "var(--line-d)", color: AWARD_TEXT[film.strand] || "#fff", borderColor: AWARD_COLORS[film.strand] || "var(--line-d)" }}>{film.strand} Winner</span>
                      <span className="label muted">{fmtFilmRuntime(film)}</span>
                    </div>
                    <div className="title" style={{ color: "var(--paper)" }}>{film.title}</div>
                    <div className="sub muted">{film.directors} · {film.country}</div>
                  </div>
                </div>
                )}
              </div>
            </div>
          }
        </div>
      </section>

      {/* ── EDITORIAL QUOTE ── */}
      <section className="section" style={{ background: "var(--paper-2)" }}>
        <div className="wrap">
          <Kicker n="§ 02">From the Journal</Kicker>
          <blockquote style={{ margin: "0 0 40px", maxWidth: 1000 }}>
            <p className="display" style={{ fontSize: "clamp(28px,4.5vw,62px)", fontWeight: 700, fontStretch: "100%", fontStyle: "italic", lineHeight: 1.08 }}>
              "{quote}"
            </p>
          </blockquote>
          <div className="grid cols-3">
            {news.slice(0, 3).map((n) => {
              const coverImg = (n.cover) || (window.firstBlockImage && window.firstBlockImage(n));
              return (
            <article key={n.id} className="film-card" onClick={() => navigate("/news/" + n.id)} style={{ cursor: "pointer" }}>
                {coverImg
                  ? <div style={{ aspectRatio: "16/10", overflow: "hidden", borderRadius: 10 }}><img src={coverImg} alt={n.title} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} /></div>
                  : <Frame seed={n.title} ratio="16/10" style={{ borderRadius: 10 }} />
                }
                <div className="meta">
                  <div className="toprow"><span className="tag">{n.category}</span><span className="label muted">{fmtDate(n.date)}</span></div>
                  <div className="title" style={{ fontSize: 22 }}>{n.title}</div>
                  <div className="sub">By {n.author}</div>
                </div>
              </article>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── CTA ── */}
      {((f.ticketsEnabled !== false && ctaTickets.enabled !== false) || ctaSubmit.enabled !== false) && (
      <section className="section dark">
        <div className="wrap home-cta" style={{ display: "grid", gridTemplateColumns: (f.ticketsEnabled !== false && ctaTickets.enabled !== false && ctaSubmit.enabled !== false) ? "1fr 1fr" : "1fr", gap: 16 }}>
          {f.ticketsEnabled !== false && ctaTickets.enabled !== false && <CtaCard eyebrow={ctaTickets.eyebrow} title={ctaTickets.title} body={ctaTickets.body} cta={ctaTickets.cta} onClick={() => navigate("/tickets")} bg={ctaTickets.bg || f.accentColor || "var(--pink)"} />}
          {ctaSubmit.enabled  !== false && <CtaCard eyebrow={ctaSubmit.eyebrow}  title={ctaSubmit.title}  body={ctaSubmit.body}  cta={ctaSubmit.cta}  onClick={() => navigate("/submit")}  bg={ctaSubmit.bg  || f.accentColor2 || "var(--purple)"} />}
        </div>
      </section>
      )}
    </Page>
  );
}

function CtaCard({ eyebrow, title, body, cta, onClick, solid, bg }) {
  const fill = bg || (solid ? "var(--pink)" : null);
  return (
    <div style={{ padding: "clamp(28px,4vw,52px)", background: fill || "transparent", border: fill ? "none" : "1px solid var(--line-d)", color: fill ? "#fff" : "var(--paper)" }}>
      <span className="label" style={{ opacity: 0.85 }}>{eyebrow}</span>
      <div className="display" style={{ fontSize: "clamp(30px,4vw,52px)", margin: "14px 0 14px" }}>{title}</div>
      <p style={{ opacity: 0.9, maxWidth: 380, fontSize: 16 }}>{body}</p>
      <button className="btn" onClick={onClick} style={{ background: "var(--ink)", borderColor: "var(--ink)", color: "var(--paper)", marginTop: 12 }}>{cta} <SIcon name="arrowR" /></button>
    </div>
  );
}

function fmtDate(s) {
  if (!s) return "";
  const [y, m, dd] = s.split("-");
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${dd} ${months[(+m || 1) - 1]} ${y}`;
}

Object.assign(window, { Home, CtaCard, fmtDate });
