/**
 * Sidebar Module
 *
 * Unified sidebar toggle functionality for CounterMeasure applications.
 * Handles collapsible sidebar for desktop and mobile with localStorage persistence.
 *
 * Usage:
 * - Add data-sidebar="{variant}" to your sidebar element (e.g., data-sidebar="admin")
 * - Add data-sidebar-toggle to the toggle button
 * - Add data-sidebar-mobile-toggle to the mobile toggle button
 * - Add data-sidebar-backdrop="{variant}" to the backdrop element
 */

// Re-export programmatic sidebar component
export { SidebarComponent } from './component'
export type {
  SidebarComponentConfig,
  SidebarNavItem,
  SidebarSection,
  SidebarUser,
  SidebarFooterAction,
} from './types'

export interface SidebarConfig {
  storageKey?: string
  mobileBreakpoint?: number
  collapsedClass?: string
}

export interface LegacySidebarConfig {
  sidebar: string
  toggle: string
  mobileToggle: string
  backdrop: string
  collapsedClass: string
}

const DEFAULT_CONFIG: Required<SidebarConfig> = {
  storageKey: 'sidebar-collapsed',
  mobileBreakpoint: 900,
  collapsedClass: 'sidebar--collapsed',
}

let currentConfig: Required<SidebarConfig> = { ...DEFAULT_CONFIG }

/**
 * Configure sidebar settings.
 */
export function configureSidebar(config: SidebarConfig): void {
  currentConfig = { ...DEFAULT_CONFIG, ...config }
}

/**
 * Check if we're on mobile viewport.
 */
export function isMobile(): boolean {
  return window.innerWidth <= currentConfig.mobileBreakpoint
}

/**
 * Get stored collapsed state for a sidebar.
 */
export function getStoredState(key: string): boolean {
  const stored = localStorage.getItem(`${currentConfig.storageKey}-${key}`)
  return stored === 'true'
}

/**
 * Save collapsed state for a sidebar.
 */
export function saveState(key: string, collapsed: boolean): void {
  localStorage.setItem(`${currentConfig.storageKey}-${key}`, String(collapsed))
}

/**
 * Close a sidebar (mobile).
 */
function closeSidebar(sidebar: HTMLElement, backdrop: HTMLElement | null): void {
  sidebar.setAttribute('data-open', 'false')
  if (backdrop) {
    backdrop.setAttribute('data-visible', 'false')
  }
}

/**
 * Toggle sidebar open state (mobile).
 */
function toggleSidebarOpen(sidebar: HTMLElement, backdrop: HTMLElement | null): void {
  const isOpen = sidebar.getAttribute('data-open') === 'true'
  sidebar.setAttribute('data-open', String(!isOpen))
  if (backdrop) {
    backdrop.setAttribute('data-visible', String(!isOpen))
  }
}

interface SidebarHandlerParams {
  sidebar: HTMLElement
  toggle: HTMLButtonElement | null
  mobileToggles: HTMLButtonElement[]
  backdrop: HTMLElement | null
  collapsedClass: string
  key: string
}

/**
 * Attach all sidebar event handlers (shared between unified and legacy init).
 */
function attachSidebarHandlers({
  sidebar,
  toggle,
  mobileToggles,
  backdrop,
  collapsedClass,
  key,
}: SidebarHandlerParams): void {
  // Apply stored collapsed state on desktop
  if (!isMobile() && getStoredState(key)) {
    sidebar.classList.add(collapsedClass)
  }

  // Desktop toggle handler
  if (toggle) {
    toggle.addEventListener('click', () => {
      const isCollapsed = sidebar.classList.toggle(collapsedClass)
      saveState(key, isCollapsed)
    })
  }

  // Mobile toggle handler
  mobileToggles.forEach(mobileToggle => {
    mobileToggle.addEventListener('click', () => {
      toggleSidebarOpen(sidebar, backdrop)
    })
  })

  // Backdrop click handler
  if (backdrop) {
    backdrop.addEventListener('click', () => {
      closeSidebar(sidebar, backdrop)
    })
  }

  // Handle window resize
  window.addEventListener('resize', () => {
    if (isMobile()) {
      closeSidebar(sidebar, backdrop)
    }
  })

  // Close sidebar on escape key
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape' && sidebar.getAttribute('data-open') === 'true') {
      closeSidebar(sidebar, backdrop)
    }
  })
}

