const isBrowser = typeof window !== 'undefined';

// Kratos configuration - always use production auth server
const KRATOS_BASE_URL = 'https://auth.example.com';

// Get the app's origin for return_to URLs
const APP_ORIGIN = isBrowser ? window.location.origin : '';

export type SessionIdentity = {
	id: string;
	traits: {
		email?: string;
		name?: {
			first?: string;
			last?: string;
		};
		phone?: string;
		profile_type?: string;
	};
	metadata_public?: {
		django_profile_id?: string;
		customer_id?: string;
	};
};

export type Session = {
	id: string;
	active: boolean;
	identity: SessionIdentity;
	expires_at?: string;
	authenticated_at?: string;
} | null;

function createAuthStore() {
	let session = $state<Session>(null);
	let checkInProgress = false;

	const isAuthenticated = $derived(Boolean(session?.active));
	const userEmail = $derived(session?.identity?.traits?.email ?? null);
	const userFullName = $derived(
		session?.identity?.traits?.name
			? `${session.identity.traits.name.first ?? ''} ${session.identity.traits.name.last ?? ''}`.trim()
			: null
	);

	async function checkSession(fetchFn?: typeof fetch): Promise<Session> {
		const fetchToUse = fetchFn || (isBrowser ? fetch : null);
		if (!fetchToUse) return null;
		if (checkInProgress && !fetchFn) return null;

		if (!fetchFn) checkInProgress = true;

		try {
			const response = await fetchToUse(`${KRATOS_BASE_URL}/sessions/whoami`, {
				credentials: 'include',
				headers: {
					Accept: 'application/json'
				}
			});

			if (response.ok) {
				const sessionData = await response.json();
				session = sessionData;
				return sessionData;
			} else {
				session = null;
				return null;
			}
		} catch (error) {
			console.warn('Failed to check session:', error);
			session = null;
			return null;
		} finally {
			if (!fetchFn) checkInProgress = false;
		}
	}

	async function logout(returnTo?: string): Promise<void> {
		if (!isBrowser) return;

		try {
			const returnUrl = returnTo || APP_ORIGIN;
			const logoutEndpoint = `${KRATOS_BASE_URL}/self-service/logout/browser?return_to=${encodeURIComponent(returnUrl)}`;
			const response = await fetch(logoutEndpoint, {
				credentials: 'include'
			});

			if (response.ok) {
				const logoutData = await response.json();
				if (logoutData.logout_url) {
					window.location.href = logoutData.logout_url;
				}
			}
		} catch (error) {
			console.error('Logout failed:', error);
		} finally {
			session = null;
		}
	}

	function redirectToLogin(returnTo?: string): void {
		if (!isBrowser) return;

		const returnUrl = returnTo
			? returnTo.startsWith('http')
				? returnTo
				: `${APP_ORIGIN}${returnTo}`
			: window.location.href;

		window.location.href = `${KRATOS_BASE_URL}/self-service/login/browser?return_to=${encodeURIComponent(returnUrl)}`;
	}

	function redirectToRegistration(returnTo?: string): void {
		if (!isBrowser) return;

		const returnUrl = returnTo
			? returnTo.startsWith('http')
				? returnTo
				: `${APP_ORIGIN}${returnTo}`
			: window.location.href;

		window.location.href = `${KRATOS_BASE_URL}/self-service/registration/browser?return_to=${encodeURIComponent(returnUrl)}`;
	}

	// Initialize session check on browser
	if (isBrowser) {
		checkSession().catch(() => {
			// Intentionally ignored - error already logged in checkSession
		});
	}

	return {
		get session() {
			return session;
		},
		get isAuthenticated() {
			return isAuthenticated;
		},
		get userEmail() {
			return userEmail;
		},
		get userFullName() {
			return userFullName;
		},
		checkSession,
		logout,
		redirectToLogin,
		redirectToRegistration
	};
}

export const auth = createAuthStore();
