"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import ThemeToggle from "./theme-toggle";

type Me = {
    id: string;
    discordId: string;
    username: string;
    avatar?: string;
    role: "admin" | "writer" | "reader";
};

function getAvatarUrl(me: Me) {
    if (!me.avatar) {
        return `https://cdn.discordapp.com/embed/avatars/${Number(me.discordId) % 5}.png`;
    }

    if (me.avatar.startsWith("http://") || me.avatar.startsWith("https://")) {
        return me.avatar;
    }

    const ext = me.avatar.startsWith("a_") ? "gif" : "png";
    return `https://cdn.discordapp.com/avatars/${me.discordId}/${me.avatar}.${ext}?size=128`;
}

export default function Header() {
    const [me, setMe] = useState<Me | null>(null);
    const [menuOpen, setMenuOpen] = useState(false);
    const menuRef = useRef<HTMLDivElement | null>(null);
    const developerClickTimeoutRef = useRef<number | null>(null);

    function handleIconClick() {
        if (typeof window === "undefined") {
            return;
        }

        const clickCountKey = "developer_icon_click_count";
        const lastClickAtKey = "developer_icon_click_last_at";
        const developerKey = "developer";
        const now = Date.now();
        const lastClickAt = Number(window.localStorage.getItem(lastClickAtKey) ?? "0");
        const previousCount = Number(window.localStorage.getItem(clickCountKey) ?? "0");
        const nextCount = now - lastClickAt > 1500 ? 1 : previousCount + 1;

        window.localStorage.setItem(clickCountKey, String(nextCount));
        window.localStorage.setItem(lastClickAtKey, String(now));

        if (developerClickTimeoutRef.current !== null) {
            window.clearTimeout(developerClickTimeoutRef.current);
        }

        developerClickTimeoutRef.current = window.setTimeout(() => {
            window.localStorage.removeItem(clickCountKey);
            window.localStorage.removeItem(lastClickAtKey);
            developerClickTimeoutRef.current = null;
        }, 1500);

        if (nextCount >= 10) {
            window.localStorage.setItem(developerKey, "true");
            window.localStorage.removeItem(clickCountKey);
            window.localStorage.removeItem(lastClickAtKey);

            if (developerClickTimeoutRef.current !== null) {
                window.clearTimeout(developerClickTimeoutRef.current);
                developerClickTimeoutRef.current = null;
            }
        }
    }

    useEffect(() => {
        return () => {
            if (developerClickTimeoutRef.current !== null) {
                window.clearTimeout(developerClickTimeoutRef.current);
            }
        };
    }, []);

    useEffect(() => {
        let active = true;

        async function loadMe() {
            try {
                const response = await fetch("/api/auth/me", { cache: "no-store" });
                if (!response.ok) {
                    if (response.status === 401 || response.status === 404) {
                        if (active) setMe(null);
                        return;
                    }
                    throw new Error(`Failed to load profile: ${response.status}`);
                }

                const profile = await response.json() as Me;
                if (active) {
                    setMe(profile);
                }
            } catch {
                if (active) {
                    setMe(null);
                }
            }
        }

        void loadMe();
        return () => {
            active = false;
        };
    }, []);

    useEffect(() => {
        function handleOutsideClick(event: MouseEvent) {
            if (!menuRef.current) {
                return;
            }

            if (!menuRef.current.contains(event.target as Node)) {
                setMenuOpen(false);
            }
        }

        document.addEventListener("mousedown", handleOutsideClick);
        return () => {
            document.removeEventListener("mousedown", handleOutsideClick);
        };
    }, []);

    async function logout() {
        try {
            await fetch("/api/auth/logout", {
                method: "POST",
                cache: "no-store",
            });
        } finally {
            setMenuOpen(false);
            setMe(null);
            window.location.href = "/";
        }
    }

    return (
        <header className="relative z-60 flex h-16 items-center justify-between border-b border-border bg-background/90 backdrop-blur px-6">
            <div className="flex items-center gap-6">
                <Link href="/" className="text-2xl" id="icon" onClick={handleIconClick}>🎀</Link>
            </div>
            {me ? (
                <div className="relative flex items-center gap-4" id="menu" ref={menuRef}>
                    {me.role === "admin" || me.role === "writer" ? (
                        <Link href="/add" className="text-[16px] text-foreground/50">[ <span className="text-foreground">+</span> ]</Link>
                    ) : null}
                    <div>
                        <ThemeToggle />
                    </div>

                    <button
                        type="button"
                        className="block"
                        title={`${me.username} (${me.role})`}
                        onClick={() => setMenuOpen((current) => !current)}
                    >
                        <img
                            src={getAvatarUrl(me)}
                            alt={`${me.username} profile`}
                            className="h-8 w-8 rounded-full border border-border/70 object-cover"
                            loading="lazy"
                            decoding="async"
                            referrerPolicy="no-referrer"
                        />
                    </button>

                    {menuOpen ? (
                        <div className="absolute right-0 top-full z-70 mt-2 min-w-40 overflow-hidden rounded-lg border border-border bg-background/95 p-1 shadow-xl backdrop-blur">
                            <div className="px-3 py-2 text-xs text-foreground/60">
                                {me.username} ({me.role})
                            </div>
                            {me.role === "admin" ? (
                                <a
                                    href="/dashboard"
                                    className="block rounded px-3 py-2 text-sm text-foreground/80 hover:bg-accent"
                                    onClick={() => setMenuOpen(false)}
                                >
                                    Dashboard
                                </a>
                            ) : null}
                            <button
                                type="button"
                                className="block w-full rounded px-3 py-2 text-left text-sm text-red-600 hover:bg-destructive/10 transition-colors"
                                onClick={() => {
                                    void logout();
                                }}
                            >
                                Logout
                            </button>
                            <a href="/docs/privacy">개인정보 처리 방침</a>
                            <a href="/docs/tos">이용약관</a>
                        </div>
                    ) : null}
                </div>
            ) : (
                <div className="relative flex items-center gap-4" id="menu">
                    <ThemeToggle />
                    <a href="/api/auth/discord/login" className="text-[16px] text-foreground/50">[ <span className="text-foreground">Login</span> ]</a>
                </div>
            )}
        </header>
    );
}