"use client"

/**
 * UtilityBarSlot — persistent shell row for global utility actions
 * (Search, Notifications, Help, Settings, Ask Leo, Profile, and — in the
 * "utility-bar" shell layout variant — the product switcher too).
 *
 * Three shell layout variants, driven by `useShellLayout()`:
 *   - "sidebar-classic": not mounted — actions live in the sidebar.
 *   - "utility-sidebar": mounted inside `[data-app-shell-workspace]`,
 *     spanning the secondary rail + main canvas only.
 *   - "utility-bar": mounted as a full-width row ABOVE the sidebar+workspace
 *     row. Sidebar expand/collapse + product switcher on the left; avatar-only
 *     school/scope sits in the trailing identity cluster next to profile.
 *
 * At mobile / high-zoom (`useUtilityBarCompact`), Search, Ask Leo, Help, and
 * Settings collapse into a single More menu; Notifications + profile stay visible.
 */

import * as React from "react"
import { Link, useLocation } from "react-router"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { SidebarTrigger, useSidebar } from "@/components/ui/sidebar"
import { useModKeyLabel } from "@/hooks/use-mod-key-label"
import { useIsMobile } from "@/hooks/use-mobile"
import { useSidebarReflowZoom } from "@/hooks/use-sidebar-reflow-zoom"
import { requestOpenCommandMenu } from "@/components/command-menu"
import { AskLeoShortcutKbds, useAskLeo } from "@/components/ask-leo-context"
import { AskLeoToggle } from "@/components/ask-leo-sidebar"
import { ExxatProductMark } from "@/components/exxat-product-logo"
import { NotificationBell } from "@/components/notification-bell"
import { UtilityUserMenu } from "@/components/utility-user-menu"
import { UtilityBarProductSwitcher } from "@/components/utility-bar-product-switcher"
import { UtilityBarSchoolSwitcher } from "@/components/utility-bar-school-switcher"
import { useProduct } from "@/contexts/product-context"
import { useShellLayout, isFullWidthUtilityBar } from "@/contexts/shell-layout-context"
import { getSecondaryNavForProduct } from "@/lib/mock/navigation"
import { isProductsHomePath } from "@/lib/product-home"
import { cn } from "@/lib/utils"
import { utilityBarActionButtonClass } from "@/components/utility-bar-chrome"

const SUPPRESS_UTILITY_BAR_PATHS: ReadonlyArray<string> = ["/builder/onboarding"]

/**
 * Which registry entry supplies the home mark. The choice is cosmetic — the
 * round mark is brand-level and every product registers the same corporate
 * pink gradient for it — but naming the flagship keeps the mark off whatever
 * product the store happens to still be holding from the last session.
 */
const HOME_BRAND_MARK_PRODUCT = "exxat-prism" as const

function useUtilityBarCompact() {
  const isMobile = useIsMobile()
  const reflowZoom = useSidebarReflowZoom()
  return isMobile || reflowZoom
}

