// ─── Polished variant: cases (horizontal scroll) + process (pinned) ───

function PolishedCases({ layout }) {
  const D = window.ARCLINE_DATA.cases;
  const ref = React.useRef(null);
  const trackRef = React.useRef(null);
  const progressRef = React.useRef(null);

  React.useEffect(() => {
    if (!window.gsap || !ref.current) return;
    const ctx = gsap.context(() => {
      // entry reveals
      gsap.from(ref.current.querySelectorAll('.head .mono-label, .head h2, .head .progress'), {
        opacity: 0, y: 24, duration: 0.8, ease: 'power3.out', stagger: 0.08,
        scrollTrigger: { trigger: ref.current, start: 'top 75%' },
      });

      if (layout !== 'horizontal' || window.innerWidth <= 720) {
        // Cards just fade in for stacked/grid (or mobile)
        gsap.from(ref.current.querySelectorAll('.p-case'), {
          opacity: 0, y: 36, duration: 0.7, ease: 'power3.out', stagger: 0.1,
          scrollTrigger: { trigger: trackRef.current, start: 'top 80%' },
        });
        return;
      }

      // Horizontal scroll setup
      const track = trackRef.current;
      if (!track) return;
      const cases = track.querySelectorAll('.p-case');
      const trackWidth = track.scrollWidth;
      const distance = trackWidth - window.innerWidth + 56;
      const trigger = ref.current.querySelector('.p-cases-pin');

      gsap.to(track, {
        x: -distance,
        ease: 'none',
        scrollTrigger: {
          trigger,
          start: 'top top',
          end: () => `+=${distance}`,
          pin: true,
          scrub: 1,
          invalidateOnRefresh: true,
          onUpdate: (self) => {
            const idx = Math.min(cases.length, Math.max(1, Math.round(self.progress * cases.length + 0.5)));
            if (progressRef.current) progressRef.current.textContent = String(idx).padStart(2, '0');
          },
        },
      });
    }, ref);
    return () => ctx.revert();
  }, [layout]);

  return (
    <section id="work" className="p-cases" data-layout={layout} ref={ref}>
      <div className="container">
        <div className="head">
          <div>
            <div className="mono-label"><span className="slash">//</span>{D.eyebrow}</div>
            <h2>{D.head[0]} <em>{D.head[1]}</em></h2>
          </div>
          <div className="progress">
            <span className="now" ref={progressRef}>01</span> / {String(D.items.length).padStart(2, '0')}
          </div>
        </div>
      </div>
      {layout === 'horizontal' ? (
        <div className="p-cases-pin">
          <div className="p-cases-track" ref={trackRef}>
            {D.items.map((c) => <PolishedCaseCard key={c.idx} c={c} />)}
            <div style={{ flex: '0 0 56px' }} />
          </div>
        </div>
      ) : (
        <div className="container" style={{ paddingTop: 32 }}>
          <div className="p-cases-track" ref={trackRef}>
            {D.items.map((c) => <PolishedCaseCard key={c.idx} c={c} />)}
          </div>
        </div>
      )}
      <div className="p-cases-spacer" />
    </section>
  );
}

function PolishedCaseCard({ c }) {
  return (
    <article className="p-case interactive">
      <div className="visual">
        <div className="badge">Case · {c.idx}</div>
        <div className="client">{c.client}</div>
        <div className="placeholder">{c.glyph}</div>
      </div>
      <div className="body">
        <div className="role">{c.role} · {c.year}</div>
        <h3>{c.title}</h3>
        <div className="metrics">
          {c.metrics.map((m, i) => (
            <div className="metric" key={i}>
              <div className="v"><em>{m.v}</em></div>
              <div className="k">{m.k}</div>
            </div>
          ))}
        </div>
      </div>
    </article>
  );
}

function PolishedProcess() {
  const D = window.ARCLINE_DATA.process;
  const ref = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    if (!window.gsap || !ref.current) return;
    const ctx = gsap.context(() => {
      const wrap = ref.current.querySelector('.pin-wrap');
      const steps = ref.current.querySelectorAll('.step');
      const N = steps.length;

      ScrollTrigger.create({
        trigger: wrap,
        start: 'top top',
        end: 'bottom bottom',
        onUpdate: (self) => {
          const idx = Math.min(N - 1, Math.floor(self.progress * N));
          setActive(idx);
        },
      });
    }, ref);
    return () => ctx.revert();
  }, []);

  return (
    <section id="process" className="p-process" ref={ref}>
      <div className="pin-wrap">
        <div className="pin-inner">
          <div className="left">
            <div className="mono-label" style={{ marginBottom: 32 }}>
              <span className="slash">//</span>{D.eyebrow} · 04 steps
            </div>
            {D.steps.map((s, i) => (
              <div className={`step ${i === active ? 'active' : ''}`} key={i}>
                <h2><span className="step-num">{s.n}</span>{s.title}</h2>
                <p className="step-copy">{s.copy}</p>
              </div>
            ))}
            <div className="dots">
              {D.steps.map((_, i) => <div className={`dot ${i === active ? 'active' : ''}`} key={i} />)}
            </div>
          </div>
          <div className="right">
            {D.steps.map((s, i) => (
              <div className={`visual-frame ${i === active ? 'active' : ''}`} key={i}>
                <window.ProcessVisual kind={s.visual} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

window.PolishedCases = PolishedCases;
window.PolishedProcess = PolishedProcess;
