const { useState, useEffect, useRef } = React;

/* ============ Brand mark SVG ============ */
function LogoMark({ className = '', color = 'currentColor' }) {
  // mMs: m letter, two arches, s letter
  return (
    <svg className={className} viewBox="0 0 120 70" fill="none" xmlns="http://www.w3.org/2000/svg">
      {/* m */}
      <text x="0" y="56" fontFamily="Geist, sans-serif" fontSize="28" fontWeight="300" fill={color}>m</text>
      {/* two arches */}
      <path d="M 28 56 Q 28 18 50 18 Q 72 18 72 56" stroke={color} strokeWidth="2.5" fill="none" strokeLinecap="round" />
      <path d="M 48 56 Q 48 22 70 22 Q 92 22 92 56" stroke={color} strokeWidth="2.5" fill="none" strokeLinecap="round" />
      {/* s */}
      <text x="100" y="56" fontFamily="Geist, sans-serif" fontSize="28" fontWeight="300" fill={color}>s</text>
    </svg>
  );
}

/* ============ Header ============ */
function Header({ lang, setLang, coverMode, scrolled }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const navItems = [
    { href: '#personas', es: 'Personas', en: 'Individuals' },
    { href: '#empresas', es: 'Empresas', en: 'Companies' },
    { href: '#agencias', es: 'Agencias', en: 'Partners' },
    { href: '#nosotros', es: 'Nosotros', en: 'About' },
    { href: '#internacional', es: 'Por qué internacional', en: 'Why international' },
  ];

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

  const close = () => setMenuOpen(false);

  return (
    <header className={`site-header ${scrolled ? 'scrolled' : ''} ${coverMode && !scrolled ? 'cover-mode' : ''} ${menuOpen ? 'menu-open' : ''}`}>
      <a href="#top" className="brand" onClick={close}>
        <LogoMark className="brand-mark" />
        <span className="brand-text">Margarita <span className="last">Sanmartín</span></span>
      </a>
      <nav className="nav">
        {navItems.map(n => (
          <a key={n.href} href={n.href}>{lang === 'es' ? n.es : n.en}</a>
        ))}
      </nav>
      <div className="header-right">
        <div className="lang">
          <button className={lang === 'es' ? 'active' : ''} onClick={() => setLang('es')}>ES</button>
          <span className="sep">/</span>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
        <a href="#contacto" className="cta-mini" data-magnetic onClick={close}>
          {lang === 'es' ? 'Agendar asesoría' : 'Book a call'}
        </a>
        <button
          className="menu-toggle"
          aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(v => !v)}
        >
          <span></span><span></span><span></span>
        </button>
      </div>

      <div className={`mobile-nav ${menuOpen ? 'open' : ''}`} aria-hidden={!menuOpen}>
        <nav>
          {navItems.map((n, i) => (
            <a key={n.href} href={n.href} onClick={close} style={{ transitionDelay: `${0.06 + i * 0.04}s` }}>
              <span className="num">{String(i + 1).padStart(2, '0')}</span>
              {lang === 'es' ? n.es : n.en}
            </a>
          ))}
          <a href="#contacto" className="mobile-cta" onClick={close} style={{ transitionDelay: `${0.06 + navItems.length * 0.04}s` }}>
            {lang === 'es' ? 'Agendar asesoría' : 'Book a call'}
          </a>
        </nav>
      </div>
    </header>
  );
}

/* ============ Cover ============ */
function Cover({ lang }) {
  return (
    <section className="cover" id="top">
      <div className="cover-bg" data-parallax="0.35" style={{ backgroundImage: "url('https://images.unsplash.com/photo-1436491865332-7a61a109cc05?w=2400&q=85&auto=format&fit=crop')" }}></div>
      <div className="cover-overlay"></div>
      <div className="cover-inner">
        <div className="cover-meta">
          <div><span className="dot"></span>{lang === 'es' ? 'Disponible para nuevos clientes · 2026' : 'Accepting new clients · 2026'}</div>
          <div>Medellín · Latam · Global</div>
        </div>

        <div className="cover-bottom">
          <div className="cover-logo-block">
            <LogoMark className="mark" color="#ffffff" />
            <div>
              <div className="name">Margarita<br/><span className="last">Sanmartín</span></div>
              <div className="tag">{lang === 'es' ? 'Estrategias de protección' : 'Protection strategies'}</div>
            </div>
          </div>

          <div className="cover-text">
            <h1>
              {lang === 'es'
                ? <>Protección internacional para personas, familias y <em>compañías globales.</em></>
                : <>International protection for individuals, families and <em>global companies.</em></>
              }
            </h1>
            <p>
              {lang === 'es'
                ? 'Soluciones globales en salud, vida, viajes y planificación patrimonial para quienes viven y se mueven internacionalmente.'
                : 'Global solutions in health, life, travel and wealth planning for those who live and move internationally.'}
            </p>
          </div>

          <a href="#soluciones" className="cover-cta" data-magnetic data-magnetic-strength="0.4">
            {lang === 'es' ? 'Explorar soluciones' : 'Explore solutions'}
            <svg className="arrow" width="16" height="10" viewBox="0 0 16 10" fill="none"><path d="M1 5H15M15 5L11 1M15 5L11 9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
          </a>
        </div>
      </div>

      <div className="cover-scroll">
        <div>Scroll</div>
        <div className="line"></div>
      </div>
    </section>
  );
}

