// Hero section with 4 headline variants

const HEADLINES = {
  A: {
    title: <>El CRM inmobiliario que <span className="serif" style={{fontStyle:'italic'}}>siempre quisimos</span> tener — así que lo construimos.</>,
    sub: 'CloserBroker reúne tu CRM, tu sitio web, tu bolsa y tu WhatsApp en un solo lugar. Hecho con agencias de México y Colombia, pensado para vender más sin perder horas en la herramienta.',
  },
  B: {
    title: <>El CRM todo-en-uno que la inmobiliaria de <span className="grad-text">LATAM</span> merece.</>,
    sub: 'CRM, sitio web, bolsa inmobiliaria, IA, WhatsApp y portales — todo en una sola plataforma diseñada para agencias de México y Colombia que quieren cerrar más rápido.',
  },
  C: {
    title: <>Deja de pegar <span className="serif" style={{fontStyle:'italic'}}>5 herramientas</span> con cinta para gestionar tu agencia.</>,
    sub: 'CRM, sitio web que convierte, bolsa inmobiliaria, IA y WhatsApp — en un solo lugar. Sin integraciones rotas, sin Excel, sin perder leads entre apps.',
  },
  D: {
    title: <>Vende más propiedades, en menos tiempo, con <span className="grad-text">menos herramientas</span>.</>,
    sub: 'CloserBroker es la plataforma todo-en-uno para agencias inmobiliarias de México y Colombia: CRM, sitio web, bolsa, IA y automatizaciones. Una sola suscripción, todo conectado.',
  },
};

const FUNCIONALIDADES_GROUPS = [
  {
    label: 'Atraer y captar',
    items: [
      { label: 'Sitio web y marketing', href: '/funcionalidades/marketing' },
      { label: 'Portal Ogarom', href: '/funcionalidades/ogarom' },
      { label: 'Catálogo de propiedades', href: '/funcionalidades/propiedades' },
    ],
  },
  {
    label: 'Gestionar y convertir',
    items: [
      { label: 'CRM y gestión de leads', href: '/funcionalidades/crm' },
      { label: 'Automatizaciones e IA', href: '/funcionalidades/automatizaciones' },
      { label: 'Productividad y organización', href: '/funcionalidades/productividad' },
      { label: 'Equipo y colaboración', href: '/funcionalidades/equipo' },
      { label: 'Bolsa Inmobiliaria', href: '/funcionalidades/bolsa' },
    ],
  },
];

const FUNCIONALIDADES_LINKS = FUNCIONALIDADES_GROUPS.flatMap(g => g.items);

