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

<script setup>
import { useQuasar } from "quasar";
import { StatusBar, Style } 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";
  
const updateStatusBar = async (isDark) => {
  if (!Capacitor.isNativePlatform()) return;

  await StatusBar.show();
  await StatusBar.setStyle({
    style: isDark ? Style.Dark : Style.Light,
  });
};

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

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

onBeforeMount(async () => {
  const { value: themePref } = await Preferences.get({ key: "theme" });
  const theme = themePref || systemTheme;
  const isDark = theme === "dark";

  $q.dark.set(isDark);
  await updateStatusBar(isDark);

  const { value: localePref } = await Preferences.get({ key: "locale" });
  const userLocale = localePref || window.navigator.language;

  console.log(theme, userLocale);
});
</script>
