/* global React, window */
/* "O que fazemos com agentes": três formas, apresentadas como escada de autonomia,
   cada uma com um diagrama SVG no estilo Swiss (graphite sobre cream, pontilhado
   que rima com o plano do Hero). Movimento calmo e orgânico, com sentido:
   a aura que emana, o trabalho que vira agente, o sinal que percorre as tools.
   Tudo respeita prefers-reduced-motion e só anima quando a seção entra em vista. */
const { useRef: useAWRef, useEffect: useAWEffect } = React;

const AW_INK = '#141414';
const AW_GRAPHITE = '#5a5347';
const AW_SOFT = '#8a8175';
const AW_LINE = '#d8d2c4';

/* pontos ao longo de um arco (para a "aura" de superpoderes) */
function awArcDots(cx, cy, r, a0, a1, count, rad, cls) {
  const out = [];
  for (let i = 0; i < count; i++) {
    const t = count === 1 ? 0 : i / (count - 1);
    const a = (a0 + (a1 - a0) * t) * Math.PI / 180;
    out.push(<circle key={cls + '-' + i} className={cls} cx={(cx + Math.cos(a) * r).toFixed(1)} cy={(cy + Math.sin(a) * r).toFixed(1)} r={rad} fill={AW_GRAPHITE} />);
  }
  return out;
}

/* 1 · Uma pessoa com superpoderes: figura + aura de pontos que emana em ondas */
function DiagramPerson() {
  return (
    <svg viewBox="0 0 220 150" className="way-svg" role="img" aria-label="">
      <g className="aura">
        <g className="aura-ring aura-r1">{awArcDots(110, 84, 30, 200, 340, 9, 1.7, 'ad1')}</g>
        <g className="aura-ring aura-r2">{awArcDots(110, 84, 42, 194, 346, 12, 1.6, 'ad2')}</g>
        <g className="aura-ring aura-r3">{awArcDots(110, 84, 54, 188, 352, 15, 1.5, 'ad3')}</g>
      </g>
      {/* faíscas */}
      <g stroke={AW_GRAPHITE} strokeWidth="1.4">
        <path className="spark spark-a" d="M56 40 l0 10 M51 45 l10 0" />
        <path className="spark spark-b" d="M168 52 l0 8 M164 56 l8 0" />
      </g>
      {/* figura */}
      <g className="way-figure">
        <circle cx="110" cy="80" r="12" fill={AW_INK} />
        <path d="M86 138 Q86 100 110 98 Q134 100 134 138 Z" fill={AW_INK} />
      </g>
    </svg>
  );
}

/* 2 · Um time com agentes autônomos: pessoas ligadas a um loop de nós-agente */
function DiagramTeam() {
  const person = (x, y, s, k) => (
    <g fill={AW_INK} className="way-figure" key={k}>
      <circle cx={x} cy={y} r={7 * s} />
      <path d={`M${x - 13 * s} ${y + 34 * s} Q${x - 13 * s} ${y + 12 * s} ${x} ${y + 10 * s} Q${x + 13 * s} ${y + 12 * s} ${x + 13 * s} ${y + 34 * s} Z`} />
    </g>
  );
  const node = (x, y, cls) => (
    <g className={cls}>
      <rect x={x - 12} y={y - 12} width="24" height="24" rx="3" fill="none" stroke={AW_GRAPHITE} strokeWidth="1.6" />
      <circle cx={x} cy={y} r="3.4" fill={AW_GRAPHITE} />
    </g>
  );
  return (
    <svg viewBox="0 0 220 150" className="way-svg" role="img" aria-label="">
      {person(40, 58, 1, 'p1')}
      {person(40, 96, 0.82, 'p2')}
      {/* ligação pessoas -> loop, com token que viaja */}
      <path d="M62 74 H104" fill="none" stroke={AW_LINE} strokeWidth="1.4" />
      <circle className="token" cx="62" cy="74" r="2.6" fill={AW_INK} />
      {/* loop de agentes */}
      <g className="way-rot">
        <path d="M150 40 L188 92 L112 92 Z" fill="none" stroke={AW_LINE} strokeWidth="1.4" strokeDasharray="3 4" />
      </g>
      {node(150, 40, 'agn agn-1')}
      {node(188, 92, 'agn agn-2')}
      {node(112, 92, 'agn agn-3')}
    </svg>
  );
}

