<script setup>
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import CaptainAssistant from 'dashboard/api/captain/assistant';
import MessageFormatter from 'shared/helpers/MessageFormatter.js';

const props = defineProps({
  range: {
    type: String,
    default: '30',
  },
});

const route = useRoute();
const assistantId = computed(() => route.params.assistantId);

// Markdown summary generated by the model from the assistant's stats (served by
// the captain/assistants/:id/summary endpoint). Numbers are emphasised with
// **bold** so we can highlight them (see prose-strong styling below).
const welcomeMarkdown = ref('');
const isLoading = ref(false);

const fetchSummary = async () => {
  isLoading.value = true;
  try {
    const { data } = await CaptainAssistant.getSummary({
      assistantId: assistantId.value,
      range: props.range,
    });
    welcomeMarkdown.value = data.message ?? '';
  } catch {
    welcomeMarkdown.value = '';
  } finally {
    isLoading.value = false;
  }
};

watch([() => props.range, assistantId], fetchSummary, { immediate: true });

// Render through the shared markdown formatter (html disabled, so it is safe)
// used everywhere else for Captain output, instead of a bespoke parser. It
// handles paragraphs, line breaks, links, lists and emphasis consistently.
const formattedSummary = computed(
  () => new MessageFormatter(welcomeMarkdown.value).formattedMessage
);
</script>

<!-- eslint-disable-next-line vue/no-root-v-if -->
<template>
  <div v-if="isLoading || welcomeMarkdown" class="flex flex-col gap-3">
    <div class="flex items-center gap-1.5 text-n-slate-10">
      <span class="i-lucide-sparkles size-3.5" />
      <span class="text-xs">
        {{ $t('CAPTAIN.OVERVIEW.WELCOME.LABEL') }}
      </span>
    </div>
    <div
      v-if="isLoading"
      class="flex flex-col gap-5"
      :aria-label="$t('CAPTAIN.OVERVIEW.WELCOME.LOADING')"
    >
      <div class="flex flex-col gap-2.5">
        <div class="w-full h-5 rounded bg-n-slate-3 animate-pulse" />
        <div class="w-11/12 h-5 rounded bg-n-slate-3 animate-pulse" />
        <div class="w-4/6 h-5 rounded bg-n-slate-3 animate-pulse" />
      </div>
      <div class="w-5/6 h-5 rounded bg-n-slate-3 animate-pulse" />
    </div>
    <div
      v-else
      v-dompurify-html="formattedSummary"
      class="max-w-none prose prose-p:text-lg prose-p:leading-relaxed prose-p:mt-0 prose-p:mb-3 last:prose-p:mb-0 prose-strong:font-bold prose-strong:tabular-nums prose-strong:text-n-brand text-n-slate-12"
    />
  </div>
</template>
