// app.jsx — Main shell: Navbar + routing + Footer

function Navbar({ page, go, scrolled }) {
  const [menuOpen, setMenuOpen] = React.useState(false);

  // Lock body scroll when menu is open
  React.useEffect(() => {
    if (menuOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen]);

  // Close menu on page change
  React.useEffect(() => {
    setMenuOpen(false);
  }, [page]);

  const links = [
    { id: 'home', label: 'Inicio' },
    { id: 'copytrading', label: 'CopyTrading' },
    { id: 'signals', label: 'Premium' },
    { id: 'tradingview', label: 'Análisis' },
    { id: 'fondeadas', label: 'Cuentas de Fondeo' },
    { id: 'academia', label: 'Academia' },
  ];
  const handleClick = (id) => {
    setMenuOpen(false);
    go(id);
  };
  return (
    <>
      <header className={"fixed top-0 left-0 right-0 z-[70] transition-all duration-300 " + (scrolled || page !== 'home' || menuOpen ? 'nav-solid' : '')} style={{ height: 68 }}>
        <div className="max-w-[1280px] mx-auto px-5 md:px-8 h-full flex items-center justify-between gap-6">
          {/* Logo */}
          <button onClick={() => { setMenuOpen(false); go('home'); }} className="flex items-center gap-2.5 group shrink-0" aria-label="DAMCOVISION inicio">
            <img src="img/damcovision.svg" alt="DAMCOVISION" className="logo-white h-[26px] md:h-[28px] w-auto" style={{ filter: 'brightness(0) invert(1) drop-shadow(0 0 12px rgba(0,212,255,0.35))' }} />
          </button>

          {/* Desktop nav */}
          <nav className="hidden lg:flex items-center gap-1 flex-1 justify-center">
            {links.map(l => {
              const active = page === l.id;
              return (
                <button
                  key={l.id}
                  onClick={() => handleClick(l.id)}
                  className="relative px-3.5 py-2 text-[13.5px] font-medium transition-all rounded-md"
                  style={{
                    color: active ? '#ffffff' : 'var(--text-dim)',
                    background: active ? 'rgba(0,212,255,0.08)' : 'transparent',
                  }}
                  onMouseEnter={(e) => { if (!active) e.currentTarget.style.color = '#cdf2ff'; }}
                  onMouseLeave={(e) => { if (!active) e.currentTarget.style.color = 'var(--text-dim)'; }}
                >
                  {l.label}
                  {active && (
                    <span className="absolute left-1/2 -translate-x-1/2 -bottom-1 w-1.5 h-1.5 rounded-full" style={{ background: '#00d4ff', boxShadow: '0 0 10px #00d4ff' }}></span>
                  )}
                </button>
              );
            })}
          </nav>

          {/* CTA */}
          <div className="hidden lg:flex items-center gap-2.5 shrink-0">
            <button className="btn btn-primary text-[13px] py-2.5 px-4" onClick={() => go('empezar')}>
              Empezar Ahora <Icon name="arrow-right" size={14} />
            </button>
          </div>

          {/* Mobile */}
          <button className="lg:hidden w-10 h-10 rounded-lg flex items-center justify-center relative z-10" style={{ border: '1px solid var(--border)', background: menuOpen ? 'rgba(0,212,255,0.08)' : 'transparent' }} onClick={() => setMenuOpen(v => !v)} aria-label="Menú" aria-expanded={menuOpen}>
            <Icon name={menuOpen ? 'x' : 'menu'} size={18} />
          </button>
        </div>
      </header>

      {/* Mobile menu overlay — OUTSIDE header for proper fixed positioning */}
      {menuOpen && (
        <div className="lg:hidden fixed left-0 right-0 z-[65]" style={{ top: 68, bottom: 0, background: '#06060e', overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
          <div className="px-5 py-6 flex flex-col gap-1.5">
            {links.map(l => {
              const active = page === l.id;
              return (
                <button
                  key={l.id}
                  onClick={() => handleClick(l.id)}
                  className="text-left px-4 py-3.5 rounded-xl flex items-center justify-between"
                  style={{
                    background: active ? 'rgba(0,212,255,0.10)' : 'rgba(255,255,255,0.025)',
                    border: '1px solid ' + (active ? 'rgba(0,212,255,0.4)' : 'var(--border)'),
                    color: active ? '#ffffff' : 'var(--text)',
                  }}
                >
                  <span className="font-display font-semibold text-[17px]">{l.label}</span>
                  {active ? (
                    <span className="w-2 h-2 rounded-full" style={{ background: '#00d4ff', boxShadow: '0 0 10px #00d4ff' }}></span>
                  ) : (
                    <Icon name="arrow-right" size={16} />
                  )}
                </button>
              );
            })}
            <button className="btn btn-primary justify-center mt-4 text-base py-3.5" onClick={() => { setMenuOpen(false); go('empezar'); }}>
              Empezar Ahora <Icon name="arrow-right" size={15} />
            </button>
          </div>
        </div>
      )}
    </>
  );
}

function Footer({ go }) {
  return (
    <footer className="relative pt-20 pb-10" style={{ background: '#04040a', borderTop: '1px solid var(--border)' }}>
      <div className="absolute inset-x-0 top-0 h-px" style={{ background: 'linear-gradient(90deg, transparent, rgba(0,212,255,0.3), transparent)' }}></div>
      <Container>
        <div className="grid lg:grid-cols-[1.4fr_1fr_1fr_1fr] gap-10 mb-14">
          {/* Brand */}
          <div>
            <button onClick={() => go('home')} className="flex items-center gap-2.5 mb-5" aria-label="DAMCOVISION inicio">
              <img src="img/damcovision.svg" alt="DAMCOVISION" className="logo-white h-[26px] w-auto" />
            </button>
            <p className="text-[14px] max-w-xs leading-relaxed" style={{ color: 'var(--text-dim)' }}>
              Ecosistema premium para trading de índices sintéticos. Educación, señales, copy y fondeo.
            </p>
            <div className="flex flex-wrap gap-2 mt-5">
              {[
                { name: 'send', label: 'Telegram', href: 'https://t.me/damcovision' },
                { name: 'instagram', label: 'Instagram', href: 'https://instagram.com/damcovision' },
                { name: 'music-2', label: 'TikTok', href: 'https://tiktok.com/@damcovision' },
              ].map((s, i) => (
                <a key={i} href={s.href} target="_blank" rel="noopener noreferrer" title={s.label + ' @damcovision'} className="w-9 h-9 rounded-lg flex items-center justify-center transition-all hover:bg-cyan-300/10 hover:border-cyan-300/40" style={{ background: 'rgba(255,255,255,0.025)', border: '1px solid var(--border)', color: 'var(--text-dim)' }}>
                  <Icon name={s.name} size={15} />
                </a>
              ))}
              <div className="flex items-center px-3 ml-1 rounded-lg font-mono text-[11px]" style={{ background: 'rgba(0,212,255,0.06)', border: '1px solid rgba(0,212,255,0.2)', color: '#7fe5ff' }}>
                @damcovision
              </div>
            </div>
          </div>

          {/* Columns */}
          {[
            { title: 'Servicios', links: [
              { l: 'CopyTrading', p: 'copytrading' },
              { l: 'Premium', p: 'signals' },
              { l: 'Análisis', p: 'tradingview' },
              { l: 'Cuentas de Fondeo', p: 'fondeadas' },
              { l: 'Academia', p: 'academia' },
            ]},
            { title: 'Comunidad', links: [
              { l: 'Señales gratis (Telegram)', p: 'https://t.me/damcovision', ext: true },
              { l: 'Noticias Cuentas de Fondeo', p: 'https://chat.whatsapp.com/B8MjHQVaxN4IaFkDT6HMvc', ext: true },
              { l: 'Anuncios CopyTrading', p: 'https://chat.whatsapp.com/I6Iblc8inKX9sZtaIXH2NU', ext: true },
              { l: 'Soporte directo', p: 'https://t.me/barbieshark', ext: true },
            ]},
            { title: 'Legal', links: [
              { l: 'Términos', p: '#' }, { l: 'Privacidad', p: '#' }, { l: 'Disclaimer', p: '#' }, { l: 'Contacto', p: 'https://t.me/barbieshark', ext: true },
            ]},
          ].map((col, ci) => (
            <div key={ci}>
              <div className="font-display font-bold text-[14.5px] mb-4">{col.title}</div>
              <ul className="space-y-2.5">
                {col.links.map((l, i) => (
                  <li key={i}>
                    {l.ext ? (
                      <a href={l.p} target="_blank" rel="noopener noreferrer" className="text-[13.5px] hover:text-white transition-colors inline-flex items-center gap-1.5" style={{ color: 'var(--text-dim)' }}>
                        {l.l} <Icon name="external-link" size={11} style={{ opacity: 0.5 }} />
                      </a>
                    ) : (
                      <button
                        onClick={() => typeof l.p === 'string' && l.p !== '#' ? go(l.p) : null}
                        className="text-[13.5px] hover:text-white transition-colors text-left"
                        style={{ color: 'var(--text-dim)' }}
                      >
                        {l.l}
                      </button>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div className="rounded-xl p-5 mb-8" style={{ background: 'rgba(212,160,23,0.05)', border: '1px solid rgba(212,160,23,0.15)' }}>
          <div className="flex items-start gap-3">
            <Icon name="alert-triangle" size={18} style={{ color: '#f0d68a', marginTop: 2 }} />
            <p className="text-[12.5px] leading-relaxed" style={{ color: '#c8b87a' }}>
              <span className="text-white font-semibold">Disclaimer: </span>
              DAMCOVISION no garantiza ganancias. Operar en mercados financieros implica riesgos sustanciales y puede generar pérdidas. Las rentabilidades pasadas no garantizan resultados futuros. No gestionamos cuentas de terceros. Operá con responsabilidad.
            </p>
          </div>
        </div>

        <div className="pt-6 flex flex-wrap items-center justify-between gap-4 border-t" style={{ borderColor: 'var(--border)' }}>
          <div className="font-mono text-[11.5px]" style={{ color: 'var(--text-mute)' }}>
            © 2026 DAMCOVISION · Todos los derechos reservados
          </div>
          <div className="flex items-center gap-4 font-mono text-[11px]" style={{ color: 'var(--text-mute)' }}>
            <span className="flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full anim-blink" style={{ background: '#10b981' }}></span>
              SISTEMA OPERATIVO
            </span>
            <span>v2026.05</span>
          </div>
        </div>
      </Container>
    </footer>
  );
}

// ============================================================
// LANDING (composed)
// ============================================================
function Landing({ go }) {
  return (
    <>
      <Hero go={go} />
      <MarketTicker />
      <BrokerStrip />
      <QueOperamos />
      <Sobre />
      <Servicios go={go} />
      <AcademiaBlock go={go} />
      <Resultados />
      <Fondeadas go={go} />
      <Testimonios />
      <CTAFinal go={go} />
    </>
  );
}

// ============================================================
// APP
// ============================================================

// Mapa de rutas URL ↔ pageId
const ROUTES = {
  '/':            'home',
  '/copytrading': 'copytrading',
  '/premium':     'signals',
  '/analisis':    'tradingview',
  '/fondeadas':   'fondeadas',
  '/academia':    'academia',
  '/empezar':     'empezar',
};
// Inverso: pageId → path
const PAGE_TO_PATH = Object.fromEntries(Object.entries(ROUTES).map(([k, v]) => [v, k]));

function pathToPage(pathname) {
  // Normalizar: quitar trailing slash excepto en "/"
  const clean = pathname.replace(/\/$/, '') || '/';
  return ROUTES[clean] || 'home';
}

function App() {
  const [page, setPage] = React.useState(() => pathToPage(window.location.pathname));
  const [scrolled, setScrolled] = React.useState(false);

  // Scroll listener para el navbar
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Escuchar botón "atrás / adelante" del navegador
  React.useEffect(() => {
    const onPop = () => {
      const p = pathToPage(window.location.pathname);
      setPage(p);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const go = React.useCallback((p) => {
    const path = PAGE_TO_PATH[p] || '/';
    // Solo hacer pushState si la ruta cambia
    if (window.location.pathname !== path) {
      window.history.pushState({ page: p }, '', path);
    }
    setPage(p);
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, []);

  useReveal();
  React.useEffect(() => {
    // re-trigger reveal on page change
    const t = setTimeout(() => {
      document.querySelectorAll('.reveal').forEach(el => {
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight - 40) el.classList.add('in');
      });
    }, 50);
    return () => clearTimeout(t);
  }, [page]);

  let content;
  if (page === 'home') content = <Landing go={go} />;
  else if (page === 'copytrading') content = <PageCopyTrading go={go} />;
  else if (page === 'signals') content = <PageSignals go={go} />;
  else if (page === 'tradingview') content = <PageTradingView go={go} />;
  else if (page === 'fondeadas') content = <PageFondeadas go={go} />;
  else if (page === 'academia') content = <PageAcademia go={go} />;
  else if (page === 'empezar') content = <PageEmpezar go={go} />;
  else content = <Landing go={go} />;

  return (
    <div data-screen-label={page === 'home' ? '01 Home' : '02 ' + page}>
      <Navbar page={page} go={go} scrolled={scrolled} />
      <main>{content}</main>
      <Footer go={go} />
    </div>
  );
}

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