/* global React, window */
/* "Onde a IA entra": torre isométrica scroll-driven, look Moore (graphite sobre
   cream, grade de pontos). Autocontido. Versão limpa: 4 plates sólidas e
   espaçadas, enquadramento fixo (sem câmera/zoom), a camada ativa se eleva e
   mostra suas caixas; as inativas ficam como plates limpas com o nome no topo.
   Sem sobreposição de camadas fantasma. Respeita reduced-motion e pausa fora da tela. */
const { useState: useOS, useEffect: useOSE, useRef: useOSR } = React;

const OS_COS = 0.8660254, OS_SIN = 0.5;
const osIso = (x, y, z) => ({ sx: (x - y) * OS_COS, sy: (x + y) * OS_SIN - z });
const osPts = (a) => a.map((p) => p.sx.toFixed(2) + ',' + p.sy.toFixed(2)).join(' ');
const osTop = (x, y, z) => { const o = osIso(x, y, z); return 'matrix(' + OS_COS + ' ' + OS_SIN + ' ' + -OS_COS + ' ' + OS_SIN + ' ' + o.sx.toFixed(2) + ' ' + o.sy.toFixed(2) + ')'; };

const OS_BOX = { top: '#5a5347', left: '#43403a', right: '#312e29' };
const OS_PLATE = { top: '#efece4', left: '#ddd6c8', right: '#c4bdb0' };
const OS_PLATE_ON = { top: '#ffffff', left: '#e6e1d5', right: '#cfc7b8' };
const OS_DOT = '#c4bdb0';
const OS_EDGE = 'rgba(20,20,20,0.12)';
const OS_LABEL = '#f6f4ef';
const OS_INK = '#141414';
const OS_DASH = '#8a8175';
const OS_MONO = '"Geist Mono", ui-monospace, monospace';
const OS_PW = 300, OS_PTH = 16;

function OSTopFace({ x, y, z, children }) { return <g transform={osTop(x, y, z)}>{children}</g>; }

function OSBox({ x, y, z, w, d, h, tone, label, labelSize }) {
  const t = tone || OS_BOX;
  const A = osIso(x, y, z + h), B = osIso(x + w, y, z + h), C = osIso(x + w, y + d, z + h), D = osIso(x, y + d, z + h);
  const E = osIso(x + w, y, z), F = osIso(x + w, y + d, z), G = osIso(x, y + d, z);
  const lines = label ? (Array.isArray(label) ? label : [label]) : null;
  const fs = labelSize || 13;
  const isPlate = t.top === OS_PLATE.top || t.top === OS_PLATE_ON.top;
  return (
    <g>
      <polygon points={osPts([A, B, C, D])} fill={t.top} stroke={OS_EDGE} strokeWidth="0.75" strokeLinejoin="round" />
      <polygon points={osPts([D, C, F, G])} fill={t.left} stroke={OS_EDGE} strokeWidth="0.75" strokeLinejoin="round" />
      <polygon points={osPts([B, E, F, C])} fill={t.right} stroke={OS_EDGE} strokeWidth="0.75" strokeLinejoin="round" />
      {lines ? (
        <OSTopFace x={x} y={y} z={z + h}>
          <text x={w / 2} y={d / 2 - (lines.length - 1) * fs * 0.55} textAnchor="middle" dominantBaseline="middle" fontFamily={OS_MONO} fontSize={fs} fill={isPlate ? OS_INK : OS_LABEL} letterSpacing="0.02em">
            {lines.map((ln, i) => <tspan key={i} x={w / 2} dy={i === 0 ? 0 : fs * 1.15}>{ln}</tspan>)}
          </text>
        </OSTopFace>
      ) : null}
    </g>
  );
}

/* plate sólida; ativa mostra grade de pontos + caixas; inativa fica limpa
   (o nome de cada camada vive na sidebar, que mapeia pela posição). */
