/* global React, ReactDOM, I18N, HeroDiagram, BOOKING_URL */

const { useState, useEffect, useMemo } = React;

/* ---------------- Icons ---------------- */
const Icon = {
  shield: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l8 3v6c0 5-3.5 8.5-8 9-4.5-.5-8-4-8-9V6l8-3z"/><path d="M9 12l2 2 4-4"/></svg>,
  compass: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M15.5 8.5l-2 5-5 2 2-5 5-2z"/></svg>,
  cloud: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M7 18a5 5 0 010-10 6 6 0 0111.6 1.8A4 4 0 0118 18H7z"/><path d="M9 14l2 2 4-4"/></svg>,
  pipeline: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="5" cy="6" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 6h6a4 4 0 014 4v0M7 18h6a4 4 0 004-4v0"/></svg>,
  spark: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="8" width="16" height="11" rx="2.5"/><path d="M12 4v4"/><circle cx="12" cy="3.2" r="1.1" fill="currentColor" stroke="none"/><circle cx="9" cy="13" r="1" fill="currentColor" stroke="none"/><circle cx="15" cy="13" r="1" fill="currentColor" stroke="none"/><path d="M9.5 16.5h5"/><path d="M3 13v2M21 13v2"/></svg>,
  radar: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/><path d="M12 12L18 6"/></svg>,
  plus: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>,
  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>,
};

const SERVICE_ICONS = [Icon.shield, Icon.compass, Icon.cloud, Icon.pipeline, Icon.spark, Icon.radar];

/* ---------------- Brand stack icons — official logos with auto-fallback ---------------- */
// `src` = direct URL · `slug` = simple-icons slug · `node` = inline JSX · `color` = brand hex (no #)
// AWS & Azure use devicon because simple-icons removed them for trademark reasons.
// Claude (Anthropic) & MCP use inline SVGs because their official logos aren't on standard CDNs.
const CLAUDE_NODE = (
  <svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    {/* Anthropic-style 8-point burst */}
    <path
      d="M16 1 L17.6 12.4 L22.3 5.7 L20.2 14 L30.5 11.7 L21.6 16 L30.5 20.3 L20.2 18 L22.3 26.3 L17.6 19.6 L16 31 L14.4 19.6 L9.7 26.3 L11.8 18 L1.5 20.3 L10.4 16 L1.5 11.7 L11.8 14 L9.7 5.7 L14.4 12.4 Z"
      fill="#D97757"
    />
  </svg>
);
const MCP_NODE = (
  <svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round">
    {/* Connected-nodes diamond representing the protocol */}
    <path d="M16 4 L26 16 L16 28 L6 16 Z" />
    <circle cx="16" cy="4" r="2.4" fill="currentColor" stroke="none" />
    <circle cx="26" cy="16" r="2.4" fill="currentColor" stroke="none" />
    <circle cx="16" cy="28" r="2.4" fill="currentColor" stroke="none" />
    <circle cx="6" cy="16" r="2.4" fill="currentColor" stroke="none" />
    <path d="M16 4 L16 28 M6 16 L26 16" opacity="0.55" />
  </svg>
);

