// Shared layout — Header + Footer + theme persistence across pages.
// Each page imports this and renders its content inside <Layout active="...">.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "whiteLabel": "ai-company",
  "hexIntensity": "subtle"
}/*EDITMODE-END*/;

const THEMES = {
  'ai-company': { brandName: 'AI Company',       primary: '#1B3A6B', secondary: '#1E6BB0', accent: '#E8620A' },
  'bakery':     { brandName: 'Panadería Aurora', primary: '#7C2D12', secondary: '#C2410C', accent: '#FACC15' },
  'fashion':    { brandName: 'Atelier Noir',     primary: '#18181B', secondary: '#52525B', accent: '#E11D48' },
  'wellness':   { brandName: 'Verde Salud',      primary: '#14532D', secondary: '#16A34A', accent: '#F59E0B' },
};

// Read theme from localStorage so it persists across pages
function readPersistedTheme(){
  try {
    const v = localStorage.getItem('aic_theme');
    if (v) return JSON.parse(v);
  } catch(e){}
  return { whiteLabel: 'ai-company', custom: THEMES['ai-company'], hexIntensity: 'subtle' };
}
function persistTheme(state){
  try{ localStorage.setItem('aic_theme', JSON.stringify(state)); }catch(e){}
}

function applyTheme(theme){
  const r = document.documentElement;
  r.style.setProperty('--brand-primary',   theme.primary);
  r.style.setProperty('--brand-secondary', theme.secondary);
  r.style.setProperty('--brand-accent',    theme.accent);
}

// Re-export SiteHeader & SiteFooter that accept "active" prop
function NavHeader({ theme, active = '' }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const items = [
    { id: 'como-funciona', label: 'Cómo funciona', href: 'como-funciona.html' },
    { id: 'colaboradores', label: 'Colaboradores',  href: 'colaboradores.html' },
    { id: 'casos-de-uso',  label: 'Casos de uso',   href: 'casos-de-uso.html' },
    { id: 'precios',       label: 'Precios',        href: 'precios.html' },
    { id: 'blog',          label: 'Blog',           href: 'blog.html' },
  ];

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

  return (
    <header className="site" data-screen-label="Header">
      <div className="container inner">
        <a className="brand" href="index.html">
          <span className="glyph"/>
          <span className="name">{theme.brandName}</span>
        </a>
        <nav className="primary" aria-label="Principal">
          {items.map(it => (
            <a key={it.id} href={it.href} className={active === it.id ? 'active' : ''}>{it.label}</a>
          ))}
        </nav>
        <div className="header-cta">
          <a href="contacto.html" className="login">Contacto</a>
          <a href="demo.html" className="btn btn-primary btn-cta-header">Empieza gratis</a>
          <button
            className="hamburger"
            aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
          >
            <span className={'bar ' + (menuOpen ? 'open' : '')}/>
            <span className={'bar ' + (menuOpen ? 'open' : '')}/>
            <span className={'bar ' + (menuOpen ? 'open' : '')}/>
          </button>
        </div>
      </div>

      {/* Mobile drawer */}
      <div className={'mobile-drawer ' + (menuOpen ? 'open' : '')} onClick={() => setMenuOpen(false)}>
        <div className="mobile-drawer-inner" onClick={e => e.stopPropagation()}>
          <nav aria-label="Móvil">
            {items.map(it => (
              <a key={it.id} href={it.href} className={active === it.id ? 'active' : ''}>{it.label}</a>
            ))}
            <a href="contacto.html">Contacto</a>
            <a href="demo.html" className="btn btn-primary btn-lg" style={{ marginTop: 12, justifyContent:'center' }}>Empieza gratis →</a>
          </nav>
        </div>
      </div>
    </header>
  );
}

