/* global React, Icon, Button, Eyebrow, Badge, Droplets, Container */

const { useState, useEffect, useRef } = React;

// ============================================================
// MENU MODEL — mapped to the FRSKO sitemap
// ============================================================
const HUES = {
  leadgen:     { soft: 'var(--sub-leadgen-bg)',     ink: 'var(--sub-leadgen-1)' },
  neuro:       { soft: 'var(--sub-neuro-bg)',       ink: 'var(--sub-neuro-1)' },
  interactive: { soft: 'var(--sub-interactive-bg)', ink: 'var(--sub-interactive-1)' },
  academy:     { soft: 'var(--sub-academy-bg)',     ink: 'var(--sub-academy-1)' },
  start:       { soft: 'var(--sub-start-bg)',       ink: 'var(--sub-start-1)' },
  cyan:        { soft: 'var(--cyan-50)',            ink: 'var(--cyan-800)' },
  teal:        { soft: 'var(--teal-50)',            ink: 'var(--teal-700)' },
  yellow:      { soft: 'var(--yellow-50)',          ink: 'var(--yellow-700)' },
};

// Static export adapter. For the future build, remove these overrides so
// links resolve to their clean sitemap routes.
const STATIC_ROUTE_OVERRIDES = {
  '/': '/',
};

const HUBSPOT_MEETING_URL = 'https://meetings.hubspot.com/cristian13';

function linkTo(route) {
  return STATIC_ROUTE_OVERRIDES[route] || route;
}

function assetTo(path) {
  if (!path || path[0] !== '/') return path;
  const isLeadEngineFolder = window.location.pathname.replace(/\\/g, '/').includes('/ia/lead-engine/');
  const prefix = isLeadEngineFolder ? '../../' : '../';
  return prefix + path.replace(/^\/+/, '');
}

