// @ts-nocheck
import { get } from 'svelte/store';
import { afterEach, describe, expect, it } from 'vitest';

import {
	appState,
	createInitialState,
	getAppState,
	patchAppState,
	resetAppState,
	setAppState,
	unreadNotificationsCount
} from './store';

afterEach(() => {
	resetAppState();
});

describe('app store', () => {
	it('creates the expected initial state shape', () => {
		const state = createInitialState();

		expect(state.page).toBe('auth');
		expect(state.motionDetection.profile).toBe('balanced');
		expect(state.clientPlaceholderText).toBe('Select a camera to view');
		expect(state.streamDiagnostics).toEqual({});
	});

	it('setAppState merges top-level properties into the current store', () => {
		setAppState({ page: 'client', socketConnected: true });

		const state = getAppState();
		expect(state.page).toBe('client');
		expect(state.socketConnected).toBe(true);
		expect(state.deviceToken).toBeNull();
	});

	it('patchAppState derives the next state from the previous state', () => {
		patchAppState((state) => ({
			authForm: {
				...state.authForm,
				email: 'test@example.com'
			},
			toasts: [{ id: 'toast-1', title: 'Saved' }]
		}));

		const state = getAppState();
		expect(state.authForm.email).toBe('test@example.com');
		expect(state.toasts).toHaveLength(1);
	});

	it('resetAppState restores defaults while keeping explicit overrides', () => {
		setAppState({ page: 'client', socketConnected: true });
		resetAppState({ page: 'settings' });

		const state = getAppState();
		expect(state.page).toBe('settings');
		expect(state.socketConnected).toBe(false);
		expect(state.linkedCameras).toEqual([]);
	});

	it('counts only unread motion notifications', () => {
		appState.set({
			...createInitialState(),
			motionNotifications: [
				{ id: 'n1', isRead: false },
				{ id: 'n2', isRead: true },
				{ id: 'n3', isRead: false }
			]
		});

		expect(get(unreadNotificationsCount)).toBe(2);
	});
});
