/* global React, ReactDOM */
/* /products/atlas — 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 TOUR_ES = [
  { key: "dashboard",  label: "Dashboard",  desc: "Vista ejecutiva de tu postura de seguridad: hallazgos activos por severidad, tendencias, riesgo de identidad y cobertura de compliance en tiempo real." },
  { key: "clowdearth", label: "ClowdEarth", desc: "Globo 3D interactivo con la distribución geográfica de todos tus recursos cloud y sus riesgos asociados por región y proveedor." },
  { key: "compliance", label: "Compliance",  desc: "19 marcos regulatorios incluidos: ENS (requisito legal en España), DORA, CIS Benchmarks, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA y más, con remediación guiada." },
  { key: "finops",     label: "FinOps",      desc: "Oportunidades de ahorro ordenadas por impacto económico: recursos sobredimensionados, instancias idle y análisis pre-despliegue de IaC." },
  { key: "inventory",  label: "Inventario",  desc: "Inventario en tiempo real de todos los recursos en las 5 nubes, con grafo de relaciones y análisis de exposición a internet." },
  { key: "clowdai",    label: "ClowdAI",     desc: "Copiloto de IA integrado: pregunta en lenguaje natural sobre tu postura, recursos y hallazgos — respuestas contextualizadas al instante." },
];
const TOUR_EN = [
  { key: "dashboard",  label: "Dashboard",  desc: "Executive view of your full security posture: active findings by severity, trends, identity risk and compliance coverage in real time." },
  { key: "clowdearth", label: "ClowdEarth", desc: "Interactive 3D globe showing the geographical distribution of all your cloud resources and associated risks by region and provider." },
  { key: "compliance", label: "Compliance",  desc: "19 built-in frameworks: ENS (legal requirement in Spain), DORA, CIS Benchmarks, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA and more, with guided remediation." },
  { key: "finops",     label: "FinOps",      desc: "Savings opportunities ranked by financial impact: oversized resources, idle instances and IaC pre-deploy analysis." },
  { key: "inventory",  label: "Inventory",   desc: "Real-time inventory of all resources across 5 clouds, with relationship graph and internet exposure analysis." },
  { key: "clowdai",    label: "ClowdAI",     desc: "Built-in AI copilot: ask in natural language about your posture, resources and findings — contextualised answers instantly." },
];

const FEATURES_ES = [
  { icon: "🛡️", title: "CSPM",      desc: "Detección continua de misconfiguraciones en recursos cloud sobre los 5 grandes proveedores. Severidad priorizada y remediación paso a paso." },
  { icon: "✅", title: "Compliance", desc: "19 marcos: ENS, DORA, CIS, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA y más. Evidencias listas para auditoría con un clic." },
  { icon: "💰", title: "FinOps",     desc: "Identifica costes evitables antes y después del despliegue. Análisis de IaC integrado para detectar sobredimensionamiento en diseño." },
  { icon: "🗂️", title: "Inventario", desc: "Descubrimiento automático de todos tus recursos con grafo de relaciones, exposición a internet y comparativa en el tiempo." },
  { icon: "🔑", title: "CIEM",       desc: "Gestión de identidades y accesos cloud: detecta privilegios excesivos, credenciales expuestas y rutas de escalada en AWS, Azure y GCP." },
  { icon: "🤖", title: "ClowdAI",    desc: "Copiloto de IA en lenguaje natural: responde preguntas sobre hallazgos, recursos y tendencias con contexto de tu infraestructura real." },
];
const FEATURES_EN = [
  { icon: "🛡️", title: "CSPM",      desc: "Continuous misconfiguration detection across cloud resources on all 5 major providers. Prioritised severity and step-by-step remediation." },
  { icon: "✅", title: "Compliance", desc: "19 frameworks: ENS, DORA, CIS, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA and more. Audit-ready evidence with one click." },
  { icon: "💰", title: "FinOps",     desc: "Identify avoidable costs before and after deployment. Integrated IaC analysis to detect oversizing at design time." },
  { icon: "🗂️", title: "Inventory",  desc: "Automatic discovery of all your resources with relationship graph, internet exposure analysis and point-in-time comparison." },
  { icon: "🔑", title: "CIEM",       desc: "Cloud identity and access management: detect excessive privileges, exposed credentials and escalation paths across AWS, Azure and GCP." },
  { icon: "🤖", title: "ClowdAI",    desc: "Natural-language AI copilot: answers questions about findings, resources and trends with context from your real infrastructure." },
];

const WHY_ES = [
  { num: "5",   title: "Nubes en una sola plataforma",     desc: "AWS, Azure, GCP, OCI y Alibaba Cloud. Sin cambiar de herramienta, sin silos, con visibilidad unificada desde el primer día." },
  { num: "19",  title: "Marcos de compliance incluidos",    desc: "ENS, DORA, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA, CIS y más — sin licencias adicionales ni integraciones manuales." },
  { num: "0",   title: "Agentes que desplegar",             desc: "Atlas funciona en modo read-only: solo necesitas permisos de lectura en tu cloud. No hay nada que instalar en tus servidores." },
  { num: "IA",  title: "Copiloto integrado de serie",       desc: "ClowdAI responde preguntas en lenguaje natural sobre tu infraestructura real. No es un chatbot genérico: conoce tu entorno." },
];
const WHY_EN = [
  { num: "5",   title: "Clouds in a single platform",       desc: "AWS, Azure, GCP, OCI and Alibaba Cloud. No tool-switching, no silos, unified visibility from day one." },
  { num: "19",  title: "Compliance frameworks included",    desc: "ENS, DORA, NIS2, ISO 27001, PCI DSS, SOC 2, HIPAA, CIS and more — no extra licences, no manual integrations." },
  { num: "0",   title: "Agents to deploy",                  desc: "Atlas works read-only: you only need read permissions in your cloud. Nothing to install on your servers." },
  { num: "AI",  title: "Built-in copilot as standard",      desc: "ClowdAI answers natural-language questions about your real infrastructure. Not a generic chatbot — it knows your environment." },
];

const CLOUD_BADGES = ["AWS", "Azure", "GCP", "OCI", "Alibaba Cloud", "ENS", "DORA", "NIS2", "ISO 27001", "PCI DSS", "SOC 2", "CIS Benchmarks"];

/* ── Tour component ─────────────────────────────────────────────────────── */
function AtlasTour({ shots }) {
  const [active, setActive] = useState(0);
  return (
    <div>
      <div className="tour-tabs" role="tablist">
        {shots.map((s, i) => (
          <button key={s.key} role="tab" aria-selected={i === active}
            className={"tour-tab" + (i === active ? " is-active" : "")}
            onClick={() => setActive(i)}>
            {s.label}
          </button>
        ))}
      </div>
      <div className="tour-frame">
        <img key={shots[active].key} className="tour-shot"
          src={"/assets/atlas/" + shots[active].key + ".webp"}
          alt={"Atlas CNAPP — " + shots[active].label}
          loading="lazy" width="1280" height="720" />
      </div>
      <p className="tour-caption">{shots[active].desc}</p>
    </div>
  );
}

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

  useEffect(() => { window.gtmEvent('view_atlas'); }, []);
  const shots = isEs ? TOUR_ES    : TOUR_EN;
  const feats = isEs ? FEATURES_ES : FEATURES_EN;
  const whys  = isEs ? WHY_ES     : WHY_EN;

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

        <section className="atlas-hero">
          <div className="wrap">
            <nav aria-label="breadcrumb" style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 40, display: "flex", gap: 6, alignItems: "center" }}>
              <a href="/" style={{ color: "var(--ink-3)" }}>ClowdSecOps</a>
              <span>›</span>
              <a href="/products" style={{ color: "var(--ink-3)" }}>{window.I18N[lang].nav.products || "Productos"}</a>
              <span>›</span>
              <span style={{ color: "var(--ink-1)" }}>Atlas</span>
            </nav>
            <div className="atlas-hero-inner">
              <div>
                <img src="/assets/atlas/logo-atlas-wordmark.png" alt="Atlas CNAPP" className="atlas-wordmark" />
                <h1>{isEs ? "Seguridad cloud autónoma, impulsada por IA" : "Autonomous cloud security, powered by AI"}</h1>
                <p>{isEs
                  ? "La plataforma CNAPP de ClowdSecOps que unifica gestión de postura, compliance, FinOps, inventario y CIEM sobre los 5 grandes proveedores cloud — con un copiloto de IA que responde preguntas sobre tu infraestructura en tiempo real."
                  : "ClowdSecOps's CNAPP platform that unifies posture management, compliance, FinOps, inventory and CIEM across all 5 major cloud providers — with an AI copilot that answers questions about your real-time infrastructure."}</p>
                <div className="atlas-hero-ctas">
                  <a href="https://atlas.clowdsecops.com" target="_blank" rel="noreferrer" className="btn btn-primary"
                    onClick={() => window.gtmEvent('click_cta', { cta_label: 'go_to_atlas', source: 'atlas_hero' })}>
                    {isEs ? "Ir a Atlas" : "Go to Atlas"} ↗
                  </a>
                  <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-ghost"
                    onClick={() => { window.gtmEvent('book_demo', { source: 'atlas_hero' }); window.gtmEvent('generate_lead', { source: 'atlas_hero' }); }}>
                    {isEs ? "Solicitar demo" : "Request a demo"}
                  </a>
                </div>
                <div className="atlas-stats">
                  <div><div className="atlas-stat-val">5</div><div className="atlas-stat-lbl">{isEs ? "Nubes soportadas" : "Clouds supported"}</div></div>
                  <div><div className="atlas-stat-val">19</div><div className="atlas-stat-lbl">{isEs ? "Marcos de compliance" : "Compliance frameworks"}</div></div>
                  <div><div className="atlas-stat-val">0</div><div className="atlas-stat-lbl">{isEs ? "Agentes a instalar" : "Agents to install"}</div></div>
                </div>
              </div>
              <div className="atlas-hero-visual">
                <img src="/assets/atlas/dashboard.webp" alt="Atlas dashboard" width="720" height="450" />
              </div>
            </div>
          </div>
        </section>

        <section className="atlas-tour-section" style={{ borderTop: "1px solid var(--border)" }}>
          <div className="wrap">
            <h2>{isEs ? "Tour de la plataforma" : "Platform tour"}</h2>
            <p className="section-sub">{isEs ? "Explora los módulos de Atlas — haz clic en cada pestaña para ver la interfaz en detalle." : "Explore Atlas modules — click each tab to see the interface in detail."}</p>
            <AtlasTour shots={shots} />
          </div>
        </section>

        <section className="atlas-features">
          <div className="wrap">
            <h2>{isEs ? "Todo lo que necesitas para cloud security" : "Everything you need for cloud security"}</h2>
            <p className="section-sub">{isEs ? "Seis módulos integrados en una sola plataforma, sin herramientas adicionales." : "Six modules integrated into a single platform, no additional tools."}</p>
            <div className="feat-grid">
              {feats.map(f => (
                <div className="feat-card" key={f.title}>
                  <span className="feat-icon" aria-hidden="true">{f.icon}</span>
                  <h3>{f.title}</h3>
                  <p>{f.desc}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section className="atlas-why">
          <div className="wrap">
            <h2>{isEs ? "Por qué Atlas" : "Why Atlas"}</h2>
            <p className="section-sub">{isEs ? "Diferenciadores que importan cuando evalúas una CNAPP para tu organización." : "Differentiators that matter when evaluating a CNAPP for your organisation."}</p>
            <div className="why-grid">
              {whys.map(w => (
                <div className="why-card" key={w.title}>
                  <div className="why-num">{w.num}</div>
                  <h3>{w.title}</h3>
                  <p>{w.desc}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section className="atlas-clouds">
          <div className="wrap">
            <h2>{isEs ? "COMPATIBLE CON" : "COMPATIBLE WITH"}</h2>
            <div className="cloud-logos">
              {CLOUD_BADGES.map(b => <span key={b} className="cloud-pill">{b}</span>)}
            </div>
          </div>
        </section>

        <section className="atlas-cta" style={{ borderTop: "1px solid var(--border)" }}>
          <div className="wrap">
            <h2>{isEs ? "¿Listo para ver Atlas en acción?" : "Ready to see Atlas in action?"}</h2>
            <p>{isEs ? "Solicita una demo con nuestro equipo o accede directamente a la plataforma." : "Request a demo with our team or access the platform directly."}</p>
            <div className="atlas-cta-btns">
              <a href="https://atlas.clowdsecops.com" target="_blank" rel="noreferrer" className="btn btn-primary btn-lg"
                onClick={() => window.gtmEvent('click_cta', { cta_label: 'go_to_atlas', source: 'atlas_bottom_cta' })}>
                {isEs ? "Ir a Atlas" : "Go to Atlas"} ↗
              </a>
              <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-ghost btn-lg"
                onClick={() => { window.gtmEvent('book_demo', { source: 'atlas_bottom_cta' }); window.gtmEvent('generate_lead', { source: 'atlas_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(<AtlasPage />);
