/* global React, h, Icons, Btn, Chip, StatusBadge, Eyebrow, SectionHeader, ImagePanel, SPECIES, PILLARS, PIPELINE, THREATS */
// ============================================================================
// BioBits.CL — Sections (bottom): Pilares, Mito/Realidad, Conservación,
// Metodología, Rigor, Contacto, Footer + Species modal
// ============================================================================
const { useState: useStateB } = React;

// ---- PILARES --------------------------------------------------------------
function Pilares() {
  return h("section", { className: "bb-section", style: { paddingBottom: "var(--sp-9)" } },
    h("div", { className: "bb-container" },
      h(SectionHeader, { eyebrow: "Línea editorial", title: "Cuatro pilares de contenido",
        intro: "Cada especie se cuenta desde estos cuatro ángulos editoriales. Así convertimos biología dura en narrativa visual." }),
      h("div", { className: "bb-pillars", style: { marginTop: "var(--sp-6)" } },
        PILLARS.map((p) => h("div", { key: p.idx, className: "bb-pillar bb-hud" },
          h("div", { className: "idx" }, p.idx),
          h(Icons[p.icon], { className: "ico", size: 30 }),
          h("h3", { className: "bb-h4", style: { marginBottom: "10px" } }, p.name),
          h("p", { className: "bb-body-sm" }, p.desc)
        ))
      )
    )
  );
}

// ---- MITO VS REALIDAD -----------------------------------------------------
function MitoRealidad() {
  const cases = SPECIES.filter((s) => s.myth);
  const [active, setActive] = useStateB(0);
  const c = cases[active];
  return h("section", { className: "bb-section", style: { background: "var(--bg-1)", borderBlock: "1px solid var(--line)" } },
    h("div", { className: "bb-container" },
      h(SectionHeader, { eyebrow: "Desinformación", title: "Mito vs. Realidad",
        intro: "La desinformación es una amenaza concreta para algunas especies. Desmontamos los mitos con evidencia." }),
      h("div", { style: { display: "flex", gap: "8px", margin: "var(--sp-5) 0 var(--sp-6)", flexWrap: "wrap" } },
        cases.map((cc, i) => h("button", {
          key: cc.id, onClick: () => setActive(i),
          className: i === active ? "bb-btn bb-btn--ghost bb-btn--sm" : "bb-btn bb-btn--subtle bb-btn--sm",
        }, cc.name))
      ),
      h("div", { className: "bb-myth" },
        h("div", { className: "bb-myth-col mito" },
          h("div", { className: "bb-myth-label" }, h(Icons.x, { size: 16 }), "El mito"),
          h("p", { className: "bb-body-lg", style: { marginTop: "16px", color: "var(--fg-0)" } }, c.myth.mito)
        ),
        h("div", { className: "bb-myth-col real" },
          h("div", { className: "bb-myth-label" }, h(Icons.check, { size: 16 }), "La realidad"),
          h("p", { className: "bb-body-lg", style: { marginTop: "16px", color: "var(--fg-0)" } }, c.myth.real)
        )
      )
    )
  );
}

// ---- CONSERVACIÓN ---------------------------------------------------------
function Conservacion() {
  return h("section", { id: "conservacion", className: "bb-section" },
    h("div", { className: "bb-container" },
      h(SectionHeader, { eyebrow: "Por qué importa", title: "Amenazas transversales",
        intro: "Conectamos la narrativa visual con el impacto real sobre la fauna chilena: hábitat, océano, especies invasoras, conflicto y desinformación." }),
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: "var(--sp-4)", marginTop: "var(--sp-6)" } },
        THREATS.map((t, i) => h("div", { key: i, className: "bb-pillar", style: { display: "flex", gap: "16px", alignItems: "flex-start" } },
          h("div", { style: { flex: "none", width: "44px", height: "44px", display: "grid", placeItems: "center", borderRadius: "var(--r-sm)", background: "var(--cyan-tint)", color: "var(--cyan)", boxShadow: "inset 0 0 0 1px var(--line-cyan)" } },
            h(Icons[t.icon], { size: 22 })),
          h("div", null,
            h("h3", { className: "bb-h4", style: { marginBottom: "6px" } }, t.name),
            h("p", { className: "bb-body-sm" }, t.desc)
          )
        ))
      ),
      h("div", { className: "bb-hud", style: { marginTop: "var(--sp-6)", padding: "var(--sp-6)", background: "linear-gradient(120deg, rgba(112,0,255,0.10), transparent 60%), var(--bg-1)", border: "1px solid var(--line-cyan)", borderRadius: "var(--r-md)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: "24px", flexWrap: "wrap" } },
        h("div", null,
          h("h3", { className: "bb-h3", style: { marginBottom: "8px" } }, "Hagamos visible la fauna chilena"),
          h("p", { className: "bb-body", style: { maxWidth: "520px" } }, "Súmate como educador, documentalista, institución o creador. La conservación empieza por verla distinto.")
        ),
        h(Btn, { variant: "accent", size: "lg", iconRight: "arrowRight", onClick: () => document.getElementById("contacto").scrollIntoView() }, "Colaborar con BioBits")
      )
    )
  );
}

