<template>
  <main class="container">
    <h1>{{ t('nav.analyse') }}</h1>
    <p v-if="message">{{ message }}</p>

    <section class="card" style="margin-bottom: 16px;">
      <h2>{{ t('analyse.title') }}</h2>
      <div style="display: grid; gap: 8px;">
        <label>
          {{ t('analyse.type') }}
          <select v-model="type">
            <option value="auto">{{ t('analyse.auto') }}</option>
            <option value="lspci">lspci</option>
            <option value="lsusb">lsusb</option>
          </select>
        </label>
        <textarea
          v-model="texte"
          rows="10"
          :placeholder="t('analyse.placeholder')"
        />
        <button class="card" type="button" :disabled="loading" @click="runAnalyse">
          {{ loading ? t('form.saving') : t('analyse.run') }}
        </button>
      </div>
    </section>

    <section v-if="result" class="card">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h2>{{ t('analyse.result') }}</h2>
        <button class="card" type="button" @click="copyJson">{{ t('actions.copy') }}</button>
      </div>
      <p>{{ t('analyse.count') }}: {{ result.count }}</p>
      <pre>{{ formatted }}</pre>
    </section>
  </main>
</template>

<script setup lang="ts">
type AnalyseResponse = {
  type: string
  count: number
  devices: unknown[]
}

const { apiBase, getErrorMessage } = useApi()
const { t } = useI18n()

const type = ref("auto")
const texte = ref("")
const loading = ref(false)
const message = ref("")
const result = ref<AnalyseResponse | null>(null)

const formatted = computed(() => (result.value ? JSON.stringify(result.value, null, 2) : ""))

const runAnalyse = async () => {
  message.value = ""
  result.value = null
  if (!texte.value.trim()) {
    message.value = t("analyse.empty")
    return
  }
  loading.value = true
  try {
    const payload = {
      type: type.value === "auto" ? "" : type.value,
      texte: texte.value
    }
    result.value = await $fetch(`${apiBase}/analyse-hardware`, {
      method: "POST",
      body: payload
    })
  } catch (err) {
    message.value = getErrorMessage(err, t("messages.loadError"))
  } finally {
    loading.value = false
  }
}

const copyJson = async () => {
  if (!formatted.value) {
    return
  }
  try {
    await navigator.clipboard.writeText(formatted.value)
    message.value = t("messages.copied")
  } catch {
    message.value = t("errors.copy")
  }
}
</script>
