<template>
  <main class="container">
    <h1>{{ t('nav.settings') }}</h1>
    <p>{{ t('settings.description') }}</p>

    <I18nStub />

    <ThemeToggle />

    <section class="card">
      <div style="display: grid; gap: 8px; margin-bottom: 12px;">
        <label for="timezone">{{ t('settings.timezone') }}</label>
        <input id="timezone" v-model="timezoneInput" placeholder="Europe/Paris" />
        <button class="card" type="button" @click="applyTimezone">
          {{ t('settings.applyTimezone') }}
        </button>
      </div>
      <label for="config">{{ t('settings.configJson') }}</label>
      <textarea
        id="config"
        v-model="configText"
        rows="14"
        style="width: 100%; margin-top: 8px; font-family: monospace;"
      />
      <div style="margin-top: 12px; display: flex; gap: 12px;">
        <button class="card" type="button" @click="reload">{{ t('actions.reload') }}</button>
        <button class="card" type="button" @click="save">{{ t('actions.save') }}</button>
      </div>
      <p v-if="message" style="margin-top: 8px;">{{ message }}</p>
    </section>
  </main>
</template>

<script setup lang="ts">
const { apiBase, getErrorMessage } = useApi()
const { t } = useI18n()

const configText = ref('')
const message = ref('')
const timezoneInput = ref('Europe/Paris')

const reload = async () => {
  message.value = ''
  try {
    const data = await $fetch(`${apiBase}/config`)
    configText.value = JSON.stringify(data, null, 2)
    timezoneInput.value = data?.timezone || 'Europe/Paris'
  } catch (err) {
    message.value = getErrorMessage(err, t('errors.load'))
  }
}

const save = async () => {
  message.value = ''
  try {
    const parsed = JSON.parse(configText.value)
    if (timezoneInput.value) {
      parsed.timezone = timezoneInput.value
    }
    const data = await $fetch(`${apiBase}/config`, {
      method: 'PUT',
      body: parsed
    })
    configText.value = JSON.stringify(data, null, 2)
    message.value = 'Configuration sauvegardee.'
  } catch (err) {
    message.value = getErrorMessage(err, t('messages.saveError'))
  }
}

const applyTimezone = () => {
  try {
    const parsed = JSON.parse(configText.value || '{}')
    parsed.timezone = timezoneInput.value || 'Europe/Paris'
    configText.value = JSON.stringify(parsed, null, 2)
  } catch (err) {
    message.value = getErrorMessage(err, t('errors.invalidJson'))
  }
}

onMounted(reload)
</script>
