/* global React, I18N, BOOKING_URL */
// Shared blog components — Nav, Footer, theme/lang state hooks.
// In production these are EJS partials rendered by Express. For the static
// prototype we re-implement them in JSX so blog pages share the same look as
// the main site without re-running React state through tweaks-panel.

const { useState, useEffect } = React;

/* ---------- Persisted theme / lang / typography ---------- */
function applyPersistedAppearance() {
  // Read tweak state that the main app already persists to localStorage
  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 BIcon = {
  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>,
  back: () => <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 8H4M7 5L4 8l3 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>,
};

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 BlogNav({ 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="index.html#services">{t.nav.services}</a>
          <a href="index.html#why">{t.nav.why}</a>
          <a href="index.html#process">{t.nav.process}</a>
          <a href="index.html#stack">{t.nav.stack}</a>
          <a href="index.html#faq">{t.nav.faq}</a>
          <a href="blog" className="is-active">{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">
            {t.nav.book}<span className="arrow"><BIcon.arrow /></span>
          </a>
        </div>
      </div>
    </header>
  );
}

function BlogFooter({ 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="index.html#why">{t.nav.why}</a></li>
              <li><a href="index.html#process">{t.nav.process}</a></li>
              <li><a href="index.html#faq">{t.nav.faq}</a></li>
              <li><a href="blog">{t.nav.blog || "Blog"}</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="index.html#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>
  );
}

/* ---------- Cover art (abstract patterns per category) ---------- */
function CoverArt({ color, pattern }) {
  const Patterns = {
    burst: (
      <g>
        <circle cx="200" cy="120" r="50" fill={color} opacity="0.9" />
        {Array.from({ length: 12 }).map((_, i) => {
          const a = (i / 12) * Math.PI * 2;
          const x1 = 200 + Math.cos(a) * 55;
          const y1 = 120 + Math.sin(a) * 55;
          const x2 = 200 + Math.cos(a) * 105;
          const y2 = 120 + Math.sin(a) * 105;
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={color} strokeWidth="14" strokeLinecap="round" opacity="0.9" />;
        })}
      </g>
    ),
    alert: (
      <g>
        <path d="M120 60 L280 60 L320 100 L320 180 L280 220 L120 220 L80 180 L80 100 Z" fill={color} opacity="0.18" stroke={color} strokeWidth="2" />
        <text x="200" y="155" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="48" fill={color} fontWeight="700">CVE</text>
      </g>
    ),
    grid: (
      <g>
        <pattern id={`pat-${color.replace('#','')}`} x="0" y="0" width="28" height="28" patternUnits="userSpaceOnUse">
          <rect x="0" y="0" width="28" height="28" fill="transparent" />
          <circle cx="2" cy="2" r="1.4" fill={color} opacity="0.6" />
        </pattern>
        <rect x="40" y="30" width="320" height="180" fill={`url(#pat-${color.replace('#','')})`} />
        <rect x="100" y="80" width="180" height="80" rx="10" fill={color} opacity="0.85" />
      </g>
    ),
    nodes: (
      <g stroke={color} strokeWidth="2.4" fill="none">
        {[
          [120, 80], [280, 80], [200, 130], [120, 180], [280, 180],
        ].map(([x, y], i) => <circle key={i} cx={x} cy={y} r="14" fill={color} opacity="0.9" />)}
        <path d="M120 80 L200 130 L280 80 M120 180 L200 130 L280 180 M120 80 L120 180 M280 80 L280 180" opacity="0.55" />
      </g>
    ),
    k8s: (
      <g fill="none" stroke={color} strokeWidth="3" strokeLinejoin="round">
        <polygon points="200,50 320,110 290,200 110,200 80,110" fill={color} opacity="0.18" />
        <polygon points="200,80 280,118 262,182 138,182 120,118" fill={color} opacity="0.5" />
        <circle cx="200" cy="130" r="22" fill={color} opacity="0.95" stroke="none" />
      </g>
    ),
  };
  return (
    <svg viewBox="0 0 400 240" className="cover-art" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <rect width="400" height="240" fill="var(--bg-elev)" />
      {Patterns[pattern] || Patterns.grid}
    </svg>
  );
}

/* ---------- Article card ---------- */
function ArticleCard({ a, featured }) {
  const lang = localStorage.getItem("cs_lang") || "en";
  const dateLabel = new Date(a.published_at).toLocaleDateString(lang === "es" ? "es-ES" : "en-US", { day: "numeric", month: "short", year: "numeric" });
  const minLabel = lang === "es" ? `${a.reading_time_min} min` : `${a.reading_time_min} min read`;
  return (
    <a className={`article-card ${featured ? "is-featured" : ""}`} href={`blog-${a.slug}.html`}>
      <div className="article-card-cover" style={{ background: `color-mix(in oklab, ${a.cover_color} 14%, var(--bg-elev))` }}>
        <CoverArt color={a.cover_color} pattern={a.cover_pattern} />
        <span className="article-card-lang">{a.language.toUpperCase()}</span>
      </div>
      <div className="article-card-body">
        <div className="article-card-tags">
          {a.tags.map((t) => <span key={t}>{t}</span>)}
        </div>
        <h3 className="article-card-title">{a.title}</h3>
        <p className="article-card-excerpt">{a.excerpt}</p>
        <div className="article-card-meta">
          <span>{dateLabel}</span>
          <span>·</span>
          <span>{minLabel}</span>
        </div>
      </div>
    </a>
  );
}

Object.assign(window, {
  BlogNav, BlogFooter, ArticleCard, CoverArt, useAppearance, BIcon,
});