const MENU = [
  {
    label: 'Soluciones IA',
    href: linkTo('/ia'),
    kind: 'mega',
    width: 980,
    eyebrow: 'PRODUCTOS IA',
    intro: 'IA aplicada al marketing — no como adorno, como motor.',
    columns: [
      {
        title: 'Disponibles hoy',
        meta: '6 productos · Live',
        metaTone: 'cyan',
        items: [
          { label: 'Lead Engine AI',       href: linkTo('/ia/lead-engine'),    desc: 'El SDR que nunca duerme',           icon: 'target',     hue: 'leadgen'},
          { label: 'NeuroCopy Lab',        href: linkTo('/ia/neurocopy-lab'),  desc: 'Copy con ciencia, no con suerte',   icon: 'brain',      hue: 'neuro'},
          { label: 'Content Studio AI',    href: linkTo('/ia/content-studio'), desc: '60 piezas al mes, mismo costo',     icon: 'film',       hue: 'interactive'},
          { label: 'Smart Ads AI',         href: linkTo('/ia/smart-ads'),      desc: 'Copiloto para Meta, Google, TikTok',icon: 'zap',        hue: 'cyan'},
          { label: 'SEO Pulse',            href: linkTo('/ia/seo-pulse'),      desc: 'SEO + AEO para ChatGPT y Perplexity',icon: 'search',    hue: 'academy'},
          { label: 'Bootcamps & Workshops',href: linkTo('/ia/bootcamps'),      desc: 'Forma a tu equipo en IA',           icon: 'graduation', hue: 'start'},
        ],
      },
      {
        title: 'Enterprise',
        meta: 'Q3 2026 · Próximamente',
        metaTone: 'neutral',
        muted: true,
        items: [
          { label: 'Onboarding Claude',     href: linkTo('/ia/enterprise/onboarding-claude'),   icon: 'sparkles' },
          { label: 'AI Strategy Sprint',    href: linkTo('/ia/enterprise/ai-strategy-sprint'),  icon: 'compass' },
          { label: 'Sales Co-Pilot',        href: linkTo('/ia/enterprise/sales-copilot'),       icon: 'users' },
          { label: 'Customer Support AI',   href: linkTo('/ia/enterprise/customer-support-ai'), icon: 'message' },
          { label: 'Knowledge Q&A',         href: linkTo('/ia/enterprise/knowledge-qa'),        icon: 'search' },
          { label: 'Content Engine',        href: linkTo('/ia/enterprise/content-engine'),      icon: 'film' },
          { label: 'Market Intelligence',   href: linkTo('/ia/enterprise/market-intelligence'), icon: 'chart' },
          { label: 'Document Automation',   href: linkTo('/ia/enterprise/document-automation'), icon: 'clipboard' },
          { label: 'AI Training in-company',href: linkTo('/ia/enterprise/ai-training'),         icon: 'graduation' },
        ],
        more: 'Ver Enterprise completo',
        moreHref: linkTo('/ia/enterprise'),
      },
    ],
    promo: {
      eyebrow: '5 MIN · GRATIS',
      title: '¿No sabes por dónde empezar?',
      body: 'Responde 5 preguntas y te decimos qué solución FRSKO tiene más sentido para tu empresa hoy.',
      cta: 'Hacer el diagnóstico',
      href: linkTo('/herramientas/diagnostico-ia'),
    },
  },

  {
    label: 'Servicios',
    href: linkTo('/servicios'),
    kind: 'dropdown',
    items: [
      { label: 'Consultoría estratégica', href: linkTo('/servicios/consultoria'),        sub: 'FRSKO Start',           icon: 'compass',    hue: 'start' },
      { label: 'Campañas digitales',      href: linkTo('/servicios/campanas-digitales'), sub: 'FRSKO Interactive',     icon: 'megaphone',  hue: 'interactive' },
      { label: 'Generación de leads',     href: linkTo('/servicios/lead-generation'),    sub: 'FRSKO LeadGen',         icon: 'target',     hue: 'leadgen' },
      { label: 'Neuromarketing',          href: linkTo('/servicios/neuromarketing'),     sub: 'FRSKO Neuro Insights',  icon: 'brain',      hue: 'neuro' },
    ],
  },

  {
    label: 'Industrias',
    href: linkTo('/industrias'),
    kind: 'mega',
    width: 880,
    eyebrow: 'POR VERTICAL',
    intro: 'Llegamos con los playbooks ya probados — los ajustamos a tu caso.',
    columns: [
      {
        title: 'Verticales MX',
        meta: 'México · LATAM',
        metaTone: 'teal',
        items: [
          { label: 'Bienes Raíces',       href: linkTo('/industrias/bienes-raices'),     icon: 'home' },
          { label: 'Retail & E-commerce', href: linkTo('/industrias/retail-ecommerce'),  icon: 'shopping' },
          { label: 'Fintech & Servicios', href: linkTo('/industrias/fintech'),           icon: 'credit-card' },
          { label: 'Salud',               href: linkTo('/industrias/salud'),             icon: 'heart' },
          { label: 'Legal',               href: linkTo('/industrias/legal'),             icon: 'scale' },
          { label: 'B2B & SaaS',          href: linkTo('/industrias/b2b-saas'),          icon: 'server' },
          { label: 'Emprendedores',       href: linkTo('/industrias/emprendedores'),     icon: 'rocket' },
        ],
      },
      {
        title: 'Empresas extranjeras',
        meta: 'Tu equipo en MX',
        metaTone: 'cyan',
        items: [
          { label: 'USA y Canadá',    href: linkTo('/industrias/empresas-extranjeras/usa-canada'),    icon: 'globe', tag: 'EN' },
          { label: 'España y Europa', href: linkTo('/industrias/empresas-extranjeras/espana-europa'), icon: 'globe' },
          { label: 'LATAM',           href: linkTo('/industrias/empresas-extranjeras/latam'),         icon: 'globe' },
        ],
      },
    ],
    promo: {
      eyebrow: 'NEARSHORING',
      title: 'Marketing en México, sin abrir oficina.',
      body: 'Equipo bilingüe, ágil y local. Para marcas de USA, Canadá y Europa.',
      cta: 'Ver propuesta nearshoring',
      href: linkTo('/en/nearshoring-marketing-partner'),
    },
  },

  { label: 'Academy', href: linkTo('/academy'), kind: 'link' },

  {
    label: 'Recursos',
    href: linkTo('/recursos'),
    kind: 'dropdown',
    items: [
      { label: 'Blog IA & Marketing', href: linkTo('/blog'),             sub: '4 categorías activas', icon: 'message',   hue: 'teal' },
      { label: 'Guías & whitepapers', href: linkTo('/guias'),            sub: 'Pillar pages SEO',     icon: 'clipboard', hue: 'cyan' },
      { label: 'Herramientas gratis', href: linkTo('/herramientas'),     sub: 'Calculadoras y diagnóstico IA', icon: 'sparkles', hue: 'yellow' },
      { label: 'Casos de éxito',      href: linkTo('/casos-de-exito'),   sub: 'Pilotos y resultados', icon: 'chart',     hue: 'leadgen' },
    ],
  },
];

