/* global React, GenesisLogo, SlashMotif, Reveal, RotatingWord, Eyebrow, StepBadge */
const { useState, useEffect, useRef } = React;

/* ============================================================
   THEME RAIL — seletor vertical delicado na lateral (segue o scroll)
   ============================================================ */
function ThemeRail({ theme, onTheme }) {
  const themes = [
    { id: "dark",  label: "Escuro", icon: <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" /> },
    { id: "glass", label: "Vidro",  icon: <path d="M12 3s6 5.4 6 10a6 6 0 0 1-12 0c0-4.6 6-10 6-10z" /> },
    { id: "light", label: "Claro",  icon: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" /></> },
  ];
  return (
    <div className="gen-rail" role="group" aria-label="Tema da página">
      <span className="gen-rail-cap" aria-hidden="true">Tema</span>
      {themes.map((th) => (
        <button
          key={th.id}
          type="button"
          data-label={th.label}
          aria-label={"Tema " + th.label}
          aria-pressed={theme === th.id}
          className={"gen-rail-btn " + (theme === th.id ? "is-active" : "")}
          onClick={() => onTheme && onTheme(th.id)}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{th.icon}</svg>
        </button>
      ))}
    </div>
  );
}

/* ============================================================
   THEME SWITCH — seletor de tema + acento no header
   ============================================================ */
function ThemeSwitch({ theme, accentMode, onTheme, onAccent }) {
  const themes = [
    { id: "dark",  label: "Escuro", icon: <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" /> },
    { id: "glass", label: "Vidro",  icon: <path d="M12 3s6 5.4 6 10a6 6 0 0 1-12 0c0-4.6 6-10 6-10z" /> },
    { id: "light", label: "Claro",  icon: <><circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" /></> },
  ];
  const accents = [
    { id: "mint", color: "#3CE285", label: "Menta" },
    { id: "cyan", color: "#10CAFE", label: "Ciano" },
  ];
  return (
    <div className="gen-switch" role="group" aria-label="Tema e cor de destaque">
      <div className="gen-seg" role="group" aria-label="Tema da página">
        {themes.map((th) => (
          <button
            key={th.id}
            type="button"
            title={"Tema " + th.label}
            aria-label={"Tema " + th.label}
            aria-pressed={theme === th.id}
            className={"gen-seg-btn " + (theme === th.id ? "is-active" : "")}
            onClick={() => onTheme && onTheme(th.id)}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{th.icon}</svg>
            <span className="gen-seg-lbl">{th.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ============================================================
   HEADER
   ============================================================ */
function Header({ theme = "dark", accentMode = "mint", onTheme, onAccent }) {
  const [menu, setMenu] = React.useState(false);
  const links = [
    ["#governanca", "Governança"],
    ["#ia-atendimento", "IA WhatsApp"],
    ["#assinaturas", "Assinaturas"],
    ["#fechamento", "Fechamento"],
    ["#planos", "Planos"],
  ];
  const themes = [
    ["dark", "Escuro"],
    ["glass", "Vidro"],
    ["light", "Claro"],
  ];
  React.useEffect(() => {
    document.body.style.overflow = menu ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menu]);
  return (
    <header className="gen-header">
      <div className="gen-container gen-header__inner">
        <a href="#top" aria-label="Gênesis S/A — início">
          <GenesisLogo size={32} variant="full" />
        </a>
        <nav className="gen-nav" aria-label="principal">
          {links.map(([h, t]) => <a key={h} href={h}>{t}</a>)}
        </nav>
        <div className="gen-header__right">
          <a href="#cta" className="gen-btn gen-btn--primary gen-header__cta" style={{ padding: "12px 20px", fontSize: 14 }}>
            Ver Planos <span className="arrow">→</span>
          </a>
          <button
            className={"gen-burger " + (menu ? "is-open" : "")}
            onClick={() => setMenu(v => !v)}
            aria-label={menu ? "Fechar menu" : "Abrir menu"}
            aria-expanded={menu}
          >
            <i /><i /><i />
          </button>
        </div>
      </div>

      {/* Menu mobile */}
      <div className={"gen-drawer " + (menu ? "is-open" : "")} role="dialog" aria-label="Menu" aria-hidden={!menu}>
        <nav className="gen-drawer__nav">
          {links.map(([h, t], i) => (
            <a key={h} href={h} onClick={() => setMenu(false)} style={{ "--i": i }}>
              <span className="gen-drawer__n">{String(i + 1).padStart(2, "0")}</span>
              {t}
            </a>
          ))}
        </nav>
        <div className="gen-drawer__foot">
          <span className="gen-drawer__lbl">Tema</span>
          <div className="gen-drawer__themes">
            {themes.map(([id, label]) => (
              <button
                key={id}
                className={"gen-drawer__theme " + (theme === id ? "is-active" : "")}
                onClick={() => onTheme && onTheme(id)}
                aria-pressed={theme === id}
              >{label}</button>
            ))}
          </div>
          <a href="#cta" className="gen-btn gen-btn--primary gen-drawer__cta" onClick={() => setMenu(false)}>
            Ver Planos <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function Hero() {
  return (
    <section className="gen-section" id="top" data-screen-label="01 Hero" style={{ paddingTop: 80, paddingBottom: 0, position: "relative" }}>
      <SlashMotif opacity={0.07} />
      <div className="gen-container" style={{ position: "relative" }}>
        <div className="hero-grid" style={{ display: "grid", gridTemplateColumns: "1.4fr 0.9fr", gap: 64, alignItems: "start" }}>
        <div>
        <Reveal stagger={0}>
          <div className="gen-eyebrow" style={{ marginBottom: 32 }}>
            — GOVERNANÇA COM INTELIGÊNCIA OPERACIONAL
          </div>
        </Reveal>

        <Reveal stagger={1}>
          <h1 className="gen-h1" style={{ margin: 0, maxWidth: "16ch", fontSize: "clamp(48px, 5.4vw, 96px)", lineHeight: 0.92 }}>
            Pare de gerir<br />
            seu negócio na<br />
            <RotatingWord words={["sorte.", "adivinhação.", "sorte.", "esperança."]} />
          </h1>
        </Reveal>

        <Reveal stagger={2}>
          <p className="gen-lead" style={{ marginTop: 40, maxWidth: "52ch" }}>
            Receba o diagnóstico real do seu lucro <strong style={{ color: "var(--fg)" }}>todo dia no seu WhatsApp</strong>.
            Blindagem financeira, comissões auditadas e uma IA que atende leads e recupera clientes.
            Finalmente, um sistema de governança que faz o trabalho braçal por você.
          </p>
        </Reveal>

        <Reveal stagger={3}>
          <div style={{ display: "flex", gap: 16, marginTop: 48, flexWrap: "wrap" }}>
            <a href="#planos" className="gen-btn gen-btn--primary gen-btn--lg">
              Ver Planos de Governança <span className="arrow">→</span>
            </a>
            <a href="https://wa.me/5562994987799" target="_blank" rel="noreferrer" className="gen-btn gen-btn--ghost gen-btn--lg">
              <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
                <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12.04 2C6.6 2 2.18 6.42 2.18 11.86c0 1.94.56 3.75 1.53 5.28L2 22l4.99-1.66a9.83 9.83 0 0 0 5.05 1.38c5.44 0 9.86-4.42 9.86-9.86C21.9 6.42 17.48 2 12.04 2Zm0 17.86c-1.6 0-3.1-.44-4.38-1.2l-.31-.19-3.07 1.02 1.03-3-.2-.32a7.94 7.94 0 0 1-1.2-4.31c0-4.4 3.58-7.98 8.13-7.98 4.4 0 7.98 3.58 7.98 7.98 0 4.4-3.58 8-8 8Z"/>
                  <path d="M17.47 14.38c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.95 1.17-.17.2-.35.22-.65.07-.3-.15-1.23-.45-2.34-1.44-.86-.77-1.44-1.72-1.62-2.02-.17-.3-.02-.47.13-.62.13-.13.3-.35.45-.52.15-.18.2-.3.3-.5.1-.2.05-.37-.03-.52-.07-.15-.67-1.62-.92-2.2-.24-.58-.49-.5-.67-.5h-.57c-.2 0-.52.07-.79.37-.27.3-1.04 1.02-1.04 2.48s1.06 2.88 1.21 3.08c.15.2 2.08 3.32 5.06 4.52 2.98 1.2 3.28.98 3.87.92.6-.05 1.93-.79 2.2-1.55.27-.77.27-1.42.2-1.55-.08-.13-.28-.2-.58-.35Z"/>
                </svg>
                Falar no WhatsApp
              </span>
            </a>
          </div>
        </Reveal>
        </div>

        {/* Right column — phone mockup */}
        <Reveal stagger={2}>
          <HeroPhoneMockup />
        </Reveal>
        </div>

        {/* Stats row */}
        <Reveal stagger={4}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 0,
            marginTop: 96,
            borderTop: "1px solid var(--line)",
            paddingTop: 32
          }} className="hero-stats">
            {[
              [<CountUp value={100} suffix="%" />, "comissões auditadas"],
              ["24/7", "IA no WhatsApp"],
              [<CountUp value={1} suffix=" clique" />, "fechamento mensal"],
              ["Diário", "resumo executivo"],
            ].map(([num, lbl]) => (
              <div key={lbl} style={{ padding: "0 24px 0 0", borderRight: "1px solid var(--line)" }}>
                <div style={{ fontFamily: "var(--ff-condensed)", fontSize: "clamp(36px, 4vw, 56px)", lineHeight: 1, color: "var(--accent)" }}>{num}</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--fg-muted)", marginTop: 8 }}>{lbl}</div>
              </div>
            ))}
          </div>
        </Reveal>

        {/* Hero mockup — WhatsApp + dashboard schematic */}
        <Reveal stagger={5}>
          <HeroMockup />
        </Reveal>
      </div>
      <style>{`
        @media (max-width: 980px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 48px !important; }
          .hero-phone-wrap { max-width: 380px; margin: 0 auto; }
        }
        @media (max-width: 720px) {
          .hero-stats { grid-template-columns: repeat(2, 1fr) !important; gap: 24px !important; }
          .hero-stats > div { border-right: 0 !important; }
        }
      `}</style>
    </section>
  );
}

function HeroPhoneMockup() {
  return (
    <div className="hero-phone-wrap" style={{ position: "relative", paddingTop: 8, maxWidth: 340, marginLeft: "auto" }}>
      {/* Ambient glow */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: "-12% -22%",
        background: "radial-gradient(58% 50% at 50% 35%, rgba(var(--accent-rgb), 0.22), transparent 72%)",
        filter: "blur(28px)", pointerEvents: "none", zIndex: 0
      }} />

      {/* iPhone 17 titanium frame */}
      <div style={{
        position: "relative", zIndex: 1,
        borderRadius: 54,
        padding: 8,
        background: "linear-gradient(155deg, #6f7479 0%, #2a2d31 30%, #16181a 55%, #2a2d31 78%, #5a5e63 100%)",
        boxShadow: "0 40px 90px -22px rgba(0,0,0,0.75), 0 0 0 1px rgba(255,255,255,0.05) inset, 0 -2px 0 1px rgba(255,255,255,0.08) inset"
      }}>
        {/* Side buttons */}
        <div aria-hidden="true" style={{ position: "absolute", left: -2, top: 110, width: 3, height: 28, background: "#3a3d40", borderRadius: 2 }} />
        <div aria-hidden="true" style={{ position: "absolute", left: -2, top: 160, width: 3, height: 56, background: "#3a3d40", borderRadius: 2 }} />
        <div aria-hidden="true" style={{ position: "absolute", left: -2, top: 230, width: 3, height: 56, background: "#3a3d40", borderRadius: 2 }} />
        <div aria-hidden="true" style={{ position: "absolute", right: -2, top: 180, width: 3, height: 80, background: "#3a3d40", borderRadius: 2 }} />

        {/* Inner bezel */}
        <div style={{
          borderRadius: 47,
          padding: 3,
          background: "#000",
          position: "relative"
        }}>
          {/* Screen */}
          <div style={{
            borderRadius: 44,
            background: "#0a0d12",
            position: "relative",
            overflow: "hidden",
            aspectRatio: "9 / 19.5"
          }}>

            {/* Placeholder visual when no video */}
            <div aria-hidden="true" style={{
              position: "absolute", inset: 0,
              background: "radial-gradient(120% 80% at 50% 0%, rgba(16,202,254,0.22), transparent 60%), linear-gradient(170deg, #0c1929 0%, #07080e 60%, #0a1422 100%)"
            }} />
            {/* Tela real do sistema */}
            <img
              src={window.__resources.heroAppScreen}
              alt="Agenda do GÊNESIS em operação"
              style={{
                position: "absolute", inset: 0, width: "100%", height: "100%",
                objectFit: "cover", zIndex: 1
              }}
            />
            <div aria-hidden="true" style={{
              position: "absolute", inset: 0, zIndex: 1,
              background: "linear-gradient(180deg, rgba(6,13,20,0.4) 0%, transparent 26%, rgba(6,13,20,0.5) 76%, rgba(6,13,20,0.92) 100%)"
            }} />
            {/* Diagonal slashes */}
            <svg aria-hidden="true" width="100%" height="100%" style={{ position: "absolute", inset: 0, opacity: 0.07 }} preserveAspectRatio="none" viewBox="0 0 100 200">
              {Array.from({ length: 10 }).map((_, i) => (
                <line key={i} x1={-30 + i * 18} y1="-10" x2={20 + i * 18} y2="220" stroke="#10cafe" strokeWidth="0.6" />
              ))}
            </svg>

            {/* Bottom caption */}
            <div style={{
              position: "absolute", left: 0, right: 0, bottom: 26, zIndex: 2,
              padding: "0 22px", textAlign: "center"
            }}>
              <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9.5, letterSpacing: "0.2em", color: "var(--accent)", textTransform: "uppercase" }}>
                Tela real do sistema
              </div>
              <div style={{ fontFamily: "var(--ff-condensed)", fontSize: 18, lineHeight: 1.05, color: "#fff", marginTop: 8, textTransform: "uppercase", letterSpacing: "0.01em" }}>
                Agenda auditada<br/>por cadeira
              </div>
            </div>

            {/* Bottom home indicator */}
            <div aria-hidden="true" style={{
              position: "absolute", bottom: 8, left: "50%", transform: "translateX(-50%)",
              width: 120, height: 4, background: "rgba(255,255,255,0.55)", borderRadius: 3, zIndex: 3
            }} />
          </div>
        </div>
      </div>

      {/* Floating caption tag */}
      <div style={{
        position: "absolute", left: -16, bottom: 190, zIndex: 2,
        background: "var(--bg)",
        border: "1px solid var(--line-strong)",
        padding: "8px 14px",
        borderRadius: 999,
        fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--fg)",
        display: "inline-flex", alignItems: "center", gap: 8,
        boxShadow: "0 8px 20px -8px rgba(0,0,0,0.5)"
      }}>
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--accent)", boxShadow: "0 0 10px var(--accent)" }} />
        GÊNESIS · iPhone
      </div>
    </div>
  );
}

function HeroMockup() {
  const [ref, inView] = useInView({ threshold: 0.15 });
  return (
   <MockupCtx.Provider value={inView}>
    <div id="video" ref={ref} className={"gen-mockup " + (inView ? "in" : "")} style={{
      marginTop: 80,
      position: "relative",
      borderRadius: "var(--r-lg)",
      overflow: "hidden",
      border: "1px solid var(--line-strong)",
      background: "linear-gradient(180deg, #0a1320 0%, #060a13 100%)",
      boxShadow: "var(--shadow-lg), 0 0 80px -30px rgba(var(--accent-rgb), 0.25)",
      opacity: inView ? 1 : 0,
      transform: inView ? "translateY(0)" : "translateY(24px)",
      transition: "opacity 800ms ease, transform 800ms cubic-bezier(0.22,0.61,0.36,1)"
    }}>
      {/* Grid background */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        backgroundImage: "linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px)",
        backgroundSize: "44px 44px",
        maskImage: "radial-gradient(ellipse 80% 60% at 50% 40%, #000 30%, transparent 80%)",
        pointerEvents: "none"
      }} />
      {/* Glow accents */}
      <div aria-hidden="true" style={{
        position: "absolute", top: "-10%", left: "20%", width: "60%", height: 200,
        background: "radial-gradient(60% 100% at 50% 0%, rgba(var(--accent-rgb), 0.18), transparent 70%)",
        pointerEvents: "none", filter: "blur(40px)"
      }} />

      {/* Scan line on reveal */}
      <div className="gen-scanline" aria-hidden="true" />

      {/* Top status bar */}
      <CommandTopBar />

      <div style={{
        display: "grid",
        gridTemplateColumns: "1.4fr 1fr",
        position: "relative"
      }} className="hero-mockup-grid">
        {/* Left — command center */}
        <div style={{ padding: "20px 28px 28px", borderRight: "1px solid rgba(255,255,255,0.05)" }}>
          <CommandCenter />
        </div>
        {/* Right — WhatsApp stream */}
        <div style={{ background: "#0a1218", padding: "20px 24px 24px", display: "flex", flexDirection: "column", gap: 12, position: "relative" }}>
          <WhatsAppHeader />
          <WhatsAppExecutiveReport />
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .hero-mockup-grid { grid-template-columns: 1fr !important; }
          .hero-mockup-grid > div:first-child { border-right: 0 !important; border-bottom: 1px solid rgba(255,255,255,0.05); }
        }
        @keyframes gen-pulse-dot { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.45; transform: scale(0.85); } }
        @keyframes gen-scan { 0% { transform: translateY(-30%); } 100% { transform: translateY(800%); } }
        @keyframes gen-marquee { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }
        @keyframes gen-cursor-blink { 0%, 49% { opacity: 1; } 50%, 100% { opacity: 0; } }
        @keyframes gen-ping { 0% { transform: scale(1); opacity: 0.6; } 100% { transform: scale(2.5); opacity: 0; } }
        @keyframes gen-bar-rise { 0% { transform: scaleY(0.05); } 100% { transform: scaleY(1); } }
        @keyframes gen-fade-up { 0% { opacity: 0; transform: translateY(8px); } 100% { opacity: 1; transform: translateY(0); } }
        @keyframes gen-draw { from { stroke-dashoffset: var(--len); } to { stroke-dashoffset: 0; } }
        @keyframes gen-scanline { 0% { transform: translateY(-100%); opacity: 0; } 20% { opacity: 1; } 80% { opacity: 1; } 100% { transform: translateY(600%); opacity: 0; } }
        .gen-mockup .gen-stagger { opacity: 0; transform: translateY(12px); }
        .gen-mockup.in .gen-stagger { opacity: 1; transform: translateY(0); transition: opacity 700ms ease, transform 700ms cubic-bezier(0.22,0.61,0.36,1); transition-delay: var(--d, 0ms); }
        .gen-mockup .gen-draw-line { stroke-dasharray: var(--len); stroke-dashoffset: var(--len); }
        .gen-mockup.in .gen-draw-line { animation: gen-draw 2200ms cubic-bezier(0.65,0,0.35,1) forwards; animation-delay: 300ms; }
        .gen-mockup .gen-fill-area { opacity: 0; }
        .gen-mockup.in .gen-fill-area { opacity: 1; transition: opacity 1400ms ease 1200ms; }
        .gen-mockup .gen-head-dot { opacity: 0; }
        .gen-mockup.in .gen-head-dot { opacity: 1; transition: opacity 400ms ease 2400ms; }
        .gen-mockup .gen-tooltip { opacity: 0; transform: translateY(-6px); }
        .gen-mockup.in .gen-tooltip { opacity: 1; transform: translateY(0); transition: opacity 500ms ease 2600ms, transform 500ms ease 2600ms; }
        .gen-mockup .gen-sparkline { stroke-dasharray: 200; stroke-dashoffset: 200; }
        .gen-mockup.in .gen-sparkline { animation: gen-draw 1600ms ease-out forwards; --len: 200; animation-delay: var(--d, 1400ms); }
        .gen-mockup .gen-scanline { position: absolute; left: 0; right: 0; top: 0; height: 80px; pointer-events: none; z-index: 4;
          background: linear-gradient(180deg, transparent 0%, rgba(var(--accent-rgb), 0.06) 50%, transparent 100%);
          mix-blend-mode: screen; }
        .gen-mockup.in .gen-scanline { animation: gen-scanline 2200ms ease-out 200ms; }
      `}</style>
    </div>
   </MockupCtx.Provider>
  );
}

function CommandTopBar() {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 16,
      padding: "12px 24px",
      borderBottom: "1px solid rgba(255,255,255,0.05)",
      background: "rgba(0,0,0,0.25)",
      fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase",
      color: "rgba(255,255,255,0.55)"
    }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 8, color: "var(--accent)" }}>
        <span style={{ position: "relative", width: 8, height: 8 }}>
          <span style={{ position: "absolute", inset: 0, borderRadius: "50%", background: "var(--accent)", animation: "gen-pulse-dot 1.4s ease-in-out infinite" }} />
          <span style={{ position: "absolute", inset: 0, borderRadius: "50%", background: "var(--accent)", animation: "gen-ping 1.6s ease-out infinite" }} />
        </span>
        Sistema online
      </span>
      <span style={{ color: "rgba(255,255,255,0.18)" }}>·</span>
      <span>Sessão #G-4471</span>
      <span style={{ color: "rgba(255,255,255,0.18)" }}>·</span>
      <span>Latência 38ms</span>
      <span style={{ flex: 1 }} />
      <span style={{ color: "rgba(255,255,255,0.4)" }}>
        Última sincronização <span style={{ color: "#fff" }}>há 4s</span>
      </span>
    </div>
  );
}

function useInView(opts = { threshold: 0.25 }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current || inView) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); obs.disconnect(); }
    }, opts);
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [inView]);
  return [ref, inView];
}

function useTicker(target, durationMs = 1400, active = true) {
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    if (!active) return;
    let raf, start = null;
    const initial = 0;
    const step = (t) => {
      if (start === null) start = t;
      const p = Math.min(1, (t - start) / durationMs);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(initial + (target - initial) * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target, active, durationMs]);
  return val;
}

const MockupCtx = React.createContext(false);

function CommandCenter() {
  const inView = React.useContext(MockupCtx);
  const revenue = useTicker(184720, 2000, inView);
  const profit = useTicker(62418, 2000, inView);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => (t + 1) % 1000), 1600);
    return () => clearInterval(id);
  }, []);

  return (
    <div style={{ position: "relative" }}>
      {/* Header */}
      <div className="gen-stagger" style={{ "--d": "100ms", display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 20 }}>
        <div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--ff-mono)", fontSize: 10, color: "rgba(255,255,255,0.5)", letterSpacing: "0.2em", textTransform: "uppercase" }}>
            <svg width="10" height="10" viewBox="0 0 10 10"><circle cx="5" cy="5" r="2" fill="var(--accent)" /></svg>
            Faturamento · Novembro / 2026
          </div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 6 }}>
            <span style={{ fontFamily: "var(--ff-condensed)", fontSize: 44, lineHeight: 1, color: "#fff", letterSpacing: "-0.01em" }}>
              R$ {Math.round(revenue).toLocaleString("pt-BR")}
            </span>
            <span style={{ width: 2, height: 28, background: "var(--accent)", animation: "gen-cursor-blink 1s steps(1) infinite" }} />
          </div>
          <div style={{ display: "flex", gap: 14, marginTop: 8, fontFamily: "var(--ff-mono)", fontSize: 11 }}>
            <span style={{ color: "var(--accent)" }}>↑ 23,4% MoM</span>
            <span style={{ color: "rgba(255,255,255,0.35)" }}>—</span>
            <span style={{ color: "rgba(255,255,255,0.55)" }}>Meta atingida em 18d</span>
          </div>
        </div>

        {/* Mini radial gauge */}
        <RadialGauge value={73} label="Margem" />
      </div>

      {/* Live area chart */}
      <div className="gen-stagger" style={{ "--d": "200ms" }}>
        <LiveAreaChart />
      </div>

      {/* Mini stat strip */}
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 1fr", gap: 12, marginTop: 18 }}>
        <StatTile delay="1400ms" label="Lucro líquido" value={`R$ ${(profit / 1000).toFixed(1).replace(".", ",")}k`} spark={[12, 18, 14, 22, 19, 28, 24, 32, 30, 36]} accent />
        <StatTile delay="1550ms" label="Cadeiras ocupadas" value="88%" spark={[8, 6, 9, 12, 10, 13, 11, 14, 13, 15]} />
        <StatTile delay="1700ms" label="Assinantes ativos" value="247" delta="+12" spark={[5, 7, 6, 8, 9, 10, 11, 13, 14, 16]} accent />
      </div>

      {/* Activity feed */}
      <div className="gen-stagger" style={{ "--d": "1900ms", marginTop: 18, paddingTop: 14, borderTop: "1px dashed rgba(255,255,255,0.08)" }}>
        <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: "rgba(255,255,255,0.4)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 10, display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--accent)", animation: "gen-pulse-dot 1.4s infinite" }} />
          Eventos · streaming
        </div>
        <ActivityFeed tick={tick} inView={inView} />
      </div>
    </div>
  );
}

function RadialGauge({ value = 73, label = "Margem" }) {
  const inView = React.useContext(MockupCtx);
  const r = 30, c = 2 * Math.PI * r;
  const animated = useTicker(value, 1800, inView);
  const offset = c - (animated / 100) * c;
  return (
    <div style={{ position: "relative", width: 88, height: 88 }}>
      <svg viewBox="0 0 88 88" width="88" height="88" style={{ transform: "rotate(-90deg)" }}>
        <circle cx="44" cy="44" r={r} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="6" />
        <circle cx="44" cy="44" r={r} fill="none" stroke="var(--accent)"
          strokeWidth="6" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={offset}
          style={{ filter: "drop-shadow(0 0 6px rgba(var(--accent-rgb), 0.6))", transition: "stroke-dashoffset 80ms linear" }} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
        <div>
          <div style={{ fontFamily: "var(--ff-condensed)", fontSize: 20, color: "#fff", lineHeight: 1 }}>{Math.round(animated)}<span style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", marginLeft: 1 }}>%</span></div>
          <div style={{ fontFamily: "var(--ff-mono)", fontSize: 8, color: "rgba(255,255,255,0.45)", letterSpacing: "0.18em", textTransform: "uppercase", marginTop: 2 }}>{label}</div>
        </div>
      </div>
    </div>
  );
}

function LiveAreaChart() {
  // 28 data points, smooth-ish
  const data = React.useMemo(() => {
    const seed = [42, 48, 44, 56, 52, 60, 58, 64, 62, 72, 68, 76, 74, 80, 82, 90, 88, 94, 102, 98, 108, 112, 118, 124, 132, 138, 146, 156];
    return seed;
  }, []);
  const W = 520, H = 150, P = 4;
  const min = Math.min(...data), max = Math.max(...data);
  const points = data.map((v, i) => {
    const x = P + (i / (data.length - 1)) * (W - 2 * P);
    const y = H - P - ((v - min) / (max - min)) * (H - 2 * P);
    return [x, y];
  });
  const line = points.map(([x, y], i) => `${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${y.toFixed(1)}`).join(" ");
  const area = `${line} L ${W - P} ${H - P} L ${P} ${H - P} Z`;
  const [head] = points.slice(-1);

  return (
    <div style={{ position: "relative", width: "100%", overflow: "hidden", borderRadius: 8 }}>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: "100%", height: 150, display: "block" }}>
        <defs>
          <linearGradient id="genArea" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.45" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </linearGradient>
          <pattern id="genGrid" width="40" height="30" patternUnits="userSpaceOnUse">
            <path d="M 40 0 L 0 0 0 30" fill="none" stroke="rgba(255,255,255,0.04)" strokeWidth="1" />
          </pattern>
        </defs>
        <rect width={W} height={H} fill="url(#genGrid)" />
        {/* y-axis baselines */}
        {[0.25, 0.5, 0.75].map((p, i) => (
          <line key={i} x1={P} x2={W - P} y1={H * p} y2={H * p} stroke="rgba(255,255,255,0.05)" strokeDasharray="2 4" />
        ))}
        <path className="gen-fill-area" d={area} fill="url(#genArea)" />
        <path className="gen-draw-line" d={line} fill="none" stroke="var(--accent)" strokeWidth="2"
          style={{ "--len": 1800, filter: "drop-shadow(0 2px 8px rgba(var(--accent-rgb), 0.5))" }} />
        {/* head dot */}
        <g className="gen-head-dot">
          <circle cx={head[0]} cy={head[1]} r="8" fill="var(--accent)" opacity="0.2">
            <animate attributeName="r" values="6;16;6" dur="2.2s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.35;0;0.35" dur="2.2s" repeatCount="indefinite" />
          </circle>
          <circle cx={head[0]} cy={head[1]} r="4" fill="var(--accent)" />
          <line x1={head[0]} x2={head[0]} y1={head[1]} y2={H} stroke="var(--accent)" strokeOpacity="0.35" strokeDasharray="2 3" />
        </g>
      </svg>
      {/* Floating tooltip on head */}
      <div className="gen-tooltip" style={{
        position: "absolute", right: 8, top: 6,
        background: "rgba(0,0,0,0.65)", border: "1px solid rgba(var(--accent-rgb), 0.4)",
        padding: "6px 10px", borderRadius: 4,
        fontFamily: "var(--ff-mono)", fontSize: 10, color: "#fff",
        letterSpacing: "0.06em",
        backdropFilter: "blur(8px)"
      }}>
        <div style={{ color: "var(--accent)", fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase" }}>22 Nov · 22:14</div>
        <div>R$ 8.420 <span style={{ color: "rgba(255,255,255,0.5)" }}>(+18%)</span></div>
      </div>
      {/* x-axis */}
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontFamily: "var(--ff-mono)", fontSize: 9, color: "rgba(255,255,255,0.35)", letterSpacing: "0.14em" }}>
        <span>01/11</span><span>08/11</span><span>15/11</span><span>22/11</span>
      </div>
    </div>
  );
}

function StatTile({ label, value, spark = [], delta, accent, delay = "0ms" }) {
  const min = Math.min(...spark), max = Math.max(...spark);
  const w = 100, h = 28;
  const pts = spark.map((v, i) => {
    const x = (i / (spark.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * h;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  return (
    <div className="gen-stagger" style={{
      "--d": delay,
      padding: "12px 14px",
      border: "1px solid rgba(255,255,255,0.06)",
      background: "rgba(255,255,255,0.015)",
      borderRadius: 6,
      position: "relative",
      overflow: "hidden"
    }}>
      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, color: "rgba(255,255,255,0.45)", letterSpacing: "0.16em", textTransform: "uppercase" }}>{label}</div>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginTop: 4 }}>
        <span style={{ fontFamily: "var(--ff-condensed)", fontSize: 22, color: accent ? "var(--accent)" : "#fff", lineHeight: 1 }}>{value}</span>
        {delta && <span style={{ fontFamily: "var(--ff-mono)", fontSize: 10, color: "var(--accent)" }}>{delta}</span>}
      </div>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: 24, marginTop: 6, display: "block" }}>
        <polyline className="gen-sparkline" style={{ "--d": `calc(${delay} + 600ms)` }} points={pts} fill="none" stroke={accent ? "var(--accent)" : "rgba(255,255,255,0.45)"} strokeWidth="1.2" />
      </svg>
    </div>
  );
}

function ActivityFeed({ tick, inView }) {
  const events = [
    { c: "var(--accent)", k: "TX", t: "Pagamento confirmado · Cliente #4471 · R$ 89,00" },
    { c: "#fff", k: "AI", t: "IA respondeu lead em 8s · agendou 14:30 quinta" },
    { c: "var(--accent)", k: "COM", t: "Comissão lançada · Bruno · R$ 26,70 (líquido)" },
    { c: "#fff", k: "AUD", t: "Auditoria sem divergência · 184 atendimentos" },
    { c: "var(--accent)", k: "REC", t: "Cliente recuperado · não vinha há 47 dias" },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      {events.map((e, i) => (
        <div key={i} style={{
          display: "grid", gridTemplateColumns: "auto 38px 1fr auto", gap: 10, alignItems: "center",
          padding: "6px 0",
          opacity: inView ? (1 - i * 0.12) : 0,
          transform: inView ? "translateY(0)" : "translateY(8px)",
          transition: `opacity 500ms ease ${2100 + i * 140}ms, transform 500ms ease ${2100 + i * 140}ms`
        }}>
          <span style={{ width: 6, height: 6, borderRadius: "50%", background: e.c, boxShadow: `0 0 6px ${e.c}` }} />
          <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, color: "rgba(255,255,255,0.5)", letterSpacing: "0.16em" }}>{e.k}</span>
          <span style={{ fontFamily: "var(--ff-body)", fontSize: 12, color: "rgba(255,255,255,0.82)" }}>{e.t}</span>
          <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, color: "rgba(255,255,255,0.35)" }}>{`22:1${4 - i}`}</span>
        </div>
      ))}
    </div>
  );
}

function WhatsAppHeader() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, paddingBottom: 12, borderBottom: "1px solid #1f2c33" }}>
      <div style={{
        width: 40, height: 40, borderRadius: "50%",
        background: "#0b141a", display: "grid", placeItems: "center",
        position: "relative", overflow: "hidden",
        boxShadow: "0 0 0 1px rgba(16,202,254,0.45), 0 0 16px -4px rgba(16,202,254,0.7)"
      }}>
        <img src={(window.__resources && window.__resources.genesisG) || "genesis-g.png"} alt="Gênesis" style={{ width: 26, height: 26, objectFit: "contain" }} />
      </div>
      <div>
        <div style={{ color: "#e9edef", fontSize: 15, fontWeight: 600 }}>Gênesis · IA Executiva</div>
        <div style={{ color: "#8696a0", fontSize: 12 }}>online · diagnóstico diário</div>
      </div>
    </div>
  );
}

function WhatsAppExecutiveReport() {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, fontFamily: "var(--ff-body)" }}>
      <div className="gen-stagger" style={{ "--d": "300ms", alignSelf: "center", fontSize: 11, color: "#8696a0", background: "#182229", padding: "4px 12px", borderRadius: 8 }}>
        hoje · 22:14
      </div>
      <div className="gen-stagger wa-bubble" style={{ "--d": "900ms" }}>
        <div style={{ fontWeight: 600, marginBottom: 6 }}>📊 Resumo Executivo · 22 Nov</div>
        Faturamento bruto: <strong>R$ 8.420</strong><br />
        Lucro líquido: <strong>R$ 2.840</strong> (33,7%)<br />
        Ociosidade cadeiras: <strong>14%</strong>
        <span className="wa-bubble__time"> 22:14 ✓✓</span>
      </div>
      <div className="gen-stagger wa-bubble" style={{ "--d": "1600ms" }}>
        ⚠️ <strong>1 cliente recorrente</strong> não voltou em 47 dias.<br />
        Disparei mensagem de recuperação automática.
        <span className="wa-bubble__time"> 22:14 ✓✓</span>
      </div>
      <div className="gen-stagger wa-bubble" style={{ "--d": "2300ms" }}>
        🎯 <strong>3 colaboradores</strong> bateram meta hoje. Comissões já lançadas nos extratos.
        <span className="wa-bubble__time"> 22:14 ✓✓</span>
      </div>
    </div>
  );
}

Object.assign(window, { Header, Hero, HeroPhoneMockup, ThemeRail });