function OSPlate({ label, on, children }) {
  const dots = [];
  if (on) for (let u = 40; u <= 260; u += 40) for (let v = 40; v <= 260; v += 40) dots.push(<circle key={u + '_' + v} cx={u} cy={v} r="2" fill={OS_DOT} />);
  return (
    <g>
      <OSBox x={-150} y={-150} z={0} w={OS_PW} d={OS_PW} h={OS_PTH} tone={on ? OS_PLATE_ON : OS_PLATE} />
      {on ? (
        <g>
          <OSTopFace x={-150} y={-150} z={OS_PTH}>{dots}</OSTopFace>
          <g className="opstack-blocks">{children}</g>
        </g>
      ) : null}
    </g>
  );
}

/* 01 · O que você já usa */
function OSLayerBase({ label, on }) {
  const z = OS_PTH;
  return (
    <OSPlate label={label} on={on}>
      <OSBox x={-95} y={-120} z={z} w={92} d={54} h={34} label="CRM" />
      <OSBox x={35} y={-70} z={z} w={92} d={54} h={34} label="ERP" />
      <OSBox x={-130} y={-5} z={z} w={92} d={54} h={34} label="E-mail" />
      <OSBox x={-5} y={45} z={z} w={100} d={54} h={34} label="Planilhas" labelSize={12} />
    </OSPlate>
  );
}
/* 02 · Seus dados e processos */
function OSLayerData({ label, on }) {
  const z = OS_PTH;
  return (
    <OSPlate label={label} on={on}>
      <OSBox x={-110} y={-40} z={z} w={130} d={80} h={22} label="Dados" labelSize={14} />
      <OSBox x={40} y={-92} z={z} w={72} d={60} h={46} label="Fluxos" labelSize={12} />
      <OSBox x={38} y={18} z={z} w={72} d={60} h={32} label="Regras" labelSize={12} />
    </OSPlate>
  );
}
/* 03 · Agentes em produção */
function OSLayerAgents({ label, on }) {
  const z = OS_PTH;
  const pillar = [[-58, -34], [34, -34], [-58, 12], [34, 12]];
  return (
    <OSPlate label={label} on={on}>
      <OSBox x={-72} y={-48} z={z} w={140} d={92} h={8} tone={{ top: '#6b6258', left: '#4a443b', right: '#3d3934' }} />
      {pillar.map(([px, py], i) => <OSBox key={i} x={px} y={py} z={z + 8} w={16} d={16} h={50} />)}
      <OSBox x={-80} y={-56} z={z + 8 + 50} w={156} d={108} h={12} label="Agentes" labelSize={15} />
    </OSPlate>
  );
}
/* 04 · Resultado na operação */
function OSLayerResult({ label, on }) {
  const z = OS_PTH;
  return (
    <OSPlate label={label} on={on}>
      <OSBox x={-58} y={-128} z={z} w={110} d={56} h={38} label="Vendas" labelSize={12} />
      <OSBox x={-140} y={-30} z={z} w={92} d={54} h={38} label={['Atendi-', 'mento']} labelSize={11} />
      <OSBox x={-10} y={-8} z={z} w={104} d={58} h={38} label="Operações" labelSize={11.5} />
      <OSBox x={-55} y={72} z={z} w={100} d={54} h={38} label="Financeiro" labelSize={11} />
    </OSPlate>
  );
}

/* torre fixa: cada camada num nível fixo (topo = índice 0 desenhado embaixo).
   índice 0 (base) fica embaixo; índice 3 (resultado) em cima. */
const OS_STEP = 150;
function osLevelY(i) { return -i * OS_STEP; }

function OSStackArt({ active, labels }) {
  const draws = [OSLayerBase, OSLayerData, OSLayerAgents, OSLayerResult];
  return (
    <svg className="opstack-svg" viewBox="0 0 760 760" aria-hidden="true" focusable="false">
      <g transform="translate(380, 560)">
        {draws.map((Draw, i) => {
          const on = i === active;
          const y = osLevelY(i) + (on ? -16 : 0);
          return (
            <g key={i} className={'opstack-layer' + (on ? ' on' : '')} style={{ transform: 'translateY(' + y + 'px)' }}>
              {on ? <ellipse className="os-halo" cx="0" cy="120" rx="250" ry="42" fill="rgba(20,20,20,0.14)" /> : null}
              <Draw label={labels[i]} on={on} />
            </g>
          );
        })}
      </g>
    </svg>
  );
}