// ============================================================
// MEGA / DROPDOWN PANELS
// ============================================================

function MegaPanel({ item, onClose }) {
  const isMega = item.kind === 'mega';
  return (
    <div
      style={{
        position: 'absolute', top: '100%', left: '50%',
        transform: 'translateX(-50%)',
        paddingTop: 10,
        width: isMega
          ? `min(${Math.min(item.width || 960, 1140)}px, calc(100vw - 48px))`
          : 'min(360px, calc(100vw - 48px))',
        animation: 'megaIn 220ms var(--ease-out) both',
      }}
      onMouseLeave={onClose}
    >
      <div style={{
        background: '#fff',
        borderRadius: 24,
        border: '1px solid var(--border)',
        boxShadow: 'var(--shadow-xl)',
        overflow: 'hidden',
      }}>
        {isMega ? <MegaContent item={item} onClose={onClose} /> : <DropdownContent item={item} onClose={onClose} />}
      </div>
    </div>
  );
}

function MegaContent({ item, onClose }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1.4fr 1fr', gap: 0 }}>
      {item.columns.map((col, i) => (
        <MegaColumn key={i} col={col} onClose={onClose} />
      ))}
      <PromoCard promo={item.promo} eyebrow={item.eyebrow} intro={item.intro} />
    </div>
  );
}

function MegaColumn({ col, onClose }) {
  const toneColors = {
    cyan:    { bg: 'var(--cyan-50)',   fg: 'var(--cyan-800)' },
    teal:    { bg: 'var(--teal-50)',   fg: 'var(--teal-700)' },
    neutral: { bg: 'var(--ink-100)',   fg: 'var(--ink-600)' },
  };
  const tone = toneColors[col.metaTone] || toneColors.teal;
  return (
    <div style={{
      padding: '28px 24px 24px',
      borderRight: '1px solid var(--border)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
        <div style={{
          fontFamily: 'var(--font-heading)', fontSize: 12, fontWeight: 700,
          letterSpacing: '0.04em', textTransform: 'uppercase',
          color: col.muted ? 'var(--ink-500)' : 'var(--fg1)',
        }}>{col.title}</div>
        <span style={{
          fontSize: 10, fontWeight: 600, letterSpacing: '0.08em',
          textTransform: 'uppercase',
          padding: '3px 8px', borderRadius: 999,
          background: tone.bg, color: tone.fg,
        }}>{col.meta}</span>
      </div>

      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 4 }}>
        {col.items.map(it => <MegaItem key={it.label} it={it} muted={col.muted} onClose={onClose} />)}
      </ul>

      {col.more && (
        <a href={col.moreHref || '#'} onClick={onClose} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          marginTop: 14, fontSize: 13, fontWeight: 600,
          color: 'var(--brand)', cursor: 'pointer',
        }}>
          {col.more}
          <Icon name="arrow-right" size={14} />
        </a>
      )}
    </div>
  );
}

