// Visibility for docked apps — persisted so "hidden" survives reloads.
// Keyed by app id; an ABSENT key means visible (the default for a newly
// registered docked app, so a fresh install shows the mascot without the
// operator opting in). This means the store only holds *overrides* — it
// doesn't need to enumerate the docked apps to seed defaults, which would
// require importing APPS and create a static cycle (apps.ts -> pages ->
// windows.ts -> here -> apps.ts, TDZ on APPS at init). Unknown persisted
// keys are kept (merge semantics), so an uninstalled-then-reinstalled
// docked app remembers its visibility across the gap.
import { writable, get } from 'svelte/store'

export const STORAGE_KEY = 'oikos-docked-apps'

function load(): Record<string, boolean> {
  if (typeof localStorage === 'undefined') return {}
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return {}
    return JSON.parse(raw) as Record<string, boolean>
  } catch {
    return {}
  }
}

const _visibility = writable<Record<string, boolean>>(load())

function persist(vis: Record<string, boolean>): void {
  if (typeof localStorage === 'undefined') return
  localStorage.setItem(STORAGE_KEY, JSON.stringify(vis))
}

_visibility.subscribe(persist)

// Read-only surface for components; mutations go through toggleDocked.
export const dockedVisibility = { subscribe: _visibility.subscribe }

export function toggleDocked(appId: string): void {
  _visibility.update((vis) => ({ ...vis, [appId]: !(vis[appId] ?? true) }))
}

export function isDockedVisible(appId: string): boolean {
  return get(_visibility)[appId] ?? true
}
