import { CardVariant } from '@/Components/game/GameCard';
import GameCard from '@/Components/game/GameCard';
import GameGrid from '@/Components/game/GameGrid';
import Seo from '@/Components/shared/Seo';
import { Badge } from '@/Components/ui/badge';
import PublicLayout from '@/Layouts/PublicLayout';
import { stagger } from '@/lib/motion';
import { PageProps } from '@/types';
import { GameCard as Game, Recommended } from '@/types/models';
import { Link, usePage } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { Sparkles } from 'lucide-react';
import { ReactNode } from 'react';

type Personal = { playing: { data?: Game[] } | Game[]; wishlist_soon: Game[]; recommended: Recommended[]; has_signal: boolean };
type Props = { featured: { data: Game[] }; trending: { data: Game[] }; upcoming: { data: Game[] }; latest: { data: Game[] }; personal: Personal | null };

const fmtDay = (d: string | null) => (d ? new Date(`${d}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }) : 'TBA');

function Section({ id, title, subtitle, href, children }: { id?: string; title: ReactNode; subtitle?: string; href?: string; children: ReactNode }) {
    return (
        <section id={id} className="scroll-mt-24 space-y-4">
            <div className="flex items-end justify-between gap-4">
                <div><h2 className="text-h2">{title}</h2>{subtitle && <p className="mt-0.5 text-sm text-muted-foreground">{subtitle}</p>}</div>
                {href && <Link href={href} className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">See all</Link>}
            </div>
            {children}
        </section>
    );
}

const asList = (v: Personal['playing']): Game[] => (Array.isArray(v) ? v : v.data ?? []);

export default function Home({ featured, trending, upcoming, latest, personal }: Props) {
    const { auth } = usePage<PageProps>().props;
    const playing = personal ? asList(personal.playing) : [];

    return (
        <PublicLayout>
            <Seo title="Discover games" />
            <div className="space-y-14">
                <section className="py-8 sm:py-14">
                    <h1 className="text-display max-w-3xl">{auth.user ? `Welcome back, ${auth.user.name.split(' ')[0]}.` : 'A quieter way to find your next game.'}</h1>
                    <p className="mt-4 max-w-xl text-muted-foreground">{auth.user ? "Here's what's new, and what we think you'll like." : 'Browse, filter and track the games you love, without the noise.'}</p>
                    <div className="mt-6 flex flex-wrap gap-3">
                        <Link href={route('catalog')} className="inline-flex rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90">Browse catalog</Link>
                        <Link href={route('compare')} className="inline-flex rounded-lg border border-border bg-card/60 px-4 py-2 text-sm font-medium transition hover:bg-accent">Compare games</Link>
                    </div>
                </section>

                {personal && playing.length > 0 && (
                    <Section title="Continue playing" subtitle="Games you're in the middle of" href={route('library', { status: 'playing' })}><GameGrid games={playing} /></Section>
                )}

                {personal && personal.recommended.length > 0 && (
                    <Section title={<span className="inline-flex items-center gap-2"><Sparkles className="size-5 text-primary" />Recommended for you</span>} subtitle="Based on your ratings and library">
                        <motion.div variants={stagger} initial="hidden" animate="show" className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                            {personal.recommended.slice(0, 10).map((g) => (
                                <div key={g.id} className="space-y-1.5">
                                    <GameCard game={g} />
                                    <div className="flex flex-wrap gap-1">{g.reasons.map((r) => <Badge key={r} variant="accent">Because you like {r}</Badge>)}</div>
                                </div>
                            ))}
                        </motion.div>
                    </Section>
                )}

                {personal && personal.wishlist_soon.length > 0 && (
                    <Section title="From your wishlist" subtitle="Releasing around now" href={route('library', { status: 'wishlist' })}>
                        <GameGrid games={personal.wishlist_soon} caption={(g) => fmtDay(g.release_date)} />
                    </Section>
                )}

                {personal && !personal.has_signal && (
                    <div className="rounded-2xl border border-dashed border-border p-6 text-sm text-muted-foreground">
                        Rate a few games or add some to your library and this page will start recommending games for you.
                    </div>
                )}

                {featured.data.length > 0 && <Section title="Featured"><GameGrid games={featured.data} variant={'featured' as CardVariant} /></Section>}

                <Section title="Trending this week" subtitle="Most rated and wishlisted in the last 7 days" href={route('catalog', { sort: 'popular' })}><GameGrid games={trending.data} /></Section>

                {upcoming.data.length > 0 && (
                    <Section id="upcoming" title="Upcoming releases" subtitle="Coming soon" href={route('catalog', { sort: 'newest' })}>
                        <GameGrid games={upcoming.data} caption={(g) => fmtDay(g.release_date)} />
                    </Section>
                )}

                <Section title="Recently released" href={route('catalog', { sort: 'newest' })}><GameGrid games={latest.data} /></Section>
            </div>
        </PublicLayout>
    );
}