const OS_CSS = `
.opstack-outer { height: 260vh; }
.opstack-sticky { position: sticky; top: var(--nav-h, 72px); height: calc(100vh - var(--nav-h, 72px)); min-height: 560px; display: flex; align-items: center; overflow: hidden; }
.opstack-grid { display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 56px; align-items: center; width: 100%; }
.opstack-left { display: flex; gap: 22px; }
.opstack-rail { position: relative; width: 2px; background: var(--cream-3); border-radius: 2px; flex: 0 0 auto; }
.opstack-rail-fill { position: absolute; top: 0; left: 0; width: 100%; background: var(--graphite); border-radius: 2px; height: 0; transition: height .18s linear; }
.opstack-colinner { flex: 1 1 auto; min-width: 0; }
.opstack-side { display: flex; flex-direction: column; gap: 8px; }
.opstack-item { appearance: none; background: transparent; border: none; border-left: 3px solid transparent; text-align: left; padding: 14px 18px; cursor: pointer; border-radius: 2px; transition: background .25s var(--ease-out), border-color .25s var(--ease-out); width: 100%; }
.opstack-item .n { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--warm-500); margin-bottom: 5px; transition: color .25s var(--ease-out); }
.opstack-item .t { font-size: 16px; letter-spacing: -0.01em; color: var(--warm-600); font-weight: 500; transition: color .25s var(--ease-out); }
.opstack-item.on { background: var(--cream-2); border-left-color: var(--graphite); }
.opstack-item.on .t { color: var(--ink); }
.opstack-item.on .n { color: var(--graphite); }
.opstack-desc { margin-top: 22px; padding-top: 20px; border-top: 1px solid var(--border); min-height: 132px; }
.opstack-desc-in { animation: osFade .32s var(--ease-out) both; }
@keyframes osFade { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
.opstack-desc p { font-size: 16px; line-height: 1.55; color: var(--warm-700); margin: 0 0 14px; max-width: 42ch; }
.opstack-tags { display: flex; flex-wrap: wrap; gap: 8px; }
.opstack-tag { font-family: var(--font-mono); font-size: 10.5px; letter-spacing: 0.06em; color: var(--warm-700); border: 1px solid var(--border); background: rgba(255,255,255,0.5); border-radius: 999px; padding: 5px 12px; }
.opstack-art { display: flex; justify-content: center; opacity: 0; transform: translateY(24px); transition: opacity .8s var(--ease-out), transform .8s var(--ease-out); }
.opstack.in .opstack-art { opacity: 1; transform: none; }
.opstack.in .opstack-left { animation: osFade .7s var(--ease-out) both; }
.opstack-svg { display: block; width: 100%; max-width: 560px; height: auto; }

/* torre calma: cada camada muda de nível com ease; a ativa sobe um tico */
.opstack-layer { transition: transform 520ms cubic-bezier(.22,1,.36,1); will-change: transform; }
.opstack-tower { transform-origin: center; }
.opstack.live .opstack-tower { animation: osBob 9s ease-in-out infinite; }
@keyframes osBob { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
.os-halo { opacity: 0; animation: osHalo .5s var(--ease-out) forwards; }
@keyframes osHalo { to { opacity: 1; } }
.opstack-blocks { animation: osSettle .55s var(--ease-out) both; }
@keyframes osSettle { from { opacity: 0; transform: translateY(9px); } to { opacity: 1; transform: none; } }

@media (prefers-reduced-motion: reduce) {
  .opstack-layer { transition: none; }
  .opstack-art { opacity: 1; transform: none; transition: none; }
  .opstack.live .opstack-tower, .os-halo, .opstack-blocks, .opstack-desc-in, .opstack.in .opstack-left { animation: none !important; opacity: 1; }
}
@media (max-width: 880px) {
  .opstack-outer { height: auto; }
  .opstack-sticky { position: static; height: auto; min-height: 0; overflow: visible; padding: 8px 0 8px; }
  .opstack-grid { grid-template-columns: 1fr; gap: 24px; }
  .opstack-left { display: block; }
  .opstack-colinner { display: block; }
  .opstack-rail { display: none; }
  .opstack-side { flex-direction: row; overflow-x: auto; gap: 8px; padding-bottom: 6px; -webkit-overflow-scrolling: touch; }
  .opstack-item { flex: 0 0 auto; width: auto; border-left: none; border-bottom: 3px solid transparent; padding: 10px 14px; }
  .opstack-item.on { border-bottom-color: var(--graphite); }
  .opstack-desc { min-height: 0; }
  .opstack-svg { max-width: 420px; }
}
`;

