/* ==================================================
   STOCK, Institucional page interactive components
   Editorial/industrial language, distinct from Produto.
   Depends on React (global) + internal.jsx (Counter opt.)
   Exposes: useInstFx, EdNums, Timeline, DifRows, SegMarquee
   ================================================== */

const { useState: iUseState, useEffect: iUseEffect, useRef: iUseRef } = React;

/* ---------- scroll fx: wipe/rise reveals + strip parallax + timeline ---------- */
function useInstFx() {
  iUseEffect(() => {
    /* reveals */
    const els = document.querySelectorAll('.wipe, .rise');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('on'); io.unobserve(e.target); } });
    }, { threshold: 0.18 });
    els.forEach(el => io.observe(el));

    /* strip parallax */
    const strips = document.querySelectorAll('.ed-strip img');
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const vh = window.innerHeight;
        strips.forEach(img => {
          const r = img.parentElement.getBoundingClientRect();
          const p = (r.top + r.height / 2 - vh / 2) / vh; // -0.5..0.5-ish
          img.style.transform = `translateY(${p * -40}px)`;
        });
        /* timeline fill + dots */
        const tl = document.querySelector('.tl');
        if (tl) {
          const fill = tl.querySelector('.tl-fill');
          const r = tl.getBoundingClientRect();
          const passed = Math.min(Math.max((vh * 0.55 - r.top) / r.height, 0), 1);
          if (fill) fill.style.height = `${passed * 100}%`;
          tl.querySelectorAll('.tl-step').forEach(step => {
            const sr = step.getBoundingClientRect();
            step.classList.toggle('on', sr.top + sr.height / 2 < vh * 0.62);
          });
        }
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); io.disconnect(); };
  }, []);
}

/* ---------- giant numbers with count-up ---------- */
function EdNum({ to, suffix, label, delay }) {
  const ref = iUseRef(null);
  const [v, setV] = iUseState(0);
  iUseEffect(() => {
    const el = ref.current;
    const io = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      io.disconnect();
      const t0 = performance.now();
      const dur = 1600;
      const tick = (t) => {
        const p = Math.min((t - t0) / dur, 1);
        setV(Math.round(to * (1 - Math.pow(1 - p, 3))));
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to]);
  return (
    <div className={`ed-num rise${delay ? ` rise-d${delay}` : ''}`} ref={ref}>
      <div className="en-v">{v.toLocaleString('pt-BR')}<span className="en-suf">{suffix}</span></div>
      <div className="en-l">{label}</div>
    </div>
  );
}

function EdNums({ items }) {
  return (
    <section className="ed-nums">
      <div className="container">
        <div className="ed-nums-grid">
          {items.map((n, i) => <EdNum key={n.label} to={n.to} suffix={n.suffix} label={n.label} delay={i} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- vertical timeline (Projeto / Fabricação / Instalação) ---------- */
function Timeline({ steps }) {
  return (
    <section className="tl-sec" id="processo">
      <div className="container">
        <div className="tl-head rise">
          <span className="isec-eyebrow">Como trabalhamos</span>
          <h2 className="isec-title">Do desenho à instalação</h2>
          <p>Uma equipe só cuida de todo o processo, sem terceirizar etapas, sem repassar responsabilidade.</p>
        </div>
        <div className="tl">
          <div className="tl-rail"><div className="tl-fill"></div></div>
          {steps.map((s, i) => (
            <div className="tl-step" id={s.id} key={s.id}>
              <div className="tl-dot"></div>
              <div className="tl-media wipe">
                <img src={s.img} alt={s.t} />
              </div>
              <div className="tl-body rise">
                <span className="tl-n">{String(i + 1).padStart(2, '0')}</span>
                <h3>{s.t}</h3>
                <p>{s.d}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- diferenciais: expanding rows ---------- */
function DifRows({ items }) {
  return (
    <section className="dif-sec">
      <div className="container">
        <div className="isec-head rise">
          <span className="isec-eyebrow">Por que a Stock</span>
          <h2 className="isec-title">Nossos diferenciais</h2>
        </div>
        <div className="dif-rows">
          {items.map((d, i) => (
            <div className="dif-row rise" key={d.t}>
              <span className="df-n">{String(i + 1).padStart(2, '0')}</span>
              <span className="df-t">{d.t}</span>
              <span className="df-a" aria-hidden="true">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
              </span>
              <p className="df-d">{d.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- segments: double marquee ---------- */
function SegMarquee({ items }) {
  const half = Math.ceil(items.length / 2);
  const rows = [items.slice(0, half), items.slice(half)];
  const Chip = ({ s }) => (
    <span className="segmq-chip">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      {s}
    </span>
  );
  return (
    <section className="segmq">
      <div className="container">
        <div className="isec-head center rise">
          <span className="isec-eyebrow">Onde atuamos</span>
          <h2 className="isec-title">Segmentos atendidos</h2>
        </div>
      </div>
      {rows.map((row, ri) => (
        <div className={`segmq-row r${ri + 1}`} key={ri}>
          <div className="segmq-track">
            {[...row, ...row, ...row, ...row].map((s, i) => <Chip s={s} key={`${s}-${i}`} />)}
          </div>
        </div>
      ))}
    </section>
  );
}

Object.assign(window, { useInstFx, EdNums, Timeline, DifRows, SegMarquee });
