// ============================================================
// PACE — Secciones A: Header, Hero, Stats, Selector de meta
// ============================================================

// ---- Dropdown de navegación ----
function NavDrop({ label, items }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div
      className={"nav-drop" + (open ? " open" : "")}
      onMouseEnter={() => setOpen(true)}
      onMouseLeave={() => setOpen(false)}
    >
      <button className="nav-drop-btn" type="button" onClick={() => setOpen(!open)}>
        {label} <span style={{ fontSize: 9, color: "var(--orange)" }}>▾</span>
      </button>
      <div className="drop-menu">
        {items.map((it) => (
          <a key={it.label} href={it.href} className="drop-item" onClick={() => setOpen(false)}>
            {it.label}
          </a>
        ))}
      </div>
    </div>
  );
}

// ---- Header ----
function Header({ route }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const groups = [
    {
      label: "Entrenamiento",
      items: [
        { label: "¿Cuál es tu meta? · Planes", href: "#/metas" },
        { label: "Programas mensuales", href: "#/programas" },
        { label: "El método PACE", href: "#/metodo" },
      ],
    },
    {
      label: "El club",
      items: [
        { label: "Comunidad y horarios", href: "#/club" },
        { label: "Preguntas frecuentes", href: "#/faq" },
      ],
    },
  ];
  const links = [{ label: "Inicio", href: "#/" }].concat(groups[0].items, groups[1].items);
  return (
    <header className={"site-header" + (scrolled || route ? " scrolled" : "")}>
      <div
        className="wrap"
        style={{ height: 68, display: "flex", alignItems: "center", justifyContent: "space-between" }}
      >
        <a href="#/" aria-label="PACE Run Club">
          <img src="img/logo-blanco.png" alt="PACE Run Club" style={{ height: 26, width: "auto" }} />
        </a>
        <nav
          style={{ display: "flex", alignItems: "center", gap: 30 }}
          className="header-desktop-nav"
        >
          <a
            href="#/"
            className="link-grow"
            style={{ fontSize: 13, fontWeight: 600, color: route === "" ? "var(--cream)" : "rgba(244,239,233,0.85)" }}
          >
            Inicio
          </a>
          {groups.map((g) => (
            <NavDrop key={g.label} label={g.label} items={g.items} />
          ))}
          <a href="#/athletics" className="btn-athletics">
            Athletics <span className="new-pill">Nuevo</span>
          </a>
          <Magnetic strength={0.18}>
            <a
              href={PACE.waLink()}
              target="_blank"
              rel="noreferrer"
              className="btn btn-orange"
              style={{ padding: "11px 24px", fontSize: 13 }}
            >
              Inscribirme
            </a>
          </Magnetic>
        </nav>
        <button
          className="header-burger"
          onClick={() => setOpen(!open)}
          aria-label="Menú"
          style={{
            display: "none",
            flexDirection: "column",
            gap: 6,
            background: "none",
            border: "none",
            padding: 10,
            cursor: "pointer",
          }}
        >
          <span style={{ display: "block", width: 24, height: 2, background: "var(--cream)", transition: "transform .3s", transform: open ? "translateY(8px) rotate(45deg)" : "none" }}></span>
          <span style={{ display: "block", width: 24, height: 2, background: "var(--cream)", opacity: open ? 0 : 1, transition: "opacity .3s" }}></span>
          <span style={{ display: "block", width: 24, height: 2, background: "var(--cream)", transition: "transform .3s", transform: open ? "translateY(-8px) rotate(-45deg)" : "none" }}></span>
        </button>
      </div>
      {open && (
        <nav
          style={{
            background: "rgba(13,13,13,0.96)",
            backdropFilter: "blur(16px)",
            borderTop: "1px solid var(--line)",
            display: "flex",
            flexDirection: "column",
            gap: 4,
            padding: "18px 24px 26px",
          }}
        >
          {links.map((l) => (
            <a
              key={l.label}
              href={l.href}
              onClick={() => setOpen(false)}
              className="font-display"
              style={{ fontSize: 28, padding: "10px 0", color: "var(--cream)" }}
            >
              {l.label}
            </a>
          ))}
          <a
            href={PACE.waLink()}
            target="_blank"
            rel="noreferrer"
            className="btn btn-orange"
            style={{ marginTop: 12 }}
          >
            Inscribirme
          </a>
        </nav>
      )}
    </header>
  );
}

