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

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

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

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

const hasEntitlement = computed(() => Boolean(props.entitlement));
const displayUsed = computed(() => props.entitlement?.monthlyTopicUsed ?? props.used);
const displayLimit = computed(() => props.entitlement?.monthlyTopicLimit ?? props.limit);
const exhausted = computed(() => displayLimit.value !== null && displayLimit.value > 0 && displayUsed.value >= displayLimit.value);
const nearLimit = computed(() => displayLimit.value !== null && displayLimit.value > 0 && displayUsed.value / displayLimit.value >= 0.8);
const title = computed(() => props.entitlement ? "本月主题使用情况" : "今日陪伴使用情况");
const usageText = computed(() => {
  if (displayLimit.value === null) return props.entitlement ? "本月不限" : "不限";
  if (props.entitlement) return `已使用 ${displayUsed.value}/${displayLimit.value} 个主题`;
  return `今日 ${displayUsed.value}/${displayLimit.value}`;
});
const guidanceText = computed(() => {
  if (exhausted.value) return "本月深度主题使用较多，建议先完成已有功课；如需继续高频陪伴，可联系运营老师确认权益。";
  if (nearLimit.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?.enableGrowthProfile"
        type="button"
        class="quota-link"
        @click="$emit('openProfile')"
      >
        我的档案
      </button>
      <button type="button" class="quota-link" :disabled="finishing" @click="$emit('finishTopic')">
        {{ finishing ? '沉淀中' : '沉淀本主题' }}
      </button>
      <button
        v-if="entitlement?.allowHelpCard"
        type="button"
        class="quota-link"
        :disabled="generatingHelpCard"
        @click="$emit('generateHelpCard')"
      >
        {{ generatingHelpCard ? '生成中' : '求助卡' }}
      </button>
      <button
        v-if="entitlement?.allowShareDraft"
        type="button"
        class="quota-link"
        :disabled="generatingShareDraft"
        @click="$emit('generateShareDraft')"
      >
        {{ generatingShareDraft ? '生成中' : '分享稿' }}
      </button>
      <strong>{{ usageText }}</strong>
    </div>
    <p v-if="guidanceText" class="session-quota-guidance">{{ guidanceText }}</p>
  </section>
</template>
