/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import { derived, get, writable } from 'svelte/store';

export const createInitialState = () => ({
	page: 'auth',
	session: null,
	device: null,
	deviceToken: null,
	socketConnected: false,
	isMotionActive: false,
	activeMotionSource: null,
	cameraStatus: 'idle',
	cameraPreviewReady: false,
	cameraInputDevices: [],
	selectedCameraInputId: '',
	linkedCameras: [],
	recordings: [],
	motionNotifications: [],
	activeCameraDeviceId: null,
	activeStreamSessionId: null,
	openLinkedCameraMenuId: null,
	activityLog: [],
	cameraSessions: {},
	connectedStreamSessionIds: [],
	loading: true,
	isRegistering: false,
	authForm: {
		email: '',
		password: '',
		name: ''
	},
	onboardingForm: {
		name: '',
		role: 'client',
		pushToken: ''
	},
	toasts: [],
	recordingModal: {
		open: false,
		title: 'Recording Playback',
		url: ''
	},
	motionDetection: {
		enabled: false,
		profile: 'balanced',
		state: 'idle',
		score: 0,
		debug: false,
		lastTriggeredAt: null
	},
	clientStreamMode: 'none',
	clientPlaceholderText: 'Select a camera to view',
	lastError: null
});

export const appState = writable(createInitialState());

export const setAppState = (partial) => {
	appState.update((state) => ({ ...state, ...partial }));
};

export const patchAppState = (updater) => {
	appState.update((state) => ({ ...state, ...updater(state) }));
};

export const getAppState = () => get(appState);

export const resetAppState = (keep = {}) => {
	appState.set({ ...createInitialState(), ...keep });
};

export const unreadNotificationsCount = derived(appState, ($state) =>
	$state.motionNotifications.reduce((count, notification) => count + (notification.isRead ? 0 : 1), 0)
);
