<template>
  <div class="p-4 max-w-4xl mx-auto">
    <h1 class="text-2xl font-bold text-blue mb-4">📅 Calendrier</h1>

    <!-- Onglets -->
    <div class="flex gap-1 mb-6 bg-bg-soft rounded-lg p-1 w-fit">
      <button v-for="tab in tabs" :key="tab.id" @click="activeTab = tab.id"
        :class="['px-4 py-2 rounded-md text-sm font-medium transition-colors',
          activeTab === tab.id ? 'bg-blue text-bg' : 'text-text-muted hover:text-text']">
        {{ tab.label }}
      </button>
    </div>

    <!-- Sélecteur mois (onglets lunaire/dictons) -->
    <div v-if="activeTab === 'lunaire' || activeTab === 'dictons'" class="flex items-center gap-3 mb-4">
      <button @click="prevMonth" class="text-text-muted hover:text-text text-lg">◀</button>
      <span class="text-text font-semibold">{{ monthLabel }}</span>
      <button @click="nextMonth" class="text-text-muted hover:text-text text-lg">▶</button>
    </div>

    <!-- === LUNAIRE === -->
    <div v-if="activeTab === 'lunaire'">
      <div v-if="loadingLunar" class="text-text-muted text-sm py-4">Calcul en cours (skyfield)...</div>
      <div v-else-if="errorLunar" class="bg-red/10 border border-red rounded-lg p-4 text-red text-sm">
        {{ errorLunar }}
      </div>
      <div v-else-if="!lunarDays.length" class="text-text-muted text-sm py-4">Aucune donnée lunaire.</div>
      <div v-else>
        <!-- Grille calendrier -->
        <div class="grid grid-cols-7 gap-1 mb-2">
          <div v-for="d in ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim']" :key="d"
            class="text-center text-text-muted text-xs py-1">{{ d }}</div>
        </div>
        <div class="grid grid-cols-7 gap-1">
          <div v-for="_ in firstDayOffset" :key="'empty-'+_" class="h-16"></div>
          <div v-for="day in lunarDays" :key="day.date"
            @click="selectedDay = day"
            :class="['h-16 bg-bg-soft rounded-lg p-1 cursor-pointer hover:border hover:border-blue transition-colors flex flex-col items-center justify-center gap-0.5',
              selectedDay?.date === day.date ? 'border border-blue' : 'border border-transparent']">
            <span class="text-text-muted text-xs">{{ new Date(day.date+'T12:00:00').getDate() }}</span>
            <img :src="moonIcon(day.illumination, day.croissante_decroissante)" class="w-6 h-6 opacity-90" alt="phase" />
            <span class="text-xs leading-none" :class="typeColor(day.type_jour)">{{ typeEmoji(day.type_jour) }}</span>
          </div>
        </div>

        <!-- Détail jour sélectionné -->
        <div v-if="selectedDay" class="mt-4 bg-bg-soft rounded-xl p-4 border border-bg-hard">
          <div class="flex items-center gap-3 mb-3">
            <img :src="moonIcon(selectedDay.illumination, selectedDay.croissante_decroissante)" class="w-10 h-10" alt="phase" />
            <div>
              <div class="text-text font-bold">{{ formatDate(selectedDay.date) }}</div>
              <div class="text-text-muted text-sm">{{ selectedDay.phase || 'Pas de phase particulière' }}</div>
            </div>
          </div>
          <div class="grid grid-cols-2 gap-2 text-sm">
            <div class="bg-bg rounded-lg p-2">
              <div class="text-text-muted text-xs mb-1">Illumination</div>
              <div class="text-text">{{ selectedDay.illumination }}%</div>
            </div>
            <div class="bg-bg rounded-lg p-2">
              <div class="text-text-muted text-xs mb-1">Tendance</div>
              <div class="text-text">{{ selectedDay.croissante_decroissante }}</div>
            </div>
            <div class="bg-bg rounded-lg p-2">
              <div class="text-text-muted text-xs mb-1">Lune</div>
              <div class="text-text">{{ selectedDay.montante_descendante }}</div>
            </div>
            <div class="bg-bg rounded-lg p-2">
              <div class="text-text-muted text-xs mb-1">Signe</div>
              <div class="text-text">{{ selectedDay.signe }}</div>
            </div>
            <div class="bg-bg rounded-lg p-2 col-span-2">
              <div class="text-text-muted text-xs mb-1">Type de jour</div>
              <div :class="['font-semibold', typeColor(selectedDay.type_jour)]">
                {{ typeEmoji(selectedDay.type_jour) }} {{ selectedDay.type_jour }}
              </div>
            </div>
          </div>
          <div v-if="selectedDay.perigee" class="mt-2 text-xs text-orange bg-orange/10 rounded px-2 py-1">⚡ Périgée (lune proche)</div>
          <div v-if="selectedDay.apogee" class="mt-2 text-xs text-blue bg-blue/10 rounded px-2 py-1">🌌 Apogée (lune éloignée)</div>
          <div v-if="selectedDay.noeud_lunaire" class="mt-2 text-xs text-yellow bg-yellow/10 rounded px-2 py-1">✦ Nœud lunaire</div>
        </div>
      </div>
    </div>

    <!-- === MÉTÉO === -->
    <div v-if="activeTab === 'meteo'">
      <div v-if="loadingMeteo" class="text-text-muted text-sm py-4">Chargement météo...</div>
      <div v-else-if="!meteoData.length" class="text-text-muted text-sm py-4">Données météo non disponibles.</div>
      <div v-else class="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div v-for="day in meteoData" :key="day.date"
          class="bg-bg-soft rounded-xl p-3 border border-bg-hard flex flex-col items-center gap-1">
          <div class="text-text-muted text-xs">{{ formatDate(day.date) }}</div>
          <img :src="weatherIcon(day.code)" class="w-10 h-10" :alt="day.label" />
          <div class="text-text text-xs font-medium text-center">{{ day.label }}</div>
          <div class="flex gap-2 text-xs mt-1">
            <span class="text-orange">↑{{ day.t_max?.toFixed(0) }}°</span>
            <span class="text-blue">↓{{ day.t_min?.toFixed(0) }}°</span>
          </div>
          <div v-if="day.pluie_mm > 0" class="text-xs text-blue">💧 {{ day.pluie_mm }}mm</div>
        </div>
      </div>
    </div>

    <!-- === TÂCHES === -->
    <div v-if="activeTab === 'taches'">
      <p class="text-text-muted text-sm py-4">Les tâches planifiées s'afficheront ici.</p>
    </div>

    <!-- === DICTONS === -->
    <div v-if="activeTab === 'dictons'">
      <div v-if="!dictons.length" class="text-text-muted text-sm py-4">Aucun dicton pour ce mois.</div>
      <div v-for="d in dictons" :key="d.id" class="bg-bg-soft rounded-lg p-4 mb-2 border border-bg-hard">
        <p class="text-text italic text-sm">"{{ d.texte }}"</p>
        <p v-if="d.region" class="text-text-muted text-xs mt-1">— {{ d.region }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { lunarApi, type LunarDay, type Dicton } from '@/api/lunar'
import { meteoApi, type MeteoDay } from '@/api/meteo'

const activeTab = ref('lunaire')
const tabs = [
  { id: 'lunaire', label: '🌙 Lunaire' },
  { id: 'meteo', label: '☀️ Météo' },
  { id: 'taches', label: '✅ Tâches' },
  { id: 'dictons', label: '📜 Dictons' },
]

const now = new Date()
const currentYear = ref(now.getFullYear())
const currentMonth = ref(now.getMonth() + 1)

const monthLabel = computed(() => {
  const d = new Date(currentYear.value, currentMonth.value - 1, 1)
  return d.toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })
})

