import { journals } from '../stores/entriesStore.svelte.js';
import { nameToId } from '../shared/countries.js';
import { getUserProfile } from '../auth/userStore.svelte.js';

let selected = $state(new Set());
let totalCountries = $state(0);
let flashing = $state(new Set());

journals.subscribe((entries) => {
  const ids = new Set();
  for (const e of entries) {
    const id = nameToId[e.location?.country];
    if (id) ids.add(id);
  }
  const profile = getUserProfile();
  if (profile?.homeCountry) {
    const homeId = nameToId[profile.homeCountry];
    if (homeId) ids.add(homeId);
  }
  selected = ids;
});

export function getSelected() {
  return selected;
}

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

export function getTotalCount() {
  return totalCountries;
}

export function getFlashing() {
  return flashing;
}

export function flashCountry(countryName) {
  const id = nameToId[countryName];
  if (!id) return;
  flashing = new Set([...flashing, id]);
  setTimeout(() => {
    flashing = new Set([...flashing].filter(x => x !== id));
  }, 1600);
}
