---
/**
 * EnvironmentSlider - Photo slider for work environment
 * Pixel-perfect implementation based on Webflow design
 * Features: 8 photos, arrow navigation, dot navigation, touch swipe support
 */

interface SlideImage {
  src: string;
  alt: string;
}

interface Props {
  slides?: SlideImage[];
}

const defaultSlides: SlideImage[] = [
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b4962117e2d84363174_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871.jpg",
    alt: "恩群環境照片 1",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b49558b7e5b0e81de8f_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-7.jpg",
    alt: "恩群環境照片 2",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b4962117e2d84363174_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-1.jpg",
    alt: "恩群環境照片 3",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76c511895ed028da1c7f0_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-3.jpg",
    alt: "恩群環境照片 4",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b48558b7e072a81de8e_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-4.jpg",
    alt: "恩群環境照片 5",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b483504a25babe537ef_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-1.jpg",
    alt: "恩群環境照片 6",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/61f76b48ef5754e17a8c1676_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%871-6.jpg",
    alt: "恩群環境照片 7",
  },
  {
    src: "https://enchun-cms.anlstudio.cc/api/media/file/620639d7a68fef44f6569b23_%E6%81%A9%E7%BE%A4%E7%92%B0%E5%A2%83%20%E7%85%A7%E7%89%879.jpg",
    alt: "恩群環境照片 8",
  },
];

const slides = Astro.props.slides || defaultSlides;

import SectionHeader from "../components/SectionHeader.astro";
---

<section
  class="section-video py-10 md:py-20 md:px-5 px-4 bg-white"
  aria-label="工作環境照片"
>
  <div class="container w-container max-w-3xl mx-auto">
    <!-- Section Header -->
    <SectionHeader
      title="在恩群工作的環境"
      subtitle="Working Enviroment"
      sectionBg="bg-white"
    />

    <!-- Environment Slider -->
    <div
      class="environment-slider relative w-full max-w-4xl mx-auto"
      id="env-slider-{Math.random().toString(36).slice(2, 8)}"
    >
      <!-- Slides Container -->
      <div
        class="slides-container flex overflow-x-auto snap-x snap-mandatory scroll-smooth overscroll-x-contain [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden cursor-grab"
      >
        {
          slides.map((slide, index) => (
            <div
              class="environment-slide flex-none w-full snap-start aspect-video overflow-hidden rounded-xl"
              data-index={index}
            >
              <img
                src={slide.src}
                alt={slide.alt}
                loading={index === 0 ? "eager" : "lazy"}
                width="800"
                height="450"
                class="w-full h-full object-cover"
              />
            </div>
          ))
        }
      </div>

      <!-- Arrow Navigation -->
      <button
        class="slider-arrow slider-arrow-left absolute top-1/2 -translate-y-1/2 w-12 h-12 md:w-12 md:h-12 w-10 h-10 bg-white/80 rounded-full flex items-center justify-center cursor-pointer transition-all duration-200 ease-in-out z-10 hover:bg-white hover:scale-110 left-4 md:left-4 left-2"
        aria-label="上一張"
      >
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path
            fill="currentColor"
            d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path>
        </svg>
      </button>
      <button
        class="slider-arrow slider-arrow-right absolute top-1/2 -translate-y-1/2 w-12 h-12 md:w-12 md:h-12 w-10 h-10 bg-white/80 rounded-full flex items-center justify-center cursor-pointer transition-all duration-200 ease-in-out z-10 hover:bg-white hover:scale-110 right-4 md:right-4 right-2"
        aria-label="下一張"
      >
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path
            fill="currentColor"
            d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path>
        </svg>
      </button>

      <!-- Dot Navigation -->
      <div class="slider-dots flex justify-center gap-2 mt-4">
        {
          slides.map((_, index) => (
            <button
              class={`slider-dot w-3 h-3 rounded-full cursor-pointer transition-all duration-200 ease-in-out ${index === 0 ? "active bg-(--color-enchunblue) w-8 rounded-[6px]" : "bg-(--color-enchunblue)/30"}`}
              data-index={index}
              aria-label={`顯示第 ${index + 1} 張照片`}
            />
          ))
        }
      </div>
    </div>
  </div>
</section>