// ---- METODOLOGÍA ----------------------------------------------------------
function Metodologia() {
  return h("section", { id: "metodologia", className: "bb-section", style: { background: "var(--bg-1)", borderBlock: "1px solid var(--line)" } },
    h("div", { className: "bb-container" },
      h(SectionHeader, { eyebrow: "Cómo lo hacemos", title: "Del dato al reel",
        intro: "Un flujo híbrido entre divulgación científica y diseño digital. Cada dato se verifica antes de publicarse." }),
      h("div", { className: "bb-pipe", style: { marginTop: "var(--sp-7)" } },
        PIPELINE.map((s) => h("div", { key: s.n, className: "bb-pipe-step" },
          h("div", { className: "line" }),
          h("div", { className: "n" }, s.n),
          h(Icons[s.icon], { size: 22, style: { color: "var(--cyan)", marginTop: "18px" } }),
          h("h3", { className: "bb-h4", style: { marginTop: "12px", marginBottom: "6px" } }, s.name),
          h("p", { className: "bb-body-sm", style: { paddingRight: "16px" } }, s.desc)
        ))
      ),
      h("div", { className: "bb-hud", style: { marginTop: "var(--sp-7)", padding: "var(--sp-5) var(--sp-6)", background: "var(--bg-0)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", display: "flex", gap: "14px", alignItems: "center" } },
        h(Icons.shield, { size: 26, style: { color: "var(--lime)", flex: "none" } }),
        h("p", { className: "bb-body", style: { color: "var(--fg-0)" } },
          h("strong", { style: { color: "var(--lime)", fontFamily: "var(--font-mono)", fontSize: "13px", letterSpacing: "0.08em", textTransform: "uppercase", marginRight: "10px" } }, "Rigor editorial"),
          "Todos los datos se verifican con fuentes científicas y oficiales antes de su publicación.")
      )
    )
  );
}