const monthStr = computed(() => `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}`)

function prevMonth() {
  if (currentMonth.value === 1) { currentMonth.value = 12; currentYear.value-- }
  else currentMonth.value--
}
function nextMonth() {
  if (currentMonth.value === 12) { currentMonth.value = 1; currentYear.value++ }
  else currentMonth.value++
}

// Lunaire
const lunarDays = ref<LunarDay[]>([])
const loadingLunar = ref(false)
const errorLunar = ref('')
const selectedDay = ref<LunarDay | null>(null)

const firstDayOffset = computed(() => {
  if (!lunarDays.value.length) return 0
  const d = new Date(lunarDays.value[0].date + 'T12:00:00')
  return (d.getDay() + 6) % 7  // Lundi=0
})

async function loadLunar() {
  loadingLunar.value = true; errorLunar.value = ''; selectedDay.value = null
  try {
    lunarDays.value = await lunarApi.getMonth(monthStr.value)
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    errorLunar.value = err?.response?.data?.detail || 'Erreur lors du chargement du calendrier lunaire.'
  } finally {
    loadingLunar.value = false
  }
}

// Météo
const meteoData = ref<MeteoDay[]>([])
const loadingMeteo = ref(false)

async function loadMeteo() {
  loadingMeteo.value = true
  try {
    const res = await meteoApi.getForecast(14)
    meteoData.value = res.days || []
  } catch { meteoData.value = [] }
  finally { loadingMeteo.value = false }
}

