/* global React, window, document, IsoStackZoom */
/* /lab2: iteração do stack isométrico. As camadas inativas se fecham num bloco
   compacto e a câmera dá zoom na camada ativa (comportamento do primero.ai). */
const { useState: useStateLab2, useEffect: useEffectLab2, useRef: useRefLab2 } = React;

const LAB2_LAYERS = [
  {
    num: '01', label: 'RECORD', title: 'Sistemas de registro',
    desc: 'Onde a sua operação já vive hoje: CRM, ERP, e-mail, planilhas. Nada disso muda. É a base que os agentes leem e escrevem.',
    tags: ['CRM', 'ERP', 'E-mail', 'Docs'],
  },
  {
    num: '02', label: 'DATA', title: 'Infraestrutura de dados',
    desc: 'A fundação governada onde os registros operacionais viram dados utilizáveis para análise, permissões e fluxos de IA com padrão corporativo.',
    tags: ['Lakehouse', 'Warehouse', 'ML', 'Permissions'],
  },
  {
    num: '03', label: 'INTELLIGENCE', title: 'Camada de inteligência',
    desc: 'Onde os agentes raciocinam sobre os seus dados: interpretam contexto, decidem o próximo passo e operam dentro de limites definidos por você.',
    tags: ['Agents', 'Reasoning', 'Guardrails'],
  },
  {
    num: '04', label: 'MODULES', title: 'Módulos de negócio',
    desc: 'Fluxos compostos para os times de vendas, atendimento, financeiro e operações, todos sobre a mesma fundação.',
    tags: ['Sales', 'Customer Service', 'Finance', 'Operations'],
  },
];

const LAB2_CSS = `
.lab-outer { height: 400vh; background: #f0ede6; }
.lab-sticky { position: sticky; top: 72px; height: calc(100vh - 72px); overflow: hidden; display: flex; align-items: center; }
.lab-grid { display: grid; grid-template-columns: 260px minmax(0, 1fr) minmax(0, 1.15fr); gap: 56px; align-items: center; width: 100%; }
.lab-side { display: flex; flex-direction: column; gap: 10px; }
.lab-side .lab-item:nth-child(1) { order: 4; }
.lab-side .lab-item:nth-child(2) { order: 3; }
.lab-side .lab-item:nth-child(3) { order: 2; }
.lab-side .lab-item:nth-child(4) { order: 1; }
.lab-item {
  appearance: none; background: transparent; border: none; border-left: 3px solid transparent;
  text-align: left; padding: 16px 18px; cursor: pointer; border-radius: 2px;
  transition: background 250ms ease, border-color 250ms ease;
}
.lab-item .lab-item-num {
  font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em;
  text-transform: uppercase; color: var(--warm-500); margin-bottom: 6px;
}
.lab-item .lab-item-title { font-size: 17px; letter-spacing: -0.01em; color: var(--warm-600); font-weight: 500; transition: color 250ms ease; }
.lab-item.is-active { background: #ffffff; border-left-color: #7f89ef; box-shadow: 0 10px 30px rgba(20, 20, 20, 0.06); }
.lab-item.is-active .lab-item-title { color: var(--ink); }
.lab-copy { min-height: 380px; }
.lab-copy-inner { animation: labFadeUp 320ms ease both; }
@keyframes labFadeUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
.lab-num { font-family: var(--font-mono); font-size: 12px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--graphite); margin: 26px 0 14px; }
.lab-title { font-size: clamp(34px, 3.6vw, 56px); font-weight: 500; letter-spacing: -0.03em; line-height: 1.05; margin: 0 0 20px; color: var(--ink); }
.lab-desc { font-size: 18px; line-height: 1.6; color: var(--warm-700); max-width: 44ch; margin: 0 0 26px; }
.lab-tags { display: flex; flex-wrap: wrap; gap: 10px; }
.lab-tag {
  font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.06em; color: var(--warm-700);
  border: 1px solid var(--cream-3); background: rgba(255, 255, 255, 0.5); border-radius: 999px; padding: 6px 14px;
}
.lab-art { display: flex; justify-content: center; }
.iso-svg { display: block; width: 100%; max-width: 620px; height: auto; }
.iso-camera { transition: transform 750ms cubic-bezier(0.22, 1, 0.36, 1); }
.iso-zlayer { transition: transform 750ms cubic-bezier(0.22, 1, 0.36, 1); }
.iso-zlayer .iso-blocks { transition: opacity 450ms ease; }
.iso-zlayer:not(.is-active) .iso-blocks { opacity: 0.12; }
@media (prefers-reduced-motion: reduce) {
  .iso-camera, .iso-zlayer, .lab-item { transition: none; }
  .iso-zlayer .iso-blocks { transition: none; }
  .lab-copy-inner { animation: none; }
}
@media (max-width: 880px) {
  .lab-outer { height: auto; }
  .lab-sticky { position: static; height: auto; overflow: visible; padding: 40px 0 64px; }
  .lab-grid { grid-template-columns: 1fr; gap: 28px; }
  .lab-side { flex-direction: row; overflow-x: auto; gap: 8px; padding-bottom: 6px; -webkit-overflow-scrolling: touch; }
  .lab-side .lab-item { order: 0; flex: 0 0 auto; border-left: none; border-bottom: 3px solid transparent; padding: 10px 14px; }
  .lab-item.is-active { border-bottom-color: #7f89ef; }
  .lab-item .lab-item-title { font-size: 15px; }
  .lab-copy { min-height: 0; order: 3; }
  .lab-art { order: 2; }
  .iso-svg { max-width: 440px; }
  .lab-num { margin-top: 8px; }
}
`;

