/* =========================================================
   RENFECHT — Home / Landing page
   ========================================================= */

function useCountdown(target) {
  const [now, setNow] = React.useState(() => Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target.getTime() - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor((diff % 86400000) / 3600000),
    m: Math.floor((diff % 3600000) / 60000),
    s: Math.floor((diff % 60000) / 1000),
  };
}

function useParallax() {
  const [y, setY] = React.useState(0);
  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setY(window.scrollY));
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);
  return y;
}

/* ---------- Hero ---------- */

function Hero({ variant = "layered", onNavigate }) {
  const v = useValues();
  const y = useParallax();
  const layered = variant === "layered";
  return (
    <section className="hero" style={{
      position: "relative",
      paddingTop: "clamp(56px, 8vw, 96px)",
      paddingBottom: "clamp(40px, 6vw, 80px)",
      overflow: "hidden",
    }}>
      {/* Background crest watermark */}
      <div aria-hidden="true" className="flourish" style={{
        position: "absolute", inset: 0, display: "grid", placeItems: "center",
        color: "var(--ink)", opacity: 0.06,
        transform: `translateY(${y * 0.18}px) scale(1.05)`,
        pointerEvents: "none",
      }}>
        <Crest size={760} withBanner={false} />
      </div>

      {/* Background hairlines */}
      <div aria-hidden="true" className="flourish" style={{
        position: "absolute", inset: 0, pointerEvents: "none",
        backgroundImage: "linear-gradient(to right, color-mix(in oklab, var(--rule) 60%, transparent) 1px, transparent 1px)",
        backgroundSize: "calc(100% / 6) 100%",
        opacity: 0.18,
        transform: `translateY(${y * 0.05}px)`,
      }} />

      <div className="wrap" style={{ position: "relative" }}>
        <div className={"hero-grid " + (layered ? "is-layered" : "is-centered")}>
          <div className="reveal in" style={{ textAlign: layered ? "left" : "center" }}>
            <div style={{ display: "flex", justifyContent: layered ? "flex-start" : "center", gap: 18, alignItems: "center", marginBottom: 20, flexWrap: "wrap" }}>
              <span className="pill pill-accent">{v.event.dateDisplay}</span>
              <span className="eyebrow">{v.event.location.toUpperCase()}</span>
            </div>

            <h1 style={{
              fontSize: layered ? "clamp(3rem, 9vw, 8rem)" : "clamp(3.5rem, 12vw, 11rem)",
              lineHeight: 0.92,
              letterSpacing: "0.01em",
              margin: 0,
              fontFamily: "var(--font-logotype)",
              color: "var(--accent)",
              fontWeight: 400,
            }}>
              {v.event.name}
            </h1>

            <p className="lede" style={{
              maxWidth: "46ch",
              margin: layered ? "1.6rem 0 0" : "1.6rem auto 0",
              fontSize: "clamp(1.05rem, 1.7vw, 1.5rem)",
            }}>
              {v.event.tagline}
            </p>

            <div style={{
              marginTop: 36,
              display: "flex",
              gap: 14,
              flexWrap: "wrap",
              justifyContent: layered ? "flex-start" : "center",
            }}>
              <a href="#register" className="btn btn-accent" onClick={(e) => { e.preventDefault(); onNavigate("register"); }}>
                Register Now →
              </a>
              <a href="#event" className="btn btn-ghost" onClick={(e) => { e.preventDefault(); onNavigate("event"); }}>
                Event Details
              </a>
            </div>

            <div style={{ marginTop: 56, maxWidth: layered ? "none" : 720, marginInline: layered ? 0 : "auto" }}>
              <Countdown />
            </div>
          </div>

          {layered && (
            <div className="reveal in hero-image" style={{ position: "relative" }}>
              <Placeholder label="HERO PHOTO — fighter in harness, longsword vom Tag" ratio="4 / 5" style={{ border: "1px solid var(--rule)" }} />
              <div className="frame" style={{ position: "absolute", bottom: -24, left: -24, padding: 18, background: "var(--paper)" }}>
                <CornerDots />
                <div className="eyebrow" style={{ marginBottom: 4 }}>BOUTS</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: "2rem", letterSpacing: "0.06em" }}>{v.event.totalBouts}</div>
              </div>
            </div>
          )}
        </div>
      </div>
      <style>{`
        .hero-grid { display: grid; gap: var(--space-7); align-items: center; }
        .hero-grid.is-layered { grid-template-columns: 1.2fr 1fr; }
        .hero-grid.is-centered { grid-template-columns: 1fr; }
        @media (max-width: 880px) {
          .hero-grid.is-layered { grid-template-columns: 1fr; }
          .hero-image { max-width: 480px; margin-inline: auto; }
        }
      `}</style>
    </section>
  );
}

