import { useEffect, useLayoutEffect, useRef, useState } from "react"
import { Link, useLocation, useNavigate } from "react-router-dom"
import { Avatar, Button, Dropdown } from "@heroui/react"
import {
  Bell,
  ChevronDown,
  FileText,
  Gift,
  HelpCircle,
  LayoutDashboard,
  LogOut,
  Menu,
  Package,
  Receipt,
  Search,
  Server,
  Settings,
  ShoppingCart,
  User,
  X,
} from "lucide-react"
import BrandLogo from "./BrandLogo"
import { useAuth } from "../contexts/AuthContext"
import { getUnreadCount } from "../api/notifications"

type Variant = "home" | "app" | "solid"

interface SiteHeaderProps {
  variant?: Variant
  /** Home 顶栏使用的滚动渐变进度（0-1）；仅 variant=home 时生效 */
  scrollProgress?: number
  /** Home 顶栏的锚点链接；仅 variant=home 时显示 */
  anchorLinks?: { href: string; label: string }[]
}

type NavChild = { path: string; label: string; icon: typeof LayoutDashboard }
type NavItem =
  | { path: string; label: string; icon: typeof LayoutDashboard; children?: undefined }
  | { label: string; icon: typeof LayoutDashboard; children: NavChild[]; path?: undefined }

const PRIMARY_NAV: NavItem[] = [
  { path: "/dashboard", label: "仪表盘", icon: LayoutDashboard },
  {
    label: "产品服务",
    icon: Package,
    children: [
      { path: "/control/server", label: "服务器管理", icon: Server },
      { path: "/store", label: "购买服务器", icon: Package },
      { path: "/orders", label: "订单管理", icon: FileText },
      { path: "/finance", label: "财务管理", icon: Receipt },
    ],
  },
  {
    label: "支持",
    icon: HelpCircle,
    children: [
      { path: "/tickets", label: "工单支持", icon: HelpCircle },
      { path: "/settings", label: "账户设置", icon: Settings },
    ],
  },
]

const HOME_ANNOUNCEMENT_STORAGE_KEY = "qycw:home-announcement-dismissed"

