import { Link, Outlet, useNavigate } from "react-router-dom"
import { useAuthStore } from "@/store/authStore"
import { Button } from "@/components/ui/button"
import ThemeToggle from "@/components/ThemeToggle"

export default function AppLayout() {
  const token = useAuthStore((s) => s.token)
  const username = useAuthStore((s) => s.username)
  const clearAuth = useAuthStore((s) => s.clearAuth)
  const navigate = useNavigate()

  function handleLogout() {
    clearAuth()
    navigate("/books", { replace: true })
  }

  return (
    <div className="min-h-screen">
      <header className="sticky top-[var(--safe-top,0px)] z-40 border-b bg-background">
        <div className="mx-auto flex h-12 max-w-[1200px] items-center gap-6 px-4">
          <Link to="/books" className="font-heading text-base font-semibold shrink-0">
            图书管理系统
          </Link>
          <nav className="flex items-center gap-4 text-sm">
            <Link to="/books" className="text-muted-foreground hover:text-foreground transition-colors">
              书目
            </Link>
            {token && (
              <Link to="/my-borrows" className="text-muted-foreground hover:text-foreground transition-colors">
                我的借阅
              </Link>
            )}
          </nav>
          <div className="ml-auto flex items-center gap-3">
            <ThemeToggle />
            {token ? (
              <>
                <span className="text-sm text-muted-foreground">{username}</span>
                <Button variant="outline" size="sm" onClick={handleLogout}>
                  退出
                </Button>
              </>
            ) : (
              <Button variant="outline" size="sm" onClick={() => navigate("/login")}>
                登录
              </Button>
            )}
          </div>
        </div>
      </header>
      <Outlet />
    </div>
  )
}