function OperationStack({ lang }) {
  const tr = (k) => window.tr(lang, k);
  const rootRef = useOSR(null);
  const outerRef = useOSR(null);
  const railRef = useOSR(null);
  const [active, setActive] = useOS(0);
  const count = 4;
  const reduced = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  useOSE(() => {
    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));
      if (railRef.current) railRef.current.style.height = (p * 100).toFixed(1) + '%';
      setActive((prev) => {
        const target = Math.min(count - 1, Math.floor(p * count));
        if (target === prev) return prev;
        const inBand = p * count - target, 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); };
  }, []);

  useOSE(() => {
    const el = rootRef.current;
    if (!el) return;
    if (!('IntersectionObserver' in window)) { el.classList.add('in', 'live'); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { el.classList.add('in'); el.classList.add('live'); } else el.classList.remove('live'); });
    }, { threshold: 0.08 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const goTo = (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 layers = [
    { label: tr('opstack.l1_label'), tags: ['CRM', 'ERP', 'E-mail', 'Planilhas'] },
    { label: tr('opstack.l2_label'), tags: ['Dados', 'Fluxos', 'Permissões'] },
    { label: tr('opstack.l3_label'), tags: ['Copilotos', 'Agentes', 'Tools'] },
    { label: tr('opstack.l4_label'), tags: ['Vendas', 'Atendimento', 'Operações', 'Financeiro'] },
  ];
  const wrap = { padding: '120px 0', borderTop: '1px solid var(--ink)' };
  const header = { display: 'grid', gridTemplateColumns: '5fr 7fr', gap: '64px', alignItems: 'end', paddingBottom: '48px' };
  const h2 = { fontSize: 'clamp(40px, 5.4vw, 72px)', fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1.02, color: 'var(--ink)', margin: '16px 0 0', maxWidth: '16ch' };
  const lead = { fontSize: '19px', lineHeight: 1.55, color: 'var(--warm-700)', margin: 0, maxWidth: '46ch' };
  const L = layers[active];

  return (
    <section ref={rootRef} style={wrap} id="camadas" className="sec opstack">
      <style>{OS_CSS}</style>
      <div className="container">
        <header style={header} className="sec-header">
          <div>
            <div className="eyebrow"><span className="n">02</span>{tr('opstack.eyebrow')}</div>
            <h2 style={h2}>{tr('opstack.heading')}<span style={{ color: 'var(--graphite)' }}>.</span></h2>
          </div>
          <p style={lead}>{tr('opstack.lead')}</p>
        </header>
      </div>

      <section ref={outerRef} className="opstack-outer">
        <div className="opstack-sticky">
          <div className="container opstack-grid">
            <div className="opstack-left">
              <div className="opstack-rail"><div ref={railRef} className="opstack-rail-fill" /></div>
              <div className="opstack-colinner">
                <div className="opstack-side" role="tablist" aria-label={tr('opstack.eyebrow')}>
                  {layers.map((it, i) => (
                    <button key={i} type="button" role="tab" aria-selected={i === active} className={'opstack-item' + (i === active ? ' on' : '')} onClick={() => goTo(i)}>
                      <div className="n">{'0' + (i + 1)} / {it.label}</div>
                      <div className="t">{tr('opstack.l' + (i + 1) + '_title')}</div>
                    </button>
                  ))}
                </div>
                <div className="opstack-desc">
                  <div key={active} className="opstack-desc-in">
                    <p>{tr('opstack.l' + (active + 1) + '_desc')}</p>
                    <div className="opstack-tags">{L.tags.map((t) => <span key={t} className="opstack-tag">{t}</span>)}</div>
                  </div>
                </div>
              </div>
            </div>
            <div className="opstack-art">
              <div className="opstack-tower"><OSStackArt active={active} labels={layers.map((l) => l.label)} /></div>
            </div>
          </div>
        </div>
      </section>
    </section>
  );
}

window.OperationStack = OperationStack;