/* ---------- Countdown ---------- */

function Countdown() {
  const v = useValues();
  const target = React.useMemo(() => new Date(v.event.dateISO), [v.event.dateISO]);
  const { d, h, m, s } = useCountdown(target);
  const Cell = ({ value, label }) => (
    <div className="count-cell">
      <div className="count-num">{String(value).padStart(2, "0")}</div>
      <div className="count-label">{label}</div>
    </div>
  );
  return (
    <div className="countdown">
      <div className="eyebrow" style={{ textAlign: "center", marginBottom: 12 }}>THE FIGHTING BEGINS IN...</div>
      <div className="count-row">
        <Cell value={d} label="DAYS" />
        <span className="count-sep">·</span>
        <Cell value={h} label="HOURS" />
        <span className="count-sep">·</span>
        <Cell value={m} label="MIN" />
        <span className="count-sep">·</span>
        <Cell value={s} label="SEC" />
      </div>
      <style>{`
        .countdown { background: color-mix(in oklab, var(--paper-deep) 60%, var(--paper)); border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); padding: 22px clamp(16px, 3vw, 36px); position: relative; }
        .countdown::before, .countdown::after { content: ""; position: absolute; left: 50%; transform: translateX(-50%); width: 38px; height: 8px; background: var(--paper); border-left: 1px solid var(--rule); border-right: 1px solid var(--rule); }
        .countdown::before { top: -1px; }
        .countdown::after { bottom: -1px; }
        .count-row { display: flex; align-items: baseline; justify-content: center; gap: clamp(8px, 2vw, 24px); }
        .count-cell { text-align: center; min-width: 70px; }
        .count-num { font-family: var(--font-display); font-size: clamp(2.2rem, 5vw, 3.4rem); font-weight: 600; letter-spacing: 0.04em; line-height: 1; color: var(--ink); font-variant-numeric: tabular-nums; }
        .count-label { font-family: var(--font-mono); font-size: 0.7rem; letter-spacing: 0.32em; color: var(--ink-mute); margin-top: 6px; }
        .count-sep { font-family: var(--font-display); color: var(--rule); font-size: clamp(1.4rem, 3vw, 2.2rem); }
      `}</style>
    </div>
  );
}

/* ---------- Divisions strip ---------- */

