<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()
}

// ── « C'est moi » — un collectif importé (seed, fichier) n'a aucun isMe :
// on se désigne parmi les personnes existantes, ou on s'ajoute.
const newMeName = ref('')

function claimMe(personId: string) {
  const current = store.current
  if (!current || store.me) return
  const person = current.people.find(p => p.id === personId && !p.archivedAt)
  if (!person) return
  person.isMe = true
  store.stamp(person)
  store.persist()
}

function createMe() {
  const current = store.current
  const displayName = newMeName.value.trim()
  if (!current || store.me || !displayName) return
  const now = store.now()
  current.people.push({
    id: store.newId(),
    collectiveId: current.collective.id,
    createdAt: now,
    updatedAt: now,
    displayName,
    isMe: true,
  })
  newMeName.value = ''
  store.persist()
}
</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.current" class="data-card__empty">
      Aucun collectif actif — crée ou importe un collectif pour poser ton identité.
    </p>

    <template v-else-if="!store.me">
      <p class="data-card__text">
        Personne n'est encore désigné·e comme toi dans ce collectif —
        retrouve-toi dans la liste, ou ajoute-toi.
      </p>
      <div class="claim-chips">
        <button
          v-for="person in store.people"
          :key="person.id"
          type="button"
          class="claim-chip"
          @click="claimMe(person.id)"
        >
          <UIcon name="i-lucide-user-round-check" />
          <span>{{ person.displayName }}</span>
          <span class="claim-chip__me">c'est moi</span>
        </button>
      </div>
      <form class="claim-new" @submit.prevent="createMe">
        <input
          v-model="newMeName"
          class="field__input claim-new__input"
          type="text"
          placeholder="Ton prénom ici"
          autocomplete="off"
        >
        <button type="submit" class="ld-btn" :disabled="newMeName.trim().length === 0">
          <UIcon name="i-lucide-plus" /> Je m'ajoute
        </button>
      </form>
    </template>

    <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; }

/* « C'est moi » — désignation dans un collectif importé */
.claim-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.4rem;
}

.claim-chip {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  min-height: 2.25rem;
  padding: 0.35rem 0.8rem;
  border-radius: var(--r-pill);
  font-size: 0.875rem;
  font-weight: 600;
  background: var(--mood-input-bg);
  color: var(--mood-text);
  cursor: pointer;
  transition: background 0.1s ease, transform 0.1s ease;
}
.claim-chip:hover {
  background: var(--mood-accent-soft);
  transform: translateY(-1px);
}
.claim-chip:active { transform: translateY(0); }

.claim-chip__me {
  font-size: 0.75rem;
  font-weight: 700;
  color: var(--mood-accent);
}

.claim-new {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.claim-new__input { flex: 1; min-width: 0; }
</style>
