// #region AuthStore [C:3] [TYPE Store] [SEMANTICS auth, store, jwt, token, login, session]
// @BRIEF Manages the global authentication state including JWT token, user profile, and login/logout lifecycle.
// @RELATION BINDS_TO -> [PermissionsModule]
// @UX_STATE Loading -> Auth state being initialized from localStorage
// @UX_STATE Authenticated -> User profile and token active
// @UX_STATE Unauthenticated -> No valid session, login required
// @RATIONALE Migrated from Svelte 4 writable + { subscribe, set, update } to Svelte 5 $state runes.
//            Backward-compatible .subscribe() retained for $auth syntax.

// #region authStore:Store [TYPE Function]
// @SEMANTICS: auth, store, svelte, jwt, session
// @PURPOSE:   Manages the global authentication state on the frontend.
// @LAYER:     Feature
// @RELATION CALLED_BY -> AuthService
// @RELATION BINDS_TO -> Navbar

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

// #region AuthState:Interface [TYPE Function]
/**
 * @purpose Defines the structure of the authentication state.
 */
export interface AuthState {
    user: any | null;
    token: string | null;
    isAuthenticated: boolean;
    loading: boolean;
}
// #endregion AuthState:Interface

function createAuthStore() {
    // Reactive state (Svelte 5 rune)
    let _user = $state<any | null>(null);
    let _token = $state<string | null>(browser ? localStorage.getItem('auth_token') : null);
    let _isAuthenticated = $state(false);
    let _loading = $state(true);

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

    function _getState(): AuthState {
        return {
            user: _user,
            token: _token,
            isAuthenticated: _isAuthenticated,
            loading: _loading,
        };
    }

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

    // #region setToken:Function [TYPE Function]
    /**
     * @purpose Updates the store with a new JWT token.
     * @pre token must be a valid JWT string.
     * @post Store updated with new token, isAuthenticated set to true.
     * @param {string} token - The JWT access token.
     */
    function setToken(token: string): void {
        console.log("[setToken][Action] Updating token");
        if (browser) {
            localStorage.setItem('auth_token', token);
        }
        _token = token;
        _isAuthenticated = !!token;
        _notify();
    }
    // #endregion setToken:Function

    // #region setUser:Function [TYPE Function]
    /**
     * @purpose Sets the current user profile data.
     * @pre User object must contain valid profile data.
     * @post Store updated with user, isAuthenticated true, loading false.
     * @param {any} user - The user profile object.
     */
    function setUser(user: any): void {
        console.log("[setUser][Action] Setting user profile");
        _user = user;
        _isAuthenticated = !!user;
        _loading = false;
        _notify();
    }
    // #endregion setUser:Function

    // #region logout:Function [TYPE Function]
    /**
     * @purpose Clears authentication state and storage.
     * @pre User is currently authenticated.
     * @post Auth token removed from localStorage, store reset to initial state.
     */
    function logout(): void {
        console.log("[logout][Action] Logging out");
        if (browser) {
            localStorage.removeItem('auth_token');
        }
        _user = null;
        _token = null;
        _isAuthenticated = false;
        _loading = false;
        _notify();
    }
    // #endregion logout:Function

    // #region setLoading:Function [TYPE Function]
    /**
     * @purpose Updates the loading state.
     * @pre None.
     * @post Store loading state updated.
     * @param {boolean} loading - Loading status.
     */
    function setLoading(loading: boolean): void {
        console.log(`[setLoading][Action] Setting loading to ${loading}`);
        _loading = loading;
        _notify();
    }
    // #endregion setLoading:Function

    return {
        subscribe(run: (value: AuthState) => void): () => void {
            _subscribers.push(run);
            run(_getState());
            return () => {
                _subscribers = _subscribers.filter((fn) => fn !== run);
            };
        },
        setToken,
        setUser,
        logout,
        setLoading,
    };
}
// #endregion createAuthStore:Function

export const auth = createAuthStore();

// #endregion authStore:Store
// #endregion AuthStore
