/* Services Section - white background */
const TECH_STACK = [
  { name: "Flutter",     icon: "assets/icons/tech-stack/flutter.svg" },
  { name: "Django",      icon: "assets/icons/tech-stack/django.svg" },
  { name: "React",       icon: "assets/icons/tech-stack/react.svg" },
  { name: "Python",      icon: "assets/icons/tech-stack/python.svg" },
  { name: "Spring Boot", icon: "assets/icons/tech-stack/springboot.svg" },
  { name: "Laravel",     icon: "assets/icons/tech-stack/laravel.svg" },
  { name: "PostgreSQL",  icon: "assets/icons/tech-stack/postgresql.svg" },
  { name: "Docker",      icon: "assets/icons/tech-stack/docker.svg" },
  { name: "AWS",         icon: "assets/icons/tech-stack/amazonaws.svg" },
  { name: "Railway",     icon: "assets/icons/tech-stack/railway.svg" },
  { name: "GitHub",      icon: "assets/icons/tech-stack/github.svg" },
  { name: "OpenJDK",     icon: "assets/icons/tech-stack/openjdk.svg" },
  { name: "Postman",     icon: "assets/icons/tech-stack/postman.svg" },
  { name: "Figma",       icon: "assets/icons/tech-stack/figma.svg" },
  { name: "Jira",        icon: "assets/icons/tech-stack/jira.svg" },
  { name: "Vercel",      icon: "assets/icons/tech-stack/vercel.svg" },
];

/* Triplicate for seamless infinite scroll with no gaps */
const COL_LEFT  = [...TECH_STACK.slice(0, 8),  ...TECH_STACK.slice(0, 8),  ...TECH_STACK.slice(0, 8)];
const COL_RIGHT = [...TECH_STACK.slice(7),      ...TECH_STACK.slice(7),      ...TECH_STACK.slice(7)];

function TechCard({ item }) {
  return (
    <div
      className="flex flex-col items-center gap-2 py-3 px-2"
    >
      <div
        className="w-14 h-14 rounded-2xl flex items-center justify-center"
        style={{ background: "rgba(12,12,12,0.06)" }}
      >
        <img
          src={item.icon}
          alt={item.name}
          className="w-8 h-8 object-contain"
        />
      </div>
      <span
        className="text-[#0C0C0C] font-light text-center leading-tight"
        style={{ fontSize: "0.65rem", opacity: 0.45 }}
      >
        {item.name}
      </span>
    </div>
  );
}

function HorizontalTechRow({ items, speed = 0.6 }) {
  const ref = React.useRef(null);
  const animRef = React.useRef(null);
  const pos = React.useRef(0);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const tick = () => {
      const third = el.scrollWidth / 2;
      pos.current -= speed;
      if (Math.abs(pos.current) >= third) pos.current = 0;
      el.style.transform = `translateX(${pos.current}px)`;
      animRef.current = requestAnimationFrame(tick);
    };
    animRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(animRef.current);
  }, [speed]);

  const doubled = [...items, ...items];

  return (
    <div
      style={{
        overflow: "hidden",
        maskImage: "linear-gradient(to right, transparent, black 10%, black 90%, transparent)",
        WebkitMaskImage: "linear-gradient(to right, transparent, black 10%, black 90%, transparent)",
      }}
    >
      <div ref={ref} className="flex" style={{ willChange: "transform", width: "max-content" }}>
        {doubled.map((item, i) => (
          <TechCard key={i} item={item} />
        ))}
      </div>
    </div>
  );
}

function InfiniteColumn({ items, direction, speed }) {
  const ref = React.useRef(null);
  const animRef = React.useRef(null);
  const pos = React.useRef(0);
  const paused = React.useRef(false);

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

    /* start the down column pre-scrolled so content fills from the top */
    if (direction === "down") {
      const third = el.scrollHeight / 3;
      pos.current = -third;
    }

    const tick = () => {
      if (!paused.current) {
        const third = el.scrollHeight / 3;
        if (direction === "up") {
          pos.current -= speed;
          if (Math.abs(pos.current) >= third) pos.current = 0;
        } else {
          pos.current += speed;
          if (pos.current >= 0) pos.current = -third;
        }
        el.style.transform = `translateY(${pos.current}px)`;
      }
      animRef.current = requestAnimationFrame(tick);
    };

    animRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(animRef.current);
  }, [direction, speed]);

  return (
    <div
      style={{ overflow: "hidden", position: "absolute", inset: 0 }}
      onMouseEnter={() => (paused.current = true)}
      onMouseLeave={() => (paused.current = false)}
    >
      {/* fade top */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 80,
        background: "linear-gradient(to bottom, white, transparent)",
        zIndex: 2, pointerEvents: "none"
      }} />
      {/* fade bottom */}
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0, height: 80,
        background: "linear-gradient(to top, white, transparent)",
        zIndex: 2, pointerEvents: "none"
      }} />
      <div ref={ref} style={{ willChange: "transform" }}>
        {items.map((item, i) => (
          <TechCard key={i} item={item} />
        ))}
      </div>
    </div>
  );
}

