
const SectionBridge = () => {
  const steps = [
    { n: '01', k: 'Diagnóstico', d: 'Mapeamento da cadeia, gaps regulatórios e pontos críticos de auditoria.' },
    { n: '02', k: 'Estruturação', d: 'Desenho da arquitetura de dados, governança e responsabilidades.' },
    { n: '03', k: 'Automação', d: 'Entra a plataforma Traceply para coleta, validação e auditoria contínua de dados.' },
    { n: '04', k: 'Integração', d: 'Processos em campo, integrações com ERP, fornecedores e parceiros.' },
    { n: '05', k: 'Operação', d: 'Monitoramento 24/7, atualização regulatória e evolução da cadeia.' },
  ];

  const scrollerRef = React.useRef(null);
  const railRef = React.useRef(null);
  const [activeIdx, setActiveIdx] = React.useState(0);

  React.useEffect(() => {
    const sc = scrollerRef.current;
    const rail = railRef.current;
    if (!sc || !rail) return;
    const update = () => {
      const dots = sc.querySelectorAll('.bridge__dot');
      if (dots.length < 2) return;
      const scRect = sc.getBoundingClientRect();
      const firstR = dots[0].getBoundingClientRect();
      const lastR = dots[dots.length - 1].getBoundingClientRect();
      const startX = (firstR.left + firstR.width / 2) - scRect.left + sc.scrollLeft;
      const endX = (lastR.left + lastR.width / 2) - scRect.left + sc.scrollLeft;
      const yCenter = (firstR.top + firstR.height / 2) - scRect.top;
      rail.style.left = startX + 'px';
      rail.style.width = (endX - startX) + 'px';
      rail.style.top = (yCenter - 9) + 'px';
      rail.style.transform = 'none';
    };
    update();
    const ro = new ResizeObserver(update);
    ro.observe(sc);
    sc.querySelectorAll('.bridge__dot').forEach(d => ro.observe(d));
    window.addEventListener('resize', update);
    
    requestAnimationFrame(update);
    setTimeout(update, 100);
    return () => { ro.disconnect(); window.removeEventListener('resize', update); };
  }, []);

  const goTo = (idx) => {
    const sc = scrollerRef.current;
    if (!sc) return;
    const cards = sc.querySelectorAll('.bridge__step');
    const card = cards[idx];
    if (!card) return;
    const left = card.offsetLeft - (sc.clientWidth - card.clientWidth) / 2;
    sc.scrollTo({ left, behavior: 'smooth' });
    setActiveIdx(idx);
  };

  return (
    <section className="section section--bridge section--dark" id="bridge">
      <div className="bridge__glow" aria-hidden="true" />
      <div className="container">
        <div className="section__head section__head--dark">
          <h2 className="section__title section__title--dark">
            Da <span className="accent-word">estratégia</span><br />
            à execução.
          </h2>
          <p className="bridge__lede">
            Cinco passos conectados que transformam exigência regulatória
            em vantagem operacional contínua.
          </p>
        </div>

        <div className="bridge__timeline" ref={scrollerRef}>
          <svg ref={railRef} className="bridge__rail-svg" viewBox="0 0 1000 20" preserveAspectRatio="none" aria-hidden="true">
            <defs>
              <linearGradient id="bridgeRail" x1="0" y1="0" x2="1000" y2="0" gradientUnits="userSpaceOnUse">
                <stop offset="0%" stopColor="#5B9BFF" />
                <stop offset="18%" stopColor="#22D3EE" />
                <stop offset="38%" stopColor="#34D399" />
                <stop offset="55%" stopColor="#3BAF7A" />
                <stop offset="100%" stopColor="#3BAF7A" />
              </linearGradient>
              <filter id="bridgeGlow" x="-2%" y="-400%" width="104%" height="900%">
                <feGaussianBlur stdDeviation="2.5" result="b1" />
                <feGaussianBlur stdDeviation="6" in="SourceGraphic" result="b2" />
                <feMerge>
                  <feMergeNode in="b2" />
                  <feMergeNode in="b1" />
                  <feMergeNode in="SourceGraphic" />
                </feMerge>
              </filter>
            </defs>
            {}
            <path d="M 0 10 L 1000 10" stroke="url(#bridgeRail)" strokeWidth="8" strokeLinecap="round" opacity="0.45" filter="url(#bridgeGlow)" />
            {}
            <path
              d="M 0 10 L 1000 10"
              stroke="url(#bridgeRail)"
              strokeWidth="2.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              fill="none"
              vectorEffect="non-scaling-stroke"
            />
          </svg>

          {steps.map((s, i) => (
            <div
              className={`bridge__step ${i === activeIdx ? 'bridge__step--active' : ''}`}
              data-idx={i}
              key={s.n}
            >
              {s.n === '03' && (
                <div className="bridge__tag bridge__tag--top">
                  <span className="bridge__tag-led" />
                  TRACEPLY
                </div>
              )}
              <div className="bridge__dot">
                <div className="bridge__dot-ring" />
                <div className="bridge__dot-inner" />
              </div>
              <div className="bridge__connector" aria-hidden="true" />
              <div className="bridge__num">{s.n}</div>
              <div className="bridge__step-title">{s.k}</div>
              <div className="bridge__step-desc">{s.d}</div>
            </div>
          ))}
        </div>

        <div className="bridge__pager" aria-hidden="true">
          {steps.map((s, i) => (
            <button
              key={s.n}
              type="button"
              className={`bridge__pager-dot ${i === activeIdx ? 'is-active' : ''}`}
              onClick={() => goTo(i)}
              aria-label={`Ir para passo ${s.n}`}
            />
          ))}
        </div>
      </div>
    </section>
  );
};