const BRANDS = {
  "AWS":            { src: "https://cdn.jsdelivr.net/gh/devicons/devicon@v2.16.0/icons/amazonwebservices/amazonwebservices-original-wordmark.svg", color: "FF9900" },
  "Azure":          { src: "https://cdn.jsdelivr.net/gh/devicons/devicon@v2.16.0/icons/azure/azure-original.svg",                                  color: "0078D4" },
  "Google Cloud":   { slug: "googlecloud",       color: "4285F4" },
  "Terraform":      { slug: "terraform",         color: "844FBA" },
  "Kubernetes":     { slug: "kubernetes",        color: "326CE5" },
  "GitHub Actions": { slug: "githubactions",     color: "2088FF" },
  "GitLab CI":      { slug: "gitlab",            color: "FC6D26" },
  "Docker":         { slug: "docker",            color: "2496ED" },
  "Ansible":        { slug: "ansible",           color: "EE0000", invertOnDark: true },
  "Helm":           { slug: "helm",              color: "0F1689", invertOnDark: true },
  "Prometheus":     { slug: "prometheus",        color: "E6522C" },
  "Datadog":        { slug: "datadog",           color: "632CA6" },
  // AI / LLM row
  "Claude":         { src: "assets/claude-logo.png", color: "D97757" },
  "OpenAI":         { src: "assets/openai-logo.png", color: "000000", invertOnDark: true },
  "MCP":            { node: MCP_NODE,            color: "2A6FDB", inheritColor: true },
  "LangChain":      { slug: "langchain",         color: "1C3C3C", invertOnDark: true },
  "Ollama":         { slug: "ollama",            color: "000000", invertOnDark: true },
  "Hugging Face":   { slug: "huggingface",       color: "FFD21E" },
};

function FallbackMark({ name, color }) {
  const initials = name.split(/[\s]/).map(w => w[0]).join("").slice(0, 2).toUpperCase();
  return (
    <span className="brand-fallback" style={{ ["--bm"]: `#${color}` }}>
      {initials}
    </span>
  );
}

function BrandMark({ name }) {
  const b = BRANDS[name];
  const [failed, setFailed] = useState(false);
  if (!b) return null;
  if (b.node) {
    return (
      <span
        className="brand-logo-inline"
        style={b.inheritColor ? { color: `#${b.color}` } : undefined}
        aria-label={`${name} logo`}
      >
        {b.node}
      </span>
    );
  }
  if (failed) return <FallbackMark name={name} color={b.color} />;
  const src = b.src || `https://cdn.simpleicons.org/${b.slug}/${b.color}`;
  return (
    <img
      className={`brand-logo ${b.invertOnDark ? "invert-on-dark" : ""}`}
      src={src}
      alt={`${name} logo`}
      loading="lazy"
      width="22"
      height="22"
      referrerPolicy="no-referrer"
      onError={() => setFailed(true)}
    />
  );
}

/* ---------------- Nav ---------------- */
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 ? (
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>
            </svg>
          ) : (
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <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>
          )}
        </span>
      </span>
    </button>
  );
}

