"use client";

import React, { useRef, useState, useEffect, useCallback } from "react";
import { Mountain as MountainIcon, ChevronLeft, ChevronRight } from "lucide-react";
import GalleryPhotoCard from "./GalleryPhotoCard";
import type { GalleryGroup } from "@/types/gallery";
import styles from "./MountainSection.module.css";

interface MountainSectionProps {
  group: GalleryGroup;
  groupIndex: number;
  onPhotoClick: (imageIndex: number) => void;
}

// Subtitle generator based on mountain name or authentic outdoor tone
function getMountainSubtitle(name: string): string {
  const lower = name.toLowerCase();
  if (lower.includes("prau")) {
    return "Keindahan golden sunrise, lautan awan, dan padang savana di atas awan.";
  }
  if (lower.includes("merbabu")) {
    return "Pesona sabana hijau luas dan panorama megah puncak Jawa Tengah.";
  }
  if (lower.includes("slamet")) {
    return "Tantangan atap Jawa Tengah dengan lanskap vulkanik yang menakjubkan.";
  }
  if (lower.includes("sindoro")) {
    return "Sensasi pendakian gunung piramida dengan kawah aktif yang memukau.";
  }
  if (lower.includes("sumbing")) {
    return "Jalur terjal berbatu dan pemandangan kawah purba yang memikat.";
  }
  if (lower.includes("rinjani")) {
    return "Keagungan Danau Segara Anak dan kemegahan puncak pulau Lombok.";
  }
  if (lower.includes("semeru")) {
    return "Petualangan legendaris menuju puncak Mahameru dan Ranu Kumbolo.";
  }
  return `Kumpulan dokumentasi momen perjalanan dan pendakian di ${name}.`;
}

export default function MountainSection({
  group,
  onPhotoClick,
}: MountainSectionProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  const images = group.images || [];
  const count = images.length;
  // If count >= 3, use horizontal slider with arrow controls. If <= 2, use static grid.
  const isSlider = count >= 3;

  const updateScrollButtons = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;
    setCanScrollLeft(scrollLeft > 5);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 5);
  }, []);

  useEffect(() => {
    if (!isSlider) return;
    const el = scrollRef.current;
    if (!el) return;

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

    return () => {
      el.removeEventListener("scroll", updateScrollButtons);
      window.removeEventListener("resize", updateScrollButtons);
    };
  }, [isSlider, updateScrollButtons, images]);

  const scroll = (direction: "left" | "right") => {
    const el = scrollRef.current;
    if (!el) return;
    // Scroll about 1 card width or half the container
    const scrollAmount = el.clientWidth * 0.75;
    el.scrollBy({
      left: direction === "left" ? -scrollAmount : scrollAmount,
      behavior: "smooth",
    });
  };

  const subtitle = getMountainSubtitle(group.mountain.name);

  return (
    <section
      className={styles.section}
      aria-labelledby={`mountain-heading-${group.mountain.id}`}
    >
      {/* ── Section Header ────────────────────────────────────────── */}
      <div className={styles.sectionHeader}>
        <div className={styles.headerLeft}>
          <div className={styles.iconSquircle} aria-hidden="true">
            <MountainIcon size={20} />
          </div>
          <div className={styles.titleInfo}>
            <h2
              id={`mountain-heading-${group.mountain.id}`}
              className={styles.mountainTitle}
            >
              {group.mountain.name}
            </h2>
            <p className={styles.mountainSubtitle}>{subtitle}</p>
          </div>
        </div>

        <div className={styles.headerRight}>
          <span className={styles.photoCountBadge}>{count} foto</span>

          {isSlider && (
            <div className={styles.arrowControls} aria-label="Navigasi galeri foto">
              <button
                type="button"
                className={styles.arrowBtn}
                onClick={() => scroll("left")}
                disabled={!canScrollLeft}
                aria-label="Geser ke kiri"
              >
                <ChevronLeft size={18} />
              </button>
              <button
                type="button"
                className={styles.arrowBtn}
                onClick={() => scroll("right")}
                disabled={!canScrollRight}
                aria-label="Geser ke kanan"
              >
                <ChevronRight size={18} />
              </button>
            </div>
          )}
        </div>
      </div>

      {/* ── Photo Gallery: Conditional Grid vs Slider ─────────────── */}
      {count === 0 ? (
        <div className={styles.emptyCard}>
          <MountainIcon size={24} className={styles.emptyIcon} aria-hidden="true" />
          <p className={styles.emptyText}>Dokumentasi perjalanan belum tersedia.</p>
        </div>
      ) : isSlider ? (
        <div
          ref={scrollRef}
          className={styles.sliderTrack}
          role="region"
          aria-label={`Daftar foto ${group.mountain.name}`}
          tabIndex={0}
        >
          {images.map((image, idx) => (
            <div key={image.id} className={styles.sliderItem}>
              <GalleryPhotoCard
                image={image}
                mountainName={group.mountain.name}
                onClick={() => onPhotoClick(idx)}
              />
            </div>
          ))}
        </div>
      ) : (
        <div className={styles.staticGrid}>
          {images.map((image, idx) => (
            <div key={image.id} className={styles.gridItem}>
              <GalleryPhotoCard
                image={image}
                mountainName={group.mountain.name}
                onClick={() => onPhotoClick(idx)}
              />
            </div>
          ))}
        </div>
      )}

      {/* ── Divider between mountain sections ─────────────────────── */}
      <div className={styles.sectionDivider} aria-hidden="true" />
    </section>
  );
}
