import { setAuthToken, setUnauthorizedHandler } from '$lib/api/client';
import { getSession } from '$lib/api/admin';

function safeGet(key: string): string | null {
	try {
		return localStorage.getItem(key);
	} catch {}
	try {
		return sessionStorage.getItem(key);
	} catch {}
	try {
		// @ts-expect-error - app-local global fallback
		return globalThis.__treehouse_auth?.[key] ?? null;
	} catch {}
	return null;
}

function safeSet(key: string, value: string) {
	let ok = false;
	try {
		localStorage.setItem(key, value);
		ok = true;
	} catch {}
	if (!ok) {
		try {
			sessionStorage.setItem(key, value);
			ok = true;
		} catch {}
	}
	if (!ok) {
		try {
			// @ts-expect-error - app-local global fallback
			globalThis.__treehouse_auth = globalThis.__treehouse_auth || {};
			// @ts-expect-error - app-local global fallback
			globalThis.__treehouse_auth[key] = value;
		} catch {}
	}
}

function safeRemove(key: string) {
	try {
		localStorage.removeItem(key);
	} catch {}
	try {
		sessionStorage.removeItem(key);
	} catch {}
	try {
		// @ts-expect-error - app-local global fallback
		if (globalThis.__treehouse_auth) delete globalThis.__treehouse_auth[key];
	} catch {}
}

function createAuthStore() {
	let token = $state('');
	let authenticated = $state(false);
	let sessionCheckSeq = 0;
	let ready = $state(false);

	function init() {
		ready = false;
		setUnauthorizedHandler(() => {
			token = '';
			authenticated = false;
		});
		const saved = safeGet('mc_token');
		if (saved) {
			token = saved;
			authenticated = true;
			setAuthToken(saved);
			ready = true;
			return;
		}
		// Cookie-based session (for browsers that block storage).
		const seq = ++sessionCheckSeq;
		getSession()
			.then(() => {
				if (sessionCheckSeq !== seq) return;
				authenticated = true;
				setAuthToken('');
				ready = true;
			})
			.catch(() => {
				if (sessionCheckSeq !== seq) return;
				authenticated = false;
				ready = true;
			});
	}

	function login(t: string) {
		sessionCheckSeq++;
		token = t;
		authenticated = true;
		setAuthToken(t);
		safeSet('mc_token', t);
	}

	function loginCookieSession() {
		sessionCheckSeq++;
		token = '';
		authenticated = true;
		setAuthToken('');
		safeRemove('mc_token');
	}

	function logout() {
		sessionCheckSeq++;
		token = '';
		authenticated = false;
		setAuthToken('');
		safeRemove('mc_token');
	}

	return {
		get token() { return token; },
		get authenticated() { return authenticated; },
		get ready() { return ready; },
		init,
		login,
		loginCookieSession,
		logout,
	};
}

export const auth = createAuthStore();
