// 04 — Resultados. Problema → sistema → impacto in one panel of three unequal acts.
// Scroll runs the demonstration instead of describing it.

const CASES = [
  {
    sector: 'Distribución industrial', short: 'Distribución industrial',
    title: 'Propuestas comerciales tardaban casi una semana.',
    problem: 'Precios, histórico del cliente y condiciones comerciales vivían en tres sistemas distintos.',
    metric: '5,5', unit: 'días', metricCap: 'tiempo medio por propuesta',
    agent: ['Agente IA', 'de propuestas'],
    inputs: [['inventory_2', 'Catálogo'], ['history', 'Histórico cliente'], ['rule', 'Reglas de márgenes']],
    outputs: [['verified', 'Aprobación'], ['description', 'Propuesta final']],
    chips: [['psychology', 'Context aware'], ['sell', 'Pricing rules'], ['database', 'CRM history'], ['task_alt', 'Approval engine']],
    delta: 92, deltaLabel: 'ahorro de tiempo',
    before: '5,5 días', after: '4 horas',
    stats: [['trending_up', '48', 'propuestas / mes'], ['check_circle', '0', 'errores de precio en 3 meses']]
  },
  {
    sector: 'Servicios de salud', short: 'Servicios de salud',
    title: 'Siete reuniones semanales para saber cómo iba la operación.',
    problem: 'La información existía en cada sede, pero nadie la tenía junta en el mismo momento.',
    metric: '14', unit: 'h / semana', metricCap: 'coordinación operativa por responsable',
    agent: ['Agente IA', 'de operación'],
    inputs: [['record_voice_over', 'Actas de reunión'], ['monitoring', 'Indicadores por sede'], ['assignment', 'Compromisos']],
    outputs: [['notifications_active', 'Alertas de desvío'], ['summarize', 'Resumen semanal']],
    chips: [['graphic_eq', 'Speech to text'], ['rule_settings', 'Sede rules'], ['person_check', 'Owner tracking'], ['bolt', 'Alerting']],
    delta: 82, deltaLabel: 'menos coordinación',
    before: '14 h / semana', after: '2,5 h / semana',
    stats: [['event_busy', '57', 'reuniones eliminadas / trimestre'], ['schedule', '9 h', 'recuperadas por responsable']]
  }
];

const RS_NODES = { in: [[14, 20], [14, 50], [14, 78]], out: [[85, 35.7], [85, 64.3]] };
const RS_CHIPS = [[26, 5.4], [68, 5.4], [30, 95], [72, 95]];
// node boxes are sized in % of the stage, so these anchors hold at any width:
// input right edge 110, agent 140–260, output left edge 286 (of 400)
const RS_WIRES = ['M110 72C136 72 118 148 140 148', 'M110 180H140', 'M110 281C136 281 118 212 140 212', 'M260 148C284 148 262 128 286 128', 'M260 212C284 212 262 232 286 232'];
const RS_DASH = ['M104 38L152 126', 'M272 38L244 126', 'M120 324L166 234', 'M288 324L254 234'];

function useRsProgress(ref) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setP(1); return; }
    const read = () => {
      const r = el.getBoundingClientRect();
      const raw = (window.innerHeight - r.top) / (window.innerHeight * 0.6 + r.height * 0.55);
      setP(Math.max(0, Math.min(1, raw)));
    };
    read();
    const poll = setInterval(read, 130);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, [ref]);
  return p;
}

