'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { AnimatePresence } from 'framer-motion';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { sanitizeInternalReturnTo } from '@/lib/security';
import MainPageBackground from './MainPageBackground';
import Navbar from './Navbar';
import Hero from './Hero';
import FeaturesSection from './FeaturesSection';
import SecretNotesSection from './SecretNotesSection';
import AnalyticsSection from './AnalyticsSection';
import PricingSection from './PricingSection';
import CtaSection from './CtaSection';
import Footer from './Footer';
import TelegramLoginModal from './TelegramLoginModal';

const DEFAULT_LOGIN_RETURN_TO = '/profile';
const PRICING_RETURN_TO = '/profile/pricing';

export default function LandingPageShell() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { status } = useSession();
  const isAuthenticated = status === 'authenticated';
  const [isLoginModalOpen, setIsLoginModalOpen] = useState(false);
  const [modalReturnTo, setModalReturnTo] = useState(DEFAULT_LOGIN_RETURN_TO);

  const defaultReturnTo = useMemo(
    () => sanitizeInternalReturnTo(searchParams.get('returnTo'), DEFAULT_LOGIN_RETURN_TO),
    [searchParams]
  );

  const handleOpenLogin = useCallback((targetReturnTo?: string) => {
    const resolvedReturnTo = sanitizeInternalReturnTo(targetReturnTo, defaultReturnTo);
    if (status === 'authenticated') {
      router.push(resolvedReturnTo, { scroll: false });
      return;
    }
    setModalReturnTo(resolvedReturnTo);
    setIsLoginModalOpen(true);
  }, [defaultReturnTo, router, status]);

  const handleSelectPlan = useCallback(() => {
    handleOpenLogin(PRICING_RETURN_TO);
  }, [handleOpenLogin]);

  const handleCloseLogin = useCallback(() => {
    setIsLoginModalOpen(false);
  }, []);

  useEffect(() => {
    if (status !== 'authenticated') {
      return;
    }

    router.prefetch(defaultReturnTo);
    router.prefetch('/profile/links');
    router.prefetch('/profile/analytics');
    router.prefetch(PRICING_RETURN_TO);

    const warmupProfileApi = () => {
      void fetch('/api/profile/dashboard', { cache: 'no-store', credentials: 'same-origin' }).catch(() => undefined);
      void fetch('/api/profile/overview?period=7', { cache: 'no-store', credentials: 'same-origin' }).catch(() => undefined);
    };

    const idleWindow = window as Window & {
      requestIdleCallback?: (callback: () => void, options?: { timeout?: number }) => number;
      cancelIdleCallback?: (id: number) => void;
    };

    if (idleWindow.requestIdleCallback) {
      const idleId = idleWindow.requestIdleCallback(warmupProfileApi, { timeout: 1200 });
      return () => {
        idleWindow.cancelIdleCallback?.(idleId);
      };
    }

    const timer = window.setTimeout(warmupProfileApi, 280);
    return () => window.clearTimeout(timer);
  }, [defaultReturnTo, router, status]);

  return (
    <div className="relative min-h-screen text-white selection:bg-violet-500/30">
      <MainPageBackground />
      <Navbar onOpenLogin={handleOpenLogin} isAuthenticated={isAuthenticated} />
      <main id="main" className="relative z-10 pb-24">
        <Hero />
        <FeaturesSection />
        <SecretNotesSection />
        <AnalyticsSection />
        <PricingSection onSelectPlan={handleSelectPlan} />
        <CtaSection onOpenLogin={handleOpenLogin} isAuthenticated={isAuthenticated} />
      </main>
      <Footer onOpenLogin={handleOpenLogin} isAuthenticated={isAuthenticated} />

      <AnimatePresence>
        {isLoginModalOpen && (
          <TelegramLoginModal
            onClose={handleCloseLogin}
            returnTo={modalReturnTo}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