/**
 * Initialize a single sidebar using the unified data-sidebar attribute.
 */
function initUnifiedSidebar(sidebar: HTMLElement): void {
  const variant = sidebar.getAttribute('data-sidebar')
  if (variant === null || variant === '') {
    return
  }

  attachSidebarHandlers({
    sidebar,
    toggle: sidebar.querySelector<HTMLButtonElement>('[data-sidebar-toggle]'),
    mobileToggles: Array.from(
      document.querySelectorAll<HTMLButtonElement>('[data-sidebar-mobile-toggle]')
    ),
    backdrop: document.querySelector<HTMLElement>(`[data-sidebar-backdrop="${variant}"]`),
    collapsedClass: currentConfig.collapsedClass,
    key: variant,
  })
}

/**
 * Initialize a legacy sidebar (backwards compatibility).
 */
function initLegacySidebar(config: LegacySidebarConfig): void {
  const sidebar = document.querySelector<HTMLElement>(config.sidebar)
  if (!sidebar) {
    return
  }

  // Skip if this sidebar uses the new unified approach
  if (sidebar.hasAttribute('data-sidebar')) {
    return
  }

  attachSidebarHandlers({
    sidebar,
    toggle: document.querySelector<HTMLButtonElement>(config.toggle),
    mobileToggles: Array.from(document.querySelectorAll<HTMLButtonElement>(config.mobileToggle)),
    backdrop: document.querySelector<HTMLElement>(config.backdrop),
    collapsedClass: config.collapsedClass,
    key: config.sidebar.replace(/[^a-z]/g, ''),
  })
}

/**
 * Default legacy sidebar configurations for CounterMeasure apps.
 */
export const defaultLegacyConfigs: LegacySidebarConfig[] = [
  {
    sidebar: '.page__sidebar',
    toggle: '[data-page-sidebar-toggle]',
    mobileToggle: '[data-page-mobile-toggle]',
    backdrop: '.sidebar-backdrop',
    collapsedClass: 'page__sidebar--collapsed',
  },
  {
    sidebar: '.chat-sidebar',
    toggle: '[data-chat-sidebar-toggle]',
    mobileToggle: '.chat-header__menu-toggle',
    backdrop: '.chat-sidebar-backdrop',
    collapsedClass: 'chat-sidebar--collapsed',
  },
  {
    sidebar: '.files-sidebar',
    toggle: '[data-files-sidebar-toggle]',
    mobileToggle: '[data-files-mobile-toggle]',
    backdrop: '.files-sidebar-backdrop',
    collapsedClass: 'files-sidebar--collapsed',
  },
  {
    sidebar: '.storage-sidebar',
    toggle: '[data-storage-sidebar-toggle]',
    mobileToggle: '[data-storage-mobile-toggle]',
    backdrop: '.storage-sidebar-backdrop',
    collapsedClass: 'storage-sidebar--collapsed',
  },
]

/**
 * Initialize all sidebars (both new unified and legacy).
 */
export function initSidebar(
  config?: SidebarConfig,
  legacyConfigs: LegacySidebarConfig[] = defaultLegacyConfigs
): void {
  if (config) {
    configureSidebar(config)
  }

  // Initialize new unified sidebars
  document.querySelectorAll<HTMLElement>('[data-sidebar]').forEach(initUnifiedSidebar)

  // Initialize legacy sidebars for backwards compatibility
  legacyConfigs.forEach(initLegacySidebar)
}