export function UtilityBarSlot() {
  const location = useLocation()
  const { variant } = useShellLayout()
  const fullWidth = isFullWidthUtilityBar(variant)
  const compact = useUtilityBarCompact()
  const [leoGlowIntroActive, setLeoGlowIntroActive] = React.useState(true)
  if (SUPPRESS_UTILITY_BAR_PATHS.some(path => location.pathname.startsWith(path))) return null

  // The products home has no product and no sidebar, so most of this bar has
  // nothing to act on: search scopes to a product, Settings and Ask Leo belong
  // to one, the scope picker needs one, and the sidebar toggle would toggle a
  // sidebar that is not rendered. What is left is genuinely global.
  const productsHome = isProductsHomePath(location.pathname)

  return (
    <nav
      aria-label="Global utilities"
      data-slot="utility-bar"
      className={cn(
        "relative flex min-w-0 shrink-0 items-center gap-1",
        fullWidth
          ? "z-30 h-12 min-h-12 w-full overflow-visible bg-sidebar pe-2 sm:pe-3"
          : "z-40 mx-2 mb-1.5 overflow-visible py-1 md:mb-2",
      )}
    >
      {fullWidth && !productsHome ? <UtilityBarLeadingCluster /> : null}
      {productsHome ? <HomeBrandMark /> : null}

      <div className="flex min-w-0 flex-1 self-stretch items-center justify-end gap-1">
        {productsHome ? (
          <>
            <NotificationBell className={utilityBarActionButtonClass} />
            <HelpTrigger />
          </>
        ) : compact ? (
          <>
            <NotificationBell className={utilityBarActionButtonClass} />
            <UtilityBarMoreMenu />
          </>
        ) : (
          <>
            <SearchTrigger />
            <NotificationBell className={utilityBarActionButtonClass} />
            <HelpTrigger />
            <SettingsTrigger />
            <div
              data-ask-leo-utility-glow-wrap=""
              data-intro={leoGlowIntroActive ? "" : undefined}
              className="relative z-[1] flex shrink-0 items-center self-stretch"
            >
              <span
                aria-hidden
                data-ask-leo-utility-glow=""
                className="pointer-events-none absolute inset-0 forced-colors:hidden"
                onAnimationEnd={(event) => {
                  if (event.animationName === "ask-leo-utility-glow-intro") {
                    setLeoGlowIntroActive(false)
                  }
                }}
              />
              <AskLeoToggle
                showLabel
                className={cn(
                  utilityBarActionButtonClass,
                  "relative z-[1] !bg-transparent hover:!bg-transparent focus-visible:!bg-transparent aria-expanded:!bg-transparent",
                )}
              />
            </div>
          </>
        )}
      </div>

      <div className="mx-0.5 h-5 w-px shrink-0 bg-border sm:mx-1" aria-hidden="true" />
      <div className="flex shrink-0 items-center gap-1.5">
        {fullWidth && !productsHome ? <UtilityBarSchoolSwitcher /> : null}
        <UtilityUserMenu />
      </div>
    </nav>
  )
}

/**
 * Exxat mark on the products home.
 *
 * The leading cluster is suppressed there (no sidebar to toggle, no product to
 * name), which left the row with no brand on it at all. The mark is the one
 * piece of that cluster that still holds on a page about every product: it is
 * drawn from the brand registry, and every registered brand paints it in the
 * same corporate pink, so it says "Exxat" rather than naming a product the
 * user has not picked yet.
 *
 * Sits at the start of the row, where the product mark sits inside a product,
 * so the brand stays in one place as you move between home and a product.
 * Decorative, and deliberately not a link — the page it would navigate to is
 * the page it is on.
 */
function HomeBrandMark() {
  return (
    <span className="flex size-8 shrink-0 items-center justify-center ms-2 sm:ms-3">
      <ExxatProductMark product={HOME_BRAND_MARK_PRODUCT} className="size-6" />
    </span>
  )
}

/** Expand / collapse + product — toggle centered on the inset icon rail. */
function UtilityBarLeadingCluster() {
  const { isNavFlyout } = useSidebar()
  const { pathname } = useLocation()
  // On the products home the page itself is the switcher, and no product is
  // selected yet — a trigger reading "Prism" there would claim a context the
  // user has not chosen.
  const productsHome = pathname === "/home" || pathname.startsWith("/home/")
  return (
    <div className="flex min-w-0 shrink-0 items-center gap-0.5">
      <div
        className={cn(
          "flex shrink-0 items-center",
          // Inset sidebar gap is `--sidebar-width-icon + spacing(4)` with `p-2`
          // on the container — match that width so the toggle shares a center
          // line with the dashboard / primary icons below. The width MUST NOT
          // depend on expanded/collapsed state: the icon column keeps the same
          // center line in both, and a state-dependent slot would slide the
          // product switcher sideways on every toggle. Flyout mode has no rail
          // in layout, so it falls back to plain leading padding.
          isNavFlyout
            ? "justify-start ps-2 sm:ps-3"
            : "w-[calc(var(--sidebar-width-icon)+(--spacing(4)))] justify-center",
        )}
      >
        <UtilityBarSidebarToggle />
      </div>
      {productsHome ? null : <UtilityBarProductSwitcher />}
    </div>
  )
}

