// BEAKEN — primitivos compartidos
const { useState, useEffect, useRef, useMemo } = React;

// ---- Router (hash-based) ----
const useRoute = () => {
  const [route, setRoute] = useState(() => (window.location.hash || '#/').replace('#', '') || '/');
  useEffect(() => {
    const onHash = () => {
      setRoute((window.location.hash || '#/').replace('#', '') || '/');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
};

const navigate = (path) => { window.location.hash = path; };

// ---- Reveal on scroll ----
const Reveal = ({ children, delay = 0, as: Tag = 'div', className = '', ...rest }) => {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVis(true); io.unobserve(el); }
    }, { threshold: 0.12, rootMargin: '-40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const delayClass = delay ? ` reveal-delay-${delay}` : '';
  return (
    <Tag ref={ref} className={`reveal${vis ? ' in' : ''}${delayClass} ${className}`} {...rest}>
      {children}
    </Tag>
  );
};

// ---- SVG icons ----
const Arr = ({ className = '' }) => (
  <svg className={`arr ${className}`} viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8">
    <path d="M3 11 L11 3 M5 3 L11 3 L11 9"/>
  </svg>
);
const ArrRight = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8">
    <path d="M2 7 L12 7 M8 3 L12 7 L8 11"/>
  </svg>
);
const Plus = ({ size = 12 }) => (
  <svg width={size} height={size} viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.8">
    <path d="M6 1 V11 M1 6 H11"/>
  </svg>
);
const Check = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="2">
    <path d="M3 9 L7.5 13 L15 5"/>
  </svg>
);
const Cross = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8">
    <path d="M3 3 L11 11 M11 3 L3 11"/>
  </svg>
);

// ---- Nav ----
const Nav = ({ route }) => {
  const primary = [
    { to: '/', label: 'Agency' },
    { to: '/lab', label: 'Lab' },
    { to: '/academy', label: 'Academy' },
  ];
  const secondary = [
    { to: '/origo', label: 'Origo Beaken', desc: 'Joint Venture · Estrategia + IA' },
    { to: '/aliados', label: 'Aliados', desc: 'Instituciones y Empresas Impulsoras' },
    { to: '/mentores', label: 'Mentores', desc: 'Comunidad de especialistas' },
  ];
  const isActive = (to) => to === '/' ? (route === '/' || route === '' || route === '/agency') : route === to;
  const secondaryActive = secondary.some(s => s.to === route);

  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (!open) return;
    const close = () => setOpen(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [open]);

  return (
    <nav className="nav">
      <div className="container nav-inner">
        <a href="#/" className="nav-logo" onClick={(e) => { e.preventDefault(); navigate('/'); }}>
          <img src="assets/logo.png" alt="Beaken" />
        </a>
        <div className="nav-links">
          {primary.map(l => (
            <a key={l.to} href={`#${l.to}`} onClick={(e)=>{e.preventDefault();navigate(l.to);}}
               className={`nav-link nav-link-primary${isActive(l.to) ? ' active' : ''}`}>{l.label}</a>
          ))}
          <div className={`nav-dropdown${open ? ' open' : ''}${secondaryActive ? ' active' : ''}`}>
            <button className="nav-link nav-link-more" onClick={(e)=>{e.stopPropagation();setOpen(!open);}}>
              Más
              <svg className="nav-chev" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M3 4.5 L6 7.5 L9 4.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
            <div className="nav-dropdown-menu">
              {secondary.map(s => (
                <a key={s.to} href={`#${s.to}`}
                   onClick={(e)=>{e.preventDefault();setOpen(false);navigate(s.to);}}
                   className={`nav-dropdown-item${route === s.to ? ' active' : ''}`}>
                  <span className="ddi-label">{s.label}</span>
                  <span className="ddi-desc">{s.desc}</span>
                </a>
              ))}
            </div>
          </div>
          <a href="#/contacto" onClick={(e)=>{e.preventDefault();navigate('/contacto');}} className="nav-cta">
            <span className="pulse"></span> Hablemos
          </a>
        </div>
        <div className="nav-burger">
          <a href="#/contacto" onClick={(e)=>{e.preventDefault();navigate('/contacto');}} className="nav-cta">
            <span className="pulse"></span> Contacto
          </a>
        </div>
      </div>
    </nav>
  );
};

// ---- Mexico Central Time ----
const useClock = () => {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(id);
  }, []);
  return now;
};

const getMexicoTime = (date) => date.toLocaleString('es-MX', {
  timeZone: 'America/Mexico_City',
  hour: '2-digit', minute: '2-digit', hour12: false,
});

const isOpen = (date) => {
  const local = new Date(date.toLocaleString('en-US', { timeZone: 'America/Mexico_City' }));
  const d = local.getDay(), t = local.getHours() * 60 + local.getMinutes();
  return d >= 1 && d <= 5 && t >= 540 && t < 1080;
};

// ---- Ticker ----
const Ticker = () => {
  const now = useClock();
  const mxTime = getMexicoTime(now);
  const open = isOpen(now);

  const items = [
    { k: 'STATUS', v: 'AGENDANDO Q2 2026', live: true },
    { k: 'PROMESA', v: 'DIAGNÓSTICO EN 2 HORAS' },
    { k: 'HORA CST', v: `${mxTime} · ${open ? 'ABIERTO' : 'CERRADO'}`, live: true },
    { k: 'METODOLOGÍA', v: 'BLUEPRINT + SPRINT' },
    { k: 'COBERTURA', v: 'MX · LATAM · REMOTO' },
    { k: 'TICKET ENTRADA', v: 'DESDE $1,000 MXN' },
    { k: 'INCUBADORA', v: 'COMMUNITY 2026 ABIERTO' },
    { k: 'ACADEMY', v: 'TALLERES IA · PRÓXIMA FECHA' },
    { k: 'BASE', v: 'LEÓN GTO · MX' },
  ];
  const loop = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {loop.map((it, i) => (
          <span key={i} className="ticker-item">
            <span>{it.k}</span>
            <span className="sep">//</span>
            <span className={it.live ? 'val' : ''}>{it.v}</span>
          </span>
        ))}
      </div>
    </div>
  );
};

