<template>
  <router-view />
</template>

<script setup>
import { useQuasar } from "quasar";
import { StatusBar } from "@capacitor/status-bar";
import { Capacitor } from "@capacitor/core";
import { watch, onBeforeMount } from "vue";
import { useI18n } from "vue-i18n";
import { Preferences } from "@capacitor/preferences";

defineOptions({
  name: "App",
});

const { locale } = useI18n();

const $q = useQuasar();
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
  ? "dark"
  : "light";

watch(
  () => $q.dark.isActive,
  async (value) => {
    await Preferences.set({ key: "theme", value: value });
  },
);

watch(
  () => locale.value,
  async (value) => {
    await Preferences.set({ key: "locale", value: value });
  },
);

onBeforeMount(async () => {
  const isNative = Capacitor.isNativePlatform();
  if (isNative) await StatusBar.show();
  const { value: themePref } = await Preferences.get({ key: "theme" });
  const theme = themePref || systemTheme;
  if (isNative) await StatusBar.setStyle({ style: theme.toUpperCase() });
  const { value: localePref } = await Preferences.get({ key: "locale" });
  const userLocale = localePref || window.navigator.language;
  console.log(theme, userLocale);
  $q.dark.set(theme == "dark");
});
</script>
