import { useState, useEffect } from 'react';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Image } from '@/components/ui/primitives/Image';
import { EnrollModal } from './EnrollModal';
import { useAuthGateStore } from '@/lib/stores/auth-gate';

type Props = {
  isLoggedIn: boolean;
  isAlreadyAffiliate: boolean;
};

export function Hero({ isLoggedIn, isAlreadyAffiliate }: Props) {
  const t = useT('affiliate_landing');
  const [modalOpen, setModalOpen] = useState(false);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const shouldOpenFromCta =
      new URLSearchParams(window.location.search).get('cta') === 'enroll' &&
      isLoggedIn &&
      !isAlreadyAffiliate;
    if (shouldOpenFromCta) {
      // Sync mount-time URL state after hydration so SSR and first client render stay identical.

      void Promise.resolve().then(() => setModalOpen(true));
      const url = new URL(window.location.href);
      url.searchParams.delete('cta');
      window.history.replaceState({}, '', url.toString());
    }
  }, [isAlreadyAffiliate, isLoggedIn]);

  const handleCta = () => {
    if (isAlreadyAffiliate) {
      window.location.href = '/affiliate';
      return;
    }
    if (!isLoggedIn) {
      useAuthGateStore.getState().triggerAuth(() => {
        window.location.href = '/affiliate-program?cta=enroll';
      });
      return;
    }
    setModalOpen(true);
  };

  return (
    <section
      aria-labelledby="hero-heading"
      className="relative overflow-hidden bg-(--color-surface) pt-16 pb-8 text-center"
    >
      {/* Hero SVG illustration */}
      <div className="mx-auto mb-8 w-full max-w-lg" aria-hidden="true">
        <Image
          src="/affiliate-program/hero.svg"
          alt=""
          decorative
          width={640}
          height={480}
          loading="eager"
          className="mx-auto"
        />
      </div>

      <h1
        id="hero-heading"
        className="mb-4 text-4xl font-extrabold text-(--color-text) sm:text-5xl"
      >
        {t('hero_heading')}
      </h1>
      <p className="mx-auto mb-8 max-w-xl text-lg text-(--color-text-muted)">{t('hero_sub')}</p>

      <Button variant="primary" size="lg" onClick={handleCta}>
        {isAlreadyAffiliate ? t('hero_cta_dashboard') : t('hero_cta_enroll')}
      </Button>

      {modalOpen && (
        <EnrollModal
          open={modalOpen}
          onClose={() => setModalOpen(false)}
          onSuccess={() => {
            window.location.href = '/affiliate';
          }}
        />
      )}
    </section>
  );
}
