<script setup>
import { inject, computed, ref } from 'vue'
import { localDateStr, startOfWeek, jobSpansDate, techDaySchedule, techDayCapacityH, fmtDur, expandRRule } from 'src/composables/useHelpers'
import { ABSENCE_REASONS } from 'src/composables/useTechManagement'

const props = defineProps({
  anchorDate: Date,
  filteredResources: Array,
  todayStr: String,
  selectedTechId: { type: String, default: null },
})

const emit = defineEmits(['go-to-day', 'select-tech', 'open-schedule'])

const TECH_COLORS = inject('TECH_COLORS')
const planningMode = inject('planningMode', ref(false))

function isDayToday (d) { return localDateStr(d) === props.todayStr }

const monthWeeks = computed(() => {
  const first = new Date(props.anchorDate.getFullYear(), props.anchorDate.getMonth(), 1)
  const last  = new Date(props.anchorDate.getFullYear(), props.anchorDate.getMonth() + 1, 0)
  const start = startOfWeek(first)
  const end   = new Date(last)
  const dow   = end.getDay()
  if (dow !== 0) end.setDate(end.getDate() + (7 - dow))
  const weeks = []; let cur = new Date(start)
  while (cur <= end) {
    const week = []
    for (let i = 0; i < 7; i++) { week.push(new Date(cur)); cur.setDate(cur.getDate() + 1) }
    weeks.push(week)
  }
  return weeks
})

function techsActiveOnDay (dateStr) {
  return props.filteredResources.filter(tech =>
    tech.queue.some(j => jobSpansDate(j, dateStr, tech)) ||
    (tech.assistJobs || []).some(j => jobSpansDate(j, dateStr, tech) && j.assistants.find(a => a.techId === tech.id)?.pinned)
  )
}

function dayJobCount (dateStr) {
  const jobIds = new Set()
  props.filteredResources.forEach(t => t.queue.filter(j => jobSpansDate(j, dateStr, t)).forEach(j => jobIds.add(j.id)))
  return jobIds.size
}

function isTechAvailableOnDay (tech, dateStr) {
  // Explicit absence
  if (tech.status === 'off' && tech.absenceFrom) {
    const from = tech.absenceFrom
    const until = tech.absenceUntil || from
    if (dateStr >= from && dateStr <= until) return false
  }
  // Schedule off-day
  if (!techDaySchedule(tech, dateStr)) return false
  return true
}

// ── Selected tech availability for planning mode ────────────────────────────
const selectedTech = computed(() => props.selectedTechId ? props.filteredResources.find(t => t.id === props.selectedTechId) : null)

function selectedTechDayInfo (dateStr) {
  const tech = selectedTech.value
  if (!tech) return null
  // Absence check
  const isExplicitAbsent = tech.status === 'off' && tech.absenceFrom && dateStr >= tech.absenceFrom && dateStr <= (tech.absenceUntil || tech.absenceFrom)
  const sched = techDaySchedule(tech, dateStr)
  const isScheduleOff = !sched

  if (isExplicitAbsent) {
    const r = ABSENCE_REASONS.find(x => x.value === tech.absenceReason)
    return { type: 'absence', label: r ? r.label : 'Absent', icon: r ? r.icon : '⏸', color: 'var(--sb-sched-absence, #ef444466)' }
  }
  if (isScheduleOff) {
    return { type: 'dayoff', label: 'Repos', icon: '📅', color: 'var(--sb-sched-dayoff, #6b728044)' }
  }
  // On-call / extra shifts
  const extras = (tech.extraShifts || []).filter(s => {
    if (!s.rrule || !s.startTime || !s.endTime) return false
    const dates = expandRRule(s.rrule, s.from || dateStr, dateStr, dateStr, [])
    return dates.includes(dateStr)
  })
  if (extras.length) {
    const ex = extras[0]
    return { type: 'oncall', label: `${ex.label || 'Garde'} ${ex.startTime}–${ex.endTime}`, icon: '🔔', color: 'var(--sb-sched-oncall, #f59e0b44)' }
  }
  // Available
  return { type: 'available', label: `${sched.start} – ${sched.end}`, icon: '✓', color: 'var(--sb-sched-avail, #4ade8033)' }
}