/** Expand / collapse primary sidebar — leading control before the product mark. */
function UtilityBarSidebarToggle() {
  const { state, isMobile } = useSidebar()
  const mod = useModKeyLabel()
  const collapsed = state === "collapsed" && !isMobile
  const label = collapsed ? "Expand sidebar" : "Collapse sidebar"
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <SidebarTrigger
          aria-label={label}
          className={cn(
            "size-8 shrink-0 text-sidebar-foreground",
            utilityBarActionButtonClass,
          )}
        />
      </TooltipTrigger>
      <TooltipContent side="bottom" className="flex flex-wrap items-center gap-1.5">
        <span>{label}</span>
        <KbdGroup>
          <Kbd>{mod}</Kbd>
          <Kbd>B</Kbd>
        </KbdGroup>
      </TooltipContent>
    </Tooltip>
  )
}

function UtilityBarMoreMenu() {
  const mod = useModKeyLabel()
  const { product } = useProduct()
  const [settings] = getSecondaryNavForProduct(product)
  const { toggle: toggleAskLeo, open: askLeoOpen } = useAskLeo()

  return (
    <DropdownMenu>
      <Tooltip>
        <TooltipTrigger asChild>
          <DropdownMenuTrigger asChild>
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              aria-label="More utilities"
              className={utilityBarActionButtonClass}
            >
              <i className="fa-light fa-ellipsis text-sm" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
        </TooltipTrigger>
        <TooltipContent side="bottom">More</TooltipContent>
      </Tooltip>
      <DropdownMenuContent align="end" side="bottom" sideOffset={8} className="w-52">
        <DropdownMenuItem
          onClick={() => requestOpenCommandMenu()}
          className="gap-2"
        >
          <i className="fa-light fa-magnifying-glass w-4 text-center text-sm" aria-hidden="true" />
          <span className="flex-1">Search</span>
          <KbdGroup className="ms-auto">
            <Kbd>{mod}</Kbd>
            <Kbd>K</Kbd>
          </KbdGroup>
        </DropdownMenuItem>
        <DropdownMenuItem asChild className="gap-2">
          <Link to="/help">
            <i className="fa-light fa-circle-question w-4 text-center text-sm" aria-hidden="true" />
            Get Help
          </Link>
        </DropdownMenuItem>
        <DropdownMenuItem asChild className="gap-2">
          <Link to={settings.url}>
            <i className="fa-light fa-gear w-4 text-center text-sm" aria-hidden="true" />
            {settings.title}
          </Link>
        </DropdownMenuItem>
        <DropdownMenuItem onClick={toggleAskLeo} className="gap-2">
          <i
            className="fa-duotone fa-solid fa-star-christmas w-4 text-center text-sm text-brand"
            aria-hidden="true"
          />
          <span className="flex-1">{askLeoOpen ? "Close Ask Leo" : "Ask Leo"}</span>
          <AskLeoShortcutKbds className="ms-auto" />
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function SearchTrigger() {
  const mod = useModKeyLabel()
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size="icon-sm"
          aria-label="Search"
          className={utilityBarActionButtonClass}
          onClick={() => requestOpenCommandMenu()}
        >
          <i className="fa-light fa-magnifying-glass text-sm" aria-hidden="true" />
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom" className="flex items-center gap-1.5">
        <span>Search</span>
        <KbdGroup>
          <Kbd>{mod}</Kbd>
          <Kbd>K</Kbd>
        </KbdGroup>
      </TooltipContent>
    </Tooltip>
  )
}

function SettingsTrigger() {
  const { product } = useProduct()
  const [settings] = getSecondaryNavForProduct(product)

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size="icon-sm"
          aria-label={settings.title}
          className={utilityBarActionButtonClass}
          asChild
        >
          <Link to={settings.url}>
            <i className="fa-light fa-gear text-sm" aria-hidden="true" />
          </Link>
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom">{settings.title}</TooltipContent>
    </Tooltip>
  )
}

function HelpTrigger() {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size="icon-sm"
          aria-label="Get Help"
          className={utilityBarActionButtonClass}
          asChild
        >
          <Link to="/help">
            <i className="fa-light fa-circle-question text-sm" aria-hidden="true" />
          </Link>
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom">Get Help</TooltipContent>
    </Tooltip>
  )
}
