import { motion } from "framer-motion";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import { Logo } from "./Logo";
import { ThemeToggle } from "./ThemeToggle";
import { Button } from "./ui/Button";

export function Navbar() {
  const { user, logout } = useAuth();
  const { pathname } = useLocation();
  const navigate = useNavigate();

  return (
    <motion.header
      initial={{ y: -64, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ type: "spring", stiffness: 320, damping: 28, delay: 0.05 }}
      className="sticky top-0 z-50"
    >
      <div className="mx-auto mt-3 flex max-w-5xl items-center justify-between gap-3 rounded-2xl border-[1.5px] border-line bg-[var(--surface)]/80 px-3.5 py-2.5 backdrop-blur-xl sm:px-4">
        <Logo />

        <nav className="flex items-center gap-1.5 sm:gap-2">
          <ThemeToggle />
          {user ? (
            <>
              {pathname !== "/dashboard" && (
                <Link to="/dashboard" className="hidden sm:block">
                  <Button variant="ghost" size="sm">
                    Dashboard
                  </Button>
                </Link>
              )}
              <div className="flex items-center gap-2 rounded-xl border-[1.5px] border-line bg-surface px-1 py-1 pr-2.5">
                <span className="grid h-7 w-7 place-items-center rounded-lg bg-accent text-xs font-bold text-accent-ink">
                  {user.name.slice(0, 1).toUpperCase()}
                </span>
                <button
                  onClick={() => logout()}
                  className="focusable rounded-md text-xs font-medium text-muted hover:text-ink"
                >
                  Sign out
                </button>
              </div>
            </>
          ) : (
            <Button size="sm" variant="dark" onClick={() => navigate("/login")}>
              Sign in
            </Button>
          )}
        </nav>
      </div>
    </motion.header>
  );
}
