/* global React, ReactDOM */
/* /products/academy — self-contained bundle (shared + page) */

const { useState, useEffect } = React;

/* ── Appearance ─────────────────────────────────────────────────────────── */
function applyPersistedAppearance() {
  const theme   = localStorage.getItem("cs_theme")   || "dark";
  const bg      = localStorage.getItem("cs_bg")      || "mist";
  const display = localStorage.getItem("cs_display") || "apple";
  document.documentElement.setAttribute("data-theme",   theme);
  document.documentElement.setAttribute("data-bg",      bg);
  document.documentElement.setAttribute("data-display", display);
}
applyPersistedAppearance();

function useAppearance() {
  const [theme, setTheme] = useState(() => localStorage.getItem("cs_theme") || "dark");
  const [lang,  setLang]  = useState(() => localStorage.getItem("cs_lang")  || "en");
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("cs_theme", theme);
  }, [theme]);
  useEffect(() => {
    document.documentElement.lang = lang;
    localStorage.setItem("cs_lang", lang);
  }, [lang]);
  return { theme, setTheme, lang, setLang };
}

/* ── Icons ──────────────────────────────────────────────────────────────── */
const PIcon = {
  arrow:    () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 8h8M9 5l3 3-3 3"/></svg>,
  external: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M7 3H3v10h10V9"/><path d="M9 3h4v4M13 3L7 9"/></svg>,
  sun:      () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4l1.4-1.4M17 7l1.4-1.4"/></svg>,
  moon:     () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/></svg>,
};

function ThemeToggle({ theme, setTheme }) {
  const isDark = theme === "dark";
  return (
    <button type="button" className="theme-toggle"
      aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
      aria-pressed={isDark} onClick={() => setTheme(isDark ? "light" : "dark")}>
      <span className="theme-toggle-track">
        <span className="theme-toggle-thumb" data-mode={isDark ? "dark" : "light"}>
          {isDark ? <PIcon.moon /> : <PIcon.sun />}
        </span>
      </span>
    </button>
  );
}

/* ── Nav ────────────────────────────────────────────────────────────────── */
function ProductNav({ lang, setLang, theme, setTheme }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 4);
    window.addEventListener("scroll", on, { passive: true });
    on();
    return () => window.removeEventListener("scroll", on);
  }, []);
  const t = window.I18N[lang];
  return (
    <header className={"nav" + (scrolled ? " is-scrolled" : "")}>
      <div className="wrap nav-inner">
        <a href="/" className="brand">
          <img src="/assets/clowdsecops-logo.png" alt="ClowdSecOps" />
        </a>
        <nav className="nav-links">
          <a href="/products" className="is-active">{t.nav.products || "Productos"}</a>
          <a href="/services">{t.nav.services}</a>
          <a href="/why">{t.nav.why}</a>
          <a href="/process">{t.nav.process}</a>
          <a href="/stack">{t.nav.stack}</a>
          <a href="/faq">{t.nav.faq}</a>
          <a href="/blog">{t.nav.blog || "Blog"}</a>
        </nav>
        <div className="nav-cta">
          <ThemeToggle theme={theme} setTheme={setTheme} />
          <div className="lang" role="group" aria-label="Language">
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
            <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
          </div>
          <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-primary btn-sm"
            onClick={() => window.gtmEvent('book_demo', { source: 'nav' })}>
            {t.nav.book}<span className="arrow"><PIcon.arrow /></span>
          </a>
        </div>
      </div>
    </header>
  );
}

/* ── Footer ─────────────────────────────────────────────────────────────── */
function ProductFooter({ lang }) {
  const t = window.I18N[lang];
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-col">
            <a href="/" className="brand" style={{ marginBottom: 14 }}>
              <img src="/assets/clowdsecops-logo.png" alt="ClowdSecOps" />
            </a>
            <p style={{ color: "var(--ink-3)", fontSize: 14, maxWidth: 320, marginTop: 8 }}>{t.footer.tagline}</p>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_company}</h5>
            <ul>
              <li><a href="/why">{t.nav.why}</a></li>
              <li><a href="/process">{t.nav.process}</a></li>
              <li><a href="/faq">{t.nav.faq}</a></li>
              <li><a href="/blog">{t.nav.blog || "Blog"}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>{t.nav.products || "Productos"}</h5>
            <ul>
              <li><a href="/products/atlas">Atlas CNAPP</a></li>
              <li><a href="/products/academy">ClowdAcademy</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_services}</h5>
            <ul>
              {t.services.items.map(s => <li key={s.title}><a href="/services">{s.title}</a></li>)}
            </ul>
          </div>
          <div className="footer-col">
            <h5>{t.footer.col_contact}</h5>
            <ul>
              <li><a href="mailto:info@clowdsecops.com">info@clowdsecops.com</a></li>
              <li><a href="tel:+34677414674">+34 677 414 674</a></li>
              <li>{t.footer.hours}</li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>{t.footer.copyright}</span>
          <span style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
            <span>{t.footer.built}</span>
            <span style={{ color: 'var(--border-strong)' }}>·</span>
            <a href="/cookies" style={{ color: 'var(--ink-3)' }}>{lang === 'es' ? 'Política de cookies' : 'Cookie policy'}</a>
            <a href="/privacy" style={{ color: 'var(--ink-3)' }}>{lang === 'es' ? 'Privacidad' : 'Privacy'}</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

