// Problem → Solutions → Method. The method section is the one light-themed band
// in the page: the narrative shifts from diagnosis to process.

const DIAG_NODES = [
  ['description', 'Cotizaciones', '14 min/op', 'Manual', 0],
  ['person', 'Aprobaciones', '3.2 días', 'Cuello de botella', 1],
  ['bar_chart', 'Reportes', '8 h/semana', 'Repetitivo', 0]
];

// Scroll drives three stages: the operation reads as normal, its findings surface,
// then the paths converge and the recoverable margin resolves.
function useDiagStage(ref) {
  const [stage, setStage] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setStage(3); return; }
    const read = () => {
      const r = el.getBoundingClientRect();
      const p = (window.innerHeight - r.top) / (window.innerHeight * 0.7 + r.height * 0.4);
      setStage(p < 0.3 ? 0 : p < 0.52 ? 1 : p < 0.74 ? 2 : 3);
    };
    read();
    // A poll backs the scroll listener up: some embedded contexts freeze scroll
    // and rAF callbacks, and the section must never sit half-drawn.
    const poll = setInterval(read, 140);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, [ref]);
  return stage;
}

function Problem() {
  const treeRef = React.useRef(null);
  const stage = useDiagStage(treeRef);
  return (
    <section className="lp-section lp-diag-section" id="problema">
      <div className="lp-wrap">
        <div className="lp-diag">
          <div className="lp-diag-left">
            <span className="eg-eyebrow">01 — Diagnóstico</span>
            <h2 className="lp-h2" style={{ marginTop: 18 }}>Dónde se pierde el margen</h2>
            <p className="lp-sub">
              El margen rara vez se pierde por falta de esfuerzo. Se pierde en procesos
              manuales, decisiones lentas y operaciones que crecieron sin rediseñarse.
            </p>
            <div className="lp-diag-note">
              <span>↓</span>
              <span>Detectamos las fugas antes de automatizar.</span>
            </div>
          </div>
          <div className="lp-diag-right">
            <span className="lp-diag-axis" />
            <div className="lp-tree reveal" ref={treeRef} data-leaks={stage >= 1 ? 'on' : 'off'} data-bus={stage >= 2 ? 'on' : 'off'} data-out={stage >= 3 ? 'on' : 'off'}>
              <div className="lp-node lp-node--root">
                <span className="lp-node-icon"><span className="eg-icon" style={{ fontSize: 22 }}>layers</span></span>
                <div>
                  <div className="lp-node-title">Operación actual</div>
                  <div className="lp-node-sub">47 procesos activos</div>
                </div>
                <span className="lp-jd lp-jd--bottom" />
              </div>
              <svg className="lp-tree-svg" viewBox="0 0 1000 78" preserveAspectRatio="none" aria-hidden="true">
                <path d="M500 0V78" vectorEffect="non-scaling-stroke" />
                <path d="M500 26H168.67Q158.67 26 158.67 36V78" vectorEffect="non-scaling-stroke" />
                <path d="M500 26H831.33Q841.33 26 841.33 36V78" vectorEffect="non-scaling-stroke" />
              </svg>
              <div className="lp-tree-row">
                {DIAG_NODES.map(([icon, name, metric, chip, hot]) => (
                  <div className="lp-node lp-node--proc" key={name}>
                    <div className="lp-node-row">
                      <span className="lp-node-icon"><span className="eg-icon" style={{ fontSize: 20 }}>{icon}</span></span>
                      <div>
                        <div className="lp-node-title">{name}</div>
                        <div className="lp-node-metric">{metric}</div>
                      </div>
                    </div>
                    <span className={'lp-chip' + (hot ? ' lp-chip--hot' : '')}>{chip}</span>
                    <span className="lp-jd lp-jd--top" />
                  </div>
                ))}
              </div>
              <svg className="lp-tree-svg lp-tree-svg--down" viewBox="0 0 1000 78" preserveAspectRatio="none" aria-hidden="true">
                <path className="lp-flow" pathLength="1" d="M500 0V78" vectorEffect="non-scaling-stroke" />
                <path className="lp-flow" pathLength="1" d="M158.67 0V42Q158.67 52 168.67 52H500" vectorEffect="non-scaling-stroke" />
                <path className="lp-flow" pathLength="1" d="M841.33 0V42Q841.33 52 831.33 52H500" vectorEffect="non-scaling-stroke" />
              </svg>
              <div className="lp-node lp-node--out">
                <span className="lp-ring"><span className="eg-icon" style={{ fontSize: 26 }}>trending_up</span></span>
                <div>
                  <div className="lp-out-label">Margen recuperable</div>
                  <div className="lp-out-figure">+21%</div>
                  <div className="lp-out-cap">mediante automatización</div>
                </div>
                <span className="lp-jd lp-jd--top" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const LAYERS = [
  ['05', 'Software', 'paneles · portales', 'code_blocks'],
  ['04', 'Automatización', 'flujos · reglas', 'bolt'],
  ['03', 'IA aplicada', 'agentes · decisiones', 'auto_awesome'],
  ['02', 'Integraciones', 'ERP · CRM · APIs', 'hub'],
  ['01', 'Data', 'fuentes · contexto', 'database']
];

// Scroll progress across the stack: the pile builds from the data layer up and
// spreads a few pixels as it passes, which is where the depth reads from.
function useScrollProgress(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.65 + r.height * 0.6);
      setP(Math.max(0, Math.min(1, raw)));
    };
    read();
    const poll = setInterval(read, 140);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, [ref]);
  return p;
}

