// PEN Landing — Header, Hero, and App composition.

const { useState: useStateA, useEffect: useEffectA } = React;

// ────────────────────────────────────────────────────────────────────
// Status bar (top strip)
// ────────────────────────────────────────────────────────────────────
function StatusBar({ copy }) {
  const [time, setTime] = useStateA(() => fmtClock());
  useEffectA(() => {
    const t = setInterval(() => setTime(fmtClock()), 1000);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="status-bar">
      <div className="container">
        <div className="status-bar-section">
          <span className="pulse-dot" />
          <span>{copy.uptime}</span>
        </div>
        <div className="status-bar-section">
          <span>{copy.coords}</span>
        </div>
        <div className="status-bar-spacer" />
        <div className="status-bar-section">
          <span>{copy.live}</span>
          <span>·</span>
          <span>{time}</span>
        </div>
      </div>
    </div>);

}
function fmtClock() {
  const options = {
    timeZone: "America/Lima",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false
  };
  const formatter = new Intl.DateTimeFormat("es-PE", options);
  return `${formatter.format(new Date())} PET`;
}
function pad(n) {return String(n).padStart(2, "0");}

// ────────────────────────────────────────────────────────────────────
// Header
// ────────────────────────────────────────────────────────────────────
function Header({ copy, onCta, onNav }) {
  const handleNav = (e, sec) => {
    e.preventDefault();
    onNav("landing", sec);
  };
  return (
    <header className="header">
      <div className="container header-inner">
        <a className="header-brand" href="#" onClick={(e) => { e.preventDefault(); onNav("landing"); }}>
          <span className="header-brand-mark">
            <img src="assets/pen-mark-transparent.png" alt="PEN" style={{ width: "28px" }} />
          </span>
          <span className="header-brand-word"></span>
        </a>
        <nav className="header-nav">
          <a href="#vulnerabilidades" onClick={(e) => handleNav(e, "vulnerabilidades")}>{copy.risks}</a>
          <a href="#soluciones" onClick={(e) => handleNav(e, "soluciones")}>{copy.solutions}</a>
          <a href="#como" onClick={(e) => handleNav(e, "como")}>{copy.howItWorks}</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("about"); }}>{copy.about}</a>
          <a href="#clientes" onClick={(e) => handleNav(e, "clientes")}>{copy.mission}</a>
          <a href="#faq" onClick={(e) => handleNav(e, "faq")}>{copy.faq}</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("contact"); }}>{copy.contact}</a>
        </nav>
        <div className="header-actions">
          <button className="btn btn-primary" onClick={onCta}>
            {copy.cta}
            <span className="btn-glyph">›</span>
          </button>
        </div>
      </div>
    </header>);
}