// Dictons
const dictons = ref<Dicton[]>([])
async function loadDictons() {
  try { dictons.value = await lunarApi.getDictons(currentMonth.value) }
  catch { dictons.value = [] }
}

// Helpers affichage
function moonIcon(illum: number, tendance: string): string {
  const i = illum / 100
  let name: string
  if (i < 0.05) name = 'new_moon'
  else if (tendance === 'Croissante') {
    if (i < 0.35) name = 'waxing_crescent'
    else if (i < 0.65) name = 'first_quarter'
    else if (i < 0.95) name = 'waxing_gibbous'
    else name = 'full_moon'
  } else {
    if (i > 0.95) name = 'full_moon'
    else if (i > 0.65) name = 'waning_gibbous'
    else if (i > 0.35) name = 'last_quarter'
    else name = 'waning_crescent'
  }
  return `/icons/moon/${name}.svg`
}

function weatherIcon(code: number): string {
  // WMO code → fichier SVG disponible
  const available = [0, 1, 2, 3, 45, 48, 51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 71, 73, 75, 77, 80, 81, 82, 85, 86, 95, 96, 99]
  const closest = available.reduce((prev, curr) =>
    Math.abs(curr - code) < Math.abs(prev - code) ? curr : prev
  )
  return `/icons/weather/${closest}.svg`
}
function typeEmoji(type: string): string {
  return ({ Racine: '🌱', Feuille: '🌿', Fleur: '🌸', Fruit: '🍅' } as Record<string, string>)[type] || '●'
}
function typeColor(type: string): string {
  return ({ Racine: 'text-yellow', Feuille: 'text-green', Fleur: 'text-orange', Fruit: 'text-red' } as Record<string, string>)[type] || 'text-text-muted'
}
function formatDate(dateStr: string): string {
  return new Date(dateStr + 'T12:00:00').toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })
}

watch(monthStr, () => {
  if (activeTab.value === 'lunaire') loadLunar()
  if (activeTab.value === 'dictons') loadDictons()
})

watch(activeTab, (tab) => {
  if (tab === 'lunaire' && !lunarDays.value.length) loadLunar()
  if (tab === 'meteo' && !meteoData.value.length) loadMeteo()
  if (tab === 'dictons' && !dictons.value.length) loadDictons()
})

onMounted(() => { loadLunar(); loadMeteo() })
</script>
