import React, { useState, useEffect, useRef } from 'react';
import type { Locale, LangCode } from './i18n';
import { OwlMascot } from './OwlMascot';

const LOGO_SRC = '/assets/logo-horizontal.png';

interface NavProps {
    t: Locale;
    lang: LangCode;
    setLang: (l: LangCode) => void;
    onHome?: boolean;
}

export function Nav({ t, lang, setLang, onHome = true }: NavProps) {
    const base = onHome ? '' : '/';
    const [scrolled, setScrolled] = useState(false);
    useEffect(() => {
        const onScroll = () => setScrolled(window.scrollY > 24);
        window.addEventListener('scroll', onScroll);
        return () => window.removeEventListener('scroll', onScroll);
    }, []);
    return (
        <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
            <div className="wrap nav-inner">
                <a className="brand" href={onHome ? '#top' : '/'} aria-label="Flameowl home">
                    <img src={LOGO_SRC} alt="Flameowl" className="brand-logo" draggable={false} />
                </a>
                <div className="nav-links">
                    <a href={base + '#games'}>{t.nav.games}</a>
                    <a href={base + '#services'}>{t.nav.services}</a>
                    <a href={base + '#studio'}>{t.nav.studio}</a>
                    <a href="/news" className={onHome ? '' : 'active'}>{t.nav.news}</a>
                    <a href={base + '#contact'}>{t.nav.contact}</a>
                </div>
                <div className="nav-right">
                    <div className="lang-toggle" role="group" aria-label="Language">
                        <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
                        <button className={lang === 'zh' ? 'active' : ''} onClick={() => setLang('zh')}>中</button>
                    </div>
                    <a
                        className="btn btn-primary"
                        href={base + '#contact'}
                        style={{ padding: '11px 20px', boxShadow: '0 5px 0 0 color-mix(in oklab, var(--accent), #000 32%)' }}
                    >
                        {t.nav.cta}
                    </a>
                </div>
            </div>
        </nav>
    );
}

export function EmberCanvas({ motion }: { motion: boolean }) {
    const ref = useRef<HTMLCanvasElement | null>(null);
    useEffect(() => {
        if (!motion) return;
        const cv = ref.current;
        if (!cv) return;
        const ctx = cv.getContext('2d');
        if (!ctx) return;
        let raf = 0;
        let w = 0;
        let h = 0;
        const dpr = Math.min(window.devicePixelRatio || 1, 2);
        const resize = () => {
            const parent = cv.parentElement;
            if (!parent) return;
            const r = parent.getBoundingClientRect();
            w = r.width;
            h = r.height;
            cv.width = w * dpr;
            cv.height = h * dpr;
            cv.style.width = w + 'px';
            cv.style.height = h + 'px';
            ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        };
        resize();
        window.addEventListener('resize', resize);
        const N = Math.min(60, Math.floor(w / 16));
        const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#F2622E';
        const parts = Array.from({ length: N }, () => ({
            x: Math.random() * w,
            y: h + Math.random() * h,
            r: Math.random() * 2.6 + 0.8,
            vy: Math.random() * 0.7 + 0.25,
            vx: (Math.random() - 0.5) * 0.3,
            a: Math.random() * 0.5 + 0.2,
            tw: Math.random() * Math.PI * 2,
        }));
        const loop = () => {
            ctx.clearRect(0, 0, w, h);
            for (const p of parts) {
                p.y -= p.vy;
                p.x += p.vx;
                p.tw += 0.04;
                if (p.y < -10) {
                    p.y = h + 10;
                    p.x = Math.random() * w;
                }
                const flick = 0.6 + Math.sin(p.tw) * 0.4;
                ctx.globalAlpha = p.a * flick;
                ctx.fillStyle = accent;
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
                ctx.fill();
            }
            ctx.globalAlpha = 1;
            raf = requestAnimationFrame(loop);
        };
        loop();
        return () => {
            cancelAnimationFrame(raf);
            window.removeEventListener('resize', resize);
        };
    }, [motion]);
    return <canvas ref={ref} className="hero-ember-canvas" />;
}

export function Hero({ t, motion }: { t: Locale; motion: boolean }) {
    return (
        <header className="hero" id="top">
            <EmberCanvas motion={motion} />
            <div className="hero-blob b1" />
            <div className="hero-blob b2" />
            <div className="wrap hero-inner centered">
                <span className="kicker reveal in">{t.hero.kicker}</span>
                <h1 className="reveal in d1">
                    {t.hero.titleA}{' '}
                    <span className="em">
                        {t.hero.titleEm}
                        <svg viewBox="0 0 300 24" preserveAspectRatio="none" aria-hidden="true">
                            <path d="M3 17 C 70 6, 150 6, 297 13" stroke="var(--accent)" strokeWidth="6" fill="none" strokeLinecap="round" opacity="0.55" />
                        </svg>
                    </span>
                </h1>
                <p className="hero-sub reveal in d2">{t.hero.sub}</p>
                <div className="hero-owl reveal in d2">
                    <div className="hero-owl-ring" />
                    <div className="hero-owl-disc" />
                    <OwlMascot motion={motion} labels={t.hero.mascot} />
                </div>
                <div className="hero-cta reveal in d3">
                    <a className="btn btn-primary" href="#games">
                        {t.hero.ctaPrimary} <span className="arrow">→</span>
                    </a>
                    <a className="btn btn-ghost" href="#contact">{t.hero.ctaGhost}</a>
                </div>
                <div className="hero-stats reveal in d4">
                    {t.hero.stats.map((s, i) => (
                        <div className="hero-stat" key={i}>
                            <div className="n">{s.n}</div>
                            <div className="l">{s.l}</div>
                        </div>
                    ))}
                </div>
            </div>
        </header>
    );
}

export function Marquee({ items }: { items: string[] }) {
    const row = [...items, ...items];
    return (
        <div className="marquee" aria-hidden="true">
            <div className="marquee-track">
                {row.map((it, i) => (
                    <span className="marquee-item" key={i}>
                        {it}
                        <span className="dot" />
                    </span>
                ))}
            </div>
        </div>
    );
}

interface SideNavItem {
    id: string;
    label: string;
}

export function SideNav({ items, darkIds = [], lang }: { items: SideNavItem[]; darkIds?: string[]; lang: LangCode }) {
    const [active, setActive] = useState(items[0].id);
    useEffect(() => {
        const obs = new IntersectionObserver(
            (entries) => {
                entries.forEach((e) => {
                    if (e.isIntersecting) setActive((e.target as HTMLElement).id);
                });
            },
            { rootMargin: '-45% 0px -50% 0px', threshold: 0 }
        );
        items.forEach((it) => {
            const el = document.getElementById(it.id);
            if (el) obs.observe(el);
        });
        return () => obs.disconnect();
    }, [items, lang]);
    const onDark = darkIds.includes(active);
    return (
        <nav className={'sidenav' + (onDark ? ' on-dark' : '')} aria-label="Section navigation">
            {items.map((it) => (
                <a
                    key={it.id}
                    href={'#' + it.id}
                    className={'sidenav-item' + (active === it.id ? ' active' : '')}
                    aria-current={active === it.id ? 'true' : undefined}
                >
                    <span className="sidenav-label">{it.label}</span>
                    <span className="sidenav-dot" />
                </a>
            ))}
        </nav>
    );
}