function MegaItem({ it, muted, onClose }) {
  const hue = HUES[it.hue] || HUES.teal;
  return (
    <li>
      <a href={it.href || '#'} onClick={onClose} style={{
        display: 'flex', alignItems: 'flex-start', gap: 12,
        padding: '10px 12px', borderRadius: 14,
        cursor: 'pointer',
        transition: 'background var(--dur-fast) var(--ease-out)',
      }}
        onMouseEnter={e => { e.currentTarget.style.background = 'var(--ink-50)'; }}
        onMouseLeave={e => { e.currentTarget.style.background = ''; }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10, flexShrink: 0,
          background: muted ? 'var(--ink-50)' : hue.soft,
          color: muted ? 'var(--ink-500)' : hue.ink,
          display: 'grid', placeItems: 'center',
        }}>
          <Icon name={it.icon} size={17} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              fontSize: 14, fontWeight: 600,
              color: muted ? 'var(--fg2)' : 'var(--fg1)',
            }}>{it.label}</span>
            {it.tag && <span style={{
              fontSize: 9, fontWeight: 700, letterSpacing: '0.08em',
              padding: '2px 6px', borderRadius: 4,
              background: 'var(--ink-100)', color: 'var(--ink-600)',
            }}>{it.tag}</span>}
          </div>
          {it.desc && <div style={{ fontSize: 12.5, color: 'var(--fg3)', lineHeight: 1.4, marginTop: 2 }}>{it.desc}</div>}
        </div>
      </a>
    </li>
  );
}

function PromoCard({ promo, eyebrow, intro }) {
  return (
    <div style={{
      background: 'var(--grad-deep)',
      color: '#fff',
      padding: '28px 24px',
      position: 'relative',
      overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      <Droplets style={{ right: -30, top: -20 }} color="rgba(0,218,227,0.3)" opacity={0.7} size={140} />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.14em',
          textTransform: 'uppercase', color: 'var(--cyan-300)', marginBottom: 12,
        }}>{promo.eyebrow}</div>
        <h4 style={{
          fontFamily: 'var(--font-heading)', fontSize: 20, fontWeight: 700,
          letterSpacing: '-0.02em', lineHeight: 1.15, margin: '0 0 10px',
        }}>{promo.title}</h4>
        <p style={{ fontSize: 13.5, lineHeight: 1.55, color: 'rgba(255,255,255,0.75)', margin: 0 }}>
          {promo.body}
        </p>
        <a href={promo.href || '#'} style={{
          marginTop: 'auto',
          paddingTop: 18,
          display: 'inline-flex', alignItems: 'center', gap: 6,
          fontSize: 14, fontWeight: 600, color: 'var(--cta)',
          cursor: 'pointer',
        }}>
          {promo.cta}
          <Icon name="arrow-right" size={15} />
        </a>
      </div>
    </div>
  );
}

function DropdownContent({ item, onClose }) {
  return (
    <div style={{ padding: 12 }}>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 2 }}>
        {item.items.map(it => <MegaItem key={it.label} it={it} onClose={onClose} />)}
      </ul>
      <div style={{
        marginTop: 8, padding: '12px 16px',
        borderTop: '1px solid var(--border)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span style={{ fontSize: 12.5, color: 'var(--fg3)' }}>Ver todo en {item.label.toLowerCase()}</span>
        <a href={item.href || '#'} onClick={onClose} style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          fontSize: 13, fontWeight: 600, color: 'var(--brand)', cursor: 'pointer',
        }}>
          Ir <Icon name="arrow-right" size={13} />
        </a>
      </div>
    </div>
  );
}

// ============================================================
// DESKTOP NAV
// ============================================================

