"use client"

/**
 * AskLeoSidebar — app-wide right rail for the AI assistant.
 * Mirrors the left sidebar behavior: slides in/out with a toggle button.
 * Lives in the (app) layout so it persists across all pages.
 *
 * The conversation itself is `AskLeoThreadBody`, shared with the floating
 * window (`components/ask-leo-window.tsx`); this file owns only the docked
 * shell and its header.
 */

import * as React from "react"
import { useLocation } from "react-router"
import { useProduct } from "@/contexts/product-context"
import { productSlug } from "@/stores/app-store"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { useSidebar } from "@/components/ui/sidebar"
import {
  ASK_LEO_PANEL_WIDTH_DEFAULT,
  ASK_LEO_PANEL_WIDTH_KEY,
  NestedSecondaryPanelShell,
} from "@/components/templates/nested-secondary-panel-shell"
import { useSidebarReflowZoom } from "@/hooks/use-sidebar-reflow-zoom"
import { AskLeoShortcutKbds, useAskLeo } from "@/components/ask-leo-context"
import {
  AskLeoIdentity,
  AskLeoNewChatButton,
  AskLeoThreadBody,
} from "@/components/ask-leo-thread-body"
import { AskLeoViewToggle } from "@/components/ask-leo-view-toggle"
import { useLeoAmbience } from "@/components/leo-ambience-context"
import { LeoIcon } from "@/components/ui/leo-icon"
import { focusAskLeoLauncher } from "@/lib/ask-leo-focus"

function isLeoLandingPath(pathname: string, leoHref: string) {
  return pathname === leoHref || pathname.startsWith(`${leoHref}/`)
}

/**
 * Right-rail Ask Leo — same shell as {@link NestedSecondaryPanelShell} / library secondary nav.
 * Sits beside `SidebarInset` in the app row (not inside the main inset card).
 */
export function AskLeoSidebar() {
  const { open, setOpen } = useAskLeo()
  const { setSettingsOpen } = useLeoAmbience()
  const { isMobile } = useSidebar()
  const reflowZoom = useSidebarReflowZoom()
  const navFlyout = isMobile || reflowZoom
  const { pathname } = useLocation()
  const { product } = useProduct()
  const leoHref = `/${productSlug(product)}/leo`
  const isOnLeoLanding = isLeoLandingPath(pathname, leoHref)

  // Closing takes the focused button off the page with it, which drops focus to
  // the document root. Hand it back to the toggle that reopens the panel.
  const closePanel = React.useCallback(() => {
    setOpen(false)
    focusAskLeoLauncher()
  }, [setOpen])

  // Primary-nav collapse lives in `AskLeoShell` so switching panel → window
  // restores the hub width (window must not leave the sidebar collapsed).

  if (isOnLeoLanding) {
    return null
  }

  return (
    <>
      {navFlyout && open ? (
        <div
          aria-hidden="true"
          className="fixed inset-0 z-40 bg-background/60"
          onClick={() => setOpen(false)}
        />
      ) : null}
      <NestedSecondaryPanelShell
        open={open}
        compact={false}
        overlay={navFlyout ? (isMobile ? "mobile" : "desktop") : false}
        side="right"
        dataSlot="ask-leo-panel"
        widthPersistKey={ASK_LEO_PANEL_WIDTH_KEY}
        widthDefault={ASK_LEO_PANEL_WIDTH_DEFAULT}
        aria-label="Ask Leo, AI assistant"
        contentClassName="flex min-h-0 flex-1 flex-col overflow-hidden"
      >
        <div className="flex min-h-0 flex-1 flex-col">
          {/* Header — title row + view menu + close */}
          <div className="flex shrink-0 flex-col gap-2 border-b border-sidebar-border/50 px-3 pb-3 pt-3.5">
            <div className="flex items-start justify-between gap-2">
              {/* Double-click is a pointer shortcut only. The keyboard route to
                  appearance is the Appearance item in `AskLeoViewToggle`. */}
              <div
                className="min-w-0 flex-1 select-none"
                onDoubleClick={() => setSettingsOpen(true)}
              >
                <AskLeoIdentity />
              </div>
              <div className="flex shrink-0 items-center gap-1">
                <AskLeoNewChatButton />
                <AskLeoViewToggle />
                <Tooltip>
                  <TooltipTrigger asChild>
                    <button
                      type="button"
                      onClick={closePanel}
                      className="icon-button-chrome inline-flex size-8 shrink-0 items-center justify-center rounded-md hover:bg-sidebar-accent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      aria-label="Close Ask Leo"
                    >
                      <i className="fa-light fa-xmark text-xs" aria-hidden="true" />
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side="bottom" className="flex max-w-xs flex-wrap items-center gap-1.5 text-xs">
                    <span>Close Ask Leo</span>
                    <AskLeoShortcutKbds />
                  </TooltipContent>
                </Tooltip>
              </div>
            </div>
          </div>

          <AskLeoThreadBody />
        </div>
      </NestedSecondaryPanelShell>
    </>
  )
}

// ─────────────────────────────────────────────────────────────────────────────
// Toggle button — can be placed anywhere (e.g. in SiteHeader or floating)
// ─────────────────────────────────────────────────────────────────────────────

export function AskLeoToggle({
  className,
  showLabel = false,
}: {
  className?: string
  /** When true, show “Ask Leo” text beside the icon (utility bar). */
  showLabel?: boolean
}) {
  const { toggle, open } = useAskLeo()
  const ariaLabel = open ? "Close Ask Leo" : "Ask Leo"
  const [motionActive, setMotionActive] = React.useState(false)
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          type="button"
          variant="ghost"
          size={showLabel ? "sm" : "icon-sm"}
          // Focus comes back here when Leo closes.
          data-slot="ask-leo-toggle"
          aria-label={ariaLabel}
          onClick={toggle}
          onMouseEnter={() => setMotionActive(true)}
          onMouseLeave={() => setMotionActive(false)}
          onFocus={() => setMotionActive(true)}
          onBlur={() => setMotionActive(false)}
          className={cn(
            "items-center overflow-visible",
            showLabel && "h-8 gap-1.5 px-2",
            open && "bg-brand/10 text-brand hover:bg-brand/15 hover:text-brand",
            className,
          )}
        >
          <span
            aria-hidden
            className="relative inline-flex size-5 shrink-0 items-center justify-center self-center overflow-visible [--leo-icon-fill:var(--brand-color)]"
          >
            <LeoIcon
              variant="ambient"
              size="xs"
              motionActive={motionActive}
              className="pointer-events-none overflow-visible"
            />
          </span>
          {showLabel ? (
            <span className="self-center text-sm font-medium leading-none">Ask Leo</span>
          ) : null}
        </Button>
      </TooltipTrigger>
      <TooltipContent side="bottom" className="flex flex-wrap items-center gap-1.5">
        {showLabel ? <AskLeoShortcutKbds /> : (
          <>
            <span>{ariaLabel}</span>
            <AskLeoShortcutKbds />
          </>
        )}
      </TooltipContent>
    </Tooltip>
  )
}
