import { clsx } from 'clsx';
import { FC, useCallback } from 'react';

import AuraButton from '@/components/button/AuraButton';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { CreateIcon } from '@/icons';
import { ArrowDownIcon } from '@/icons/generated';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';

import { CampaignContent } from '../HomePageClient';
import { HomePageScreens } from '../HomePageClient';
import DecorativeGraphicsLayer from '../components/DecorativeGraphicsLayer';
import LogoCloud from '../components/LogoCloud';
import { PRESS_LOGOS } from '../components/PressLogos';
import QuickBoxCreate from '../components/QuickBoxCreate';
import { SongPreviewCardContainer } from '../components/SongPreviewCardContainer';
import TypingAnimation from '../components/TypingAnimation';
import { TYPING_PHRASES } from '../utils/utils';

interface HeroSectionProps {
  campaignContent: CampaignContent | null;
  isWebviewAgent: boolean;
  scrollOpacity: number;
  isSignedIn: boolean;
  setCurrentPage: (page: HomePageScreens) => void;
  advancedModeEnabled: boolean;
  statsigLoaded: boolean;
  onMusicianClick: () => void;
  onGenerate: (prompt?: string) => Promise<void>;
  enablePreviewGenerations: boolean;
  hasCachedGeneration: boolean;
  cachedClip: Clip | null;
  onCreateRedirect: () => void;
}

