import React, { useState, useEffect } from 'react';
import { I18N, type LangCode } from './i18n';
import { Hero, Marquee, Nav, SideNav } from './components';
import { Games, Services, Clients, Process, Studio, ContactCTA, Footer } from './sections';
import { Chatbot } from './Chatbot';
import { NewsIndex, NewsPost, type NewsItem } from './News';
import { SubscriptionPage, type NewsCategory } from './Subscribe';

const ACCENT = '#FF751A';
const MOTION = true;
const START_LANG: LangCode = 'en';

interface AppProps {
    page: string;
    props: Record<string, unknown>;
    categories: NewsCategory[];
}

function App({ page, props, categories }: AppProps) {
    const onHome = page === 'home';
    const [lang, setLang] = useState<LangCode>(() => {
        // Links in our emails open in the language the visitor subscribed with.
        if (props.lang === 'en' || props.lang === 'zh') return props.lang;
        const saved = localStorage.getItem('fo_lang');
        return saved === 'en' || saved === 'zh' ? saved : START_LANG;
    });
    const [reducedMotion, setReducedMotion] = useState(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches);
    const motion = MOTION && !reducedMotion;
    const t = I18N[lang];

    useEffect(() => {
        const preference = window.matchMedia('(prefers-reduced-motion: reduce)');
        const onChange = () => setReducedMotion(preference.matches);
        preference.addEventListener('change', onChange);
        return () => preference.removeEventListener('change', onChange);
    }, []);

    const navItems = [
        { id: 'top', label: t.secnav.top },
        { id: 'games', label: t.secnav.games },
        { id: 'services', label: t.secnav.services },
        { id: 'clients', label: t.secnav.clients },
        { id: 'process', label: t.secnav.process },
        { id: 'studio', label: t.secnav.studio },
        { id: 'contact', label: t.secnav.contact },
    ];

    useEffect(() => {
        localStorage.setItem('fo_lang', lang);
        document.documentElement.lang = lang === 'zh' ? 'zh-HK' : 'en';
    }, [lang]);

    useEffect(() => {
        document.documentElement.style.setProperty('--accent', ACCENT);
    }, []);

    useEffect(() => {
        document.body.classList.toggle('reduce-motion', !motion);
    }, [motion]);

    useEffect(() => {
        if (!motion) {
            document.querySelectorAll('.reveal').forEach((el) => el.classList.add('in'));
            return;
        }
        const io = new IntersectionObserver(
            (entries) => {
                entries.forEach((e) => {
                    if (e.isIntersecting) {
                        e.target.classList.add('in');
                        io.unobserve(e.target);
                    }
                });
            },
            { threshold: 0.12, rootMargin: '0px 0px -8% 0px' }
        );
        const els = document.querySelectorAll('.reveal:not(.in)');
        els.forEach((el) => io.observe(el));
        return () => io.disconnect();
    }, [lang, motion]);

    useEffect(() => {
        if (page === 'news-post') {
            const post = props.post as NewsItem;
            document.title = `${post.title[lang]} — Flameowl Studio`;
        } else if (page === 'news') {
            document.title = `${t.nav.news} — Flameowl Studio`;
        }
    }, [page, props, lang, t]);

    if (!onHome) {
        return (
            <>
                <Nav t={t} lang={lang} setLang={setLang} onHome={false} />
                <main>
                    {page === 'subscription' ? (
                        <SubscriptionPage t={t} props={props as unknown as React.ComponentProps<typeof SubscriptionPage>['props']} />
                    ) : page === 'news-post' ? (
                        <NewsPost t={t} lang={lang} post={props.post as NewsItem} more={(props.more as NewsItem[]) ?? []} />
                    ) : (
                        <NewsIndex t={t} lang={lang} posts={(props.posts as NewsItem[]) ?? []} categories={categories} />
                    )}
                </main>
                <Footer t={t} lang={lang} categories={categories} />
                <Chatbot t={t} lang={lang} />
            </>
        );
    }

    return (
        <>
            <Nav t={t} lang={lang} setLang={setLang} />
            <SideNav items={navItems} darkIds={['games']} lang={lang} />
            <main>
                <Hero t={t} motion={motion} />
                <Marquee items={t.marquee} />
                <Games t={t} motion={motion} />
                <Services t={t} />
                <Clients t={t} />
                <Process t={t} />
                <Studio t={t} />
                <ContactCTA t={t} />
            </main>
            <Footer t={t} lang={lang} categories={categories} />
            <Chatbot t={t} lang={lang} />
        </>
    );
}

export default App;
