/**
 * Sidebar React wrapper — Lane A imperative wrap over src/sidebar/component.ts
 *
 * Import from the dedicated subpath:
 *   import { Sidebar } from '@countermeasure-platform/web-components/react/sidebar'
 *
 * The wrapper renders a host div then mounts `SidebarComponent` into it on
 * mount. Prop changes to `sections`, `activeItemId`, and `user` are synced via
 * the class's public API (`setActive`, `updateBadge`, etc.).
 */

import * as React from 'react'
import { cn } from './primitives/utils'
import { SidebarComponent } from '../sidebar/component'
import type {
  SidebarComponentConfig,
  SidebarNavItem,
  SidebarSection,
  SidebarUser,
  SidebarFooterAction,
} from '../sidebar/types'

export interface SidebarProps extends Omit<
  SidebarComponentConfig,
  'container' | 'onNavigate' | 'onCollapse'
> {
  /** Currently active nav item ID. Synced via `setActive` on changes. */
  activeItemId?: string
  /** Called when the user clicks a nav item. */
  onNavigate?: (item: SidebarNavItem) => void
  /** Called when the sidebar is collapsed/expanded. */
  onCollapse?: (collapsed: boolean) => void
  className?: string
}

export type { SidebarNavItem, SidebarSection, SidebarUser, SidebarFooterAction }

function Sidebar({ activeItemId, onNavigate, onCollapse, className, ...config }: SidebarProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const sidebarRef = React.useRef<SidebarComponent | null>(null)
  const onNavigateRef = React.useRef(onNavigate)
  const onCollapseRef = React.useRef(onCollapse)
  onNavigateRef.current = onNavigate
  onCollapseRef.current = onCollapse

  // Construct once on mount — SSR-safe
  React.useEffect(() => {
    if (typeof document === 'undefined' || !containerRef.current) return
    sidebarRef.current = new SidebarComponent({
      ...config,
      container: containerRef.current,
      onNavigate: (item: SidebarNavItem) => {
        onNavigateRef.current?.(item)
      },
      onCollapse: (collapsed: boolean) => {
        onCollapseRef.current?.(collapsed)
      },
    })
    return () => {
      sidebarRef.current?.destroy()
      sidebarRef.current = null
    }
  }, [])

  // Sync active item when prop changes
  React.useEffect(() => {
    if (!sidebarRef.current || activeItemId === undefined) return
    sidebarRef.current.setActive(activeItemId)
  }, [activeItemId])

  return <div ref={containerRef} data-slot="sidebar" className={cn(className)} />
}

Sidebar.displayName = 'Sidebar'

export { Sidebar }
