/** The Conscious Code — 2026 redesign (top).
 *
 * Hero (new copy) · Pain Points · Roadmap of services · Why Us / team.
 * Audience: family-business owner in MX/LATAM. Warm Spanish, no jargon.
 * Visual DNA: Neon Monolith (cyan #00ffcc on Void #0c141f) — unchanged.
 */

const { useEffect, useRef, useState } = React;

/* ───────────────────────────────────────────────────────  HeroNew */
function HeroNew() {
  const { t } = useLang();
  const containerRef = useRef(null);
  const headerRef    = useRef(null);
  const cubeRef      = useRef(null);
  const hintRef      = useRef(null);
  const asteriskRef  = useRef(null);

  useEffect(() => {
    let inView = false, ticking = false;
    const update = () => {
      ticking = false;
      const el = containerRef.current;
      if (!el || !inView) return;
      const rect = el.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const p = Math.max(0, Math.min(1, -rect.top / total));
      const headerProg = Math.min(1, p / 0.25);
      if (headerRef.current) {
        headerRef.current.style.opacity = String(1 - headerProg);
        headerRef.current.style.transform = `translate3d(0, ${-100 * headerProg}px, 0)`;
      }
      if (hintRef.current) hintRef.current.style.opacity = String(1 - headerProg);
      if (cubeRef.current) {
        const y = -160 * p + 80, rot = 360 * p;
        const o = p < 0.05 ? p / 0.05 : (p > 0.9 ? 1 - (p - 0.9) / 0.1 * 0.2 : 1);
        cubeRef.current.style.transform = `translate3d(-50%, ${y}px, 0) rotate(${rot}deg)`;
        cubeRef.current.style.opacity = String(o);
      }
      if (asteriskRef.current) {
        const blur = 10 + p * 32, a = Math.min(1, 0.6 + p * 0.4);
        asteriskRef.current.style.textShadow = `0 0 ${blur}px rgba(0,255,213,${a})`;
      }
    };
    const onScroll = () => {
      if (!ticking) {
        requestAnimationFrame(update);
        ticking = true;
      }
    };
    // Only run when hero intersects viewport — when below, nothing fires.
    const io = new IntersectionObserver(([e]) => {
      inView = e.isIntersecting;
      if (inView) update(); // sync once on enter
    }, { threshold: 0 });
    if (containerRef.current) io.observe(containerRef.current);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      io.disconnect();
    };
  }, []);

  return (
    <section ref={containerRef} id="home" className="hero-scroll">
      <div className="hero-sticky">
        <div className="container" style={{ position: 'relative', zIndex: 4 }}>
          <div ref={headerRef} className="hero-header">
            {/* Eyebrow */}
            <div style={{ marginBottom: 56, display: 'flex', alignItems: 'center', gap: 14, justifyContent: 'center' }}>
              <span style={{ display: 'inline-block', width: 32, height: 1, background: 'var(--tcc-primary)' }} />
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--tcc-primary)', letterSpacing: '0.3em', textTransform: 'uppercase', fontWeight: 700 }}>
                {t('Tecnología familiar · IA con propósito · México & LATAM', 'Family-business tech · AI with purpose · Mexico & LATAM')}
              </span>
              <span style={{ display: 'inline-block', width: 32, height: 1, background: 'var(--tcc-primary)' }} />
            </div>

            {/* Triple-weight headline, but with the new family-business copy */}
            <h1 style={{
              fontFamily: 'var(--tcc-font-display)',
              fontSize: 'clamp(2.25rem, 5.5vw, 5rem)',
              lineHeight: 1.04,
              letterSpacing: '-0.03em',
              maxWidth: '22ch',
              margin: '0 auto',
              textAlign: 'center',
              color: 'var(--tcc-on-surface)',
              fontWeight: 300,
            }}>
              <MaskLine delay={0}>
                <span style={{ fontWeight: 300 }}>{t('Tecnología con propósito,', 'Technology with a purpose,')}</span>
              </MaskLine>
              <MaskLine delay={200}>
                <span style={{ fontWeight: 700 }}>{t('simplicidad absoluta', 'dead-simple to use')}</span>
              </MaskLine>
              <MaskLine delay={400}>
                <span style={{ fontWeight: 300, color: 'var(--tcc-on-surface-variant)' }}>{t('y', 'and')}{' '}
                  <span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>{t('consciencia de negocio.', 'built around your business.')}</span>
                </span>
              </MaskLine>
            </h1>

            <p className="lead" style={{ marginTop: 48, maxWidth: 620, marginInline: 'auto', textAlign: 'center', fontSize: 19, fontWeight: 300 }}>
              {t('Llevamos la experiencia de empresas globales a negocios familiares en Latinoamérica. Sin complicaciones tecnológicas. Sin riesgos innecesarios.', 'We bring the experience of global companies to family businesses across Latin America. No tech headaches. No needless risk.')}
            </p>

            <div style={{ marginTop: 56, display: 'flex', justifyContent: 'center', gap: 24, flexWrap: 'wrap', alignItems: 'center' }}>
              <PrimaryButton onClick={() => document.getElementById('contacto')?.scrollIntoView()}>
                {t('Conoce cómo podemos ayudarte', 'See how we can help')}
                <span style={{ width: 16, height: 16 }}><Icon.ChevronRight /></span>
              </PrimaryButton>
              <a className="moment-link" onClick={(e) => { e.preventDefault(); document.getElementById('pain')?.scrollIntoView(); }}>
                {t('Ver señales de alarma', 'See the warning signs')}
              </a>
            </div>
          </div>
        </div>

        <div
          ref={cubeRef}
          className="hero-cube"
          style={{
            position: 'absolute', top: '60%', left: '50%',
            transform: 'translate(-50%, 80px)', pointerEvents: 'none',
            zIndex: 3, width: 220, height: 220,
            filter: 'drop-shadow(0 0 24px rgba(0,255,213,0.4))',
          }}
        >
          <CubeWithGlow asteriskRef={asteriskRef} />
        </div>

        <div ref={hintRef} style={{
          position: 'absolute', bottom: 32, left: '50%', transform: 'translateX(-50%)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
          color: 'rgba(189,203,194,0.35)',
        }}>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase' }}>{t('Explorar', 'Scroll')}</span>
          <div style={{ width: 1, height: 48, background: 'linear-gradient(to bottom, rgba(0,255,204,0.4), transparent)' }} />
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────  Pain Points · "The Mirror" */
function PainPoints() {
  const { t } = useLang();
  const pains = [
    { icon: <Icon.Workflow />, title: t('Todo depende de una sola persona', 'Everything rides on one person'), desc: t('Si tu contador, tu gerente de ventas, o tú mismo se van de vacaciones — ¿el negocio sigue funcionando igual?', 'If your bookkeeper, your sales manager, or you take a week off — does the business still run the same?') },
    { icon: <Icon.Database />, title: t('Tus datos están en 20 lugares', 'Your data lives in 20 places'), desc: t('Excel aquí, WhatsApp allá, cuadernos por otro lado. ¿Cuánto estás perdiendo sin saberlo?', 'A spreadsheet here, WhatsApp there, notebooks somewhere else. How much are you losing without knowing it?') },
    { icon: <Icon.Users    />, title: t('La siguiente generación necesita herramientas diferentes', 'The next generation needs different tools'), desc: t('Tu hijo o hija quiere modernizar, pero ¿por dónde empezar sin poner en riesgo lo que ya funciona?', 'Your son or daughter wants to modernize — but where do you start without breaking what already works?') },
  ];
  return (
    <section id="pain" className="section bg-low">
      <div className="container">
        <div style={{ marginBottom: 72, display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 32, alignItems: 'end' }}>
          <div style={{ gridColumn: 'span 5' }}>
            <Eyebrow>{t('· Señales de alarma', '· Warning signs')}</Eyebrow>
            <h2 style={{ marginTop: 18, fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2rem, 5vw, 4.25rem)', fontWeight: 300, lineHeight: 1, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)' }}>
              <MaskLine delay={0}><span style={{ fontWeight: 300 }}>{t('¿Te suena', 'Sound')}</span></MaskLine>
              <MaskLine delay={180}><span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>{t('familiar?', 'familiar?')}</span></MaskLine>
            </h2>
          </div>
          <p style={{ gridColumn: 'span 7 / span 7', fontFamily: 'var(--tcc-font-body)', fontWeight: 300, fontSize: 17, color: 'var(--tcc-on-surface-variant)', lineHeight: 1.65, maxWidth: '52ch', marginLeft: 'auto' }}>
            {t('Estos tres patrones se repiten en casi todas las empresas familiares con las que hablamos. Si reconoces uno, vale la pena platicar.', 'These three patterns show up in almost every family business we talk to. If even one rings true, it’s worth a conversation.')}
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32 }} className="pain-grid">
          {pains.map((p, i) => (
            <Reveal key={p.title} delay={i * 120}>
              <article className="pain-card">
                <div className="icon-chip"><div style={{ width: 26, height: 26 }}>{p.icon}</div></div>
                <h3>{p.title}</h3>
                <p>{p.desc}</p>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ───────────────────────────────────────────────  Roadmap · "How We Help" */
function RoadmapServices() {
  const { t } = useLang();
  const steps = [
    { num: '01', icon: <Icon.Search />,       title: t('Entendemos tu negocio', 'We learn your business'),                  desc: t('Nos sentamos contigo, entendemos cómo opera tu empresa hoy, y te damos un diagnóstico claro — sin jerga técnica, sin compromisos.', 'We sit down with you, learn how your company runs today, and give you a clear read — no tech jargon, no strings attached.'),                              tag: t('Diagnóstico claro y accionable', 'A clear, usable diagnosis') },
    { num: '02', icon: <Icon.BrainCircuit />, title: t('Capacitamos a tu equipo', 'We train your team'),                desc: t('Tu gente aprende a usar IA de forma práctica. No necesitan ser ingenieros — solo necesitan ganas de mejorar.', 'Your people learn to use AI in a hands-on way. They don’t need to be engineers — just willing to improve.'),                                                  tag: t('Equipo autónomo con nuevas herramientas', 'A self-sufficient team with new tools') },
    { num: '03', icon: <Icon.Database />,     title: t('Ordenamos tu información', 'We organize your data'),               desc: t('Limpiamos y organizamos tus datos para que puedas tomar decisiones con información real, no con intuición.', 'We clean up and organize your data so you can make decisions on real numbers, not gut feel.'),                                                       tag: t('Una sola fuente de verdad', 'One single source of truth') },
    { num: '04', icon: <Icon.Zap />,          title: t('Automatizamos lo repetitivo', 'We automate the busywork'),            desc: t('Asistentes digitales trabajan 24/7 en las tareas que nadie quiere hacer: reportes, seguimientos, conciliaciones.', 'Digital assistants work 24/7 on the tasks nobody wants to do: reports, follow-ups, reconciliations.'),                                                tag: t('Horas libres para lo que importa', 'Hours freed up for what matters') },
    { num: '05', icon: <Icon.ShieldCheck />,  title: t('Rescatamos tu conocimiento', 'We capture your know-how'),             desc: t('Los 30 años de experiencia de Don Carlos no se van cuando él se retire. Los convertimos en un activo digital permanente.', 'Don Carlos’s 30 years of experience don’t walk out the door when he retires. We turn them into a permanent digital asset.'),                                       tag: t('Memoria institucional protegida', 'Company memory, protected') },
    { num: '06', icon: <Icon.TrendingUp />,   title: t('Te acompañamos a largo plazo', 'We stick with you long-term'),           desc: t('No te dejamos solo después del proyecto. Somos tu director de datos fraccionado — estrategia continua sin el costo de un ejecutivo de tiempo completo.', 'We don’t disappear when the project ends. We’re your fractional data chief — ongoing strategy without the cost of a full-time exec.'),          tag: t('Dirección estratégica permanente', 'Ongoing strategic direction') },
  ];
  return (
    <section id="servicios" className="section">
      <div className="container">
        <div style={{ marginBottom: 72, display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 32, alignItems: 'end' }}>
          <div style={{ gridColumn: 'span 6' }}>
            <Eyebrow>{t('· Cómo trabajamos', '· How we work')}</Eyebrow>
            <h2 style={{ marginTop: 18, fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2rem, 5vw, 4.5rem)', fontWeight: 300, lineHeight: 1, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)' }}>
              <MaskLine delay={0}><span style={{ fontWeight: 300 }}>{t('Un camino', 'A clear')}</span></MaskLine>
              <MaskLine delay={180}><span style={{ fontWeight: 700 }}>{t('claro,', 'path,')}</span></MaskLine>
              <MaskLine delay={360}><span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>{t('paso a paso.', 'one step at a time.')}</span></MaskLine>
            </h2>
          </div>
          <p style={{ gridColumn: 'span 6 / span 6', fontFamily: 'var(--tcc-font-body)', fontWeight: 300, fontSize: 17, color: 'var(--tcc-on-surface-variant)', lineHeight: 1.65, maxWidth: '50ch', marginLeft: 'auto' }}>
            {t('Seis pasos auditables, contratables por separado. Empezamos por entender — no por vender. Cada etapa se mide antes de pasar a la siguiente.', 'Six clear steps you can hire one at a time. We start by understanding — not by selling. Each stage is measured before we move to the next.')}
          </p>
        </div>

        <div className="roadmap">
          {steps.map((s, i) => (
            <Reveal key={s.num} delay={i * 100}>
              <article className="roadmap-step">
                <div className="step-eyebrow">{`${s.num}. ${s.title.toUpperCase()}`}</div>
                <h3 className="step-title">{s.title}</h3>
                <p className="step-desc">{s.desc}</p>
                <span className="result-tag">→ {s.tag.toUpperCase()}</span>
                <div className="step-icon">
                  <div className="step-icon-chip"><div style={{ width: 22, height: 22 }}>{s.icon}</div></div>
                </div>
              </article>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────  Why Us · trust + team + logos */
function WhyUs() {
  const { t } = useLang();
  const bios = [
    { name: 'Eduardo Martínez Fonseca', initial: 'E', role: t('Senior Advisor · Estrategia de Negocios & Gobernanza de Datos', 'Senior Advisor · Business Strategy & Data Governance'), body: t('Con dominio del ecosistema internacional de negocios e Inteligencia Artificial. Rigor corporativo forjado en consultoría de élite y empresas de consumo masivo en Europa, con el enfoque en entender tu modelo de negocio latinoamericano antes de que hablemos de datos, para asegurar que el desarrollo de tecnología sea relevante, gobernada, eficiente, segura y escalable.', 'Fluent in the international worlds of business and AI. Corporate discipline built at top-tier consulting firms and major consumer brands in Europe — with a focus on understanding your Latin American business model before we ever talk data, so the technology we build is relevant, well-governed, efficient, secure, and ready to scale.') },
    { name: 'Francisco Cambero', initial: 'F', role: t('Especialista · Entornos basados en Agentes de IA', 'Specialist · AI Agent-Based Systems'), body: t('Experiencia en el desarrollo de automatización avanzada y tecnologías digitales para optimizar el crecimiento empresarial y la excelencia operativa. Tras escalar soluciones de automatización autónoma asistidas por IA junto a líderes del sector agrícola como Koidra y Hoogendoorn, su enfoque actual transforma por completo la analítica tradicional.', 'Experienced in building advanced automation and digital tools that drive business growth and operational excellence. After scaling AI-assisted autonomous automation alongside ag-tech leaders like Koidra and Hoogendoorn, his current work completely reimagines traditional analytics.') },
  ];
  const pillars = [
    { h: t('Simple y rentable', 'Simple and cost-effective'),      p: t('No te vamos a vender tecnología que no necesitas. Usamos herramientas accesibles, priorizamos lo que genera impacto real, y te mostramos resultados antes de pedirte un peso más.', 'We won’t sell you tech you don’t need. We use affordable tools, focus on what actually moves the needle, and show you results before asking for another dollar.') },
    { h: t('Tu negocio, tu control', 'Your business, your control'), p: t('No dependes de nosotros. Te enseñamos, te empoderas, y te dejamos herramientas que tu equipo puede manejar. Si mañana decides seguir solo, podrás hacerlo.', 'You don’t depend on us. We teach you, hand you the controls, and leave you with tools your team can run. If you decide to go it alone tomorrow, you can.') },
  ];
  return (
    <section id="nosotros" className="section bg-low">
      <div className="container">
        <div style={{ marginBottom: 56, maxWidth: 880 }}>
          <Eyebrow>{t('· Por qué confiar en nosotros', '· Why trust us')}</Eyebrow>
          <h2 style={{ marginTop: 18, fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2rem, 5vw, 4.25rem)', fontWeight: 300, lineHeight: 1.02, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)' }}>
            <MaskLine delay={0}><span style={{ fontWeight: 300 }}>{t('Somos profesionales latinos', 'We’re Latino professionals')}</span></MaskLine>
            <MaskLine delay={180}><span style={{ fontWeight: 700 }}>{t('con experiencia global —', 'with global experience —')}</span></MaskLine>
            <MaskLine delay={360}><span style={{ fontWeight: 300, color: 'var(--tcc-on-surface-variant)' }}>{t('liderando equipos y resultados en', 'leading teams and results across')}</span></MaskLine>
            <MaskLine delay={540}><span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>{t('Países Bajos, Inglaterra, USA y México.', 'the Netherlands, England, the USA, and Mexico.')}</span></MaskLine>
          </h2>
        </div>

        {/* Bios */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: 24, marginBottom: 72 }}>
          {bios.map((b, i) => (
            <Reveal key={b.name} delay={i * 150}>
              <div className="bio-card">
                <div className="bio-name">
                  <span className="bio-avatar">{b.initial}</span>
                  <span style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <span>{b.name}</span>
                    {b.role ? (
                      <span style={{ fontFamily: 'var(--tcc-font-mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 400, color: 'var(--tcc-primary)' }}>{b.role}</span>
                    ) : null}
                  </span>
                </div>
                <p style={{ fontFamily: 'var(--tcc-font-body)', fontWeight: 300, fontSize: 15, color: 'var(--tcc-on-surface-variant)', lineHeight: 1.7 }}>{b.body}</p>
              </div>
            </Reveal>
          ))}
        </div>

        {/* Pillars */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 40, marginBottom: 72 }}>
          {pillars.map((x, i) => (
            <Reveal key={x.h} delay={i * 120}>
              <div className="pillar">
                <h4>{x.h}</h4>
                <p>{x.p}</p>
              </div>
            </Reveal>
          ))}
        </div>

        {/* Logo bar */}
        <Reveal>
          <div>
            <div style={{ fontFamily: 'var(--tcc-font-mono)', fontSize: 11, letterSpacing: '0.25em', textTransform: 'uppercase', color: 'var(--tcc-on-surface-dim)', marginBottom: 18, textAlign: 'center' }}>
              {t('Nuestro equipo ha colaborado con', 'Our team has worked with')}
            </div>
            <div className="logo-bar">
              {['Unilever', 'Deloitte', 'AB-InBev', 'Burning Man Project', 'Dale Carnegie Training', 'Koidra', 'Hoogendoorn', 'Tec de Monterrey'].map(n => (
                <span key={n} className="logo-item">{n}</span>
              ))}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { HeroNew, PainPoints, RoadmapServices, WhyUs });