/* 3 · Software agent-friendly: blocos isométricos encaixados e cabeados */
function DiagramTools() {
  const COS = 0.866, SIN = 0.5;
  const iso = (x, y, z) => [(x - y) * COS, (x + y) * SIN - z];
  const box = (ox, oy, w, d, h, key, cls) => {
    const p = (x, y, z) => { const [sx, sy] = iso(x, y, z); return (ox + sx).toFixed(1) + ',' + (oy - sy).toFixed(1); };
    const top = [p(0, 0, h), p(w, 0, h), p(w, d, h), p(0, d, h)].join(' ');
    const left = [p(0, d, h), p(w, d, h), p(w, d, 0), p(0, d, 0)].join(' ');
    const right = [p(w, 0, h), p(w, d, h), p(w, d, 0), p(w, 0, 0)].join(' ');
    return (
      <g key={key} className={cls}>
        <polygon points={left} fill={AW_INK} />
        <polygon points={right} fill="#2a2722" />
        <polygon points={top} fill={AW_GRAPHITE} />
      </g>
    );
  };
  return (
    <svg viewBox="0 0 220 150" className="way-svg" role="img" aria-label="">
      {/* cabos entre blocos + empalmes que pulsam em sequência */}
      <path d="M74 96 L110 78 M146 96 L110 78" fill="none" stroke={AW_LINE} strokeWidth="1.4" strokeDasharray="3 4" />
      <circle className="joint joint-1" cx="74" cy="96" r="2.4" fill={AW_GRAPHITE} />
      <circle className="joint joint-2" cx="110" cy="78" r="2.4" fill={AW_GRAPHITE} />
      <circle className="joint joint-3" cx="146" cy="96" r="2.4" fill={AW_GRAPHITE} />
      {box(74, 118, 22, 22, 20, 'a', 'tbox tbox-1')}
      {box(146, 118, 22, 22, 20, 'b', 'tbox tbox-2')}
      {box(110, 100, 26, 26, 28, 'c', 'tbox tbox-3')}
    </svg>
  );
}

const AW_DIAGRAMS = [DiagramPerson, DiagramTeam, DiagramTools];

const AW_CSS = `
.ways-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 0; padding-top: 48px; }
.way-cell { padding: 40px 40px 40px 0; border-right: 1px solid var(--border); display: flex; flex-direction: column; gap: 18px; opacity: 0; transform: translateY(16px); transition: opacity .7s var(--ease-out), transform .7s var(--ease-out); }
.way-cell:last-child { border-right: none; padding-right: 0; padding-left: 40px; }
.way-cell:first-child { padding-left: 0; }
.way-cell:not(:first-child) { padding-left: 40px; }
.ways-grid.in .way-cell { opacity: 1; transform: none; }
.ways-grid.in .way-cell:nth-child(2) { transition-delay: .09s; }
.ways-grid.in .way-cell:nth-child(3) { transition-delay: .18s; }
.way-frame { aspect-ratio: 16 / 10; background: var(--cream-2); border: 1px solid var(--border); border-radius: 2px; display: flex; align-items: center; justify-content: center; overflow: hidden; transition: transform .4s var(--ease-out), box-shadow .4s var(--ease-out), border-color .4s var(--ease-out); }
.way-svg { display: block; width: 78%; height: auto; }
.way-num { font-family: var(--font-mono); font-size: 12px; letter-spacing: 0.14em; color: var(--graphite); font-weight: 500; }
.way-title { font-size: clamp(22px, 1.9vw, 27px); font-weight: 500; letter-spacing: -0.02em; line-height: 1.12; color: var(--ink); margin: 0; max-width: 18ch; }
.way-body { font-size: 15px; line-height: 1.55; color: var(--warm-700); margin: 0; }
.way-sub { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--warm-600); margin-top: auto; padding-top: 20px; border-top: 1px solid var(--border); }
.way-list { display: flex; flex-direction: column; gap: 6px; margin: 12px 0 0; padding: 0; list-style: none; }
.way-item { display: flex; align-items: baseline; gap: 10px; font-size: 14px; color: var(--ink); font-weight: 500; }
.way-item .m { color: var(--graphite); font-family: var(--font-mono); font-size: 11px; }

/* hover (desktop): eleva a moldura e intensifica o diagrama */
@media (hover: hover) {
  .way-cell:hover .way-frame { transform: translateY(-4px); box-shadow: 0 16px 40px rgba(20,20,20,0.10); border-color: var(--warm-300); }
  .way-cell:hover .aura { animation-duration: 3.4s; }
  .way-cell:hover .way-rot { animation-duration: 14s; }
}

/* --- movimento (só quando .in / em vista) --- */
.ways-grid .aura-ring, .ways-grid .spark, .ways-grid .token, .ways-grid .agn circle, .ways-grid .joint { will-change: opacity, transform; }

/* 1 · aura que emana em ondas (rings pulsam em sequência) */
.ways-grid.in .aura-r1 { animation: awEmanate 4.8s var(--ease-out) infinite; }
.ways-grid.in .aura-r2 { animation: awEmanate 4.8s var(--ease-out) infinite; animation-delay: .5s; }
.ways-grid.in .aura-r3 { animation: awEmanate 4.8s var(--ease-out) infinite; animation-delay: 1s; }
.aura-ring { opacity: .5; transform-origin: 110px 84px; }
@keyframes awEmanate { 0% { opacity: .25; transform: scale(.92); } 35% { opacity: 1; } 70%,100% { opacity: .25; transform: scale(1.06); } }
.spark { opacity: .45; }

/* 2 · token que viaja pessoa -> loop, nós que acendem em sequência, loop girando */
.way-rot { animation: none; transform-origin: 150px 74px; }
.ways-grid.in .way-rot { animation: awRot 24s linear infinite; }
@keyframes awRot { to { transform: rotate(360deg); } }
.token { opacity: 0; }
.ways-grid.in .token { animation: awToken 3.2s var(--ease-out) infinite; }
@keyframes awToken { 0% { transform: translateX(0); opacity: 0; } 12% { opacity: 1; } 55% { transform: translateX(42px); opacity: 1; } 70%,100% { transform: translateX(42px); opacity: 0; } }
.agn circle { opacity: .55; }
@keyframes awNode { 0%,100% { opacity: .3; } 40% { opacity: 1; } }

/* 3 · empalmes que pulsam em sequência (sinal fluindo) + blocos que assentam */
.joint { opacity: .4; }
.ways-grid.in .joint-1 { animation: awNode 3s var(--ease-out) infinite; }
.ways-grid.in .joint-2 { animation: awNode 3s var(--ease-out) infinite; animation-delay: 1s; }
.ways-grid.in .joint-3 { animation: awNode 3s var(--ease-out) infinite; animation-delay: 2s; }
.tbox { opacity: 0; transform: translateY(10px); }
.ways-grid.in .tbox { animation: awSettle .6s var(--ease-out) forwards; }
.ways-grid.in .tbox-1 { animation-delay: .15s; }
.ways-grid.in .tbox-2 { animation-delay: .28s; }
.ways-grid.in .tbox-3 { animation-delay: .41s; }
@keyframes awSettle { to { opacity: 1; transform: none; } }

@media (prefers-reduced-motion: reduce) {
  .way-cell { opacity: 1; transform: none; transition: none; }
  .aura-ring, .spark, .token, .agn circle, .joint, .tbox { animation: none !important; opacity: 1; transform: none; }
  .way-frame { transition: none; }
}
@media (max-width: 880px) {
  .ways-grid { grid-template-columns: 1fr; padding-top: 32px; }
  .way-cell, .way-cell:not(:first-child), .way-cell:last-child { padding: 28px 0; border-right: none; border-bottom: 1px solid var(--border); }
  .way-cell:last-child { border-bottom: none; }
  .way-frame { aspect-ratio: 2 / 1; }
  .way-svg { width: 58%; }
}
`;

