import { db } from '../firebase.js';
import { doc, onSnapshot, updateDoc, arrayUnion, arrayRemove } from 'firebase/firestore';

let selected = $state(new Set());
let totalCountries = $state(0);
let homeCountryCode = $state(null);
let _uid = null;
let _unsubscribe = null;

export function initSelectionListener(uid) {
  if (_unsubscribe) _unsubscribe();
  _uid = uid;
  const userRef = doc(db, 'users', uid);
  _unsubscribe = onSnapshot(userRef, (snap) => {
    if (snap.exists()) {
      const codes = snap.data().visitedCountries || [];
      selected = new Set(codes);
      homeCountryCode = snap.data().homeCountryCode || null;
    }
  });
}

export function toggle(id) {
  if (!_uid) return;
  const was = selected.has(id);
  const next = new Set(selected);
  if (was) {
    next.delete(id);
  } else {
    next.add(id);
  }
  selected = next;
  const userRef = doc(db, 'users', _uid);
  if (was) {
    updateDoc(userRef, { visitedCountries: arrayRemove(id) });
  } else {
    updateDoc(userRef, { visitedCountries: arrayUnion(id) });
  }
}

export function clearAll() {
  if (!_uid) return;
  selected = new Set();
  const userRef = doc(db, 'users', _uid);
  updateDoc(userRef, { visitedCountries: [] });
}

export function getSelected() {
  return selected;
}

export function setTotalCount(n) {
  totalCountries = n;
}

export function getTotalCount() {
  return totalCountries;
}

export function getHomeCountryCode() {
  return homeCountryCode;
}