function NavFooter({ theme }) {
  const cols = [
    { title: 'Producto', items: [
      ['Cómo funciona', 'como-funciona.html'],
      ['Colaboradores', 'colaboradores.html'],
      ['Casos de uso',  'casos-de-uso.html'],
      ['Precios',       'precios.html'],
      ['Demo',          'demo.html'],
    ]},
    { title: 'Empresa', items: [
      ['Blog',          'blog.html'],
      ['Sobre nosotros','#'],
      ['Contacto',      'contacto.html'],
      ['Prensa',        '#'],
      ['Carreras',      '#'],
    ]},
    { title: 'Legal', items: [
      ['Privacidad', '#'], ['Términos','#'], ['Cookies','#'], ['Seguridad','#'], ['GDPR','#'],
    ]},
  ];
  return (
    <footer style={{ background:'#0A1428', color:'rgba(255,255,255,.7)', padding:'56px 0 24px' }} data-screen-label="Footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="brand" style={{ color:'#fff' }}>
              <span className="glyph"/>
              <span className="name">{theme.brandName}</span>
            </div>
            <p style={{ marginTop: 16, fontSize: 13.5, maxWidth: '32ch', color:'rgba(255,255,255,.65)' }}>
              Plataforma SaaS para convertir cualquier negocio en una empresa autónoma operada por colaboradores de IA.
            </p>
            <div style={{ marginTop: 16, display:'flex', gap: 10 }}>
              {['IG','X','LI','YT'].map(s => (
                <a key={s} href="#" style={{
                  width: 34, height: 34, borderRadius: 8,
                  background:'rgba(255,255,255,.06)', border:'1px solid rgba(255,255,255,.08)',
                  display:'inline-flex', alignItems:'center', justifyContent:'center',
                  fontSize: 11, fontWeight: 600, color:'#fff',
                }}>{s}</a>
              ))}
            </div>
          </div>
          {cols.map(c => (
            <div key={c.title}>
              <div style={{ fontSize: 12, fontWeight: 700, color:'#fff', textTransform:'uppercase', letterSpacing:'.08em', marginBottom: 14 }}>{c.title}</div>
              <ul style={{ listStyle:'none', padding: 0, margin: 0, display:'flex', flexDirection:'column', gap: 10 }}>
                {c.items.map(([label, href]) => (
                  <li key={label}><a href={href} style={{ fontSize: 13.5, color:'rgba(255,255,255,.7)' }}>{label}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div style={{
          marginTop: 40, padding: '16px 20px',
          background:'rgba(232,98,10,.1)', border:'1px solid rgba(232,98,10,.2)',
          borderRadius: 12, color:'rgba(255,255,255,.85)', fontSize: 13, lineHeight: 1.5,
          display:'flex', alignItems:'center', gap: 12, flexWrap:'wrap',
        }}>
          <span style={{
            background:'var(--brand-accent)', color:'#fff',
            padding:'4px 10px', borderRadius: 999,
            fontSize: 11, fontWeight: 700, letterSpacing:'.06em', textTransform:'uppercase',
            display:'inline-flex', alignItems:'center', gap: 6, flexShrink: 0,
          }}>
            <span className="pulse-dot"/> Operado por AI Company
          </span>
          <span>
            Este sitio es operado por AI Company. Nuestros propios colaboradores gestionan el contenido, las campañas y la atención al cliente de esta página. <a href="blog.html" style={{ color:'var(--brand-accent)', fontWeight: 600 }}>Léelo en el blog →</a>
          </span>
        </div>

        <div style={{
          marginTop: 28, paddingTop: 24, borderTop:'1px solid rgba(255,255,255,.08)',
          display:'flex', justifyContent:'space-between', alignItems:'center', gap: 16,
          fontSize: 12.5, color:'rgba(255,255,255,.5)', flexWrap:'wrap',
        }}>
          <span>© 2026 AI Company. Todos los derechos reservados.</span>
          <span>Hecho con colaboradores IA · Disponible en ES · EN · PT</span>
        </div>
      </div>
    </footer>
  );
}

function PageHero({ crumb, title, subtitle, eyebrow }) {
  return (
    <section className="page-hero hex-pattern subtle" data-screen-label="Page Hero">
      <div className="container">
        {crumb && (
          <div className="crumb">
            {crumb.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span style={{ opacity:.5 }}>/</span>}
                {c.href ? <a href={c.href}>{c.label}</a> : <span>{c.label}</span>}
              </React.Fragment>
            ))}
          </div>
        )}
        {eyebrow && <div className="eyebrow" style={{ marginBottom: 14 }}><span className="dot"/> {eyebrow}</div>}
        <h1 className="h-display" style={{ fontSize: 'clamp(32px, 4.4vw, 52px)' }}>{title}</h1>
        {subtitle && <p className="lead" style={{ marginTop: 16, fontSize: 18 }}>{subtitle}</p>}
      </div>
    </section>
  );
}

// Layout component — wraps page content, applies theme.
function Layout({ active, children }) {
  const [state, setState] = React.useState(readPersistedTheme);
  const theme = state.whiteLabel === 'custom' ? state.custom : (THEMES[state.whiteLabel] || THEMES['ai-company']);

  React.useEffect(() => {
    applyTheme(theme);
    document.body.dataset.hex = state.hexIntensity;
    persistTheme(state);
  }, [state.whiteLabel, state.hexIntensity, theme.primary, theme.secondary, theme.accent]);

  // Reveal-on-scroll
  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.12 });
    document.querySelectorAll('.section').forEach(s => { s.classList.add('reveal'); io.observe(s); });
    return () => io.disconnect();
  }, []);

  const childrenWithTheme = React.Children.map(children, child =>
    React.isValidElement(child) ? React.cloneElement(child, { theme }) : child
  );

  return (
    <>
      <NavHeader theme={theme} active={active} />
      <main>{childrenWithTheme}</main>
      <NavFooter theme={theme} />
    </>
  );
}

Object.assign(window, { Layout, NavHeader, NavFooter, PageHero, THEMES, readPersistedTheme });
