'use client';

import { useState, useRef, useEffect } from 'react';

const slides = [
  {
    label: 'Cocina',
    before: '/antes.webp',
    after: '/despues.webp',
  },
  {
    label: 'Baño',
    before: '/antes-bano.webp',
    after: '/despues-bano.webp',
  },
  {
    label: 'Comedor',
    before: '/antes-comedor.webp',
    after: '/despues-comedor.webp',
  },
];

export default function ReformaSlider() {
  const [activeSlide, setActiveSlide] = useState(0);
  const [sliderX, setSliderX] = useState(50);
  const [dragging, setDragging] = useState(false);
  const [visible, setVisible] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const sectionRef = useRef<HTMLElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('opacity-100', 'translate-y-0');
            entry.target.classList.remove('opacity-0', 'translate-y-6');
          }
        });
      },
      { threshold: 0.1 }
    );
    const elements = sectionRef.current?.querySelectorAll('.reveal');
    elements?.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  const handleMove = (clientX: number) => {
    if (!dragging || !containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    const x = ((clientX - rect.left) / rect.width) * 100;
    setSliderX(Math.min(Math.max(x, 5), 95));
  };

  const switchSlide = (index: number) => {
    if (index === activeSlide) return;
    setVisible(false);
    setTimeout(() => {
      setActiveSlide(index);
      setSliderX(50);
      setVisible(true);
    }, 300);
  };

  return (
    <section id="ver-reforma" className="bg-white py-16 md:py-24" ref={sectionRef}>
      <div className="container text-center">
        <h2 className="text-[clamp(1.875rem,5vw,3rem)] font-black tracking-[-0.04em] leading-[1.1] text-black mb-10 md:mb-12 reveal opacity-0 translate-y-6 transition-all duration-700 ease-out">
          Ve cómo quedará tu reforma
        </h2>
        <div className="flex flex-col gap-4 reveal opacity-0 translate-y-6 transition-all duration-700 ease-out delay-100">
          <div
            ref={containerRef}
            className="relative w-full aspect-[16/9] rounded-xl overflow-hidden cursor-col-resize select-none"
            onMouseDown={() => setDragging(true)}
            onMouseUp={() => setDragging(false)}
            onMouseLeave={() => setDragging(false)}
            onMouseMove={(e) => handleMove(e.clientX)}
            onTouchStart={() => setDragging(true)}
            onTouchEnd={() => setDragging(false)}
            onTouchMove={(e) => handleMove(e.touches[0].clientX)}
          >
            <div
              className="absolute inset-0 transition-opacity duration-300"
              style={{ opacity: visible ? 1 : 0 }}
            >
              <img
                src={slides[activeSlide].after}
                alt="Después de la reforma"
                className="absolute inset-0 w-full h-full object-cover"
              />
              <div
                className="absolute inset-0 overflow-hidden"
                style={{ width: `${sliderX}%` }}
              >
                <img
                  src={slides[activeSlide].before}
                  alt="Antes de la reforma"
                  className="absolute inset-0 w-full h-full object-cover"
                  style={{ width: `${(100 / sliderX) * 100}%`, maxWidth: 'none' }}
                />
              </div>
              <span className="absolute top-3 left-4 bg-black/70 text-white text-xs font-medium px-3 py-1 rounded-full">
                Antes
              </span>
              <span className="absolute top-3 right-4 bg-white/90 text-black text-xs font-medium px-3 py-1 rounded-full">
                Después
              </span>
              <div
                className="absolute top-0 bottom-0 w-[2px] bg-white shadow-lg"
                style={{ left: `${sliderX}%` }}
              >
                <div className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 w-9 h-9 bg-white rounded-full shadow-xl flex items-center justify-center">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path d="M8 4l-4 8 4 8M16 4l4 8-4 8" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </div>
              </div>
            </div>
          </div>

          {slides.length > 1 && (
            <div className="flex gap-3 justify-center mt-2">
              {slides.map((slide, i) => (
                <button
                  key={slide.label}
                  onClick={() => switchSlide(i)}
                  className={`relative rounded-lg overflow-hidden w-24 h-16 shrink-0 transition-all duration-200 ${i === activeSlide ? 'ring-2 ring-black ring-offset-2' : 'opacity-50 hover:opacity-80'
                    }`}
                  aria-label={`Ver reforma de ${slide.label}`}
                >
                  <img src={slide.before} alt={slide.label} className="w-full h-full object-cover" />
                  <span className="absolute bottom-1 left-1/2 -translate-x-1/2 bg-black/70 text-white text-[10px] px-2 py-0.5 rounded-full whitespace-nowrap">
                    {slide.label}
                  </span>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