// ---- Hero ----
function Hero({ copy }) {
  const [ready, setReady] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setReady(true), 150);
    return () => clearTimeout(t);
  }, []);
  const c = PACE.heroCopies[copy] || PACE.heroCopies["No corres solo"];
  return (
    <section
      id="top"
      data-screen-label="Hero"
      className={"grain" + (ready ? " hero-ready" : "")}
      style={{
        position: "relative",
        minHeight: "100svh",
        display: "flex",
        alignItems: "flex-end",
        overflow: "hidden",
      }}
    >
      <div style={{ position: "absolute", inset: 0 }}>
        <img
          src="img/run-hero.jpg"
          alt="Comunidad PACE corriendo de noche"
          className="slow-zoom"
          style={{ width: "100%", height: "100%", objectFit: "cover" }}
        />
      </div>
      <div
        style={{
          position: "absolute",
          inset: 0,
          background:
            "linear-gradient(to top, #0D0D0D 4%, rgba(13,13,13,0.62) 42%, rgba(13,13,13,0.25) 100%)",
        }}
      ></div>

      <SpeedLines
        count={6}
        width={220}
        animate={true}
        style={{ right: "6%", top: "22%", transform: "rotate(-18deg)", zIndex: 2, opacity: 0.9 }}
      />

      <div
        className="wrap"
        style={{ position: "relative", zIndex: 2, width: "100%", paddingBottom: 96, paddingTop: 160 }}
      >
        <div
          className="hero-line"
          style={{ marginBottom: 26 }}
        >
          <span
            className="font-mono"
            style={{ fontSize: 12, color: "var(--orange)", transitionDelay: "0.1s" }}
          >
            Bogotá · 2.640 m de altura · Correr con sentido
          </span>
        </div>
        <h1
          className="font-display"
          style={{ fontSize: "clamp(64px, 11.5vw, 176px)", margin: "0 0 30px", color: "var(--cream)" }}
        >
          <span className="hero-line">
            <span style={{ transitionDelay: "0.25s" }}>{c.a}</span>
          </span>
          <span className="hero-line">
            <span style={{ transitionDelay: "0.4s", color: "var(--orange)" }}>{c.b}</span>
          </span>
        </h1>
        <div className="hero-line" style={{ marginBottom: 42 }}>
          <span
            style={{
              transitionDelay: "0.55s",
              fontSize: "clamp(17px, 1.8vw, 22px)",
              fontWeight: 300,
              color: "rgba(244,239,233,0.85)",
              maxWidth: 560,
              lineHeight: 1.55,
            }}
          >
            Planes de entrenamiento para cada meta — de tus primeros pasos a la maratón.
            Con coach real, comunidad real.
          </span>
        </div>
        <div
          className="rv in"
          style={{
            display: "flex",
            flexWrap: "wrap",
            gap: 16,
            opacity: ready ? 1 : 0,
            transition: "opacity 0.9s 0.75s",
          }}
        >
          <Magnetic>
            <a href="#/metas" className="btn btn-cream">
              Elige tu meta →
            </a>
          </Magnetic>
          <Magnetic>
            <a href={PACE.waLink()} target="_blank" rel="noreferrer" className="btn btn-ghost">
              Hablar con un coach
            </a>
          </Magnetic>
        </div>
      </div>
    </section>
  );
}