/* ── Page data ──────────────────────────────────────────────────────────── */
const ENTERPRISE_ES = {
  badge: "Para equipos · En preparación",
  title: "Certifica a tu equipo en ATLAS",
  sub: "El programa oficial de formación para organizaciones que operan Atlas. Rutas por rol, certificados verificables y seguimiento de progreso para todo el equipo.",
  items: [
    "Rutas de certificación por rol: Security Analyst, Cloud Engineer, Compliance Officer",
    "Certificados con QR verificable — shareables en LinkedIn",
    "Panel de administración para seguimiento del equipo completo",
    "Formación en cloud security, IaC, FinOps y compliance dentro de Atlas",
    "Integración nativa con el ecosistema ClowdSecOps",
  ],
  roles: [
    { icon: "\u{1F6E1}️", label: "Security Analyst" },
    { icon: "⚙️",   label: "Cloud Engineer" },
    { icon: "\u{1F4CB}",      label: "Compliance Officer" },
    { icon: "\u{1F4B0}",      label: "FinOps Specialist" },
  ],
  cta: "Unirse a la lista de espera",
  cta2: "Hablar con el equipo",
  comingSoon: "Próximamente",
};

const ENTERPRISE_EN = {
  badge: "For teams · Coming soon",
  title: "Certify your team in ATLAS",
  sub: "The official training programme for organisations operating Atlas. Role-based tracks, verifiable certificates and progress tracking across your whole team.",
  items: [
    "Role-based certification tracks: Security Analyst, Cloud Engineer, Compliance Officer",
    "QR-verifiable certificates — shareable on LinkedIn",
    "Admin panel for full team progress tracking",
    "Training in cloud security, IaC, FinOps and Atlas compliance",
    "Native integration with the ClowdSecOps ecosystem",
  ],
  roles: [
    { icon: "\u{1F6E1}️", label: "Security Analyst" },
    { icon: "⚙️",   label: "Cloud Engineer" },
    { icon: "\u{1F4CB}",      label: "Compliance Officer" },
    { icon: "\u{1F4B0}",      label: "FinOps Specialist" },
  ],
  cta: "Join the waitlist",
  cta2: "Talk to the team",
  comingSoon: "Coming soon",
};

const PROGRAMS_ES = [
  {
    tier: "Programa",
    title: "IA Automation Engineer",
    tagline: "Fundamentos sólidos para automatizar con IA en producción",
    price: "1.197€",
    priceNote: "Pago único · Acceso de por vida",
    featured: false,
    popular: null,
    features: [
      "3 módulos estructurados · 23 lecciones",
      "Tutor IA ClowdBot incluido en cada lección",
      "Proyectos prácticos por módulo",
      "Gamificación: puntos, badges y leaderboard",
      "Certificado oficial por módulo completado",
      "Comunidad y soporte en Discord",
    ],
  },
  {
    tier: "Máster",
    title: "IA Automation Máster",
    tagline: "El programa completo para convertirte en referente de IA",
    price: "3.897€",
    priceNote: "Pago único · Acceso de por vida",
    featured: true,
    popular: "Más popular",
    features: [
      "4 módulos completos · 31 lecciones",
      "Todo lo del programa Engineer",
      "Módulo avanzado de agentes y orquestación",
      "Casos de uso reales en entornos enterprise",
      "Proyecto final con revisión del equipo",
      "Certificado Máster ClowdAcademy",
      "Acceso prioritario a nuevos contenidos",
    ],
  },
];