// ---- Section header ----
const SecHead = ({ num, title, sub, right }) => (
  <div className="sec-head">
    <Reveal className="sec-num">{num}</Reveal>
    <Reveal delay={1}>
      <h2 className="sec-title" dangerouslySetInnerHTML={{ __html: title }}></h2>
      {sub && <p style={{ marginTop: 20, maxWidth: 720, fontSize: 18, lineHeight: 1.45, color: 'var(--body)', fontWeight: 400, fontFamily: 'var(--font-body)' }}>{sub}</p>}
      {right}
    </Reveal>
  </div>
);

// ---- Image block with HUD ----
const ImgBlock = ({ src, caption, code = "BK-001", label = "HERO" }) => (
  <div className="imgblock" style={{ height: '100%', minHeight: 360 }}>
    <img src={src} alt={caption} referrerPolicy="no-referrer" />
    <div className="veil"></div>
    <div className="crosshair ch-tl"></div>
    <div className="crosshair ch-br"></div>
    <div className="hud">
      <span className="live"><span className="dot"></span> LIVE · {code}</span>
      <span>{label}</span>
    </div>
    <div className="cap">{caption}</div>
  </div>
);

// ---- Big CTA ----
const BigCTA = ({ title, sub, cta, eyebrow }) => (
  <section className="big-cta">
    <Reveal>
      <div className="container">
        <div style={{ marginBottom: 24 }}>
          <span className="tag" style={{ background: 'rgba(255,255,255,0.15)', color: '#fff', borderColor: 'rgba(255,255,255,0.3)' }}>
            <span className="dot" style={{ background: '#fff' }}></span> {eyebrow || 'LLAMADA DE 15 MIN · GRATIS'}
          </span>
        </div>
        <h2>{title}</h2>
        <p>{sub}</p>
        <a href="#/contacto" onClick={(e)=>{e.preventDefault();navigate('/contacto');}} className="btn btn-primary">
          {cta || 'Agenda tu llamada'} <Arr />
        </a>
      </div>
    </Reveal>
  </section>
);

// ---- Section anchor (numbered subsection heading) ----
const SectionAnchor = ({ num, label, title }) => (
  <Reveal className="section-anchor">
    <div className="num">{num}</div>
    <div>
      <div className="label">{label}</div>
      <h3>{title}</h3>
    </div>
  </Reveal>
);

// ---- Footer ----
const Footer = () => (
  <footer className="footer">
    <div className="container" style={{ position: 'relative', zIndex: 2 }}>
      <div className="footer-grid">
        <div>
          <div className="footer-logo">
            <img src="assets/logo.png" alt="Beaken" />
          </div>
          <p className="mono up" style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', lineHeight: 1.8 }}>
            Inteligencia de Negocios<br/>
            Aplicada · Diagnóstico ·<br/>
            Ejecución · Adopción
          </p>
          <div style={{ marginTop: 24, display: 'flex', gap: 8 }}>
            <span className="tag dark"><span className="dot"></span> AGENDANDO Q2 2026</span>
          </div>
        </div>
        <div className="footer-col">
          <h4>Unidades</h4>
          <ul>
            <li><a href="#/" onClick={(e)=>{e.preventDefault();navigate('/');}}>Agency</a></li>
            <li><a href="#/lab" onClick={(e)=>{e.preventDefault();navigate('/lab');}}>Lab</a></li>
            <li><a href="#/academy" onClick={(e)=>{e.preventDefault();navigate('/academy');}}>Academy</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Ecosistema</h4>
          <ul>
            <li><a href="#/origo" onClick={(e)=>{e.preventDefault();navigate('/origo');}}>Origo Beaken</a></li>
            <li><a href="#/aliados" onClick={(e)=>{e.preventDefault();navigate('/aliados');}}>Aliados</a></li>
            <li><a href="#/mentores" onClick={(e)=>{e.preventDefault();navigate('/mentores');}}>Mentores</a></li>
            <li><a href="#/contacto" onClick={(e)=>{e.preventDefault();navigate('/contacto');}}>Contacto</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Base</h4>
          <ul>
            <li><a href="mailto:hola@beaken.mx">hola@beaken.mx</a></li>
            <li>León, Guanajuato</li>
            <li style={{ color: 'rgba(255,255,255,0.55)' }}>Operación remota LATAM</li>
          </ul>
        </div>
      </div>
      <div className="footer-bot">
        <p>© 2026 BEAKEN · INTELIGENCIA DE NEGOCIOS APLICADA</p>
        <p>v.26.04 · BEAKEN.AGENCY</p>
      </div>
    </div>
    <div className="footer-big">BEAKEN</div>
  </footer>
);

// Export
Object.assign(window, {
  useRoute, navigate, Reveal, Arr, ArrRight, Plus, Check, Cross,
  Nav, Ticker, SecHead, ImgBlock, BigCTA, SectionAnchor, Footer,
  useClock, getMexicoTime, isOpen,
});
