"use client"

/**
 * UtilityBarSchoolSwitcher — avatar-only school/program (or site/location)
 * scope picker for the full-width `utility-bar` shell layout.
 *
 * Sits in the trailing identity cluster next to `UtilityUserMenu` (same
 * size-8 avatar footprint). Labels live in the tooltip + dropdown — not
 * on the trigger — so the bar stays quiet.
 *
 * Menu body and state are shared with the sidebar switcher and the products
 * home — see `components/scope-switcher-menu.tsx`.
 */

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
  SHELL_IDENTITY_MENU_SURFACE_CLASS,
} from "@/components/ui/dropdown-menu"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { utilityBarActionButtonClass } from "@/components/utility-bar-chrome"
import {
  ScopeSwitcherMenuBody,
  useScopeSwitcher,
} from "@/components/scope-switcher-menu"
import { useProduct, type Product } from "@/contexts/product-context"
import { cn } from "@/lib/utils"

export function UtilityBarSchoolSwitcher() {
  const { product } = useProduct()
  return <UtilityBarSchoolSwitcherInner key={product} product={product} />
}

function UtilityBarSchoolSwitcherInner({ product }: { product: Product }) {
  const scope = useScopeSwitcher(product)

  return (
    <DropdownMenu onOpenChange={scope.onOpenChange}>
      <Tooltip>
        <TooltipTrigger asChild>
          <DropdownMenuTrigger asChild>
            <button
              type="button"
              aria-label={scope.ariaLabel}
              data-utility-bar-school-switcher=""
              className={cn(
                // Mirror `UtilityUserMenu` trigger — same size-8 hit + avatar
                // footprint so the two identity circles read as a pair.
                "flex size-8 shrink-0 items-center justify-center rounded-full outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/50",
                utilityBarActionButtonClass,
              )}
            >
              <Avatar className="size-8">
                <AvatarImage
                  src={scope.parent.logo}
                  alt=""
                  referrerPolicy="origin"
                  className="object-cover"
                  aria-hidden="true"
                />
                <AvatarFallback aria-hidden="true">{scope.parent.initials}</AvatarFallback>
              </Avatar>
            </button>
          </DropdownMenuTrigger>
        </TooltipTrigger>
        <TooltipContent side="bottom">
          {scope.child.name} · {scope.parent.name}
        </TooltipContent>
      </Tooltip>

      <DropdownMenuContent
        className={SHELL_IDENTITY_MENU_SURFACE_CLASS}
        align="end"
        side="bottom"
        sideOffset={8}
      >
        <ScopeSwitcherMenuBody scope={scope} />
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
