'use client';

import { useAuth, useClerk } from '@clerk/nextjs';
import { useParameterStore, useStatsigClient } from '@statsig/react-bindings';
import { AnimatePresence, motion } from 'framer-motion';
import { shuffle } from 'lodash-es';
import { observer } from 'mobx-react-lite';
import dynamic from 'next/dynamic';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { useInView } from 'react-intersection-observer';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Logo from '@/components/image/Logo';
import { useMobileBanner } from '@/context/MobileBannerContext';
import { useBreakpointLg } from '@/hooks/useBreakpoint';
import usePageViewLog from '@/hooks/usePageViewLog';
import { useScrollToSection } from '@/hooks/useScrollToSection';
import { useSproutTracking } from '@/hooks/useSproutTracking';
import { HomePageSectionName } from '@/logging/eventTypes/HomePageEventType';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  REFERRER_PARAM,
  SIGNUP_SOURCE_PARAM,
  SIGNUP_SOURCE_VALUES,
} from '@/utils/constants';
import {
  getClerkSignInRedirectProps,
  getClerkSignUpRedirectProps,
  getRandomAuraURL,
} from '@/utils/utils';

import { BackgroundSongCard } from './components/BackgroundSongCard';
import { HighlightItemProps } from './components/HighlightItem';
import MusicianCreate from './components/MusicianCreate';
import { NonAuthAntiAbuse } from './components/NonAuthAntiAbuse';
import { useNonAuthAntiAbuse } from './hooks/useNonAuthAntiAbuse';
import { useNonAuthGeneration } from './hooks/useNonAuthGeneration';
import BestAppSection from './sections/BestAppSection';
import CreateSongDemoSection from './sections/CreateSongDemoSection';
import FeatureHighlightsSection from './sections/FeatureHighlightsSection';
import FeaturedCreatorsSection from './sections/FeaturedCreatorsSection';
import FeaturedSongsSection from './sections/FeaturedSongsSection';
import FooterSection from './sections/FooterSection';
import HeroSection from './sections/HeroSection';
//import MakeMusicEverywhereSection from './sections/MakeMusicEverywhereSection';
import { PricingSection } from './sections/PricingSection';
import SongPreviewSection from './sections/SongPreviewSection';
import { MarketingStoreProvider } from './stores/MarketingStoreContext';
import { TURNSTILE_CONTAINER_IDS } from './types/antiAbuse';
import {
  NONAUTH_SPLASH_GEN_FLOW,
  NonAuthSplashGenFlow,
} from './types/parameterStore';
import { HERO_SONGS, HERO_VIDEOS, HIGHLIGHTS } from './utils/data';
import { getRandomTypingPhrase } from './utils/utils';

const SimplePlayer = dynamic(
  () => import('@/components/playbar/SimplePlayer'),
  { ssr: false }
);

interface SectionViewLoggerProps {
  sectionName: HomePageSectionName;
  threshold?: number;
}

const loggedSections = new Map<string, boolean>();

export const SectionViewLogger: React.FC<SectionViewLoggerProps> = ({
  sectionName,
  threshold = 0.5,
}) => {
  const { ref } = useInView({
    threshold,
    onChange: (inView) => {
      if (inView && !loggedSections.get(sectionName)) {
        logWebUserEvent({
          actionName: 'HomePageSectionViewed',
          context: {
            sectionName,
          },
        });
        loggedSections.set(sectionName, true);
      }
    },
  });

  return <div ref={ref} />;
};

export enum HomePageScreens {
  HOME = 'home',
  GENERATE = 'generate',
  MUSICIAN = 'musician',
}

const STATSIG_READY_TIMEOUT = 5000;

interface TypingText {
  text: string;
  className: string;
  once?: boolean;
}

interface VideoMedia {
  id: string;
  videoUrl: string;
  posterUrl: string;
  title: string;
  artistName: string;
  playCount: number;
  likeCount: number;
}

