import React, { useEffect, useRef, useState } from "react";

/**
 * StackedOfferSection Component
 * 
 * @param {Object} props - Component props
 * @param {Array} props.cards - Array of card objects with the following structure:
 *   - id: number
 *   - title: string
 *   - subtitle?: string
 *   - description?: string
 *   - badge?: string
 *   - color: string (no longer used - all cards are white)
 *   - features?: string[]
 *   - stats?: Array<{label: string, value: string}>
 *   - icon?: React.ComponentType
 */

export type StackedOfferCard = {
  id: number;
  title: string;
  subtitle?: string;
  description?: string;
  badge?: string;
  color?: string;
  features?: string[];
  stats?: Array<{ label: string; value: string }>;
  icon?: React.ComponentType<any>;
};

const demoCards: StackedOfferCard[] = [
  {
    id: 1,
    title: "Leadership Foundations",
    subtitle: "Orientation • Strategy",
    description:
      "Build strong leadership behaviors with research-backed frameworks and deliberate practice.",
    badge: "Featured",
    color: "from-indigo-500 to-blue-600", // No longer used
    features: ["Decision Making", "Self-awareness", "Feedback Loops", "Coaching"],
    stats: [
      { label: "Modules", value: "08" },
      { label: "Hours", value: "12" },
      { label: "Format", value: "Self-paced" }
    ]
  },
  {
    id: 2,
    title: "Executive Presence",
    subtitle: "Influence • Communication",
    description:
      "Elevate your impact with persuasive narratives, clarity, and confident delivery.",
    badge: "New",
    color: "from-emerald-500 to-teal-600", // No longer used
    features: ["Narratives", "Storylining", "Speaking", "Signals"],
    stats: [
      { label: "Modules", value: "06" },
      { label: "Hours", value: "10" },
      { label: "Format", value: "Cohort" }
    ]
  },
  {
    id: 3,
    title: "Strategic Execution",
    subtitle: "Operating Rhythm",
    description:
      "Translate strategy into outcomes with ruthless prioritization and cadence.",
    color: "from-rose-500 to-orange-500", // No longer used
    features: ["OKRs", "Cadence", "Reviews", "Debriefs"],
    stats: [
      { label: "Modules", value: "07" },
      { label: "Hours", value: "11" },
      { label: "Format", value: "Hybrid" }
    ]
  },
  {
    id: 4,
    title: "Change Leadership",
    subtitle: "Adoption • Momentum",
    description:
      "Lead transformation with systems thinking and stakeholder alignment.",
    color: "from-purple-500 to-fuchsia-600", // No longer used
    features: ["Systems", "Stakeholders", "Momentum", "Sustain"],
    stats: [
      { label: "Modules", value: "05" },
      { label: "Hours", value: "09" },
      { label: "Format", value: "Self-paced" }
    ]
  }
];

type StackedOfferSectionProps = {
  cards?: StackedOfferCard[];
  headingTitle?: string;
  headingEmphasis?: string;
  headingDescription?: string;
};