function HeaderCtaLink({ children = 'Habla con un estratega', size = 'sm', style, ...props }) {
  const sizes = {
    sm: { padding: '9px 14px', fontSize: 13 },
    compact: { padding: '8px 12px', fontSize: 12.5 },
    md: { padding: '13px 22px', fontSize: 15 },
  };
  return (
    <a
      href={HUBSPOT_MEETING_URL}
      target="_blank"
      rel="noopener noreferrer"
      {...props}
      style={{
        fontFamily: 'var(--font-body)',
        fontWeight: 600,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 8,
        lineHeight: 1,
        borderRadius: 999,
        letterSpacing: '-0.005em',
        whiteSpace: 'nowrap',
        background: 'var(--cta)',
        color: 'var(--teal-900)',
        boxShadow: 'var(--shadow-cta)',
        cursor: 'pointer',
        ...sizes[size],
        ...(style || {}),
      }}
    >
      {children}
      <Icon name="arrow-right" size={16} />
    </a>
  );
}

function DesktopNav({ scrolled, compact, openIdx, setOpenIdx, onCta }) {
  const closeTimer = useRef(null);
  const open = (i) => {
    clearTimeout(closeTimer.current);
    setOpenIdx(i);
  };
  const scheduleClose = () => {
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpenIdx(null), 120);
  };

  return (
    <Container style={{
      padding: compact ? '11px 20px' : '14px 32px',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: compact ? 14 : 24,
      position: 'relative',
    }}>
      <a href={linkTo('/')} style={{ display: 'inline-flex', position: 'relative', zIndex: 1 }}>
        <img src={assetTo('/ds/assets/Frsko-500px.webp')} alt="FRSKO" style={{ height: compact ? 42 : 48, width: 'auto' }} fetchpriority="high" />
      </a>

      <nav aria-label="Menú principal" style={{ display: 'flex', alignItems: 'center', gap: compact ? 2 : 4, position: 'relative', flex: '0 1 auto' }}>
        {MENU.map((m, i) => {
          const hasPanel = m.kind === 'mega' || m.kind === 'dropdown';
          const isOpen = openIdx === i;
          return (
            <div key={m.label}
              style={{ position: hasPanel ? 'static' : 'relative' }}
              onMouseEnter={() => hasPanel && open(i)}
              onMouseLeave={scheduleClose}>
              <a href={m.href}
                aria-expanded={hasPanel ? isOpen : undefined}
                aria-haspopup={hasPanel ? 'true' : undefined}
                onFocus={() => hasPanel && open(i)}
                onKeyDown={(e) => { if (e.key === 'Escape') setOpenIdx(null); }}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  padding: compact ? '8px 10px' : '8px 14px', borderRadius: 999,
                  fontSize: compact ? 14 : 15, fontWeight: 560,
                  color: isOpen ? 'var(--brand)' : 'var(--fg1)',
                  background: isOpen ? 'var(--teal-50)' : 'transparent',
                  transition: 'all var(--dur-fast) var(--ease-out)',
                  cursor: 'pointer',
                }}>
                {m.label}
                {hasPanel && <Icon name="arrow-right" size={12} style={{ transform: `rotate(${isOpen ? -45 : 45}deg)`, transition: 'transform var(--dur-fast) var(--ease-out)' }} />}
              </a>
              {hasPanel && isOpen && (
                <MegaPanel item={m} onClose={() => setOpenIdx(null)} />
              )}
            </div>
          );
        })}
      </nav>

      <div style={{ display: 'flex', alignItems: 'center', gap: compact ? 10 : 14, position: 'relative', zIndex: 1, flexShrink: 0 }}>
        <a href={linkTo('/herramientas/diagnostico-ia')} style={{ fontSize: compact ? 12.5 : 13.5, color: 'var(--fg2)', fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' }}>
          {compact ? 'Diagnóstico' : 'Diagnóstico gratis'}
        </a>
        <HeaderCtaLink size={compact ? 'compact' : 'sm'} />
      </div>
    </Container>
  );
}

// ============================================================
// MOBILE DRAWER
// ============================================================

