// Services. A list of "vehicles" with scroll-driven SINGLE-ACTIVE illumination:
// whichever row is closest to the viewport center is lit; the rest sit dim.
// Hovering overrides the scroll-pick while the mouse is inside the list.
const Vehicle = React.forwardRef(({ n, title, body }, ref) => (
  <div
    ref={ref}
    className="orx-vehicle"
    style={{
      position: 'relative',
      display: 'grid',
      gridTemplateColumns: '72px 1fr minmax(280px, 440px)',
      alignItems: 'baseline',
      gap: 40,
      padding: '40px 0',
      borderTop: '1px solid rgba(245,238,228,0.08)',
    }}
  >
    <div className="orx-vehicle__num" style={{
      fontFamily: "'Inter Tight', sans-serif",
      fontSize: 12, letterSpacing: '0.22em', textTransform: 'uppercase',
      fontWeight: 500,
      transition: 'color 480ms cubic-bezier(0.22,1,0.36,1)',
    }}>{n}</div>
    <h3 className="orx-vehicle__title" style={{
      fontFamily: "'Inter Tight', sans-serif",
      fontSize: 'clamp(32px, 4.2vw, 56px)',
      fontWeight: 400, letterSpacing: '-0.035em', lineHeight: 1.02,
      margin: 0, textWrap: 'pretty',
      transition: 'letter-spacing 480ms cubic-bezier(0.22,1,0.36,1), transform 480ms cubic-bezier(0.22,1,0.36,1)',
    }}>{title}</h3>
    <p className="orx-vehicle__body" style={{
      fontFamily: "'Inter Tight', sans-serif",
      fontSize: 15, lineHeight: 1.55, color: '#8A7F70', margin: 0,
      textWrap: 'pretty',
      transition: 'color 480ms cubic-bezier(0.22,1,0.36,1)',
    }}>{body}</p>
  </div>
));

