'use client';

import { usePathname } from 'next/navigation';
import { Menu, ShieldCheck } from 'lucide-react';

import { UserMenu } from '@/components/layout/user-menu';
import { getAllMenuItems, getMenuIcon } from '@/lib/menu';
import { siteConfig } from '@/lib/site';

const extraTitles: Record<string, string> = {
  '/parametres-compte': 'Paramètres du compte',
};

function useCurrentEntry(): { title: string; icon: string | null } {
  const pathname = usePathname();

  // Le titre ne dépend pas des autorisations : l'entrée est cherchée parmi
  // toutes celles déclarées, même si l'utilisateur n'y a pas accès.
  const current = getAllMenuItems().find(
    (item) => pathname === item.href || pathname.startsWith(`${item.href}/`),
  );

  if (current) {
    return { title: current.label, icon: current.icon };
  }

  return {
    title: extraTitles[pathname] ?? siteConfig.product,
    icon: null,
  };
}

export function Header({ onOpenMenu }: { onOpenMenu: () => void }) {
  const { title, icon } = useCurrentEntry();
  const Icon = icon ? getMenuIcon(icon) : ShieldCheck;

  return (
    <header className="sticky top-0 z-30 flex h-16 shrink-0 items-center gap-3 border-b border-border/70 bg-card/80 px-4 backdrop-blur-xl sm:px-6">
      <button
        type="button"
        className="rounded-lg p-2 text-muted-foreground transition-colors hover:bg-accent hover:text-primary lg:hidden"
        aria-label="Ouvrir le menu"
        onClick={onOpenMenu}
      >
        <Menu className="h-5 w-5" />
      </button>

      <span
        aria-hidden
        className="brand-gradient flex h-9 w-9 shrink-0 items-center justify-center rounded-xl text-white shadow-brand"
      >
        <Icon className="h-[18px] w-[18px]" strokeWidth={1.9} />
      </span>

      <div className="min-w-0">
        <p className="truncate text-base font-semibold leading-tight tracking-tight">
          {title}
        </p>
        <p className="hidden truncate text-[11px] text-muted-foreground sm:block">
          {siteConfig.product} · Coffre-fort numérique
        </p>
      </div>

      <div className="ml-auto flex items-center gap-2">
        <UserMenu />
      </div>
    </header>
  );
}
