import type { App } from '../shared/types'

export type DashboardTab = string

// UI state (survives re-renders)
export let currentView: 'dashboard' | 'settings' = 'dashboard'
export let isNarrow: boolean = window.matchMedia('(max-width: 768px)').matches
export let selectedApp: string | null = null
export let sidebarCollapsed: boolean = localStorage.getItem('sidebarCollapsed') === 'true'
export let dashboardTab: DashboardTab = 'urls'
export let mobileSidebar: boolean = false
export let sidebarSection: 'apps' | 'tools' = (localStorage.getItem('sidebarSection') as 'apps' | 'tools') || 'apps'

// Server state (from SSE)
export let apps: App[] = []

// Tab state
export let appTabs: Record<string, string> = {}

// State setters
export function setDashboardTab(tab: DashboardTab) {
  dashboardTab = tab
}

export function setCurrentView(view: 'dashboard' | 'settings') {
  currentView = view
}

export function setSelectedApp(name: string | null) {
  selectedApp = name
}

export function setIsNarrow(narrow: boolean) {
  isNarrow = narrow
}

export function setMobileSidebar(open: boolean) {
  mobileSidebar = open
}

export function setSidebarCollapsed(collapsed: boolean) {
  sidebarCollapsed = collapsed
  localStorage.setItem('sidebarCollapsed', String(collapsed))
}

export function setSidebarSection(section: 'apps' | 'tools') {
  sidebarSection = section
  localStorage.setItem('sidebarSection', section)
}

export function setApps(newApps: App[]) {
  apps = newApps
}

export const getSelectedTab = (appName: string | null) =>
  appName ? appTabs[appName] || 'overview' : 'overview'

export function setSelectedTab(appName: string | null, tab: string) {
  if (!appName) return
  appTabs[appName] = tab
}
