/** The Conscious Code — premium-sections.jsx
 *
 * Refactor of Hero / Services / CTA + a new Stats section, applying the
 * Kinetic Luxe principles from skills/premium-design/:
 *   • Typography is the protagonist (mask reveals, italic accents, bigger scale)
 *   • Motion intentional, scroll-driven (1.2–1.4s easeOutExpo)
 *   • One signature motion per section
 *   • Composition breaks the grid (asymmetric splits, scale contrast)
 *
 * The brand palette stays — cyan #00ffcc on Void #0c141f. Only the
 * aesthetic *technique* is borrowed.
 */

const { useEffect, useRef, useState } = React;

/* ───────────────────────────────────────────────  MaskLine helper
 * Wraps a single line of text in overflow-hidden; child translates 110%→0
 * once the line scrolls into view. Pure CSS transition; classes in site.css.
 */
function MaskLine({ children, delay = 0 }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setTimeout(() => el.classList.add('visible'), delay);
        obs.disconnect();
      }
    }, { threshold: 0.2 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <span ref={ref} className="mask-line">
      <span className="mask-inner">{children}</span>
    </span>
  );
}

/* ─────────────────────────────────────────────────  HeroPremium
 * Same scrollytelling mechanic as before, but the headline is rebuilt
 * as a three-line mask reveal with an italic accent on "rentabilidad".
 */
