'use client';

import React, { useRef, useState, useEffect, useCallback } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';

interface Slide {
  image: string;
  title: string;
  description: string;
  tag: string;
  linkUrl: string;
}

interface HeroSlideCarouselProps {
  slides?: Slide[];
  theme?: string;
}

export function HeroSlideCarousel({
  slides = [],
  theme = 'default',
}: HeroSlideCarouselProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState(0);

  const updateActiveIndex = useCallback(() => {
    if (!scrollRef.current) return;
    const container = scrollRef.current;
    const scrollLeft = container.scrollLeft;
    const children = Array.from(container.children) as HTMLElement[];
    let closest = 0;
    let minDiff = Infinity;
    children.forEach((child, i) => {
      const diff = Math.abs(child.offsetLeft - scrollLeft - container.offsetLeft);
      if (diff < minDiff) { minDiff = diff; closest = i; }
    });
    setActiveIndex(closest);
  }, []);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener('scroll', updateActiveIndex, { passive: true });
    return () => el.removeEventListener('scroll', updateActiveIndex);
  }, [updateActiveIndex]);

  const themeClasses: Record<string, { gradient: string; badge: string }> = {
    default: { gradient: 'from-black/70 via-black/30 to-transparent', badge: 'bg-crimson-red' },
    warm: { gradient: 'from-orange-900/70 via-orange-900/20 to-transparent', badge: 'bg-orange-500' },
    professional: { gradient: 'from-slate-900/80 via-slate-900/40 to-transparent', badge: 'bg-slate-600' },
    ocean: { gradient: 'from-blue-900/70 via-blue-900/20 to-transparent', badge: 'bg-blue-500' },
    forest: { gradient: 'from-emerald-900/70 via-emerald-900/20 to-transparent', badge: 'bg-emerald-500' },
  };
  const t = themeClasses[theme] || themeClasses.default;

  const scroll = (dir: 'left' | 'right') => {
    if (!scrollRef.current) return;
    const amount = scrollRef.current.offsetWidth * 0.6;
    scrollRef.current.scrollBy({ left: dir === 'left' ? -amount : amount, behavior: 'smooth' });
  };

  if (slides.length === 0) {
    return (
      <section className="w-full py-10">
        <div className="container max-w-5xl mx-auto px-4">
          <div className="bg-dark-gray rounded-2xl p-12 text-center border border-soft-gray-border/20">
            <p className="text-text-light-gray">スライドを追加してください。エディターパネルから「Slides」を編集できます。</p>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="w-full py-10">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 relative">
        {/* Scroll buttons */}
        {slides.length > 1 && (
          <>
            <button
              onClick={() => scroll('left')}
              className="absolute left-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 rounded-full bg-white/80 backdrop-blur-sm shadow-md flex items-center justify-center hover:bg-white transition-colors"
              aria-label="Previous slide"
            >
              <ChevronLeft className="w-5 h-5 text-slate-700" />
            </button>
            <button
              onClick={() => scroll('right')}
              className="absolute right-2 top-1/2 -translate-y-1/2 z-10 w-10 h-10 rounded-full bg-white/80 backdrop-blur-sm shadow-md flex items-center justify-center hover:bg-white transition-colors"
              aria-label="Next slide"
            >
              <ChevronRight className="w-5 h-5 text-slate-700" />
            </button>
          </>
        )}

        {/* Scrollable Carousel */}
        <div
          ref={scrollRef}
          className="flex gap-4 overflow-x-auto pb-4 snap-x snap-mandatory scrollbar-hide -mx-4 pl-4"
        >
          {slides.map((slide, i) => {
            const Wrapper = slide.linkUrl ? 'a' : 'div';
            const linkProps = slide.linkUrl ? { href: slide.linkUrl } : {};

            return (
              <Wrapper
                key={i}
                {...linkProps}
                className="relative rounded-2xl overflow-hidden shrink-0 w-[85%] sm:w-[60%] lg:w-[45%] aspect-[16/10] snap-start group shadow-md hover:shadow-lg transition-shadow cursor-pointer"
              >
                {/* Background */}
                {slide.image ? (
                  <img
                    src={slide.image}
                    alt={slide.title || `Slide ${i + 1}`}
                    className="w-full h-full object-cover absolute inset-0 group-hover:scale-105 transition-transform duration-700"
                  />
                ) : (
                  <div className="w-full h-full absolute inset-0 bg-gradient-to-br from-slate-300 to-slate-200" />
                )}

                {/* Overlay */}
                <div className={`absolute inset-0 bg-gradient-to-t ${t.gradient}`} />

                {/* Content */}
                <div className="absolute inset-0 flex flex-col justify-end p-5">
                  {slide.tag && (
                    <span className={`text-[10px] font-bold uppercase tracking-wider px-2.5 py-0.5 rounded-full ${t.badge} text-white w-fit mb-2`}>
                      {slide.tag}
                    </span>
                  )}
                  {slide.title && (
                    <h3 className="text-white text-lg font-bold line-clamp-2 leading-snug">
                      {slide.title}
                    </h3>
                  )}
                  {slide.description && (
                    <p className="text-white/70 text-xs line-clamp-1 mt-1">{slide.description}</p>
                  )}
                </div>
              </Wrapper>
            );
          })}
        </div>

        {/* Dot indicators */}
        {slides.length > 1 && (
          <div className="flex items-center justify-center gap-1.5 mt-3">
            {slides.map((_, i) => (
              <div key={i} className={`w-2 h-2 rounded-full transition-all duration-200 ${i === activeIndex ? t.badge + ' scale-125' : 'bg-slate-300'}`} />
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