function Lab2() {
  const outerRef = useRefLab2(null);
  const [active, setActive] = useStateLab2(0);
  const count = LAB2_LAYERS.length;

  const reduced = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  useEffectLab2(() => {
    let raf = 0;
    const measure = () => {
      raf = 0;
      const el = outerRef.current;
      if (!el) return;
      const total = el.offsetHeight - window.innerHeight;
      if (total <= 40) return;
      const p = Math.min(1, Math.max(0, -el.getBoundingClientRect().top / total));
      setActive((prev) => {
        const target = Math.min(count - 1, Math.floor(p * count));
        if (target === prev) return prev;
        const inBand = p * count - target;
        const H = 0.12;
        if (target > prev && inBand < H) return prev;
        if (target < prev && inBand > 1 - H) return prev;
        return target;
      });
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(measure); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    measure();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [count]);

  const scrollToLayer = (i) => {
    const el = outerRef.current;
    if (!el) return;
    const total = el.offsetHeight - window.innerHeight;
    if (total <= 40) { setActive(i); return; }
    const absTop = window.scrollY + el.getBoundingClientRect().top;
    window.scrollTo({ top: absTop + ((i + 0.5) / count) * total, behavior: reduced ? 'auto' : 'smooth' });
  };

  const l = LAB2_LAYERS[active];

  return (
    <div className="lab">
      <style>{LAB2_CSS}</style>
      <section ref={outerRef} className="lab-outer">
        <div className="lab-sticky">
          <div className="container lab-grid">
            <div className="lab-side" role="tablist" aria-label="Camadas do stack">
              {LAB2_LAYERS.map((it, i) => (
                <button
                  key={it.num}
                  type="button"
                  role="tab"
                  aria-selected={i === active}
                  className={'lab-item' + (i === active ? ' is-active' : '')}
                  onClick={() => scrollToLayer(i)}
                >
                  <div className="lab-item-num">{it.num} / {it.label}</div>
                  <div className="lab-item-title">{it.title}</div>
                </button>
              ))}
            </div>
            <div className="lab-copy">
              <div className="eyebrow">Como a IA se encaixa na sua operação</div>
              <div key={active} className="lab-copy-inner">
                <div className="lab-num">{l.num} / {l.label}</div>
                <h1 className="lab-title">{l.title}</h1>
                <p className="lab-desc">{l.desc}</p>
                <div className="lab-tags">
                  {l.tags.map((t) => <span key={t} className="lab-tag">{t}</span>)}
                </div>
              </div>
            </div>
            <div className="lab-art">
              <IsoStackZoom active={active} />
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.Lab2 = Lab2;