const HeroSection: FC<HeroSectionProps> = ({
  campaignContent,
  isWebviewAgent,
  //scrollOpacity,
  isSignedIn,
  setCurrentPage,
  advancedModeEnabled,
  statsigLoaded,
  onMusicianClick,
  onGenerate,
  enablePreviewGenerations,
  hasCachedGeneration,
  cachedClip,
  onCreateRedirect,
}) => {
  const showCachedPreview =
    enablePreviewGenerations && hasCachedGeneration && cachedClip;

  // NEW: Determine hero layout mode
  const heroMode = campaignContent?.heroLayout?.mode || 'standard';
  const showInputBox = heroMode === 'standard' && !showCachedPreview;
  const showCtaOnly = heroMode === 'cta-only' && !showCachedPreview;

  const handleCtaClick = useCallback(() => {
    const action = campaignContent?.heroLayout?.ctaAction || 'generate';
    const target = campaignContent?.heroLayout?.ctaTarget;

    if (action === 'scroll-to-pricing') {
      document
        .getElementById('pricing-section')
        ?.scrollIntoView({ behavior: 'smooth' });
    } else if (action === 'scroll-to-section' && target) {
      document.getElementById(target)?.scrollIntoView({ behavior: 'smooth' });
    } else if (isSignedIn) {
      window.location.href = '/create';
    } else {
      setCurrentPage(HomePageScreens.GENERATE);
      if (enablePreviewGenerations) {
        onGenerate();
      }
    }

    logWebUserEvent({
      actionName: 'HomePageHeroCtaClicked',
      context: { action, target },
    });
  }, [
    campaignContent?.heroLayout,
    isSignedIn,
    setCurrentPage,
    enablePreviewGenerations,
    onGenerate,
  ]);

  return (
    <>
      {/* NEW: Decorative graphics layer */}
      <DecorativeGraphicsLayer
        graphics={campaignContent?.decorativeElements?.hero}
        scope='hero'
      />

      <section className='z-10'>
        <div className='flex items-center justify-center text-center'></div>
        <div className='[@media(max-height:549px)]:mt-20'>
          {campaignContent && !isWebviewAgent ? (
            campaignContent.hero.title ? (
              // Static title when title is provided
              <div className='flex min-h-[150px] items-center justify-center'>
                <h1 className='mx-auto max-w-[700px] px-[20px] text-center font-sans text-5xl leading-tight font-medium tracking-[-0.96px] text-white md:px-0 md:text-7xl md:leading-tight'>
                  {campaignContent.hero.title}
                </h1>
              </div>
            ) : campaignContent.hero.typingText ? (
              // Typing animation when typingText is provided
              <TypingAnimation phrases={campaignContent.hero.typingText} />
            ) : (
              // Fallback
              <TypingAnimation phrases={TYPING_PHRASES} />
            )
          ) : (
            <div className='flex h-[150px] items-center justify-center'>
              <h1 className='mx-auto h-[150px] max-w-[560px] px-[20px] text-center font-sans text-5xl leading-[44px] font-medium tracking-[-0.96px] text-white md:px-0 md:text-7xl md:leading-[64px]'>
                Make any song you can imagine
                <span className='ml-[10px] inline-block h-[70px] w-[2px] animate-pulse bg-foreground-primary align-middle' />
              </h1>
            </div>
          )}
        </div>
        <div>
          <h2 className='mx-auto max-w-[310px] pt-3 text-center text-[16px] leading-6 font-light text-white md:max-w-[410px] md:px-[20px]'>
            {showCachedPreview
              ? 'A preview of your first song is ready. Sign up for free to hear the full version and create more songs.'
              : campaignContent?.hero.subHeading ||
                'Start with a simple prompt or dive into our pro editing tools, your next track is just a step away.'}
          </h2>
        </div>
      </section>
      <section className='mx-auto mt-6 w-full max-w-[800px] px-[20px]'>
        {showCachedPreview ? (
          <div className='flex flex-col items-center gap-6'>
            <SongPreviewCardContainer
              clip={cachedClip}
              isLoading={false}
              onSignUp={onCreateRedirect}
              signUpToListen='Sign up for free to create more'
              requireSignUp={false}
            />
          </div>
        ) : showInputBox ? (
          <QuickBoxCreate
            onSubmit={(prompt) => {
              if (isSignedIn) {
                window.location.href = '/create';
              } else {
                // Switch to the generate page first to show loading state
                setCurrentPage(HomePageScreens.GENERATE);

                // Then start generation (don't await - let it run in background)
                if (enablePreviewGenerations) {
                  onGenerate(prompt); // runs in background
                }
              }
            }}
            placeholderOverride={
              enablePreviewGenerations
                ? 'Type any idea you have into a song'
                : campaignContent?.heroInput?.placeholder ||
                  'Chat to make music'
            }
            buttonText={campaignContent?.heroInput?.createButton || 'Create'}
            openSignUp={false}
            onAdvancedClick={
              advancedModeEnabled && statsigLoaded && !enablePreviewGenerations
                ? onMusicianClick
                : undefined
            }
          />
        ) : showCtaOnly ? (
          // NEW: CTA-only mode for campaigns
          <div className='flex justify-center'>
            <AuraButton
              onClick={handleCtaClick}
              text={campaignContent?.heroInput?.createButton || 'Explore Plans'}
              textExtraClasses='text-base md:text-lg'
              icon={<CreateIcon className='h-5 w-5' />}
              borderRadius='rounded-full'
              extraClasses='px-8 py-4 text-lg font-medium'
            />
          </div>
        ) : null}
      </section>

      {enablePreviewGenerations && (
        <section className='mx-auto mt-8 flex w-full max-w-[800px] justify-center px-[20px] md:mt-12'>
          <Button
            onClick={() => {
              logWebUserEvent({
                actionName: 'HomePageExploreAdvancedFeaturesClicked',
              });

              if (typeof document === 'undefined') return;

              const featuresSection = document.getElementById('features');
              if (featuresSection) {
                featuresSection.scrollIntoView({
                  behavior: 'smooth',
                  block: 'start',
                });
              }
            }}
            variant={ButtonVariant.Glass}
            size={ButtonSize.Medium}
            shape={ButtonShape.Pill}
            aria-label='Explore Advanced Features'
            className='border border-primary/10 px-[12px]'
          >
            Explore Advanced Features <ArrowDownIcon className='h-4 w-4' />
          </Button>
        </section>
      )}

      <div
        className={clsx(
          'relative mt-8 w-full',
          '[@media(min-height:550px)]:absolute',
          '[@media(min-height:550px)]:bottom-10',
          '[@media(min-height:550px)]:left-0',
          '[@media(min-height:550px)]:-z-10',
          '[@media(min-height:550px)]:mt-0'
        )}
      >
        <LogoCloud logos={PRESS_LOGOS} />
      </div>
    </>
  );
};

export default HeroSection;