const ChevronDown = ({ size = 12, open }) => (
  <svg
    width={size} height={size} viewBox="0 0 24 24"
    fill="none" stroke="currentColor"
    strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"
    style={{ transform: open ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 0.2s ease' }}
    aria-hidden="true"
  >
    <polyline points="6 9 12 15 18 9" />
  </svg>
);

const FuncionalidadesDropdown = () => {
  const [open, setOpen] = React.useState(false);
  const [hoverCapable, setHoverCapable] = React.useState(true);
  const wrapRef = React.useRef(null);
  const triggerRef = React.useRef(null);
  const itemRefs = React.useRef([]);
  const dropCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const dropCountry = (dropCtx && dropCtx.country) || 'co';
  const localizeFuncHref = (href) => `/${dropCountry}${href.endsWith('/') ? href : href + '/'}`;

  React.useEffect(() => {
    const mq = window.matchMedia('(hover: hover)');
    const update = () => setHoverCapable(mq.matches);
    update();
    mq.addEventListener?.('change', update);
    return () => mq.removeEventListener?.('change', update);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => {
      if (e.key === 'Escape') {
        setOpen(false);
        triggerRef.current?.focus();
      }
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const focusItem = (i) => {
    const len = FUNCIONALIDADES_LINKS.length;
    const idx = ((i % len) + len) % len;
    itemRefs.current[idx]?.focus();
  };

  const onTriggerClick = (e) => {
    e.preventDefault();
    if (!hoverCapable) setOpen(o => !o);
  };

  const onTriggerKeyDown = (e) => {
    if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') {
      e.preventDefault();
      setOpen(true);
      setTimeout(() => focusItem(0), 0);
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setOpen(true);
      setTimeout(() => focusItem(-1), 0);
    }
  };

  const onItemKeyDown = (e, i) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); focusItem(i + 1); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); focusItem(i - 1); }
    else if (e.key === 'Home') { e.preventDefault(); focusItem(0); }
    else if (e.key === 'End') { e.preventDefault(); focusItem(-1); }
    else if (e.key === 'Tab') { setOpen(false); }
  };

  return (
    <div
      ref={wrapRef}
      onMouseEnter={() => hoverCapable && setOpen(true)}
      onMouseLeave={() => hoverCapable && setOpen(false)}
      style={{ position: 'relative' }}
    >
      <button
        ref={triggerRef}
        type="button"
        className="cb-nav-link-host"
        onClick={onTriggerClick}
        onKeyDown={onTriggerKeyDown}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls="funcionalidades-menu"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          color: 'var(--fg-soft)', fontSize: 14, padding: 0,
        }}
      >
        <span className="cb-nav-link-text">Funcionalidades</span>
        <ChevronDown open={open} />
      </button>

      <div
        style={{
          position: 'absolute', top: '100%', left: '50%',
          transform: 'translateX(-50%)',
          paddingTop: 10,
          minWidth: 280,
          opacity: open ? 1 : 0,
          visibility: open ? 'visible' : 'hidden',
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity 0.18s ease, visibility 0.18s',
          zIndex: 100,
        }}
      >
        <div
          id="funcionalidades-menu"
          role="menu"
          aria-label="Funcionalidades"
          style={{
            background: '#fff',
            border: '1px solid var(--border)',
            borderRadius: 12,
            boxShadow: 'var(--shadow)',
            padding: 8,
            transform: open ? 'translateY(0)' : 'translateY(-4px)',
            transition: 'transform 0.18s ease',
          }}
        >
          {FUNCIONALIDADES_GROUPS.map((group, gi) => {
            const baseIdx = FUNCIONALIDADES_GROUPS
              .slice(0, gi)
              .reduce((sum, g) => sum + g.items.length, 0);
            const setActive = (a, active) => {
              a.style.backgroundColor = active ? 'var(--bg-soft)' : 'transparent';
              const s = a.querySelector('span');
              if (s) s.style.color = active ? 'transparent' : 'var(--fg-soft)';
            };
            return (
              <div key={group.label} role="group" aria-label={group.label}>
                {gi > 0 && (
                  <div style={{
                    height: 1,
                    background: 'var(--border-soft)',
                    margin: '8px 12px',
                  }} />
                )}
                <div className="mono" style={{
                  padding: '6px 12px 6px',
                  fontSize: 10.5,
                  textTransform: 'uppercase',
                  letterSpacing: '0.14em',
                  color: 'var(--fg-faint)',
                  pointerEvents: 'none',
                }}>
                  {group.label}
                </div>
                {group.items.map((it, j) => {
                  const i = baseIdx + j;
                  return (
                    <a
                      key={it.href}
                      ref={el => itemRefs.current[i] = el}
                      href={localizeFuncHref(it.href)}
                      role="menuitem"
                      tabIndex={open ? 0 : -1}
                      onKeyDown={(e) => onItemKeyDown(e, i)}
                      onClick={() => setOpen(false)}
                      onMouseEnter={(e) => setActive(e.currentTarget, true)}
                      onMouseLeave={(e) => setActive(e.currentTarget, false)}
                      onFocus={(e) => setActive(e.currentTarget, true)}
                      onBlur={(e) => setActive(e.currentTarget, false)}
                      style={{
                        display: 'block',
                        padding: '10px 12px',
                        fontSize: 14,
                        borderRadius: 8,
                        whiteSpace: 'nowrap',
                        outline: 'none',
                        transition: 'background-color 0.15s ease',
                      }}
                    >
                      <span style={{
                        color: 'var(--fg-soft)',
                        backgroundImage: 'var(--grad)',
                        WebkitBackgroundClip: 'text',
                        backgroundClip: 'text',
                        transition: 'color 0.15s ease',
                      }}>
                        {it.label}
                      </span>
                    </a>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

const CountrySwitcher = () => {
  // Fallback robuste : si CountryProvider n'est pas chargé (anciennes pages non migrées),
  // on lit/écrit localStorage directement et on redirige au clic.
  const fallback = (() => {
    let c = 'co';
    try {
      const stored = localStorage.getItem('cb_country');
      if (stored === 'mx' || stored === 'co') c = stored;
    } catch (e) {}
    return {
      country: c,
      flag: c === 'mx' ? '🇲🇽' : '🇨🇴',
      setCountry: (next) => {
        if (next !== 'mx' && next !== 'co') return;
        try { localStorage.setItem('cb_country', next); } catch (e) {}
        window.location.href = '/' + next + '/';
      },
    };
  });
  const { country, setCountry, flag } = (typeof useCountry === 'function')
    ? useCountry()
    : fallback();
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const options = [
    { code: 'mx', flag: '🇲🇽', label: 'México' },
    { code: 'co', flag: '🇨🇴', label: 'Colombia' },
  ];

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`País: ${country === 'mx' ? 'México' : 'Colombia'}`}
        className="cb-country-trigger"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '7px 10px',
          fontSize: 14,
          borderRadius: 8,
          border: '1px solid var(--border)',
          background: '#fff',
          cursor: 'pointer',
          transition: 'border-color 0.18s ease, background 0.18s ease',
          lineHeight: 1,
        }}
      >
        <span style={{ fontSize: 16, lineHeight: 1 }}>{flag}</span>
        <ChevronDown size={11} open={open} />
      </button>
      <div style={{
        position: 'absolute', top: '100%', right: 0,
        paddingTop: 8,
        minWidth: 150,
        opacity: open ? 1 : 0,
        visibility: open ? 'visible' : 'hidden',
        pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 0.18s ease, visibility 0.18s',
        zIndex: 100,
      }}>
        <div role="listbox" aria-label="País" style={{
          background: '#fff',
          border: '1px solid var(--border)',
          borderRadius: 10,
          boxShadow: 'var(--shadow)',
          padding: 6,
          transform: open ? 'translateY(0)' : 'translateY(-4px)',
          transition: 'transform 0.18s ease',
        }}>
          {options.map(opt => {
            const active = opt.code === country;
            return (
              <button
                key={opt.code}
                type="button"
                role="option"
                aria-selected={active}
                onClick={() => { setOpen(false); setCountry(opt.code); }}
                style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 12px',
                  fontSize: 14,
                  borderRadius: 6,
                  background: active ? 'var(--bg-soft)' : 'transparent',
                  color: 'var(--fg)',
                  cursor: 'pointer',
                  textAlign: 'left',
                  transition: 'background 0.15s ease',
                  border: 'none',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-soft)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{ fontSize: 16 }}>{opt.flag}</span>
                <span>{opt.label}</span>
                {active && <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--fg-muted)' }}>✓</span>}
              </button>
            );
          })}
        </div>
      </div>
      <style>{`
        .cb-country-trigger:hover { border-color: var(--fg) !important; }
      `}</style>
    </div>
  );
};

const Nav = () => {
  const [scrolled, setScrolled] = React.useState(false);
  const navCtx = (typeof useCountry === 'function') ? useCountry() : { country: 'co' };
  const preciosHref = `/${navCtx.country}/precios/`;
  const homeHref = `/${navCtx.country}/`;
  const blogHref = `/${navCtx.country}/blog/`;
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      padding: scrolled ? '12px 0' : '20px 0',
      background: scrolled ? 'rgba(255,255,255,0.85)' : 'transparent',
      backdropFilter: scrolled ? 'blur(12px)' : 'none',
      borderBottom: scrolled ? '1px solid var(--border-soft)' : '1px solid transparent',
      transition: 'all 0.3s ease',
    }}>
      <div className="container" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 32 }}>
        <a href={homeHref} style={{ display: 'flex', alignItems: 'center', justifySelf: 'start' }}>
          <img src="/assets/closerbroker-logo.png" alt="CloserBroker" style={{ height: 28, width: 'auto', display: 'block' }} />
        </a>
        <div style={{ display: 'flex', alignItems: 'center', gap: 36, fontSize: 14, justifySelf: 'center' }}>
          <FuncionalidadesDropdown />
          <a href={preciosHref} className="cb-nav-link-host" style={{ color: 'var(--fg-soft)' }}>
            <span className="cb-nav-link-text">Precios</span>
          </a>
          <a href={blogHref} className="cb-nav-link-host" style={{ color: 'var(--fg-soft)' }}>
            <span className="cb-nav-link-text">Blog</span>
          </a>
        </div>
        <style>{`
          .cb-nav-link-text {
            background-image: var(--grad);
            -webkit-background-clip: text;
            background-clip: text;
            transition: color 0.18s ease;
          }
          .cb-nav-link-host:hover .cb-nav-link-text { color: transparent; }
          .cb-nav-link-host:focus-visible .cb-nav-link-text { color: transparent; }
        `}</style>
        <div style={{ justifySelf: 'end', display: 'flex', alignItems: 'center', gap: 12 }}>
          <CountrySwitcher />
          <a href="https://app.closerbroker.com/login" className="btn btn-primary">Entrar</a>
        </div>
      </div>
    </nav>
  );
};

