<script setup lang="ts">
import { useMarketStore } from "../../shared/stores/market";
import { useUiStore } from "../../shared/stores/ui";

const market = useMarketStore();
const ui = useUiStore();

function change(event: Event): void {
  const input = event.target as HTMLInputElement;
  const value = input.value.trim();
  const parsed = new Date(`${value}T12:00:00+08:00`);
  if (/^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === value) {
    void market.selectDate(value);
    return;
  }
  input.value = market.selectedDate;
  ui.showToast("请输入 YYYY-MM-DD 格式的日期");
}
</script>

<template>
  <div class="date-control" aria-label="交易日期控制">
    <button class="icon-button" type="button" aria-label="前一日" title="前一日" @click="market.moveDate(-1)">‹</button>
    <input :value="market.selectedDate" class="date-input" type="text" inputmode="numeric" pattern="\d{4}-\d{2}-\d{2}" maxlength="10" aria-label="交易日期" @change="change" />
    <button class="icon-button" type="button" aria-label="后一日" title="后一日" @click="market.moveDate(1)">›</button>
  </div>
</template>
