import React from "react";
import { Link, useNavigate } from "react-router-dom";
import { frontendConfig } from "../change";

export default function Navbar({ onLogout }) {
  const navigate = useNavigate();
  const activeUser = localStorage.getItem("username") || "Administrator";

  const handleLogout = () => {
    // 1. Wipe out all authentication values from localStorage
    localStorage.removeItem("username");
    localStorage.removeItem("isAuthenticated");
    localStorage.removeItem("user"); // Wipes the user token completely

    // 2. Alert the parent state wrapper (App.jsx) that authentication is dead
    if (onLogout) {
      onLogout(); 
    }

    // 3. Immediately kick the user to the login route
    navigate("/login", { replace: true });
  };

  return (
    <nav className="bg-slate-900 text-white shadow-md border-b border-slate-800">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          
          {/* Logo Brand */}
          <div className="flex items-center gap-3">
            <div className="bg-indigo-600 p-2 rounded-xl text-white font-black text-sm">SF</div>
            <span className="font-black text-slate-100">{frontendConfig.appName}</span>
          </div>

          {/* Links Grid — Now correctly maps ALL array items including Dashboard */}
          <div className="hidden md:flex items-center gap-2">
            {frontendConfig.menuItems?.map((item) => (
              <Link 
                key={item} 
                // Converts link targets to lowercase (e.g., /dashboard, /suppliers) 
                // ensuring compatibility with standard route paths
                to={`/${item.toLowerCase()}`} 
                className="text-xs font-bold px-3.5 py-2 rounded-xl text-slate-300 hover:text-white hover:bg-slate-800 transition-all"
              >
                {item}
              </Link>
            ))}
          </div>

          {/* Active Profile Status & Clear Button */}
          <div className="flex items-center gap-4">
            <span className="text-xs font-mono font-bold text-slate-300 bg-slate-800/60 rounded-xl px-3.5 py-1.5 border border-slate-700/50">
              👤 {activeUser}
            </span>
            
            {/* CLICK EVENT HANDLER */}
            <button 
              onClick={handleLogout} 
              className="text-xs font-bold bg-rose-600/10 hover:bg-rose-600 text-rose-400 hover:text-white px-3.5 py-2 rounded-xl transition-all border border-rose-500/20"
            >
              Sign Out
            </button>
          </div>

        </div>
      </div>
    </nav>
  );
}