// NEW: Decorative graphics system for campaign landing pages
export interface DecorativeGraphic {
  id: string;
  src: string; // CDN URL or /public path
  alt?: string;
  type: 'image' | 'gif' | 'video';

  // Positioning
  position: {
    // Desktop positioning
    desktop: {
      top?: string; // CSS values: '10%', '50px', 'auto'
      left?: string;
      right?: string;
      bottom?: string;
      transform?: string; // Optional transform for rotation, scale, etc
      display?: 'block' | 'none'; // Hide on desktop if needed
    };
    // Tablet positioning (optional, falls back to desktop)
    tablet?: {
      top?: string;
      left?: string;
      right?: string;
      bottom?: string;
      transform?: string;
      display?: 'block' | 'none'; // Hide on tablet if needed
    };
    // Mobile positioning (optional, falls back to tablet/desktop)
    mobile?: {
      top?: string;
      left?: string;
      right?: string;
      bottom?: string;
      transform?: string;
      display?: 'block' | 'none'; // Hide on mobile if needed
    };
  };

  // Sizing
  size: {
    desktop: { width?: string; height?: string };
    tablet?: { width?: string; height?: string };
    mobile?: { width?: string; height?: string };
  };

  // Animation (using framer-motion)
  animation?: {
    type: 'float' | 'pulse' | 'rotate' | 'none';
    duration?: number; // seconds
    delay?: number;
    easing?: 'linear' | 'easeInOut' | 'easeIn' | 'easeOut';
    // Custom framer-motion animation if needed (use any valid motion.div props)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    custom?: any;
  };

  // Behavior
  interactive?: {
    clickable?: boolean;
    onClick?: 'open-url' | 'scroll-to' | 'none';
    target?: string; // URL or section ID
  };

  // Layering
  zIndex?: number;
  opacity?: number;
}

export interface CampaignContent {
  hero: {
    title?: string; // Static title - takes precedence over typingText
    typingText?: TypingText[]; // Typing animation - only used if title is not provided
    subHeading: string;
    backgroundImage?: string;
  };
  featuredSongs: {
    playlist_id: string;
    heading: string;
    subHeading: string;
  };
  featuredVideos: {
    heading: string;
    subHeading: string;
    videoMediaUrls: VideoMedia[];
  };
  // NEW optional sections for localization
  navigation?: {
    signIn?: string;
    signUp?: string;
    create?: string;
    clerkHeaderTitle?: string;
  };
  heroInput?: {
    placeholder?: string;
    createButton?: string;
  };
  featureHighlights?: {
    heading?: string;
    features?: HighlightItemProps[];
  };
  pricing?: {
    heading?: string;
    subheading?: string;
    toggleMonthly?: string;
    toggleYearly?: string;
  };
  bestApp?: {
    heading?: string;
    subheading?: string;
    topBadge?: string;
    downloadIos?: string;
    downloadAndroid?: string;
    iosReviews?: string;
    androidReviews?: string;
    iosRating?: string;
    androidRating?: string;
  };
  songGeneration?: {
    songsAlmostReady?: string;
    songsReady?: string;
    signUpToListen?: string;
  };
  signUpButton?: string;

  // NEW: Generic decorative graphics system
  decorativeElements?: {
    hero?: DecorativeGraphic[]; // Graphics for hero section
    global?: DecorativeGraphic[]; // Page-level graphics
    sections?: {
      [sectionName: string]: DecorativeGraphic[];
    };
  };

  // NEW: Hero layout mode
  heroLayout?: {
    mode: 'standard' | 'cta-only'; // Standard = input + button, CTA-only = button only
    ctaAction?: 'generate' | 'scroll-to-pricing' | 'scroll-to-section';
    ctaTarget?: string; // Section ID for scroll target
    hideBackgroundCards?: boolean; // Hide the floating song cards on desktop
  };
}
// all campaign config including the default home page
interface CampaignConfig {
  default: CampaignContent;
  [key: string]: CampaignContent;
}

