"use client";

import { useEffect } from "react";

import { AppBottomNav, MobileShell } from "@/app/_components/core";
import { useAppNavigator } from "@/router/use-app-navigator";
import {
  useActiveCharacter,
  useActiveCharacterRoutes,
} from "@/providers/character-provider";
import { useAuthState } from "@/stores/auth/auth-context";
import { pwaUtil } from "@/utils/pwa";

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

export function SplashScreen() {
  const navigator = useAppNavigator();
  const character = useActiveCharacter();
  const characterRoutes = useActiveCharacterRoutes();
  const authState = useAuthState();
  const latestMessage = useSplashLatestMessage({
    characterId: character.id,
    hasInitialized: authState.hasInitialized,
    isAuthLoading: authState.isLoading,
    loginStatus: authState.loginStatus,
  });

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

  const handleOpenPrivateZoom = () => {
    navigator.push(characterRoutes.privateZoom, { scroll: false });
  };

  const handleOpenSplash = () => {
    navigator.push(characterRoutes.splash, { scroll: false });
  };

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

  return (
    <MobileShell background="var(--color-splash-background)">
      <div className={styles.wrapper}>
        <SplashBackground src={character.assets.cover} />
        {/* 渐变叠加层：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}
            characterName={character.shortName}
            avatarUrl={character.assets.avatar}
            isLoading={latestMessage.isLoading}
            onOpenChat={handleStartChat}
          />
          <SplashContent characterName={character.shortName} />
          <div className={styles.buttonArea}>
            <SplashButton onStartChat={handleStartChat} />
          </div>
          <p className={styles.bottom}>
            {character.displayName}, {character.tagline}
            <br />
            24/7 online | Chat | Companion | Heal | Sweet moments
          </p>
        </div>
        <AppBottomNav
          activeItem="chat"
          privateZoomLabel={character.copy.privateZoomTitle}
          onChatClick={handleOpenSplash}
          onPrivateZoomClick={handleOpenPrivateZoom}
        />
      </div>
    </MobileShell>
  );
}
