// Work — horizontal scrolling section, one row per company

const { useRef, useEffect, useState } = React;

const COMPANIES = [
  {
    id: 'roblox',
    name: 'Roblox',
    year: '2022 — Now',
    role: 'Senior Product Design Manager',
    tint: 'var(--blue)',
    projects: [
      { name: 'Discovery', note: 'Powering how players discover, evaluate, and join games across home, details pages, search, and events.', href: '#' },
      { name: 'Design Systems', note: 'Leading components, patterns, and templates.', href: '#' },
      { name: 'Hack Week', note: 'Won 1st place out of 600 teams. Built a new way for users to spectate live games before joining.', href: '#' },
      { name: 'Design Summit', note: 'Spearheaded our annual conference to share inspiration with internal and external speakers.', href: '#' },
    ],
  },
  {
    id: 'google',
    name: 'Google',
    year: '2022',
    role: 'Senior Interaction Designer',
    tint: 'var(--blue)',
    projects: [
      { name: 'App Ads', note: 'Led gaming, retail, and emerging verticals for app ads.', href: '#' },
    ],
  },
  {
    id: 'meta',
    name: 'Meta',
    year: '2020 — 2022',
    role: 'Senior Product Designer',
    tint: 'var(--blue)',
    projects: [
      { name: 'Avatar System', note: 'Led cross-platform Avatar experiences and editing systems across Meta’s Family of Apps. Launched new 3D Avatars and Avatar Store.', href: '#' },
      { name: 'Reality Labs', note: 'Built social, onboarding, identity, and privacy products for Oculus, empowering people to connect in VR.', href: '#' },
    ],
  },
  {
    id: 'adobe',
    name: 'Adobe',
    year: '2017 — 2020',
    role: 'Experience Designer',
    tint: 'var(--blue)',
    projects: [
      { name: 'Photoshop Camera', note: 'Designed the 0-to-1 mobile app for real-time creative effects, powered by AI.', href: '#' },
      { name: 'Patents', note: 'Granted two patents for context-aware camera interactions.', href: '#' },
    ],
  },
];

