import { writable, derived } from 'svelte/store';
import type { User } from '@supabase/supabase-js';

export const currentUser = writable<User | null>(null);
export const authLoading = writable<boolean>(true);

export const isAuthenticated = derived(currentUser, ($user) => $user !== null);

/** Display name derived from Supabase user metadata, with email fallback. */
export const displayName = derived(currentUser, ($user) => {
	if (!$user) return '';
	const meta = $user.user_metadata as Record<string, unknown>;
	return (
		(meta['full_name'] as string) ??
		(meta['name'] as string) ??
		$user.email?.split('@')[0] ??
		''
	);
});
