// #region SidebarStore [C:3] [TYPE Store] [SEMANTICS sidebar, store, navigation, state, toggle]
// @BRIEF Manage sidebar visibility, expansion state, active navigation item, and mobile overlay.
// @LAYER UI
// @RELATION BINDS_TO -> [EnvironmentContextStore]
// @UX_STATE Idle -> Sidebar visible with current state
// @UX_STATE Toggling -> Expand/collapse animation
// @INVARIANT isExpanded state is always synced with localStorage
// @RATIONALE Migrated from Svelte 4 writable to Svelte 5 $state runes.
//            Backward-compatible .subscribe() retained for $sidebarStore syntax.

import { browser } from '$app/environment';

interface SidebarState {
	isExpanded: boolean;
	activeCategory: string;
	activeItem: string;
	isMobileOpen: boolean;
}

const STORAGE_KEY = 'sidebar_state';

function loadState(): SidebarState | null {
	if (!browser) return null;
	try {
		const saved = localStorage.getItem(STORAGE_KEY);
		if (saved) {
			return JSON.parse(saved) as SidebarState;
		}
	} catch (e) {
		console.error('[SidebarStore] Failed to load state:', e);
	}
	return null;
}

function saveState(state: SidebarState): void {
	if (!browser) return;
	try {
		localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
	} catch (e) {
		console.error('[SidebarStore] Failed to save state:', e);
	}
}

const initialState: SidebarState = loadState() || {
	isExpanded: true,
	activeCategory: 'dashboards',
	activeItem: '/dashboards',
	isMobileOpen: false,
};

// Reactive state (Svelte 5 rune)
let _state: SidebarState = $state(initialState);

// Subscriber list for backward compat with $sidebarStore syntax
let _subscribers: Array<(value: SidebarState) => void> = [];

function _notify(): void {
	const current = _state;
	_subscribers.forEach((fn) => fn(current));
}

export const sidebarStore = {
	subscribe(run: (value: SidebarState) => void): () => void {
		_subscribers.push(run);
		run(_state);
		return () => {
			_subscribers = _subscribers.filter((fn) => fn !== run);
		};
	},
	get value(): SidebarState {
		return _state;
	},
};

export function toggleSidebar(): void {
	_state = { ..._state, isExpanded: !_state.isExpanded };
	saveState(_state);
	_notify();
}

export function setActiveItem(category: string, item: string): void {
	if (_state.activeCategory === category && _state.activeItem === item) return;
	_state = { ..._state, activeCategory: category, activeItem: item };
	saveState(_state);
	_notify();
}

export function setMobileOpen(isOpen: boolean): void {
	if (_state.isMobileOpen === isOpen) return;
	_state = { ..._state, isMobileOpen: isOpen };
	_notify();
}

export function closeMobile(): void {
	if (!_state.isMobileOpen) return;
	_state = { ..._state, isMobileOpen: false };
	_notify();
}

export function toggleMobileSidebar(): void {
	_state = { ..._state, isMobileOpen: !_state.isMobileOpen };
	_notify();
}
// #endregion SidebarStore