function Work({ scrollMode = 'pin-pan' }) {
  const scrollerRef = useRef(null);
  const pinOuterRef = useRef(null);
  const pinViewportRef = useRef(null);
  const trackRef = useRef(null);
  const [progress, setProgress] = useState(0);

  // smart-hijack: progress tracks native scrollLeft on .work-scroller
  useEffect(() => {
    if (scrollMode !== 'smart-hijack') return;
    const el = scrollerRef.current;
    if (!el) return;
    const onScroll = () => {
      const max = el.scrollWidth - el.clientWidth;
      setProgress(max > 0 ? el.scrollLeft / max : 0);
    };
    onScroll();
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [scrollMode]);

  // smart-hijack: convert vertical wheel to horizontal, with flick/burst/fast bypass
  useEffect(() => {
    if (scrollMode !== 'smart-hijack') return;
    const el = scrollerRef.current;
    if (!el) return;
    let last = 0;
    const recent = [];
    const onWheel = (e) => {
      const now = performance.now();
      const idle = now - last;
      last = now;
      recent.push(Math.abs(e.deltaY));
      if (recent.length > 5) recent.shift();
      const mean = recent.reduce((a, b) => a + b, 0) / recent.length;

      const flick = Math.abs(e.deltaY) >= 80;
      const burst = idle >= 180 && Math.abs(e.deltaY) >= 40;
      const fast = mean > 55;
      if (flick || burst || fast) return;

      const maxLeft = el.scrollWidth - el.clientWidth;
      const atStart = el.scrollLeft <= 0;
      const atEnd = el.scrollLeft >= maxLeft - 1;
      const down = e.deltaY > 0;
      if ((down && !atEnd) || (!down && !atStart)) {
        e.preventDefault();
        el.scrollLeft += e.deltaY;
      }
    };
    el.addEventListener('wheel', onWheel, { passive: false });
    return () => el.removeEventListener('wheel', onWheel);
  }, [scrollMode]);

  // pin-pan mobile: native horizontal swipe on the viewport drives the
  // progress bar. Desktop pin-pan uses window scroll instead (effect below).
  useEffect(() => {
    if (scrollMode !== 'pin-pan') return;
    if (window.matchMedia('(min-width: 861px)').matches) return;
    const el = pinViewportRef.current;
    if (!el) return;
    const onScroll = () => {
      const max = el.scrollWidth - el.clientWidth;
      setProgress(max > 0 ? el.scrollLeft / max : 0);
    };
    onScroll();
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [scrollMode]);

  // pin-pan: sticky section, translate track as the window scrolls through it
  useEffect(() => {
    if (scrollMode !== 'pin-pan') return;
    if (!window.matchMedia('(min-width: 861px)').matches) return;
    const outer = pinOuterRef.current;
    const track = trackRef.current;
    if (!outer || !track) return;

    let pan = 0;

    const recompute = () => {
      pan = Math.max(0, track.scrollWidth - window.innerWidth);
      outer.style.height = (window.innerHeight + pan) + 'px';
    };
    const onScroll = () => {
      const top = outer.getBoundingClientRect().top;
      const p = Math.min(1, Math.max(0, -top / Math.max(1, pan)));
      track.style.transform = `translate3d(${-p * pan}px,0,0)`;
      setProgress(p);
    };

    const ro = new ResizeObserver(() => { recompute(); onScroll(); });
    ro.observe(track);
    window.addEventListener('resize', recompute);
    window.addEventListener('scroll', onScroll, { passive: true });
    recompute();
    onScroll();

    return () => {
      ro.disconnect();
      window.removeEventListener('resize', recompute);
      window.removeEventListener('scroll', onScroll);
      // reset inline styles when switching modes so the fallback layout is clean
      outer.style.height = '';
      track.style.transform = '';
    };
  }, [scrollMode]);

  const header = (
    <header className="work-header">
      <div className="work-header-right">
        <span className="label">Scroll horizontally →</span>
        <div className="progress">
          <div className="progress-bar" style={{ transform: `scaleX(${progress})` }} />
        </div>
      </div>
    </header>
  );

  return (
    <section className="work" id="experience" data-screen-label="02 Work" data-scroll-mode={scrollMode}>
      {scrollMode === 'pin-pan' ? (
        <div className="work-pin-outer" ref={pinOuterRef}>
          <div className="work-pin-inner">
            {header}
            <div className="work-pin-viewport" ref={pinViewportRef}>
              <div className="work-track" ref={trackRef}>
                {COMPANIES.map((c, i) => (
                  <CompanyBlock key={c.id} company={c} index={i} />
                ))}
              </div>
            </div>
          </div>
        </div>
      ) : (
        <>
          {header}
          <div className="work-scroller" ref={scrollerRef}>
            <div className="work-track" ref={trackRef}>
              {COMPANIES.map((c, i) => (
                <CompanyBlock key={c.id} company={c} index={i} />
              ))}
            </div>
          </div>
        </>
      )}
    </section>
  );
}

function CompanyBlock({ company, index }) {
  return (
    <article className="company" style={{ '--tint': company.tint }}>
      <div className="company-meta">
        <div className="company-index">0{index + 1}</div>
        <div className="company-stack">
          <div className="company-year">{company.year}</div>
          <div className="company-role">{company.role}</div>
        </div>
      </div>

      <h2 className="company-name">{company.name}</h2>

      <ul className="project-list">
        {company.projects.map((p) => (
          <ProjectRow key={p.name} project={p} tint={company.tint} />
        ))}
      </ul>
    </article>
  );
}

function ProjectRow({ project, tint }) {
  return (
    <li className="project-row">
      <div className="project-link">
        <span className="project-name">{project.name}</span>
        <span className="project-note">{project.note}</span>
      </div>
    </li>
  );
}

window.Work = Work;
