"use client";

import { LogOut, Settings } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Link from "next/link";

const API_URL = "";

function TopBar() {
  const router = useRouter();
  const [username, setUsername] = useState<string | null>(null);
  const [role, setRole] = useState<number | null>(null);

  useEffect(() => {
    const storedUser = localStorage.getItem("username");
    const token = localStorage.getItem("token");
    setUsername(storedUser);

    if (token) {
      fetch(`${API_URL}/api/me`, {
        headers: { Authorization: `Bearer ${token}` },
      })
        .then((r) => r.json())
        .then((data) => setRole(data.role))
        .catch(() => setRole(null));
    }
  }, []);

  return (
    <header className="fixed top-0 left-0 w-full bg-white/15 backdrop-blur-md border-b border-white/20 flex items-center justify-between px-6 py-3 z-50">
      {/* Left side (app name) */}
      <Link href="/landing">
        <h1 className="text-white text-2xl font-bold cursor-pointer hover:text-white/80">
          FeedMee
        </h1>
      </Link>

      {/* Right side (username + settings + logout) */}
      <div className="flex items-center space-x-3 max-w-[50%]">
        <span className="text-white truncate">{username}</span>

        {/* Settings icon if mod/admin */}
        {role !== null && role <= 50 && (
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.push(role <= 1 ? "/admin" : "/mod")}
            className="text-white hover:bg-white/75"
            title="Settings"
          >
            <Settings className="h-5 w-5" />
          </Button>
        )}

        <Button
          variant="ghost"
          size="icon"
          onClick={() => {
            localStorage.removeItem("token");
            localStorage.removeItem("username");
            router.push("/auth");
          }}
          className="text-white hover:bg-white/75"
        >
          <LogOut className="h-5 w-5" />
        </Button>
      </div>
    </header>
  );
}

export { TopBar };