function daySummary (dateStr) {
  let present = 0, absent = 0, loadH = 0, capH = 0
  props.filteredResources.forEach(tech => {
    if (isTechAvailableOnDay(tech, dateStr)) {
      present++
      capH += techDayCapacityH(tech, dateStr)
      loadH += tech.queue.filter(j => jobSpansDate(j, dateStr, tech)).reduce((s, j) => s + (parseFloat(j.duration) || 0), 0)
    } else {
      absent++
    }
  })
  return { present, absent, loadH, capH }
}
</script>

<template>
<div class="sb-month-wrap">
  <div class="sb-month-dow-hdr">
    <div v-for="wd in ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim']" :key="wd" class="sb-month-dow">{{ wd }}</div>
  </div>
  <div v-for="(week, wi) in monthWeeks" :key="wi" class="sb-month-week">
    <div v-for="day in week" :key="localDateStr(day)"
         class="sb-month-day"
         :class="{ 'sb-month-day-out': day.getMonth() !== anchorDate.getMonth(), 'sb-month-day-today': isDayToday(day) }"
         @click="emit('go-to-day', day)">
      <div class="sb-month-day-num">{{ day.getDate() }}</div>
      <!-- Planning mode: selected tech availability -->
      <div v-if="planningMode && selectedTech && selectedTechDayInfo(localDateStr(day))"
           class="sb-month-avail" :class="'sb-month-avail-' + selectedTechDayInfo(localDateStr(day)).type"
           :style="'background:' + selectedTechDayInfo(localDateStr(day)).color"
           @click.stop="emit('open-schedule', selectedTech)"
           :title="selectedTech.fullName + ': ' + selectedTechDayInfo(localDateStr(day)).label + ' — cliquer pour modifier'">
        <span class="sb-month-avail-icon">{{ selectedTechDayInfo(localDateStr(day)).icon }}</span>
        <span class="sb-month-avail-label">{{ selectedTechDayInfo(localDateStr(day)).label }}</span>
      </div>
      <div class="sb-month-stats">
        <span class="sb-month-stat sb-month-stat-present" :title="daySummary(localDateStr(day)).present + ' tech(s) disponible(s)'">
          👷 {{ daySummary(localDateStr(day)).present }}
        </span>
        <span v-if="daySummary(localDateStr(day)).absent" class="sb-month-stat sb-month-stat-absent" :title="daySummary(localDateStr(day)).absent + ' tech(s) absent(s)'">
          ⏸ {{ daySummary(localDateStr(day)).absent }}
        </span>
      </div>
      <div class="sb-month-avatars">
        <div v-for="tech in techsActiveOnDay(localDateStr(day))" :key="tech.id"
             class="sb-month-avatar" :style="'background:'+TECH_COLORS[tech.colorIdx]"
             :title="tech.fullName + ' — ' + tech.queue.filter(j=>jobSpansDate(j,localDateStr(day),tech)).length + ' job(s)'"
             @click.stop="emit('select-tech', tech)">
          {{ tech.fullName.split(' ').map(n=>n[0]).join('').toUpperCase().slice(0,2) }}
        </div>
      </div>
      <div v-if="daySummary(localDateStr(day)).capH" class="sb-month-hours">
        {{ fmtDur(daySummary(localDateStr(day)).loadH) }}/{{ fmtDur(daySummary(localDateStr(day)).capH) }}
      </div>
      <div v-if="dayJobCount(localDateStr(day))" class="sb-month-job-count">
        {{ dayJobCount(localDateStr(day)) }} job{{ dayJobCount(localDateStr(day))>1?'s':'' }}
      </div>
    </div>
  </div>
</div>
</template>