<script>
  // Environment Slider functionality
  function initEnvironmentSlider() {
    const sliders = document.querySelectorAll(".environment-slider");

    sliders.forEach((slider) => {
      const container = slider.querySelector(
        ".slides-container",
      ) as HTMLElement;
      const slides = slider.querySelectorAll(".environment-slide");
      const dots = slider.querySelectorAll(".slider-dot");
      const prevBtn = slider.querySelector(
        ".slider-arrow-left",
      ) as HTMLButtonElement;
      const nextBtn = slider.querySelector(
        ".slider-arrow-right",
      ) as HTMLButtonElement;

      if (!container || slides.length === 0) return;

      let currentIndex = 0;
      const totalSlides = slides.length;
      let isDragging = false;
      let startPos = 0;
      let currentTranslate = 0;
      let prevTranslate = 0;
      let animationID: number;

      // Update slider position
      const updateSlider = () => {
        container.scrollTo({
          left: currentIndex * container.offsetWidth,
          behavior: "smooth",
        });
        updateDots();
      };

      // Update dots
      const updateDots = () => {
        dots.forEach((dot, index) => {
          if (index === currentIndex) {
            dot.classList.add(
              "active",
              "w-8",
              "rounded-[6px]",
              "bg-(--color-enchunblue)",
            );
            dot.classList.remove("w-3", "bg-(--color-enchunblue)/30");
          } else {
            dot.classList.remove(
              "active",
              "w-8",
              "rounded-[6px]",
              "bg-(--color-enchunblue)",
            );
            dot.classList.add("w-3", "bg-(--color-enchunblue)/30");
          }
        });
      };

      // Go to specific slide
      const goToSlide = (index: number) => {
        if (index < 0) index = totalSlides - 1;
        if (index >= totalSlides) index = 0;
        currentIndex = index;
        updateSlider();
      };

      // Previous slide
      prevBtn?.addEventListener("click", () => goToSlide(currentIndex - 1));

      // Next slide
      nextBtn?.addEventListener("click", () => goToSlide(currentIndex + 1));

      // Dot navigation
      dots.forEach((dot, index) => {
        dot.addEventListener("click", () => goToSlide(index));
      });

      // Scroll snap detection
      container.addEventListener("scroll", () => {
        const slideIndex = Math.round(
          container.scrollLeft / container.offsetWidth,
        );
        if (slideIndex !== currentIndex) {
          currentIndex = slideIndex;
          updateDots();
        }
      });

      // Touch/swipe support
      const touchStart = (_index: number) => {
        return function (event: TouchEvent) {
          isDragging = true;
          startPos = event.touches[0].clientX;
          animationID = requestAnimationFrame(animation);
          container.style.cursor = "grabbing";
        };
      };

      const touchEnd = () => {
        isDragging = false;
        cancelAnimationFrame(animationID);
        container.style.cursor = "grab";

        const movedBy = currentTranslate - prevTranslate;

        if (movedBy < -50 && currentIndex < totalSlides - 1) {
          currentIndex += 1;
        } else if (movedBy > 50 && currentIndex > 0) {
          currentIndex -= 1;
        }

        goToSlide(currentIndex);
      };

      const touchMove = (event: TouchEvent) => {
        if (isDragging) {
          const currentPosition = event.touches[0].clientX;
          currentTranslate = prevTranslate + currentPosition - startPos;
        }
      };

      const animation = () => {
        if (isDragging) requestAnimationFrame(animation);
      };

      // Mouse events for desktop
      let mouseStartPos = 0;
      let isMouseDown = false;

      container.addEventListener("mousedown", (e: MouseEvent) => {
        isMouseDown = true;
        mouseStartPos = e.clientX;
        container.style.cursor = "grabbing";
      });

      container.addEventListener("mouseup", (e: MouseEvent) => {
        if (!isMouseDown) return;
        isMouseDown = false;
        container.style.cursor = "grab";

        const movedBy = e.clientX - mouseStartPos;
        if (movedBy < -50 && currentIndex < totalSlides - 1) {
          currentIndex += 1;
        } else if (movedBy > 50 && currentIndex > 0) {
          currentIndex -= 1;
        }
        goToSlide(currentIndex);
      });

      container.addEventListener("mouseleave", () => {
        isMouseDown = false;
        container.style.cursor = "grab";
      });

      // Touch events
      container.addEventListener("touchstart", touchStart(currentIndex));
      container.addEventListener("touchend", touchEnd);
      container.addEventListener("touchmove", touchMove);

      // Keyboard navigation
      slider.addEventListener("keydown", (e) => {
        if (e instanceof KeyboardEvent) {
          if (e.key === "ArrowLeft") goToSlide(currentIndex - 1);
          if (e.key === "ArrowRight") goToSlide(currentIndex + 1);
        }
      });

      // Set initial state
      container.style.cursor = "grab";
    });
  }

  // Initialize when DOM is ready
  document.addEventListener("DOMContentLoaded", initEnvironmentSlider);
  if (document.readyState !== "loading") {
    initEnvironmentSlider();
  }
</script>