// Progress measured against a tall track behind a pinned stage: the viewer stops,
// the stack builds, and the next section stays off screen until it is done.
function useTrackProgress(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 span = r.height - window.innerHeight;
      setP(span <= 0 ? 1 : Math.max(0, Math.min(1, -r.top / span)));
    };
    read();
    const poll = setInterval(read, 120);
    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 Solutions() {
  const { Badge } = window.EG;
  const trackRef = React.useRef(null);
  const p = useTrackProgress(trackRef);
  const shown = [0.06, 0.2, 0.34, 0.48, 0.62].filter(t => p >= t).length;
  const spread = (p - 0.5) * 2;
  return (
    <section className="lp-cap-section" id="soluciones">
      <div className="lp-cap-scroll" ref={trackRef}><div className="lp-cap-stick">
      <div className="lp-wrap">
        <div className="lp-cap-head">
          <div>
            <span className="eg-eyebrow">02 — Capacidades</span>
            <h2 className="lp-h2" style={{ marginTop: 16 }}>Cinco capas que se implementan juntas</h2>
          </div>
          <p className="lp-sub" style={{ marginTop: 6 }}>
            Rara vez el problema es sólo un modelo o sólo una integración. La mayoría de
            proyectos toca tres de estas cinco capas.
          </p>
        </div>
        <div className="lp-cap-body">
          <div className="lp-cap-aside">
            <div className="lp-cap-note"><b>Parallax</b>Profundidad que se revela al hacer scroll.</div>
          </div>
          <div className="lp-stack">
            {LAYERS.map(([num, name, sub, icon], i) => {
              const depth = 2 - i;
              const on = shown > (4 - i);
              return (
                <div className="lp-layer" key={num} data-on={on ? 1 : 0}
                  style={{ '--i': i, transform: 'translateY(' + ((on ? 0 : 44) + depth * spread * 7).toFixed(1) + 'px) scale(' + (on ? 1 : 0.965) + ')' }}>
                  <div className="lp-layer-label">
                    <span className="lp-layer-num">{num}</span>
                    <div>
                      <div className="lp-layer-name">{name}</div>
                      <div className="lp-layer-sub">{sub}</div>
                    </div>
                  </div>
                  <span className="lp-layer-line" />
                  <div className="lp-layer-plate">
                    <img src="../../assets/layer-plate.png" alt="" />
                    <span className="eg-icon lp-layer-icon">{icon}</span>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="lp-cap-side">
            <div className="lp-cap-note"><b>Scroll build</b>Cada capa aparece progresivamente al hacer scroll.</div>
            <div className="lp-cap-chevrons">
              <span className="eg-icon">keyboard_arrow_up</span>
              <span className="eg-icon">keyboard_arrow_up</span>
              <span className="eg-icon">keyboard_arrow_up</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '22px 20px 24px', borderRadius: 'var(--radius-lg)', border: '1px dashed var(--border-default)' }}>
              <Badge tone="neutral" variant="outline">Siguiente</Badge>
              <p style={{ font: 'var(--type-body-sm)', color: 'var(--text-secondary)' }}>
                El alcance se define después del diagnóstico, no antes.
              </p>
              <a href="#metodologia" style={{ font: 'var(--type-caption)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                Ver metodología <span className="eg-icon eg-icon--sm">arrow_forward</span>
              </a>
            </div>
          </div>
        </div>
      </div>
      </div></div>
    </section>
  );
}

// 03 — Metodología. The render is cut into six equal panels hinged on their left
// edge: scroll unfolds the brochure crease by crease, left to right. Each station
// sits on its own panel, so a label only appears once its panel lies flat.
const METHOD_STEPS = [
  ['01', 'Entendemos', 'Proceso · personas · excepciones', 'Mapeamos el proceso real, no el documentado. Personas, herramientas, tiempos y excepciones.', 9.4, 55.5],
  ['02', 'Diseñamos', 'Flujos · decisiones · interfaces', 'Definimos qué se automatiza, qué asiste un agente y qué sigue siendo decisión humana.', 26.9, 48.5],
  ['03', 'Construimos', 'Integraciones · IA · agentes', 'Implementación por incrementos: cada semana algo entra en uso real.', 40.6, 40.8],
  ['04', 'Implementamos', 'Equipo · formación · operación', 'Despliegue con el equipo dentro. Formación corta y documentación viva.', 52.9, 31.5],
  ['05', 'Medimos', 'Tiempo · coste · errores', 'Tiempo, coste y errores antes y después. Sin métricas no hay proyecto.', 70.1, 30.2],
  ['06', 'Optimizamos', 'Uso · aprendizaje · mejora', 'El sistema se ajusta con uso. Lo que no aporta se retira.', 84.6, 27.8]
];
const LEADS = ['M350 596L452 646', 'M622 528L716 556', 'M851 456L926 470', 'M1056 366L1146 412', 'M1324 354L1372 384', 'M1474 306L1506 350'];
// The fold: panel 00 is the cover and stays flat; the five creases after it open in
// sequence. GATHER is how much width a still-folded crease takes out of the spread,
// so the closed panels huddle against the last open one instead of floating apart.
const PANELS = 6;
// exact cuts of the 1672×941 render into six panels (assets/method/panel-N.png)
const PANEL_X = [0, 16.6866, 33.3134, 50, 66.6866, 83.3134];
const PANEL_W = [16.6866, 16.6268, 16.6866, 16.6866, 16.6268, 16.6866];
const FOLD_AT = [0, 0.06, 0.20, 0.34, 0.48, 0.62];
const FOLD_DUR = 0.17;
const GATHER = 13.2;
const FOLD_DEG = 78;
const easeFold = t => 1 - Math.pow(1 - t, 3);

function Method() {
  const scrollRef = React.useRef(null);
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setP(1); return; }
    const read = () => {
      const r = el.getBoundingClientRect();
      const total = r.height - window.innerHeight;
      setP(total > 0 ? Math.max(0, Math.min(1, -r.top / total)) : 1);
    };
    read();
    const poll = setInterval(read, 120);
    window.addEventListener('scroll', read, { passive: true });
    window.addEventListener('resize', read);
    return () => { clearInterval(poll); window.removeEventListener('scroll', read); window.removeEventListener('resize', read); };
  }, []);
  // Per-panel open amount, then the running gather of everything still folded.
  const open = FOLD_AT.map((s, i) => (i === 0 ? 1 : easeFold(Math.max(0, Math.min(1, (p - s) / FOLD_DUR)))));
  const shift = [];
  for (let i = 0, acc = 0; i < PANELS; i++) { shift.push(acc); acc += (1 - open[i]) * GATHER; }
  const active = open.reduce((a, o, i) => (o > 0.75 ? i : a), 0);
  const done = p >= 0.86;
  return (
    <section className="mt" id="metodologia" data-theme="light">
      <div className="mt-scroll" ref={scrollRef}>
        <div className="mt-sticky">
          <div className="mt-canvas">
            <div className="mt-flow"><img src="../../assets/method/path-full.png" alt="Recorrido de la metodología en seis estaciones" /></div>
            <div className="mt-fold">
              {open.map((o, i) => {
                const folded = 1 - o;
                const deg = (i % 2 ? -1 : 1) * FOLD_DEG * folded;
                return (
                  <div className="mt-panel" key={i} data-dir={i % 2 ? 'a' : 'b'}
                    style={{
                      left: (PANEL_X[i] - shift[i]).toFixed(3) + '%',
                      width: PANEL_W[i] + '%',
                      transform: 'rotateY(' + deg.toFixed(2) + 'deg) scaleX(1.002)',
                      boxShadow: '0 ' + (folded * 26).toFixed(1) + 'px ' + (folded * 46).toFixed(1) + 'px -18px rgba(8, 11, 16, ' + (folded * 0.34).toFixed(3) + ')'
                    }}>
                    <span className="mt-face"><img src={'../../assets/method/panel-' + (i + 1) + '.png'} alt="" /></span>
                    <span className="mt-shade" style={{ opacity: folded.toFixed(3) }} />
                    <span className="mt-crease" style={{ opacity: (folded * 0.9).toFixed(3) }} />
                  </div>
                );
              })}
            </div>
            <svg className="mt-leads" viewBox="0 0 1672 941" preserveAspectRatio="none" aria-hidden="true">
              {LEADS.map((d, i) => (
                <path key={i} d={d} vectorEffect="non-scaling-stroke" style={{ opacity: open[i] > 0.6 ? (i === active ? 0.9 : 0.32) : 0 }} />
              ))}
            </svg>
            <div className="mt-labels">
              {METHOD_STEPS.map(([num, name, micro, desc, x, y], i) => (
                <div className="mt-label" key={num} style={{ '--x': x, '--y': y }} data-on={open[i] > 0.6 ? 1 : 0} data-active={i === active && open[i] > 0.6 ? 1 : 0}>
                  <span className="mt-num">{num}</span>
                  <h3 className="mt-name">{name}</h3>
                  <p className="mt-micro">{micro}</p>
                  <p className="mt-desc">{desc}</p>
                </div>
              ))}
            </div>
          </div>
          <div className="mt-ui">
            <div className="mt-head">
              <span className="eg-eyebrow">03 — Metodología</span>
              <h2>Seis pasos, cuatro a ocho semanas</h2>
            </div>
            <p className="mt-sub">
              El mismo recorrido para una automatización pequeña y para una plataforma
              interna. Cambia la profundidad, no el orden.
            </p>
            <div className="mt-prog">
              <span>{METHOD_STEPS[active][0]} / 06</span>
              <span className="mt-prog-bars">
                {METHOD_STEPS.map((s, i) => <i key={s[0]} data-on={i <= active ? 1 : 0} />)}
              </span>
            </div>
            <div className="mt-foot">El alcance define la profundidad. La metodología no cambia.</div>
          </div>
          <div className="mt-weeks" data-on={done ? 1 : 0}>
            <span className="mt-clock"><span className="eg-icon" style={{ fontSize: 24 }}>schedule</span></span>
            <div>
              <div className="mt-weeks-fig">04—08 SEMANAS</div>
              <div className="mt-weeks-cap">De diagnóstico a operación</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Problem, Solutions, Method });
