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';
import { generateBaseMetadata } from '@/lib/metadata';
import type { Metadata } from 'next';

export const dynamic = 'force-dynamic';

const prisma = new PrismaClient();

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }): Promise<Metadata> {
    const { locale } = await params;
    const t = await getTranslations('Home');
    
    // Get localized title and description
    const title = locale === 'de' 
        ? 'Hördle - Tägliches Musik-Erraten'
        : 'Hördle - Daily Music Guessing Game';
    
    const description = locale === 'de'
        ? 'Spiele Hördle und errate Songs aus kurzen Audio-Clips! Täglich neue Rätsel aus verschiedenen Genres. Inspiriert von Wordle, aber für Musikfans.'
        : 'Play Hördle and guess songs from short audio clips! Daily new puzzles from various genres. Inspired by Wordle, but for music lovers.';
    
    return await generateBaseMetadata(locale, '', title, description);
}

export default async function Home({
    params
}: {
    params: Promise<{ 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({
        where: { hidden: false },
    });

    // 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;
    });

    // Required daily keys: global + all active genres (by localized name, as used in gameState storage)
    const requiredDailyKeys = ['global', ...genres.map(g => getLocalizedValue(g.name, locale))];

    return (
        <>
            <div id="tour-genres" style={{ textAlign: 'center', padding: '1rem', background: '#f3f4f6', position: 'relative' }}>
                {/* Language Switcher - rechts oben */}
                <div style={{ position: 'absolute', top: '1rem', right: '1rem', zIndex: 10 }}>
                    <LanguageSwitcher />
                </div>
                
                {/* Zentrierte Navigation */}
                <div style={{ display: 'flex', justifyContent: 'center', gap: '1rem', flexWrap: 'wrap', alignItems: 'center', marginBottom: '0.5rem' }}>
                    <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', textAlign: 'center' }}>
                        {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 id="tour-news">
                <NewsSection locale={locale} />
            </div>

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