why do the destination texts (for example Cyclades|Ionian Islands|Dodecanese|Saronic Gulf) not have the samee animation as the counter?

"use client";

import { useState, useEffect, useRef } from 'react';
import HomeHeader from '../components/HomeHeader/HomeHeader';
import FooterSection from '../components/FooterSection/FooterSection';
import styles from './page.module.css';
import gsap from 'gsap';

const DESTINATIONS = [
  { title: 'Greece', image: '/assets/images/destinations/slideshow/greece.jpg' },
  { title: 'Italy', image: '/assets/images/destinations/slideshow/italy.jpg' },
  { title: 'Monaco', image: '/assets/images/destinations/slideshow/monaco.jpg' },
  { title: 'Croatia', image: '/assets/images/destinations/slideshow/croatia.jpg' },
  { title: 'Montenegro', image: '/assets/images/destinations/slideshow/montenegro.jpg' }
];

const DESCRIPTIONS = [
  [
    'Indonesia is a stunning archipelago',
    'with diverse landscapes and rich',
    'cultural heritage.'
  ],
  [
    'Greece is a stunning archipelago',
    'with diverse landscapes and tall',
    'impressive heritage.'
  ],
  [
    'Indonesia is the stunning archipelago',
    'with diverse landscapes of rich',
    'cultural and heritage.'
  ],
  [
    'Croatia is a stunning archipelago',
    'and diverse landscapes with rich',
    'cultural heritage ok.'
  ],
  [
    'Indonesia of the stunning archipelago',
    'with diverse landscapes of the rich',
    'cultural the heritage.'
  ]
];