export default function SiteHeader({ variant = "app", scrollProgress = 1, anchorLinks }: SiteHeaderProps) {
  const { user, logout } = useAuth()
  const location = useLocation()
  const navigate = useNavigate()
  const [openMenu, setOpenMenu] = useState<string | null>(null)
  const [mobileOpen, setMobileOpen] = useState(false)
  const [announcementOpen, setAnnouncementOpen] = useState(() => {
    try {
      return window.localStorage.getItem(HOME_ANNOUNCEMENT_STORAGE_KEY) !== "1"
    } catch {
      return true
    }
  })
  const [unreadCount, setUnreadCount] = useState(0)
  const navRef = useRef<HTMLDivElement | null>(null)

  // 轮询未读站内信数（登录后每 60s）
  useEffect(() => {
    if (!user) {
      setUnreadCount(0)
      return
    }
    let active = true
    const fetchUnread = async () => {
      try {
        const data = await getUnreadCount()
        if (active) setUnreadCount(data.total)
      } catch {
        // 静默
      }
    }
    void fetchUnread()
    const timer = window.setInterval(fetchUnread, 60_000)
    return () => {
      active = false
      window.clearInterval(timer)
    }
  }, [user])

  // 点击外部关闭一级下拉
  useEffect(() => {
    if (!openMenu) return
    const onClick = (e: MouseEvent) => {
      if (navRef.current && !navRef.current.contains(e.target as Node)) {
        setOpenMenu(null)
      }
    }
    document.addEventListener("mousedown", onClick)
    return () => document.removeEventListener("mousedown", onClick)
  }, [openMenu])

  // 路由变化关闭所有菜单
  useEffect(() => {
    setOpenMenu(null)
    setMobileOpen(false)
  }, [location.pathname])

  // 移动端打开时锁滚动
  useEffect(() => {
    if (mobileOpen) {
      const prev = document.body.style.overflow
      document.body.style.overflow = "hidden"
      return () => { document.body.style.overflow = prev }
    }
  }, [mobileOpen])

  useLayoutEffect(() => {
    if (variant !== "home") return
    document.documentElement.style.setProperty("--home-header-height", announcementOpen ? "112px" : "72px")
    return () => {
      document.documentElement.style.removeProperty("--home-header-height")
    }
  }, [announcementOpen, variant])

  const dismissAnnouncement = () => {
    try {
      window.localStorage.setItem(HOME_ANNOUNCEMENT_STORAGE_KEY, "1")
    } catch {
      // Storage may be unavailable in privacy mode; closing still works for this visit.
    }
    setAnnouncementOpen(false)
  }

  const isActive = (path: string) => {
    if (path === "/dashboard") return location.pathname === "/dashboard"
    if (path === "/store") return location.pathname.startsWith("/store")
    return location.pathname.startsWith(path)
  }

  if (variant === "home") {
    return (
      <>
        <header className="fixed inset-x-0 top-0 z-50">
          {announcementOpen && (
            <div className="relative flex h-10 items-center justify-center bg-[#171d4f] px-12 text-sm font-semibold text-white">
              <span>全新云产品矩阵，蓄势待发</span>
              <button
                type="button"
                onClick={dismissAnnouncement}
                className="absolute right-5 flex h-7 w-7 items-center justify-center rounded-full border border-white/20 text-white/70 transition-colors hover:border-white/50 hover:text-white"
                aria-label="关闭公告"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          )}

          <div
            className="border-b border-slate-200/80 backdrop-blur-md"
            style={{
              backgroundColor: `rgba(255, 255, 255, ${0.94 + 0.06 * scrollProgress})`,
              boxShadow: `0 2px 8px rgba(15, 23, 42, ${0.04 + 0.04 * scrollProgress})`,
            }}
          >
            <div className="flex h-[72px] items-stretch pl-4 pr-0 sm:pl-6 lg:pl-8">
              <div className="flex min-w-0 flex-1 items-center gap-5 xl:gap-7">
                <Link to="/" className="flex shrink-0 items-center">
                  <BrandLogo className="h-10 w-auto max-w-[148px] object-contain" />
                </Link>

                {anchorLinks && anchorLinks.length > 0 && (
                  <nav className="hidden min-w-0 items-stretch gap-1 xl:flex">
                    {anchorLinks.map((link) => (
                      link.href.startsWith("#") ? (
                      <a
                        key={`${link.href}-${link.label}`}
                        href={link.href}
                        className="group relative flex h-[72px] items-center whitespace-nowrap px-2.5 text-[14px] font-medium text-slate-800 transition-colors hover:text-[#0568f5] 2xl:px-3.5"
                      >
                        {link.href === "/activities" && (
                          <span className="absolute left-1/2 top-1 -translate-x-1/2 rounded-t-md rounded-br-md bg-[#ff3030] px-1.5 py-0.5 text-[9px] font-bold leading-none text-white shadow-sm">
                            HOT
                          </span>
                        )}
                        {link.label}
                        <span className="absolute inset-x-2 bottom-0 h-0.5 origin-center scale-x-0 bg-[#0568f5] transition-transform group-hover:scale-x-100" />
                      </a>
                      ) : (
                      <Link
                        key={`${link.href}-${link.label}`}
                        to={link.href}
                        className="group relative flex h-[72px] items-center whitespace-nowrap px-2.5 text-[14px] font-medium text-slate-800 transition-colors hover:text-[#0568f5] 2xl:px-3.5"
                      >
                        {link.href === "/activities" && (
                          <span className="absolute left-1/2 top-1 -translate-x-1/2 rounded-t-md rounded-br-md bg-[#ff3030] px-1.5 py-0.5 text-[9px] font-bold leading-none text-white shadow-sm">
                            HOT
                          </span>
                        )}
                        {link.label}
                        <span className="absolute inset-x-2 bottom-0 h-0.5 origin-center scale-x-0 bg-[#0568f5] transition-transform group-hover:scale-x-100" />
                      </Link>
                      )
                    ))}
                  </nav>
                )}
              </div>

              <div className="flex shrink-0 items-stretch">
                <Link
                  to="/store"
                  className="my-4 hidden w-[176px] items-center justify-between bg-[#f7f8fa] px-4 text-sm text-slate-500 transition-colors hover:bg-slate-100 2xl:flex"
                >
                  <span>云服务器</span>
                  <Search className="h-5 w-5 text-slate-500" strokeWidth={1.8} />
                </Link>

                <div className="hidden items-center gap-4 px-5 text-sm text-slate-800 lg:flex">
                  <a href="#faq" className="whitespace-nowrap transition-colors hover:text-[#0568f5]">文档中心</a>
                  <span className="h-4 w-px bg-slate-300" />
                  <Link to={user ? "/dashboard" : "/login"} className="whitespace-nowrap transition-colors hover:text-[#0568f5]">
                    控制台
                  </Link>
                  <span className="h-4 w-px bg-slate-300" />
                  {user ? (
                    <Link to="/settings" className="max-w-[92px] truncate whitespace-nowrap transition-colors hover:text-[#0568f5]">
                      {user.username}
                    </Link>
                  ) : (
                    <Link to="/login" className="whitespace-nowrap transition-colors hover:text-[#0568f5]">登录</Link>
                  )}
                </div>

                <Link
                  to={user ? "/dashboard" : "/register"}
                  className="hidden min-w-[150px] items-center justify-center gap-2 bg-[#0868f5] px-6 text-sm font-semibold text-white transition-colors hover:bg-[#0059df] sm:flex"
                >
                  <Gift className="h-5 w-5" strokeWidth={1.8} />
                  {user ? "进入控制台" : "免费注册"}
                </Link>

                <button
                  type="button"
                  className="flex w-12 items-center justify-center text-slate-700 lg:hidden"
                  onClick={() => setMobileOpen((open) => !open)}
                  aria-label={mobileOpen ? "关闭菜单" : "打开菜单"}
                >
                  {mobileOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
                </button>
              </div>
            </div>
          </div>
        </header>

        <div
          className={`fixed inset-x-0 z-40 border-b border-slate-200 bg-white shadow-xl transition-all duration-200 lg:hidden ${
            announcementOpen ? "top-[112px]" : "top-[72px]"
          } ${mobileOpen ? "visible translate-y-0 opacity-100" : "invisible -translate-y-3 opacity-0"}`}
        >
          <nav className="grid grid-cols-2 gap-px bg-slate-100 p-px">
            {anchorLinks?.map((link) => (
              link.href.startsWith("#") ? (
                <a
                  key={`${link.href}-${link.label}-mobile`}
                  href={link.href}
                  onClick={() => setMobileOpen(false)}
                  className="bg-white px-5 py-4 text-sm font-medium text-slate-700 hover:text-[#0568f5]"
                >
                  {link.label}
                </a>
              ) : (
                <Link
                  key={`${link.href}-${link.label}-mobile`}
                  to={link.href}
                  onClick={() => setMobileOpen(false)}
                  className="bg-white px-5 py-4 text-sm font-medium text-slate-700 hover:text-[#0568f5]"
                >
                  {link.label}
                </Link>
              )
            ))}
            <Link to="/store" onClick={() => setMobileOpen(false)} className="bg-white px-5 py-4 text-sm font-medium text-slate-700">
              云服务器
            </Link>
            <Link to={user ? "/dashboard" : "/login"} onClick={() => setMobileOpen(false)} className="bg-white px-5 py-4 text-sm font-medium text-slate-700">
              {user ? "进入控制台" : "登录控制台"}
            </Link>
          </nav>
        </div>
      </>
    )
  }

  const showAppNav = !!user

  // 容器样式：home 透明滚动渐变；app 企业控制台顶栏；solid 白底分隔线
  const headerOuter = (() => {
    if (variant === "app") return "sticky top-0 z-30 border-b border-white/70 bg-white/72 shadow-sm shadow-gray-200/50 backdrop-blur-xl"
    return "sticky top-0 z-30 border-b border-gray-200 bg-white"
  })()

  const headerInner = (() => {
    if (variant === "app") {
      return "mx-auto w-full max-w-[1400px] px-4 sm:px-6 lg:px-8"
    }
    return "mx-auto w-full max-w-7xl px-4 sm:px-6"
  })()

  const barClass = (() => {
    if (variant === "app") {
      return "flex h-16 items-center justify-between bg-transparent"
    }
    if (variant === "solid") {
      return "flex h-16 items-center justify-between rounded-2xl border border-white/70 bg-white/78 px-4 sm:px-5 shadow-sm backdrop-blur-xl"
    }
    return "flex h-20 items-center justify-between"
  })()

  return (
    <>
      <header className={headerOuter}>
        <div className={`relative ${headerInner}`}>
          <div className={barClass}>
            {/* 左：Logo + 主导航 */}
            <div className="flex items-center gap-6 lg:gap-8 min-w-0">
              <Link to="/" className="flex shrink-0 items-center">
                <BrandLogo className="h-10 w-auto object-contain" />
              </Link>

              {/* 一级导航 — 仅已登录用户 */}
              {showAppNav && (
                <nav ref={navRef} className="hidden lg:flex items-center gap-1">
                  {PRIMARY_NAV.map((item) => {
                    const active = item.path
                      ? isActive(item.path)
                      : item.children?.some((c) => isActive(c.path))
                    const Icon = item.icon
                    const open = openMenu === item.label

                    if (item.path) {
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          className={`group relative flex h-16 items-center gap-2 border-b-2 px-3 text-sm font-medium transition-colors ${
                            active
                              ? "border-sky-400 text-sky-600"
                              : "border-transparent text-gray-600 hover:border-gray-200 hover:text-gray-900"
                          }`}
                        >
                          <Icon strokeWidth={active ? 2.5 : 2} className={`h-4 w-4 ${active ? "text-sky-500" : "text-gray-400 group-hover:text-gray-600"}`} />
                          {item.label}
                        </Link>
                      )
                    }

                    return (
                      <div key={item.label} className="relative">
                        <button
                          type="button"
                          onClick={() => setOpenMenu(open ? null : item.label)}
                          className={`group relative flex h-16 items-center gap-2 border-b-2 px-3 text-sm font-medium transition-colors ${
                            active || open
                              ? "border-sky-400 text-sky-600"
                              : "border-transparent text-gray-600 hover:border-gray-200 hover:text-gray-900"
                          }`}
                        >
                          <Icon strokeWidth={active || open ? 2.5 : 2} className={`h-4 w-4 ${active || open ? "text-sky-500" : "text-gray-400 group-hover:text-gray-600"}`} />
                          {item.label}
                          <ChevronDown className={`h-3.5 w-3.5 transition-transform duration-200 ${open ? "rotate-180 text-sky-500" : "text-gray-400 group-hover:text-gray-600"}`} />
                        </button>

                        {open && (
                          <div className="absolute left-0 top-full pt-2 z-50 w-52">
                            <div className="rounded-2xl border border-gray-100 bg-white p-2 shadow-lg shadow-gray-200/50">
                              {item.children!.map((child) => {
                                const childActive = isActive(child.path)
                                const ChildIcon = child.icon
                                return (
                                  <Link
                                    key={child.path}
                                    to={child.path}
                                    onClick={() => setOpenMenu(null)}
                                    className={`group flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors ${
                                      childActive
                                        ? "bg-sky-50 text-sky-600"
                                        : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
                                    }`}
                                  >
                                    <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${childActive ? "bg-white shadow-sm" : "bg-gray-50 group-hover:bg-white group-hover:shadow-sm"}`}>
                                      <ChildIcon strokeWidth={childActive ? 2 : 1.5} className={`h-4 w-4 ${childActive ? "text-sky-500" : "text-gray-500 group-hover:text-gray-700"}`} />
                                    </div>
                                    {child.label}
                                  </Link>
                                )
                              })}
                            </div>
                          </div>
                        )}
                      </div>
                    )
                  })}
                </nav>
              )}

            </div>

            {/* 右：操作区 */}
            <div className="flex items-center gap-2 sm:gap-3">
              {user ? (
                <>
                  {/* 余额标签 */}
                  <span className="hidden sm:inline-flex items-center rounded-md border border-gray-200 bg-gray-50 px-3 py-1.5 text-xs font-medium text-gray-700">
                    余额 ¥{((user.balance || 0) / 100).toFixed(2)}
                  </span>

                  <Link
                    to="/cart"
                    className="flex h-9 w-9 items-center justify-center rounded-md border border-transparent text-gray-500 hover:border-gray-200 hover:bg-gray-50 hover:text-gray-900 transition-colors"
                    title="购物车"
                  >
                    <ShoppingCart className="h-[18px] w-[18px]" />
                  </Link>

                  <Link
                    to="/notifications"
                    className="relative flex h-9 w-9 items-center justify-center rounded-md border border-transparent text-gray-500 hover:border-gray-200 hover:bg-gray-50 hover:text-gray-900 transition-colors"
                    title="消息通知"
                  >
                    <Bell className="h-[18px] w-[18px]" />
                    {unreadCount > 0 && (
                      <span className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-medium text-white">
                        {unreadCount > 99 ? "99+" : unreadCount}
                      </span>
                    )}
                  </Link>

                  <Dropdown.Root>
                    <Dropdown.Trigger className="flex items-center gap-2 rounded-md border border-transparent p-1 pl-2 transition-colors cursor-pointer hover:border-gray-200 hover:bg-gray-50">
                      <span className="hidden md:block max-w-[100px] truncate text-sm font-medium text-gray-700">
                        {user.username}
                      </span>
                      <Avatar.Root size="sm" className="h-8 w-8 ring-2 ring-white shadow-sm">
                        <Avatar.Fallback className="bg-gray-100 text-gray-700 text-sm font-semibold border border-gray-200">
                          {user.username?.charAt(0).toUpperCase() || "U"}
                        </Avatar.Fallback>
                      </Avatar.Root>
                    </Dropdown.Trigger>
                    <Dropdown.Popover className="w-56 rounded-2xl border border-gray-100 shadow-xl shadow-gray-200/50">
                      <Dropdown.Menu className="p-2">
                        <Dropdown.Item id="profile" className="gap-2.5 rounded-xl py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:text-gray-900" onAction={() => navigate("/settings")}>
                          <User className="h-4 w-4 text-gray-400" /> 个人资料
                        </Dropdown.Item>
                        <Dropdown.Item id="settings" className="gap-2.5 rounded-xl py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 hover:text-gray-900" onAction={() => navigate("/settings")}>
                          <Settings className="h-4 w-4 text-gray-400" /> 账户设置
                        </Dropdown.Item>
                        <Dropdown.Item id="logout" className="gap-2.5 rounded-xl py-2.5 text-sm font-medium text-red-600 hover:bg-red-50 mt-1" onAction={logout}>
                          <LogOut className="h-4 w-4 text-red-500" /> 退出登录
                        </Dropdown.Item>
                      </Dropdown.Menu>
                    </Dropdown.Popover>
                  </Dropdown.Root>

                  {/* 移动端汉堡 */}
                  <button
                    type="button"
                    className="lg:hidden flex h-9 w-9 items-center justify-center rounded-md border border-transparent text-gray-600 hover:border-gray-200 hover:bg-gray-50 transition-colors"
                    onClick={() => setMobileOpen(true)}
                    aria-label="打开菜单"
                  >
                    <Menu className="h-5 w-5" />
                  </button>
                </>
              ) : (
                <>
                  <Link
                    to="/login"
                    className="hidden sm:inline-flex items-center px-3 py-1.5 text-sm font-medium text-gray-600 hover:text-sky-500 transition-colors"
                  >
                    登录
                  </Link>
                  <Button
                    onPress={() => navigate("/register")}
                    className="!text-white [&_*]:!text-white bg-sky-500 hover:bg-sky-600 active:bg-sky-700 rounded-lg px-4 sm:px-5 font-semibold shadow-sm shadow-sky-200/70"
                  >
                    免费注册
                  </Button>
                </>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* 移动端抽屉 */}
      {showAppNav && (
        <div
          className={`fixed inset-0 z-50 lg:hidden transition-opacity duration-200 ${
            mobileOpen ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none"
          }`}
        >
          <div
            className="absolute inset-0 bg-gray-900/40 backdrop-blur-sm"
            onClick={() => setMobileOpen(false)}
          />
          <div
            className={`absolute right-0 top-0 h-full w-[280px] bg-white shadow-2xl transition-transform duration-300 ease-out ${
              mobileOpen ? "translate-x-0" : "translate-x-full"
            }`}
          >
            <div className="flex h-16 items-center justify-between border-b border-gray-100 px-5">
              <span className="text-sm font-semibold text-gray-800">菜单</span>
              <button
                type="button"
                className="flex h-9 w-9 items-center justify-center rounded-full text-gray-500 hover:bg-gray-100"
                onClick={() => setMobileOpen(false)}
                aria-label="关闭"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <nav className="flex flex-col gap-1 p-3 overflow-y-auto max-h-[calc(100vh-64px)]">
              {PRIMARY_NAV.map((item) => {
                const Icon = item.icon
                if (item.path) {
                  const active = isActive(item.path)
                  return (
                    <Link
                      key={item.path}
                      to={item.path}
                      className={`flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium ${
                        active ? "bg-sky-50 text-sky-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      <Icon className={`h-4 w-4 ${active ? "text-sky-500" : "text-gray-400"}`} />
                      {item.label}
                    </Link>
                  )
                }
                return (
                  <div key={item.label} className="mt-2">
                    <div className="px-3 pb-1.5 text-[11px] font-semibold uppercase tracking-wider text-gray-400">
                      {item.label}
                    </div>
                    {item.children!.map((c) => {
                      const active = isActive(c.path)
                      const ChildIcon = c.icon
                      return (
                        <Link
                          key={c.path}
                          to={c.path}
                          className={`flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium ${
                            active ? "bg-sky-50 text-sky-600" : "text-gray-700 hover:bg-gray-50"
                          }`}
                        >
                          <ChildIcon className={`h-4 w-4 ${active ? "text-sky-500" : "text-gray-400"}`} />
                          {c.label}
                        </Link>
                      )
                    })}
                  </div>
                )
              })}
            </nav>
          </div>
        </div>
      )}
    </>
  )
}
