"use client"

import { useEffect, useRef } from "react"
import { useLocation } from "react-router-dom"
import { useSidebar } from "@/components/ui/sidebar"
import { useSecondaryPanel } from "@/components/sidebar/secondary-panel"
import { isLibraryFocusShellWithNestedNav } from "@/lib/library-nav"

/**
 * Collapses the primary sidebar on mount for focused full-page forms / wizards.
 * Restores previous primary state on unmount.
 *
 * When nested library scope nav was already open, the focus shell hides the
 * primary sidebar entirely and keeps the secondary panel on its compact icon rail.
 *
 * Both transitions pass `{ persist: false }` so the visual collapse never
 * overwrites the user's saved sidebar preference (the `sidebar_state_v2`
 * cookie). Only an explicit toggle (⌘B / sidebar button) persists.
 */
export function SidebarAutoCollapse() {
  const { pathname } = useLocation()
  const { open, setOpen } = useSidebar()
  const { activePanel, openPanel } = useSecondaryPanel()
  const prevOpen = useRef(open)
  const nestedNavOnMount = useRef(
    isLibraryFocusShellWithNestedNav(pathname, activePanel),
  )

  useEffect(() => {
    prevOpen.current = open
    setOpen(false, { persist: false })

    if (nestedNavOnMount.current) {
      openPanel("library", { compact: true })
    }

    return () => {
      setOpen(prevOpen.current, { persist: false })
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return null
}