const Hero = ({ variant }) => {
  const h = HEADLINES[variant] || HEADLINES.A;
  return (
    <section style={{ paddingTop: 140, paddingBottom: 80, position: 'relative', overflow: 'hidden' }}>
      {/* Aurora bg */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -300, left: '20%', width: 600, height: 600, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.25) 0%, transparent 70%)', filter: 'blur(40px)' }} />
        <div style={{ position: 'absolute', top: -200, right: '15%', width: 500, height: 500, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.25) 0%, transparent 70%)', filter: 'blur(40px)' }} />
      </div>

      <div className="container" style={{ position: 'relative' }}>
        <div style={{ textAlign: 'center', maxWidth: 920, margin: '0 auto' }}>
          <div className="reveal in" style={{ marginBottom: 32 }}>
            <div className="eyebrow">
              <span className="eyebrow-dot pulse" />
              <span>En lanzamiento · Únete a las 100 primeras agencias</span>
            </div>
          </div>

          <h1 className="h1 reveal in reveal-delay-1" style={{ marginBottom: 24, textWrap: 'balance' }}>
            {h.title}
          </h1>

          <p className="reveal in reveal-delay-2" style={{ fontSize: 19, color: 'var(--fg-soft)', maxWidth: 720, margin: '0 auto 36px', lineHeight: 1.5, textWrap: 'pretty' }}>
            {h.sub}
          </p>

          <div className="reveal in reveal-delay-3" style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: 24, flexWrap: 'wrap' }}>
            <a href="https://app.closerbroker.com/signup" className="btn btn-primary btn-lg">Comienza ahora<Icon name="arrow" size={15} /></a>
            <a href="#funcionalidades" className="btn btn-secondary btn-lg">Ver funcionalidades</a>
          </div>

          <div className="reveal in reveal-delay-4" style={{ display: 'flex', gap: 24, justifyContent: 'center', flexWrap: 'wrap', fontSize: 13, color: 'var(--fg-muted)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check" size={14} color="#16a34a" />
              <span>Migración en 1 click desde EasyBroker, Wasi y Tokko</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check" size={14} color="#16a34a" />
              <span>En vivo en menos de 5min</span>
            </div>
          </div>
        </div>

        {/* Dashboard mockup */}
        <div className="reveal" style={{ marginTop: 80, maxWidth: 1100, margin: '80px auto 0', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: -40, background: 'radial-gradient(ellipse at center, rgba(84,181,227,0.15), transparent 60%)', filter: 'blur(40px)' }} />
          <div style={{ position: 'relative' }}>
            <DashboardMockup />
          </div>
        </div>
      </div>
    </section>
  );
};

