'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Navbar } from '@/components/layout/Navbar';
import { Footer } from '@/components/layout/Footer';
import type { SessionUser } from '@/components/layout/UserMenu';
import { HeroSection } from './HeroSection';
import { ThreePathsSection, type PathId } from './ThreePathsSection';
import { HowItWorksSection } from './HowItWorksSection';
import { SampleResultsSection } from './SampleResultsSection';
import { CtaBanner } from './CtaBanner';
import { ServiceFlow } from '@/components/scan/ServiceFlow';
import { SERVICES, type Service } from '@/lib/reports/services';
import { PAYMENTS_ENABLED } from '@/lib/features';

import { VideoModal } from '@/components/modals/VideoModal';
import { PricingModal } from '@/components/modals/PricingModal';
import { BlueprintModal } from '@/components/assessments/BlueprintModal';

import { synthesizePersonalBlueprint } from '@/lib/blueprint/synthesizer';
import { getSamples } from '@/lib/reports/samples';
import { useLocale } from '@/i18n/client';
import { startCheckout } from '@/app/actions/affiliate';

type Overlay = 'start' | 'scan' | 'video' | 'pricing' | 'blueprint' | null;

/** Deep links other pages use to open a flow here, e.g. /#foto-aura after signing up. */
const HASH_TO_OVERLAY: Record<string, Overlay> = {
  '#mulai': 'start',
  '#foto-aura': 'scan',
};

const SCAN_AFTER_SIGNUP = `/daftar?next=${encodeURIComponent('/#foto-aura')}`;
const START_AFTER_SIGNUP = `/daftar?next=${encodeURIComponent('/#mulai')}`;

export function HomeClient({ user }: { user: SessionUser | null }) {
  const router = useRouter();
  const locale = useLocale();
  const [overlay, setOverlay] = useState<Overlay>(null);
  // Services ticked when the picker opens, e.g. only BaZi when coming from the BaZi card.
  const [preset, setPreset] = useState<Service[]>([...SERVICES]);
  const close = () => setOverlay(null);

  // The photo scan is saved to an account, so guests sign up first and come straight back to the camera.
  const open = (next: Overlay) => {
    if (next === 'scan' && !user) router.push(SCAN_AFTER_SIGNUP);
    else setOverlay(next);
  };

  useEffect(() => {
    const target = HASH_TO_OVERLAY[window.location.hash];
    if (!target) return;
    history.replaceState(null, '', window.location.pathname);
    if (target === 'scan' && !user) {
      router.push(SCAN_AFTER_SIGNUP);
      return;
    }
    // Opening a modal from a deep link is a one-off sync with the URL on mount.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setOverlay(target);
  }, [router, user]);

  const startWith = (services: Service[]) => {
    setPreset(services);
    setOverlay('start');
  };
  const selectPath = (path: PathId) => startWith([path]);
  const samples = getSamples();

  return (
    <main className="relative min-h-screen">
      <Navbar
        user={user}
        onGetStarted={() => (user ? startWith([...SERVICES]) : router.push('/daftar'))}
        onPricing={PAYMENTS_ENABLED ? () => open('pricing') : undefined}
      />

      <HeroSection onDiscoverClick={() => startWith([...SERVICES])} onWatchVideoClick={() => open('video')} />
      <ThreePathsSection onSelectPath={selectPath} />
      <HowItWorksSection />
      <SampleResultsSection onExploreSample={selectPath} />
      <CtaBanner
        onGetStarted={() => startWith([...SERVICES])}
        onViewPricing={PAYMENTS_ENABLED ? () => open('pricing') : undefined}
      />
      <Footer />

      <ServiceFlow
        open={overlay === 'start' || overlay === 'scan'}
        onClose={close}
        preset={overlay === 'scan' ? ['aura'] : preset}
        skipPicker={overlay === 'scan'}
        signedIn={Boolean(user)}
        userName={user?.name}
        signUpHref={START_AFTER_SIGNUP}
      />

      <VideoModal isOpen={overlay === 'video'} onClose={close} onStart={() => startWith([...SERVICES])} />
      {PAYMENTS_ENABLED && (
      <PricingModal
        isOpen={overlay === 'pricing'}
        onClose={close}
        onSelectPlan={async (plan) => {
          if (plan !== 'premium') return open('start');
          if (!user) return router.push(`/daftar?next=${encodeURIComponent('/akun/afiliasi')}`);
          const res = await startCheckout();
          if (res.ok) window.location.assign(res.redirectUrl);
          else router.push('/akun/afiliasi');
        }}
      />
      )}
      <BlueprintModal
        isOpen={overlay === 'blueprint'}
        onClose={close}
        data={synthesizePersonalBlueprint(samples.aura, samples.bazi, samples.numerology, locale)}
      />
    </main>
  );
}
