import Game from '@/components/Game';
import NewsSection from '@/components/NewsSection';
import OnboardingTour from '@/components/OnboardingTour';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import { getOrCreateDailyPuzzle } from '@/lib/dailyPuzzle';
import { Link } from '@/lib/navigation';
import { PrismaClient } from '@prisma/client';
import { getTranslations } from 'next-intl/server';
import { getLocalizedValue } from '@/lib/i18n';

export const dynamic = 'force-dynamic';

const prisma = new PrismaClient();

export default async function Home({
    params
}: {
    params: { locale: string };
}) {
    const { locale } = await params;
    const t = await getTranslations('Home');
    const tNav = await getTranslations('Navigation');

    const dailyPuzzle = await getOrCreateDailyPuzzle(null); // Global puzzle
    const genres = await prisma.genre.findMany({
        where: { active: true },
    });
    const specials = await prisma.special.findMany();

    // Sort in memory
    genres.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale)));
    specials.sort((a, b) => getLocalizedValue(a.name, locale).localeCompare(getLocalizedValue(b.name, locale)));

    const now = new Date();

    const activeSpecials = specials.filter(s => {
        const isStarted = !s.launchDate || s.launchDate <= now;
        const isEnded = s.endDate && s.endDate < now;
        return isStarted && !isEnded;
    });

    const upcomingSpecials = specials.filter(s => {
        return s.launchDate && s.launchDate > now;
    });

    return (
        <>
            <div id="tour-genres" style={{ textAlign: 'center', padding: '1rem', background: '#f3f4f6' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem', maxWidth: '1200px', margin: '0 auto', padding: '0 1rem' }}>
                    <div style={{ flex: 1 }} />
                    <div style={{ display: 'flex', justifyContent: 'center', gap: '1rem', flexWrap: 'wrap', alignItems: 'center', flex: 2 }}>
                        <div className="tooltip">
                            <Link href="/" style={{ fontWeight: 'bold', textDecoration: 'underline' }}>{tNav('global')}</Link>
                            <span className="tooltip-text">{t('globalTooltip')}</span>
                        </div>

                        {/* Genres */}
                        {genres.map(g => {
                            const name = getLocalizedValue(g.name, locale);
                            const subtitle = getLocalizedValue(g.subtitle, locale);
                            return (
                                <div key={g.id} className="tooltip">
                                    <Link href={`/${name}`} style={{ color: '#4b5563', textDecoration: 'none' }}>
                                        {name}
                                    </Link>
                                    {subtitle && <span className="tooltip-text">{subtitle}</span>}
                                </div>
                            );
                        })}

                        {/* Separator if both exist */}
                        {genres.length > 0 && activeSpecials.length > 0 && (
                            <span style={{ color: '#d1d5db' }}>|</span>
                        )}

                        {/* Active Specials */}
                        {activeSpecials.map(s => {
                            const name = getLocalizedValue(s.name, locale);
                            const subtitle = getLocalizedValue(s.subtitle, locale);
                            return (
                                <div key={s.id} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                                    <div className="tooltip">
                                        <Link
                                            href={`/special/${name}`}
                                            style={{
                                                color: '#be185d', // Pink-700
                                                textDecoration: 'none',
                                                fontWeight: '500'
                                            }}
                                        >
                                            ★ {name}
                                        </Link>
                                        {subtitle && <span className="tooltip-text">{subtitle}</span>}
                                    </div>
                                    {s.curator && (
                                        <span style={{ fontSize: '0.75rem', color: '#666' }}>
                                            {t('curatedBy')} {s.curator}
                                        </span>
                                    )}
                                </div>
                            );
                        })}
                    </div>

                    {/* Upcoming Specials */}
                    {upcomingSpecials.length > 0 && (
                        <div style={{ marginTop: '0.5rem', fontSize: '0.875rem', color: '#666' }}>
                            {t('comingSoon')}: {upcomingSpecials.map(s => {
                                const name = getLocalizedValue(s.name, locale);
                                return (
                                    <span key={s.id} style={{ marginLeft: '0.5rem' }}>
                                        ★ {name} ({s.launchDate ? new Date(s.launchDate).toLocaleDateString(locale, {
                                            day: '2-digit',
                                            month: '2-digit',
                                            year: 'numeric',
                                            timeZone: process.env.TZ
                                        }) : ''})
                                        {s.curator && <span style={{ fontStyle: 'italic', marginLeft: '0.25rem' }}>{t('curatedBy')} {s.curator}</span>}
                                    </span>
                                );
                            })}
                        </div>
                    )}
                </div>
                <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
                    <LanguageSwitcher />
                </div>
            </div>

            <div id="tour-news">
                <NewsSection locale={locale} />
            </div>

            <Game dailyPuzzle={dailyPuzzle} genre={null} />
            <OnboardingTour />
        </>
    );
}
