<script setup lang="ts">
// Mini-editor of a « Réglage collectif »: up to 7 named sliders
// {label, min, max, step, unit, baseline}, plus the 100 % split option with
// its ONE named derived share (« calculé » — resolved, never voted).
import type { ParamDef, ParamSpec } from '~/types/domain'

const props = defineProps<{ modelValue?: ParamSpec }>()
const emit = defineEmits<{ (e: 'update:modelValue', spec: ParamSpec): void }>()

interface Row {
  label: string
  min: number
  max: number
  step: number
  unit: string
  baseline: number | null
}

const blankRow = (): Row => ({ label: '', min: 0, max: 100, step: 1, unit: '', baseline: null })

const rows = ref<Row[]>(
  props.modelValue
    ? props.modelValue.params
        .filter(p => !p.derived)
        .map(p => ({
          label: p.label,
          min: p.min,
          max: p.max,
          step: p.step,
          unit: p.unit ?? '',
          baseline: p.baseline ?? null,
        }))
    : [blankRow()],
)
const sum100 = ref(props.modelValue?.constraint === 'sum100')
const derivedName = ref(
  props.modelValue?.params.find(p => p.derived)?.label ?? 'Réserve (calculé)',
)

const maxRows = computed(() => (sum100.value ? 6 : 7))
const derivedBaseline = computed(() =>
  Math.max(0, 100 - rows.value.reduce((sum, r) => sum + (r.baseline ?? 0), 0)),
)

function build(): ParamSpec {
  const params: ParamDef[] = rows.value.map((row, i) => ({
    key: `p${i + 1}`,
    label: row.label.trim() || `Curseur ${i + 1}`,
    kind: sum100.value ? 'share' : 'slider',
    min: sum100.value ? 0 : row.min,
    max: sum100.value ? 100 : row.max,
    step: row.step > 0 ? row.step : 1,
    ...(sum100.value ? { unit: '%' } : row.unit.trim() ? { unit: row.unit.trim() } : {}),
    ...(row.baseline !== null ? { baseline: row.baseline } : {}),
  }))
  if (sum100.value) {
    params.push({
      key: 'derived',
      label: derivedName.value.trim() || 'Réserve (calculé)',
      kind: 'share',
      min: 0,
      max: 100,
      step: 1,
      unit: '%',
      baseline: derivedBaseline.value,
      derived: true,
    })
  }
  return { params, constraint: sum100.value ? 'sum100' : 'none' }
}

function sync() {
  emit('update:modelValue', build())
}

function addRow() {
  if (rows.value.length >= maxRows.value) return
  rows.value.push(blankRow())
  sync()
}

function removeRow(index: number) {
  rows.value.splice(index, 1)
  if (rows.value.length === 0) rows.value.push(blankRow())
  sync()
}

onMounted(sync)
</script>

<template>
  <!-- ld-v2 -->
  <div class="pe">
    <div v-for="(row, i) in rows" :key="i" class="pe__row">
      <input
        v-model="row.label"
        class="pe__label"
        type="text"
        :placeholder="`Curseur ${i + 1} — libellé métier`"
        @input="sync"
      >
      <div class="pe__nums">
        <template v-if="!sum100">
          <label class="pe__num"><span>min</span>
            <input v-model.number="row.min" type="number" @input="sync">
          </label>
          <label class="pe__num"><span>max</span>
            <input v-model.number="row.max" type="number" @input="sync">
          </label>
          <label class="pe__num"><span>pas</span>
            <input v-model.number="row.step" type="number" min="0" @input="sync">
          </label>
          <label class="pe__num"><span>unité</span>
            <input v-model="row.unit" type="text" placeholder="€, h…" @input="sync">
          </label>
        </template>
        <label class="pe__num"><span>aujourd'hui</span>
          <input v-model.number="row.baseline" type="number" @input="sync">
        </label>
        <button
          v-if="rows.length > 1"
          class="pe__remove"
          type="button"
          aria-label="Retirer ce curseur"
          @click="removeRow(i)"
        >
          <UIcon name="i-lucide-x" />
        </button>
      </div>
    </div>

    <button v-if="rows.length < maxRows" class="ld-btn ld-btn--quiet pe__add" type="button" @click="addRow">
      <UIcon name="i-lucide-plus" /> Ajouter un curseur
    </button>

    <label class="pe__sum">
      <input v-model="sum100" type="checkbox" @change="sync">
      <span>Répartition 100 % — une part est calculée, jamais votée</span>
    </label>
    <div v-if="sum100" class="pe__derived">
      <input v-model="derivedName" class="pe__label" type="text" @input="sync">
      <span class="pe__derived-value">calculé — {{ derivedBaseline }} % aujourd'hui</span>
    </div>
  </div>
</template>

<style scoped>
.pe { display: flex; flex-direction: column; gap: 0.625rem; }
.pe__row {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
  padding: 0.625rem;
  border-radius: var(--r-input);
  background: color-mix(in srgb, var(--mood-accent) 5%, transparent);
}
.pe__label { padding: 0.5rem 0.75rem; font-size: 0.9375rem; font-weight: 600; width: 100%; }
.pe__nums { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 0.5rem; }
.pe__num { display: flex; flex-direction: column; gap: 2px; }
.pe__num span {
  font-size: 0.6875rem;
  font-weight: 700;
  color: var(--mood-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.04em;
}
.pe__num input { width: 5.25rem; padding: 0.375rem 0.5rem; font-size: 0.875rem; }
.pe__remove {
  background: none;
  color: var(--mood-text-muted);
  cursor: pointer;
  padding: 0.375rem;
  border-radius: var(--r-input);
  min-height: 2.25rem;
}
.pe__remove:hover { color: var(--mood-error); background: var(--mood-accent-soft); }
.pe__add { align-self: flex-start; font-size: 0.875rem; }
.pe__sum {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
}
.pe__sum input { accent-color: var(--mood-accent); width: 1rem; height: 1rem; }
.pe__derived { display: flex; align-items: center; gap: 0.625rem; flex-wrap: wrap; }
.pe__derived .pe__label { max-width: 16rem; }
.pe__derived-value {
  font-size: 0.8125rem;
  font-style: italic;
  color: var(--mood-text-muted);
}
</style>
