"use client";

import { useEffect } from "react";

import { AppBottomNav, MobileShell } from "@/app/_components/core";
import { ROUTES } from "@/router/routes";
import { useAppNavigator } from "@/router/use-app-navigator";
import { useAuthState } from "@/stores/auth/auth-context";
import { pwaUtil } from "@/utils";

import {
  SplashBackground,
  SplashButton,
  SplashContent,
  SplashLatestMessage,
  SplashLogo,
} from "./components";
import { useSplashLatestMessage } from "./hooks/use-splash-latest-message";
import styles from "./components/splash-screen.module.css";

// 尽量早地缓存 beforeinstallprompt，避免用户停留 splash 时浏览器事件已触发并丢失。
if (typeof window !== "undefined") {
  pwaUtil.prepareInstallPrompt();
}

export function SplashScreen() {
  const navigator = useAppNavigator();
  const authState = useAuthState();
  const latestMessage = useSplashLatestMessage({
    hasInitialized: authState.hasInitialized,
    isAuthLoading: authState.isLoading,
    loginStatus: authState.loginStatus,
  });

  const handleStartChat = () => {
    navigator.openChat({ replace: true });
  };

  const handleOpenPrivateRoom = () => {
    navigator.push(ROUTES.privateRoom, { scroll: false });
  };

  useEffect(() => {
    pwaUtil.prepareInstallPrompt();
  }, []);

  return (
    <MobileShell background="var(--color-sidebar-background)">
      <div className={styles.wrapper}>
        <SplashBackground />
        {/* 渐变叠加层：accent → transparent (bottom-left → center-right) */}
        <div className={styles.gradientOverlay} aria-hidden="true" />
        <div className={styles.content}>
          <SplashLogo />
          <div className={styles.spacer} />
          <SplashLatestMessage
            message={latestMessage.message}
            isLoading={latestMessage.isLoading}
            onOpenChat={handleStartChat}
          />
          <SplashContent />
          <div className={styles.buttonArea}>
            <SplashButton onStartChat={handleStartChat} />
          </div>
          <p className={styles.bottom}>
            Elio Silvestri, Your exclusive AI boyfriend
            <br />
            24/7 online | Chat | Companion | Heal | Sweet moments
          </p>
        </div>
        <AppBottomNav
          activeItem={null}
          variant="dark"
          onChatClick={handleStartChat}
          onPrivateRoomClick={handleOpenPrivateRoom}
        />
      </div>
    </MobileShell>
  );
}
