import { useState, useEffect, useRef } from 'react';
import { motion, useScroll, useTransform, useInView } from 'motion/react';
import { ImageWithFallback } from './figma/ImageWithFallback';

// Journey steps data
const journeySteps = [
  {
    id: 1,
    title: "Choose Your City",
    subtitle: "Select Your Destination", 
    description: "Browse our collection of amazing cities and pick the perfect destination for your next adventure. Each city offers unique experiences and attractions.",
    leftImage: "https://images.unsplash.com/photo-1604488632867-721fbeda8451?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxjaXR5JTIwc2t5bGluZSUyMHNlbGVjdGlvbiUyMHRyYXZlbCUyMGRlc3RpbmF0aW9ufGVufDF8fHx8MTc1NjIwMTkzMXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1754299520114-a04483392973?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0cmF2ZWwlMjBndWlkZSUyMG1hcCUyMGRlc3RpbmF0aW9ufGVufDF8fHx8MTc1NjIwMTkzN3ww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  },
  {
    id: 2,
    title: "Select Your Pass",
    subtitle: "Pick Your Perfect Plan",
    description: "Choose from our flexible pass options that match your travel style and duration. From 1-day express to 7-day explorer passes.",
    leftImage: "https://images.unsplash.com/photo-1721632093726-da7496162bd9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxkaWdpdGFsJTIwcGFzcyUyMHRpY2tldCUyMG1vYmlsZSUyMHBob25lfGVufDF8fHx8MTc1NjIwMTkzMXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1567748534085-467f8a8a475d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0cmF2ZWwlMjB0aWNrZXRzJTIwYm9hcmRpbmclMjBwYXNzfGVufDF8fHx8MTc1NjIwMTkzOXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  },
  {
    id: 3,
    title: "Plan Your Itinerary",
    subtitle: "Create Your Schedule",
    description: "Use our smart planning tools to create the perfect itinerary with skip-the-line access to your favorite attractions and experiences.",
    leftImage: "https://images.unsplash.com/photo-1532594722383-b75fb8381b55?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0cmF2ZWwlMjBwbGFubmluZyUyMGl0aW5lcmFyeSUyMG5vdGVib29rfGVufDF8fHx8MTc1NjIwMTkzMnww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1654763001178-a263a55f9821?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxjaXR5JTIwYXJjaGl0ZWN0dXJlJTIwYnVpbGRpbmdzfGVufDF8fHx8MTc1NjE2NDk5Mnww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  },
  {
    id: 4,
    title: "Download the App",
    subtitle: "Get Mobile Access",
    description: "Download our mobile app to have instant access to your digital pass, maps, and real-time updates wherever you go.",
    leftImage: "https://images.unsplash.com/photo-1587573578335-9672da4d0292?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxtb2JpbGUlMjBhcHAlMjBkb3dubG9hZCUyMHNtYXJ0cGhvbmV8ZW58MXx8fHwxNzU2MTk2ODkzfDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1755286218783-5b8334109336?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHxzbWFydHBob25lJTIwdHJhdmVsJTIwYXBwcyUyMGludGVyZmFjZXxlbnwxfHx8fDE3NTYyMDE5Mzl8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  },
  {
    id: 5,
    title: "Enjoy Your Adventure",
    subtitle: "Explore & Discover",
    description: "Show your digital pass and enjoy instant access to attractions, tours, and experiences. No more waiting in long ticket lines.",
    leftImage: "https://images.unsplash.com/photo-1695554124271-f26da5212a14?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0b3VyaXN0JTIwYXR0cmFjdGlvbnMlMjBhZHZlbnR1cmUlMjBleHBsb3JhdGlvbnxlbnwxfHx8fDE3NTYyMDE5MzJ8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1662714183155-f5d955df7e05?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0b3VyaXN0JTIwbGFuZG1hcmslMjBtdXNldW0lMjBhdHRyYWN0aW9ufGVufDF8fHx8MTc1NjIwMTkzOXww&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  },
  {
    id: 6,
    title: "Create Memories",
    subtitle: "Share Your Journey",
    description: "Capture amazing moments and share your experiences with friends. Rate attractions and help future travelers discover the best spots.",
    leftImage: "https://images.unsplash.com/photo-1594269732608-e9897da9baab?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0cmF2ZWwlMjBwaG90b2dyYXBoeSUyMG1lbW9yaWVzJTIwc2hhcmluZ3xlbnwxfHx8fDE3NTYyMDE5MzJ8MA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral",
    rightImage: "https://images.unsplash.com/photo-1649310655785-abdb55366303?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3w3Nzg4Nzd8MHwxfHNlYXJjaHwxfHx0cmF2ZWwlMjBqb3VybmFsJTIwY2FtZXJhJTIwbWVtb3JpZXN8ZW58MXx8fHwxNzU2MjAxOTM5fDA&ixlib=rb-4.1.0&q=80&w=1080&utm_source=figma&utm_medium=referral"
  }
];

// Individual step component
interface JourneyStepProps {
  step: typeof journeySteps[0];
  index: number;
  isActive: boolean;
  globalScrollProgress: any;
}

function JourneyStep({ step, index, isActive, globalScrollProgress }: JourneyStepProps) {
  // Calculate simple parallax effects based on activity
  const leftCardOffset = isActive ? 0 : -200;
  const rightCardOffset = isActive ? 0 : 200;
  const textOffset = isActive ? 0 : 40;

  return (
    <motion.div
      className="absolute inset-0 flex items-center justify-center px-8"
      initial={{ opacity: index === 0 ? 1 : 0 }}
      animate={{ opacity: isActive ? 1 : 0 }}
      transition={{ duration: 0.6, ease: [0.25, 0.1, 0.25, 1] }}
    >
      {/* Background gradient overlay - Light mode */}
      <div className="absolute inset-0 bg-gradient-to-b from-white/90 via-gray-100/70 to-white/90" />

      {/* Left Image Card */}
      <motion.div
        className="absolute left-[10%] top-1/2 -translate-y-1/2 w-64 h-80 z-10"
        initial={{ x: index === 0 ? 0 : -200, opacity: index === 0 ? 1 : 0, rotate: -5 }}
        animate={isActive ? { x: 0, opacity: 1, rotate: -5 } : { x: -200, opacity: 0, rotate: -5 }}
        transition={{ duration: 0.8, delay: isActive ? 0.2 : 0, ease: [0.25, 0.1, 0.25, 1] }}
      >
        <div className="relative w-full h-full rounded-3xl overflow-hidden border-4 border-white shadow-2xl transform rotate-[-5deg]">
          <ImageWithFallback
            src={step.leftImage}
            alt={`${step.title} - Left`}
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black/10 to-transparent" />
        </div>
      </motion.div>

      {/* Right Image Card */}
      <motion.div
        className="absolute right-[10%] top-1/2 -translate-y-1/2 w-64 h-80 z-10"
        initial={{ x: index === 0 ? 0 : 200, opacity: index === 0 ? 1 : 0, rotate: 5 }}
        animate={isActive ? { x: 0, opacity: 1, rotate: 5 } : { x: 200, opacity: 0, rotate: 5 }}
        transition={{ duration: 0.8, delay: isActive ? 0.4 : 0, ease: [0.25, 0.1, 0.25, 1] }}
      >
        <div className="relative w-full h-full rounded-3xl overflow-hidden border-4 border-white shadow-2xl transform rotate-[5deg]">
          <ImageWithFallback
            src={step.rightImage}
            alt={`${step.title} - Right`}
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-black/10 to-transparent" />
        </div>
      </motion.div>

      {/* Center Text Content */}
      <motion.div
        className="relative z-20 text-center max-w-2xl mx-auto px-8"
        initial={{ y: index === 0 ? 0 : 40, opacity: index === 0 ? 1 : 0 }}
        animate={isActive ? { y: 0, opacity: 1 } : { y: 40, opacity: 0 }}
        transition={{ duration: 0.8, delay: isActive ? 0.1 : 0, ease: [0.25, 0.1, 0.25, 1] }}
      >
        {/* Step Number */}
        <motion.div
          className="inline-block mb-6 px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-full"
          initial={{ scale: index === 0 ? 1 : 0 }}
          animate={isActive ? { scale: 1 } : { scale: 0 }}
          transition={{ duration: 0.5, delay: isActive ? 0.3 : 0, ease: [0.25, 0.1, 0.25, 1] }}
        >
          <span className="text-white font-semibold text-lg">Step {step.id}</span>
        </motion.div>

        {/* Title with mixed font weights - Dark text for light mode */}
        <motion.h2
          className="mb-4"
          initial={{ y: index === 0 ? 0 : 20, opacity: index === 0 ? 1 : 0 }}
          animate={isActive ? { y: 0, opacity: 1 } : { y: 20, opacity: 0 }}
          transition={{ duration: 0.6, delay: isActive ? 0.4 : 0, ease: [0.25, 0.1, 0.25, 1] }}
        >
          <span className="text-5xl text-foreground font-light">
            {step.title.split(' ').slice(0, -1).join(' ')}{' '}
          </span>
          <span className="text-5xl text-foreground font-bold italic">
            {step.title.split(' ').slice(-1)[0]}
          </span>
        </motion.h2>

        {/* Subtitle with gradient */}
        <motion.h3
          className="mb-6 text-2xl font-semibold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent"
          initial={{ y: index === 0 ? 0 : 20, opacity: index === 0 ? 1 : 0 }}
          animate={isActive ? { y: 0, opacity: 1 } : { y: 20, opacity: 0 }}
          transition={{ duration: 0.6, delay: isActive ? 0.5 : 0, ease: [0.25, 0.1, 0.25, 1] }}
        >
          {step.subtitle}
        </motion.h3>

        {/* Description - Muted text for light mode */}
        <motion.p
          className="text-xl text-muted-foreground leading-relaxed max-w-xl mx-auto font-poppins"
          initial={{ y: index === 0 ? 0 : 20, opacity: index === 0 ? 1 : 0 }}
          animate={isActive ? { y: 0, opacity: 1 } : { y: 20, opacity: 0 }}
          transition={{ duration: 0.6, delay: isActive ? 0.6 : 0, ease: [0.25, 0.1, 0.25, 1] }}
        >
          {step.description}
        </motion.p>
      </motion.div>
    </motion.div>
  );
}

// Main component
export function ScrollAnimatedJourney() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [activeStep, setActiveStep] = useState(0);
  
  // Scroll progress for the entire section
  const { scrollYProgress } = useScroll({
    target: containerRef,
    offset: ["start center", "end center"]
  });

  // Calculate which step should be active based on scroll progress
  useEffect(() => {
    const unsubscribe = scrollYProgress.on("change", (progress) => {
      // Ensure we have at least the first step active when progress is very low
      const newActiveStep = Math.max(0, Math.min(Math.floor(progress * journeySteps.length), journeySteps.length - 1));
      setActiveStep(newActiveStep);
    });

    return () => unsubscribe();
  }, [scrollYProgress]);

  return (
    <section className="relative bg-gradient-to-b from-gray-50/50 to-white" ref={containerRef}>
      {/* Section Header */}
      <div className="relative z-10 py-20 text-center">
        <div className="container mx-auto px-4">
          <motion.div
            initial={{ y: 30, opacity: 0 }}
            whileInView={{ y: 0, opacity: 1 }}
            viewport={{ once: true }}
            transition={{ duration: 0.8, ease: [0.25, 0.1, 0.25, 1] }}
          >
            <h2 className="mb-6">
              <span className="text-5xl md:text-6xl text-foreground font-light">Your</span>{' '}
              <span className="text-5xl md:text-6xl font-bold italic bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                Journey
              </span>{' '}
              <span className="text-5xl md:text-6xl text-foreground font-light">Starts Here</span>
            </h2>
            <p className="text-xl text-muted-foreground max-w-2xl mx-auto font-poppins">
              Follow these simple steps to unlock amazing experiences in your chosen city
            </p>
          </motion.div>
        </div>
      </div>

      {/* Single Journey Steps Container - Tall enough for all steps */}
      <div className="relative h-[4800px] w-full max-w-[1440px] mx-auto overflow-hidden">
        {/* All steps stacked in the same position */}
        {journeySteps.map((step, index) => (
          <JourneyStep
            key={step.id}
            step={step}
            index={index}
            isActive={activeStep === index}
            globalScrollProgress={scrollYProgress}
          />
        ))}

        {/* Step Progress Indicator - Fixed position */}
        <div className="fixed bottom-8 left-1/2 -translate-x-1/2 flex space-x-3 z-30">
          {journeySteps.map((_, i) => (
            <div
              key={i}
              className={`w-2 h-2 rounded-full transition-all duration-300 ${
                i === activeStep ? 'bg-primary w-8' : 'bg-muted-foreground/30'
              }`}
            />
          ))}
        </div>
      </div>

      {/* Background Effects - Light mode */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <motion.div
          className="absolute top-1/4 -left-32 w-64 h-64 bg-gradient-to-r from-primary/10 to-secondary/10 rounded-full blur-3xl"
          animate={{
            y: [0, -30, 0],
            x: [0, 20, 0],
          }}
          transition={{
            duration: 8,
            repeat: Infinity,
            ease: "easeInOut"
          }}
        />
        <motion.div
          className="absolute bottom-1/4 -right-32 w-80 h-80 bg-gradient-to-l from-secondary/8 to-primary/8 rounded-full blur-3xl"
          animate={{
            y: [0, 40, 0],
            x: [0, -15, 0],
          }}
          transition={{
            duration: 10,
            repeat: Infinity,
            ease: "easeInOut",
            delay: 1
          }}
        />
      </div>
    </section>
  );
}