function AgentWays({ lang, onOpenContact }) {
  const tr = (k) => window.tr(lang, k);
  const gridRef = useAWRef(null);

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

  const wrap = { padding: '120px 0' };
  const header = { display: 'grid', gridTemplateColumns: '5fr 7fr', gap: '64px', alignItems: 'end', paddingBottom: '48px', borderBottom: '1px solid var(--ink)' };
  const h2 = { fontSize: 'clamp(40px, 5.4vw, 72px)', fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1.02, color: 'var(--ink)', margin: '16px 0 0', maxWidth: '15ch' };
  const lead = { fontSize: '19px', lineHeight: 1.55, color: 'var(--warm-700)', margin: 0, maxWidth: '50ch' };

  const ways = [
    { n: '01', Dia: AW_DIAGRAMS[0], title: 'w1_title', body: 'w1_body', sub: 'w1_sub', items: ['w1_l1', 'w1_l2', 'w1_l3', 'w1_l4'] },
    { n: '02', Dia: AW_DIAGRAMS[1], title: 'w2_title', body: 'w2_body', sub: 'w2_sub', items: ['w2_l1', 'w2_l2', 'w2_l3', 'w2_l4'] },
    { n: '03', Dia: AW_DIAGRAMS[2], title: 'w3_title', body: 'w3_body', sub: 'w3_sub', items: ['w3_l1', 'w3_l2', 'w3_l3', 'w3_l4'] },
  ];

  return (
    <section style={wrap} id="fazemos" className="sec">
      <style>{AW_CSS}</style>
      <div className="container">
        <header style={header} className="sec-header">
          <div>
            <div className="eyebrow"><span className="n">01</span>{tr('agentways.eyebrow')}</div>
            <h2 style={h2}>{tr('agentways.heading')}<span style={{ color: 'var(--graphite)' }}>.</span></h2>
          </div>
          <p style={lead}>{tr('agentways.lead')}</p>
        </header>

        <div className="ways-grid" ref={gridRef}>
          {ways.map((w) => {
            const Dia = w.Dia;
            return (
              <div key={w.n} className="way-cell">
                <div className="way-frame"><Dia /></div>
                <span className="way-num">{w.n}</span>
                <h3 className="way-title">{tr('agentways.' + w.title)}</h3>
                <p className="way-body">{tr('agentways.' + w.body)}</p>
                <div className="way-sub">
                  {tr('agentways.' + w.sub)}
                  <ul className="way-list">
                    {w.items.map((it) => <li key={it} className="way-item"><span className="m">·</span> {tr('agentways.' + it)}</li>)}
                  </ul>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

window.AgentWays = AgentWays;