const SectionTraceply = () => {
  return (
    <section className="section section--traceply section--dark" id="traceply">
      <div className="container">
        <div className="traceply__grid">
          <div className="traceply__left">
            <div className="traceply__logo">
              <img src="assets/traceply-logo.png" alt="Traceply" />
            </div>
            <h2 className="section__title section__title--dark">
              Tecnologia que <span className="accent-lime">sustenta</span><br />
              a operação.
            </h2>
            <p className="traceply__body">
              A Traceply é a plataforma que permite automatizar, validar e
              escalar a conformidade em tempo real — transformando o método
              Veros em infraestrutura operacional.
            </p>
            <div className="traceply__ctas">
              <a href="https://traceply.com" target="_blank" rel="noopener noreferrer" className="btn btn--lime">
                Conhecer a plataforma
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1 7h12M8 2l5 5-5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </a>
            </div>
          </div>
          <div className="traceply__right">
            <div className="traceply__viz">
              <div className="traceply__viz-top">
                <div className="traceply__viz-tab traceply__viz-tab--active">
                  <span className="traceply__viz-led" />
                  Compliance Live
                </div>
                <div className="traceply__viz-tab">Auditoria</div>
                <div className="traceply__viz-tab">Fornecedores</div>
              </div>
              <div className="traceply__viz-stat">
                <div className="traceply__viz-stat-k">Lotes monitorados · 24h</div>
                <div className="traceply__viz-stat-v">
                  18,492
                  <span className="traceply__viz-stat-delta">+12.4%</span>
                </div>
              </div>
              <div className="traceply__viz-bars">
                {Array.from({ length: 24 }).map((_, i) => {
                  const h = 20 + Math.abs(Math.sin(i * 0.7 + 1.2)) * 70;
                  return (
                    <div
                      key={i}
                      className="traceply__viz-bar"
                      style={{ height: `${h}%`, opacity: i < 20 ? 1 : 0.35 }}
                    />
                  );
                })}
              </div>
              <div className="traceply__viz-rows">
                {[
                  ['SP-BR', 'COMPLIANT', 'ok'],
                  ['MG-BR', 'COMPLIANT', 'ok'],
                  ['PA-BR', 'REVIEW', 'warn'],
                  ['MT-BR', 'COMPLIANT', 'ok'],
                ].map(([node, st, k]) => (
                  <div className="traceply__viz-row" key={node}>
                    <span className="traceply__viz-row-node">{node}</span>
                    <div className="traceply__viz-row-bar">
                      <div
                        className={`traceply__viz-row-fill traceply__viz-row-fill--${k}`}
                        style={{ width: k === 'ok' ? '92%' : '64%' }}
                      />
                    </div>
                    <span className={`traceply__viz-row-status traceply__viz-row-status--${k}`}>{st}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

window.SectionBridge = SectionBridge;
window.SectionTraceply = SectionTraceply;
