<script setup>
import { computed } from "vue";
import { WEEKDAYS } from "../composables/useHoursApi.js";
import { addCalendarDaysIso, isoWeekNumber } from "../composables/useHourWeekNavigate.js";
import strings from "../strings.js";

const props = defineProps({
  lines: {
    /** @type {import('vue').PropType<Array<Record<string, unknown>>>} */
    type: Array,
    required: true,
  },
  weekMondayIso: { type: String, required: true },
  selectedIsoDate: { type: String, required: true },
});

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

/** @typedef {{ key: typeof WEEKDAYS[number], iso: string, label: string, total: number }} DayChip */

/** @returns {typeof WEEKDAYS} */
function weekdayLetters() {
  return ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
}

const dayChips = computed(() => {
  /** @type {DayChip[]} */
  const out = WEEKDAYS.map((k, ix) => {
    const iso = addCalendarDaysIso(props.weekMondayIso, ix);

    /** @type {number} */
    let total = 0;
    for (const ln of props.lines ?? []) {
      const dmap = ln?.durations ?? {};
      const v = typeof dmap[k] === "number" ? dmap[k] : Number(dmap[k]) || 0;
      total += v;
    }

    return {
      key: k,
      iso,
      label: weekdayLetters()[ix],
      total: Math.round(total * 100) / 100,
    };
  });

  return out;
});

const weekGrandTotal = computed(
  () =>
    Math.round(dayChips.value.reduce((s, c) => s + c.total, 0) * 100) / 100,
);

const weekNo = computed(() => isoWeekNumber(props.weekMondayIso));
</script>

<template>
  <div class="flex flex-wrap gap-2 items-stretch">
    <div
      class="min-w-[5.25rem] flex flex-col justify-center px-3 py-2 rounded-lg border border-surface-200 dark:border-surface-700 bg-surface-50 dark:bg-surface-900"
    >
      <span class="text-xs uppercase tracking-wide text-surface-500 dark:text-surface-400">{{ strings.weekNumber }} {{ weekNo }}</span>
      <span class="font-semibold text-lg text-surface-900 dark:text-surface-50">{{ strings.weekStripTotal }}</span>
      <span class="text-primary font-semibold">{{ weekGrandTotal }}</span>
      <span class="text-xs text-muted-color">h</span>
    </div>

    <button
      v-for="c in dayChips"
      :key="c.key"
      type="button"
      class="cursor-pointer rounded-lg border text-left px-2 py-2 min-w-[4.75rem] transition-colors hover:bg-primary-50 dark:hover:bg-primary-950/40"
      :class="
        selectedIsoDate === c.iso
          ? 'border-primary border-t-4 border-t-primary pt-px text-primary'
          : 'border-surface-200 dark:border-surface-700'
      "
      @click="emit('select-day', c.iso)"
    >
      <div class="text-xs font-medium text-surface-500 dark:text-surface-400">
        {{ c.label }}
      </div>
      <div class="font-semibold text-surface-900 dark:text-surface-50">{{ c.iso.slice(8, 10) }}</div>
      <div class="text-sm font-medium mt-1">{{ c.total }}</div>
      <div class="text-[10px] text-muted-color">h</div>
    </button>
  </div>
</template>