const SocialBar = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const eyebrow = (ctx && ctx.copy && ctx.copy.heroEyebrow)
    || 'Construido junto a agencias inmobiliarias de México 🇲🇽 y Colombia 🇨🇴';
  return (
  <section style={{ padding: '40px 0', borderTop: '1px solid var(--border-soft)', borderBottom: '1px solid var(--border-soft)' }}>
    <div className="container">
      <div style={{ textAlign: 'center', marginBottom: 24 }}>
        <div className="mono" style={{ fontSize: 12, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
          {eyebrow}
        </div>
      </div>
      <div style={{ overflow: 'hidden', maskImage: 'linear-gradient(90deg, transparent, black 10%, black 90%, transparent)' }}>
        <div className="marquee">
          {[...Array(2)].map((_, n) => (
            <React.Fragment key={n}>
              {[
                'INMOBILIARIA AURA',
                'CASA & VIDA',
                'BIENES RAÍCES MX',
                'PROPERTIES CO',
                'GRUPO INVERSIÓN',
                'HOGAR PREMIUM',
                'MERIDIANO',
                'ALCALÁ INMUEBLES',
              ].map((name, i) => (
                <div key={i} style={{
                  fontSize: 18, fontWeight: 500, color: 'var(--fg-faint)',
                  letterSpacing: '0.05em', whiteSpace: 'nowrap',
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--fg-faint)' }} />
                  {name}
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  </section>
  );
};

window.Hero = Hero;
window.Nav = Nav;
window.SocialBar = SocialBar;
