import { auth, db, googleProvider } from '../firebase.js';
import { onAuthStateChanged, signInWithPopup, signOut as fbSignOut } from 'firebase/auth';
import { doc, getDoc, setDoc, serverTimestamp } from 'firebase/firestore';
import { initSelectionListener } from '../layout/selection.svelte.js';
import { initEntriesListener } from '../stores/entriesStore.svelte.js';

let _initialized = false;

let user = $state(null);
let userProfile = $state(null);
let loading = $state(true);
let needsCountry = $state(false);

export function getUser() { return user; }
export function getUserProfile() { return userProfile; }
export function getLoading() { return loading; }
export function getNeedsCountry() { return needsCountry; }

export async function signInWithGoogle() {
  await signInWithPopup(auth, googleProvider);
}

export async function signOut() {
  await fbSignOut(auth);
  user = null;
  userProfile = null;
  needsCountry = false;
}

export async function setHomeCountry(name, code) {
  if (!user) return;
  await setDoc(doc(db, 'users', user.uid), {
    displayName: user.displayName,
    photoURL: user.photoURL,
    email: user.email,
    homeCountry: name,
    homeCountryCode: code,
    visitedCountries: [code],
    createdAt: serverTimestamp(),
  });
  userProfile = { ...userProfile, homeCountry: name, homeCountryCode: code, visitedCountries: [code] };
  needsCountry = false;
}

export function initAuth() {
  if (_initialized) return;
  _initialized = true;
  onAuthStateChanged(auth, async (fbUser) => {
    if (fbUser) {
      user = fbUser;
      initSelectionListener(fbUser.uid);
      initEntriesListener(fbUser.uid);
      const docRef = doc(db, 'users', fbUser.uid);
      const docSnap = await getDoc(docRef);
      if (docSnap.exists()) {
        userProfile = docSnap.data();
        needsCountry = false;
      } else {
        userProfile = {
          displayName: fbUser.displayName,
          photoURL: fbUser.photoURL,
          email: fbUser.email,
        };
        needsCountry = true;
      }
    } else {
      user = null;
      userProfile = null;
      needsCountry = false;
    }
    loading = false;
  });
}