const HomePage = observer(() => {
  const [isLoading, setIsLoading] = useState(true);
  const [scrollOpacity, setScrollOpacity] = useState(1);
  const containerRef = useRef<HTMLDivElement>(null);
  const clerk = useClerk();
  const pathname = usePathname();

  // Initialize Sprout tracking
  useSproutTracking();
  const [songs, setSongs] = useState(shuffle(HERO_SONGS));
  const [currentPage, setCurrentPage] = useState<HomePageScreens>(
    HomePageScreens.HOME
  );
  const [randomAura1, setRandomAura1] = useState<string>('');
  const [randomAura2, setRandomAura2] = useState<string>('');
  const { isSignedIn } = useAuth();
  const [heroBackgroundLoaded, setHeroBackgroundLoaded] = useState(false);
  const [, setRandomTypingPhrase] = useState<string>('');
  const [songsReady, setSongsReady] = useState(false);
  const [advancedModeEnabled, setAdvancedModeEnabled] = useState(true);
  const [enableLyricsGeneration, setEnableLyricsGeneration] = useState(false);
  const [statsigLoaded, setStatsigLoaded] = useState(false);
  const [campaignContent, setCampaignContent] =
    useState<CampaignContent | null>(null);
  const [campaignId, setCampaignId] = useState<string | null>(null);
  const [isCardsAnimated, setIsCardsAnimated] = useState(false);
  const [isEntranceComplete, setIsEntranceComplete] = useState(false);
  const [enablePreviewGenerations, setEnablePreviewGenerations] =
    useState(false);
  const isDesktop = useBreakpointLg();

  // Anti-abuse hook for Turnstile and Honeypot
  const { containerId, getAntiAbuseTokens } = useNonAuthAntiAbuse({
    containerId: TURNSTILE_CONTAINER_IDS.SPLASH_PAGE,
    enabled: enablePreviewGenerations,
  });

  // Use non-auth generation hook
  const {
    generationResponse,
    isGeneratingSong,
    isGeneratingVisitorToken,
    generateWithVisitorToken,
    requireSignUp,
    hasCachedGeneration,
  } = useNonAuthGeneration({
    enablePreviewGenerations,
    isSignedIn: !!isSignedIn,
  });

  // Check for webview/in-app browser
  // Those browsers may limit JS execution for the typing animation
  const isWebviewAgent =
    typeof window !== 'undefined' &&
    (window.navigator.userAgent.toLowerCase().includes('instagram') ||
      window.navigator.userAgent.toLowerCase().includes('fbav') ||
      window.navigator.userAgent.toLowerCase().includes('fban') ||
      window.navigator.userAgent.toLowerCase().includes('wv'));

  const [randomGenerationTime1] = useState(
    () => Math.floor(Math.random() * 2000) + 1000
  );
  const [randomGenerationTime2] = useState(
    () => Math.floor(Math.random() * 2000) + 1000
  );
  const { isBannerVisible } = useMobileBanner();
  const statsigClient = useStatsigClient();
  const sunoWebStore = useParameterStore('suno-web');
  const [statsigReady, setStatsigReady] = useState(false);

  //const isMobile = !useBreakpointMd();

  useEffect(() => {
    if (statsigClient?.client?.loadingStatus !== 'Ready') return;
    setStatsigLoaded(true);
    const isAdvancedMode = statsigClient.checkGate('splash_page_advanced_mode');
    const enableLyricsGeneration = statsigClient.checkGate(
      'enable-splash-page-lyric-gen'
    );
    setEnableLyricsGeneration(enableLyricsGeneration);

    // Check for non-auth preview feature via parameter store
    const nonAuthSplashGenFlow = sunoWebStore.get(
      'nonauth-splash-gen-flow',
      NONAUTH_SPLASH_GEN_FLOW.REQUIRE_SIGNUP
    ) as NonAuthSplashGenFlow;

    const enableNonAuthPreviews =
      nonAuthSplashGenFlow === NONAUTH_SPLASH_GEN_FLOW.GENERATE_PREVIEW;

    // Check for query parameter override
    if (typeof window !== 'undefined') {
      const urlParams = new URLSearchParams(window.location.search);
      const enablePreviewsParam = urlParams.get('enable_previews') === 'true';

      // Enable when both feature gate and query param are true
      setEnablePreviewGenerations(enableNonAuthPreviews && enablePreviewsParam);
    }

    const experiment = statsigClient.getExperiment(
      'forked-onboarding-experiment'
    );

    if (experiment) {
      const show_forked_onboarding = experiment.get('show_forked_onboarding');
      if (show_forked_onboarding) {
        setAdvancedModeEnabled(true);
      } else {
        setAdvancedModeEnabled(false);
        setCurrentPage(HomePageScreens.HOME);
      }
    } else {
      if (isAdvancedMode) {
        setAdvancedModeEnabled(true);
      } else {
        setAdvancedModeEnabled(false);
        setCurrentPage(HomePageScreens.HOME);
      }
    }
  }, [statsigClient]);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const currentSearch = window.location.search;
    const currentHash = window.location.hash;
    if (currentPage === HomePageScreens.MUSICIAN && advancedModeEnabled) {
      window.history.pushState(
        {},
        '',
        `/home/advanced${currentSearch}${currentHash}`
      );
    } else {
      window.history.pushState({}, '', `/home${currentSearch}${currentHash}`);
    }
  }, [currentPage, advancedModeEnabled]);

  useEffect(() => {
    if (!advancedModeEnabled && pathname === '/home/advanced') {
      setCurrentPage(HomePageScreens.HOME);
    }

    if (
      pathname === '/home/advanced' &&
      currentPage !== HomePageScreens.MUSICIAN
    ) {
      setCurrentPage(HomePageScreens.MUSICIAN);
    } else if (
      pathname === '/home' &&
      currentPage === HomePageScreens.MUSICIAN
    ) {
      setCurrentPage(HomePageScreens.HOME);
    }
  }, [pathname]);

  useEffect(() => {
    if (currentPage === HomePageScreens.GENERATE) {
      setSongsReady(false);

      const timer1 = setTimeout(
        () => {
          setSongsReady(true);
        },
        Math.max(randomGenerationTime1, randomGenerationTime2)
      );

      return () => {
        clearTimeout(timer1);
      };
    }
  }, [currentPage, randomGenerationTime1, randomGenerationTime2]);

  useEffect(() => {
    setRandomTypingPhrase(getRandomTypingPhrase()?.text ?? '');
  }, []);

  // Initialize page and start entrance animations
  useEffect(() => {
    const initializePage = async () => {
      try {
        // Add a small delay to ensure content is ready
        await new Promise((resolve) => setTimeout(resolve, 100));
        setIsLoading(false);

        // animate cards in
        setTimeout(() => {
          setIsCardsAnimated(true);
          setTimeout(() => {
            setIsEntranceComplete(true);
          }, 1000);
        }, 800);
      } catch (error) {
        console.error('Error initializing page:', error);
        setIsLoading(false);
      }
    };

    initializePage();
  }, []); // Only run once on mount

  // Setup scroll listener for opacity effect
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const scrollPosition = container.scrollTop;
      const opacity = Math.max(0, 1 - scrollPosition / 200);
      setScrollOpacity(opacity);
    };

    container.addEventListener('scroll', handleScroll);
    return () => {
      container.removeEventListener('scroll', handleScroll);
    };
  }, []); // Only run once on mount - containerRef.current is intentionally not a dependency

  usePageViewLog({
    actionName: 'PageViewed',
    componentContext: 'home',
  });

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (statsigClient?.client?.loadingStatus !== 'Ready') {
        setStatsigReady(true); // Force ready state after timeout
      }
    }, STATSIG_READY_TIMEOUT);

    if (statsigClient?.client?.loadingStatus === 'Ready') {
      setStatsigReady(true);
      clearTimeout(timeoutId);
      return () => clearTimeout(timeoutId);
    }

    let checkInterval: NodeJS.Timeout;
    const checkStatsig = () => {
      if (statsigClient?.client?.loadingStatus === 'Ready') {
        setStatsigReady(true);
        clearTimeout(timeoutId);
        clearTimeout(checkInterval);
      } else {
        checkInterval = setTimeout(checkStatsig, 100);
      }
    };

    checkInterval = setTimeout(checkStatsig, 100);

    return () => {
      clearTimeout(timeoutId);
      clearTimeout(checkInterval);
    };
  }, [statsigClient]);

  useEffect(() => {
    if (!statsigReady || typeof window === 'undefined') return;

    const urlParams = new URLSearchParams(window.location.search);
    const campaignIdParam = urlParams.get('campaign_id');
    setCampaignId(campaignIdParam);

    if (statsigClient?.client?.loadingStatus === 'Ready') {
      const campaignConfig = statsigClient.getDynamicConfig(
        'splash-page-campaign-config'
      );
      const configContent = campaignConfig.get(
        'content',
        null
      ) as CampaignConfig | null;

      if (configContent) {
        const content =
          campaignIdParam && configContent[campaignIdParam]
            ? configContent[campaignIdParam]
            : configContent.default;

        setCampaignContent(content);

        if (content.hero.typingText && content.hero.typingText.length > 0) {
          const randomPhrase =
            content.hero.typingText[
              Math.floor(Math.random() * content.hero.typingText.length)
            ];
          setRandomTypingPhrase(randomPhrase.text);
        }

        if (content.featuredSongs.playlist_id) {
          const apiUrl = `${process.env.NEXT_PUBLIC_API_BASE}/api/playlist/${content.featuredSongs.playlist_id}`;

          fetch(apiUrl)
            .then((response) => response.json())
            .then(
              (data: {
                playlist_clips?: Array<{ clip?: Record<string, unknown> }>;
              }) => {
                const transformedSongs =
                  data?.playlist_clips?.map((item) => {
                    const clip = item?.clip;
                    return {
                      id: (clip?.id as string) ?? '',
                      imageUrl: (clip?.image_url as string) ?? '',
                      title: (clip?.title as string) ?? '',
                      artistName: (clip?.display_name as string) ?? '',
                      artistImageUrl: (clip?.avatar_image_url as string) ?? '',
                      audioUrl: (clip?.audio_url as string) ?? '',
                      playCount: (clip?.play_count as number) ?? 0,
                      likeCount: (clip?.upvote_count as number) ?? 0,
                    };
                  }) ?? [];
                // Only update songs if we got valid data
                if (transformedSongs.length > 0) {
                  setSongs(shuffle(transformedSongs));
                }
              }
            )
            .catch((error) => {
              console.error('Error fetching campaign songs:', error);
            });
        }
      }
    }
  }, [statsigReady, statsigClient, campaignId]);

  // Memoize hero background URL to prevent unnecessary re-renders
  const heroBackgroundUrl =
    campaignContent?.hero.backgroundImage ||
    'https://cdn-o.suno.com/Aura-1-Hero-Web.jpg';

  // Reset hero background loaded state when image URL actually changes to ensure fade-in transition
  useEffect(() => {
    setHeroBackgroundLoaded(false);
  }, [heroBackgroundUrl]);

  useEffect(() => {
    setRandomAura1(getRandomAuraURL());
    setRandomAura2(getRandomAuraURL());
  }, []); // Empty dependency array ensures this only runs once on mount

  useScrollToSection();

  const clerkRedirectOptions = {
    [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.SPLASH_PAGE,
    [REFERRER_PARAM]: pathname,
  };

  const songPreviewTitleReady =
    generationResponse?.clips?.[0]?.title &&
    generationResponse?.clips?.[0]?.title !== '';

  const handleCreateRedirect = () => {
    if (typeof window === 'undefined') return;
    if (isSignedIn) {
      window.location.href = '/create';
    } else {
      clerk.openSignUp({
        ...getClerkSignUpRedirectProps('/create', clerkRedirectOptions),
        appearance: {
          elements: {
            headerTitle:
              campaignContent?.navigation?.clerkHeaderTitle ||
              'Create your free account',
          },
        },
      });
    }
  };

  const handleLikeClick = () => {
    if (typeof window === 'undefined') return;
    if (isSignedIn) {
      window.location.href = '/create';
    } else {
      return;
    }
  };

  if (isLoading) {
    return (
      <div className='flex h-screen w-full scale-[0.5] items-center justify-center bg-background-primary opacity-50'>
        <div className='flex items-center gap-1'>
          {[...Array(15)].map((_, i) => (
            <div
              key={i}
              className='w-1 animate-waveform rounded-full bg-primary md:w-2'
              style={{
                height: '20px',
                animation: `waveform ${Math.floor(Math.random() * 1000) + 500}ms ease-in-out infinite`,
                animationDelay: `${Math.random() * 0.5}s`,
              }}
            />
          ))}
        </div>
      </div>
    );
  }

  return (
    <MarketingStoreProvider>
      <div className='h-full w-full bg-background-primary'>
        <div
          ref={containerRef}
          className='scrollbar-hide relative flex h-full w-full flex-col overflow-x-hidden overflow-y-scroll scroll-smooth'
        >
          <div className='absolute inset-0 z-0 h-full w-full'>
            {/* image compressed from 1.5mb to 246kb */}
            <ImageWithFallback
              className='absolute inset-0 h-full w-full object-cover transition-opacity duration-[1500ms] ease-in-out'
              style={{
                mixBlendMode: 'screen',
                opacity: heroBackgroundLoaded ? 1 : 0,
              }}
              src={campaignContent?.hero.backgroundImage}
              fallbackSrc='https://cdn-o.suno.com/Aura-1-Hero-Web.jpg'
              alt='Suno background aura'
              onLoad={() => setHeroBackgroundLoaded(true)}
              loading='lazy'
            />
            <div
              className='absolute inset-0'
              style={{
                background: `linear-gradient(180deg, rgba(16, 16, 18, 0.00) 0%, #101012 100%)`,
              }}
            />
          </div>
          <div className='relative z-10'>
            <div
              className={`fixed top-0 right-0 left-0 z-50 w-full p-[20px] ${
                isBannerVisible ? 'top-[72px] md:top-0' : ''
              }`}
            >
              <div className='flex items-center'>
                <div className='flex flex-1 items-start'>
                  <Logo
                    href='/home'
                    className='h-[19.394px] w-[78.709px]'
                    enableDropShadow={false}
                    onClick={() => {
                      if (isSignedIn) {
                        window.location.href = '/';
                      } else {
                        setCurrentPage(HomePageScreens.HOME);
                      }
                    }}
                  />
                </div>
                <div className='flex flex-2 items-start justify-end gap-[10px]'>
                  {!isSignedIn ? (
                    <>
                      <Button
                        variant={ButtonVariant.Secondary}
                        size={ButtonSize.Small}
                        shape={ButtonShape.Pill}
                        onClick={() => {
                          clerk.openSignIn({
                            ...getClerkSignInRedirectProps(
                              '/create',
                              clerkRedirectOptions
                            ),
                          });
                          logWebUserEvent({
                            actionName: 'HomePageNavSignInClicked',
                          });
                        }}
                      >
                        {campaignContent?.navigation?.signIn || 'Sign In'}
                      </Button>
                      <Button
                        variant={ButtonVariant.Primary}
                        size={ButtonSize.Small}
                        shape={ButtonShape.Pill}
                        onClick={() => {
                          handleCreateRedirect();
                          logWebUserEvent({
                            actionName: 'HomePageNavSignUpClicked',
                          });
                        }}
                      >
                        {campaignContent?.navigation?.signUp || 'Sign Up'}
                      </Button>
                    </>
                  ) : (
                    <Button
                      variant={ButtonVariant.Primary}
                      size={ButtonSize.Small}
                      shape={ButtonShape.Rounded}
                      onClick={() => {
                        window.location.href = '/create';
                      }}
                    >
                      {campaignContent?.navigation?.create || 'Create'}
                    </Button>
                  )}
                </div>
              </div>
            </div>

            <AnimatePresence mode='wait'>
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                transition={{
                  type: 'tween',
                  duration: 0.6,
                  ease: 'easeInOut',
                }}
                className={`relative flex min-h-[100vh] animate-fade-in flex-col items-center justify-center ${currentPage === HomePageScreens.HOME ? '' : 'hidden'}`}
                style={{ animationDuration: '600ms' }}
              >
                {isDesktop &&
                  songs &&
                  songs[0] &&
                  !campaignContent?.heroLayout?.hideBackgroundCards && (
                    <BackgroundSongCard
                      song={songs[0]}
                      side='left'
                      containerRef={containerRef}
                      isCardsAnimated={isCardsAnimated}
                      isEntranceComplete={isEntranceComplete}
                      onSongClick={handleCreateRedirect}
                      onLikeClick={handleLikeClick}
                    />
                  )}

                {isDesktop &&
                  songs &&
                  songs[1] &&
                  !campaignContent?.heroLayout?.hideBackgroundCards && (
                    <BackgroundSongCard
                      song={songs[1]}
                      side='right'
                      containerRef={containerRef}
                      isCardsAnimated={isCardsAnimated}
                      isEntranceComplete={isEntranceComplete}
                      onSongClick={handleCreateRedirect}
                      onLikeClick={handleLikeClick}
                    />
                  )}

                <HeroSection
                  key={campaignId || 'default'}
                  campaignContent={campaignContent}
                  isWebviewAgent={isWebviewAgent}
                  scrollOpacity={scrollOpacity}
                  isSignedIn={!!isSignedIn}
                  setCurrentPage={setCurrentPage}
                  advancedModeEnabled={advancedModeEnabled}
                  statsigLoaded={statsigLoaded}
                  onMusicianClick={() => {
                    if (advancedModeEnabled) {
                      setCurrentPage(HomePageScreens.MUSICIAN);
                      logWebUserEvent({
                        actionName: 'HomePageIamMusicianCreateButtonClicked',
                      });
                    }
                  }}
                  onGenerate={async (prompt) => {
                    // Get Turnstile token and honeypot sealed payload before generating
                    const { turnstileToken, honeypotSealed } =
                      await getAntiAbuseTokens();
                    return generateWithVisitorToken(
                      prompt || '',
                      turnstileToken || undefined,
                      honeypotSealed || undefined
                    );
                  }}
                  enablePreviewGenerations={enablePreviewGenerations}
                  hasCachedGeneration={hasCachedGeneration}
                  cachedClip={generationResponse?.clips?.[0] || null}
                  onCreateRedirect={handleCreateRedirect}
                />
              </motion.div>
            </AnimatePresence>

            {currentPage === HomePageScreens.MUSICIAN && (
              <AnimatePresence mode='wait'>
                <motion.section
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  transition={{
                    type: 'tween',
                    duration: 0.5,
                    ease: 'easeInOut',
                  }}
                >
                  <MusicianCreate
                    setCurrentPage={setCurrentPage}
                    handleCreateRedirect={handleCreateRedirect}
                    enableLyricsGeneration={enableLyricsGeneration}
                  />
                </motion.section>
              </AnimatePresence>
            )}

            {currentPage === HomePageScreens.HOME && (
              <>
                <FeaturedSongsSection
                  id='featured-songs'
                  heading={
                    campaignContent?.featuredSongs.heading ||
                    'Mind blowing song quality'
                  }
                  subheading={
                    campaignContent?.featuredSongs.subHeading ||
                    "Whether you have a melody in your head, lyrics you've written, or just a feeling you want to hear—Suno makes high-quality music creation accessible to all."
                  }
                  songs={songs}
                  onSongClick={handleCreateRedirect}
                  onLikeClick={() => {
                    handleLikeClick();
                  }}
                />

                <FeatureHighlightsSection
                  id='features'
                  heading={campaignContent?.featureHighlights?.heading}
                  highlights={
                    campaignContent?.featureHighlights?.features || HIGHLIGHTS
                  }
                />

                <PricingSection
                  id='pricing-section'
                  heading={campaignContent?.pricing?.heading}
                  subheading={campaignContent?.pricing?.subheading}
                  toggleMonthly={campaignContent?.pricing?.toggleMonthly}
                  toggleYearly={campaignContent?.pricing?.toggleYearly}
                />

                <BestAppSection
                  id='app'
                  heading={
                    campaignContent?.bestApp?.heading || 'The #1 AI music app'
                  }
                  subhead={
                    campaignContent?.bestApp?.subheading ||
                    'Where you can discover, create and share from anywhere because music has no boundaries.'
                  }
                  topBadge={campaignContent?.bestApp?.topBadge}
                  downloadIos={campaignContent?.bestApp?.downloadIos}
                  downloadAndroid={campaignContent?.bestApp?.downloadAndroid}
                  iosReviews={campaignContent?.bestApp?.iosReviews}
                  androidReviews={campaignContent?.bestApp?.androidReviews}
                  iosRating={campaignContent?.bestApp?.iosRating}
                  androidRating={campaignContent?.bestApp?.androidRating}
                />

                <FeaturedCreatorsSection
                  id='creators'
                  heading={campaignContent?.featuredVideos.heading}
                  subhead={campaignContent?.featuredVideos.subHeading}
                  videos={
                    campaignContent?.featuredVideos.videoMediaUrls ||
                    HERO_VIDEOS
                  }
                  signUpButton={campaignContent?.signUpButton}
                  onCreateRedirect={handleCreateRedirect}
                />
              </>
            )}

            {currentPage === HomePageScreens.GENERATE &&
              (enablePreviewGenerations ? (
                <SongPreviewSection
                  clip={generationResponse?.clips?.[0] || null}
                  isLoading={
                    requireSignUp
                      ? false
                      : isGeneratingSong ||
                        isGeneratingVisitorToken ||
                        !songPreviewTitleReady
                  }
                  songsAlmostReady={
                    campaignContent?.songGeneration?.songsAlmostReady
                  }
                  songsReadyText={campaignContent?.songGeneration?.songsReady}
                  signUpToListen={
                    campaignContent?.songGeneration?.signUpToListen
                  }
                  onCreateRedirect={handleCreateRedirect}
                  requireSignUp={requireSignUp}
                />
              ) : (
                <CreateSongDemoSection
                  songsReady={songsReady}
                  randomAura1={randomAura1}
                  randomAura2={randomAura2}
                  randomGenerationTime1={randomGenerationTime1}
                  randomGenerationTime2={randomGenerationTime2}
                  songsAlmostReady={
                    campaignContent?.songGeneration?.songsAlmostReady
                  }
                  songsReadyText={campaignContent?.songGeneration?.songsReady}
                  signUpToListen={
                    campaignContent?.songGeneration?.signUpToListen
                  }
                  onCreateRedirect={handleCreateRedirect}
                />
              ))}

            <FooterSection />
          </div>
        </div>
        <NonAuthAntiAbuse containerId={containerId} />

        {enablePreviewGenerations && (
          <div className='absolute inset-x-0 bottom-0 overflow-hidden'>
            <SimplePlayer hidden={true} inline={true} />
          </div>
        )}
      </div>
    </MarketingStoreProvider>
  );
});

export default HomePage;
