import { watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSidebar } from '@/components/ui/sidebar'
import { useUiStore } from '@/stores/uiStore'

/**
 * Composable that auto-collapses sidebar when navigating to trace view
 * and expands it when returning to trace list.
 *
 * Must be used inside a component within the SidebarProvider tree.
 */
export function useSidebarAutoCollapse() {
  const route = useRoute()
  const uiStore = useUiStore()
  const { setOpen } = useSidebar()

  watch(
    () => route.name,
    (newRouteName, oldRouteName) => {
      // On first load, force sidebar open only on main page.
      // Keep persisted state when deep-linking to trace or node routes.
      if (!oldRouteName) {
        if (newRouteName === 'traceList') {
          setOpen(true)
        }
        return
      }

      // skip route-based automation if user has manually overridden sidebar state
      if (uiStore.sidebarUserOverride) return

      if (newRouteName === 'traceList') {
        setOpen(true)
      } else if (newRouteName === 'trace' && oldRouteName === 'traceList') {
        setOpen(false)
      }
    },
  )
}