// ---- CONTACTO -------------------------------------------------------------
function Contacto() {
  // status: 'idle' | 'sending' | 'sent' | 'error'
  const [status, setStatus] = useStateB('idle');
  const [errMsg, setErrMsg] = useStateB('');

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus('sending');
    setErrMsg('');

    const form = e.target;
    const data = {
      nombre: form.nombre.value.trim(),
      email: form.email.value.trim(),
      tipo: form.tipo.value,
      mensaje: form.mensaje.value.trim(),
    };

    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || 'Error al enviar');
      setStatus('sent');
    } catch (err) {
      setErrMsg(err.message || 'No se pudo enviar. Intenta de nuevo.');
      setStatus('error');
    }
  }

  return h("section", { id: "contacto", className: "bb-section" },
    h("div", { className: "bb-container", style: { display: "grid", gridTemplateColumns: "0.9fr 1.1fr", gap: "var(--sp-7)" } },
      h("div", null,
        h(SectionHeader, { eyebrow: "Contacto / Colaboraciones", title: "Entra al laboratorio BioBits",
          intro: "Abrimos espacio a alianzas con educadores, documentalistas, organizaciones de conservación, instituciones públicas y creadores de ciencia y tecnología." }),
        h("div", { style: { marginTop: "var(--sp-6)", display: "flex", flexDirection: "column", gap: "14px" } },
          [["instagram", "@biobits.cl"], ["youtube", "BioBits"], ["tiktok", "@biobits.cl"]].map(([ic, t], i) =>
            h("a", { key: i, href: "#", style: { display: "flex", alignItems: "center", gap: "12px", color: "var(--fg-1)" } },
              h(Icons[ic], { size: 20, style: { color: "var(--cyan)" } }),
              h("span", { className: "bb-mono", style: { fontSize: "14px" } }, t)
            ))
        )
      ),
      h("form", { className: "bb-hud", onSubmit: handleSubmit,
        style: { background: "var(--bg-1)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: "var(--sp-6)", display: "flex", flexDirection: "column", gap: "var(--sp-4)" } },
        status === 'sent'
          ? h("div", { style: { textAlign: "center", padding: "var(--sp-7) 0" } },
              h(Icons.check, { size: 40, style: { color: "var(--lime)", margin: "0 auto 16px" } }),
              h("h3", { className: "bb-h3" }, "Mensaje enviado"),
              h("p", { className: "bb-body", style: { marginTop: "8px" } }, "Gracias por escribir a BioBits. Te responderemos pronto a tu correo."))
          : [
              h("div", { key: "g", style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--sp-4)" } },
                h("div", { className: "bb-field" }, h("label", { className: "bb-label" }, "Nombre"), h("input", { name: "nombre", className: "bb-input", placeholder: "Tu nombre", required: true, disabled: status === 'sending' })),
                h("div", { className: "bb-field" }, h("label", { className: "bb-label" }, "Email"), h("input", { name: "email", className: "bb-input", type: "email", placeholder: "tu@correo.cl", required: true, disabled: status === 'sending' }))
              ),
              h("div", { key: "t", className: "bb-field" },
                h("label", { className: "bb-label" }, "Tipo de colaboración"),
                h("select", { name: "tipo", className: "bb-select", disabled: status === 'sending' }, ["Editorial / campaña", "Educación", "Institución / ONG", "Prensa", "Otra"].map((o) => h("option", { key: o, value: o }, o)))
              ),
              h("div", { key: "m", className: "bb-field" },
                h("label", { className: "bb-label" }, "Mensaje"),
                h("textarea", { name: "mensaje", className: "bb-textarea", placeholder: "Cuéntanos qué quieres construir con BioBits…", required: true, disabled: status === 'sending' })
              ),
              status === 'error' && h("div", { key: "e", style: { padding: "12px 16px", background: "rgba(255,77,109,0.12)", border: "1px solid rgba(255,77,109,0.3)", borderRadius: "var(--r-sm)", color: "#FF4D6D", fontFamily: "var(--font-mono)", fontSize: "12px", letterSpacing: "0.06em" } },
                "⚠ ", errMsg),
              h(Btn, { key: "b", variant: "accent", iconRight: "send", type: "submit", disabled: status === 'sending' },
                status === 'sending' ? "Enviando…" : "Enviar mensaje")
            ]
      )
    )
  );
}

// ---- FOOTER ---------------------------------------------------------------
function Footer({ onNav }) {
  return h("footer", { className: "bb-footer" },
    h("div", { className: "bb-container" },
      h("div", { className: "bb-footer-grid" },
        h("div", null,
          h("img", { src: "assets/logotipo-biobits.png", alt: "BioBits", style: { height: "26px", marginBottom: "16px" } }),
          h("p", { className: "bb-body-sm", style: { maxWidth: "320px" } }, "Fauna chilena, ciencia visual y conservación. Ciencia Salvaje × IA."),
          h("div", { style: { display: "flex", gap: "12px", marginTop: "18px" } },
            ["instagram", "youtube", "tiktok"].map((ic) => h("a", { key: ic, href: "#", style: { color: "var(--fg-2)" } }, h(Icons[ic], { size: 20 })))
          )
        ),
        h("div", null, h("div", { className: "bb-foot-h" }, "Navegar"),
          ["inicio", "proyecto", "especies"].map((id) => h("a", { key: id, className: "bb-foot-link", href: "#" + id, onClick: (e) => { e.preventDefault(); onNav(id); } }, id[0].toUpperCase() + id.slice(1)))),
        h("div", null, h("div", { className: "bb-foot-h" }, "Más" ),
          ["conservacion", "metodologia", "contacto"].map((id) => h("a", { key: id, className: "bb-foot-link", href: "#" + id, onClick: (e) => { e.preventDefault(); onNav(id); } }, id[0].toUpperCase() + id.slice(1)))),
        h("div", null, h("div", { className: "bb-foot-h" }, "Especies"),
          SPECIES.slice(0, 5).map((s) => h("a", { key: s.id, className: "bb-foot-link", href: "#especies" }, s.name)))
      ),
      h("div", { className: "bb-divider", style: { margin: "var(--sp-6) 0 var(--sp-5)" } }),
      h("div", { style: { display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: "12px" } },
        h("span", { className: "bb-caption", style: { fontFamily: "var(--font-mono)" } }, "© 2026 BioBits.CL — Chile Salvaje"),
        h("span", { className: "bb-caption", style: { fontFamily: "var(--font-mono)" } }, "Datos verificados con fuentes científicas y oficiales")
      )
    )
  );
}

// ---- REEL VIDEO MAP -------------------------------------------------------
// BunnyCDN iframe URLs por especie
const SPECIES_REELS = {
  ranita: "https://player.mediadelivery.net/embed/675234/9d556842-00ee-4c89-9bbc-fb6df9603cc9?autoplay=true&loop=false&muted=true&preload=true&responsive=true",
};

// ---- REEL MODAL (glitch video player) ------------------------------------
function ReelModal({ sp, onClose }) {
  const videoSrc = SPECIES_REELS[sp.id];
  return h("div", { className: "bb-reel-scrim", onClick: onClose },
    h("div", { className: "bb-reel-player", onClick: (e) => e.stopPropagation() },
      // HUD overlays
      h("div", { className: "bb-reel-scanlines" }),
      h("div", { className: "bb-reel-scan-beam" }),
      h("div", { className: "bb-reel-vignette" }),
      // HUD corners
      h("div", { className: "bb-reel-corners" },
        h("svg", { className: "reel-corner tl", viewBox: "0 0 44 44" }, h("path", { d: "M0 40 L0 0 L40 0" })),
        h("svg", { className: "reel-corner tr", viewBox: "0 0 44 44" }, h("path", { d: "M4 0 L44 0 L44 40" })),
        h("svg", { className: "reel-corner bl", viewBox: "0 0 44 44" }, h("path", { d: "M0 4 L0 44 L40 44" })),
        h("svg", { className: "reel-corner br", viewBox: "0 0 44 44" }, h("path", { d: "M4 44 L44 44 L44 4" }))
      ),
      // HUD top
      h("div", { className: "bb-reel-hud-top" },
        h("span", { className: "bb-reel-sys" }, `SYS // ${sp.id.toUpperCase()} · REEL_01`),
        h("span", { className: "bb-reel-rec" }, h("span", { className: "bb-reel-dot" }, "●"), " REC")
      ),
      // Video iframe (BunnyCDN) or placeholder
      h("div", { className: "bb-reel-video-wrap" },
        videoSrc
          ? h("iframe", {
              className: "bb-reel-iframe",
              src: videoSrc,
              loading: "eager",
              allow: "accelerometer;gyroscope;autoplay;encrypted-media;picture-in-picture;fullscreen",
              allowFullScreen: true,
            })
          : h("div", { className: "bb-reel-soon" },
              h("div", { className: "bb-reel-soon-icon" }, h(Icons.film, { size: 40 })),
              h("div", { className: "bb-reel-soon-txt" }, "REEL EN PRODUCCIÓN"),
              h("div", { className: "bb-reel-soon-sub" }, sp.name + " · próximamente")
            )
      ),
      // HUD bottom
      h("div", { className: "bb-reel-hud-bot" },
        h("span", { className: "bb-reel-sys" }, sp.sci),
        h("span", { className: "bb-reel-sys" }, "BIO ▸ BITS")
      ),
      // Close button
      h("button", { className: "bb-reel-close", onClick: onClose }, h(Icons.x, { size: 18 }))
    )
  );
}

// ---- SPECIES MODAL --------------------------------------------------------
function SpeciesModal({ sp, onClose }) {
  const [showReel, setShowReel] = React.useState(false);
  if (!sp) return null;
  return h(React.Fragment, null,
    h("div", { className: "bb-modal-scrim", onClick: onClose },
      h("div", { className: "bb-modal", onClick: (e) => e.stopPropagation() },
        h("div", { style: { position: "relative" } },
          h("div", { className: "bb-imgpanel", style: { aspectRatio: "16/7" } },
            h("image-slot", { id: sp.slot, placeholder: sp.img, shape: "rect", src: `assets/species/${sp.id}.jpg`, style: { width: "100%", height: "100%" } }),
            h("div", { style: { position: "absolute", inset: 0, background: "linear-gradient(to top, var(--bg-1), transparent 60%)" } })
          ),
          h("button", { onClick: onClose, style: { position: "absolute", top: "14px", right: "14px", width: "38px", height: "38px", borderRadius: "var(--r-sm)", background: "rgba(8,8,9,0.6)", color: "var(--fg-0)", display: "grid", placeItems: "center", boxShadow: "inset 0 0 0 1px var(--line)" } }, h(Icons.x, { size: 18 })),
          h("div", { style: { position: "absolute", left: "var(--sp-6)", bottom: "var(--sp-5)", display: "flex", gap: "10px", alignItems: "center" } },
            h(StatusBadge, { code: sp.status }),
            h(Chip, { variant: "neutral" }, sp.pillar)
          )
        ),
        h("div", { style: { padding: "var(--sp-6)" } },
          h("div", { className: "bb-card-sci", style: { fontSize: "13px" } }, sp.sci),
          h("h2", { className: "bb-h2", style: { marginTop: "4px" } }, sp.name),
          h("p", { className: "bb-body-lg", style: { marginTop: "16px" } }, sp.intro),
          h("div", { style: { marginTop: "var(--sp-6)" } },
            h("div", { className: "bb-mono-tag", style: { marginBottom: "14px" } }, "// Ficha técnica"),
            h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: "1px", background: "var(--line)", border: "1px solid var(--line)" } },
              sp.data.map((d, i) => h("div", { key: i, style: { background: "var(--bg-0)", padding: "16px" } },
                h("div", { style: { fontFamily: "var(--font-mono)", fontSize: "10.5px", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-2)" } }, d.k),
                h("div", { style: { fontFamily: "var(--font-mono)", fontSize: "16px", color: "var(--lime)", marginTop: "6px" } }, d.v)
              ))
            )
          ),
          h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--sp-4)", marginTop: "var(--sp-5)" } },
            h("div", { style: { padding: "var(--sp-5)", background: "var(--bg-0)", borderRadius: "var(--r-sm)", boxShadow: "inset 0 0 0 1px var(--line)" } },
              h("div", { className: "bb-myth-label", style: { color: "var(--cyan)" } }, h(Icons.eye, { size: 15 }), "Comportamiento invisible"),
              h("p", { className: "bb-body-sm", style: { marginTop: "12px", color: "var(--fg-0)" } }, sp.invisible)),
            h("div", { style: { padding: "var(--sp-5)", background: "var(--bg-0)", borderRadius: "var(--r-sm)", boxShadow: "inset 0 0 0 1px var(--line)" } },
              h("div", { className: "bb-myth-label", style: { color: "var(--status-en)" } }, h(Icons.alert, { size: 15 }), "Amenazas"),
              h("p", { className: "bb-body-sm", style: { marginTop: "12px", color: "var(--fg-0)" } }, sp.threat))
          ),
          sp.myth && h("div", { style: { marginTop: "var(--sp-4)", padding: "var(--sp-5)", background: "linear-gradient(120deg, var(--cyan-tint), transparent)", borderRadius: "var(--r-sm)", boxShadow: "inset 0 0 0 1px var(--line-cyan)" } },
            h("div", { className: "bb-mono-tag" }, "// Mito vs. realidad"),
            h("p", { className: "bb-body-sm", style: { marginTop: "10px" } }, h("strong", { style: { color: "var(--danger)" } }, "Mito: "), sp.myth.mito),
            h("p", { className: "bb-body-sm", style: { marginTop: "6px" } }, h("strong", { style: { color: "var(--cyan)" } }, "Realidad: "), sp.myth.real)
          ),
          h("div", { style: { marginTop: "var(--sp-6)", display: "flex", gap: "12px", flexWrap: "wrap" } },
            h(Btn, { variant: "accent", iconRight: "film", onClick: () => setShowReel(true) }, "Ver reels"),
            h(Btn, { variant: "ghost", onClick: onClose }, "Cerrar ficha")
          )
        )
      )
    ),
    showReel && h(ReelModal, { sp, onClose: () => setShowReel(false) })
  );
}

Object.assign(window, { Pilares, MitoRealidad, Conservacion, Metodologia, Contacto, Footer, SpeciesModal });