export default function StackedOfferSection({
  cards = demoCards,
  headingTitle = "What We",
  headingEmphasis = "Offer",
  headingDescription = "Comprehensive executive leadership development solutions designed to transform\nsenior leadership capabilities and drive organizational excellence.",
}: StackedOfferSectionProps) {
  const sectionRef = useRef<HTMLDivElement | null>(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [stickyStartPosition, setStickyStartPosition] = useState<number | null>(null);
  const [isSticky, setIsSticky] = useState(false);

  // Constants - Increased card height from 400px to 480px
  const CARD_HEIGHT = 480;
  const SCROLL_PER_CARD = 500; // Pixels to scroll for each card

  useEffect(() => {
    let ticking = false;

    const handleScroll = () => {
      if (!ticking) {
        requestAnimationFrame(() => {
          if (!sectionRef.current) return;

          const section = sectionRef.current;
          const rect = section.getBoundingClientRect();
          const currentScrollY = window.scrollY;
          
          // Check if section has reached the top (becomes sticky)
          const sectionIsSticky = rect.top <= 0;
          
          if (sectionIsSticky && !isSticky) {
            // Section just became sticky - record the scroll position
            setStickyStartPosition(currentScrollY);
            setIsSticky(true);
            setActiveIndex(0); // Start with first card
            return;
          } else if (!sectionIsSticky && isSticky) {
            // Section is no longer sticky - reset everything
            setIsSticky(false);
            setStickyStartPosition(null);
            setActiveIndex(0);
            return;
          }

          // If section is sticky and we have a starting position
          if (sectionIsSticky && stickyStartPosition !== null) {
            // Calculate how much we've scrolled since becoming sticky
            const scrolledSinceSticky = currentScrollY - stickyStartPosition;
            
            // Determine which card should be active based on scroll distance
            let newCardIndex = 0;
            
            if (scrolledSinceSticky >= SCROLL_PER_CARD * 3) {
              newCardIndex = 3; // Card 4 (Change Leadership)
            } else if (scrolledSinceSticky >= SCROLL_PER_CARD * 2) {
              newCardIndex = 2; // Card 3 (Strategic Execution)
            } else if (scrolledSinceSticky >= SCROLL_PER_CARD) {
              newCardIndex = 1; // Card 2 (Executive Presence)
            } else {
              newCardIndex = 0; // Card 1 (Leadership Foundations)
            }

            // Only update if card index has changed
            if (newCardIndex !== activeIndex) {
              setActiveIndex(newCardIndex);
            }
          }

          ticking = false;
        });
        ticking = true;
      }
    };

    // Add scroll listener
    window.addEventListener('scroll', handleScroll, { passive: true });
    
    // Initial call
    handleScroll();

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [activeIndex, stickyStartPosition, isSticky]);

  return (
    <div className="relative">
      {/* Sticky Section - What We Offer */}
      <section 
        ref={sectionRef}
        className="sticky top-0 py-20 min-h-screen flex items-center justify-center z-10" 
        style={{ backgroundColor: '#FFFFFF' }}
      >
        <div className="mx-auto section-margin-x">
          {/* Heading */}
          <div className="text-center mb-16 max-w-4xl mx-auto">
            <h2 className="text-h2 mb-6">
              {headingTitle} <span className="text-primary">{headingEmphasis}</span>
            </h2>
            <p className="text-body-lg text-muted" style={{ whiteSpace: 'pre-line' }}>
              {headingDescription}
            </p>
          </div>

          {/* Desktop: Stacking Cards */}
          <div className="hidden lg:block relative">
            {/* Stack Container - Increased width from max-w-2xl to max-w-3xl and height to match new card height */}
            <div className="relative mx-auto max-w-3xl h-[480px]">
              {/* Stack Area */}
              <div className="relative w-full h-full flex items-center justify-center">
                {cards.map((card, index) => {
                  const shouldShow = index <= activeIndex;
                  const isActive = activeIndex === index;
                  
                  return (
                    <div
                      key={card.id}
                      className={`
                        absolute inset-0 transition-all duration-700 ease-out
                        ${shouldShow
                          ? 'opacity-100 translate-y-0 scale-100' 
                          : 'opacity-0 translate-y-full scale-95'
                        }
                      `}
                      style={{
                        zIndex: 10 + index,
                        transitionDelay: shouldShow ? `${index * 100}ms` : '0ms'
                      }}
                    >
                      {/* Card Content - White Background with Brand Colors */}
                      <div
                        className="w-full h-full rounded-3xl p-8 bg-white border border-gray-200 card-shadow-dramatic"
                        style={{ height: `${CARD_HEIGHT}px` }}
                      >
                        {/* Header */}
                        <div className="flex items-start justify-between mb-6">
                          <div className="flex items-center gap-4">
                            <div className="w-16 h-16 rounded-2xl bg-blue-50 border border-blue-100 flex items-center justify-center">
                              {card.icon && <card.icon className="w-8 h-8 text-primary" />}
                            </div>
                            <div>
                              {card.badge && (
                                <span className="inline-flex items-center px-2.5 py-0.5 rounded-md text-primary border border-primary bg-blue-50 mb-2 text-xs font-medium">
                                  {card.badge}
                                </span>
                              )}
                              {card.subtitle && (
                                <div className="text-sm text-muted">{card.subtitle}</div>
                              )}
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="text-4xl font-bold mb-1 text-primary">
                              {String(card.id).padStart(2, "0")}
                            </div>
                            <div className="w-8 h-0.5 bg-primary ml-auto" />
                          </div>
                        </div>

                        {/* Content */}
                        <div className="mb-6">
                          <h3 className="text-h3 mb-3 text-black">{card.title}</h3>
                          {card.description && (
                            <p className="text-body text-muted leading-relaxed mb-4">
                              {card.description}
                            </p>
                          )}
                          {card.features?.length && (
                            <div className="grid grid-cols-2 gap-3">
                              {card.features.map((feature, idx) => (
                                <div key={idx} className="flex items-center gap-2">
                                  <div className="w-1.5 h-1.5 rounded-full bg-primary" />
                                  <span className="text-sm text-black">{feature}</span>
                                </div>
                              ))}
                            </div>
                          )}
                        </div>

                        {/* Footer stats */}
                        {card.stats?.length && (
                          <div className="flex justify-between items-center pt-6 border-t border-gray-200">
                            {card.stats.map((stat, idx) => (
                              <div key={idx} className="text-center">
                                <div className="text-2xl font-bold text-primary">{stat.value}</div>
                                <div className="text-xs text-muted">{stat.label}</div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Progress Indicators */}
          <div className="hidden lg:block fixed right-8 top-1/2 transform -translate-y-1/2 z-50">

          </div>

          {/* Mobile/Tablet: Simple Card List - Updated with White Background */}
          <div className="lg:hidden">
            <div className="space-y-8">
              {cards.map((card, index) => (
                <div
                  key={`mobile-${card.id}`}
                  className="rounded-2xl p-6 bg-white border border-gray-200 card-shadow-elevated card-hover-lift"
                >
                  <div className="flex items-center gap-3 mb-4">
                    <div className="w-12 h-12 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center">
                      {card.icon && <card.icon className="w-6 h-6 text-primary" />}
                    </div>
                    <div>
                      {card.badge && (
                        <span className="inline-block px-2 py-0.5 rounded text-xs bg-blue-50 border border-primary text-primary mb-1 font-medium">
                          {card.badge}
                        </span>
                      )}
                      {card.subtitle && (
                        <div className="text-xs text-muted">{card.subtitle}</div>
                      )}
                    </div>
                  </div>
                  
                  <h3 className="text-h4 mb-2 text-black">{card.title}</h3>
                  {card.description && (
                    <p className="text-body text-muted mb-4">{card.description}</p>
                  )}
                  
                  {card.features?.length && (
                    <div className="grid grid-cols-2 gap-2 mb-4">
                      {card.features.map((feature, idx) => (
                        <div key={idx} className="flex items-center gap-2">
                          <div className="w-1 h-1 rounded-full bg-primary" />
                          <span className="text-xs text-black">{feature}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  
                  {card.stats?.length && (
                    <div className="flex justify-between pt-4 border-t border-gray-200">
                      {card.stats.map((stat, idx) => (
                        <div key={idx} className="text-center">
                          <div className="text-lg font-bold text-primary">{stat.value}</div>
                          <div className="text-xs text-muted">{stat.label}</div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>


        </div>
      </section>

      {/* Optimized Scroll Space - Matches actual scroll distance needed */}
      <div style={{ height: `${SCROLL_PER_CARD * (cards.length - 1) + 100}px` }} className="relative">
        {/* 
        This div creates the exact scroll space needed for card reveals:
        - Card 1: 0px (immediately when sticky)
        - Card 2: 200px
        - Card 3: 400px  
        - Card 4: 600px
        Total: 600px + 100px buffer = 700px
        */}
        <div className="w-full h-full" />
      </div>
    </div>
  );
}