import { writable } from 'svelte/store';
import { auth } from '$lib/firebase/config.js';
import { signInAnonymously, onAuthStateChanged } from 'firebase/auth';

// tracks the current Firebase auth user (anonymous, persists across reloads on this device)
export const userStore = writable({
  uid: null,
  ready: false
});

// signs the device in anonymously (if not already) and keeps userStore in sync
export function initAuth() {
  signInAnonymously(auth);

  onAuthStateChanged(auth, (user) => {
    if (user) {
      userStore.set({ uid: user.uid, ready: true });
    }
  });
}
