import { useSyncExternalStore } from "react"
import { NavLink } from "react-router-dom"
import Wrap from "@/components/wrap"
import { cn } from "@/lib/utils"

export default function Header() {
  const scroll = useSyncExternalStore(
    callback => {
      window.addEventListener("scroll", callback)
      return () => {
        window.removeEventListener("scroll", callback)
      }
    },
    () => window.scrollY > 48,
    () => false,
  )

  return (
    <header className={cn("fixed top-0 left-0 w-screen z-10 flex flex-col ")}>
      <div
        className={cn(
          `flex-none pointer-events-auto`,
          `transition-[background,shadow] duration-200 ease-in-out`,
          scroll
            ? `bg-[#fffe] backdrop-blur-sm shadow-lg`
            : `bg-transparent shadow-none`,
        )}
      >
        <Wrap className="h-20 max-md:h-16 flex justify-between pl-15 pr-15">
          <nav className="flex items-center justify-between gap-4 lg:gap-8">
            <ul className="h-full items-stretch hidden lg:flex">
              <NavItem to="/">首页</NavItem>
              <NavItem to="/product">产品购买</NavItem>
              <NavItem to="/ipline">IP线路表</NavItem>
              <NavItem to="/softDownload">软件下载</NavItem>
              <NavItem to="/help">帮助/教程</NavItem>
              {/* <NavItem to="/client">下载客户端</NavItem> */}
            </ul>
          </nav>
          <ProfileOrLogin />
        </Wrap>
      </div>
    </header>
  )
}

const NavItem = ({
  to,
  children,
}: {
  to: string
  children: React.ReactNode
}) => (
  <NavLink
    to={to}
    className={({ isActive }) =>
      `h-full flex items-center relative px-3 ${
        isActive
          ? "text-blue-500 after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-blue-500"
          : "text-slate-700"
      }`
    }
  >
    {children}
  </NavLink>
)

function ProfileOrLogin() {
  return (
    <div className="flex items-center">
      <NavLink
        to="/login"
        state={{ tab: "login" }}
        className="w-24 h-12 flex items-center justify-center lg:text-lg"
      >
        <span>登录</span>
      </NavLink>
      <NavLink
        to="/login"
        state={{ tab: "register" }}
        className={[
          `w-20 lg:w-24 h-10 lg:h-12 bg-linear-to-r rounded-full flex items-center justify-center lg:text-lg text-white`,
          `transition-colors duration-200 ease-in-out`,
          `from-blue-500 to-cyan-400 hover:from-blue-500 hover:to-cyan-300`,
        ].join(" ")}
      >
        <span>注册</span>
      </NavLink>
    </div>
  )
}
