// Final CTA + Footer

const CTA_FUNC_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 CtaFuncDropdown = () => {
  const [open, setOpen] = React.useState(false);
  const [pos, setPos] = React.useState({ left: 0, top: 0 });
  const wrapRef = React.useRef(null);
  const triggerRef = React.useRef(null);
  const panelRef = React.useRef(null);
  const closeTimerRef = React.useRef(null);
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  const localize = (href) => `/${country}${href.endsWith('/') ? href : href + '/'}`;

  const updatePosition = React.useCallback(() => {
    const t = triggerRef.current;
    if (!t) return;
    const r = t.getBoundingClientRect();
    setPos({ left: r.left + r.width / 2, top: r.bottom + 10 });
  }, []);

  React.useLayoutEffect(() => {
    if (!open) return;
    updatePosition();
    const onScroll = () => updatePosition();
    const onResize = () => updatePosition();
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', onResize);
    };
  }, [open, updatePosition]);

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      const t = triggerRef.current;
      const p = panelRef.current;
      if (t && t.contains(e.target)) return;
      if (p && p.contains(e.target)) return;
      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 cancelClose = () => {
    if (closeTimerRef.current) {
      clearTimeout(closeTimerRef.current);
      closeTimerRef.current = null;
    }
  };
  const scheduleClose = () => {
    cancelClose();
    closeTimerRef.current = setTimeout(() => setOpen(false), 120);
  };

  return (
    <div
      ref={wrapRef}
      onMouseEnter={() => { cancelClose(); setOpen(true); }}
      onMouseLeave={scheduleClose}
      style={{ position: 'relative', display: 'inline-block' }}
    >
      <button
        ref={triggerRef}
        type="button"
        className="btn btn-lg"
        onClick={(e) => { e.preventDefault(); setOpen(o => !o); }}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls="cta-funcionalidades-menu"
        style={{
          background: 'rgba(255,255,255,0.08)',
          color: '#fff',
          border: '1px solid rgba(255,255,255,0.15)',
          display: 'inline-flex',
          alignItems: 'center',
          gap: 8,
        }}
      >
        Ver funcionalidades
        <svg width="13" height="13" 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>
      </button>

      {ReactDOM.createPortal(
        <div
          ref={panelRef}
          onMouseEnter={cancelClose}
          onMouseLeave={scheduleClose}
          style={{
            position: 'fixed',
            left: pos.left,
            top: pos.top,
            transform: 'translateX(-50%)',
            minWidth: 280,
            opacity: open ? 1 : 0,
            visibility: open ? 'visible' : 'hidden',
            pointerEvents: open ? 'auto' : 'none',
            transition: 'opacity 0.18s ease, visibility 0.18s',
            zIndex: 1000,
            textAlign: 'left',
          }}
        >
          <div
            id="cta-funcionalidades-menu"
            role="menu"
            aria-label="Funcionalidades"
            style={{
              background: 'rgba(20, 20, 22, 0.96)',
              backdropFilter: 'blur(12px)',
              WebkitBackdropFilter: 'blur(12px)',
              border: '1px solid rgba(255,255,255,0.12)',
              borderRadius: 12,
              boxShadow: '0 24px 48px -12px rgba(0,0,0,0.5)',
              padding: 8,
              transform: open ? 'translateY(0)' : 'translateY(-4px)',
              transition: 'transform 0.18s ease',
            }}
          >
            {CTA_FUNC_GROUPS.map((group, gi) => (
              <div key={group.label} role="group" aria-label={group.label}>
                {gi > 0 && (
                  <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', margin: '8px 12px' }} />
                )}
                <div className="mono" style={{
                  padding: '6px 12px', fontSize: 10.5,
                  textTransform: 'uppercase', letterSpacing: '0.14em',
                  color: 'rgba(255,255,255,0.4)',
                  pointerEvents: 'none',
                }}>
                  {group.label}
                </div>
                {group.items.map((it) => {
                  const setActive = (a, active) => {
                    a.style.background = active ? 'rgba(255,255,255,0.06)' : 'transparent';
                    const s = a.querySelector('span');
                    if (s) s.style.color = active ? 'transparent' : 'rgba(255,255,255,0.85)';
                  };
                  return (
                    <a
                      key={it.href}
                      href={localize(it.href)}
                      role="menuitem"
                      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 0.15s ease',
                      }}
                    >
                      <span style={{
                        color: 'rgba(255,255,255,0.85)',
                        backgroundImage: 'linear-gradient(135deg, #54B5E3 0%, #C69CFF 100%)',
                        WebkitBackgroundClip: 'text',
                        backgroundClip: 'text',
                        transition: 'color 0.15s ease',
                      }}>
                        {it.label}
                      </span>
                    </a>
                  );
                })}
              </div>
            ))}
          </div>
        </div>,
        document.body
      )}
    </div>
  );
};

