<template>
  <div class="p-4 max-w-3xl mx-auto">
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-bold text-green">📆 Planning</h1>
      <!-- Navigateur semaine -->
      <div class="flex items-center gap-3">
        <button @click="prevWeek" class="text-text-muted hover:text-text text-lg">◀</button>
        <span class="text-text text-sm font-medium">{{ weekLabel }}</span>
        <button @click="nextWeek" class="text-text-muted hover:text-text text-lg">▶</button>
        <button @click="goToday" class="text-xs text-green border border-green/30 rounded px-2 py-0.5 hover:bg-green/10">Auj.</button>
      </div>
    </div>

    <!-- Grille semaine -->
    <div class="grid grid-cols-7 gap-1 mb-2">
      <div v-for="d in weekDays" :key="d.iso"
        :class="['text-center text-xs py-1 rounded',
          d.isToday ? 'text-green font-bold' : 'text-text-muted']">
        <div>{{ d.dayShort }}</div>
        <div :class="['text-sm font-semibold mt-0.5', d.isToday ? 'bg-green text-bg rounded-full w-6 h-6 flex items-center justify-center mx-auto' : '']">
          {{ d.dayNum }}
        </div>
      </div>
    </div>

    <!-- Tâches par jour -->
    <div class="grid grid-cols-7 gap-1">
      <div v-for="d in weekDays" :key="d.iso"
        :class="['min-h-24 rounded-lg p-1 border transition-colors',
          d.isToday ? 'border-green/40 bg-green/5' : 'border-bg-hard bg-bg-soft']">
        <div v-for="t in tasksByDay[d.iso] || []" :key="t.id"
          :class="['text-xs rounded px-1 py-0.5 mb-0.5 cursor-pointer hover:opacity-80 truncate',
            priorityClass(t.priorite)]"
          :title="t.titre">
          {{ t.titre }}
        </div>
        <!-- Zone drop-cible (vide) -->
        <div v-if="!(tasksByDay[d.iso]?.length)" class="text-text-muted text-xs text-center pt-2 opacity-40">—</div>
      </div>
    </div>

    <!-- Tâches sans date -->
    <div class="mt-6">
      <h2 class="text-text-muted text-xs uppercase tracking-widest mb-2">Sans date</h2>
      <div v-if="!unscheduled.length" class="text-text-muted text-xs pl-2">Toutes les tâches ont une échéance.</div>
      <div v-for="t in unscheduled" :key="t.id"
        class="bg-bg-soft rounded-lg p-2 mb-1 border border-bg-hard flex items-center gap-2">
        <span :class="['text-xs w-2 h-2 rounded-full flex-shrink-0', dotClass(t.priorite)]"></span>
        <span class="text-text text-sm flex-1 truncate">{{ t.titre }}</span>
        <span :class="['text-xs px-1.5 py-0.5 rounded', statutClass(t.statut)]">{{ t.statut }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useTasksStore } from '@/stores/tasks'

const store = useTasksStore()

const today = new Date()
const weekStart = ref(getMonday(today))

function getMonday(d: Date) {
  const day = d.getDay()
  const diff = (day === 0 ? -6 : 1 - day)
  const m = new Date(d)
  m.setDate(d.getDate() + diff)
  m.setHours(0, 0, 0, 0)
  return m
}

function toIso(d: Date) {
  return d.toISOString().slice(0, 10)
}

const weekDays = computed(() => {
  const todayIso = toIso(today)
  return Array.from({ length: 7 }, (_, i) => {
    const d = new Date(weekStart.value)
    d.setDate(d.getDate() + i)
    return {
      iso: toIso(d),
      dayShort: d.toLocaleDateString('fr-FR', { weekday: 'short' }),
      dayNum: d.getDate(),
      isToday: toIso(d) === todayIso,
    }
  })
})

const weekLabel = computed(() => {
  const start = weekDays.value[0]
  const end = weekDays.value[6]
  const s = new Date(start.iso + 'T12:00:00')
  const e = new Date(end.iso + 'T12:00:00')
  return `${s.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })} – ${e.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}`
})

const tasksByDay = computed(() => {
  const map: Record<string, typeof store.tasks> = {}
  for (const t of store.tasks) {
    if (!t.echeance) continue
    const key = t.echeance.slice(0, 10)
    if (!map[key]) map[key] = []
    map[key].push(t)
  }
  return map
})

const unscheduled = computed(() => store.tasks.filter(t => !t.echeance && t.statut !== 'fait'))

function prevWeek() {
  const d = new Date(weekStart.value)
  d.setDate(d.getDate() - 7)
  weekStart.value = d
}
function nextWeek() {
  const d = new Date(weekStart.value)
  d.setDate(d.getDate() + 7)
  weekStart.value = d
}
function goToday() { weekStart.value = getMonday(today) }

const priorityClass = (p: string) => ({
  haute: 'bg-red/20 text-red',
  normale: 'bg-yellow/20 text-yellow',
  basse: 'bg-bg-hard text-text-muted',
}[p] || 'bg-bg-hard text-text-muted')

const dotClass = (p: string) => ({
  haute: 'bg-red', normale: 'bg-yellow', basse: 'bg-text-muted',
}[p] || 'bg-text-muted')

const statutClass = (s: string) => ({
  a_faire: 'bg-blue/20 text-blue', en_cours: 'bg-green/20 text-green',
  fait: 'bg-text-muted/20 text-text-muted',
}[s] || '')

onMounted(() => store.fetchAll())
</script>
