<template>
  <div class="p-6">
    <h2 class="kestrel-page-heading mb-4">
      Settings
    </h2>

    <section class="mb-8">
      <h3 class="kestrel-section-label">
        Map & offline
      </h3>
      <div class="kestrel-card p-4">
        <p class="mb-3 text-sm text-kestrel-text">
          Clear saved map tiles to free storage. The map will load tiles from the network again when you use it.
        </p>
        <p
          v-if="tilesStored !== null"
          class="mb-2 text-xs text-kestrel-muted"
        >
          {{ tilesStored > 0 ? `${tilesStored} tiles stored.` : 'No tiles stored.' }}
        </p>
        <p
          v-if="tilesMessage"
          class="mb-2 text-sm"
          :class="tilesMessageSuccess ? 'text-green-400' : 'text-red-400'"
        >
          {{ tilesMessage }}
        </p>
        <button
          type="button"
          class="kestrel-btn-secondary disabled:opacity-50"
          :disabled="tilesLoading"
          @click="onClearTiles"
        >
          {{ tilesLoading ? 'Clearing…' : 'Clear saved map tiles' }}
        </button>
      </div>
    </section>

    <section>
      <h3 class="kestrel-section-label">
        About
      </h3>
      <div class="kestrel-card p-4">
        <p class="font-medium text-kestrel-text">
          KestrelOS
        </p>
        <p
          v-if="version"
          class="mt-1 text-sm text-kestrel-muted"
        >
          Version {{ version }}
        </p>
        <p class="mt-2 text-xs text-kestrel-muted">
          Tactical Operations Center for OSINT feeds.
        </p>
      </div>
    </section>
  </div>
</template>

<script setup>
const config = useRuntimeConfig()
const version = config.public?.version ?? null

const tilesStored = ref(null)
const tilesMessage = ref('')
const tilesMessageSuccess = ref(false)
const tilesLoading = ref(false)

async function loadTilesStored() {
  if (typeof window === 'undefined') return
  try {
    const offline = await import('leaflet.offline')
    if (offline.getStorageLength) {
      const n = await offline.getStorageLength()
      tilesStored.value = n
    }
  }
  catch {
    tilesStored.value = null
  }
}

async function onClearTiles() {
  tilesMessage.value = ''
  tilesLoading.value = true
  try {
    const offline = await import('leaflet.offline')
    if (offline.truncate) {
      await offline.truncate()
      tilesStored.value = 0
      tilesMessage.value = 'Saved map tiles cleared.'
      tilesMessageSuccess.value = true
    }
    else {
      tilesMessage.value = 'Could not clear tiles.'
      tilesMessageSuccess.value = false
    }
  }
  catch (e) {
    tilesMessage.value = e?.message ?? 'Failed to clear tiles.'
    tilesMessageSuccess.value = false
  }
  finally {
    tilesLoading.value = false
  }
}

onMounted(() => {
  loadTilesStored()
})
</script>
