/* Page 3 — "From scattered spreadsheets to one system" (#work, yellow).
   A standalone visual block: the before/after example only (chaos of files
   → one custom platform). No chapter eyebrow, no "SoloTrack" caption and no
   surrounding copy — just the picture. The old proof-of-work cards were
   retired (they duplicated the Our Products page). */

/* Interactive "chaos of files": chips rain in on scroll, then scatter away
   from the pointer (magnetic repulsion). Pure rAF + refs, no extra state. */
const CHAOS_FILES = [
  'Sales.xlsx','Orders_v4.xlsx','Import_FINAL.xlsx','Containers.xlsx',
  'Invoices_2024.xlsx','Supplier_list.xlsx','Delivery_Q2.xlsx',
  'Payments-new.xlsx','Stock-check.xlsx'
];

function ChaosFiles() {
  const wrapRef = React.useRef(null);
  const chipsRef = React.useRef([]);

  React.useEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    const els = chipsRef.current.filter(Boolean);
    if (!els.length) return;

    const rnd = (s) => { const x = Math.sin((s + 1) * 999.7) * 43758.5453; return x - Math.floor(x); };
    const data = els.map((el, i) => ({
      el,
      restX: (rnd(i)     - 0.5) * 26,
      restY: (rnd(i + 7) - 0.5) * 22,
      restRot: ((i * 37) % 7) - 3 + (rnd(i + 3) - 0.5) * 6,
      cx: 0, cy: 0, crot: 0,
      ox: 0, oy: 0
    }));

    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) {
      data.forEach(d => {
        d.el.style.opacity = 1;
        d.el.style.transform = `translate(${d.restX}px,${d.restY}px) rotate(${d.restRot}deg)`;
      });
      return;
    }

    const measure = () => data.forEach(d => {
      d.ox = d.el.offsetLeft + d.el.offsetWidth / 2;
      d.oy = d.el.offsetTop + d.el.offsetHeight / 2;
    });
    measure();

    const pointer = { x: -9999, y: -9999, inside: false };
    let scrollProg = 0;
    const onScroll = () => {
      const r = wrap.getBoundingClientRect();
      scrollProg = (window.innerHeight - r.top) / (window.innerHeight * 0.85);
    };
    const onMove = (e) => {
      const r = wrap.getBoundingClientRect();
      pointer.x = e.clientX - r.left;
      pointer.y = e.clientY - r.top;
      pointer.inside = true;
    };
    const onLeave = () => { pointer.inside = false; pointer.x = pointer.y = -9999; };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', measure);
    wrap.addEventListener('pointermove', onMove);
    wrap.addEventListener('pointerleave', onLeave);

    let raf;
    const frame = () => {
      const p = Math.max(0, Math.min(1, scrollProg));
      data.forEach((d, i) => {
        let e = (p - i * 0.05) / 0.35;
        e = Math.max(0, Math.min(1, e));
        const ease = 1 - Math.pow(1 - e, 3);
        const entranceY = (1 - ease) * -210;
        const entranceRot = (1 - ease) * (i % 2 ? 34 : -28);
        let rx = 0, ry = 0, rr = 0;
        if (pointer.inside) {
          const dx = d.ox - pointer.x, dy = d.oy - pointer.y;
          const dist = Math.hypot(dx, dy);
          const R = 120;
          if (dist < R) {
            const f = 1 - dist / R;
            const inv = 1 / (dist || 1);
            rx = dx * inv * f * 48;
            ry = dy * inv * f * 48;
            rr = f * (dx < 0 ? -16 : 16);
          }
        }
        const tx = d.restX + rx;
        const ty = d.restY + ry + entranceY;
        const tr = d.restRot + rr + entranceRot;
        d.cx += (tx - d.cx) * 0.16;
        d.cy += (ty - d.cy) * 0.16;
        d.crot += (tr - d.crot) * 0.16;
        d.el.style.opacity = ease;
        d.el.style.transform = `translate(${d.cx.toFixed(2)}px,${d.cy.toFixed(2)}px) rotate(${d.crot.toFixed(2)}deg)`;
      });
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', measure);
      wrap.removeEventListener('pointermove', onMove);
      wrap.removeEventListener('pointerleave', onLeave);
    };
  }, []);

  return (
    <div ref={wrapRef} className="chaos-files">
      {CHAOS_FILES.map((f, i) => (
        <span key={f} ref={el => chipsRef.current[i] = el} className="chaos-chip">{f}</span>
      ))}
    </div>
  );
}

function PageWork() {
  const { L } = useLang();
  const ex = L.work.example;

  return (
    <section id="work" style={{ background:'var(--yellow)' }}>
      <div className="wrap">
        <div style={{ paddingTop:110 }}>
          <Reveal>
            <h3 className="display display-lg" style={{ maxWidth:'14ch' }}>
              {ex.head.a}<span className="strike">{ex.head.strike}</span>{ex.head.b}
              <span style={{ display:'inline-block', background:'var(--black)', color:'var(--yellow)', padding:'0 14px 4px' }}>{ex.head.accent}</span>
            </h3>
          </Reveal>

          <div className="p3-ba">
            <Reveal>
              <div className="p3-card">
                <div className="mono" style={{ opacity:.55 }}>{ex.beforeLabel}</div>
                <div className="display display-sm" style={{ marginTop:8, maxWidth:'12ch' }}>{ex.beforeTitle}</div>
                <ChaosFiles />
              </div>
            </Reveal>
            <Reveal delay={120} className="p3-arrow">→</Reveal>
            <Reveal delay={160}>
              <div className="p3-card p3-card--after">
                <div className="mono" style={{ opacity:.7 }}>{ex.afterLabel}</div>
                <div className="display display-sm" style={{ marginTop:8, maxWidth:'12ch', color:'var(--yellow)' }}>{ex.afterTitle}</div>
                <div style={{ position:'absolute', left:36, bottom:36, display:'flex', flexDirection:'column', gap:6, fontFamily:'var(--f-mono)', fontSize:11, letterSpacing:'.1em' }}>
                  <div>ORDER → SUPPLIER</div>
                  <div>SUPPLIER → CONTAINER</div>
                  <div>CONTAINER → PAYMENT</div>
                  <div>PAYMENT → DELIVERY</div>
                  <div>AI → SUMMARIES · RISKS · NEXT STEPS</div>
                </div>
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

window.PageWork = PageWork;