function DivisionsStrip({ onNavigate }) {
  const v = useValues();
  return (
    <section className="section">
      <div className="wrap">
        <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "var(--space-7)", alignItems: "end", marginBottom: "var(--space-7)" }} className="dv-head">
          <div>
            <span className="eyebrow">OUR TOURNAMENTS</span>
            <h2 style={{ marginTop: 8 }}>Three<br/>Disciplines</h2>
          </div>
          <p className="lede" style={{ maxWidth: "44ch", justifySelf: "end", margin: 0 }}>
            Each Tournament has its own rules. We have highly trained judges, a <a href="#faq-1" onClick={(e) => { e.preventDefault(); onNavigate("faq"); setTimeout(() => document.getElementById("faq-1")?.scrollIntoView({ behavior: "smooth" }), 0); }}>specific ruleset</a>, and not published to hemascorecard or hemaratings.
          </p>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))" }}>
          {v.divisions.map((d, i) => (
            <article key={d.id} className="card reveal" style={{ transitionDelay: `${i * 80}ms` }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
                <div style={{ color: "var(--accent)" }} className="flourish"><CrossedSwordsIcon size={30} /></div>
                <span className="pill">{String(i + 1).padStart(2, "0")} / {String(v.divisions.length).padStart(2, "0")}</span>
              </div>
              <h3 style={{ fontSize: "var(--scale-6)", letterSpacing: "0.04em", textTransform: "none" }}>{d.title}</h3>
              <div className="eyebrow" style={{ marginTop: 4 }}>{d.sub}</div>
              <p style={{ marginTop: 16, color: "var(--ink-soft)", fontSize: "1rem" }}>{d.body}</p>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--rule)" }}>
                <span className="mono" style={{ fontSize: "0.78rem", letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--ink-mute)" }}>{d.stat}</span>
                <a href="#about" onClick={(e) => { e.preventDefault(); onNavigate("about"); }} style={{ fontSize: "0.85rem", letterSpacing: "0.12em", textTransform: "uppercase", fontFamily: "var(--font-display)" }}>Read →</a>
              </div>
            </article>
          ))}
        </div>
        <style>{`@media (max-width: 720px) { .dv-head { grid-template-columns: 1fr !important; } }`}</style>
      </div>
    </section>
  );
}

/* ---------- What to expect ---------- */

function ExpectStrip() {
  const v = useValues();
  return (
    <section className="section" style={{ background: "color-mix(in oklab, var(--paper) 80%, var(--paper-deep))", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <SectionHeader eyebrow="THE WEEKEND" title="What to Expect" />
        <div className="expect-heroes">
          {v.expect.map((it, i) => (
            <article key={i} className="expect-hero reveal" style={{ transitionDelay: `${i * 90}ms` }}>
              <Placeholder label={`PHOTO — ${it.title.toUpperCase()}`} ratio="16 / 9" />
              <div className="expect-copy">
                <div className="eyebrow">{it.kicker}</div>
                <div className="expect-meta">
                  <span>{it.num}</span>
                  <span>{it.time}</span>
                </div>
                <h3>{it.title}</h3>
                <p>{it.body}</p>
              </div>
            </article>
          ))}
        </div>
      </div>
      <style>{`
        .expect-heroes { display: grid; gap: var(--space-6); }
        .expect-hero { display: grid; grid-template-columns: minmax(280px, 0.95fr) minmax(280px, 1.05fr); gap: var(--space-6); align-items: center; padding-block: var(--space-4); border-top: 1px solid var(--rule); }
        .expect-hero:first-child { border-top: 0; padding-top: 0; }
        .expect-hero:nth-child(even) .placeholder { order: 2; }
        .expect-copy { max-width: 48ch; }
        .expect-meta { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; margin-top: 14px; font-family: var(--font-mono); font-size: 0.78rem; letter-spacing: 0.18em; text-transform: uppercase; color: var(--accent); }
        .expect-meta span { border: 1px solid var(--rule); padding: 5px 9px; background: var(--paper); }
        .expect-copy h3 { margin-top: 16px; font-size: clamp(1.8rem, 4vw, 3.2rem); letter-spacing: 0.02em; text-transform: none; }
        .expect-copy p { margin-top: 14px; color: var(--ink-soft); font-size: 1.08rem; }
        @media (max-width: 820px) {
          .expect-hero { grid-template-columns: 1fr; }
          .expect-hero:nth-child(even) .placeholder { order: 0; }
        }
      `}</style>
    </section>
  );
}

/* ---------- Composed page ---------- */

function HomePage({ heroVariant, onNavigate }) {
  useReveal();
  return (
    <main>
      <Hero variant={heroVariant} onNavigate={onNavigate} />
      <DivisionsStrip onNavigate={onNavigate} />
      <ExpectStrip />
      <ClosingCTA
        variant="big"
        eyebrow="REGISTRATION OPEN"
        title="" /* big variant builds its own headline from values */
        cta="Register Now"
        target="register"
        onNavigate={onNavigate}
      />
    </main>
  );
}

Object.assign(window, { HomePage });
