"use client";

import { LogOut, Menu } from "lucide-react";
import { usePathname } from "next/navigation";
import { logout } from "@/actions/auth";
import type { OpenNote } from "@/lib/notes";
import { NewHireButton } from "./NewHireButton";
import { NotesBell } from "./NotesBell";

const TITLES: Record<string, string> = {
  "/": "Übersicht",
  "/employees": "Mitarbeiter:innen",
  "/orgchart": "Organigramm",
  "/positions": "Positionen",
  "/reports": "Berichte",
  "/audit": "Audit-Log",
};

function titleFor(pathname: string): string {
  if (TITLES[pathname]) return TITLES[pathname];
  const match = Object.keys(TITLES).find((key) => key !== "/" && pathname.startsWith(key));
  return match ? TITLES[match] : "Alpenwerk HR";
}

type TopbarProps = {
  userLabel: string;
  openNotes: OpenNote[];
  onOpenNav: () => void;
};

export function Topbar({ userLabel, openNotes, onOpenNav }: TopbarProps) {
  const pathname = usePathname();

  return (
    // Sticky, with the notch inset added to its top padding: on an iPhone in
    // landscape the bar would otherwise sit under the rounded corner.
    <header className="sticky top-0 z-20 flex h-14 shrink-0 items-center justify-between border-b border-border bg-white px-3 pt-[env(safe-area-inset-top)] sm:px-6">
      <div className="flex min-w-0 items-center gap-2">
        <button
          type="button"
          onClick={onOpenNav}
          aria-label="Navigation öffnen"
          className="-ml-1 rounded p-2 text-ink-body hover:bg-surface lg:hidden"
        >
          <Menu className="h-5 w-5" />
        </button>
        <h1 className="truncate text-base font-bold text-ink">{titleFor(pathname)}</h1>
      </div>
      <div className="flex shrink-0 items-center gap-1 sm:gap-4">
        <NotesBell notes={openNotes} />
        <NewHireButton />
        <div className="flex items-center gap-2 text-sm sm:border-l sm:border-border sm:pl-4">
          {/* The name is the first thing worth dropping on a narrow screen —
              the account is still reachable via the sign-out control. */}
          <span className="hidden font-semibold text-ink md:inline">{userLabel}</span>
          <form action={logout}>
            <button type="submit" aria-label="Abmelden" className="rounded p-2 text-ink-muted hover:bg-surface">
              <LogOut className="h-4 w-4" />
            </button>
          </form>
        </div>
      </div>
    </header>
  );
}
