/* global React, Tag, ArrowUpRight */
const { useState, useEffect, useRef, useCallback } = React;

// ============================================
// CASE SHOWCASE — Split 2-Column Smooth Scroll Showcase
// ============================================
function CaseShowcase() {
  const cases = window.CASE_STUDIES || [];
  const caseCount = cases.length;

  const [activeIndex, setActiveIndex] = useState(0);

  const trackRef = useRef(null);
  const mediaCardsRef = useRef([]);
  const textCardsRef = useRef([]);
  const activeIndexRef = useRef(0);
  const rafId = useRef(null);

  // Check prefers-reduced-motion
  const prefersReduced =
    typeof window !== "undefined" &&
    window.matchMedia &&
    window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  // Ultra-smooth frame update with direct DOM manipulation (Zero React renders on scroll!)
  const updateFrames = useCallback(
    (continuousProgress) => {
      const newActive = Math.max(
        0,
        Math.min(caseCount - 1, Math.round(continuousProgress))
      );

      // Only re-render React state when the active index changes (e.g. 0 -> 1)
      if (newActive !== activeIndexRef.current) {
        activeIndexRef.current = newActive;
        setActiveIndex(newActive);
      }

      for (let i = 0; i < caseCount; i++) {
        const mediaEl = mediaCardsRef.current[i];
        const textEl = textCardsRef.current[i];
        if (!mediaEl && !textEl) continue;

        const d = continuousProgress - i; // distance from current scroll position

        if (prefersReduced) {
          const isCurrent = i === newActive;
          if (mediaEl) {
            mediaEl.style.transform = "none";
            mediaEl.style.opacity = isCurrent ? "1" : "0";
            mediaEl.style.pointerEvents = isCurrent ? "auto" : "none";
            mediaEl.style.zIndex = isCurrent ? "10" : "1";
          }
          if (textEl) {
            textEl.style.transform = "none";
            textEl.style.opacity = isCurrent ? "1" : "0";
            textEl.style.pointerEvents = isCurrent ? "auto" : "none";
            textEl.style.zIndex = isCurrent ? "10" : "1";
          }
          continue;
        }

        let mediaTransform = "";
        let mediaOpacity = 0;
        let textTransform = "";
        let textOpacity = 0;
        let pointerEvents = "none";
        let zIndex = 1;

        if (d <= -1) {
          // Case is further down in the scroll track
          mediaTransform = "translate3d(0, 48px, 0) scale(0.94)";
          mediaOpacity = 0;
          textTransform = "translate3d(0, 24px, 0)";
          textOpacity = 0;
          pointerEvents = "none";
          zIndex = 1;
        } else if (d < 0) {
          // Case is entering from below as user scrolls down
          const t = d + 1; // 0 -> 1
          const mediaY = (1 - t) * 48;
          const mediaScale = 0.94 + 0.06 * t;
          mediaOpacity = Math.min(1, Math.max(0, t * 1.25));
          mediaTransform = `translate3d(0, ${mediaY.toFixed(2)}px, 0) scale(${mediaScale.toFixed(4)})`;

          const textY = (1 - t) * 28;
          textOpacity = Math.min(1, Math.max(0, (t - 0.15) / 0.85));
          textTransform = `translate3d(0, ${textY.toFixed(2)}px, 0)`;

          pointerEvents = t > 0.6 ? "auto" : "none";
          zIndex = 5 + Math.round(t * 5);
        } else if (d <= 1) {
          // Case is currently active and exiting upwards
          const mediaY = -28 * d;
          const mediaScale = 1 - 0.04 * d;
          mediaOpacity = Math.min(1, Math.max(0, 1 - d * 1.3));
          mediaTransform = `translate3d(0, ${mediaY.toFixed(2)}px, 0) scale(${mediaScale.toFixed(4)})`;

          const textY = -20 * d;
          textOpacity = Math.min(1, Math.max(0, 1 - d * 1.5));
          textTransform = `translate3d(0, ${textY.toFixed(2)}px, 0)`;

          pointerEvents = d < 0.4 ? "auto" : "none";
          zIndex = 10 - Math.round(d * 4);
        } else {
          // Case is passed and further up
          mediaTransform = "translate3d(0, -32px, 0) scale(0.96)";
          mediaOpacity = 0;
          textTransform = "translate3d(0, -20px, 0)";
          textOpacity = 0;
          pointerEvents = "none";
          zIndex = 1;
        }

        if (mediaEl) {
          mediaEl.style.transform = mediaTransform;
          mediaEl.style.opacity = mediaOpacity.toFixed(3);
          mediaEl.style.pointerEvents = pointerEvents;
          mediaEl.style.zIndex = zIndex;

          // Video playback optimization: play when in view, pause when off-screen
          const videoEl = mediaEl.querySelector("video");
          if (videoEl) {
            if (Math.abs(d) < 0.85) {
              if (videoEl.paused) videoEl.play().catch(() => {});
            } else {
              if (!videoEl.paused) videoEl.pause();
            }
          }
        }

        if (textEl) {
          textEl.style.transform = textTransform;
          textEl.style.opacity = textOpacity.toFixed(3);
          textEl.style.pointerEvents = pointerEvents;
          textEl.style.zIndex = zIndex;
        }
      }
    },
    [caseCount, prefersReduced]
  );

  // Scroll event listener (passive, rAF-throttled, zero React re-renders)
  useEffect(() => {
    if (caseCount <= 1) return;

    const handleScroll = () => {
      if (rafId.current) return;
      rafId.current = requestAnimationFrame(() => {
        rafId.current = null;
        if (!trackRef.current) return;

        const rect = trackRef.current.getBoundingClientRect();
        const trackTop = window.scrollY + rect.top;
        const trackHeight = rect.height;
        const winH = window.innerHeight;
        const maxScroll = trackHeight - winH;

        if (maxScroll <= 0) {
          updateFrames(0);
          return;
        }

        const currentScroll = window.scrollY - trackTop;
        const rawProgress = Math.max(0, Math.min(1, currentScroll / maxScroll));
        const continuousProgress = rawProgress * (caseCount - 1);
        updateFrames(continuousProgress);
      });
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("resize", handleScroll, { passive: true });
    handleScroll();

    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleScroll);
      if (rafId.current) cancelAnimationFrame(rafId.current);
    };
  }, [caseCount, updateFrames]);

  // Smooth scroll navigation to target case
  const scrollToCase = (targetIndex) => {
    if (!trackRef.current) return;
    const clampedIndex = Math.max(0, Math.min(caseCount - 1, targetIndex));
    const rect = trackRef.current.getBoundingClientRect();
    const trackTop = window.scrollY + rect.top;
    const trackHeight = rect.height;
    const winH = window.innerHeight;
    const maxScroll = trackHeight - winH;

    const targetScroll =
      trackTop + (clampedIndex / (caseCount - 1)) * maxScroll;
    window.scrollTo({ top: targetScroll, behavior: "smooth" });
  };

  // Keyboard navigation when section is in viewport
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (!trackRef.current) return;
      const rect = trackRef.current.getBoundingClientRect();
      const inView = rect.top < window.innerHeight && rect.bottom > 0;
      if (!inView) return;

      if (e.key === "ArrowRight" || e.key === "ArrowDown") {
        if (activeIndexRef.current < caseCount - 1) {
          e.preventDefault();
          scrollToCase(activeIndexRef.current + 1);
        }
      } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
        if (activeIndexRef.current > 0) {
          e.preventDefault();
          scrollToCase(activeIndexRef.current - 1);
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [caseCount]);

  // Track height based on case count (50vh per case study for snappy, responsive feel)
  const trackHeightStyle = {
    height: `calc(100vh + ${(caseCount - 1) * 50}vh)`,
  };

  return (
    <section id="work" className="showcase-track" ref={trackRef} style={trackHeightStyle}>
      <div className="showcase-sticky">
        <div className="container showcase-container">
          
          {/* Header */}
          <div className="showcase-header">
            <div>
              <div className="t-eyebrow section__eyebrow">Selected work · 2022 — 2026</div>
              <h2 className="t-h2 section__title" style={{ margin: 0 }}>Five projects I'm proud of.</h2>
            </div>
            <div className="showcase-header__counter">
              0{activeIndex + 1} <span style={{ opacity: 0.35 }}>/</span> 0{caseCount}
            </div>
          </div>

          {/* 2-Column Split Layout (>50% Left Media, Right Info + Nav) */}
          <div className="showcase-layout">
            
            {/* Left Column: Media Stage (>50% width, aspect ratio 16:10) */}
            <div className="showcase-media-stage">
              {cases.map((c, i) => {
                const isVideo =
                  c.cover?.type === "video" ||
                  (c.cover?.src && c.cover.src.endsWith(".webm"));

                return (
                  <a
                    key={c.id}
                    href={c.href}
                    ref={(el) => (mediaCardsRef.current[i] = el)}
                    className="showcase-media-card"
                    tabIndex={i === activeIndex ? 0 : -1}
                    onClick={() =>
                      window.track &&
                      window.track("case_study_click", {
                        case_id: c.id,
                        case_title: c.title,
                      })
                    }
                    aria-label={`View case study: ${c.title}`}
                  >
                    <div className="showcase-media-frame">
                      {isVideo ? (
                        <video
                          src={c.cover.src}
                          autoPlay
                          loop
                          muted
                          playsInline
                          className="showcase-media"
                        />
                      ) : (
                        <img
                          src={c.cover?.src || "images/case-WNS/cover.png"}
                          alt={c.title}
                          className="showcase-media"
                          loading="eager"
                        />
                      )}
                    </div>

                    <div className="showcase-media-badge-row">
                      <span className="showcase-media-num">{c.num}</span>
                      <span className="showcase-media-client">{c.client}</span>
                    </div>
                  </a>
                );
              })}
            </div>

            {/* Right Column: Case Info + Bottom-Right Dot Navigation */}
            <div className="showcase-info-col">
              
              {/* Text Stage (Transitioning info blocks) */}
              <div className="showcase-text-stage">
                {cases.map((c, i) => (
                  <div
                    key={c.id}
                    ref={(el) => (textCardsRef.current[i] = el)}
                    className="showcase-text-card"
                  >
                    <div className="showcase-text-card__tags">
                      {c.tags.map((t) => (
                        <Tag key={t} variant="plain">{t}</Tag>
                      ))}
                    </div>

                    <h3 className="showcase-text-card__title">
                      <a href={c.href} className="showcase-title-link">
                        {c.title}
                      </a>
                    </h3>

                    <p className="showcase-text-card__desc">{c.desc}</p>

                    {c.impact && (
                      <div className="showcase-text-card__impact">
                        <span className="showcase-impact-arrow">→</span>
                        <span className="showcase-impact-text">{c.impact}</span>
                      </div>
                    )}

                    <div className="showcase-text-card__cta-wrap">
                      <a
                        href={c.href}
                        className="btn btn--secondary btn--md showcase-cta-btn"
                        onClick={() =>
                          window.track &&
                          window.track("case_study_click", {
                            case_id: c.id,
                            case_title: c.title,
                          })
                        }
                      >
                        <span>Read case study</span>
                        <ArrowUpRight size={16} />
                      </a>
                    </div>
                  </div>
                ))}
              </div>

              {/* Bottom Row: Dot Navigation Aligned to Right */}
              <div className="showcase-info-footer">
                <nav className="showcase-nav showcase-nav--right" aria-label="Case studies navigation">
                  <button
                    type="button"
                    className="showcase-nav__btn"
                    onClick={() => scrollToCase(activeIndex - 1)}
                    disabled={activeIndex === 0}
                    aria-label="Previous case study"
                  >
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                      <path d="M19 12H5M5 12L12 19M5 12L12 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>

                  <div className="showcase-nav__dots" role="tablist">
                    {cases.map((c, i) => (
                      <button
                        key={c.id}
                        type="button"
                        role="tab"
                        aria-selected={i === activeIndex}
                        aria-label={`Go to case ${c.num}: ${c.shortTitle || c.title}`}
                        className={"showcase-nav__dot " + (i === activeIndex ? "showcase-nav__dot--active" : "")}
                        onClick={() => scrollToCase(i)}
                      />
                    ))}
                  </div>

                  <button
                    type="button"
                    className="showcase-nav__btn"
                    onClick={() => scrollToCase(activeIndex + 1)}
                    disabled={activeIndex === caseCount - 1}
                    aria-label="Next case study"
                  >
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                      <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                </nav>
              </div>

            </div>

          </div>

        </div>
      </div>
    </section>
  );
}

window.CaseShowcase = CaseShowcase;
