<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">{{ t('system.config.title') }}</h1>
      <p class="text-slate-400 mt-1">{{ t('system.config.subtitle') }}</p>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <div class="text-slate-400 flex items-center gap-3">
        <svg class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
        </svg>
        <span>{{ t('system.config.loading') }}</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="bg-rose-500/10 border border-rose-500/30 rounded-xl p-6 mb-8">
      <p class="text-rose-400">{{ t('system.config.error') }}</p>
      <button @click="fetchSettings" class="mt-3 text-sm text-rose-300 hover:text-rose-200 underline">
        {{ t('system.params.retry') }}
      </button>
    </div>

    <template v-else>
      <div class="space-y-6">
        <!-- Raw JSON Viewer -->
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-6">
          <h2 class="text-lg font-semibold text-white mb-4">{{ t('system.config.raw_json') }}</h2>
          <textarea
            v-model="rawJson"
            rows="8"
            class="w-full px-4 py-3 bg-slate-900 border border-slate-600 rounded-lg text-sm text-slate-300 font-mono focus:outline-none focus:ring-2 focus:ring-amber-500/50 focus:border-amber-500"
            :placeholder="t('system.config.raw_json')"
          ></textarea>
          <div class="mt-3 flex items-center gap-3">
            <button
              @click="applyRawJson"
              class="px-4 py-2 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded-lg text-sm font-medium transition"
            >
              {{ t('system.config.apply_json') }}
            </button>
            <span v-if="jsonError" class="text-sm text-rose-400">{{ t('system.config.invalid_json') }}{{ jsonError }}</span>
            <span v-if="jsonApplied" class="text-sm text-emerald-400">{{ t('system.config.json_applied') }}</span>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

const loading = ref(true)
const error = ref(false)
const rawJson = ref('')
const jsonError = ref<string | null>(null)
const jsonApplied = ref(false)

onMounted(() => {
  loading.value = false
})

function applyRawJson() {
  jsonError.value = null
  jsonApplied.value = false
  try {
    JSON.parse(rawJson.value) // Just validate JSON
    jsonApplied.value = true
    setTimeout(() => { jsonApplied.value = false }, 3000)
  } catch (err) {
    jsonError.value = (err as Error).message
  }
}
</script>
