/* global React, h, Icons, Btn, Chip, StatusBadge, Eyebrow, SectionHeader, ImagePanel, SPECIES, STATS, NAV */
// ============================================================================
// BioBits.CL — Sections (top): Nav, Hero, StatBand, Proyecto, Especies
// ============================================================================
const { useState, useEffect } = React;

// ---- NAV ------------------------------------------------------------------
function Nav({ active, onNav, onMenu }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll); onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return h("header", { className: `bb-nav${scrolled ? " scrolled" : ""}` },
    h("div", { className: "bb-container bb-nav-inner" },
      h("a", { className: "bb-nav-logo", href: "#inicio", onClick: (e) => { e.preventDefault(); onNav("inicio"); } },
        h("img", { src: "assets/isotipo.png", alt: "BioBits" }),
        h("img", { src: "assets/logotipo-biobits.png", alt: "BioBits", style: { height: "18px" } })
      ),
      h("nav", { className: "bb-nav-links" },
        NAV.map((n) => h("a", {
          key: n.id, href: "#" + n.id,
          className: `bb-nav-link${active === n.id ? " active" : ""}`,
          onClick: (e) => { e.preventDefault(); onNav(n.id); },
        }, n.label))
      ),
      h("div", { style: { display: "flex", alignItems: "center", gap: "10px" } },
        h("div", { style: { display: window.innerWidth > 940 ? "block" : "none" } },
          h(Btn, { variant: "ghost", size: "sm", iconRight: "arrowRight", onClick: () => onNav("especies") }, "Explorar especies")),
        h("button", { className: "bb-nav-burger", onClick: onMenu, "aria-label": "Menú" }, h(Icons.menu, { size: 22 }))
      )
    )
  );
}

// ---- HERO -----------------------------------------------------------------
function Hero({ onNav }) {
  return h("section", { id: "inicio", className: "bb-hero" },
    h("div", { className: "bb-container" },
     h("div", { className: "bb-hero-grid" },
      // left — copy
      h("div", null,
        h("div", { style: { marginBottom: "22px" } }, h(Eyebrow, null, "Ciencia Salvaje × IA")),
        h("h1", { className: "bb-display" },
          h("span", { className: "bb-glitch" }, "Fauna chilena,"), h("br"),
          h("span", { className: "bb-gradient-text" }, "decodificada.")
        ),
        h("p", { className: "bb-body-lg", style: { marginTop: "26px", maxWidth: "540px" } },
          "BioBits convierte especies nativas en experiencias digitales de alto impacto: datos científicos verificados, relatos breves y visuales IA con estética Andean Glitch para descubrir, entender y proteger la biodiversidad de Chile."),
        h("div", { style: { display: "flex", gap: "12px", marginTop: "34px", flexWrap: "wrap" } },
          h(Btn, { variant: "accent", size: "lg", iconRight: "arrowRight", onClick: () => onNav("especies") }, "Explorar especies"),
          h(Btn, { variant: "ghost", size: "lg", icon: "play", onClick: () => onNav("metodologia") }, "Ver contenido")
        ),
        h("div", { style: { display: "flex", gap: "10px", marginTop: "30px", flexWrap: "wrap" } },
          h(Chip, { variant: "cyan", dot: true }, "Datos verificados"),
          h(Chip, { variant: "neutral" }, "Especies endémicas"),
          h(Chip, { variant: "neutral" }, "Andean Glitch")
        )
      ),
      // right — fox visual
      h("div", { className: "bb-hero-visual" },
        h("div", { className: "bb-reticle" }),
        h("div", { className: "bb-hero-fox" }, h("img", { src: "assets/isotipo.png", alt: "Isotipo BioBits — zorro mitad orgánico, mitad circuito" })),
        h("div", { className: "bb-hero-readout", style: { top: "4%", left: "0" } }, "SYS // CHILE_SALVAJE"),
        h("div", { className: "bb-hero-readout", style: { top: "4%", right: "0", color: "var(--lime)" } }, "REC ●"),
        h("div", { className: "bb-hero-readout", style: { bottom: "4%", left: "0" } }, "LAT −33.4° / LON −70.6°"),
        h("div", { className: "bb-hero-readout", style: { bottom: "4%", right: "0" } }, "BIO ▸ BITS")
      )
    )
    )
  );
}

// ---- STAT BAND ------------------------------------------------------------
function StatBand() {
  return h("section", { className: "bb-container", style: { marginTop: "12px" } },
    h("div", { className: "bb-statband bb-hud" },
      STATS.map((s, i) => h("div", { key: i, className: "bb-stat" },
        h("div", { className: "num" }, s.num),
        h("div", { className: "lbl" }, s.lbl)
      ))
    )
  );
}

