<script lang="ts">
import { getDefaultSettings, syncUserSettings, setLanguage, themeList } from '@/settingsManager'

export default {
  setup() {
    let settings
    syncUserSettings()

    let storedSettings = localStorage.getItem('settings')
    if (storedSettings === null) {
      settings = getDefaultSettings()
    } else {
      settings = JSON.parse(storedSettings)
    }

    return {
      settings,
      themeList
    }
  },
  methods: {
    save() {
      const settings = JSON.stringify(this.settings)
      localStorage.setItem('settings', settings)
      setLanguage(this.settings.language.selected, this.$i18n)

      // Reload needed
      location.href = "/"
    }
    //     download() {
    //         var hiddenElement = document.createElement('a');

    //         hiddenElement.href = 'data:attachment/text,' + encodeURI(JSON.stringify(this.settings));
    //         hiddenElement.target = '_blank';
    //         hiddenElement.download = 'safetwitch_prefs.json';
    //         hiddenElement.click();
    //     },
    //     async handleImport(event: any) {
    //         const file = await event.target.files[0].text()
    //         const parsed = JSON.parse(file)

    //         if (parsed.audioOnly == undefined) {
    //             return
    //         }

    //         this.settings = file
    //         this.save()
    //     },
  }
}
</script>

<template>
  <div class="mx-auto w-[35rem] max-w-[95vw]  p-5 py-3 bg-secondary rounded-md text-contrast">
    <h1 class="font-bold text-3xl">{{ $t("nav.settings") }}</h1>
    <hr class="my-2" />
    <ul class="w-full space-y-1">
      <li v-for="setting in settings" :key="setting.type">
        <div v-if="setting.type == 'checkbox'" class="justify-between items-center flex">
          <label :for="setting.name">{{ $t(`settings.${setting.name}`)  }}</label>
          <input :name="setting.name" type="checkbox" v-model="setting.selected" />
        </div>

        <div v-else-if="setting.type == 'option'" class="justify-between items-center flex">
          <label :for="setting.name">{{ $t(`settings.${setting.name}`) }}</label>
          <select
            :name="setting.name"
            type="checkbox"
            v-model="setting.selected"
            class="text-black rounded-md h-8 p-0 pr-8 pl-2"
          >
            <option v-for="option of setting.options" :key="option" :value="option">
              {{ option }}
            </option>
          </select>
        </div>
      </li>
    </ul>

    <div class="space-x-2 mt-3">
      <button @click="save" class="bg-surface0 p-4 py-2 rounded-md">{{ $t('settings.saveButton') }}</button>
      <!-- <button @click="download" class="bg-surface0 p-4 py-2 rounded-md">Export</button>
            <input type="file" @change="handleImport" name="fileinput" ref="fileinput"
                class="bg-surface0 p-4 py-2 rounded-md"> -->
    </div>
  </div>
</template>
