<template>
  <section class="time-card">
    <div class="time-date">6月5日（周三）</div>
    <div class="time-grid">
      <div
        v-for="slot in slots"
        :key="slot.slotId"
        :class="['time-slot', { pick: selectedSlot === slot.slotId }]"
        @click="selectSlot(slot)"
      >
        {{ slot.timePeriod }}
        <div class="time-slot-meta">余{{ slot.remain ?? slot.remaining ?? '--' }}号 &middot; ¥{{ amount }}</div>
      </div>
    </div>
    <div v-if="doctorName || room" class="time-note">
      <span v-if="doctorName">{{ doctorName }}</span>
      <span v-if="doctorName && room"> &middot; </span>
      <span v-if="room">{{ room }}</span>
      <span> &middot; 挂号费 ¥{{ amount }}</span>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import type { CardInstance } from '../api/types';
import { useTerminalStore } from '../state/terminalStore';

const props = defineProps<{ card: CardInstance }>();
const emit = defineEmits<{ action: [data: { actionName: string; payload: Record<string, unknown> }] }>();
const store = useTerminalStore();

interface SlotOption {
  slotId: string;
  timePeriod: string;
  remain?: number;
  remaining?: number;
}

const slots = computed(() => (props.card.cardData.slots as SlotOption[]) ?? []);
const amount = computed(() => props.card.cardData.amountYuan ?? props.card.cardData.amount ?? '25.00');
const doctorName = computed(() => store.selection.doctorName || props.card.cardData.doctorName as string || '');
const room = computed(() => store.selection.room || props.card.cardData.room as string || '');

const selectedSlot = ref<string | null>(null);

function selectSlot(slot: SlotOption) {
  if (store.cardActionSubmitting) return;
  selectedSlot.value = slot.slotId;
  emit('action', {
    actionName: 'select_time_slot',
    payload: { slotId: slot.slotId, timePeriod: slot.timePeriod },
  });
}
</script>

<style scoped>
.time-card {
  display: flex;
  flex-direction: column;
}

.time-date {
  font-family: var(--font-display);
  font-size: var(--fs-h3);
  font-weight: 600;
  letter-spacing: -0.01em;
  margin-bottom: 14px;
}

.time-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 14px;
}

.time-slot {
  padding: 10px 12px;
  border: 1px solid var(--border);
  border-radius: var(--radius-sm);
  text-align: center;
  font-size: var(--fs-sm);
  cursor: pointer;
  transition: border-color 0.15s ease, background 0.15s ease;
}

.time-slot:hover {
  border-color: var(--accent);
}

.time-slot.pick {
  border-color: var(--accent);
  background: var(--accent-faint);
  color: var(--accent);
  font-weight: 500;
}

.time-slot-meta {
  font-size: 11px;
  color: var(--muted);
}

.time-note {
  padding: 10px 14px;
  background: var(--accent-faint);
  border-radius: var(--radius-sm);
  font-size: var(--fs-xs);
  color: var(--muted);
}
</style>
