// Section 8: Migra en un click + Section 9: Features grid

const MigrationSection = () => {
  const [step, setStep] = React.useState(0);
  const migCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const migPreciosHref = `/${(migCtx && migCtx.country) || 'co'}/precios/`;
  React.useEffect(() => {
    const i = setInterval(() => setStep(s => (s + 1) % 4), 2500);
    return () => clearInterval(i);
  }, []);

  return (
    <section id="migracion" style={{ position: 'relative', overflow: 'hidden', scrollMarginTop: 80 }}>
      <div style={{ position: 'absolute', top: '20%', left: '10%', width: 400, height: 400, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.12), transparent 70%)', filter: 'blur(60px)', pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', bottom: '10%', right: '5%', width: 500, height: 500, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.12), transparent 70%)', filter: 'blur(60px)', pointerEvents: 'none' }} />

      <div className="container" style={{ position: 'relative' }}>
        <div style={{ textAlign: 'center', maxWidth: 700, margin: '0 auto 48px' }} className="reveal">
          <div className="eyebrow" style={{ marginBottom: 18, background: 'var(--grad)', color: '#fff', border: 'none' }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#fff' }} className="pulse" />
            ⭐ Migración sin dolor
          </div>
          <h2 style={{
            fontSize: 'clamp(28px, 3.4vw, 40px)',
            fontWeight: 500,
            letterSpacing: '-0.02em',
            lineHeight: 1.05,
            marginBottom: 16,
            textWrap: 'balance',
          }}>
            ¿Ya usas un CRM?{' '}
            <span className="grad-text">Importa todo en un click.</span>
          </h2>
          <p style={{ fontSize: 15.5, color: 'var(--fg-soft)', textWrap: 'pretty', lineHeight: 1.6, maxWidth: 680, margin: '0 auto' }}>
            Sabemos que cambiar de CRM da pereza. Por eso construimos integraciones <strong style={{ fontWeight: 600 }}>nativas</strong> con <strong style={{ fontWeight: 600 }}>los CRMs inmobiliarios que ya usas</strong> (EasyBroker, Wasi, Tokko Broker…). Conectas tu cuenta, importas todo, y empiezas a trabajar el mismo día.
          </p>
        </div>

        {/* Steps row */}
        <div className="reveal" style={{ background: '#fff', borderRadius: 18, padding: '28px 32px', border: '1px solid var(--border)', boxShadow: 'var(--shadow)', maxWidth: 1080, margin: '0 auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28, gap: 16, flexWrap: 'wrap' }}>
            <h3 style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em', margin: 0 }}>Cómo funciona, en vivo.</h3>
            <div className="mono" style={{
              fontSize: 11.5,
              color: 'var(--fg-muted)',
              textTransform: 'uppercase',
              letterSpacing: '0.08em',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              padding: '6px 12px',
              borderRadius: 999,
              background: 'linear-gradient(135deg, rgba(84,181,227,0.08), rgba(198,156,255,0.08))',
              border: '1px solid rgba(84,181,227,0.15)',
            }}>
              <span style={{ fontSize: 12 }}>⚡</span>
              <span>4 pasos</span>
              <span style={{ color: 'var(--border)' }}>·</span>
              <span className="grad-text" style={{ fontWeight: 600 }}>&lt; 5 minutos</span>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, position: 'relative' }}>
            {/* Connecting line */}
            <div style={{ position: 'absolute', top: 16, left: '12.5%', right: '12.5%', height: 1.5, background: 'var(--border)' }} />
            <div style={{
              position: 'absolute', top: 16, left: '12.5%', height: 1.5, background: 'var(--grad)',
              width: `${(step + 1) * 18.75}%`, transition: 'width 0.6s ease',
            }} />

            {[
              { n: '1', t: 'Conecta tu cuenta', d: 'Pegas tu API key. 30 segundos.' },
              { n: '2', t: 'Elige qué importar', d: 'Todas, solo activas, prospectos…' },
              { n: '3', t: 'CloserBroker hace el trabajo', d: 'Sincroniza todo automáticamente.' },
              { n: '4', t: 'Empieza a trabajar', d: 'Tu agencia lista. Sync continua.' },
            ].map((s, i) => (
              <div key={i} style={{ textAlign: 'center', position: 'relative', padding: '0 6px' }}>
                <div style={{
                  width: 32, height: 32, borderRadius: '50%',
                  background: i <= step ? 'var(--grad)' : '#fff',
                  border: i <= step ? 'none' : '1.5px solid var(--border)',
                  color: i <= step ? '#fff' : 'var(--fg-muted)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  margin: '0 auto 12px', fontWeight: 600, fontSize: 13,
                  transition: 'all 0.4s', position: 'relative', zIndex: 2,
                  transform: i === step ? 'scale(1.1)' : 'scale(1)',
                  boxShadow: i === step ? '0 6px 18px rgba(84,181,227,0.35)' : 'none',
                }}>
                  {i < step ? <Icon name="check" size={14} /> : s.n}
                </div>
                <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 3, letterSpacing: '-0.005em' }}>{s.t}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', lineHeight: 1.4 }}>{s.d}</div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 28, padding: '14px 20px', borderRadius: 10, background: 'linear-gradient(135deg, rgba(84,181,227,0.06), rgba(198,156,255,0.06))', border: '1px solid rgba(84,181,227,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' }}>
            <div style={{ fontSize: 14, color: 'var(--fg)', lineHeight: 1.5, maxWidth: 600 }}>
              <strong style={{ fontWeight: 600 }}>Migra tu CRM en menos de 5 minutos.</strong>{' '}
              <span style={{ color: 'var(--fg-soft)' }}>Sin perder un dato, sin pausar tu trabajo.</span>
            </div>
            <a href={migPreciosHref} className="btn btn-grad" style={{ fontSize: 13, padding: '8px 16px' }}><span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>Migra ahora<Icon name="arrow" size={13} /></span></a>
          </div>
        </div>
      </div>
    </section>
  );
};

const FeaturesGrid = () => {
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  const portalsList = (ctx && ctx.portals && ctx.portals.length)
    ? ctx.portals.slice(0, 3).join(', ')
    : 'Inmuebles24, Mercado Libre, Lamudi';
  const [openGroup, setOpenGroup] = React.useState(null);
  const objectiveGroups = {
    atraer: [
      { label: 'Sitio web y marketing', href: 'marketing' },
      { label: 'Portal Ogarom', href: 'ogarom' },
      { label: 'Catálogo de propiedades', href: 'propiedades' },
    ],
    gestionar: [
      { label: 'CRM y gestión de leads', href: 'crm' },
      { label: 'Automatizaciones e IA', href: 'automatizaciones' },
      { label: 'Productividad y organización', href: 'productividad' },
      { label: 'Equipo y colaboración', href: 'equipo' },
      { label: 'Bolsa Inmobiliaria', href: 'bolsa' },
    ],
  };
  const features = [
    // Línea 1 — Crecimiento y ventas
    { i: 'home', t: 'Bolsa Inmobiliaria', d: 'Una red de agencias colaborando: encuentra la propiedad ideal para cada cliente y multiplica tus oportunidades de venta.' },
    { i: 'globe', t: 'Portales conectados', d: `Publica automáticamente en ${portalsList} y todos los portales de LATAM.` },
    { i: 'zap', t: 'Automatizaciones', d: 'Email, WhatsApp y tareas — automatiza el seguimiento sin perder ningún prospecto.' },
    // Línea 2 — Comunicación y captación
    { i: 'inbox', t: 'Conversaciones unificadas', d: 'Email, WhatsApp, Messenger e Instagram en un solo inbox. Nunca más pierdas un lead.' },
    { i: 'book', t: 'Guías y lead magnets', d: 'Ofrece guías descargables y captura prospectos interesados, no curiosos.' },
    { i: 'link', t: 'Mis Links', d: 'Crea una página con todos tus links y propiedades destacadas. Compártela en tu bio de Instagram y convierte seguidores en prospectos.' },
    // Línea 3 — Gestión y equipo
    { i: 'calendar', t: 'Calendario y tareas', d: 'Agenda compartida del equipo. Citas, visitas y recordatorios sin choques ni olvidos.' },
    { i: 'users', t: 'Equipo y roles', d: 'Gestiona tu equipo: roles, permisos y métricas claras de cada agente.' },
    { i: 'edit', t: 'Blog integrado', d: 'Blog con IA integrada para atraer tráfico orgánico. Más visitas, más prospectos, sin esfuerzo.' },
  ];
  return (
    <section style={{ background: 'var(--bg-soft)' }}>
      <div className="container">
        <div style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto 40px' }} className="reveal">
          <div className="eyebrow" style={{ marginBottom: 14 }}><span className="eyebrow-dot" />Todo incluido</div>
          <h2 style={{
            fontSize: 'clamp(22px, 2.6vw, 30px)',
            fontWeight: 600,
            letterSpacing: '-0.02em',
            lineHeight: 1.15,
            textWrap: 'balance',
          }}>
            Y todo lo que tu agencia necesita,{' '}
            <span className="grad-text">en el mismo lugar.</span>
          </h2>
        </div>

        <div className="features-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: 'var(--border-soft)', borderRadius: 16, overflow: 'hidden', border: '1px solid var(--border-soft)' }}>
          {features.map((f, i) => (
            <div key={i} className="reveal card-hover" style={{
              padding: 28, background: '#fff',
              transitionDelay: `${i * 0.04}s`,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--grad-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
                <Icon name={f.i} size={16} color="#54B5E3" />
              </div>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>{f.t}</div>
              <div style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.55, textWrap: 'pretty' }}>{f.d}</div>
            </div>
          ))}
        </div>

        <div className="reveal" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, marginTop: 40 }}>
          <div style={{ fontSize: 14, color: 'var(--fg-muted)', textAlign: 'center' }}>
            Explora las funcionalidades para cada objetivo
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
            {[
              { key: 'atraer', label: 'Atraer y captar' },
              { key: 'gestionar', label: 'Gestionar y convertir' },
            ].map((g) => {
              const isOpen = openGroup === g.key;
              return (
                <button
                  key={g.key}
                  type="button"
                  onClick={() => setOpenGroup(isOpen ? null : g.key)}
                  aria-expanded={isOpen}
                  className="features-more-btn"
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 8,
                    padding: '11px 20px',
                    fontSize: 14,
                    fontWeight: 500,
                    color: 'var(--fg)',
                    background: isOpen ? 'var(--bg-muted)' : '#fff',
                    border: `1px solid ${isOpen ? 'var(--fg)' : 'var(--border)'}`,
                    borderRadius: 10,
                    cursor: 'pointer',
                    transition: 'all 0.2s ease',
                  }}
                >
                  <span className="objective-toggle-text">{g.label}</span>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 0.2s ease' }} aria-hidden="true">
                    <polyline points="6 9 12 15 18 9" />
                  </svg>
                </button>
              );
            })}
          </div>
          {openGroup && (
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'center', maxWidth: 760, marginTop: 4 }}>
              {objectiveGroups[openGroup].map((item) => (
                <a
                  key={item.href}
                  href={`/${country}/funcionalidades/${item.href}/`}
                  className="objective-item"
                  style={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 6,
                    padding: '8px 14px',
                    fontSize: 13,
                    fontWeight: 500,
                    background: '#fff',
                    border: '1px solid var(--border-soft)',
                    borderRadius: 999,
                    textDecoration: 'none',
                    transition: 'all 0.2s ease',
                  }}
                >
                  <span className="objective-item-text">{item.label}</span>
                  <Icon name="arrow" size={12} />
                </a>
              ))}
            </div>
          )}
        </div>
      </div>

      <style>{`
        .features-more-btn:hover {
          background: var(--bg-muted);
          box-shadow: 0 4px 12px -4px rgba(0,0,0,0.08);
          transform: translateY(-1px);
        }
        .objective-toggle-text {
          background-image: var(--grad);
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: var(--fg);
          color: var(--fg);
          transition: -webkit-text-fill-color 0.18s ease, color 0.18s ease;
        }
        .features-more-btn:hover .objective-toggle-text,
        .features-more-btn:focus-visible .objective-toggle-text {
          -webkit-text-fill-color: transparent;
          color: transparent;
        }
        .objective-item {
          color: var(--fg-soft);
        }
        .objective-item-text {
          background-image: var(--grad);
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: var(--fg-soft);
          color: var(--fg-soft);
          transition: -webkit-text-fill-color 0.18s ease, color 0.18s ease;
        }
        .objective-item:hover {
          border-color: var(--fg);
          transform: translateY(-1px);
        }
        .objective-item:hover .objective-item-text,
        .objective-item:focus-visible .objective-item-text {
          -webkit-text-fill-color: transparent;
          color: transparent;
        }
        @media (max-width: 960px) {
          .features-grid { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 640px) {
          .features-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
};

window.MigrationSection = MigrationSection;
window.FeaturesGrid = FeaturesGrid;