function HeroPremium() {
  const containerRef = useRef(null);
  const headerRef    = useRef(null);
  const cubeRef      = useRef(null);
  const hintRef      = useRef(null);
  const asteriskRef  = useRef(null);

  useEffect(() => {
    let rafId, inView = true;
    const io = new IntersectionObserver(([e]) => { inView = e.isIntersecting; }, { threshold: 0 });
    if (containerRef.current) io.observe(containerRef.current);

    const tick = () => {
      const el = containerRef.current;
      if (el && inView) {
        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 = `translateY(${-100 * headerProg}px)`;
        }
        if (hintRef.current) hintRef.current.style.opacity = String(1 - headerProg);
        if (cubeRef.current) {
          const y = -160 * p + 80;
          const 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 = `translate(-50%, ${y}px) rotate(${rot}deg)`;
          cubeRef.current.style.opacity = String(o);
        }
        if (asteriskRef.current) {
          const blur = 10 + p * 32;
          const a = Math.min(1, 0.6 + p * 0.4);
          asteriskRef.current.style.textShadow = `0 0 ${blur}px rgba(0,255,213,${a})`;
          asteriskRef.current.style.filter = `drop-shadow(0 0 ${blur}px rgba(0,255,213,${a}))`;
        }
      }
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(rafId); 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">
            {/* Asymmetric kicker — left-aligned mono, not centered chip */}
            <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 }}>
                · Manifiesto 2026 · Estrategia &amp; Arquitectura de IA ·
              </span>
              <span style={{ display: 'inline-block', width: 32, height: 1, background: 'var(--tcc-primary)' }} />
            </div>

            <h1 style={{
              fontFamily: 'var(--tcc-font-display)',
              fontSize: 'clamp(2.75rem, 8vw, 8rem)',
              lineHeight: 0.95,
              letterSpacing: '-0.035em',
              maxWidth: '14ch',
              margin: '0 auto',
              textAlign: 'center',
              color: 'var(--tcc-on-surface)',
              fontWeight: 300,
            }}>
              <MaskLine delay={0}>
                <span style={{ fontWeight: 300 }}>Tu puente entre el</span>
              </MaskLine>
              <MaskLine delay={200}>
                <span style={{ fontWeight: 700 }}>código y la</span>
              </MaskLine>
              <MaskLine delay={400}>
                <span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>rentabilidad.</span>
              </MaskLine>
            </h1>

            <p className="lead" style={{ marginTop: 48, maxWidth: 560, marginInline: 'auto', textAlign: 'center', fontSize: 19, fontWeight: 300 }}>
              Para empresas familiares y PyMEs que rechazan la memoria tribal. Transformamos el caos de datos en un ecosistema asistido por AI — <em style={{ fontStyle: 'italic', color: 'var(--tcc-on-surface)' }}>blindado, auditable, escalable</em>.
            </p>

            <div style={{ marginTop: 56, display: 'flex', justifyContent: 'center', gap: 20, flexWrap: 'wrap', alignItems: 'center' }}>
              <PrimaryButton onClick={() => document.getElementById('contacto').scrollIntoView()}>
                Agendar Auditoría Clínica
              </PrimaryButton>
              <a className="moment-link" onClick={(e) => { e.preventDefault(); document.getElementById('servicios').scrollIntoView(); }}>
                Explorar Servicios
              </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' }}>Explorar</span>
          <div style={{ width: 1, height: 48, background: 'linear-gradient(to bottom, rgba(0,255,204,0.4), transparent)' }} />
        </div>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────  ServicesPremium · Editorial Index
 * Numbered rows + hairline dividers, ONE spotlight row with inverted treatment.
 */
function ServicesPremium() {
  const services = [
    { num: '01', title: 'Blueprint Digital',          desc: 'Auditoría y mapa financiero para priorizar el ROI antes de programar una sola línea de código.', cap: 'Semanas 1–3' },
    { num: '02', title: 'Gobernanza de Datos',        desc: 'Arquitectura auditable bajo estándares europeos (GDPR), lista para la orquestación de IA.',        cap: 'Semanas 2–5' },
    { num: '03', title: 'Desarrollo & Agentes',       desc: 'Aplicaciones y arquitecturas de datos de alto rendimiento, orquestadas por agentes autónomos y blindadas con MCP.', cap: 'Mes 2 en adelante', spotlight: true, ext: 'Sistemas propietarios diseñados para el despliegue seguro de agentes en entornos B2B. Reemplazamos la memoria tribal por conocimiento institucional auditable.' },
    { num: '04', title: 'Bóvedas de Conocimiento',    desc: 'Rescate del conocimiento fragmentado en un "Knowledge Hub" institucional seguro y accesible.',    cap: 'Mes 3' },
    { num: '05', title: 'Talleres Funcionales',       desc: 'Entrenamiento operativo para el equipo directivo sobre el uso estratégico de la IA.',             cap: 'Continuo' },
    { num: '06', title: 'Dirección Estratégica',      desc: 'Liderazgo tecnológico continuo y auditoría de modelos para asegurar la escalabilidad a largo plazo.', cap: 'Anual' },
  ];
  return (
    <section id="servicios" className="section bg-low">
      <div className="container">
        {/* Asymmetric header: kicker left (cols 1-4), heading right (cols 5-12) */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 32, marginBottom: 96 }}>
          <div style={{ gridColumn: 'span 4' }}>
            <Eyebrow>Portafolio · Fases I & II</Eyebrow>
            <p style={{ fontFamily: 'var(--tcc-font-body)', fontWeight: 300, fontSize: 15, color: 'var(--tcc-on-surface-variant)', lineHeight: 1.6, maxWidth: 28, marginTop: 16 }}>
              Resultados tangibles, entregados por fases auditables. Cada módulo se contrata y mide por separado.
            </p>
          </div>
          <h2 style={{ gridColumn: 'span 8', fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2.5rem, 6vw, 5.5rem)', fontWeight: 300, lineHeight: 0.98, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)' }}>
            <MaskLine delay={0}>
              <span style={{ fontWeight: 300 }}>Arquitectura</span>
            </MaskLine>
            <MaskLine delay={200}>
              <span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>modular,</span>{' '}
              <span style={{ fontWeight: 700 }}>implementación</span>
            </MaskLine>
            <MaskLine delay={400}>
              <span style={{ fontWeight: 300, color: 'var(--tcc-on-surface-variant)' }}>progresiva.</span>
            </MaskLine>
          </h2>
        </div>

        {/* Editorial index */}
        <div>
          {services.map((s, i) => {
            if (s.spotlight) {
              return (
                <Reveal key={s.num} delay={i * 60}>
                  <div className="idx-spotlight">
                    <div>
                      <div className="idx-num">{s.num}</div>
                      <div className="idx-cap-italic">{s.cap}</div>
                    </div>
                    <div className="sp-body">
                      <h3 className="sp-title">
                        {s.title.split(' & ')[0]} <span className="accent-italic">&amp;</span> {s.title.split(' & ')[1]}
                      </h3>
                      <p className="sp-desc">{s.desc}</p>
                      {s.ext && <p className="sp-desc" style={{ opacity: 0.75 }}>{s.ext}</p>}
                      <a className="sp-link" onClick={(e) => { e.preventDefault(); document.getElementById('contacto')?.scrollIntoView(); }}>
                        Solicitar caso de uso
                      </a>
                    </div>
                  </div>
                </Reveal>
              );
            }
            return (
              <Reveal key={s.num} delay={i * 60}>
                <div className="idx-row">
                  <span className="idx-num">{s.num}</span>
                  <span className="idx-title">{s.title}</span>
                  <span className="idx-desc">{s.desc}</span>
                  <span className="idx-cap">{s.cap}</span>
                </div>
              </Reveal>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────  StatsPremium · Editorial Numbers
 * 4-cell asymmetric grid with scroll-triggered counter animations.
 */
function CounterNumber({ to, prefix = '', suffix = '', duration = 1800, decimals = 0 }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      obs.disconnect();
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        el.textContent = prefix + to.toFixed(decimals) + suffix;
        return;
      }
      const start = performance.now();
      const ease = (t) => 1 - Math.pow(2, -10 * t); // easeOutExpo-ish
      const step = (now) => {
        const t = Math.min(1, (now - start) / duration);
        const v = to * ease(t);
        el.textContent = prefix + v.toFixed(decimals) + suffix;
        if (t < 1) requestAnimationFrame(step);
      };
      requestAnimationFrame(step);
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [to, prefix, suffix, duration, decimals]);
  return <span ref={ref}>{prefix}0{suffix}</span>;
}

function StatsPremium() {
  return (
    <section className="section bg-low" style={{ borderTop: '1px solid var(--tcc-outline-variant)' }}>
      <div className="container">
        {/* Header — left kicker, right small line */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 32, marginBottom: 80, alignItems: 'end' }}>
          <div style={{ gridColumn: 'span 5' }}>
            <Eyebrow>Impacto Operativo · 2024–2026</Eyebrow>
            <h2 style={{ marginTop: 16, fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2rem, 4.2vw, 3.75rem)', fontWeight: 300, lineHeight: 0.98, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)' }}>
              <MaskLine delay={0}>
                <span>El rigor institucional,</span>
              </MaskLine>
              <MaskLine delay={200}>
                <span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>cuantificado.</span>
              </MaskLine>
            </h2>
          </div>
          <p style={{ gridColumn: 'span 5 / span 5', fontFamily: 'var(--tcc-font-body)', fontWeight: 300, fontSize: 15, color: 'var(--tcc-on-surface-variant)', lineHeight: 1.6, maxWidth: 42 }}>
            Métricas agregadas a través de nuestro portafolio de implementaciones en empresas familiares y PyMEs.
          </p>
        </div>

        <Reveal>
          <div className="stats-grid">
            <div className="stat-cell">
              <div className="stat-label">Reducción en tiempo</div>
              <div className="stat-num">
                <CounterNumber to={62} suffix="" />
                <span className="suf">%</span>
              </div>
              <div className="stat-cap">por feature, vs. desarrollo tradicional con equipo interno.</div>
            </div>
            <div className="stat-cell">
              <div className="stat-label">Latencia en producción</div>
              <div className="stat-num">
                &lt;<CounterNumber to={200} suffix="" />
                <span className="suf">ms</span>
              </div>
              <div className="stat-cap">respuesta promedio de la capa cognitiva orquestada.</div>
            </div>
            <div className="stat-cell">
              <div className="stat-label">Flujos automatizados</div>
              <div className="stat-num">
                <CounterNumber to={14} />
              </div>
              <div className="stat-cap">procesos críticos auditables, monitorizados 24/7.</div>
            </div>
            <div className="stat-cell">
              <div className="stat-label">GDPR by-design</div>
              <div className="stat-num">
                <CounterNumber to={100} />
                <span className="suf">%</span>
              </div>
              <div className="stat-cap">desde el primer commit. Sin remediación posterior.</div>
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ─────────────────────────────────────────────────  CtaPremium · Moment CTA
 * Full-viewport closing moment. Multi-line headline, italic accent on the last line,
 * giant decorative `*` clipped bottom-right, availability signature.
 */
function CtaPremium() {
  return (
    <section id="contacto" className="moment-cta" style={{ borderTop: '1px solid var(--tcc-outline-variant)' }}>
      <span className="moment-glyph">*</span>
      <div className="container" style={{ position: 'relative', zIndex: 2, maxWidth: 1280 }}>
        {/* Header rail */}
        <div style={{ marginBottom: 64, display: 'flex', alignItems: 'center', gap: 14 }}>
          <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 }}>
            Modelo de inversión · 40 / 40 / 20
          </span>
        </div>

        <h2 className="moment-headline" style={{ maxWidth: '14ch' }}>
          <MaskLine delay={0}>
            <span className="l1">Si tu negocio merece</span>
          </MaskLine>
          <MaskLine delay={180}>
            <span className="l2">una arquitectura</span>
          </MaskLine>
          <MaskLine delay={360}>
            <span className="l3">consciente, comencemos.</span>
          </MaskLine>
        </h2>

        <div className="moment-actions">
          <PrimaryButton>
            Reservar Auditoría
            <span style={{ width: 18, height: 18 }}><Icon.ChevronRight /></span>
          </PrimaryButton>
          <a href="mailto:eduardo@the-conscious-code.com" className="moment-link">
            eduardo@the-conscious-code.com
          </a>
        </div>

        {/* 40/40/20 — small print, three columns */}
        <div style={{
          marginTop: 96, paddingTop: 40,
          borderTop: '1px solid var(--tcc-outline-variant)',
          display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
          gap: 32, maxWidth: 760,
        }}>
          {[
            { p: '40% Inicio',          d: 'Compromiso y arranque de arquitectura.' },
            { p: '40% Infraestructura', d: 'Entrega de cimientos y gobernanza.' },
            { p: '20% Validación',      d: 'Cierre y despliegue final de agentes.' },
          ].map((x) => (
            <div key={x.p}>
              <h4 style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--tcc-primary)', letterSpacing: '0.25em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 8 }}>{x.p}</h4>
              <p style={{ fontFamily: 'var(--tcc-font-body)', fontStyle: 'italic', fontSize: 13, color: 'var(--tcc-on-surface-variant)', fontWeight: 300 }}>{x.d}</p>
            </div>
          ))}
        </div>
      </div>

      <div className="moment-sig">
        <div className="sig-avail">Disponibilidad · Q3 2026</div>
        <div className="sig-status">dos engagements restantes</div>
      </div>
    </section>
  );
}

Object.assign(window, {
  HeroPremium, ServicesPremium, StatsPremium, CtaPremium,
  MaskLine, CounterNumber,
});
