"use client";

import { useState, useEffect, useRef } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";

type Project = {
  id: string;
  title: string;
  partner: string;
  tag: string;
  description: string;
  image: string;
};

export function ProjectsCarousel() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [active, setActive] = useState(0);
  const [isInView, setIsInView] = useState(false);
  const sectionRef = useRef<HTMLElement>(null);
  const headingRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetch("/api/projects")
      .then((res) => res.json())
      .then((data) => {
        setProjects(data);
        setLoading(false);
      })
      .catch((error) => {
        console.error("Error fetching projects:", error);
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      if (!headingRef.current || !sectionRef.current) return;
      const headingRect = headingRef.current.getBoundingClientRect();
      const sectionRect = sectionRef.current.getBoundingClientRect();
      const viewportHeight = window.innerHeight;
      // Expand when heading reaches 65% down, contract only when section bottom is near top
      const inMiddle = headingRect.top < viewportHeight * 0.65 && sectionRect.bottom > viewportHeight * 0.85;
      setIsInView(inMiddle);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    handleScroll(); // check on mount
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const total = projects.length;

  const prev = () => setActive((i) => Math.max(0, i - 1));
  const next = () => setActive((i) => Math.min(total - 1, i + 1));

  if (loading) {
    return (
      <section ref={sectionRef} id="projets" className="py-20 bg-[#F7F8F5]">
        <div className={`mx-auto px-4 sm:px-6 lg:px-8 transition-all duration-700 ease-out ${
          isInView ? "max-w-full" : "max-w-6xl"
        }`}>
          <div className="animate-pulse">
            <div className="h-8 bg-gray-200 rounded w-48 mb-8"></div>
            <div className="bg-gray-200 rounded-2xl h-96"></div>
          </div>
        </div>
      </section>
    );
  }

  if (projects.length === 0) {
    return null;
  }

  return (
    <section ref={sectionRef} id="projets" className="py-20 bg-[#F7F8F5]">
      <div className={`mx-auto px-4 sm:px-6 lg:px-8 transition-all duration-700 ease-out ${
        isInView ? "max-w-full" : "max-w-6xl"
      }`}>

        {/* Header row */}
        <div ref={headingRef} className="flex items-end justify-between mb-8">
          <div>
            <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-2">
              Ce que nous faisons
            </p>
            <h2 className="font-serif text-4xl md:text-5xl font-black text-[#2C3E50]">
              Projets phares
            </h2>
          </div>

          <div className="flex items-center gap-4">
            <span className="hidden sm:block text-sm text-gray-400 font-medium tabular-nums">
              {String(active + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
            </span>
            <div className="flex gap-2">
              <button
                onClick={prev}
                disabled={active === 0}
                aria-label="Projet précédent"
                className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:border-gray-400 hover:text-gray-800 disabled:opacity-25 transition-all"
              >
                <ChevronLeft size={18} />
              </button>
              <button
                onClick={next}
                disabled={active === total - 1}
                aria-label="Projet suivant"
                className="w-10 h-10 rounded-full border border-gray-200 flex items-center justify-center text-gray-500 hover:border-gray-400 hover:text-gray-800 disabled:opacity-25 transition-all"
              >
                <ChevronRight size={18} />
              </button>
            </div>
          </div>
        </div>

        {/* Carousel track */}
        <div className="overflow-hidden rounded-2xl">
          <div
            className="flex transition-transform duration-500 ease-in-out"
            style={{ transform: `translateX(-${active * 100}%)` }}
          >
            {projects.map((p, i) => (
              <div
                key={p.id}
                className="w-full flex-shrink-0 relative aspect-[16/9] sm:aspect-[16/8]"
              >
                {/* Image */}
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={p.image}
                  alt={p.title}
                  className="w-full h-full object-cover"
                />

                {/* Gradient overlay */}
                <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-black/5" />

                {/* Text content */}
                <div className="absolute inset-0 flex flex-col justify-end p-6 sm:p-10">
                  <div className="max-w-xl">
                    <p className="text-[11px] font-semibold text-white/50 uppercase tracking-widest mb-2">
                      {p.partner}
                    </p>
                    <h3 className="font-serif text-xl sm:text-2xl md:text-3xl font-bold text-white leading-tight mb-2">
                      {p.title}
                    </h3>
                    {/* <p className="text-xs sm:text-sm text-white/65 leading-relaxed mb-5 hidden sm:block">
                      {p.description}
                    </p> */}
                    <span className="inline-block text-[11px] font-medium text-white/80 border border-white/25 px-3 py-1 rounded-full">
                      {p.tag}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Progress bar dots */}
        <div className="flex items-center justify-between mt-5">
          <div className="flex gap-1.5">
            {projects.map((_, i) => (
              <button
                key={i}
                onClick={() => setActive(i)}
                aria-label={`Aller au projet ${i + 1}`}
                className={`h-1 rounded-full transition-all duration-300 ${
                  i === active
                    ? "w-8 bg-[#4A7C59]"
                    : "w-3 bg-gray-300 hover:bg-gray-400"
                }`}
              />
            ))}
          </div>
          <span className="sm:hidden text-xs text-gray-400 tabular-nums">
            {active + 1} / {total}
          </span>
        </div>

      </div>
    </section>
  );
}