function Nav({ lang, setLang, t, 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);
  }, []);
  return (
    <header className={`nav ${scrolled ? "is-scrolled" : ""}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="brand">
          <img src="assets/clowdsecops-logo.png" alt="ClowdSecOps" />
        </a>
        <nav className="nav-links">
          <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={BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-primary btn-sm">
            {t.nav.book}<span className="arrow"><Icon.arrow /></span>
          </a>
        </div>
      </div>
    </header>
  );
}

/* ---------------- Hero ---------------- */
function Hero({ t }) {
  return (
    <section className="hero" id="top">
      <div className="hero-grid-bg" aria-hidden="true" />
      <div className="wrap hero-inner">
        <div>
          <h1>
            {t.hero.title_a}<br />
            <em>{t.hero.title_b}</em><br />
            {t.hero.title_c}
          </h1>
          <p className="lead">{t.hero.lead}</p>
          <div className="hero-ctas">
            <a href={BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-primary btn-lg">
              {t.hero.cta_primary}<span className="arrow"><Icon.arrow /></span>
            </a>
            <a href="#services" className="btn btn-ghost btn-lg">{t.hero.cta_secondary}</a>
          </div>
          <div className="hero-meta">
            <span><b>↳</b> {t.hero.meta_1}</span>
            <span><b>↳</b> {t.hero.meta_2}</span>
            <span><b>↳</b> {t.hero.meta_3}</span>
          </div>
        </div>
        <HeroDiagram />
      </div>
    </section>
  );
}

/* ---------------- Stack ---------------- */
function Stack({ t }) {
  return (
    <section className="stack" id="stack">
      <div className="wrap">
        <div className="stack-label">{t.stack.label}</div>
        <div className="stack-grid">
          {t.stack.items.map((name) => (
            <div className="stack-item" key={name}>
              <BrandMark name={name} />
              <span>{name}</span>
            </div>
          ))}
        </div>
        <div className="stack-label stack-label-ai">{t.stack.ai_label}</div>
        <div className="stack-grid">
          {t.stack.ai_items.map((name) => (
            <div className="stack-item" key={name}>
              <BrandMark name={name} />
              <span>{name}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Services ---------------- */
function Services({ t }) {
  return (
    <section className="services" id="services">
      <div className="wrap">
        <div className="services-head">
          <div>
            <span className="eyebrow">{t.services.eyebrow}</span>
            <h2 className="h-section">{t.services.title}</h2>
          </div>
          <p className="section-sub">{t.services.sub}</p>
        </div>
        <div className="services-grid">
          {t.services.items.map((s, i) => {
            const IconC = SERVICE_ICONS[i];
            return (
              <div className={`service ${s.partner ? "service-partner" : ""}`} key={s.title}>
                <div className="glyph"><IconC /></div>
                <span className="num">{s.num}</span>
                <h3>{s.title}</h3>
                {s.partner && <span className="partner-pill">★ {s.partner}</span>}
                <p>{s.body}</p>
                <div className="bullets">
                  {s.tags.map((tag) => <span key={tag}>{tag}</span>)}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Why us ---------------- */
function Why({ t }) {
  return (
    <section className="why" id="why">
      <div className="wrap">
        <span className="eyebrow">{t.why.eyebrow}</span>
        <h2 className="h-section" style={{ maxWidth: 760 }}>{t.why.title}</h2>
        <p className="section-sub">{t.why.sub}</p>
        <div className="why-grid">
          {t.why.items.map((w) => (
            <div className="why-item" key={w.title}>
              <span className="num">{w.num}</span>
              <h4>{w.title}</h4>
              <p>{w.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Process ---------------- */
function Process({ t }) {
  return (
    <section className="process" id="process">
      <div className="wrap">
        <span className="eyebrow">{t.process.eyebrow}</span>
        <h2 className="h-section">{t.process.title}</h2>
        <p className="section-sub">{t.process.sub}</p>
        <div className="process-list">
          {t.process.steps.map((s) => (
            <div className="process-row" key={s.title}>
              <span className="step">{s.step}</span>
              <h4>{s.title}</h4>
              <p>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Testimonials ---------------- */
function Testimonials({ t }) {
  return (
    <section className="testimonials" id="testimonials">
      <div className="wrap">
        <span className="eyebrow">{t.testimonials.eyebrow}</span>
        <h2 className="h-section">{t.testimonials.title}</h2>
        <div className="t-grid">
          {t.testimonials.items.map((c) => (
            <div className="t-card" key={c.name}>
              <p className="quote">“{c.quote}”</p>
              <div className="who">
                <div className="avatar">{c.initials}</div>
                <div>
                  <div className="name">{c.name}</div>
                  <div className="role">{c.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- FAQ ---------------- */
function FAQ({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section className="faq" id="faq">
      <div className="wrap">
        <span className="eyebrow">{t.faq.eyebrow}</span>
        <h2 className="h-section">{t.faq.title}</h2>
        <div className="faq-list">
          {t.faq.items.map((it, i) => (
            <div className={`faq-item ${open === i ? "open" : ""}`} key={i}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span>{it.q}</span>
                <span className="ico"><Icon.plus /></span>
              </button>
              <div className="faq-a">
                <div className="faq-a-inner">{it.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- Blog ---------------- */
function Blog({ t }) {
  return (
    <section className="blog" id="insights">
      <div className="wrap">
        <span className="eyebrow">{t.blog.eyebrow}</span>
        <h2 className="h-section">{t.blog.title}</h2>
        <p className="section-sub">{t.blog.sub}</p>
        <div className="blog-grid">
          {t.blog.items.map((p) => (
            <article className="post" key={p.title}>
              <div className="thumb">{t.blog.thumb_label}</div>
              <div className="meta"><span>{p.tag}</span><span>·</span><span>{p.time}</span></div>
              <h4>{p.title}</h4>
              <p>{p.body}</p>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------------- CTA ---------------- */
function CTA({ t }) {
  return (
    <section className="cta" id="contact">
      <div className="wrap">
        <div className="cta-card">
          <span className="eyebrow">{t.cta.eyebrow}</span>
          <h2>{t.cta.title}</h2>
          <p>{t.cta.sub}</p>
          <div className="cta-actions">
            <a href={BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-primary btn-lg">
              {t.cta.primary}<span className="arrow"><Icon.arrow /></span>
            </a>
            <a href="mailto:info@clowdsecops.com" className="btn btn-ghost btn-lg">{t.cta.secondary}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Footer ---------------- */
function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div className="footer-col">
            <a href="#top" 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>
            </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>{t.footer.built}</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Tweaks ---------------- */
function CSOPSTweaks({ tweaks, setTweak }) {
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection title="Theme">
        <window.TweakRadio
          label="Mode"
          value={tweaks.theme}
          onChange={(v) => setTweak("theme", v)}
          options={[
            { value: "light", label: "Light" },
            { value: "dark", label: "Dark" },
          ]}
        />
        <window.TweakSelect
          label="Background"
          value={tweaks.bg}
          onChange={(v) => setTweak("bg", v)}
          options={[
            { value: "warm", label: "Warm off-white" },
            { value: "paper", label: "Pure paper" },
            { value: "mist", label: "Cool mist" },
            { value: "sage", label: "Sage" },
            { value: "sand", label: "Sand" },
            { value: "stone", label: "Stone" },
          ]}
        />
        <window.TweakSelect
          label="Headline font"
          value={tweaks.display}
          onChange={(v) => setTweak("display", v)}
          options={[
            { value: "apple", label: "Apple (SF Pro)" },
            { value: "space", label: "Space Grotesk" },
            { value: "bricolage", label: "Bricolage Grotesque" },
            { value: "schibsted", label: "Schibsted Grotesk" },
            { value: "inter", label: "Inter Tight" },
            { value: "instrument", label: "Instrument Serif" },
            { value: "fraunces", label: "Fraunces" },
          ]}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* ---------------- App ---------------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "bg": "mist",
  "display": "apple"
}/*EDITMODE-END*/;

function App() {
  const [lang, setLang] = useState(() => localStorage.getItem("cs_lang") || "en");
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    localStorage.setItem("cs_lang", lang);
    document.documentElement.lang = lang;
  }, [lang]);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme || "light");
    localStorage.setItem("cs_theme", tweaks.theme || "light");
  }, [tweaks.theme]);

  useEffect(() => {
    document.documentElement.setAttribute("data-bg", tweaks.bg || "warm");
    localStorage.setItem("cs_bg", tweaks.bg || "warm");
  }, [tweaks.bg]);

  useEffect(() => {
    document.documentElement.setAttribute("data-display", tweaks.display || "space");
    localStorage.setItem("cs_display", tweaks.display || "space");
  }, [tweaks.display]);

  const t = useMemo(() => window.I18N[lang], [lang]);

  return (
    <>
      <Nav lang={lang} setLang={setLang} t={t} theme={tweaks.theme} setTheme={(v) => setTweak("theme", v)} />
      <main>
        <Hero t={t} />
        <Stack t={t} />
        <Services t={t} />
        <Why t={t} />
        <Process t={t} />
        <Testimonials t={t} />
        <FAQ t={t} />
        <CTA t={t} />
      </main>
      <Footer t={t} />
      <CSOPSTweaks tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