const FinalCTA = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  const preciosHref = `/${country}/precios/`;

  return (
  <section style={{ position: 'relative' }}>
    <div className="container">
      <div style={{
        position: 'relative', borderRadius: 32, padding: '80px 40px',
        background: 'linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%)',
        color: '#fff', textAlign: 'center',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0, borderRadius: 32,
          overflow: 'hidden', pointerEvents: 'none',
        }}>
          <div style={{ position: 'absolute', top: -100, left: '20%', width: 400, height: 400, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.4), transparent 70%)', filter: 'blur(60px)' }} />
          <div style={{ position: 'absolute', bottom: -100, right: '20%', width: 400, height: 400, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.4), transparent 70%)', filter: 'blur(60px)' }} />
          <div style={{
            position: 'absolute', inset: 0, opacity: 0.4,
            backgroundImage: 'linear-gradient(rgba(255,255,255,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 1px)',
            backgroundSize: '48px 48px',
          }} />
        </div>

        <div style={{ position: 'relative', maxWidth: 720, margin: '0 auto' }} className="reveal">
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '6px 14px', borderRadius: 999, marginBottom: 24,
            background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)',
            fontSize: 12, fontFamily: 'Geist Mono', color: 'rgba(255,255,255,0.7)',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#54B5E3' }} className="pulse" />
            Plan Pionero · 47 lugares restantes · acceso limitado
          </div>

          <h2 className="h2" style={{ marginBottom: 20, textWrap: 'balance' }}>
            Únete al <span className="grad-text">Plan Pionero.</span>
          </h2>
          <p style={{ fontSize: 18, color: 'rgba(255,255,255,0.7)', marginBottom: 36, maxWidth: 560, margin: '0 auto 36px', textWrap: 'pretty' }}>
            Un plan exclusivo de lanzamiento, reservado a las primeras agencias que confían en CloserBroker. Una vez cerrado el cupo, deja de existir — para siempre.
          </p>

          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: 28, flexWrap: 'wrap', alignItems: 'center' }}>
            <a href={preciosHref} className="btn btn-grad btn-lg" style={{ textDecoration: 'none' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>Asegurar mi lugar Pionero<Icon name="arrow" size={15} /></span>
            </a>
            <CtaFuncDropdown />
          </div>

          <div style={{ display: 'flex', gap: 24, justifyContent: 'center', flexWrap: 'wrap', fontSize: 13, color: 'rgba(255,255,255,0.6)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={14} color="#54B5E3" /> Siempre el precio más bajo, de por vida</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={14} color="#54B5E3" /> Soporte prioritario</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="check" size={14} color="#54B5E3" /> Sin contratos largos</div>
          </div>
        </div>
      </div>
    </div>
  </section>
  );
};

const Footer = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  const localizeFunc = (slug) => `/${country}/funcionalidades/${slug}/`;

  const cols = [
    { t: 'Atraer y captar', l: [
        { label: 'Sitio web y marketing', href: localizeFunc('marketing') },
        { label: 'Portal Ogarom', href: localizeFunc('ogarom') },
        { label: 'Catálogo de propiedades', href: localizeFunc('propiedades') },
      ] },
    { t: 'Gestionar y convertir', l: [
        { label: 'CRM y gestión de leads', href: localizeFunc('crm') },
        { label: 'Automatizaciones e IA', href: localizeFunc('automatizaciones') },
        { label: 'Productividad y organización', href: localizeFunc('productividad') },
        { label: 'Equipo y colaboración', href: localizeFunc('equipo') },
        { label: 'Bolsa Inmobiliaria', href: localizeFunc('bolsa') },
      ] },
    { t: 'Producto', l: [
        { label: 'Precios', href: '/precios' },
        { label: 'Comparar CloserBroker', href: '/comparar' },
        { label: 'Migración', href: `/${country}/#migracion` },
      ] },
    { t: 'Recursos', l: [
        { label: 'Blog', href: '/blog/' },
        { label: 'Guías', href: '/guias' },
      ] },
  ];

  const legalLinks = [
    { label: 'Aviso Legal', href: '/legal/aviso-legal/' },
    { label: 'Política de Privacidad', href: '/legal/privacidad/' },
  ];

  const socials = [
    {
      name: 'Instagram',
      href: '#',
      svg: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="18" height="18" rx="5" />
          <circle cx="12" cy="12" r="4" />
          <circle cx="17.5" cy="6.5" r="0.8" fill="currentColor" stroke="none" />
        </svg>
      ),
    },
    {
      name: 'LinkedIn',
      href: '#',
      svg: (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
          <path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.36V9h3.41v1.56h.05c.47-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.45v6.29zM5.34 7.43a2.06 2.06 0 110-4.13 2.06 2.06 0 010 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z" />
        </svg>
      ),
    },
  ];

  return (
    <footer className="cb-footer">
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        pointerEvents: 'none', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: '15%', left: '-4%',
          width: 520, height: 520, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(84,181,227,0.22) 0%, transparent 70%)',
          filter: 'blur(60px)',
        }} />
        <div style={{
          position: 'absolute', bottom: '-15%', right: '-2%',
          width: 480, height: 480, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(198,156,255,0.22) 0%, transparent 70%)',
          filter: 'blur(60px)',
        }} />
        <div style={{
          position: 'absolute', top: '40%', left: '45%',
          width: 360, height: 360, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(198,156,255,0.10) 0%, transparent 70%)',
          filter: 'blur(60px)',
        }} />
      </div>
      <div className="container">
        <div className="cb-footer-grid">
          <div>
            <div style={{ marginBottom: 18 }}>
              <img src="/assets/closerbroker-logo.png" alt="CloserBroker" style={{ height: 32, width: 'auto', display: 'block' }} />
            </div>
            <p style={{ fontSize: 14, color: 'var(--fg-muted)', maxWidth: 280, lineHeight: 1.6, marginBottom: 20 }}>
              El CRM moderno hecho por y para agencias inmobiliarias.
            </p>
            <div style={{ display: 'flex', gap: 10 }}>
              {socials.map((s) => (
                <a
                  key={s.name}
                  href={s.href}
                  aria-label={s.name}
                  className="cb-social"
                >
                  {s.svg}
                </a>
              ))}
            </div>
          </div>
          {cols.map((c, i) => (
            <div key={i}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-faint)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 16 }}>{c.t}</div>
              <ul style={{ listStyle: 'none' }}>
                {c.l.map((it, j) => (
                  <li key={j} style={{ marginBottom: 10 }}>
                    <a href={it.href} className="cb-footer-link">{it.label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="cb-footer-bottom">
          <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
            © 2026 CloserBroker · Hecho con ❤ para agencias inmobiliarias de LATAM
          </div>
          <nav className="cb-footer-legal" aria-label="Legal">
            {legalLinks.map((it, i) => (
              <a key={i} href={it.href}>{it.label}</a>
            ))}
          </nav>
        </div>
      </div>

      <style>{`
        .cb-footer {
          position: relative;
          padding: 64px 0 32px;
          background: #fff;
        }
        .cb-footer::before {
          content: '';
          position: absolute;
          top: 0; left: 0; right: 0;
          height: 1.5px;
          background: linear-gradient(90deg, #54B5E3, #C69CFF);
          opacity: 0.85;
        }
        .cb-footer-grid,
        .cb-footer-bottom,
        .cb-footer .container {
          position: relative;
          z-index: 1;
        }
        .cb-footer-grid {
          display: grid;
          grid-template-columns: 1.2fr 1fr 1.2fr 1fr 0.8fr;
          gap: 40px;
          margin-bottom: 56px;
        }
        .cb-footer-bottom {
          padding-top: 24px;
          border-top: 1px solid var(--border-soft);
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex-wrap: wrap;
          gap: 12px 24px;
        }
        .cb-footer-legal {
          display: flex;
          gap: 18px;
          flex-wrap: wrap;
        }
        .cb-footer-legal a {
          font-size: 11px;
          color: var(--fg-faint);
          letter-spacing: 0.01em;
          transition: color 0.18s ease;
        }
        .cb-footer-legal a:hover {
          color: var(--fg-soft);
        }

        .cb-footer-link {
          font-size: 14px;
          color: var(--fg-soft);
          background-image: linear-gradient(90deg, #54B5E3, #C69CFF);
          -webkit-background-clip: text;
          background-clip: text;
          transition: color 0.25s ease;
          position: relative;
        }
        .cb-footer-link:hover {
          color: transparent;
          -webkit-text-fill-color: transparent;
        }

        .cb-social {
          width: 36px;
          height: 36px;
          border-radius: 8px;
          border: 1px solid var(--border);
          background: #fff;
          color: var(--fg-soft);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          transition: color 0.25s ease, border-color 0.25s ease, background 0.25s ease, transform 0.2s ease;
        }
        .cb-social:hover {
          color: transparent;
          background: linear-gradient(135deg, rgba(84, 181, 227, 0.08), rgba(198, 156, 255, 0.08));
          border-color: rgba(198, 156, 255, 0.4);
          transform: translateY(-1px);
        }
        .cb-social:hover svg {
          stroke: url(#cb-social-grad);
        }
        /* For LinkedIn (filled svg) */
        .cb-social svg {
          transition: filter 0.25s ease;
        }
        .cb-social:hover svg path {
          fill: url(#cb-social-grad);
        }

        @media (max-width: 960px) {
          .cb-footer-grid {
            grid-template-columns: 1fr 1fr;
            gap: 40px 32px;
          }
        }
        @media (max-width: 560px) {
          .cb-footer-grid {
            grid-template-columns: 1fr;
            gap: 36px;
          }
        }
      `}</style>

      {/* SVG gradient defs for social hover (LinkedIn fill + Instagram stroke) */}
      <svg width="0" height="0" style={{ position: 'absolute' }} aria-hidden="true">
        <defs>
          <linearGradient id="cb-social-grad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#54B5E3" />
            <stop offset="100%" stopColor="#C69CFF" />
          </linearGradient>
        </defs>
      </svg>
    </footer>
  );
};

// WhatsApp floating button
const WhatsAppButton = () => (
  <button style={{
    position: 'fixed', bottom: 24, right: 24, zIndex: 30,
    width: 56, height: 56, borderRadius: '50%',
    background: '#25D366', color: '#fff',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    boxShadow: '0 8px 24px rgba(37, 211, 102, 0.4)',
    border: 'none', cursor: 'pointer',
    transition: 'transform 0.2s',
  }}
    onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.1)'}
    onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
  >
    <Icon name="whatsapp" size={26} />
  </button>
);

window.FinalCTA = FinalCTA;
window.Footer = Footer;
window.WhatsAppButton = WhatsAppButton;
