// #region ActivityStore [C:2] [TYPE Store] [SEMANTICS activity, store, derived, task-count, badge]
// @BRIEF Derived store that counts active running tasks for navbar indicator badge.
// @LAYER UI
// @RELATION DEPENDS_ON -> [TaskDrawerStore]
// @UX_STATE Idle -> No active tasks, badge hidden
// @UX_STATE Active -> Badge shows count of running tasks
// @RATIONALE Migrated from Svelte 4 derived() to Svelte 5 $derived rune.
//            Subscribes to taskDrawerStore ($state-based) to keep _drawerState in sync.
//            $derived auto-computes _activity from _drawerState.

import { taskDrawerStore } from './taskDrawer.svelte.js';

interface TaskInfo {
	taskId: string;
	status: string;
}

interface ResourceTaskMap {
	[k: string]: TaskInfo;
}

interface DrawerState {
	isOpen: boolean;
	activeTaskId: string | null;
	resourceTaskMap: ResourceTaskMap;
}

interface ActivityState {
	activeCount: number;
	recentTasks: { taskId: string; resourceId: string; status: string }[];
}

function computeActivity(drawer: DrawerState): ActivityState {
	const activeCount = Object.values(drawer.resourceTaskMap)
		.filter((t: TaskInfo) => t.status === 'RUNNING').length;

	return {
		activeCount,
		recentTasks: Object.entries(drawer.resourceTaskMap)
			.map(([resourceId, taskInfo]) => ({
				taskId: taskInfo.taskId,
				resourceId,
				status: taskInfo.status,
			}))
			.slice(-5),
	};
}

// Reactive state (Svelte 5 rune)
let _drawerState: DrawerState = $state({
	isOpen: false,
	activeTaskId: null,
	resourceTaskMap: {},
});

// Derived computation
let _activity: ActivityState = $derived(computeActivity(_drawerState));

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

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

// Subscribe to taskDrawerStore to keep _drawerState in sync
taskDrawerStore.subscribe((drawer: DrawerState) => {
	_drawerState = drawer;
	// $derived will auto-update _activity, but we need to notify subscribers
	_notify();
});

export const activityStore = {
	subscribe(run: (value: ActivityState) => void): () => void {
		_subscribers.push(run);
		run(_activity);
		return () => {
			_subscribers = _subscribers.filter((fn) => fn !== run);
		};
	},
	get value(): ActivityState {
		return _activity;
	},
};
// #endregion ActivityStore
