'use client';

import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ThemeToggle } from '@/components/ui/theme-toggle';
import { Search, Menu, X, Bell, Languages, ChevronDown } from 'lucide-react';
import { apiFetch } from '@/lib/auth';
import { useAuth } from '@/lib/auth-context';
import { useLang, useT } from '@/i18n';

function NotificationBellComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    async function load() {
      try {
        const res = await apiFetch('/notifications/unread');
        if (res.ok) {
          const data = await res.json();
          setCount(data.count || 0);
        }
      } catch {}
    }
    load();
    const interval = setInterval(load, 30000);
    return () => clearInterval(interval);
  }, []);

  return (
    <span className="relative">
      <Button variant="ghost" size="icon" className="rounded-full" asChild>
        <Link href="/notifications">
          <Bell className="h-5 w-5" />
        </Link>
      </Button>
      {count > 0 && (
        <span className="absolute -top-1 -right-1 bg-red-500 text-white text-[10px] font-bold min-w-[18px] h-[18px] flex items-center justify-center rounded-full px-1">
          {count > 99 ? '99+' : count}
        </span>
      )}
    </span>
  );
}

export function Header() {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const { isLoggedIn, logout } = useAuth();
  const { lang, setLang } = useLang();
  const t = useT();

  const navItems = [
    { href: '/', label: t.nav.home },
    { href: '/tools', label: t.nav.tools },
    { href: '/courses', label: t.nav.courses },
    { href: '/sandbox', label: t.nav.sandbox },
    { href: '/practices', label: t.nav.practices },
    { href: '/prompts', label: t.nav.prompts },
    { href: '/resources', label: '云资源' },
    { href: '/marketplace', label: t.nav.marketplace },
    { href: '/affiliate', label: t.nav.affiliate },
    { href: '/donate', label: t.nav.donate },
    { href: '/contents', label: t.nav.articles },
  ];

  function isActive(href: string) {
    if (href === '/') return pathname === '/';
    return pathname.startsWith(href);
  }

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header
      className={`sticky top-0 z-50 transition-all duration-300 ${
        scrolled
          ? 'bg-background/80 backdrop-blur-xl border-b border-border shadow-sm'
          : 'bg-background/50 backdrop-blur-md'
      }`}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <Link href="/" className="flex items-center gap-2 group shrink-0">
            <span className="text-2xl font-bold bg-gradient-to-r from-brand-600 to-brand-400 bg-clip-text text-transparent whitespace-nowrap">{t.brand.name}</span>
            <span className="text-lg text-muted-foreground hidden sm:inline">{t.brand.suffix}</span>
          </Link>

          <nav className="hidden md:flex items-center gap-1 flex-wrap">
            {navItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={`px-2.5 py-1.5 text-sm font-medium rounded-lg transition-all ${
                  isActive(item.href)
                    ? 'bg-accent text-foreground font-semibold'
                    : 'text-muted-foreground hover:text-foreground hover:bg-accent'
                }`}
              >
                {item.label}
              </Link>
            ))}
          </nav>

          <div className="hidden md:flex items-center gap-2">
            <form action="/search" className="relative">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                name="q"
                type="text"
                placeholder={t.common.search}
                className="w-28 lg:w-36 pl-8 h-9 text-sm bg-muted/50 border-0 focus-visible:ring-1"
              />
            </form>
            <ThemeToggle />
            <button onClick={() => setLang(lang === 'zh' ? 'en' : 'zh')}
              className="p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent transition-colors text-xs font-medium">
              {lang === 'zh' ? 'EN' : '中'}
            </button>
          </div>

          <div className="hidden md:flex items-center gap-2">
            {isLoggedIn ? (
              <>
                <NotificationBellComponent />
                <Button variant="default" size="sm" asChild>
                  <Link href="/dashboard">{t.nav?.my || '控制台'}</Link>
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => { logout(); window.location.href = '/'; }}
                >
                  {t.common.logout}
                </Button>
              </>
            ) : (
              <>
                <Button variant="ghost" size="sm" asChild>
                  <Link href="/auth">{t.common.login}</Link>
                </Button>
                <Button variant="default" size="sm" asChild>
                  <Link href="/auth?tab=register">{t.common.register}</Link>
                </Button>
              </>
            )}
          </div>

          <div className="flex md:hidden items-center gap-2">
            <ThemeToggle />
            <button onClick={() => setLang(lang === 'zh' ? 'en' : 'zh')}
              className="p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-accent transition-colors text-xs font-medium">
              {lang === 'zh' ? 'EN' : '中'}
            </button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setMobileOpen(!mobileOpen)}
              className="rounded-full"
            >
              {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
            </Button>
          </div>
        </div>

        {mobileOpen && (
          <nav className="md:hidden pb-4 border-t border-border pt-4 animate-fade-in">
            {navItems.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                className={`block py-2.5 px-2 text-sm rounded-lg transition-colors ${
                  isActive(item.href)
                    ? 'bg-accent text-foreground font-semibold'
                    : 'text-muted-foreground hover:text-foreground hover:bg-accent'
                }`}
                onClick={() => setMobileOpen(false)}
              >
                {item.label}
              </Link>
            ))}
            <div className="flex flex-col gap-2 mt-4">
              {isLoggedIn ? (
                <>
                  <Button className="w-full" size="sm" asChild>
                    <Link href="/dashboard" onClick={() => setMobileOpen(false)}>{t.nav?.my || '控制台'}</Link>
                  </Button>
                  <Button variant="outline" size="sm" className="w-full" onClick={() => { logout(); window.location.href = '/'; }}>
                    {t.common.logout}
                  </Button>
                </>
              ) : (
                <>
                  <Button variant="outline" className="w-full" size="sm" asChild>
                    <Link href="/auth" onClick={() => setMobileOpen(false)}>{t.common.login}</Link>
                  </Button>
                  <Button className="w-full" size="sm" asChild>
                    <Link href="/auth?tab=register" onClick={() => setMobileOpen(false)}>{t.common.register}</Link>
                  </Button>
                </>
              )}
            </div>
          </nav>
        )}
      </div>
    </header>
  );
}
