"use client"

import { useEffect, useState } from "react"
import { ChevronRight, Menu } from "lucide-react"
import { useSidebarToggle } from "@/components/dashboard/sidebar-context"
import { dashboardHorizontalPadding } from "@/components/dashboard/shared/dashboard-layout"
import { cn } from "@/lib/utils"
import {
  getStoredCurrentUser,
  setStoredCurrentUser,
  type CachedCurrentUser,
} from "@/lib/current-user-cache"

interface NavbarProps {
  title: string
  breadcrumbs?: { label: string; href?: string }[]
  onMenuToggle?: () => void
}

type NavbarUser = CachedCurrentUser

export function Navbar({ title, breadcrumbs = [], onMenuToggle }: NavbarProps) {
  const { onMenuToggle: contextToggle } = useSidebarToggle()
  const handleMenuToggle = onMenuToggle ?? contextToggle

  const [currentUser, setCurrentUser] = useState<NavbarUser | null>(null)

  useEffect(() => {
    let active = true

    const cached = getStoredCurrentUser()
    if (cached) {
      setCurrentUser(cached)
      return
    }

    async function loadCurrentUser() {
      try {
        const res = await fetch("/api/admin/me", { cache: "no-store" })
        if (!res.ok) return

        const data = (await res.json()) as { user?: NavbarUser }
        if (active && data.user) {
          setCurrentUser(data.user)
          setStoredCurrentUser(data.user)
        }
      } catch {
        // Keep fallback UI if request fails.
      }
    }

    void loadCurrentUser()

    return () => {
      active = false
    }
  }, [])

  // Show only the user's first name in the navbar.
  const fullName = currentUser?.name?.trim() || null
  const firstName =
    fullName && fullName.length > 0
      ? fullName.split(/\s+/)[0]
      : currentUser?.email
      ? currentUser.email.split("@")[0]
      : "User"
  const displayName = firstName
  const displayEmail = currentUser?.email || "no-email"
  const userInitial = displayName.charAt(0).toUpperCase() || "U"

  return (
    <header
      className={cn(
        "h-16 flex items-center gap-4 shrink-0 bg-card border-b border-border",
        dashboardHorizontalPadding,
      )}
    >
      {/* Mobile menu */}
      <button
        onClick={handleMenuToggle}
        className="lg:hidden p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
        aria-label="Toggle menu"
      >
        <Menu className="w-5 h-5" aria-hidden="true" />
      </button>

      {/* Breadcrumbs */}
      <nav className="flex items-center gap-1.5 flex-1 min-w-0" aria-label="Breadcrumb">
        {breadcrumbs.map((crumb, i) => (
          <span key={i} className="flex items-center gap-1.5">
            {i > 0 && (
              <ChevronRight className="w-3.5 h-3.5 text-muted-foreground shrink-0" aria-hidden="true" />
            )}
            <span
              className={
                i === breadcrumbs.length - 1
                  ? "text-sm font-semibold text-foreground font-sans truncate"
                  : "text-sm text-muted-foreground font-sans hover:text-foreground transition-colors cursor-pointer"
              }
            >
              {crumb.label}
            </span>
          </span>
        ))}
      </nav>

      {/* Right side */}
      <div className="flex items-center gap-3 shrink-0">
      
       

        {/* User info */}
        <div className="flex items-center gap-2.5 min-w-0">
        
          <div className="hidden sm:block text-right min-w-0">
          <p className="text-xs font-semibold text-foreground font-sans truncate max-w-[160px]">
              Welcome back, {displayName}
            </p>
            
            
          </div>
         
        </div>
      </div>
    </header>
  )
}