export default function DestinationsPage() {
  const [currentSlide, setCurrentSlide] = useState(0);
  const [previousSlide, setPreviousSlide] = useState(0);
  const titleRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const descriptionRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const letterIndexRef = useRef(0);
  const descriptionLetterIndexRef = useRef(0);
  const entranceAnimationRef = useRef<gsap.core.Tween | null>(null); // for title
  const currentEntranceLetters = useRef<HTMLSpanElement[]>([]);
  const descEntranceAnimationRef = useRef<gsap.core.Tween | null>(null); // for description
  const currentEntranceDesc = useRef<HTMLSpanElement[]>([]);
  const counterRef = useRef<HTMLSpanElement>(null);
  const isInitialLoad = useRef(true);

  // Kill only entrance animations and hide interrupted letters/descriptions
  const killEntranceAnimation = () => {
    let wasInterrupted = false;
    if (entranceAnimationRef.current) {
      entranceAnimationRef.current.kill();
      entranceAnimationRef.current = null;
      gsap.set(currentEntranceLetters.current, { opacity: 0, y: 177 });
      currentEntranceLetters.current = [];
      wasInterrupted = true;
    }
    if (descEntranceAnimationRef.current) {
      descEntranceAnimationRef.current.kill();
      descEntranceAnimationRef.current = null;
      gsap.set(currentEntranceDesc.current, { opacity: 0, y: 40 });
      currentEntranceDesc.current = [];
      wasInterrupted = true;
    }
    return wasInterrupted;
  };

  // Animate counter
  const animateCounter = (slideIndex: number) => {
    // Calculate the height of one counter item
    const counterHeight = counterRef.current?.querySelector('span')?.offsetHeight || 0;
    
    if (isInitialLoad.current) {
      console.log(`Initial load - setting counter position to slide ${slideIndex + 1}`);
      if (counterRef.current && counterHeight > 0) {
        // Start with the first item centered by offsetting by half the container height
        // Since the parent has justify-content: center, we need to move up by half container height
        // minus half item height to show the first item
        const containerHeight = counterRef.current.parentElement?.offsetHeight || 0;
        const initialOffset = (containerHeight*2);
        gsap.set(counterRef.current, { y: initialOffset });
      }
      return;
    }
    
    // For subsequent animations, calculate position relative to the initial offset
    if (counterRef.current && counterHeight > 0) {
      const containerHeight = counterRef.current.parentElement?.offsetHeight || 0;
      const initialOffset = (containerHeight*2);
      const translateY = initialOffset - (slideIndex * counterHeight);
      
      console.log(`Animating counter to slide ${slideIndex + 1}, translateY: ${translateY}px`);
      gsap.to(counterRef.current, {
        y: translateY,
        duration: 0.6,
        ease: "power2.out"
      });
    }
  };

  // Navigation functions
  const nextSlide = () => {
    const nextIndex = (currentSlide + 1) % DESTINATIONS.length;
    setCurrentSlide(nextIndex);
  };

  const prevSlide = () => {
    const prevIndex = (currentSlide - 1 + DESTINATIONS.length) % DESTINATIONS.length;
    setCurrentSlide(prevIndex);
  };

  const goToSlide = (index: number) => {
    if (index === currentSlide) return;
    setCurrentSlide(index);
  };

  // Helper function to get description letter count for slide
  const getDescriptionLetterCount = (slideIndex: number) => {
    return DESCRIPTIONS[slideIndex].reduce((count, line) => {
      return count + line.length;
    }, 0);
  };

  // Animation functions
  const animateTitleIn = (slideIndex: number) => {
    // Calculate start and end indices for the current slide
    let startIndex = 0;
    for (let i = 0; i < slideIndex; i++) {
      startIndex += DESTINATIONS[i].title.length;
    }
    const endIndex = startIndex + DESTINATIONS[slideIndex].title.length;
    
    const titleLetters = titleRefs.current.slice(startIndex, endIndex).filter(Boolean);
    currentEntranceLetters.current = titleLetters as HTMLSpanElement[];
    
    console.log(`Starting title entrance animation for slide ${slideIndex}`);
    entranceAnimationRef.current = gsap.fromTo(titleLetters, 
      {
        y: 177,
        opacity: 0.89
      },
      {
        y: 0,
        opacity: 1,
        duration: 0.8,
        ease: "power2.out",
        stagger: 0.04,
        delay: 0.2,
        onComplete: () => {
          entranceAnimationRef.current = null;
          currentEntranceLetters.current = [];
        }
      }
    );
  };

  const animateDescIn = (slideIndex: number) => {
    // Get all current description lines
    const descLines = descRefs.current.slice(0, DESCRIPTIONS[slideIndex].length).filter(Boolean);
    currentEntranceDesc.current = descLines as HTMLSpanElement[];
    descEntranceAnimationRef.current = gsap.fromTo(descLines, 
      {
        y: 40,
        opacity: 0.89
      },
      {
        y: 0,
        opacity: 1,
        duration: 0.7,
        ease: "power2.out",
        stagger: 0.08,
        delay: 0.2,
        onComplete: () => {
          descEntranceAnimationRef.current = null;
          currentEntranceDesc.current = [];
        }
      }
    );
  };

  const animateTitleOut = (slideIndex: number) => {
    console.log(`Starting title exit animation for slide ${slideIndex}`);
    // Calculate start and end indices for the current slide
    let startIndex = 0;
    for (let i = 0; i < slideIndex; i++) {
      startIndex += DESTINATIONS[i].title.length;
    }
    const endIndex = startIndex + DESTINATIONS[slideIndex].title.length;
    
    const titleLetters = titleRefs.current.slice(startIndex, endIndex).filter(Boolean);
    
    gsap.to(titleLetters, {
      y: "-120%",
      opacity: 0,
      duration: 0.4,
      ease: "power2.in",
      stagger: 0.02
    });
  };

  const animateDescOut = (slideIndex: number) => {
    // Get all current description lines
    const descLines = descRefs.current.slice(0, DESCRIPTIONS[slideIndex].length).filter(Boolean);
    gsap.to(descLines, {
      y: "-40%",
      opacity: 0,
      duration: 0.3,
      ease: "power2.in",
      stagger: 0.04,
    });
  };

  // Handle counter animation when currentSlide changes
  useEffect(() => {
    if (!isInitialLoad.current) {
      animateCounter(currentSlide);
    }
  }, [currentSlide]);

  // Handle slide changes with interruption logic
  useEffect(() => {
    if (titleRefs.current.length > 0 && previousSlide !== currentSlide) {
      console.log(`Slide change: ${previousSlide} -> ${currentSlide}`);
      
      // Check if there are entrance animations running and kill them
      const wasInterrupted = killEntranceAnimation();
      
      if (wasInterrupted) {
        console.log('Animation was interrupted - skipping exit animation, starting entrance immediately');
        // If we interrupted entrance animations, skip the exit animations
        // and start the new entrance animations immediately
        animateTitleIn(currentSlide);
        animateDescIn(currentSlide);
        setPreviousSlide(currentSlide);
      } else {
        console.log('Normal slide change - exit animations then entrance animations');
        // Normal flow: animate out previous slide, then animate in new slide
        animateTitleOut(previousSlide);
        animateDescOut(previousSlide);
        
        setTimeout(() => {
          animateTitleIn(currentSlide);
          animateDescIn(currentSlide);
          setPreviousSlide(currentSlide);
        }, 300);
      }
    }
  }, [currentSlide, previousSlide]);

  // Initial animation for first slide
  useEffect(() => {
    const timer = setTimeout(() => {
      if (titleRefs.current.length > 0 || descriptionRefs.current.length > 0) {
        animateTitleIn(0);
        animateDescIn(0);
        setPreviousSlide(0);
        // Set initial counter position after a brief delay to ensure DOM is ready
        setTimeout(() => {
          animateCounter(0);
          isInitialLoad.current = false;
        }, 50);
      }
    }, 100);
    
    return () => clearTimeout(timer);
  }, []);

  // Cleanup animations on unmount
  useEffect(() => {
    return () => {
      if (entranceAnimationRef.current) {
        entranceAnimationRef.current.kill();
      }
      if (descEntranceAnimationRef.current) {
        descEntranceAnimationRef.current.kill();
      }
    };
  }, []);

  // Initialize title letters refs
  const setTitleLetterRef = (el: HTMLSpanElement | null, index: number) => {
    titleRefs.current[index] = el;
  };

  // Initialize description letters refs
  const setDescriptionLetterRef = (el: HTMLSpanElement | null, index: number) => {
    descriptionRefs.current[index] = el;
  };

  // Initialize description lines refs
  const descRefs = useRef<(HTMLSpanElement | null)[]>([]);
  const setDescLineRef = (el: HTMLSpanElement | null, index: number) => {
    descRefs.current[index] = el;
  };

  // Reset letter indices for each render
  letterIndexRef.current = 0;
  descriptionLetterIndexRef.current = 0;

  return (
    <>
      <HomeHeader forceScrolled={false} />
      <div className={styles.destinations}>
        <div className={styles.destinationsContainer}>
          <div className={styles.destinationWrapper}>
            <div className={styles.destinationsSlideshow}>
              <div className={styles.slideshowWrapper}>
                <div className={styles.imageWrapper}>
                  <img 
                    src={DESTINATIONS[currentSlide].image} 
                    alt={DESTINATIONS[currentSlide].title}
                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  />
                </div>
                <div className={styles.imageOverlay}></div>
                <div className={styles.destinationsContent}>
                  <div className={styles.titleWrapper}>
                    {DESTINATIONS.map((destination, idx) => (
                      <span key={destination.title} style={{ opacity: 1, transition: 'none' }}>
                        <h2 className={styles.destinationTitle}>
                          <span className={styles.maskingText}>
                            <span className={styles.textLine}>
                              {destination.title.split("").map((letter, i) => {
                                const globalIndex = letterIndexRef.current++;
                                return (
                                  <span 
                                    key={i} 
                                    className={styles.letter}
                                    ref={(el) => setTitleLetterRef(el, globalIndex)}
                                    style={{ 
                                      transform: 'translateY(177px)',
                                      opacity: 0
                                    }}
                                  >
                                    {letter}
                                  </span>
                                );
                              })}
                            </span>
                          </span>
                        </h2>
                      </span>
                    ))}
                  </div>
                  <div className={styles.border}></div>
                  <div className={styles.centerContent}>
                    <div className={styles.exploreTextContainer}>
                      <div className={styles.exploreTextWrap}>
                        <span className={styles.exploreIcon}>
                          <img src="/assets/icons/exploreIcon.svg" alt="Explore" style={{ width: 24, height: 24 }} />
                        </span>
                        <span className={styles.exploreText}>
                          <h2 className={styles.exploreTextTitle}>Explore Itineraries</h2>
                        </span>
                      </div>
                    </div>
                    <div className={styles.locationsContainer}>
                      {[
                        // Greece
                        ["Cyclades", "|", "Ionian Islands", "|", "Dodecanese", "|", "Saronic Gulf"],
                        // Italy
                        ["Amalfi Coast", "|", "Aeolian Islands", "|", "Sardinia"],
                        // Monaco
                        ["French Riviera"],
                        // Croatia
                        ["Dalmatian Islands", "|", "Dubrovnik & Mljet"],
                        // Montenegro
                        ["Bay of Kotor"]
                      ].map((locations, idx) => (
                        <span key={idx} style={{ display: idx === currentSlide ? 'block' : 'none' }}>
                          <span className={styles.locationWraps}>
                            <span className={styles.locationTextWrap}>
                              {locations.map((loc, i) => (
                                <span key={i} style={{
                                  color: '#fff',
                                  fontFamily: 'Inter Tight',
                                  fontSize: 'calc(20 / 1440 * 100vw)',
                                  fontWeight: 400,
                                  lineHeight: 1,
                                  display: 'inline',
                                  marginRight: loc === '|' ? '0.5em' : '0.25em',
                                  opacity: loc === '|' ? 0.5 : 1
                                }}>{loc}</span>
                              ))}
                            </span>
                          </span>
                        </span>
                      ))}
                    </div>
                    <div className={styles.counterWrap}>
                      <span className={styles.counterCurrent}>
                        <span 
                          ref={counterRef}
                          style={{
                            color: '#fff', 
                            fontFamily: 'Inter Tight', 
                            fontSize: 'calc(20 / 1440 * 100vw)', 
                            fontWeight: 400, 
                            lineHeight: 1,
                            display: 'flex',
                            flexDirection: 'column',
                            transform: 'translateY(0px)',
                          }}
                        >
                          {DESTINATIONS.map((_, index) => (
                            <span 
                              key={index} 
                              style={{ 
                                height: 'calc(2000svh / 812)', 
                                display: 'flex', 
                                alignItems: 'center',
                                justifyContent: 'center',
                                flexShrink: 1
                              }}
                            >
                              {String(index + 1).padStart(2, '0')}
                            </span>
                          ))}
                        </span>
                      </span>
                      <span className={styles.counterTotal}>
                        <span style={{color: '#fff', fontFamily: 'Inter Tight', fontSize: 'calc(20 / 1440 * 100vw)', fontWeight: 400, lineHeight: 1, opacity: 0.9, margin: '0 0.2em'}}> / </span>
                        <span style={{color: '#fff', fontFamily: 'Inter Tight', fontSize: 'calc(20 / 1440 * 100vw)', fontWeight: 400, lineHeight: 1, opacity: 0.9}}>
                          {String(DESTINATIONS.length).padStart(2, '0')}
                        </span>
                      </span>
                    </div>
                  </div>
                  <div className={styles.border}></div>
                  <div className={styles.bottomContent}>
                    <div className={styles.descriptionContainer}>
                      <span>
                        <span className={styles.descriptionWrapper}>
                          {DESCRIPTIONS[currentSlide].map((line, i) => (
                            <span className={styles.descriptionParts} key={i}>
                              <span className={styles.descriptionLine} ref={el => setDescLineRef(el, i)}>{line}</span>
                            </span>
                          ))}
                        </span>
                      </span>
                    </div>
                  </div>
                  <div className={styles.previews}>
                    {DESTINATIONS.map((item, idx) => (
                      <div 
                        className={styles.previewItem} 
                        key={idx}
                        onClick={() => goToSlide(idx)}
                        style={{ cursor: 'pointer', opacity: idx === currentSlide ? 1 : 0.6, transition: 'opacity 0.3s ease' }}
                      >
                        <h3 className={styles.previewTitle}>{item.title}</h3>
                        <div className={styles.previewImage}>
                          <div className={styles.previewImageWrapper}>
                            <img src={item.image} alt={item.title} />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}