"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronRight } from "lucide-react";
import { ThemeToggle } from "./theme-toggle";
import UserMenu from "@/components/auth/user-menu";
import { BRAND_NAME } from "@/components/brand/brand-logo";

const LABEL_MAP: Record<string, string> = {
  dashboard: "Dashboard",
  users: "Users",
  projects: "Projects",
  analytics: "Analytics",
  settings: "Settings",
  departments: "Departments",
  designations: "Designations",
  admin: "Admin",
  manager: "Manager",
  lead: "Unit Lead",
  member: "Member",
  management: "Management",
  create: "Create",
  wbs: "WBS",
  "logged-hours": "Logged Hours",
  profile: "Profile",
};

function titleCase(segment: string) {
  if (LABEL_MAP[segment]) return LABEL_MAP[segment];
  if (segment.length > 20) return "Details";
  return segment
    .split("-")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
}

export function PageToolbar() {
  const pathname = usePathname();
  const parts = pathname.split("/").filter(Boolean);
  const crumbs = parts.map((part, index) => {
    const href = "/" + parts.slice(0, index + 1).join("/");
    return { label: titleCase(part), href };
  });
  const title = crumbs[crumbs.length - 1]?.label || "Dashboard";

  return (
    <div className="flex items-center justify-between gap-4 px-6 py-3.5 border-b border-border bg-card/40 shrink-0">
      <div className="min-w-0">
        <nav className="flex items-center gap-1 text-xs text-muted-foreground mb-0.5 flex-wrap">
          <Link
            href="/dashboard"
            className="hover:text-foreground transition-colors font-medium tracking-wide uppercase text-[10px]"
          >
            {BRAND_NAME}
          </Link>
          {crumbs.slice(1).map((crumb) => (
            <span key={crumb.href} className="flex items-center gap-1 min-w-0">
              <ChevronRight className="h-3 w-3 shrink-0 opacity-40" />
              <Link
                href={crumb.href}
                className="truncate hover:text-foreground transition-colors"
              >
                {crumb.label}
              </Link>
            </span>
          ))}
        </nav>
        <h1 className="text-xl font-semibold tracking-tight text-foreground truncate font-secondary">
          {title}
        </h1>
      </div>
      <div className="flex items-center gap-1.5 shrink-0">
        <ThemeToggle />
        <UserMenu />
      </div>
    </div>
  );
}
