import { writable, derived } from 'svelte/store';
import { api } from '$lib/api/client';
import { calculateCurrentCharges } from '$lib/utils/charges';
import { calculateLevel } from '$lib/utils/level';
import { now } from './global';

export interface User {
	id: number;
	name: string;
	discord: string | null;
	country: string;
	droplets: number;
	currentCharges: number;
	maxCharges: number;
	chargesCooldownMs: number;
	chargesLastUpdatedAt: string;
	pixelsPainted: number;
	level: number;
	equippedFlag: number;
	extraColorsBitmap: number;
	flagsBitmap: string | null;
	showLastPixel: boolean;
	picture: string | null;
	allianceId: number | null;
	allianceRole: string;
	alliance: {
		id: number;
		name: string;
		description: string;
		pixelsPainted: number;
	} | null;
}

function createUserStore() {
	const { subscribe, set, update } = writable<User | null>(null);

	return {
		subscribe,
		set,
		update,
		async fetch() {
			try {
				const user = await api.getMe();
				set(user);
				return user;
			} catch (error) {
				console.error('Failed to fetch user:', error);
				set(null);
				return null;
			}
		},
		async updateProfile(data: { name?: string; showLastPixel?: boolean; discord?: string }) {
			try {
				const updated = await api.updateMe(data);
				set(updated);
				return updated;
			} catch (error) {
				console.error('Failed to update profile:', error);
				throw error;
			}
		},
		async logout() {
			try {
				await api.logout();
				set(null);
			} catch (error) {
				console.error('Failed to logout:', error);
				throw error;
			}
		},
		clear() {
			set(null);
		}
	};
}

export const currentUser = createUserStore();

// Derived store for current charges (recalculated based on time)
export const currentCharges = derived([currentUser, now], ([$user, $now]) => {
	if (!$user) return 0;

	return calculateCurrentCharges(
		$user.currentCharges,
		$user.maxCharges,
		new Date($user.chargesLastUpdatedAt),
		$user.chargesCooldownMs
	);
});

// Derived store for authentication status
export const isAuthenticated = derived(currentUser, ($user) => $user !== null);

// Derived store for user level
export const userLevel = derived(currentUser, ($user) => {
	if (!$user) return 1;
	return calculateLevel($user.pixelsPainted);
});