const PROGRAMS_EN = [
  {
    tier: "Programme",
    title: "AI Automation Engineer",
    tagline: "Solid foundations for automating with AI in production",
    price: "€1,197",
    priceNote: "One-time payment · Lifetime access",
    featured: false,
    popular: null,
    features: [
      "3 structured modules · 23 lessons",
      "AI tutor ClowdBot included in every lesson",
      "Practical projects per module",
      "Gamification: points, badges and leaderboard",
      "Official certificate per completed module",
      "Community and Discord support",
    ],
  },
  {
    tier: "Master",
    title: "AI Automation Master",
    tagline: "The complete programme to become an AI automation expert",
    price: "€3,897",
    priceNote: "One-time payment · Lifetime access",
    featured: true,
    popular: "Most popular",
    features: [
      "4 full modules · 31 lessons",
      "Everything in Engineer programme",
      "Advanced agents and orchestration module",
      "Real-world enterprise use cases",
      "Final project with team review",
      "ClowdAcademy Master certificate",
      "Priority access to new content",
    ],
  },
];

const FEATURES_ES = [
  { icon: "\u{1F916}", title: "ClowdBot — Tutor IA",    desc: "Asistente de aprendizaje integrado en cada lección. Pregunta dudas sobre el contenido, pide explicaciones alternativas o haz un quiz al final de cada módulo." },
  { icon: "\u{1F3C6}", title: "Gamificación real",       desc: "Sistema de puntos, badges por logros y leaderboard global. Aprende con la motivación de ver tu progreso y compararte con otros estudiantes." },
  { icon: "\u{1F512}", title: "Progreso gated",               desc: "El contenido se desbloquea en orden. Cada lección abre la siguiente cuando la completas — para garantizar que aprendes los fundamentos antes de avanzar." },
  { icon: "\u{1F4DC}", title: "Certificados por módulo", desc: "Recibes un certificado oficial al completar cada módulo, verificable con QR y compartible en LinkedIn. El Máster incluye además un certificado global del programa." },
];

const FEATURES_EN = [
  { icon: "\u{1F916}", title: "ClowdBot — AI Tutor",     desc: "Learning assistant integrated into every lesson. Ask questions about the content, request alternative explanations, or take a quiz at the end of each module." },
  { icon: "\u{1F3C6}", title: "Real gamification",             desc: "Points system, achievement badges and global leaderboard. Learn with the motivation of seeing your progress and comparing with other students." },
  { icon: "\u{1F512}", title: "Gated progress",                desc: "Content unlocks in order. Each lesson opens the next when you complete it — to ensure you learn the fundamentals before advancing." },
  { icon: "\u{1F4DC}", title: "Certificates per module",       desc: "You receive an official certificate upon completing each module, QR-verifiable and shareable on LinkedIn. The Master also includes a global programme certificate." },
];

const SHOTS_ES = [
  { key: "academy-home",         label: "Página de inicio",       sublabel: "→ assets/academy/academy-home.webp" },
  { key: "academy-lesson",       label: "Lección + ClowdBot IA",  sublabel: "→ assets/academy/academy-lesson.webp" },
  { key: "academy-pricing",      label: "Precios y programas",          sublabel: "→ assets/academy/academy-pricing.webp" },
  { key: "academy-achievements", label: "Logros y badges",              sublabel: "→ assets/academy/academy-achievements.webp" },
  { key: "academy-dashboard",    label: "Dashboard del alumno",         sublabel: "→ assets/academy/academy-dashboard.webp" },
  { key: "academy-catalog",      label: "Catálogo de lecciones",   sublabel: "→ assets/academy/academy-catalog.webp" },
];

const SHOTS_EN = [
  { key: "academy-home",         label: "Home page",              sublabel: "→ assets/academy/academy-home.webp" },
  { key: "academy-lesson",       label: "Lesson + ClowdBot AI",   sublabel: "→ assets/academy/academy-lesson.webp" },
  { key: "academy-pricing",      label: "Pricing & programmes",   sublabel: "→ assets/academy/academy-pricing.webp" },
  { key: "academy-achievements", label: "Achievements & badges",  sublabel: "→ assets/academy/academy-achievements.webp" },
  { key: "academy-dashboard",    label: "Student dashboard",      sublabel: "→ assets/academy/academy-dashboard.webp" },
  { key: "academy-catalog",      label: "Lesson catalogue",       sublabel: "→ assets/academy/academy-catalog.webp" },
];

