<script setup lang="ts">
import { Layers3, LoaderCircle } from "@lucide/vue";
import { computed } from "vue";

import type { UserEntitlementSummary } from "../types/api";
import { formatDate } from "../utils/dateTime";

const props = defineProps<{
  used: number;
  limit: number;
  entitlement?: UserEntitlementSummary | null;
  generatingHelpCard?: boolean;
  generatingShareDraft?: boolean;
}>();

defineEmits<{
  generateHelpCard: [];
  generateShareDraft: [];
}>();

const hasEntitlement = computed(() => Boolean(props.entitlement));
const displayUsed = computed(() => props.used);
const displayLimit = computed(() => props.limit);
const exhausted = computed(() => displayLimit.value > 0 && displayUsed.value >= displayLimit.value);
const title = computed(() => "今日问答使用情况");
const usageText = computed(() => {
  if (displayLimit.value <= 0) return "今日不可用";
  return `今日 ${displayUsed.value}/${displayLimit.value} 次`;
});
const guidanceText = computed(() => {
  if (props.entitlement?.lifecycleStatus === "expired_fallback") {
    return `原${props.entitlement.previousPlanName ? `“${props.entitlement.previousPlanName}”` : "权益"}已于 ${formatDate(props.entitlement.previousExpiredAt)} 到期，当前已自动切换为${props.entitlement.name}，已有对话与回顾仍会保留。`;
  }
  if (props.entitlement?.lifecycleStatus === "expiring_7" || props.entitlement?.lifecycleStatus === "expiring_30") {
    return `当前权益将于 ${formatDate(props.entitlement.expiredAt)} 到期；如需继续使用，可提前联系运营老师确认续期。`;
  }
  if (exhausted.value) return "今日问答次数已用完，次日会自动恢复；如需继续使用，可联系运营老师确认权益。";
  return "";
});
</script>

<template>
  <section class="session-quota" :class="{ exhausted }" :aria-label="title">
    <div>
      <Layers3 :size="18" aria-hidden="true" />
      <span>{{ title }}</span>
      <small v-if="hasEntitlement">{{ entitlement?.name }}</small>
    </div>
    <div class="session-quota-actions">
      <button
        v-if="entitlement?.allowHelpCard"
        type="button"
        class="quota-link"
        :disabled="generatingHelpCard"
        @click="$emit('generateHelpCard')"
      >
        <LoaderCircle v-if="generatingHelpCard" class="spinning" :size="14" aria-hidden="true" />
        {{ generatingHelpCard ? '生成中' : '求助卡' }}
      </button>
      <button
        v-if="entitlement?.allowShareDraft"
        type="button"
        class="quota-link"
        :disabled="generatingShareDraft"
        @click="$emit('generateShareDraft')"
      >
        <LoaderCircle v-if="generatingShareDraft" class="spinning" :size="14" aria-hidden="true" />
        {{ generatingShareDraft ? '生成中' : '分享稿' }}
      </button>
      <strong>{{ usageText }}</strong>
    </div>
    <p v-if="guidanceText" class="session-quota-guidance">{{ guidanceText }}</p>
  </section>
</template>