/* ============ About ============ */
function About({ lang }) {
  return (
    <section className="section about" id="nosotros">
      <div className="section-head reveal">
        <div className="label">
          <span className="num">i.</span>
          <span className="eyebrow">{lang === 'es' ? 'Quiénes somos' : 'Who we are'}</span>
        </div>
        <h2>
          {lang === 'es'
            ? <>Una firma boutique para clientes que viven, trabajan e invierten <em>sin fronteras.</em></>
            : <>A boutique firm for clients who live, work and invest <em>without borders.</em></>}
        </h2>
      </div>

      <div className="about-grid">
        <div className="about-portrait reveal">
          <div className="corner">est. 1995</div>
          <div className="corner tr">Medellín · Colombia</div>
          <LogoMark className="mark-big" color="#ffffff" />
        </div>

        <div className="about-copy reveal d1">
          <span className="eyebrow">{lang === 'es' ? 'Nuestra propuesta' : 'Our approach'}</span>
          <h3>
            {lang === 'es'
              ? <>Más de <em>30 años</em> protegiendo el patrimonio, la salud y el futuro de familias y empresas en Latinoamérica.</>
              : <>More than <em>30 years</em> protecting the wealth, health and future of families and businesses across Latin America.</>}
          </h3>
          <p>
            {lang === 'es'
              ? 'Margarita Sanmartín es una firma especializada en protección personal y planificación financiera, liderada por una profesional en Negocios Internacionales con experiencia en compañías de alto reconocimiento a nivel nacional e internacional.'
              : 'Margarita Sanmartín is a firm specialized in personal protection and financial planning, led by a professional in International Business with deep experience across leading global firms.'}
          </p>
          <p>
            {lang === 'es'
              ? 'Combinamos experiencia internacional, atención personalizada y soluciones de alto nivel —sin las limitaciones de los productos tradicionales locales— para ofrecer respuestas claras, confiables y sostenibles en el tiempo.'
              : 'We combine international expertise, personal attention and best-in-class solutions—beyond the limits of traditional local products—to deliver clear, trustworthy answers that hold up over time.'}
          </p>
          <div className="signature">
            <div>
              <div className="signature-name">Margarita Sanmartín</div>
              <div className="signature-role">{lang === 'es' ? 'Fundadora · Asesora principal' : 'Founder · Lead advisor'}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ Values ============ */
function Values({ lang }) {
  const items = lang === 'es' ? [
    { t: 'Confianza', d: 'Relaciones de largo plazo construidas sobre transparencia, prudencia y resultados verificables.' },
    { t: 'Visión global', d: 'Soluciones offshore y respaldo internacional para clientes que se mueven en múltiples geografías.' },
    { t: 'Discreción', d: 'Acompañamiento confidencial y boutique, adaptado a cada perfil patrimonial y familiar.' },
    { t: 'Independencia', d: 'Asesoría libre de presiones comerciales: el producto correcto para cada necesidad, no al revés.' },
  ] : [
    { t: 'Trust', d: 'Long-term relationships built on transparency, prudence and verifiable results.' },
    { t: 'Global vision', d: 'Offshore solutions and international backing for clients moving across geographies.' },
    { t: 'Discretion', d: 'Confidential, boutique advice tailored to each family and patrimonial profile.' },
    { t: 'Independence', d: 'Advice free from sales pressure: the right product for each need, never the reverse.' },
  ];
  return (
    <section className="values">
      <div className="section-head reveal">
        <div className="label">
          <span className="num">ii.</span>
          <span className="eyebrow">{lang === 'es' ? 'Valores' : 'Values'}</span>
        </div>
        <h2>
          {lang === 'es'
            ? <>Los principios que sostienen <em>cada decisión</em> que tomamos por nuestros clientes.</>
            : <>The principles behind <em>every decision</em> we make for our clients.</>}
        </h2>
      </div>
      <div className="values-grid">
        {items.map((it, i) => (
          <div key={i} className={`value reveal d${i}`}>
            <span className="value-num">0{i+1}</span>
            <h4>{it.t}</h4>
            <p>{it.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============ Solutions tabs ============ */
function Solutions({ lang }) {
  const [tab, setTab] = useState('personas');

  const TABS = lang === 'es'
    ? [
        { id: 'personas', label: 'Personas & familias', num: '01' },
        { id: 'empresas', label: 'Empresas', num: '02' },
        { id: 'agencias', label: 'Agencias & partners', num: '03' },
      ]
    : [
        { id: 'personas', label: 'Individuals & families', num: '01' },
        { id: 'empresas', label: 'Companies', num: '02' },
        { id: 'agencias', label: 'Agencies & partners', num: '03' },
      ];

  const CONTENT = {
    personas: {
      es: {
        title: <>Para quienes viven, viajan y proyectan su <em>futuro</em> internacionalmente.</>,
        intro: 'Estructuramos coberturas y planes de inversión para individuos y familias que necesitan protección sin fronteras y proyección de largo plazo.',
        services: [
          { eye: 'Salud internacional', title: 'Medicina global sin límites', desc: 'Acceso a las mejores redes hospitalarias del mundo con atención VIP, anytime, anywhere.', img: 'https://images.unsplash.com/photo-1538108149393-fbbd81895907?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Viajes', title: 'Protección inteligente para viajeros frecuentes', desc: 'Cobertura premium con altos límites, equipaje, retrasos y asistencia médica VIP en cualquier país.', img: 'https://images.unsplash.com/photo-1488646953014-85cb44e25828?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Vida en USD', title: 'Protege a quienes más amas', desc: 'Seguros de vida en dólares con beneficios en vida, devolución de prima y cobertura familiar integral.', img: 'https://images.unsplash.com/photo-1511895426328-dc8714191300?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Ahorro & inversión', title: 'Cierra brechas, construye patrimonio', desc: 'Planes offshore enfocados en pensión, educación de los hijos y crecimiento patrimonial sostenido.', img: 'https://images.unsplash.com/photo-1518568814500-bf0f8d125f46?w=1200&q=80&auto=format&fit=crop' },
        ]
      },
      en: {
        title: <>For those who live, travel and plan their <em>future</em> internationally.</>,
        intro: 'We structure coverage and investment plans for individuals and families who need borderless protection and long-term projection.',
        services: [
          { eye: 'International health', title: 'Global medicine without limits', desc: 'Access to the world\'s top hospital networks with VIP care, anytime, anywhere.', img: 'https://images.unsplash.com/photo-1538108149393-fbbd81895907?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Travel', title: 'Smart protection for frequent travellers', desc: 'Premium coverage with high limits, baggage, delays and VIP medical assistance in any country.', img: 'https://images.unsplash.com/photo-1488646953014-85cb44e25828?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'USD life', title: 'Protect the ones you love most', desc: 'USD-denominated life insurance with living benefits, premium refund and full family coverage.', img: 'https://images.unsplash.com/photo-1511895426328-dc8714191300?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Savings & investment', title: 'Close gaps, build wealth', desc: 'Offshore plans focused on retirement, your children\'s education and sustained wealth growth.', img: 'https://images.unsplash.com/photo-1518568814500-bf0f8d125f46?w=1200&q=80&auto=format&fit=crop' },
        ]
      }
    },
    empresas: {
      es: {
        title: <>Beneficios de alto valor percibido para <em>retener al mejor talento.</em></>,
        intro: 'Estructuramos programas corporativos orientados a la retención y fidelización del talento, integrando beneficios que fortalecen la propuesta de valor al empleado.',
        services: [
          { eye: 'Salud internacional', title: 'Medicina VIP para ejecutivos clave', desc: 'Programas para perfiles que exigen acceso global a las mejores redes hospitalarias del mundo.', img: 'https://images.unsplash.com/photo-1573497019418-b400bb3ab074?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Viajes corporativos', title: 'Movilidad protegida, riesgo controlado', desc: 'Cobertura médica integral para equipos en movimiento, reduciendo exposición y duty of care.', img: 'https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Vida grupal', title: 'Esquemas diferenciados por perfil', desc: 'Coberturas según el nivel de cada posición —parte de una gestión integral del riesgo humano.', img: 'https://images.unsplash.com/photo-1521737604893-d14cc237f11d?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Ahorro & inversión', title: 'Bienestar financiero del equipo', desc: 'Programas de ahorro acompañados de educación financiera para proyectar el futuro del colaborador.', img: 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?w=1200&q=80&auto=format&fit=crop' },
        ]
      },
      en: {
        title: <>High-perceived-value benefits to <em>retain top talent.</em></>,
        intro: 'We design corporate programs focused on talent retention, weaving in benefits that strengthen your employee value proposition.',
        services: [
          { eye: 'International health', title: 'VIP medicine for key executives', desc: 'Programs for profiles demanding global access to the world\'s top hospital networks.', img: 'https://images.unsplash.com/photo-1573497019418-b400bb3ab074?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Corporate travel', title: 'Protected mobility, controlled risk', desc: 'Comprehensive medical coverage for teams in motion—reducing exposure and duty of care.', img: 'https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Group life', title: 'Schemes differentiated by profile', desc: 'Coverage aligned to each position level—part of an integrated human-risk strategy.', img: 'https://images.unsplash.com/photo-1521737604893-d14cc237f11d?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Savings & investment', title: 'Your team\'s financial wellbeing', desc: 'Savings programs paired with financial education to project your people\'s future.', img: 'https://images.unsplash.com/photo-1542744173-8e7e53415bb0?w=1200&q=80&auto=format&fit=crop' },
        ]
      }
    },
    agencias: {
      es: {
        title: <>Expande tu portafolio a <em>soluciones internacionales.</em></>,
        intro: 'En un mundo cada vez más globalizado, los clientes buscan respaldo de compañías internacionales con cobertura sin fronteras. Vincúlate como agente o agencia y comercializa productos premium con códigos de las mejores aseguradoras.',
        services: [
          { eye: 'Reclutamiento', title: 'Códigos directos con aseguradoras', desc: 'Vinculación como agente o agencia para comercializar soluciones internacionales con respaldo global.', img: 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Capacitación', title: 'Formación técnica & comercial', desc: 'Soporte continuo en producto, suscripción y argumentos de venta para perfiles HNW y corporativos.', img: 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Portafolio premium', title: 'Vumi, Dominion & más', desc: 'Acceso a Salud Internacional, Travel premium, Vida en USD y planes de ahorro offshore.', img: 'https://images.unsplash.com/photo-1542296332-2e4473faf563?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Co-asesoría', title: 'Acompañamiento en cierre', desc: 'Acompañamos en propuestas a clientes complejos para asegurar cierres y experiencia VIP.', img: 'https://images.unsplash.com/photo-1573497620053-ea5300f94f21?w=1200&q=80&auto=format&fit=crop' },
        ]
      },
      en: {
        title: <>Expand your portfolio with <em>international solutions.</em></>,
        intro: 'In an increasingly globalized world, clients seek international companies with borderless coverage. Join as an agent or agency and offer premium products backed by the best carriers.',
        services: [
          { eye: 'Recruitment', title: 'Direct carrier codes', desc: 'Onboard as an agent or agency to distribute international solutions with global backing.', img: 'https://images.unsplash.com/photo-1556761175-5973dc0f32e7?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Training', title: 'Technical & commercial training', desc: 'Ongoing support in product, underwriting and HNW / corporate sales arguments.', img: 'https://images.unsplash.com/photo-1552664730-d307ca884978?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Premium portfolio', title: 'Vumi, Dominion & more', desc: 'Access to International Health, premium Travel, USD Life and offshore savings.', img: 'https://images.unsplash.com/photo-1542296332-2e4473faf563?w=1200&q=80&auto=format&fit=crop' },
          { eye: 'Co-advisory', title: 'Closing-stage support', desc: 'We co-pitch complex client proposals to secure closes and deliver a VIP experience.', img: 'https://images.unsplash.com/photo-1573497620053-ea5300f94f21?w=1200&q=80&auto=format&fit=crop' },
        ]
      }
    }
  };

  const data = CONTENT[tab][lang];
  return (
    <section className="solutions" id="soluciones">
      <div className="section-head reveal">
        <div className="label">
          <span className="num">iii.</span>
          <span className="eyebrow">{lang === 'es' ? 'Soluciones' : 'Solutions'}</span>
        </div>
        <h2>
          {lang === 'es'
            ? <>Coberturas y planes a la medida de <em>cada perfil.</em> Tres puertas de entrada.</>
            : <>Coverage and plans tailored to <em>each profile.</em> Three ways in.</>}
        </h2>
      </div>

      <div className="tabs" id="personas">
        {TABS.map(t => (
          <button
            key={t.id}
            className={`tab ${tab === t.id ? 'active' : ''}`}
            onClick={() => setTab(t.id)}
            id={t.id === 'empresas' || t.id === 'agencias' ? t.id : undefined}
          >
            <span className="tab-num">{t.num}</span>
            {t.label}
          </button>
        ))}
      </div>

      <div className="tab-intro" key={tab}>
        <h3 className="reveal in">{data.title}</h3>
        <p className="reveal in d1">{data.intro}</p>
      </div>

      <div className="services" key={tab + '-grid'}>
        {data.services.map((s, i) => (
          <div key={i} className={`service reveal in d${i}`} data-tilt>
            <div className="service-img" data-tilt-image style={{ backgroundImage: `url(${s.img})` }}></div>
            <div className="service-body">
              <span className="service-eye">{s.eye}</span>
              <h4>{s.title}</h4>
              <p>{s.desc}</p>
              <span className="service-arrow">
                {lang === 'es' ? 'Conocer más' : 'Learn more'}
                <svg width="14" height="9" viewBox="0 0 14 9" fill="none"><path d="M1 4.5H13M13 4.5L9.5 1M13 4.5L9.5 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
              </span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============ Why International ============ */
function Why({ lang }) {
  const items = lang === 'es' ? [
    { t: 'Familias globales', d: 'Padres en un país, hijos en otro, propiedades en un tercero. La cobertura debe seguirlos a todos.' },
    { t: 'Movilidad internacional', d: 'Trabajo remoto, expatriaciones, segundas residencias. La vida ya no cabe en una sola póliza local.' },
    { t: 'Educación en el exterior', d: 'Universidad en Estados Unidos o Europa: planificación financiera y cobertura para los años de estudio.' },
    { t: 'Ejecutivos que viajan', d: 'Decenas de vuelos al año exigen una red médica que responda en cualquier ciudad.' },
    { t: 'Protección en USD', d: 'Activos y coberturas denominados en dólares, fuera del riesgo cambiario y la inflación local.' },
    { t: 'Acceso médico mundial', d: 'Las mejores clínicas del mundo, sin redes restringidas ni topes de cobertura.' },
  ] : [
    { t: 'Global families', d: 'Parents in one country, children in another, assets in a third. Coverage must follow them all.' },
    { t: 'International mobility', d: 'Remote work, expatriations, second homes. Life no longer fits inside a single local policy.' },
    { t: 'Education abroad', d: 'University in the US or Europe: financial planning and coverage for the study years.' },
    { t: 'Executives in motion', d: 'Dozens of flights per year demand a medical network that responds in any city.' },
    { t: 'USD-denominated cover', d: 'Assets and coverage in dollars, outside FX and local inflation risk.' },
    { t: 'Worldwide access', d: 'The best clinics on the planet—no restricted networks, no coverage caps.' },
  ];
  return (
    <section className="why" id="internacional">
      <div className="why-inner">
        <div className="section-head reveal">
          <div className="label">
            <span className="num">iv.</span>
            <span className="eyebrow">{lang === 'es' ? 'Por qué internacional' : 'Why international'}</span>
          </div>
          <h2>
            {lang === 'es'
              ? <>El mundo cambió. La protección <em>también debe hacerlo.</em></>
              : <>The world has changed. Protection <em>must change too.</em></>}
          </h2>
        </div>
        <div className="why-grid">
          {items.map((it, i) => (
            <div key={i} className="why-item reveal">
              <span className="num">0{i+1}</span>
              <h4>{it.t}</h4>
              <p>{it.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ Contact ============ */
function Contact({ lang }) {
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({ nombre: '', email: '', tel: '', perfil: '', interes: '', mensaje: '' });
  const handle = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = (e) => { e.preventDefault(); setSubmitted(true); };

  const t = (es, en) => lang === 'es' ? es : en;

  const arrow = <svg className="arrow" width="18" height="12" viewBox="0 0 18 12" fill="none"><path d="M1 6H17M17 6L12 1M17 6L12 11" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>;

  return (
    <section className="contact" id="contacto">
      <div className="contact-banner">
        <div className="contact-banner-inner">
          <div className="reveal">
            <span className="eyebrow"><span className="num" style={{ marginRight: 10, opacity: 0.6 }}>v.</span>{t('Contacto', 'Contact')}</span>
            <h2>
              {lang === 'es'
                ? <>Una conversación es el <em>primer paso.</em></>
                : <>A conversation is the <em>first step.</em></>}
            </h2>
          </div>
          <p className="lede reveal d2">
            {t(
              'Asesoría confidencial, sin compromiso. Escuchamos tu situación, entendemos tus prioridades y diseñamos las soluciones que mejor se ajustan a ti, tu familia o tu empresa.',
              'Confidential, no-commitment consultation. We listen, understand your priorities and design the solutions that best fit you, your family or your company.'
            )}
          </p>
        </div>
      </div>

      <div className="contact-body">
        <div className="contact-card reveal">
          <span className="eyebrow">{t('Habla directamente conmigo', 'Talk to me directly')}</span>
          <h3>{t(<>Tres formas de empezar <em>hoy mismo.</em></>, <>Three ways to start <em>today.</em></>)}</h3>
          <p className="intro">
            {t(
              'Respondo personalmente cada mensaje. Elige el canal con el que te sientas más cómodo.',
              'I personally answer every message. Pick whichever channel feels most comfortable.'
            )}
          </p>

          <div className="margarita-card">
            <div className="avatar">
              <svg viewBox="0 0 100 60" fill="none">
                <text x="50" y="42" textAnchor="middle" fontFamily="Instrument Serif, serif" fontSize="36" fontStyle="italic" fill="#f6f4ef">mMs</text>
              </svg>
            </div>
            <div className="info">
              <div className="name">Margarita Sanmartín</div>
              <div className="role">{t('Asesora · Fundadora', 'Advisor · Founder')}</div>
              <div className="creds">{t('30+ años · Negocios Internacionales · Medellín, Colombia', '30+ years · International Business · Medellín, Colombia')}</div>
            </div>
          </div>

          <div className="quick-contacts reveal d2">
            <a className="qc-row" href="https://wa.me/573185349147" target="_blank" rel="noreferrer">
              <span className="ico"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4l-2.4-1.1c-.3-.1-.7 0-.9.2l-1 1.2c-1.5-.7-2.7-1.9-3.4-3.4l1.2-1c.2-.2.3-.5.2-.9L10.1 7c-.1-.3-.5-.5-.8-.4L7 7.3c-.3.1-.6.3-.6.7C6.4 14 10 17.6 16 17.6c.4 0 .6-.3.7-.6l.7-2.3c.1-.3-.1-.6-.4-.8z"/><path d="M12 1C6 1 1 6 1 12c0 2 .5 3.9 1.5 5.6L1 23l5.6-1.5c1.7 1 3.5 1.5 5.4 1.5 6 0 11-5 11-11S18 1 12 1zm0 20c-1.8 0-3.5-.5-5-1.4l-.4-.2-3.3.9.9-3.2-.2-.4C3 15.4 2.5 13.7 2.5 12 2.5 6.8 6.8 2.5 12 2.5S21.5 6.8 21.5 12 17.2 21.5 12 21.5z"/></svg></span>
              <span className="text">
                <span className="label">WhatsApp · {t('Respuesta en minutos', 'Reply in minutes')}</span>
                <span className="value">+57 318 534 9147</span>
              </span>
              {arrow}
            </a>
            <a className="qc-row" href="mailto:margarita.sanmartin@unityfinancialnetwork.com">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 6h18v12H3z"/><path d="M3 7l9 7 9-7"/></svg></span>
              <span className="text">
                <span className="label">Email · {t('Respondo en 24 h', 'Reply within 24 h')}</span>
                <span className="value email">margarita.sanmartin@unityfinancialnetwork.com</span>
              </span>
              {arrow}
            </a>
            <a className="qc-row" href="#contacto">
              <span className="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="16" rx="1.5"/><path d="M3 9h18M8 3v4M16 3v4"/></svg></span>
              <span className="text">
                <span className="label">{t('Agenda · Sesión 45 min', 'Schedule · 45 min session')}</span>
                <span className="value">{t('Reserva una asesoría 1:1', 'Book a 1:1 consultation')}</span>
              </span>
              {arrow}
            </a>
          </div>

          <div className="response-note">
            <span className="pulse"></span>
            <span>{t('Disponible esta semana · Lun–Vie · 9:00–18:00 (GMT−5)', 'Available this week · Mon–Fri · 9:00–18:00 (GMT−5)')}</span>
          </div>
        </div>

        <form className="contact-form reveal d2" onSubmit={submit}>
          {submitted ? (
            <div className="success-card">
              <div className="check">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12l5 5L20 7"/></svg>
              </div>
              <h4>{t('Gracias, ' + (form.nombre || 'recibido'), 'Thank you' + (form.nombre ? ', ' + form.nombre : ''))}</h4>
              <p>{t('Te contactaré personalmente en las próximas 24 horas hábiles.', 'I\'ll reach out personally within the next 24 business hours.')}</p>
            </div>
          ) : (
            <>
              <span className="eyebrow">{t('Solicitud de asesoría', 'Request a consultation')}</span>
              <h3>{t('Cuéntame en qué puedo ayudarte.', 'Tell me how I can help you.')}</h3>
              <div className="form-row">
                <div className="field">
                  <label>{t('Nombre completo', 'Full name')}</label>
                  <input required type="text" value={form.nombre} onChange={handle('nombre')} placeholder={t('María Pérez', 'Maria Perez')} />
                </div>
                <div className="field">
                  <label>{t('Teléfono', 'Phone')}</label>
                  <input type="tel" value={form.tel} onChange={handle('tel')} placeholder="+57 300 000 0000" />
                </div>
              </div>
              <div className="field">
                <label>Email</label>
                <input required type="email" value={form.email} onChange={handle('email')} placeholder="email@dominio.com" />
              </div>
              <div className="form-row">
                <div className="field">
                  <label>{t('Perfil', 'Profile')}</label>
                  <select value={form.perfil} onChange={handle('perfil')} required>
                    <option value="">{t('Selecciona…', 'Select…')}</option>
                    <option>{t('Persona / familia', 'Individual / family')}</option>
                    <option>{t('Empresa', 'Company')}</option>
                    <option>{t('Agente / agencia', 'Agent / agency')}</option>
                  </select>
                </div>
                <div className="field">
                  <label>{t('Interés principal', 'Primary interest')}</label>
                  <select value={form.interes} onChange={handle('interes')} required>
                    <option value="">{t('Selecciona…', 'Select…')}</option>
                    <option>{t('Salud internacional', 'International health')}</option>
                    <option>{t('Seguros de viaje', 'Travel insurance')}</option>
                    <option>{t('Seguros de vida (USD)', 'Life insurance (USD)')}</option>
                    <option>{t('Ahorro e inversión', 'Savings & investment')}</option>
                    <option>{t('Beneficios corporativos', 'Corporate benefits')}</option>
                    <option>{t('Vinculación como agente', 'Become an agent')}</option>
                  </select>
                </div>
              </div>
              <div className="field">
                <label>{t('Mensaje (opcional)', 'Message (optional)')}</label>
                <textarea rows="3" value={form.mensaje} onChange={handle('mensaje')} placeholder={t('Cuéntame brevemente tu situación…', 'Briefly describe your situation…')}></textarea>
              </div>
              <button type="submit" className="btn-submit" data-magnetic data-magnetic-strength="0.3">
                {t('Enviar solicitud', 'Send request')}
                <svg width="14" height="10" viewBox="0 0 16 10" fill="none"><path d="M1 5H15M15 5L11 1M15 5L11 9" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
              </button>
            </>
          )}
        </form>
      </div>
    </section>
  );
}

/* ============ Footer ============ */
function Footer({ lang }) {
  const t = (es, en) => lang === 'es' ? es : en;
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-brand">
          <LogoMark className="footer-mark" color="#ffffff" />
          <div className="name">Margarita <em>Sanmartín</em></div>
          <p>{t(
            'Firma boutique especializada en protección personal, planificación patrimonial y soluciones internacionales para clientes en Latinoamérica.',
            'Boutique firm specialized in personal protection, wealth planning and international solutions for clients across Latin America.'
          )}</p>
        </div>
        <div>
          <h5>{t('Soluciones', 'Solutions')}</h5>
          <ul>
            <li><a href="#personas">{t('Personas', 'Individuals')}</a></li>
            <li><a href="#empresas">{t('Empresas', 'Companies')}</a></li>
            <li><a href="#agencias">{t('Agencias', 'Partners')}</a></li>
          </ul>
        </div>
        <div>
          <h5>{t('Compañía', 'Company')}</h5>
          <ul>
            <li><a href="#nosotros">{t('Quiénes somos', 'About')}</a></li>
            <li><a href="#internacional">{t('Por qué internacional', 'Why international')}</a></li>
            <li><a href="#contacto">{t('Contacto', 'Contact')}</a></li>
          </ul>
        </div>
        <div>
          <h5>{t('Contacto', 'Contact')}</h5>
          <ul>
            <li><a href="https://wa.me/573185349147">+57 318 534 9147</a></li>
            <li><a href="mailto:margarita.sanmartin@unityfinancialnetwork.com">margarita.sanmartin<br/>@unityfinancialnetwork.com</a></li>
            <li>Medellín · Colombia</li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <div>© 2026 Margarita Sanmartín · {t('Todos los derechos reservados', 'All rights reserved')}</div>
        <div className="mono">UNITY FINANCIAL NETWORK · COL → LATAM → GLOBAL</div>
      </div>
    </footer>
  );
}

/* ============ App ============ */
function App() {
  const [lang, setLang] = useState('es');
  const [scrolled, setScrolled] = useState(false);
  const [coverMode, setCoverMode] = useState(true);

  // ────────────────────────────────────────────────────────────
  //  Lenis ↔ GSAP ScrollTrigger + reveal/parallax/magnetic/tilt
  // ────────────────────────────────────────────────────────────
  useEffect(() => {
    const hasGSAP = typeof window.gsap !== 'undefined' && typeof window.ScrollTrigger !== 'undefined';
    const hasLenis = typeof window.Lenis !== 'undefined';
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const isTouch = window.matchMedia('(hover: none), (pointer: coarse)').matches;

    // Always-on: header state via scroll
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 60);
      setCoverMode(y < window.innerHeight - 80);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();

    // Reduced motion → reveal everything instantly, skip Lenis+GSAP
    if (prefersReduced || !hasGSAP) {
      document.querySelectorAll('.reveal').forEach(el => el.classList.add('in'));
      return () => window.removeEventListener('scroll', onScroll);
    }

    const { gsap, ScrollTrigger } = window;
    gsap.registerPlugin(ScrollTrigger);

    // ── Lenis init + ticker sync ──
    let lenis = null;
    if (hasLenis) {
      lenis = new window.Lenis({
        duration: 1.15,
        easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
        smoothWheel: true,
        smoothTouch: false,
      });
      lenis.on('scroll', ScrollTrigger.update);
      const rafFn = (time) => lenis.raf(time * 1000);
      gsap.ticker.add(rafFn);
      gsap.ticker.lagSmoothing(0);
      // Hook in-page anchor links to lenis.scrollTo
      const anchorHandler = (e) => {
        const a = e.target.closest('a[href^="#"]');
        if (!a) return;
        const id = a.getAttribute('href');
        if (id.length < 2) return;
        const target = document.querySelector(id);
        if (!target) return;
        e.preventDefault();
        lenis.scrollTo(target, { offset: -80, duration: 1.3 });
      };
      document.addEventListener('click', anchorHandler);
      lenis._anchorHandler = anchorHandler;
    }

    // ── matchMedia gates motion intensity per breakpoint ──
    const mm = gsap.matchMedia();
    const ctx = gsap.context(() => {
      mm.add({
        isDesktop: '(min-width: 1024px)',
        isTablet: '(min-width: 640px) and (max-width: 1023px)',
        isMobile: '(max-width: 639px)',
      }, (context) => {
        const { isDesktop, isMobile } = context.conditions;

        // Reveal animations — stagger siblings inside a common parent
        const reveals = gsap.utils.toArray('.reveal');
        // Bucket by parent for grouped stagger
        const groups = new Map();
        reveals.forEach(el => {
          const parent = el.closest('.section, .values, .solutions, .why, .contact, .cover, .footer, .about-grid, .values-grid, .services, .why-grid, .contact-body, .footer-top') || document.body;
          if (!groups.has(parent)) groups.set(parent, []);
          groups.get(parent).push(el);
        });
        groups.forEach((els) => {
          gsap.fromTo(els, {
            opacity: 0,
            y: isMobile ? 18 : 28,
          }, {
            opacity: 1,
            y: 0,
            duration: isMobile ? 0.7 : 0.9,
            ease: 'power3.out',
            stagger: isMobile ? 0.05 : 0.08,
            scrollTrigger: {
              trigger: els[0],
              start: 'top 88%',
              toggleActions: 'play none none none',
              once: true,
            },
          });
          els.forEach(el => el.classList.add('in'));
        });

        // Parallax — opt-in via data-parallax="speed"
        gsap.utils.toArray('[data-parallax]').forEach(el => {
          const speed = parseFloat(el.dataset.parallax) || 0.3;
          gsap.to(el, {
            yPercent: speed * 35,
            scale: 1.06,
            ease: 'none',
            scrollTrigger: {
              trigger: el.parentElement || el,
              start: 'top top',
              end: 'bottom top',
              scrub: true,
            },
          });
        });

        // Headlines: subtle clip-reveal on serif h2 in section heads
        gsap.utils.toArray('.section-head h2, .contact-banner h2').forEach(h2 => {
          gsap.fromTo(h2, {
            clipPath: 'inset(0 100% 0 0)',
            opacity: 0.3,
          }, {
            clipPath: 'inset(0 0% 0 0)',
            opacity: 1,
            duration: isMobile ? 0.9 : 1.2,
            ease: 'power3.out',
            scrollTrigger: { trigger: h2, start: 'top 85%', once: true },
          });
        });

        // Magnetic CTAs (desktop only, non-touch)
        const magnetCleaners = [];
        if (isDesktop && !isTouch) {
          gsap.utils.toArray('[data-magnetic]').forEach(el => {
            const strength = parseFloat(el.dataset.magneticStrength) || 0.35;
            const xTo = gsap.quickTo(el, 'x', { duration: 0.4, ease: 'power3.out' });
            const yTo = gsap.quickTo(el, 'y', { duration: 0.4, ease: 'power3.out' });
            const move = (e) => {
              const r = el.getBoundingClientRect();
              xTo((e.clientX - (r.left + r.width / 2)) * strength);
              yTo((e.clientY - (r.top + r.height / 2)) * strength);
            };
            const reset = () => { xTo(0); yTo(0); };
            el.addEventListener('mousemove', move);
            el.addEventListener('mouseleave', reset);
            magnetCleaners.push(() => {
              el.removeEventListener('mousemove', move);
              el.removeEventListener('mouseleave', reset);
              gsap.set(el, { clearProps: 'transform' });
            });
          });
        }

        // 3D tilt on service cards (desktop only)
        const tiltCleaners = [];
        if (isDesktop && !isTouch) {
          gsap.utils.toArray('[data-tilt]').forEach(card => {
            const rxTo = gsap.quickTo(card, 'rotationX', { duration: 0.5, ease: 'power3.out' });
            const ryTo = gsap.quickTo(card, 'rotationY', { duration: 0.5, ease: 'power3.out' });
            gsap.set(card, { transformPerspective: 900, transformOrigin: 'center' });
            const img = card.querySelector('[data-tilt-image]');
            const imgX = img ? gsap.quickTo(img, 'x', { duration: 0.5, ease: 'power3.out' }) : null;
            const imgY = img ? gsap.quickTo(img, 'y', { duration: 0.5, ease: 'power3.out' }) : null;
            const move = (e) => {
              const r = card.getBoundingClientRect();
              const px = (e.clientX - r.left) / r.width - 0.5;
              const py = (e.clientY - r.top) / r.height - 0.5;
              ryTo(px * 8);
              rxTo(-py * 6);
              if (imgX) imgX(px * 10);
              if (imgY) imgY(py * 10);
            };
            const reset = () => {
              rxTo(0); ryTo(0);
              if (imgX) imgX(0);
              if (imgY) imgY(0);
            };
            card.addEventListener('mousemove', move);
            card.addEventListener('mouseleave', reset);
            tiltCleaners.push(() => {
              card.removeEventListener('mousemove', move);
              card.removeEventListener('mouseleave', reset);
              gsap.set(card, { clearProps: 'transform,transformPerspective,transformOrigin' });
              if (img) gsap.set(img, { clearProps: 'transform' });
            });
          });
        }

        return () => {
          magnetCleaners.forEach(fn => fn());
          tiltCleaners.forEach(fn => fn());
        };
      });
    });

    // refresh after fonts and images settle
    const refresh = () => ScrollTrigger.refresh();
    window.addEventListener('load', refresh);
    if (document.fonts && document.fonts.ready) document.fonts.ready.then(refresh);

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('load', refresh);
      mm.revert();
      ctx.revert();
      ScrollTrigger.getAll().forEach(t => t.kill());
      if (lenis) {
        document.removeEventListener('click', lenis._anchorHandler);
        gsap.ticker.remove((time) => lenis.raf(time * 1000));
        lenis.destroy();
      }
    };
  }, []);

  // Re-run ScrollTrigger after language toggle relayouts
  useEffect(() => {
    if (window.ScrollTrigger) {
      const id = setTimeout(() => window.ScrollTrigger.refresh(), 60);
      return () => clearTimeout(id);
    }
  }, [lang]);

  return (
    <>
      <Header lang={lang} setLang={setLang} coverMode={coverMode} scrolled={scrolled} />
      <Cover lang={lang} />
      <About lang={lang} />
      <Values lang={lang} />
      <Solutions lang={lang} />
      <Why lang={lang} />
      <Contact lang={lang} />
      <Footer lang={lang} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
