<script setup>
import { computed } from "vue";
import strings from "../strings.js";
import { daysInMonthYm } from "../composables/useHourWeekNavigate.js";

const props = defineProps({
  monthFirstIso: { type: String, required: true },
  /** @type {{ [date:string]: number } | Record<string, number>} */
  hoursByDate: {
    /** @type {import('vue').PropType<Record<string, number>>} */
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["pick-day"]);

const dim = computed(() => daysInMonthYm(props.monthFirstIso));

/** Monday column offset for CSS grid starting Sunday in header */
const weekdayHeader = computed(() => ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]);

const cells = computed(() => {
  const [y, m] = props.monthFirstIso.split("-").map(Number);
  const first = new Date(y, m - 1, 1, 12, 0, 0);
  /** JavaScript weekday Sunday=0 … map to Su-first grid */
  const leading = first.getDay();
  const totalSlots = Math.ceil((leading + dim.value) / 7) * 7;

  /** @type {Array<{ iso: string | null; inMonth: boolean; hours: number }>} */
  const grid = [];

  for (let i = 0; i < totalSlots; i++) {
    const dayNum = i - leading + 1;
    if (dayNum < 1 || dayNum > dim.value) {
      grid.push({ iso: null, inMonth: false, hours: 0 });

      continue;
    }

    const iso = `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(dayNum).padStart(2, "0")}`;
    grid.push({
      iso,
      inMonth: true,
      hours: props.hoursByDate[iso] ?? 0,
    });
  }

  return grid;
});
</script>

<template>
  <div class="surface-card border-round-xl border border-surface-200 dark:border-surface-700 p-4">
    <div class="grid grid-cols-7 gap-1 text-center">
      <div v-for="h in weekdayHeader" :key="'wh-' + h" class="text-xs font-semibold text-muted-color py-2">{{ h }}</div>
      <button
        v-for="(cell, ix) in cells"
        :key="'c-' + ix"
        type="button"
        :disabled="!cell.inMonth"
        class="min-h-[3.75rem] border border-transparent rounded-lg p-1 text-sm transition-colors"
        :class="cell.inMonth ? 'hover:bg-primary-50 dark:hover:bg-primary-950/40 cursor-pointer' : 'opacity-35 cursor-default'"
        @click="cell.iso && emit('pick-day', cell.iso)"
      >
        <template v-if="cell.inMonth && cell.iso">
          <div class="font-semibold">{{ cell.iso.slice(8, 10) }}</div>
          <div class="text-xs text-primary">{{ cell.hours || "—" }} h</div>
        </template>
      </button>
    </div>
    <p class="text-xs text-muted-color mt-3 m-0">
      Totals reflect saved draft hours across all statuses (not invoicing summaries).
    </p>
  </div>
</template>
