/* Projects Section - sticky stacking cards */

const TECH_ICONS = {
  flutter:  { label: "Flutter",  src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/flutter/flutter-original.svg" },
  django:   { label: "Django",   src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/django/django-plain.svg" },
  ios:      { label: "iOS",      src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/apple/apple-original.svg" },
  android:  { label: "Android",  src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/android/android-original.svg" },
  react:    { label: "React",    src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/react/react-original.svg" },
  tailwind: { label: "Tailwind", src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/tailwindcss/tailwindcss-original.svg" },
  figma:    { label: "Figma",    src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/figma/figma-original.svg" },
  windows:  { label: "Windows",  src: "https://cdn.jsdelivr.net/gh/devicons/devicon/icons/windows8/windows8-original.svg" },
};

const PROJECTS = [
  {
    id: "unitok",
    n: "01",
    name: "UniTok",
    category: "Co-Founder & CTO",
    tech: [TECH_ICONS.flutter, TECH_ICONS.ios, TECH_ICONS.android],
    col1b: { type: "img", src: "assets/images/My Profile image.png" },
    col2:  { type: "video", src: "assets/images/UniTok Video.mp4" },
  },
  {
    id: "ecobill",
    n: "02",
    name: "EcoBill",
    category: "Founding Engineer",
    tech: [TECH_ICONS.react, TECH_ICONS.tailwind],
    col1b: { type: "video", src: "assets/images/EcoBill Usage Mockup.mp4" },
    col2:  { type: "video", src: "assets/images/EcoBill Website.mp4" },
  },
  {
    id: "aurora",
    n: "03",
    name: "Aurora",
    category: "Personal Project",
    tech: [TECH_ICONS.flutter, TECH_ICONS.windows],
    col1b: { type: "img", src: "assets/images/Aurora Image2.png" },
    col2:  { type: "video", src: "assets/images/Aurora Video.mp4" },
  },
];

/* Lazy video cell — loads via IntersectionObserver, shows shimmer until ready */
function LazyVideoCell({ src, className, style }) {
  const videoRef = React.useRef(null);
  const [ready, setReady] = React.useState(false);

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

    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        obs.disconnect();
        el.src = src;
        el.load();
        el.play().catch(() => {});
        el.addEventListener('canplay', () => setReady(true), { once: true });
      }
    }, { rootMargin: '200px' });

    obs.observe(el);
    return () => obs.disconnect();
  }, [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"
        className={className}
        style={{ ...style, opacity: ready ? 1 : 0, transition: 'opacity 0.7s ease-in-out' }}
      />
    </div>
  );
}

function ProjectCard({ project, index, totalCards }) {
  const containerRef = React.useRef(null);
  const { scrollYProgress } = _useScroll({
    target: containerRef,
    offset: ["start end", "start start"],
  });

  const targetScale = 1 - (totalCards - 1 - index) * 0.03;
  const scale = _useTransform(scrollYProgress, [0, 1], [1, targetScale]);

  return (
    <div
      ref={containerRef}
      className="h-auto sm:h-[85vh] sticky"
      style={{ top: `calc(6rem + ${index * 28}px)` }}
    >
      <_motion.div
        style={{ scale, transformOrigin: "top center" }}
        className="rounded-[40px] sm:rounded-[50px] md:rounded-[60px] border-2 border-[#D7E2EA] bg-[#0C0C0C] p-4 sm:p-6 md:p-8 h-full flex flex-col"
      >
        {/* Top row */}
        <div className="flex items-center justify-between gap-4 sm:gap-6 md:gap-8 mb-4 sm:mb-6 md:mb-8">
          <div className="flex items-center gap-4 sm:gap-6 md:gap-10 min-w-0">
            <div
              className="hero-heading font-black leading-none shrink-0"
              style={{ fontSize: "clamp(3rem, 10vw, 140px)" }}
            >
              {project.n}
            </div>
            <div className="flex flex-col gap-1 sm:gap-2 min-w-0">
              <span
                className="text-[#D7E2EA]/60 font-light uppercase tracking-widest"
                style={{ fontSize: "clamp(0.7rem, 1.1vw, 1rem)" }}
              >
                {project.category}
              </span>
              <h3
                className="text-[#D7E2EA] font-medium uppercase leading-tight truncate"
                style={{ fontSize: "clamp(1.1rem, 2.4vw, 2.25rem)" }}
              >
                {project.name}
              </h3>
            </div>
          </div>
          <div className="shrink-0">
            <LiveProjectButton onClick={() => { window.location.href = `project.html#${project.id}`; }} />
          </div>
        </div>

        {/* Bottom row: 2-col media grid (stacked on mobile) */}
        <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 md:gap-5 flex-1 min-h-0">
          {/* Left col */}
          <div className="flex flex-col gap-3 sm:gap-4 md:gap-5 sm:basis-[40%]">
            {/* Tech stack icons panel */}
            <div
              className="rounded-[40px] sm:rounded-[50px] md:rounded-[60px] bg-[#111] border border-[#D7E2EA]/10 flex flex-wrap items-center justify-center gap-4 sm:gap-5 md:gap-7 px-4"
              style={{ height: "clamp(90px, 14vw, 230px)" }}
            >
              {project.tech && project.tech.map((t) => (
                <div key={t.label} className="flex flex-col items-center gap-2">
                  <img
                    src={t.src}
                    alt={t.label}
                    style={{ width: "clamp(40px, 5.5vw, 72px)", height: "clamp(40px, 5.5vw, 72px)" }}
                  />
                  <span
                    className="text-[#D7E2EA]/50 font-light uppercase tracking-widest leading-none"
                    style={{ fontSize: "clamp(0.5rem, 0.7vw, 0.65rem)" }}
                  >
                    {t.label}
                  </span>
                </div>
              ))}
            </div>
            <div
              className="rounded-[40px] sm:rounded-[50px] md:rounded-[60px] overflow-hidden flex items-center justify-center"
              style={{ aspectRatio: "4/3", background: "#fff", maxHeight: "clamp(120px, 28vw, 9999px)" }}
            >
              {project.col1b && (
                project.col1b.type === "video"
                  ? <LazyVideoCell src={project.col1b.src} className="w-full h-full" style={{ objectFit: 'contain' }} />
                  : <img src={project.col1b.src} alt="" className="w-full h-full object-contain" loading="lazy" />
              )}
            </div>
          </div>
          {/* Right col */}
          <div
            className="rounded-[40px] sm:rounded-[50px] md:rounded-[60px] overflow-hidden bg-white flex items-center justify-center sm:basis-[60%]"
            style={{ minHeight: "clamp(100px, 28vw, 400px)" }}
          >
            {project.col2 && (
              project.col2.type === "video"
                ? <LazyVideoCell src={project.col2.src} className="w-full h-full" style={{ objectFit: 'contain' }} />
                : <img src={project.col2.src} alt="" className="w-full h-full object-contain" loading="lazy" />
            )}
          </div>
        </div>
      </_motion.div>
    </div>
  );
}

function ProjectsSection() {
  return (
    <section
      id="projects"
      className="relative bg-[#0C0C0C] rounded-t-[40px] sm:rounded-t-[50px] md:rounded-t-[60px] -mt-10 sm:-mt-12 md:-mt-14 z-10 px-5 sm:px-8 md:px-10 pt-20 sm:pt-24 md:pt-32 pb-20"
      style={{ overflowX: "clip" }}
    >
      <FadeIn delay={0} y={40}>
        <h2
          className="hero-heading font-black uppercase text-center leading-none tracking-tight mb-8 sm:mb-10 md:mb-14"
          style={{ fontSize: "clamp(3rem, 12vw, 160px)" }}
        >
          Projects
        </h2>
      </FadeIn>
      <FadeIn delay={0.2} y={20}>
        <div className="flex justify-center mb-16 sm:mb-20 md:mb-28">
          <button
            onClick={() => { window.location.href = 'projects.html'; }}
            className="group flex items-center gap-3 rounded-full border-2 border-[#D7E2EA]/50 text-[#D7E2EA] font-medium uppercase tracking-widest px-8 py-3 sm:px-10 sm:py-3.5 text-sm sm:text-base transition-all duration-300 hover:bg-[#D7E2EA]/10 hover:border-[#D7E2EA] cursor-pointer"
          >
            View All Projects
            <span className="inline-block transition-transform duration-300 group-hover:translate-x-1">→</span>
          </button>
        </div>
      </FadeIn>

      <div className="max-w-7xl mx-auto">
        {PROJECTS.map((p, i) => (
          <ProjectCard key={p.n} project={p} index={i} totalCards={PROJECTS.length} />
        ))}
        {/* Ghost spacer: provides just enough scroll runway for the last
            real card to reach its sticky lock point, then the section ends. */}
        <div
          className="pointer-events-none"
          style={{ height: `calc(6rem + ${PROJECTS.length * 28}px)` }}
        />
      </div>
    </section>
  );
}

Object.assign(window, { ProjectsSection });