/* ── ShotSlot ────────────────────────────────────────────────────────────── */
function ShotSlot({ shot }) {
  const [hasImg, setHasImg] = useState(true);
  const src = "/assets/academy/" + shot.key + ".webp";
  return (
    <div className="shot-slot" title={shot.label}>
      {hasImg
        ? <img src={src} alt={shot.label} loading="lazy" onError={() => setHasImg(false)} />
        : <div className="shot-slot-placeholder">
            <svg className="shot-slot-icon" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
              <rect x="3" y="3" width="18" height="18" rx="3"/>
              <circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/>
            </svg>
            <span className="shot-slot-label">{shot.label}</span>
            <span className="shot-slot-sublabel">{shot.sublabel}</span>
          </div>}
    </div>
  );
}

/* ── Page ───────────────────────────────────────────────────────────────── */
function AcademyPage() {
  const { theme, setTheme, lang, setLang } = useAppearance();
  const isEs       = lang === "es";

  useEffect(() => { window.gtmEvent('view_academy'); }, []);
  const programs   = isEs ? PROGRAMS_ES   : PROGRAMS_EN;
  const feats      = isEs ? FEATURES_ES   : FEATURES_EN;
  const shots      = isEs ? SHOTS_ES      : SHOTS_EN;
  const enterprise = isEs ? ENTERPRISE_ES : ENTERPRISE_EN;

  return (
    <>
      <ProductNav lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
      <main>

        {/* Hero */}
        <section className="aca-hero">
          <div className="wrap">
            <nav aria-label="breadcrumb" style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 40, display: "flex", gap: 6, alignItems: "center", justifyContent: "center" }}>
              <a href="/" style={{ color: "var(--ink-3)" }}>ClowdSecOps</a>
              <span>&#8250;</span>
              <a href="/products" style={{ color: "var(--ink-3)" }}>{window.I18N[lang].nav.products || "Productos"}</a>
              <span>&#8250;</span>
              <span style={{ color: "var(--ink-1)" }}>ClowdAcademy</span>
            </nav>
            <span className="aca-logo">ClowdAcademy</span>
            <h1>{isEs ? "Aprende IA. Certifica a tu equipo." : "Learn AI. Certify your team."}</h1>
            <p>{isEs
              ? "La plataforma oficial del ecosistema ClowdSecOps. Para profesionales cloud que quieren dominar la IA Automation y para equipos enterprise que operan Atlas."
              : "The official ClowdSecOps learning platform. For cloud professionals who want to master AI Automation, and for enterprise teams operating Atlas."}</p>
            <div className="aca-hero-ctas">
              <a href="https://academy.clowdsecops.cloud" target="_blank" rel="noreferrer" className="btn btn-primary btn-lg"
                onClick={() => window.gtmEvent('click_cta', { cta_label: 'go_to_academy', source: 'academy_hero' })}>
                {isEs ? "Ir a ClowdAcademy" : "Go to ClowdAcademy"} &#8599;
              </a>
              <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-ghost btn-lg"
                onClick={() => { window.gtmEvent('book_demo', { source: 'academy_hero' }); window.gtmEvent('generate_lead', { source: 'academy_hero' }); }}>
                {isEs ? "Hablar con el equipo" : "Talk to the team"}
              </a>
            </div>
          </div>
        </section>

        {/* Enterprise Atlas Certification */}
        <section className="aca-enterprise">
          <div className="wrap">
            <div className="aca-ent-inner">
              <div className="aca-ent-body">
                <span className="eyebrow">{enterprise.badge}</span>
                <h2>{enterprise.title}</h2>
                <p>{enterprise.sub}</p>
                <ul className="aca-ent-items">
                  {enterprise.items.map(item => <li key={item}>{item}</li>)}
                </ul>
                <div className="aca-ent-ctas">
                  <a href="https://academy.clowdsecops.cloud" target="_blank" rel="noreferrer" className="btn btn-primary btn-sm"
                    onClick={() => window.gtmEvent('click_cta', { cta_label: 'go_to_academy', source: 'academy_enterprise' })}>
                    {enterprise.cta} &#8594;
                  </a>
                  <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-ghost btn-sm"
                    onClick={() => { window.gtmEvent('book_demo', { source: 'academy_enterprise' }); window.gtmEvent('generate_lead', { source: 'academy_enterprise' }); }}>
                    {enterprise.cta2}
                  </a>
                </div>
              </div>
              <div className="aca-ent-visual">
                <div className="aca-ent-visual-title">
                  <span className="aca-ent-cert-icon">&#127881;</span>
                  <span>{isEs ? "Certificación Oficial ATLAS" : "Official ATLAS Certification"}</span>
                </div>
                <div className="aca-ent-roles">
                  {enterprise.roles.map(r => (
                    <div key={r.label} className="aca-ent-role">
                      <span className="aca-ent-role-icon">{r.icon}</span>
                      <span className="aca-ent-role-label">{r.label}</span>
                    </div>
                  ))}
                </div>
                <div className="aca-ent-coming-soon">
                  <span className="aca-ent-cs-dot"></span>
                  {enterprise.comingSoon}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Individual Programs */}
        <section className="aca-programs">
          <div className="wrap">
            <h2>{isEs ? "Elige tu programa" : "Choose your programme"}</h2>
            <p className="section-sub">{isEs ? "Dos niveles según tus objetivos. Mismo método, diferente profundidad." : "Two levels for different goals. Same method, different depth."}</p>
            <div className="prog-grid">
              {programs.map(p => (
                <div key={p.title} className={"prog-card" + (p.featured ? " is-featured" : "")}>
                  {p.popular && <div className="prog-popular">{p.popular}</div>}
                  <div className="prog-tier">{p.tier}</div>
                  <h3>{p.title}</h3>
                  <p className="prog-tagline">{p.tagline}</p>
                  <div className="prog-price">{p.price}</div>
                  <p className="prog-price-note">{p.priceNote}</p>
                  <hr className="prog-divider" />
                  <ul className="prog-features">
                    {p.features.map(f => (
                      <li key={f}>
                        <span className="prog-check">&#10003;</span>
                        {f}
                      </li>
                    ))}
                  </ul>
                  <a href="https://academy.clowdsecops.cloud" target="_blank" rel="noreferrer"
                    className={"btn btn-sm " + (p.featured ? "btn-primary" : "btn-ghost")}
                    style={{ width: "100%", textAlign: "center" }}>
                    {isEs ? "Empezar ahora" : "Start now"} &#8594;
                  </a>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* Platform Features */}
        <section className="aca-features">
          <div className="wrap">
            <h2>{isEs ? "Cómo funciona ClowdAcademy" : "How ClowdAcademy works"}</h2>
            <p className="section-sub">{isEs ? "Aprendizaje guiado, con las mecánicas que mantienen el ritmo de estudio." : "Guided learning with the mechanics that keep your study pace."}</p>
            <div className="aca-feat-grid">
              {feats.map(f => (
                <div className="aca-feat-card" key={f.title}>
                  <span className="aca-feat-icon" aria-hidden="true">{f.icon}</span>
                  <div>
                    <h3>{f.title}</h3>
                    <p>{f.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* Screenshots */}
        <section className="aca-shots">
          <div className="wrap">
            <h2>{isEs ? "La plataforma" : "The platform"}</h2>
            <p className="section-sub">{isEs ? "Una experiencia de aprendizaje construida para retención real, no para hacer clic en vídeos." : "A learning experience built for real retention, not just clicking through videos."}</p>
            <div className="shots-grid">
              {shots.map(s => <ShotSlot key={s.key} shot={s} />)}
            </div>
          </div>
        </section>

        {/* CTA */}
        <section className="aca-cta" style={{ borderTop: "1px solid var(--border)" }}>
          <div className="wrap">
            <h2>{isEs ? "¿Listo para empezar?" : "Ready to start?"}</h2>
            <p>{isEs ? "Accede hoy a ClowdAcademy y empieza con el primer módulo gratis." : "Join ClowdAcademy today and start with the first module free."}</p>
            <div className="aca-cta-btns">
              <a href="https://academy.clowdsecops.cloud" target="_blank" rel="noreferrer" className="btn btn-primary btn-lg"
                onClick={() => window.gtmEvent('click_cta', { cta_label: 'go_to_academy', source: 'academy_bottom_cta' })}>
                {isEs ? "Ir a ClowdAcademy" : "Go to ClowdAcademy"} &#8599;
              </a>
              <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-ghost btn-lg"
                onClick={() => { window.gtmEvent('book_demo', { source: 'academy_bottom_cta' }); window.gtmEvent('generate_lead', { source: 'academy_bottom_cta' }); }}>
                {isEs ? "Hablar con el equipo" : "Talk to the team"}
              </a>
            </div>
          </div>
        </section>

      </main>
      <ProductFooter lang={lang} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AcademyPage />);