// ────────────────────────────────────────────────────────────────────
// Hero — left: copy + stats; right: live console
// ────────────────────────────────────────────────────────────────────
function Hero({ copy, consoleCopy, onCta }) {
  return (
    <section className="hero">
      <div className="hero-glow" />
      <div className="container hero-inner">
        <div className="hero-left">
          <div className="hero-eyebrow">{copy.eyebrow}</div>
          <h1>
            <span className="h1-line">{copy.h1Top}</span>
            <span className="h1-line h1-bottom">
              {copy.h1Bottom}
              <span className="caret" />
            </span>
          </h1>
          <p className="hero-sub">{copy.sub}</p>

          <div className="hero-cta-row">
            <button className="btn btn-primary btn-lg" onClick={onCta}>
              {copy.cta}
              <span className="btn-glyph">›</span>
            </button>
          </div>
          <div className="hero-cta-sub">{copy.ctaSub}</div>
        </div>

        <div className="hero-right">
          <HackStory copy={consoleCopy} />
        </div>
      </div>

      <div className="container">
        <div className="hero-stats-footer">
          {[copy.stat1, copy.stat2, copy.stat3].map((s, i) =>
            <div className="hero-stat" key={i}>
              <div className="hero-stat-label">{s.label}</div>
              <div className="hero-stat-value">{s.value}</div>
              <div className="hero-stat-foot">{s.foot}</div>
            </div>
          )}
          
          {copy.stat4 && (
            <div className="hero-stat hero-stat-live">
              <div className="hero-stat-label">
                <span className="live-stat-dot" /> {copy.stat4.label}
              </div>
              <div className="hero-stat-value hero-stat-live-val">
                {copy.stat4.value}
                <div className="stat-wave-container">
                  <svg className="ping-wave" viewBox="0 0 100 30" width="80" height="24">
                    <path d="M0,15 L10,15 L15,5 L20,25 L25,15 L35,15 L40,15 L45,5 L50,25 L55,15 L70,15 L75,10 L80,20 L85,15 L100,15" fill="none" stroke="var(--pen-neon)" strokeWidth="1.5" className="wave-path" />
                  </svg>
                </div>
              </div>
              <div className="hero-stat-foot">{copy.stat4.foot}</div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────────────
// Toast — "Demo solicitada" feedback when CTA pressed
// ────────────────────────────────────────────────────────────────────
function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div className="pen-toast-wrap">
      <div className="pen-toast">
        <div className="pen-toast-head">● {toast.head}</div>
        <div className="pen-toast-body">{toast.body}</div>
      </div>
    </div>);

}

// ────────────────────────────────────────────────────────────────────
// App
// ────────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "es",
  "glow": 0.55,
  "gridDensity": 0.04,
  "accentVariant": "neon"
} /*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const copy = PEN_COPY[tweaks.lang] || PEN_COPY.es;
  const [toast, setToast] = useStateA(null);
  const [view, setView] = useStateA("landing");
  const [showModal, setShowModal] = useStateA(false);

  const navigateTo = (v, secId = null) => {
    setView(v);
    
    // Dynamic SEO Title and Description updates for SPA
    try {
      const metaDesc = document.querySelector('meta[name="description"]');
      if (v === "landing") {
        document.title = "PEN — Tu perímetro, monitoreado 24/7.";
        if (metaDesc) metaDesc.setAttribute("content", "PEN Security - Auditoría de ciberseguridad, monitoreo activo de hosts y continuidad de negocio 24/7 en el Perú. Protege tu empresa contra ransomware, phishing y fugas de datos.");
      } else if (v === "about") {
        document.title = "Sobre PEN — Ciberseguridad y continuidad para la empresa peruana";
        if (metaDesc) metaDesc.setAttribute("content", "Conoce quiénes somos en PEN Security. Nuestra misión, visión y pilares operativos para proteger la infraestructura digital en Lima, Perú.");
      } else if (v === "blog") {
        document.title = "Blog Técnico — Artículos y Amenazas de Ciberseguridad en el Perú";
        if (metaDesc) metaDesc.setAttribute("content", "Análisis técnicos, guías de configuración y mejores prácticas de seguridad informática escritas por los especialistas de PEN Security.");
      } else if (v === "contact") {
        document.title = "Contacto — Hablemos de tu ciberseguridad | PEN Security";
        if (metaDesc) metaDesc.setAttribute("content", "Solicita tu diagnóstico de ciberseguridad gratuito. Ponte en contacto directo con nuestros analistas en Surquillo, Lima.");
      } else if (v === "platforms") {
        document.title = "Plataformas de Seguridad Integradas | PEN Security";
        if (metaDesc) metaDesc.setAttribute("content", "Conoce las plataformas líderes que integramos en PEN: Fortinet Firewalls, CrowdStrike EDR, SentinelOne XDR, Veeam Backup y Microsoft Defender.");
      } else if (v === "crm") {
        document.title = "Admin CRM Dashboard | PEN Security";
        if (metaDesc) metaDesc.setAttribute("content", "Sistema de gestión interna de leads y solicitudes.");
      }
    } catch (e) {
      console.warn("Fallo al actualizar metadatos SEO dinámicos:", e);
    }

    if (secId) {
      setTimeout(() => {
        const idStr = secId.toLowerCase().replace(/[^a-z0-9]+/g, "-");
        const el = document.getElementById(idStr) || document.getElementById(secId);
        if (el) el.scrollIntoView({ behavior: "smooth" });
      }, 150);
    } else {
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  // Apply glow + grid CSS vars
  useEffectA(() => {
    const r = document.documentElement;
    r.style.setProperty("--pen-glow-strength", tweaks.glow);
    r.style.setProperty("--pen-grid-opacity", tweaks.gridDensity);
    const accentMap = {
      neon: "#00FF7A",
      mint: "#B0FFD9",
      cyber: "#7FE9FF"
    };
    r.style.setProperty("--pen-accent", accentMap[tweaks.accentVariant] || accentMap.neon);
    // Also push to neon token for full effect
    if (tweaks.accentVariant === "cyber") {
      r.style.setProperty("--pen-neon", "#7FE9FF");
      r.style.setProperty("--accent", "#7FE9FF");
      r.style.setProperty("--pen-line", "rgba(127,233,255,0.16)");
      r.style.setProperty("--pen-line-strong", "rgba(127,233,255,0.34)");
    } else {
      r.style.setProperty("--pen-neon", "#00FF7A");
      r.style.setProperty("--accent", "#00FF7A");
      r.style.setProperty("--pen-line", "rgba(0,255,122,0.14)");
      r.style.setProperty("--pen-line-strong", "rgba(0,255,122,0.32)");
    }
  }, [tweaks.glow, tweaks.gridDensity, tweaks.accentVariant]);

  useEffectA(() => {
    const handleOpen = () => setShowModal(true);
    window.addEventListener("open-diagnostic-modal", handleOpen);
    return () => window.removeEventListener("open-diagnostic-modal", handleOpen);
  }, []);

  const onCta = () => {
    setShowModal(true);
  };

  return (
    <div className="pen-page">
      <div className="pen-ambient" />
      <div className="pen-ambient-scan" />

      <StatusBar copy={copy.statusBar} />
      <Header copy={copy.nav} onCta={onCta} onNav={navigateTo} />
      
      {view === "landing" && (
        <>
          <Hero copy={copy.hero} consoleCopy={copy.consoleHero} onCta={onCta} />
          <SectionVuln copy={copy.vuln} />
          <SectionSoluciones copy={copy.soluciones} />
          <SectionComo copy={copy.como} />
          <SectionClientes copy={copy.clientes} />
          <SectionFAQ copy={copy.faq} />
          <SectionFinalCta copy={copy.finalCta} onCta={onCta} />
        </>
      )}

      {view === "about" && (
        <SectionAbout onBack={() => navigateTo("landing")} />
      )}

      {view === "blog" && (
        <SectionBlog onBack={() => navigateTo("landing")} />
      )}

      {view === "contact" && (
        <SectionContact onBack={() => navigateTo("landing")} />
      )}

      {view === "platforms" && (
        <SectionPlatforms copy={copy.platforms} onBack={() => navigateTo("landing")} />
      )}

      {view === "crm" && (
        <SectionCRM onBack={() => navigateTo("landing")} />
      )}

      <FooterPen copy={copy.footer} onNav={navigateTo} />

      <Toast toast={toast} />

      <DiagnosticModal isOpen={showModal} onClose={() => setShowModal(false)} />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Idioma">
          <TweakRadio
            value={tweaks.lang}
            onChange={(v) => setTweak("lang", v)}
            options={[
            { value: "es", label: "Español" },
            { value: "en", label: "English" }]
            } />
          
        </TweakSection>
        <TweakSection title="Visuales">
          <TweakSlider
            label="Intensidad del glow"
            min={0} max={1} step={0.05}
            value={tweaks.glow}
            onChange={(v) => setTweak("glow", v)} />
          
          <TweakSlider
            label="Densidad del grid"
            min={0} max={0.12} step={0.005}
            value={tweaks.gridDensity}
            onChange={(v) => setTweak("gridDensity", v)} />
          
          <TweakRadio
            label="Acento"
            value={tweaks.accentVariant}
            onChange={(v) => setTweak("accentVariant", v)}
            options={[
            { value: "neon", label: "Neon" },
            { value: "mint", label: "Mint" },
            { value: "cyber", label: "Cyber" }]
            } />
          
        </TweakSection>
      </TweaksPanel>
    </div>);

}

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