function MobileNav({ onCta }) {
  const [open, setOpen] = useState(false);
  const [exp, setExp] = useState(null);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const mobileDrawer = open ? (
    <div style={{
      position: 'fixed',
      inset: 0,
      zIndex: 2147483000,
      minHeight: '100dvh',
      background: 'rgba(7, 12, 14, 0.72)',
      animation: 'fadeIn 200ms var(--ease-out)',
    }} onClick={() => setOpen(false)}>
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: 'min(480px, 100vw)',
        height: '100dvh',
        background: 'oklch(98.5% 0.006 196)',
        color: 'var(--fg1)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideIn 280ms var(--ease-out)',
        boxShadow: '-24px 0 70px rgba(15,22,24,0.28)',
      }} onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div style={{
          padding: '18px clamp(20px, 5vw, 26px)',
          borderBottom: '1px solid rgba(15,22,24,0.10)',
          background: 'oklch(99% 0.005 196)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <a href={linkTo('/')} onClick={() => setOpen(false)}><img src={assetTo('/ds/assets/Frsko-500px.webp')} alt="FRSKO" style={{ height: 38 }} /></a>
          <button onClick={() => setOpen(false)} aria-label="Cerrar menú" style={{
            width: 44, height: 44, borderRadius: 999,
            border: '1px solid rgba(15,22,24,0.14)', background: 'oklch(100% 0.004 196)',
            color: 'var(--fg1)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <Icon name="arrow-right" size={15} style={{ transform: 'rotate(45deg)' }} />
          </button>
        </div>

        {/* Scrollable body */}
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '10px clamp(12px, 3vw, 16px) 24px', background: 'oklch(98.5% 0.006 196)' }}>
          {MENU.map((m, i) => {
            const hasPanel = m.kind === 'mega' || m.kind === 'dropdown';
            const isOpen = exp === i;
            return (
              <div key={m.label} style={{ borderBottom: '1px solid rgba(15,22,24,0.09)' }}>
                <button
                  onClick={() => {
                    if (hasPanel) {
                      setExp(isOpen ? null : i);
                    } else {
                      window.location.href = m.href;
                    }
                  }}
                  style={{
                    width: '100%', background: 'transparent', border: 0, cursor: 'pointer',
                    padding: '17px 12px',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    textAlign: 'left',
                    fontFamily: 'var(--font-body)',
                    fontSize: 17.5, fontWeight: 760, color: 'var(--fg1)',
                  }}>
                  {m.label}
                  {hasPanel && (
                    <Icon name="arrow-right" size={16} style={{
                      color: 'var(--ink-500)',
                      transform: `rotate(${isOpen ? 90 : 0}deg)`,
                      transition: 'transform 220ms var(--ease-out)',
                    }} />
                  )}
                </button>
                {hasPanel && isOpen && (
                  <div style={{ padding: '0 8px 18px' }}>
                    <MobileAccordionBody item={m} onClose={() => setOpen(false)} />
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* Sticky footer CTA */}
        <div style={{
          padding: '16px clamp(18px, 5vw, 22px) calc(16px + env(safe-area-inset-bottom))',
          borderTop: '1px solid rgba(15,22,24,0.10)',
          background: 'oklch(97.5% 0.018 197)',
          display: 'grid', gap: 10,
          flexShrink: 0,
        }}>
          <HeaderCtaLink size="md" onClick={() => setOpen(false)} style={{ width: '100%' }}>
            Habla con un estratega
          </HeaderCtaLink>
          <Button variant="ghost" size="md" icon="sparkles" onClick={() => { setOpen(false); window.location.href = linkTo('/herramientas/diagnostico-ia'); }}
            style={{ width: '100%', justifyContent: 'center', background: 'oklch(100% 0.004 196)' }}>
            Diagnóstico gratis · 5 min
          </Button>
        </div>
      </aside>
    </div>
  ) : null;

  const renderedDrawer = mobileDrawer && typeof ReactDOM !== 'undefined' && ReactDOM.createPortal
    ? ReactDOM.createPortal(mobileDrawer, document.body)
    : mobileDrawer;

  return (
    <>
      <Container style={{ padding: '12px clamp(14px, 4vw, 22px)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
        <a href={linkTo('/')} style={{ display: 'inline-flex', minWidth: 0 }}><img src={assetTo('/ds/assets/Frsko-500px.webp')} alt="FRSKO" style={{ height: 34, width: 'auto' }} /></a>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
          <HeaderCtaLink size="compact">Agenda</HeaderCtaLink>
          <button onClick={() => setOpen(true)} aria-label="Abrir menú" style={{
            width: 42, height: 42, borderRadius: 999,
            border: '1px solid rgba(15,22,24,0.12)', background: 'rgba(255,255,255,0.88)',
            color: 'var(--fg1)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
            boxShadow: '0 10px 24px rgba(15,22,24,0.08)',
          }}>
            <Icon name="menu" size={20} />
          </button>
        </div>
      </Container>

      {renderedDrawer}
    </>
  );
}

function MobileAccordionBody({ item, onClose }) {
  if (item.kind === 'dropdown') {
    return (
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 2 }}>
        {item.items.map(it => <MegaItem key={it.label} it={it} onClose={onClose} />)}
      </ul>
    );
  }
  // mega
  return (
    <div style={{ display: 'grid', gap: 16 }}>
      {item.columns.map((col, i) => (
        <div key={i}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '8px 12px',
          }}>
            <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '0.14em',
              textTransform: 'uppercase', color: col.muted ? 'var(--ink-500)' : 'var(--brand)',
            }}>{col.title}</div>
            <span style={{ fontSize: 10, color: 'var(--fg3)' }}>{col.meta}</span>
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'grid', gap: 2 }}>
            {col.items.map(it => <MegaItem key={it.label} it={it} muted={col.muted} onClose={onClose} />)}
          </ul>
        </div>
      ))}
      {item.promo && (
        <div style={{
          background: 'var(--grad-deep)', color: '#fff',
          borderRadius: 18, padding: 20, position: 'relative', overflow: 'hidden',
        }}>
          <Droplets style={{ right: -20, top: -20 }} color="rgba(0,218,227,0.3)" opacity={0.7} size={120} />
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--cyan-300)', marginBottom: 8 }}>{item.promo.eyebrow}</div>
          <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 17, lineHeight: 1.2, marginBottom: 6 }}>{item.promo.title}</div>
          <div style={{ fontSize: 13, lineHeight: 1.5, color: 'rgba(255,255,255,0.75)' }}>{item.promo.body}</div>
          <a href={item.promo.href || '#'} onClick={onClose} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 14, color: 'var(--cta)', fontSize: 13, fontWeight: 700 }}>
            {item.promo.cta}
            <Icon name="arrow-right" size={14} />
          </a>
        </div>
      )}
    </div>
  );
}

