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

import { useSecondaryPanel } from "@/components/sidebar"
import {
  LIBRARY_ENTRY_PATH,
  LIBRARY_HUB_FIND_PATH,
  LIBRARY_LIST_PATH,
} from "@/lib/library-nav"

/** Full-page focused flows under `/library/*` that suppress the secondary panel. */
const LIBRARY_FOCUSED_FLOW_PATHS: readonly string[] = ["/library/new"]

function isLibraryFocusedFlow(pathname: string): boolean {
  return LIBRARY_FOCUSED_FLOW_PATHS.some(
    p => pathname === p || pathname.startsWith(`${p}/`),
  )
}

/**
 * Keeps the nested secondary panel open across library navigations.
 * Hub root, dedicated search surfaces, and focused authoring stay full-width.
 *
 * Mirrors the Next `app/(app)/library/layout.tsx` 1:1 — only the
 * `usePathname` import comes from `react-router-dom` instead of
 * `next/navigation`, and `<Outlet />` replaces the `children` prop.
 */
export function LibraryLayout() {
  const { pathname } = useLocation()
  const { openPanel, closePanel, activePanel } = useSecondaryPanel()
  const closePanelRef = React.useRef(closePanel)
  const openPanelRef = React.useRef(openPanel)

  React.useEffect(() => {
    closePanelRef.current = closePanel
    openPanelRef.current = openPanel
  })

  React.useEffect(() => {
    return () => {
      closePanelRef.current({ mainSidebar: "leave" })
    }
  }, [])

  React.useEffect(() => {
    const isDiscoveryHubRoot =
      pathname === LIBRARY_ENTRY_PATH || pathname === `${LIBRARY_ENTRY_PATH}/`

    const isDedicatedSearchSurface =
      pathname === LIBRARY_HUB_FIND_PATH || pathname === LIBRARY_LIST_PATH

    if (
      isDiscoveryHubRoot ||
      isDedicatedSearchSurface ||
      isLibraryFocusedFlow(pathname)
    ) {
      closePanelRef.current({ mainSidebar: "leave" })
      return undefined
    }

    if (activePanel !== "library") {
      openPanelRef.current("library")
    }
    return undefined
  }, [pathname, activePanel])

  return <Outlet />
}
