import Link from 'next/link';
import { cookies } from 'next/headers';
import { fetchAuthStatus, fetchCategories } from '@/lib/api';
import { mindSpaceOrigin, plazaPath } from '@/lib/site';

export async function Header() {
  const cookieStore = await cookies();
  const cookieHeader = cookieStore.toString();

  let categories: Awaited<ReturnType<typeof fetchCategories>>['categories'] = [];
  let authStatus: Awaited<ReturnType<typeof fetchAuthStatus>> = { authenticated: false };
  try {
    [{ categories }, authStatus] = await Promise.all([
      fetchCategories(),
      fetchAuthStatus(cookieHeader),
    ]);
  } catch {
    categories = [];
  }

  return (
    <header className="sticky top-0 z-40 border-b border-[#d6d0c3] bg-[#fffdf7]/95 backdrop-blur">
      <div className="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-3">
        <Link href={plazaPath()} className="flex items-center gap-2 font-bold text-[#17221d]">
          <span className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-[#2f6f57] text-sm text-white">
            P
          </span>
          <span>MindSpace Plaza</span>
        </Link>
        <nav className="hidden items-center gap-1 md:flex">
          {categories.slice(0, 6).map((cat) => (
            <Link
              key={cat.id}
              href={plazaPath(`cat/${cat.slug}`)}
              className="rounded-full px-3 py-1.5 text-sm text-[#4a5751] transition hover:bg-[#ebe4d6] hover:text-[#17221d]"
            >
              {cat.icon} {cat.name}
            </Link>
          ))}
        </nav>
        {authStatus.authenticated && authStatus.user ? (
          <Link
            href={authStatus.user.slug ? `/u/${authStatus.user.slug}` : mindSpaceOrigin()}
            className="flex items-center gap-2 rounded-full border border-[#d6d0c3] px-4 py-2 text-sm font-semibold text-[#17221d] transition hover:bg-[#ebe4d6]"
          >
            <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-[#2f6f57] text-xs text-white">
              {(authStatus.user.displayName || authStatus.user.username).charAt(0).toUpperCase()}
            </span>
            {authStatus.user.displayName || authStatus.user.username}
          </Link>
        ) : (
          <Link
            href={mindSpaceOrigin()}
            className="rounded-full bg-[#2f6f57] px-4 py-2 text-sm font-semibold text-white transition hover:bg-[#245742]"
          >
            登录 / 创作
          </Link>
        )}
      </div>
    </header>
  );
}