const Systems = () => {
  const items = [
    {
      n: '01',
      title: 'Operating systems.',
      body: "The core the business runs on. Pipelines, routing, permissions, the surfaces leadership actually looks at. Built to fit the shape of the operation, not the other way around.",
    },
    {
      n: '02',
      title: 'Autonomous operators.',
      body: "Agentic layers that take entire workflows off human hands. They talk to each other, pick up where the last one stopped, and keep working while the team sleeps.",
    },
    {
      n: '03',
      title: 'Demand infrastructure.',
      body: "The machinery behind every growth motion. Outbound, inbound, creative, attribution. Quiet when it is working. Unmistakable when it is not.",
    },
    {
      n: '04',
      title: 'Brand identity.',
      body: "Mark, palette, voice, surface. A posture the whole company can stand behind, handed over with the keys and a system everyone can wield.",
    },
    {
      n: '05',
      title: 'Custom software.',
      body: "Only when the problem demands it. Built to slot into the stack that is already there, never to replace it for its own sake. Owned by you on day one.",
    },
    {
      n: '06',
      title: 'Business consulting.',
      body: "The work behind the work. Offer design, positioning, pricing, the levers an operator can pull to change the trajectory. Where the numbers come from before any build begins.",
    },
  ];

  const listRef = React.useRef(null);
  const rowsRef = React.useRef([]);
  const cursorRef = React.useRef({x: 0, y: 0, known: false});
  const [activeIdx, setActiveIdx] = React.useState(1);

  // Active row = whichever row currently sits under the cursor. If the cursor
  // is outside the list (or position unknown), fall back to the row closest
  // to the viewport center. Both scroll AND mousemove feed the same picker so
  // the active row tracks the cursor even when only the page is moving —
  // giving a glissando-like sweep across the list while you scroll.
  React.useEffect(() => {
    const pickFromCursor = () => {
      if (!cursorRef.current.known || !listRef.current) return -1;
      const { x, y } = cursorRef.current;
      const under = document.elementFromPoint(x, y);
      if (!under || !listRef.current.contains(under)) return -1;
      const wrap = under.closest('.orx-vehicle-wrap');
      if (!wrap) return -1;
      return rowsRef.current.findIndex((el) => el && wrap.contains(el));
    };
    const pickFromViewport = () => {
      const mid = window.innerHeight / 2;
      let best = 0;
      let bestDist = Infinity;
      rowsRef.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const c = r.top + r.height / 2;
        const d = Math.abs(c - mid);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      return best;
    };
    const pick = () => {
      const fromCursor = pickFromCursor();
      setActiveIdx(fromCursor >= 0 ? fromCursor : pickFromViewport());
    };
    const onMove = (e) => {
      cursorRef.current = {x: e.clientX, y: e.clientY, known: true};
      pick();
    };
    const onScroll = () => pick();
    const onResize = () => pick();
    pick();
    window.addEventListener('mousemove', onMove, { passive: true });
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  return (
    <section style={{padding: '128px 48px', background: '#0A0705'}}>
      <div style={{maxWidth: 1280, margin: '0 auto'}}>
        <div className="orx-reveal" style={{maxWidth: 960, marginBottom: 56}}>
          <div style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
            color: '#FFA566', marginBottom: 20,
          }}>Services</div>
          <h2 style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 'clamp(36px, 5vw, 72px)',
            fontWeight: 400, lineHeight: 1.0, letterSpacing: '-0.04em',
            color: '#FFFAF5', margin: 0, maxWidth: 960, textWrap: 'pretty',
          }}>
            Some of the <span style={{fontFamily: "'Instrument Serif', serif", fontStyle: 'italic'}}>vehicles.</span>
          </h2>
          <p style={{
            fontFamily: "'Inter Tight', sans-serif",
            fontSize: 17, lineHeight: 1.6, color: '#BFB3A2',
            margin: '28px 0 0', maxWidth: 760,
          }}>
            If it can be delivered digitally, we can do it.
          </p>
        </div>

        <div
          ref={listRef}
          className="orx-vehicle-list"
          style={{borderBottom: '1px solid rgba(245,238,228,0.08)'}}
        >
          {items.map((it, i) => (
            // See Philosophy for the rationale: reveal is on an outer
            // wrapper React never rewrites, so the inner dynamic className
            // (`is-active`) can update without wiping `is-revealed` and
            // making rows blink away on hover.
            <div key={it.n} className="orx-reveal">
              <div
                id={`service-${it.n}`}
                className={
                  'orx-vehicle-wrap'
                  + (activeIdx === i ? ' is-active' : '')
                }
              >
                <Vehicle
                  ref={(el) => (rowsRef.current[i] = el)}
                  n={it.n}
                  title={it.title}
                  body={it.body}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        .orx-vehicle .orx-vehicle__num   { color: #5C5246; }
        .orx-vehicle .orx-vehicle__title { color: #BFB3A2; }
        .orx-vehicle .orx-vehicle__body  { color: #5C5246; }

        /* Hover wins while cursor is in the list; otherwise scroll-pick wins. */
        .orx-vehicle-list:hover .orx-vehicle-wrap:hover .orx-vehicle,
        .orx-vehicle-wrap.is-active .orx-vehicle {
          background:
            linear-gradient(90deg, rgba(255,106,10,0.055) 0%, transparent 70%);
        }
        .orx-vehicle-list:hover .orx-vehicle-wrap:hover .orx-vehicle .orx-vehicle__num,
        .orx-vehicle-wrap.is-active .orx-vehicle .orx-vehicle__num    { color: #FFA566; }
        .orx-vehicle-list:hover .orx-vehicle-wrap:hover .orx-vehicle .orx-vehicle__title,
        .orx-vehicle-wrap.is-active .orx-vehicle .orx-vehicle__title  {
          color: #FFFAF5;
          letter-spacing: -0.04em;
          transform: translateX(4px);
        }
        .orx-vehicle-list:hover .orx-vehicle-wrap:hover .orx-vehicle .orx-vehicle__body,
        .orx-vehicle-wrap.is-active .orx-vehicle .orx-vehicle__body   { color: #BFB3A2; }

        @media (max-width: 900px) {
          .orx-vehicle {
            grid-template-columns: 1fr !important;
            gap: 12px !important;
          }
        }
      `}</style>
    </section>
  );
};

window.Systems = Systems;
window.Vehicle = Vehicle;
