<template>
  <div>
    <div class="page-header">
      <h1>Site &amp; Facility</h1>
      <router-link to="/settings" class="btn btn-secondary">Back to Settings</router-link>
    </div>

    <div class="card">
      <div v-if="loading" class="muted">Loading...</div>
      <div v-else class="form-grid">
        <label v-for="s in items" :key="s.key" class="field">
          <span>{{ prettyLabel(s.key) }}</span>
          <input v-model="s.value" type="text" :placeholder="s.description" />
          <small class="muted">{{ s.description }}</small>
        </label>

        <div v-if="!items.length" class="muted">No site settings found.</div>

        <div class="actions">
          <button class="btn btn-primary" :disabled="saving || !items.length" @click="save">
            {{ saving ? 'Saving...' : 'Save' }}
          </button>
          <span v-if="saved" class="muted">Saved.</span>
          <span v-if="error" class="error">{{ error }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { settingsApi } from '@/api'
import { apiError } from '../../utils/apiError'

const items = ref([])
const loading = ref(true)
const saving = ref(false)
const saved = ref(false)
const error = ref('')

const LABELS = {
  site_base_url: 'Site URL / FQDN',
  facility_name: 'Facility Name',
  pc_access_domain: 'PC Access Domain'
}
function prettyLabel(key) {
  return LABELS[key] || key
}

async function load() {
  loading.value = true
  try {
    const response = await settingsApi.list()
    const all = response.data?.data || response.data || []
    items.value = all.filter(s => s.category === 'site')
  } catch (err) {
    console.error('Error loading site settings:', err)
    error.value = 'Could not load settings.'
  } finally {
    loading.value = false
  }
}

async function save() {
  saving.value = true
  saved.value = false
  error.value = ''
  try {
    for (const s of items.value) {
      await settingsApi.update(s.key, s.value)
    }
    saved.value = true
  } catch (err) {
    error.value = apiError(err, 'Save failed.')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>

<style scoped>
.form-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 640px;
}
.field {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.field > span {
  font-weight: 600;
}
.field input {
  padding: 8px 10px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg);
  color: var(--text);
}
.muted {
  color: var(--text-light);
  font-size: 0.85rem;
}
.error {
  color: var(--danger);
}
.actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}
</style>
