"use client";

import React, { useRef, useState, useEffect } from "react";
import { motion, useMotionValue, useSpring, useTransform, AnimatePresence } from "framer-motion";
import { ChevronRight, Sparkles } from "lucide-react";
import { HERO_SLIDES } from "@/config/siteContent";

interface HeroProps {
  onOpenSchedule: () => void;
}

export default function Hero({ onOpenSchedule }: HeroProps) {
  const containerRef = useRef<HTMLElement>(null);

  // Slide index state
  const [activeSlideIdx, setActiveSlideIdx] = useState(0);
  const currentSlide = HERO_SLIDES[activeSlideIdx] || HERO_SLIDES[0];

  // Mouse interaction state for click + slide 3D parallax
  const [isMouseDown, setIsMouseDown] = useState(false);
  const [isSliding, setIsSliding] = useState(false);
  const startPosRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });

  // Relentless continuous 5-second carousel timer (runs automatically regardless of activity)
  useEffect(() => {
    const timer = setInterval(() => {
      setActiveSlideIdx((prev) => (prev + 1) % HERO_SLIDES.length);
    }, 5000);
    return () => clearInterval(timer);
  }, []);

  // Motion values for normalized slide positions (-0.5 to 0.5)
  const mouseX = useMotionValue(0);
  const mouseY = useMotionValue(0);

  // Smooth physics springs for fluid 3D slide response
  const springConfig = { stiffness: 120, damping: 20 };
  const smoothMouseX = useSpring(mouseX, springConfig);
  const smoothMouseY = useSpring(mouseY, springConfig);

  // Parallax transform bindings for background image (activated on click + slide)
  const bgTranslateX = useTransform(smoothMouseX, [-0.5, 0.5], [-32, 32]);
  const bgTranslateY = useTransform(smoothMouseY, [-0.5, 0.5], [-26, 26]);
  const bgRotateX = useTransform(smoothMouseY, [-0.5, 0.5], [6, -6]);
  const bgRotateY = useTransform(smoothMouseX, [-0.5, 0.5], [-6, 6]);

  // Card counter-parallax shift on click + slide
  const cardTranslateX = useTransform(smoothMouseX, [-0.5, 0.5], [14, -14]);
  const cardTranslateY = useTransform(smoothMouseY, [-0.5, 0.5], [12, -12]);

  const updateCoordinates = (e: React.MouseEvent<HTMLElement>) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    const normX = (e.clientX - rect.left) / rect.width - 0.5;
    const normY = (e.clientY - rect.top) / rect.height - 0.5;

    mouseX.set(normX);
    mouseY.set(normY);
  };

  const handleMouseDown = (e: React.MouseEvent<HTMLElement>) => {
    setIsMouseDown(true);
    setIsSliding(false);
    startPosRef.current = { x: e.clientX, y: e.clientY };
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLElement>) => {
    if (!isMouseDown) return;

    const dx = e.clientX - startPosRef.current.x;
    const dy = e.clientY - startPosRef.current.y;
    const dist = Math.hypot(dx, dy);

    if (dist > 5) {
      if (!isSliding) setIsSliding(true);
      updateCoordinates(e);
    }
  };

  const handleMouseUp = () => {
    setIsMouseDown(false);
    setIsSliding(false);
    mouseX.set(0);
    mouseY.set(0);
  };

  return (
    <section
      ref={containerRef}
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseUp}
      onMouseMove={handleMouseMove}
      id="intro"
      className="relative w-full min-h-[70vh] lg:min-h-[75vh] flex items-center justify-start bg-zinc-950 overflow-hidden cursor-grab active:cursor-grabbing select-none"
    >
      {/* Background Image Carousel with 4K Cross-Fade & 3D Click-Slide Parallax */}
      <AnimatePresence mode="sync">
        <motion.div
          key={currentSlide.id}
          initial={{ opacity: 0, scale: 1.02 }}
          animate={{
            opacity: 1,
            scale: isSliding ? 1.10 : 1.04,
          }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.8, ease: "easeOut" }}
          className="absolute -inset-8 bg-cover bg-center bg-no-repeat will-change-transform"
          style={{
            backgroundImage: `url('${currentSlide.backgroundImage}')`,
            x: bgTranslateX,
            y: bgTranslateY,
            rotateX: bgRotateX,
            rotateY: bgRotateY,
          }}
        >
          {/* Subtle Gradient Overlay */}
          <div className="absolute inset-0 bg-gradient-to-r from-black/40 via-black/20 to-transparent pointer-events-none" />
        </motion.div>
      </AnimatePresence>

      {/* Hero Content Container - Positioned on Left Side */}
      <div className="relative z-10 max-w-7xl mx-auto px-6 lg:px-16 w-full py-10 pointer-events-auto flex flex-col justify-between min-h-[55vh]">
        
        {/* Sleeker, More Compact Framed Hero Box */}
        <motion.div
          style={{
            x: cardTranslateX,
            y: cardTranslateY,
          }}
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.4, ease: "easeOut" }}
          className="max-w-[380px] sm:max-w-[420px] p-6 sm:p-8 md:p-10 bg-black/45 backdrop-blur-[6px] shadow-2xl relative rounded-xs group overflow-hidden border border-white/10"
        >
          {/* Animated Golden Border Outline - Draws slowly in a linear manner */}
          <svg className="absolute inset-0 w-full h-full pointer-events-none">
            <motion.rect
              key={currentSlide.id}
              x="1"
              y="1"
              width="calc(100% - 2px)"
              height="calc(100% - 2px)"
              fill="none"
              stroke="#c5a059"
              strokeWidth="2.5"
              initial={{ pathLength: 0, opacity: 0 }}
              animate={{ pathLength: 1, opacity: 1 }}
              transition={{
                pathLength: { duration: 2.2, ease: "linear" },
                opacity: { duration: 0.2 },
              }}
            />
          </svg>

          {/* Dynamic Content Animation based on active slide */}
          <AnimatePresence mode="wait">
            <motion.div
              key={currentSlide.id}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.3 }}
            >
              {/* Golden Badge Accent */}
              <motion.div 
                initial={{ opacity: 0, y: 6 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: 0.1 }}
                className="flex items-center gap-2 mb-3"
              >
                <Sparkles size={12} className="text-[#c5a059]" />
                <span className="text-[10px] font-extrabold uppercase tracking-[0.25em] text-[#c5a059]">
                  {currentSlide.badgeText}
                </span>
              </motion.div>

              {/* Main Heading - Expands & Wipes from Left to Right */}
              <motion.h1
                key={`title-${currentSlide.id}`}
                initial={{ clipPath: "polygon(0 0, 0 0, 0 100%, 0 100%)", opacity: 0, x: -16 }}
                animate={{ clipPath: "polygon(0 0, 100% 0, 100% 100%, 0 100%)", opacity: 1, x: 0 }}
                transition={{ duration: 0.85, ease: [0.16, 1, 0.3, 1] }}
                className="text-3xl sm:text-4xl md:text-5xl font-bold font-serif text-white tracking-tight leading-[1.1] mb-6 overflow-hidden"
              >
                {currentSlide.titleLine1} <br />
                <span className="text-gold-gradient font-serif">{currentSlide.titleLine2}</span>
              </motion.h1>

              {/* Price Block */}
              <motion.div 
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.4, delay: 0.4 }}
                className="mb-6 space-y-0.5"
              >
                <p className="text-zinc-300 text-[11px] sm:text-xs font-extrabold uppercase tracking-[0.2em]">
                  {currentSlide.priceLabel}
                </p>
                <p className="text-2xl sm:text-3xl md:text-4xl font-extrabold text-white tracking-tight font-sans">
                  {currentSlide.priceValue}
                </p>
              </motion.div>

              {/* CTA Schedule Visit Button */}
              <motion.button
                initial={{ opacity: 0, y: 8 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.4, delay: 0.5 }}
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                onClick={onOpenSchedule}
                className="inline-flex items-center gap-2 bg-white hover:bg-zinc-100 text-zinc-950 font-extrabold text-xs uppercase tracking-widest px-6 py-3.5 shadow-2xl transition duration-150 rounded-xs"
              >
                <ChevronRight size={15} className="text-zinc-900 stroke-[3]" />
                {currentSlide.ctaButtonText}
              </motion.button>
            </motion.div>
          </AnimatePresence>
        </motion.div>

        {/* Automatic Continuous 5-Second Carousel Indicator Controls */}
        <div className="flex items-center gap-6 mt-6 z-20">
          <div className="flex items-center gap-2.5">
            {HERO_SLIDES.map((slide, idx) => (
              <button
                key={slide.id}
                onClick={() => setActiveSlideIdx(idx)}
                className={`relative h-2 rounded-full transition-all duration-300 ${
                  activeSlideIdx === idx ? "w-9 bg-[#c5a059]" : "w-2 bg-white/40 hover:bg-white/70"
                }`}
                aria-label={`Go to slide ${idx + 1}`}
              >
                {activeSlideIdx === idx && (
                  <motion.div
                    layoutId="heroSlideProgress"
                    className="absolute inset-0 bg-[#e5c158] rounded-full"
                    transition={{ duration: 0.3 }}
                  />
                )}
              </button>
            ))}
          </div>

          <div className="text-white/70 font-mono text-xs font-bold tracking-widest">
            0{activeSlideIdx + 1} / 0{HERO_SLIDES.length}
          </div>
        </div>

      </div>
    </section>
  );
}
