/* Marquee Section - scroll-driven horizontal rows */
const MARQUEE_VIDEOS = [
  "assets/marquee/CallinAI Website.mp4",
  "assets/marquee/Aurora Demo.mp4",
  "assets/marquee/CallinAI Design.mp4",
  "assets/marquee/Abbu Website.mp4",
  "assets/marquee/UniTok Demo.mp4",
  "assets/marquee/EcoBill Mobile App.mp4",
  "assets/marquee/EcoBill Site Design.mp4",
  "assets/marquee/Etmaam Website.mp4",
  "assets/marquee/UniTok Video.mp4",
];

const VIDEO_TO_PROJECT = {
  "CallinAI Website": "callinai",
  "Aurora Demo": "aurora",
  "CallinAI Design": "callinai",
  "Abbu Website": "abbu",
  "UniTok Demo": "unitok",
  "EcoBill Mobile App": "ecobill",
  "EcoBill Site Design": "ecobill",
  "Etmaam Website": "etmaam",
  "UniTok Video": "unitok",
};

function getCardSize() {
  const w = window.innerWidth;
  if (w < 480) return { cardW: 190, cardH: 122 };
  if (w < 640) return { cardW: 240, cardH: 154 };
  return { cardW: 420, cardH: 270 };
}

/* Lazy video card — loads src only when scrolled into view, unloads on exit */
function LazyVideoCard({ src, visible }) {
  const videoRef = React.useRef(null);
  const loadedRef = React.useRef(false);
  const [ready, setReady] = React.useState(false);

  React.useEffect(() => {
    const el = videoRef.current;
    if (!el) return;

    if (visible && !loadedRef.current) {
      loadedRef.current = true;
      el.src = src;
      el.load();
      el.play().catch(() => {});
      el.addEventListener('canplay', () => setReady(true), { once: true });
    }

    if (!visible && loadedRef.current) {
      el.pause();
      el.removeAttribute('src');
      el.load();
      loadedRef.current = false;
      setReady(false);
    }
  }, [visible, src]);

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%' }}>
      {!ready && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(90deg, #111 25%, #1c1c1c 50%, #111 75%)',
          backgroundSize: '200% 100%',
          animation: 'skeleton-shimmer 1.8s infinite linear',
        }} />
      )}
      <video
        ref={videoRef}
        autoPlay
        loop
        muted
        playsInline
        preload="none"
        style={{
          width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center',
          opacity: ready ? 1 : 0,
          transition: 'opacity 0.7s ease-in-out',
        }}
      />
    </div>
  );
}

function MarqueeRow({ images: videos, direction = 1 }) {
  const rowRef = React.useRef(null);
  const sectionRef = React.useContext(MarqueeCtx);
  const offsetRef = React.useRef(0);
  const rafRef = React.useRef(null);
  const [cardSize, setCardSize] = React.useState(getCardSize);
  const visibleSetRef = React.useRef(new Set());
  const [visibleKeys, setVisibleKeys] = React.useState(() => new Set());

  React.useEffect(() => {
    const onResize = () => setCardSize(getCardSize());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  React.useEffect(() => {
    const GAP = 12;
    const totalW = cardSize.cardW + GAP;
    const startX = direction > 0 ? -(cardSize.cardW * 1.5) : 0;
    const tripledLen = videos.length * 3;

    const tick = () => {
      const x = (direction > 0 ? offsetRef.current : -offsetRef.current) + startX;

      // Apply transform directly — zero React re-renders on scroll
      if (rowRef.current) {
        rowRef.current.style.transform = `translateX(${x}px)`;
      }

      // Recompute visibility and only setState when something changes
      const visibleStart = -(cardSize.cardW + 200);
      const visibleEnd = window.innerWidth + 200;
      const next = new Set();
      for (let i = 0; i < tripledLen; i++) {
        const cardX = x + i * totalW;
        if (cardX > visibleStart && cardX < visibleEnd) next.add(i);
      }
      const prev = visibleSetRef.current;
      const changed = next.size !== prev.size || [...next].some(k => !prev.has(k));
      if (changed) {
        visibleSetRef.current = next;
        setVisibleKeys(new Set(next));
      }

      rafRef.current = requestAnimationFrame(tick);
    };

    const onScroll = () => {
      const section = sectionRef.current;
      if (!section) return;
      const sectionTop = section.getBoundingClientRect().top + window.scrollY;
      const raw = (window.scrollY - sectionTop + window.innerHeight) * 0.5;
      offsetRef.current = raw - 200;
    };

    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    rafRef.current = requestAnimationFrame(tick);

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(rafRef.current);
    };
  }, [cardSize, direction, videos]);

  const tripled = [...videos, ...videos, ...videos];

  return (
    <div className="overflow-hidden w-full">
      <div
        ref={rowRef}
        className="flex gap-3"
        style={{ willChange: 'transform' }}
      >
        {tripled.map((src, i) => {
          const filename = src.split('/').pop().replace('.mp4', '');
          const label = filename.split(' ')[0];
          const projectId = VIDEO_TO_PROJECT[filename];
          const isVisible = visibleKeys.has(i);

          return (
            <div
              key={i}
              className="shrink-0 rounded-2xl overflow-hidden bg-[#111] relative group cursor-pointer"
              style={{ width: cardSize.cardW, height: cardSize.cardH }}
              onClick={() => projectId && (window.location.href = `project.html#${projectId}`)}
            >
              <LazyVideoCard src={src} visible={isVisible} />
              <div
                className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                style={{ background: 'rgba(0,0,0,0.45)' }}
              >
                <span
                  className="text-white font-semibold tracking-widest uppercase"
                  style={{ fontSize: 'clamp(1rem, 2.5vw, 1.4rem)', fontFamily: 'Kanit, sans-serif', letterSpacing: '0.15em' }}
                >
                  {label}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

const MarqueeCtx = React.createContext(null);

function MarqueeSection() {
  const sectionRef = React.useRef(null);
  const row1 = MARQUEE_VIDEOS.slice(0, 5);
  const row2 = MARQUEE_VIDEOS.slice(5);

  return (
    <MarqueeCtx.Provider value={sectionRef}>
      <section
        ref={sectionRef}
        className="bg-[#0C0C0C] pt-24 sm:pt-32 md:pt-40 pb-10 flex flex-col gap-3"
        style={{ overflowX: 'clip' }}
      >
        <MarqueeRow images={row1} direction={1} />
        <MarqueeRow images={row2} direction={-1} />
      </section>
    </MarqueeCtx.Provider>
  );
}

Object.assign(window, { MarqueeSection });
