import { Link } from "@tanstack/react-router";
import { format } from "date-fns";
import { fr } from "date-fns/locale";

import { Brand } from "@/components/brand/Brand";
import { useAuth } from "@/lib/auth";
import { cn } from "@/lib/utils";
import { UserMenu } from "./UserMenu";

/**
 * Topbar — greeting (desktop) ou brand (mobile) à gauche, actions slot et UserMenu à droite.
 * Sticky, bg cream/85 + backdrop-blur (cohérent landing).
 */
type AppTopbarProps = {
  /** Titre de la page courante (au lieu du greeting). Ex: "Factures". */
  title?: string;
  /** Sous-titre (date par défaut, ou contexte custom). */
  subtitle?: string;
  /** Slot d'actions à droite avant l'avatar (ex: boutons + Importer / + Saisir). */
  actions?: React.ReactNode;
};

const GREETING_BY_HOUR = (h: number): string => {
  if (h < 6) return "Bonsoir";
  if (h < 18) return "Bonjour";
  return "Bonsoir";
};

export function AppTopbar({ title, subtitle, actions }: AppTopbarProps) {
  const { user } = useAuth();
  const firstName = user?.fullName?.split(" ")[0];
  const now = new Date();
  const greeting = title ?? `${GREETING_BY_HOUR(now.getHours())} ${firstName ?? ""}`.trim();
  const dateLabel = subtitle ?? format(now, "EEEE d MMMM yyyy", { locale: fr });

  return (
    <header
      className={cn(
        "sticky top-0 z-30 border-b border-line",
        "bg-cream/85 backdrop-blur-md backdrop-saturate-150",
      )}
    >
      <div className="flex items-center justify-between gap-4 px-5 py-4 lg:px-8 lg:py-5">
        {/* Mobile : brand à gauche (pas de sidebar). Desktop : greeting.
            Le brand est cliquable → retour au dashboard. */}
        <Link
          to="/"
          aria-label="Retour au dashboard"
          className={cn(
            "lg:hidden rounded-default cursor-pointer",
            "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rubis-glow",
          )}
        >
          <Brand />
        </Link>
        <div className="hidden lg:block min-w-0">
          <h1 className="font-display text-[19px] font-semibold tracking-[-0.018em] text-ink leading-tight">
            {greeting}
            {!title && firstName && (
              <span aria-hidden="true" className="ml-1.5">
                👋
              </span>
            )}
          </h1>
          <p className="mt-0.5 text-[12.5px] text-ink-3 first-letter:uppercase">{dateLabel}</p>
        </div>

        <div className="flex items-center gap-2 sm:gap-3">
          {actions}
          <UserMenu />
        </div>
      </div>
    </header>
  );
}