// ============================================================
// MAIN HEADER
// ============================================================

function Header({ onCta }) {
  const [scrolled, setScrolled] = useState(false);
  const [openIdx, setOpenIdx] = useState(null);
  const [isMobile, setIsMobile] = useState(false);
  const [compactDesktop, setCompactDesktop] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    const onResize = () => {
      setIsMobile(window.innerWidth < 1180);
      setCompactDesktop(window.innerWidth < 1320);
    };
    onScroll(); onResize();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: openIdx !== null ? 'rgba(255,255,255,0.96)' : (scrolled ? 'rgba(255,255,255,0.88)' : 'rgba(255,255,255,0.6)'),
      backdropFilter: 'blur(14px) saturate(140%)',
      WebkitBackdropFilter: 'blur(14px) saturate(140%)',
      borderBottom: (scrolled || openIdx !== null) ? '1px solid var(--border)' : '1px solid transparent',
      transition: 'background var(--dur-base) var(--ease-out), border-color var(--dur-base) var(--ease-out)',
    }}>
      {isMobile
        ? <MobileNav onCta={onCta} />
        : <DesktopNav scrolled={scrolled} compact={compactDesktop} openIdx={openIdx} setOpenIdx={setOpenIdx} onCta={onCta} />}
    </header>
  );
}

Object.assign(window, { Header });
