<template>
  <section class="space-y-6 p-4 md:p-8">
    <div class="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
      <div>
        <p class="text-sm font-bold uppercase tracking-[0.2em] text-brand">Attendance Engine</p>
        <h2 class="mt-2 text-3xl font-black">Today punch analysis</h2>
        <p class="mt-1 text-slate-500">Check in/out, lunch, missing punch, late, early out, and OT calculations.</p>
      </div>
      <button class="rounded-2xl bg-ink px-5 py-3 text-sm font-bold text-white">Manual Entry</button>
    </div>

    <div class="grid gap-4 md:grid-cols-4">
      <MetricCard label="Records" :value="records.length" helper="Calculated today" tone="live" />
      <MetricCard label="Late" :value="lateCount" helper="Rule engine candidates" tone="warn" />
      <MetricCard label="Missing Punch" :value="missingPunchCount" helper="Needs approval" tone="risk" />
      <MetricCard label="OT Minutes" :value="overtimeTotal" helper="Pending payroll sync" tone="ok" />
    </div>

    <div class="overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-soft">
      <table class="w-full min-w-[860px] text-left text-sm">
        <thead class="bg-slate-50 text-slate-500">
          <tr>
            <th class="p-4">Employee</th><th class="p-4">Check In</th><th class="p-4">Lunch</th><th class="p-4">Check Out</th><th class="p-4">Late</th><th class="p-4">Working</th><th class="p-4">Status</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in records" :key="record.employee_code" class="border-t border-slate-100">
            <td class="p-4 font-bold">{{ record.employee_code }}</td>
            <td class="p-4">{{ record.check_in || '-' }}</td>
            <td class="p-4">{{ record.lunch_out || '-' }} / {{ record.lunch_in || '-' }}</td>
            <td class="p-4">{{ record.check_out || 'Missing' }}</td>
            <td class="p-4">{{ record.late_minutes }}m</td>
            <td class="p-4">{{ record.working_minutes }}m</td>
            <td class="p-4"><span class="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold uppercase">{{ record.status }}</span></td>
          </tr>
        </tbody>
      </table>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import MetricCard from '../components/MetricCard.vue';
import { getJson } from '../services/api.js';

const records = ref([]);
const lateCount = computed(() => records.value.filter((row) => row.late_minutes > 0).length);
const missingPunchCount = computed(() => records.value.filter((row) => !row.check_out).length);
const overtimeTotal = computed(() => records.value.reduce((sum, row) => sum + Number(row.overtime_minutes || 0), 0));

onMounted(async () => {
  try {
    const data = await getJson('/attendance/today');
    records.value = data.records;
  } catch (error) {
    console.warn(error.message);
  }
});
</script>
