<script setup lang="ts">
/**
 * /donnees §4 — mon identité locale : prénom (stamp + persist) et mes
 * attributs déclarés (clés/valeurs libres — nourrissent la carte « Pour moi »).
 */
import { useCollectiveStore } from '~/stores/collective'
import { ATTRIBUTES_HINT } from '~/lexicon'

const store = useCollectiveStore()

interface AttrRow {
  key: string
  value: number
}

const nameDraft = ref('')
const rows = ref<AttrRow[]>([])

// Re-seed the drafts only when the person changes (collective switch),
// never on our own commits — an in-progress empty row must survive.
watch(
  () => store.me?.id,
  () => {
    const me = store.me
    nameDraft.value = me?.displayName ?? ''
    rows.value = Object.entries(me?.attributes ?? {}).map(([key, value]) => ({ key, value }))
  },
  { immediate: true },
)

function commitName() {
  const me = store.me
  if (!me) return
  const value = nameDraft.value.trim()
  if (!value || value === me.displayName) {
    nameDraft.value = me.displayName
    return
  }
  me.displayName = value
  store.stamp(me)
  store.persist()
}

function commitAttributes() {
  const me = store.me
  if (!me) return
  const attributes: Record<string, number> = {}
  for (const row of rows.value) {
    const key = row.key.trim()
    if (!key) continue
    attributes[key] = Number.isFinite(row.value) ? row.value : 0
  }
  me.attributes = attributes
  store.stamp(me)
  store.persist()
}

function addRow() {
  rows.value.push({ key: '', value: 0 })
}

function removeRow(index: number) {
  rows.value.splice(index, 1)
  commitAttributes()
}
</script>

<template>
  <!-- ld-v2 -->
  <section class="ld-card data-card">
    <h2 class="data-card__title">
      <UIcon name="i-lucide-user-round" /> Mon identité
    </h2>

    <p v-if="!store.me" class="data-card__empty">
      Aucun collectif actif — crée ou importe un collectif pour poser ton identité.
    </p>

    <template v-else>
      <label class="field">
        <span class="field__label">Comment tu t'appelles ici</span>
        <input
          v-model="nameDraft"
          class="field__input"
          type="text"
          autocomplete="off"
          @change="commitName"
          @keydown.enter.prevent="commitName"
        >
      </label>

      <div class="field">
        <span class="field__label">Mes attributs</span>
        <p class="field__hint">{{ ATTRIBUTES_HINT }}</p>

        <ul v-if="rows.length" class="attr-list">
          <li v-for="(row, i) in rows" :key="i" class="attr-row">
            <input
              v-model="row.key"
              class="field__input attr-row__key"
              type="text"
              placeholder="heures/mois"
              autocomplete="off"
              @change="commitAttributes"
            >
            <input
              v-model.number="row.value"
              class="field__input attr-row__value"
              type="number"
              step="any"
              @change="commitAttributes"
            >
            <button
              type="button"
              class="attr-row__x"
              :aria-label="`Retirer l'attribut ${row.key || i + 1}`"
              @click="removeRow(i)"
            >
              <UIcon name="i-lucide-x" />
            </button>
          </li>
        </ul>

        <button type="button" class="ld-btn ld-btn--ghost attr-add" @click="addRow">
          <UIcon name="i-lucide-plus" /> Ajouter un attribut
        </button>
      </div>
    </template>
  </section>
</template>

<style scoped>
.data-card {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: clamp(1rem, 3vw, 1.5rem);
}

.data-card__title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0;
  font-size: 1.0625rem;
  font-weight: 800;
  color: var(--mood-text);
}

.data-card__empty {
  margin: 0;
  font-size: 0.9375rem;
  color: var(--mood-text-muted);
}

.field {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.field__label {
  font-size: 0.8125rem;
  font-weight: 700;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  color: var(--mood-text-muted);
}

.field__hint {
  margin: 0;
  font-size: 0.8125rem;
  font-style: italic;
  color: var(--mood-text-muted);
}

.field__input {
  min-height: 2.25rem;
  padding: 0.45rem 0.8rem;
  font-size: 0.9375rem;
  font-weight: 600;
  box-shadow: inset 0 0 0 1.5px var(--mood-input-border);
  border-radius: var(--r-input);
}
.field__input:focus-visible {
  box-shadow: inset 0 0 0 1.5px var(--mood-input-focus), 0 0 0 2.5px var(--mood-accent-soft);
}

.attr-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin: 0;
  padding: 0;
  list-style: none;
}

.attr-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.attr-row__key { flex: 1; min-width: 0; }
.attr-row__value { width: 6.5rem; flex-shrink: 0; }

.attr-row__x {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2.25rem;
  height: 2.25rem;
  flex-shrink: 0;
  border-radius: 50%;
  cursor: pointer;
  background: none;
  color: var(--mood-text-muted);
  transition: background 0.1s ease, color 0.1s ease;
}
.attr-row__x:hover {
  background: var(--mood-accent-soft);
  color: var(--mood-error);
}

.attr-add { align-self: flex-start; }
</style>