// ---- PROYECTO -------------------------------------------------------------
function Proyecto() {
  return h("section", { id: "proyecto", className: "bb-section" },
    h("div", { className: "bb-container", style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--sp-7)", alignItems: "center" } },
      h("div", null,
        h(SectionHeader, {
          eyebrow: "El proyecto",
          title: "Ciencia visual para la fauna nativa",
          intro: "BioBits es una plataforma de ciencia visual enfocada en fauna chilena. Mezclamos investigación, storytelling y herramientas de inteligencia artificial para producir contenido atractivo, riguroso y memorable.",
        }),
        h("p", { className: "bb-body", style: { marginTop: "20px", maxWidth: "560px" } },
          "Cada pieza busca una doble meta: fascinar con la complejidad biológica de las especies nativas y aumentar el valor cultural de su conservación. Chile concentra una fauna extraordinaria marcada por el endemismo, desde el desierto hasta los bosques templados y la costa de la Corriente de Humboldt."),
        h("div", { style: { display: "flex", gap: "28px", marginTop: "32px", flexWrap: "wrap" } },
          [["Asombro visual", "globe"], ["Precisión científica", "data"], ["Narrativa breve", "film"]].map(([t, ic], i) =>
            h("div", { key: i, style: { display: "flex", alignItems: "center", gap: "10px" } },
              h(Icons[ic], { size: 18, style: { color: "var(--cyan)" } }),
              h("span", { className: "bb-mono", style: { fontSize: "13px", color: "var(--fg-0)" } }, t)
            ))
        )
      ),
      h(ImagePanel, { slotId: "proyecto-visual", placeholder: "Collage hero de fauna chilena · Andean Glitch", style: { aspectRatio: "4/3", borderRadius: "var(--r-md)" } },
        h("div", { style: { position: "absolute", left: "14px", bottom: "14px", display: "flex", gap: "8px", flexWrap: "wrap" } },
          h(Chip, { variant: "cyan" }, "Bosque templado"),
          h(Chip, { variant: "cyan" }, "Costa Humboldt"),
          h(Chip, { variant: "cyan" }, "Cordillera")
        )
      )
    )
  );
}

// ---- ESPECIES -------------------------------------------------------------
function SpeciesCard({ sp, onOpen }) {
  return h("article", { className: "bb-card", onClick: () => onOpen(sp) },
    h("div", { className: "bb-card-media" },
      h("image-slot", { id: sp.slot, placeholder: sp.img, shape: "rect", src: `assets/species/${sp.id}.jpg`, style: { width: "100%", height: "100%" } }),
      h("div", { className: "scrim" }),
      h("div", { className: "topbar" },
        h(StatusBadge, { code: sp.status }),
        sp.priority && h(Chip, { variant: "lime", dot: true }, "Prioridad")
      )
    ),
    h("div", { className: "bb-card-body" },
      h("div", { className: "bb-card-sci" }, sp.sci),
      h("h3", { className: "bb-h3 bb-card-name" }, sp.name),
      h("p", { className: "bb-body-sm bb-card-hook", style: { color: "var(--fg-1)" } }, sp.hook),
      h("div", { className: "bb-card-data" },
        h("div", null,
          h("div", { className: "k" }, sp.keyStat.k),
          h("div", { className: "v" }, sp.keyStat.v)
        ),
        h(Icons.arrowUpRight, { size: 20, className: "arrow" })
      )
    )
  );
}

function Especies({ onOpen }) {
  const ecos = ["Todos", "Bosque templado", "Cordillera / costa", "Costa / océano"];
  const [filter, setFilter] = useState("Todos");
  const list = SPECIES.filter((s) => filter === "Todos" || s.eco === filter);
  return h("section", { id: "especies", className: "bb-section", style: { background: "var(--bg-1)", borderBlock: "1px solid var(--line)" } },
    h("div", { className: "bb-container" },
      h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: "24px", marginBottom: "var(--sp-6)" } },
        h(SectionHeader, {
          eyebrow: "Biblioteca de especies",
          title: "Especies del proyecto",
          intro: "El núcleo editorial de BioBits. Una biblioteca escalable de fauna nativa con ficha técnica, comportamiento invisible y estado de conservación.",
        }),
        h("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap" } },
          ecos.map((e) => h("button", {
            key: e, onClick: () => setFilter(e),
            className: filter === e ? "bb-btn bb-btn--ghost bb-btn--sm" : "bb-btn bb-btn--subtle bb-btn--sm",
          }, e))
        )
      ),
      h("div", { className: "bb-species-grid" },
        list.map((sp) => h(SpeciesCard, { key: sp.id, sp, onOpen }))
      )
    )
  );
}

Object.assign(window, { Nav, Hero, StatBand, Proyecto, Especies, SpeciesCard });
