// Industries marquee. Two rows of pills scrolling in opposite directions.
// Each row has exactly ONE accented pill at a time:
//   - Row 1 default accent: SOFTWARE
//   - Row 2 default accent: REAL ESTATE
// Hovering any pill moves the accent to the hovered one (for that row only)
// and restores the default when the cursor leaves.
const Marquee = () => {
  const row1 = [
    'REAL ESTATE', 'INSURANCE', 'MORTGAGE', 'COMMERCIAL', 'SOFTWARE', 'EVENTS',
    'FINTECH',     'MEDIA',     'LOGISTICS', 'SAAS',       'LEGAL',    'EDUCATION',
  ];
  const row2 = [
    'HOME SERVICES', 'F&B',         'CONSTRUCTION', 'REAL ESTATE', 'CREATOR',    'FITNESS',
    'HOSPITALITY',   'AUTOMOTIVE',  'WELLNESS',     'RETAIL',      'GOVERNMENT', 'HEALTHCARE',
  ];

  const ROW1_DEFAULT = row1.indexOf('SOFTWARE');   // top-row default accent
  const ROW2_DEFAULT = row2.indexOf('REAL ESTATE');// bottom-row default accent

  const pillBase = {
    display: 'inline-flex', alignItems: 'center',
    padding: '14px 28px',
    borderRadius: 999,
    fontFamily: "'Inter Tight', sans-serif",
    fontSize: 18,
    letterSpacing: '0.12em',
    fontWeight: 500,
    whiteSpace: 'nowrap',
    flexShrink: 0,
    cursor: 'default',
    transition: 'background 320ms ease, color 320ms ease, border-color 320ms ease, box-shadow 320ms ease',
  };
  const pillDark = {
    ...pillBase,
    background: 'rgba(245, 238, 228, 0.04)',
    color: '#E8DDCC',
    border: '1px solid rgba(245, 238, 228, 0.08)',
    boxShadow: 'inset 0 1px 0 rgba(245, 238, 228, 0.05)',
  };
  const pillAccent = {
    ...pillBase,
    background: 'linear-gradient(180deg, rgba(255,106,10,0.14) 0%, rgba(255,106,10,0.06) 100%)',
    color: '#FFB380',
    border: '1px solid rgba(255, 106, 10, 0.28)',
    boxShadow: 'inset 0 1px 0 rgba(255, 200, 150, 0.18), 0 0 24px rgba(255, 106, 10, 0.08)',
  };

  const Row = ({ items, defaultIdx, reverse = false, duration = 60 }) => {
    const [activeBaseIdx, setActiveBaseIdx] = React.useState(defaultIdx);
    const trackRef = React.useRef(null);
    // JS-driven animation state: offset in px, current velocity (px/ms),
    // and the "idle" base velocity the row naturally drifts at. Touch
    // overrides the offset directly and spikes the velocity on release
    // so a flick briefly accelerates the row before it decays back to
    // the base pace.
    const offsetRef = React.useRef(0);
    const velRef = React.useRef(0);
    const baseVelRef = React.useRef(0);
    const halfRef = React.useRef(0);
    const dragRef = React.useRef({
      active: false,
      startX: 0, startOffset: 0,
      lastX: 0, lastT: 0, vel: 0,
    });

    React.useEffect(() => {
      const track = trackRef.current;
      if (!track) return;
      const measure = () => {
        halfRef.current = track.scrollWidth / 2;
        const base = halfRef.current / (duration * 1000);
        baseVelRef.current = reverse ? base : -base;
        if (!dragRef.current.active) velRef.current = baseVelRef.current;
        if (offsetRef.current === 0 && reverse) {
          offsetRef.current = -halfRef.current;
        }
      };
      measure();
      const onResize = () => measure();
      window.addEventListener('resize', onResize);

      let last = 0;
      let raf = 0;
      const tick = (t) => {
        if (!last) last = t;
        const dt = Math.min(t - last, 64);
        last = t;
        if (!dragRef.current.active && halfRef.current > 0) {
          // Exponential decay toward base velocity — a flick boosts
          // velRef, then it eases back to baseVel over ~1s.
          velRef.current += (baseVelRef.current - velRef.current) * 0.06;
          offsetRef.current += velRef.current * dt;
          // Keep offset in a canonical [-half, 0] range so the doubled
          // content tiles seamlessly.
          while (offsetRef.current > 0)
            offsetRef.current -= halfRef.current;
          while (offsetRef.current < -halfRef.current)
            offsetRef.current += halfRef.current;
          track.style.transform = `translate3d(${offsetRef.current}px, 0, 0)`;
        }
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => {
        cancelAnimationFrame(raf);
        window.removeEventListener('resize', onResize);
      };
    }, [duration, reverse]);

    const onTouchStart = (e) => {
      const t = e.touches[0];
      dragRef.current = {
        active: true,
        startX: t.clientX,
        startOffset: offsetRef.current,
        lastX: t.clientX,
        lastT: performance.now(),
        vel: 0,
      };
    };
    const onTouchMove = (e) => {
      const d = dragRef.current;
      if (!d.active) return;
      const t = e.touches[0];
      const now = performance.now();
      const dtMove = now - d.lastT;
      const delta = t.clientX - d.startX;
      offsetRef.current = d.startOffset + delta;
      while (offsetRef.current > 0)
        offsetRef.current -= halfRef.current;
      while (offsetRef.current < -halfRef.current)
        offsetRef.current += halfRef.current;
      trackRef.current.style.transform = `translate3d(${offsetRef.current}px, 0, 0)`;
      if (dtMove > 0) d.vel = (t.clientX - d.lastX) / dtMove;
      d.lastX = t.clientX;
      d.lastT = now;
    };
    const onTouchEnd = () => {
      const d = dragRef.current;
      // Inject the finger's release velocity (px/ms) into the loop.
      // The RAF decay then smoothly brings it back to base over ~1s.
      velRef.current = d.vel;
      d.active = false;
    };

    const doubled = [...items, ...items];
    return (
      <div
        onTouchStart={onTouchStart}
        onTouchMove={onTouchMove}
        onTouchEnd={onTouchEnd}
        onTouchCancel={onTouchEnd}
        style={{
          overflow: 'hidden',
          maskImage: 'linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%)',
          WebkitMaskImage: 'linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%)',
          touchAction: 'pan-y',
        }}>
        <div
          ref={trackRef}
          className="orx-marquee-track"
          style={{
            display: 'flex', gap: 14, width: 'max-content',
            willChange: 'transform',
          }}
        >
          {doubled.map((label, i) => {
            const baseIdx = i % items.length;
            const isAccent = baseIdx === activeBaseIdx;
            return (
              <span
                key={i}
                className="orx-pill"
                style={isAccent ? pillAccent : pillDark}
                onMouseEnter={() => setActiveBaseIdx(baseIdx)}
              >{label}</span>
            );
          })}
        </div>
      </div>
    );
  };

  return (
    <section className="orx-marquee-section" style={{
      padding: '20px 0',
      background: '#0A0705',
      position: 'relative',
    }}>
      <div style={{display:'flex', flexDirection:'column', gap: 16}}>
        <Row items={row1} defaultIdx={ROW1_DEFAULT} duration={58}/>
        <Row items={row2} defaultIdx={ROW2_DEFAULT} reverse duration={72}/>
      </div>
      <style>{`
        @keyframes orx-marquee-l {
          0%   { transform: translateX(0); }
          100% { transform: translateX(-50%); }
        }
        @keyframes orx-marquee-r {
          0%   { transform: translateX(-50%); }
          100% { transform: translateX(0); }
        }
        .orx-marquee-track:hover { animation-play-state: paused; }

        /* Hold the pills invisible until the hero load sequence has fully
           triggered, then dissolve in slowly so the scrolling industries
           never compete with the hero's opening moment. */
        .orx-marquee-section {
          opacity: 0;
          animation: orx-marquee-reveal 3200ms cubic-bezier(0.22, 1, 0.36, 1) 2000ms forwards;
        }
        @keyframes orx-marquee-reveal {
          0%   { opacity: 0; filter: blur(6px); }
          100% { opacity: 1; filter: blur(0); }
        }

        /* Mobile: halve pill scale so the marquee reads as an ambient
           strip rather than a bold headline. Smaller font, tighter
           padding, and tighter gap between the two rows. */
        @media (max-width: 720px) {
          .orx-pill {
            padding: 7px 14px !important;
            font-size: 12px !important;
            letter-spacing: 0.1em !important;
          }
          .orx-marquee-track {
            gap: 8px !important;
          }
          .orx-marquee-section > div {
            gap: 8px !important;
          }
        }
      `}</style>
    </section>
  );
};

window.Marquee = Marquee;