function Cases() {
  const [active, setActive] = React.useState(0);
  const panelRef = React.useRef(null);
  const p = useRsProgress(panelRef);
  const c = CASES[active];
  const on = (t) => (p >= t ? 1 : 0);
  const pct = Math.round(c.delta * Math.max(0, Math.min(1, (p - 0.44) / 0.2)));
  return (
    <section className="rs" id="casos">
      <div className="lp-wrap">
        <div className="rs-head">
          <div>
            <span className="eg-eyebrow">04 — Resultados</span>
            <h2 className="rs-h2">Sistemas que cambian cómo opera un negocio.</h2>
            <p className="rs-sub">Diseñamos sistemas que reducen tiempos, errores y dependencia operativa.</p>
          </div>
          <div className="rs-seg">
            {CASES.map((x, i) => (
              <button key={x.sector} type="button" onClick={() => setActive(i)} data-on={i === active ? 1 : 0}>
                {i === active ? <i /> : null}{x.short}
              </button>
            ))}
          </div>
        </div>
        <div className="rs-panel" ref={panelRef}>
          <div className="rs-col">
            <span className="rs-tag">{c.sector}</span>
            <div style={{ marginTop: 26 }}><span className="rs-eyebrow">Problema</span></div>
            <h3 className="rs-title">{c.title}</h3>
            <p className="rs-body">{c.problem}</p>
            <div className="rs-rule" />
            <div className="rs-big" style={{ opacity: on(0.12) ? 1 : 0, transform: on(0.12) ? 'none' : 'translateY(8px)' }}>
              <span className="rs-big-n rs-grad">{c.metric}</span>
              <span className="rs-big-u">{c.unit}</span>
            </div>
            <div className="rs-cap">{c.metricCap}</div>
            <span className="rs-dots" />
          </div>
          <div className="rs-col">
            <span className="rs-eyebrow">Sistema construido</span>
            <div className="rs-diagram" data-nodes={on(0.16)} data-wires={on(0.24)} data-agent={on(0.36)} data-chips={on(0.32)}>
              <svg className="rs-svg" viewBox="0 0 400 360" preserveAspectRatio="none" aria-hidden="true">
                {RS_WIRES.map((d, i) => <path className="rs-wire" key={'w' + i} pathLength="1" d={d} vectorEffect="non-scaling-stroke" style={{ strokeDashoffset: on(0.24) ? 0 : 1, transitionDelay: (i * 90) + 'ms' }} />)}
                {RS_DASH.map((d, i) => <path className="rs-dash" key={'d' + i} d={d} vectorEffect="non-scaling-stroke" style={{ opacity: on(0.32) ? 1 : 0 }} />)}
              </svg>
              {c.inputs.map(([icon, label], i) => (
                <div className="rs-nd" key={label} style={{ left: RS_NODES.in[i][0] + '%', top: RS_NODES.in[i][1] + '%', opacity: on(0.16) ? 1 : 0, transitionDelay: (i * 70) + 'ms' }}>
                  <span className="eg-icon">{icon}</span>{label}
                </div>
              ))}
              <div className="rs-agent" style={{ opacity: on(0.16) ? 1 : 0, boxShadow: on(0.36) ? '0 0 0 1px rgba(62,119,255,.3), 0 0 44px rgba(11,76,250,.5), inset 0 1px 0 rgba(255,255,255,.1)' : 'none' }}>
                <span className="eg-icon">auto_awesome</span>
                <span>{c.agent[0]}<br />{c.agent[1]}</span>
              </div>
              {c.outputs.map(([icon, label], i) => (
                <div className="rs-nd" key={label} style={{ left: RS_NODES.out[i][0] + '%', top: RS_NODES.out[i][1] + '%', opacity: on(0.28) ? 1 : 0, transitionDelay: (140 + i * 70) + 'ms' }}>
                  <span className="eg-icon">{icon}</span>{label}
                </div>
              ))}
              {c.chips.map(([icon, label], i) => (
                <div className="rs-chip" key={label} style={{ left: RS_CHIPS[i][0] + '%', top: RS_CHIPS[i][1] + '%', opacity: on(0.32) ? 1 : 0, transitionDelay: (i * 90) + 'ms' }}>
                  <span className="eg-icon">{icon}</span>{label}
                </div>
              ))}
            </div>
          </div>
          <div className="rs-col rs-impact" data-on={on(0.5)}>
            <span className="rs-eyebrow">Impacto</span>
            <div className="rs-fig rs-grad">{pct}%</div>
            <div className="rs-fig-l">{c.deltaLabel}</div>
            <div className="rs-ba">
              <div className="rs-ba-before">
                <div className="rs-ba-v">{c.before}</div>
                <div className="rs-ba-k">Antes</div>
              </div>
              <span className="rs-arrow" style={{ transform: on(0.56) ? 'none' : 'scaleX(0)' }} />
              <div className="rs-ba-after">
                <div className="rs-ba-v">{c.after}</div>
                <div className="rs-ba-k">Después</div>
              </div>
            </div>
            <div className="rs-stats">
              {c.stats.map(([icon, n, l], i) => (
                <div className="rs-stat" key={l} style={{ opacity: on(0.6) ? 1 : 0, transform: on(0.6) ? 'none' : 'translateY(8px)', transitionDelay: (i * 110) + 'ms' }}>
                  <span className="rs-stat-ic"><span className="eg-icon" style={{ fontSize: 17 }}>{icon}</span></span>
                  <span className="rs-stat-n">{n}</span>
                  <span className="rs-stat-l">{l}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="rs-foot">
          <a className="rs-cta" href="#contacto">Explorar cómo lo construimos<span className="eg-icon">arrow_forward</span></a>
          <span className="rs-nda"><span className="eg-icon">shield</span>bajo NDA · datos normalizados</span>
        </div>
      </div>
    </section>
  );
}

// 05 — Alcance. Nine deliverables as modules of one system, not a service table.
// Scroll walks them in order: the counter climbs to 09 and the bar fills with it.
const CAPS = [
  ['smart_toy', 'AI Agents', 'Agentes autónomos que ejecutan trabajo y entregan resultados.'],
  ['handyman', 'Internal Tools', 'Herramientas propias que ordenan el trabajo del equipo.'],
  ['account_tree', 'Workflow Automation', 'Automatizaciones de punta a punta que eliminan pasos manuales.'],
  ['link', 'Integrations', 'Sistemas, APIs y fuentes de datos conectados entre sí.'],
  ['monitoring', 'Dashboards', 'Paneles en tiempo real que muestran lo que importa.'],
  ['menu_book', 'Knowledge Systems', 'Conocimiento ordenado que la IA puede consultar y razonar.'],
  ['support_agent', 'AI Assistants', 'Asistentes conversacionales con el contexto de tu dominio.'],
  ['insights', 'Business Intelligence', 'Datos convertidos en decisiones, no en informes.'],
  ['auto_awesome', 'Process Optimization', 'Detección de cuellos de botella y mejora continua del flujo.']
];

// The walkthrough writes the DOM directly instead of through state: nine cards, a
// counter and a bar updated on one poll, so no re-render work per scroll frame.
function Capabilities() {
  const secRef = React.useRef(null);
  React.useEffect(() => {
    const sec = secRef.current;
    if (!sec) return;
    const cards = Array.prototype.slice.call(sec.querySelectorAll('.sc-card'));
    const fill = sec.querySelector('.sc-rule i');
    const num = sec.querySelector('.sc-note i');
    const apply = (t) => {
      const cur = Math.min(8, Math.floor(t * 9));
      const reached = t > 0.004 ? cur : -1;
      fill.style.width = (t * 100).toFixed(1) + '%';
      num.textContent = String(Math.max(1, reached + 1)).padStart(2, '0');
      cards.forEach((c, i) => {
        c.setAttribute('data-state', i === reached ? 'cur' : i < reached ? 'on' : 'off');
        c.style.opacity = i <= reached ? '1' : '0.32';
        c.style.transform = i <= reached ? 'none' : 'translateY(6px)';
      });
    };
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { apply(1); return; }
    // The stage is pinned while the walk runs, so progress is the scroll travelled
    // through the tall container behind it — the viewer stands still and watches.
    const track = sec.querySelector('.sc-scroll');
    const read = () => {
      const r = track.getBoundingClientRect();
      const span = r.height - window.innerHeight;
      if (span <= 0) { apply(1); return; }
      apply(Math.max(0, Math.min(1, -r.top / span)));
    };
    read();
    const poll = setInterval(read, 110);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, []);
  return (
    <section className="sc" id="ia" ref={secRef}>
      <div className="sc-scroll"><div className="sc-stick">
      <div className="lp-wrap sc-grid">
        <div>
          <span className="eg-eyebrow">05 — Alcance</span>
          <h2 className="sc-h2">Construimos sistemas, no demos de IA.</h2>
          <p className="sc-body">
            Diseñamos y construimos sistemas de IA que operan en tu negocio: plataformas
            internas, automatizaciones y datos conectados que generan impacto real.
          </p>
          <div className="sc-rule"><i /></div>
          <div className="sc-note"><i>01</i>Un proyecto suele combinar 2–4 capacidades.</div>
        </div>
        <div className="sc-panel">
          <svg className="sc-net" viewBox="0 0 760 420" preserveAspectRatio="none" aria-hidden="true">
            <path d="M40 96H188V214H40" vectorEffect="non-scaling-stroke" />
            <path d="M188 96H380V38" vectorEffect="non-scaling-stroke" />
            <path d="M380 214H560V330H380" vectorEffect="non-scaling-stroke" />
            <path d="M188 330H300V214" vectorEffect="non-scaling-stroke" />
            <path d="M560 96V150H700V330" vectorEffect="non-scaling-stroke" />
            <circle cx="188" cy="96" r="2.5" /><circle cx="380" cy="214" r="2.5" />
            <circle cx="560" cy="330" r="2.5" /><circle cx="300" cy="214" r="2.5" />
            <circle cx="700" cy="150" r="2.5" /><circle cx="40" cy="214" r="2.5" />
          </svg>
          <div className="sc-head">
            <span className="sc-comb">Systems are combinable<span className="eg-icon">north_east</span></span>
          </div>
          <div className="sc-cards">
            {CAPS.map(([icon, title, desc]) => (
              <div className="sc-card" key={title} data-state="off" style={{ opacity: 0.32, transform: 'translateY(6px)' }}>
                <span className="sc-ic"><span className="eg-icon">{icon}</span></span>
                <div>
                  <h3 className="sc-t">{title}</h3>
                  <p className="sc-d">{desc}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      </div></div>
    </section>
  );
}

// 06 — Stack. Five layers of one architecture on a data spine, not a table of logos.
// Every tool is one we work with: the scroll lights the layers, never singles out
// tools. Fuchsia is scoped to this section — the rest of the page stays ion blue.
const STACK = [
  ['layers', 'Modelos', ['OpenAI', 'Anthropic', 'Google Vertex', 'Modelos locales']],
  ['bolt', 'Automatización', ['n8n', 'Temporal', 'Zapier', 'Funciones propias']],
  ['database', 'Datos', ['Postgres', 'BigQuery', 'Supabase', 'Pinecone']],
  ['code_blocks', 'Producto', ['React', 'Next.js', 'TypeScript', 'Tailwind']],
  ['cloud', 'Infraestructura', ['AWS', 'Vercel', 'Docker', 'Cloudflare']]
];

function Stack() {
  const secRef = React.useRef(null);
  React.useEffect(() => {
    const sec = secRef.current;
    if (!sec) return;
    const rows = Array.prototype.slice.call(sec.querySelectorAll('.st-row'));
    const fill = sec.querySelector('.st-fill');
    const flare = sec.querySelector('.st-flare');
    const apply = (t) => {
      const lit = Math.min(rows.length, Math.floor(t * (rows.length + 0.4)));
      fill.style.transform = 'scaleY(' + Math.max(0, Math.min(1, t * 1.06)).toFixed(3) + ')';
      flare.style.opacity = t > 0.92 ? '1' : '0';
      rows.forEach((r, i) => r.setAttribute('data-on', i < lit ? 1 : 0));
    };
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { apply(1); return; }
    const panel = sec.querySelector('.st-panel');
    const read = () => {
      const r = panel.getBoundingClientRect();
      const vh = window.innerHeight;
      const from = vh * 0.9;
      const to = vh * 0.42 - r.height;
      apply(Math.max(0, Math.min(1, (from - r.top) / Math.max(1, from - to))));
    };
    read();
    const poll = setInterval(read, 110);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, []);
  return (
    <section className="st" id="desarrollo" ref={secRef}>
      <div className="lp-wrap">
        <span className="eg-eyebrow">06 — Stack</span>
        <h2 className="st-h2">Herramientas elegidas por encaje,<br />no por moda</h2>
        <p className="st-sub">Diseñamos la arquitectura alrededor del problema. No obligamos al problema a adaptarse a una herramienta.</p>
        <div className="st-panel">
          <span className="st-spine" />
          <span className="st-fill" />
          <span className="st-flare" />
          {STACK.map(([icon, layer, chips]) => (
            <div className="st-row" key={layer} data-on="0">
              <span className="st-ic"><span className="eg-icon">{icon}</span></span>
              <span className="st-label">{layer}</span>
              <span className="st-node"><i /></span>
              <div className="st-chips">
                {chips.map(name => (
                  <span className="st-chip" key={name}><i />{name}</span>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div className="st-agn">
          <span className="st-agn-ic"><span className="eg-icon">layers</span></span>
          <div>
            <span className="st-agn-eyebrow">Stack-agnostic</span>
            <h3 className="st-agn-t">Tu infraestructura no tiene que adaptarse a nosotros.</h3>
            <p className="st-agn-d">Nosotros nos adaptamos a la arquitectura que ya funciona.</p>
          </div>
          <span className="st-agn-dots" />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Cases, Capabilities, Stack });