const SERVICES = [
  {
    n: "01",
    name: "Backend Engineering",
    desc: "Production-grade REST APIs using Django REST Framework, Laravel, and Spring Boot. Built and documented systems serving real users with full validation and Postman test suites.",
  },
  {
    n: "02",
    name: "Mobile Development",
    desc: "Cross-platform mobile apps built with Flutter — shipped to iOS, Android, and Huawei with MVVM architecture, Riverpod state management, and seamless API integration.",
  },
  {
    n: "03",
    name: "Cloud & DevOps",
    desc: "Containerised environments with Docker Compose, CI/CD pipelines via GitHub Actions (APK delivery to Discord on every staging push), and cloud deployment via Railway — automated from commit to production.",
  },
  {
    n: "04",
    name: "Full-Stack Web",
    desc: "Complete web applications from database schema to responsive frontend, using Django, React, PostgreSQL, and Railway — with an infrastructure-as-code mindset from day one.",
  },
  {
    n: "05",
    name: "Technical Leadership",
    desc: "Led a 5-member engineering team through Agile Scrum — sprint planning, stand-ups, retrospectives, and code reviews — while owning 90%+ of the Flutter codebase at UniTok.",
  },
];

function ServicesSection() {
  return (
    <section
      id="experience"
      className="bg-white rounded-t-[40px] sm:rounded-t-[50px] md:rounded-t-[60px] py-20 sm:py-24 md:py-32"
      style={{ overflowX: "clip" }}
    >
      <FadeIn delay={0} y={40}>
        <h2
          className="text-[#0C0C0C] font-black uppercase text-center mb-16 sm:mb-20 md:mb-28 leading-none tracking-tight px-5"
          style={{ fontSize: "clamp(3rem, 12vw, 160px)" }}
        >
          Expertise
        </h2>
      </FadeIn>

      {/* Main layout: carousel col | services list | carousel col */}
      <div className="flex items-stretch gap-4 md:gap-6 px-2 sm:px-4 md:px-6 max-w-7xl mx-auto">

        {/* Left column — scrolls up */}
        <div
          className="hidden md:block shrink-0"
          style={{ width: 88, alignSelf: "stretch", position: "relative" }}
        >
          <InfiniteColumn items={COL_LEFT} direction="up" speed={0.5} />
        </div>

        {/* Services list */}
        <div className="flex-1 min-w-0">
          {SERVICES.map((s, i) => (
            <FadeIn
              key={s.n}
              delay={i * 0.1}
              y={30}
              className="flex items-start gap-6 sm:gap-10 md:gap-8 py-8 sm:py-10 md:py-12 border-t border-[rgba(12,12,12,0.15)] last:border-b"
            >
              <div
                className="text-[#0C0C0C] font-black leading-none shrink-0"
                style={{ fontSize: "clamp(2.5rem, 8vw, 110px)" }}
              >
                {s.n}
              </div>
              <div className="flex flex-col gap-3 sm:gap-4 pt-2 sm:pt-3 flex-1">
                <h3
                  className="text-[#0C0C0C] font-medium uppercase leading-tight"
                  style={{ fontSize: "clamp(1rem, 2vw, 1.9rem)" }}
                >
                  {s.name}
                </h3>
                <p
                  className="text-[#0C0C0C] font-light leading-relaxed"
                  style={{ fontSize: "clamp(0.82rem, 1.4vw, 1.1rem)", opacity: 0.6 }}
                >
                  {s.desc}
                </p>
              </div>
            </FadeIn>
          ))}
        </div>

        {/* Right column — scrolls down */}
        <div
          className="hidden md:block shrink-0"
          style={{ width: 88, alignSelf: "stretch", position: "relative" }}
        >
          <InfiniteColumn items={COL_RIGHT} direction="down" speed={0.5} />
        </div>
      </div>

      {/* Mobile-only horizontal scrolling tech row */}
      <div className="block md:hidden mt-10 px-2">
        <HorizontalTechRow items={TECH_STACK} speed={0.6} />
      </div>
    </section>
  );
}

Object.assign(window, { ServicesSection });