// ---- Stats band ----
function Stats() {
  const stats = [
    { end: 2640, suffix: "", label: "metros de altura. Bogotá nos hace fuertes" },
    { end: 5, suffix: "", label: "metas: de Start a maratón" },
    { end: 1, suffix: "", label: "sesión presencial: domingos en el Parque El Virrey" },
    { end: 100, suffix: "%", label: "acompañamiento real de tu coach" },
  ];
  return (
    <section style={{ background: "var(--ink)", borderBottom: "1px solid var(--line)" }}>
      <div
        className="wrap"
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(210px, 1fr))",
          gap: 0,
          padding: "0",
        }}
      >
        {stats.map((s, i) => (
          <Reveal
            key={i}
            delay={i * 90}
            style={{
              padding: "56px 28px",
              borderLeft: i > 0 ? "1px solid var(--line)" : "none",
            }}
          >
            <div className="stat-num" style={{ color: i === 3 ? "var(--orange)" : "var(--cream)" }}>
              <CountUp end={s.end} suffix={s.suffix} />
            </div>
            <p style={{ color: "var(--cream-faint)", fontSize: 14, marginTop: 14, lineHeight: 1.5 }}>
              {s.label}
            </p>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ---- Goal selector (sección de venta principal) ----
function GoalSelector() {
  const [active, setActive] = React.useState("21k");
  const [swap, setSwap] = React.useState(false);
  const goal = PACE.goals.find((g) => g.id === active);

  const pick = (id) => {
    if (id === active) return;
    setSwap(true);
    setTimeout(() => {
      setActive(id);
      setSwap(false);
    }, 220);
  };

  const idx = PACE.goals.findIndex((g) => g.id === active);

  return (
    <section
      id="metas"
      data-screen-label="Selector de meta"
      style={{ background: "var(--ink)", padding: "110px 0 130px", position: "relative" }}
    >
      <div className="wrap">
        <Reveal>
          <span className="font-mono" style={{ fontSize: 12, color: "var(--orange)" }}>
            Planes por objetivo
          </span>
          <h2
            className="font-display"
            style={{ fontSize: "clamp(44px, 6.5vw, 96px)", margin: "18px 0 0", color: "var(--cream)" }}
          >
            ¿Cuál es tu meta?
          </h2>
          <p style={{ color: "var(--cream-dim)", fontSize: 18, fontWeight: 300, maxWidth: 520, marginTop: 18, lineHeight: 1.6 }}>
            Elige tu distancia. Cada plan tiene semanas definidas, precio de lanzamiento y
            acompañamiento de coach incluido.
          </p>
        </Reveal>

        {/* Tabs */}
        <Reveal delay={120}>
          <div
            style={{
              display: "flex",
              borderBottom: "1px solid var(--line)",
              marginTop: 56,
              position: "relative",
            }}
          >
            {PACE.goals.map((g) => (
              <button
                key={g.id}
                className={"goal-tab" + (g.id === active ? " active" : "")}
                onClick={() => pick(g.id)}
              >
                <span className="km">{g.label}</span>
                <span className="goal-name">{g.goal}</span>
              </button>
            ))}
            {/* indicador */}
            <span
              style={{
                position: "absolute",
                bottom: -1,
                left: (idx * 100) / PACE.goals.length + "%",
                width: 100 / PACE.goals.length + "%",
                height: 3,
                background: "var(--orange)",
                transition: "left 0.5s cubic-bezier(0.22,1,0.36,1)",
              }}
            ></span>
          </div>
        </Reveal>

        {/* Panel */}
        <div className={"goal-panel" + (swap ? " swap" : "")}>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))",
              gap: 56,
              marginTop: 64,
              alignItems: "start",
            }}
          >
            <div>
              <h3
                className="font-display"
                style={{ fontSize: "clamp(36px, 4.5vw, 64px)", margin: 0, color: "var(--cream)" }}
              >
                {goal.name}
                {goal.popular && (
                  <span
                    className="font-mono"
                    style={{
                      fontSize: 10,
                      background: "var(--orange)",
                      color: "#fff",
                      padding: "6px 12px",
                      borderRadius: 99,
                      verticalAlign: "middle",
                      marginLeft: 18,
                      letterSpacing: "0.14em",
                    }}
                  >
                    El más pedido
                  </span>
                )}
              </h3>
              <p style={{ color: "var(--cream-dim)", fontSize: 17, fontWeight: 300, lineHeight: 1.65, marginTop: 22, maxWidth: 480 }}>
                {goal.desc}
              </p>
              <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "grid", gap: 12 }}>
                {goal.points.map((p) => (
                  <li key={p} style={{ display: "flex", alignItems: "center", gap: 14, color: "var(--cream)", fontSize: 15 }}>
                    <span style={{ width: 22, height: 5, borderRadius: 99, background: "var(--orange)", flexShrink: 0 }}></span>
                    {p}
                  </li>
                ))}
              </ul>
            </div>

            <div
              style={{
                border: "1px solid var(--line)",
                borderRadius: 24,
                padding: "40px 36px",
                background: "rgba(244,239,233,0.03)",
              }}
              className="card-hover"
            >
              <div style={{ display: "flex", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
                <span className="font-display" style={{ fontSize: 56, color: "var(--cream)" }}>
                  {PACE.cop(goal.founder)}
                </span>
                <span style={{ color: "var(--cream-faint)", textDecoration: "line-through", fontSize: 18 }}>
                  {PACE.cop(goal.regular)}
                </span>
              </div>
              <p className="font-mono" style={{ fontSize: 11, color: "var(--orange)", marginTop: 10 }}>
                Precio de lanzamiento · COP
              </p>
              <p style={{ fontSize: 13.5, color: "var(--cream-dim)", marginTop: 14, lineHeight: 1.5 }}>
                Equivale a ≈ {PACE.cop(Math.round(goal.founder / goal.weeks / 500) * 500)} por semana
                — menos que una sola sesión de personal trainer en Bogotá.
              </p>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  borderTop: "1px solid var(--line)",
                  marginTop: 28,
                  paddingTop: 24,
                  marginBottom: 30,
                }}
              >
                <div>
                  <span className="font-display" style={{ fontSize: 30, color: "var(--cream)", display: "block" }}>
                    {goal.weeks}
                  </span>
                  <span style={{ fontSize: 12, color: "var(--cream-faint)" }}>semanas</span>
                </div>
                <div>
                  <span className="font-display" style={{ fontSize: 30, color: "var(--cream)", display: "block" }}>
                    {goal.km}
                  </span>
                  <span style={{ fontSize: 12, color: "var(--cream-faint)" }}>tu meta</span>
                </div>
                <div>
                  <span className="font-display" style={{ fontSize: 30, color: "var(--cream)", display: "block" }}>
                    1:1
                  </span>
                  <span style={{ fontSize: 12, color: "var(--cream-faint)" }}>coach</span>
                </div>
              </div>
              <Magnetic strength={0.12}>
                <a
                  href={PACE.waLink("Hola, quiero empezar el plan " + goal.name)}
                  target="_blank"
                  rel="noreferrer"
                  className="btn btn-orange"
                  style={{ width: "100%" }}
                >
                  Empezar {goal.label} →
                </a>
              </Magnetic>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Header, Hero, Stats, GoalSelector });
