<script setup>
const { t } = useTranslation()
const wa = useWebAuthn()

const keys = ref([])
const hasPasswordStored = ref(false)
const loading = ref(false)
const supported = ref(false)
const alert = ref({ status: '', message: '', processing: false })

const newNickname = ref('')
const dialogOpen = ref(false)

const refresh = async () => {
  loading.value = true
  try {
    const res = await wa.listKeys()
    keys.value = res?.keys ?? []
    hasPasswordStored.value = !!res?.hasPasswordStored
  } catch (err) {
    keys.value = []
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  supported.value = wa.isSupported()
  if (supported.value) await refresh()
})

const openAdd = () => {
  newNickname.value = ''
  dialogOpen.value = true
}

const submitAdd = async () => {
  const name = newNickname.value.trim()
  if (!name) return
  alert.value = { status: '', message: '', processing: true }
  try {
    await wa.register(name)
    alert.value = { status: '', message: t.value.security_key_added || 'Security key registered', processing: false }
    dialogOpen.value = false
    await refresh()
  } catch (err) {
    const msg = err?.data?.statusMessage || err?.message || (t.value.security_key_error || 'Failed to register key')
    alert.value = { status: 400, message: msg, processing: false }
  }
}

const removeKey = async (credentialId) => {
  if (!window.confirm(t.value.confirm_delete_security_key || 'Delete this security key?')) return
  alert.value = { status: '', message: '', processing: true }
  try {
    await wa.deleteKey(credentialId)
    alert.value = { status: '', message: t.value.security_key_deleted || 'Security key deleted', processing: false }
    await refresh()
  } catch (err) {
    const msg = err?.data?.statusMessage || err?.message || (t.value.security_key_error || 'Failed to delete key')
    alert.value = { status: 400, message: msg, processing: false }
  }
}

const formatDate = (ts) => {
  if (!ts) return ''
  try { return new Date(ts).toLocaleString() } catch { return '' }
}
</script>

<template>
  <div class="security-keys-panel">
    <div class="panel-header">
      <div>
        <h3 class="panel-title">
          <img src="/assets/yubico.svg" alt="" class="title-icon" />
          {{ t.security_keys || 'Security Keys' }}
        </h3>
        <p class="panel-sub">{{ t.security_keys_intro || 'Register a YubiKey or other security key to sign in without typing your password.' }}</p>
      </div>
      <button v-if="supported" class="button is-primary is-small" @click="openAdd" :disabled="alert.processing">
        <i class="i-mdi-plus" /> {{ t.add_security_key || 'Add a security key' }}
      </button>
    </div>

    <PasskeyExplanation variant="inline" class="explainer-block" />

    <AlertBox :alert="alert" />
    <p v-if="alert.message && (!alert.status || Number(alert.status) < 400)" class="success-msg">{{ alert.message }}</p>

    <p v-if="!supported" class="not-supported">{{ t.security_key_not_supported || 'Your browser or device does not support security keys.' }}</p>

    <div v-else>
      <p v-if="loading" class="muted">{{ t.loading || 'Loading…' }}</p>
      <p v-else-if="!keys.length" class="muted">{{ t.no_security_keys || 'No security keys registered yet.' }}</p>
      <table v-else class="table is-fullwidth is-striped">
        <thead>
          <tr>
            <th>{{ t.security_key_name || 'Name' }}</th>
            <th>{{ t.added || 'Added' }}</th>
            <th>{{ t.transports || 'Connection' }}</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="k in keys" :key="k.credentialId">
            <td>{{ k.nickname }}</td>
            <td>{{ formatDate(k.createdAt) }}</td>
            <td>{{ (k.transports || []).join(', ') || '—' }}</td>
            <td class="has-text-right">
              <button class="button is-small is-danger is-light" @click="removeKey(k.credentialId)" :disabled="alert.processing">
                <i class="i-mdi-trash-can-outline" /> {{ t.delete || 'Delete' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div v-if="dialogOpen" class="modal is-active">
      <div class="modal-background" @click="dialogOpen = false" />
      <div class="modal-card">
        <header class="modal-card-head">
          <p class="modal-card-title">{{ t.add_security_key || 'Add a security key' }}</p>
          <button class="delete" aria-label="close" @click="dialogOpen = false" />
        </header>
        <section class="modal-card-body">
          <div class="field">
            <label class="label">{{ t.security_key_name || 'Name' }}</label>
            <div class="control">
              <input class="input" type="text" v-model="newNickname" maxlength="64" :placeholder="t.security_key_name_placeholder || 'e.g. Office YubiKey'" autofocus />
            </div>
            <p class="help">{{ t.security_key_name_help || 'Used to recognize the key in the list. You can change it by deleting and re-registering.' }}</p>
          </div>
          <p class="touch-hint">{{ t.touch_key_hint || 'When you click Continue, your browser will ask you to touch the key (USB) or tap it on the back of the phone (NFC).' }}</p>
        </section>
        <footer class="modal-card-foot">
          <button class="button is-primary" :disabled="!newNickname.trim() || alert.processing" @click="submitAdd">
            {{ alert.processing ? (t.processing || 'Processing…') : (t.continue_btn || 'Continue') }}
          </button>
          <button class="button" @click="dialogOpen = false">{{ t.cancel || 'Cancel' }}</button>
        </footer>
      </div>
    </div>
  </div>
</template>

<style scoped>
.security-keys-panel {
  padding: 1rem;
  background: var(--theme-bg-primary, #fff);
  border: 1px solid var(--theme-border, #e5e7eb);
  border-radius: 12px;
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
  margin-bottom: 1rem;
}
.panel-title {
  margin: 0 0 0.25rem;
  font-size: 1.1rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}
.title-icon { width: 20px; height: 20px; display: block; }
.panel-sub {
  margin: 0;
  font-size: 0.85rem;
  color: var(--theme-text-secondary, #6b7280);
}
.explainer-block {
  margin-bottom: 1rem;
  background: var(--theme-bg-secondary, #f9fafb);
}
.muted { color: var(--theme-text-secondary, #6b7280); font-size: 0.9rem; }
.not-supported {
  color: var(--theme-text-secondary, #6b7280);
  font-size: 0.9rem;
  padding: 0.75rem;
  background: var(--theme-bg-secondary, #f3f4f6);
  border-radius: 6px;
}
.success-msg {
  color: #059669;
  font-size: 0.85rem;
  margin: 0 0 0.5rem;
}
.touch-hint {
  margin-top: 0.5rem;
  padding: 0.6rem 0.75rem;
  background: var(--theme-bg-secondary, #f3f4f6);
  border-radius: 8px;
  font-size: 0.85rem;
  color: var(--theme-text-secondary, #6b7280);
}
</style>
