<script setup lang="ts">
import { computed } from "vue";
import { renderMarkdown } from "@/utils/markdown";
import { useSettingsStore } from "@/stores/settings";
import ToolCallCard from "@/components/ToolCallCard.vue";
import BriefingToolStatusRow from "@/components/BriefingToolStatusRow.vue";
import type { Message } from "@/types/chat";

const SLOT_LABELS: Record<string, string> = {
  compilation: "Full Briefing",
  morning: "Morning Update",
  midday: "Midday Update",
  afternoon: "Afternoon Update",
};

const settingsStore = useSettingsStore();

const props = defineProps<{
  message: Message;
  isStreaming?: boolean;
}>();

const emit = defineEmits<{
  saveAsNote: [messageId: number];
}>();

const rendered = computed(() => renderMarkdown(props.message.content));

const formattedTime = computed(() => {
  if (!props.message.created_at) return "";
  const date = new Date(props.message.created_at);
  return date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
});

const roleLabel = computed(() => {
  switch (props.message.role) {
    case "user":
      return "You";
    case "assistant":
      return settingsStore.assistantName;
    default:
      return props.message.role;
  }
});

function formatMs(ms: number | null | undefined): string {
  if (ms == null) return "";
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

const metadata = computed(() => (props.message.metadata ?? {}) as Record<string, unknown>);

const isBriefingIntermediate = computed(
  () => props.message.role === "assistant" && metadata.value.briefing_intermediate === true,
);

const briefingSlot = computed(() => {
  const slot = metadata.value.briefing_slot;
  return typeof slot === "string" ? slot : null;
});

const slotLabel = computed(() => {
  const slot = briefingSlot.value;
  if (!slot) return null;
  return SLOT_LABELS[slot] ?? slot;
});

const isSlotUpdate = computed(
  () =>
    !isBriefingIntermediate.value &&
    briefingSlot.value != null &&
    briefingSlot.value !== "compilation",
);

const timingParts = computed((): string[] => {
  const t = props.message.timing;
  if (!t) return [];
  const parts: string[] = [];
  if (t.total_ms != null) parts.push(`${formatMs(t.total_ms)} total`);
  if (t.ttft_ms != null) parts.push(`first token ${formatMs(t.ttft_ms)}`);
  if (t.intent_ms != null) parts.push(`analyzed ${formatMs(t.intent_ms)}`);
  for (const tool of t.tools ?? []) {
    parts.push(`${tool.name.replace(/_/g, " ")} ${formatMs(tool.ms)}`);
  }
  if (t.generation_ms != null) parts.push(`generated ${formatMs(t.generation_ms)}`);
  return parts;
});
</script>

<template>
  <!-- Briefing intermediate: compact status row, no bubble -->
  <div v-if="isBriefingIntermediate" class="chat-message role-assistant briefing-intermediate-row">
    <BriefingToolStatusRow :tool-calls="message.tool_calls ?? []" />
  </div>
  <div v-else class="chat-message" :class="[`role-${message.role}`, { 'slot-update': isSlotUpdate }]">
    <div class="message-group">
      <div class="message-bubble" :class="{ 'bubble-slot': isSlotUpdate }">
        <div class="message-header">
          <span class="role-label">{{ roleLabel }}</span>
          <span v-if="slotLabel" class="slot-badge" :class="{ 'slot-badge-update': isSlotUpdate }">{{ slotLabel }}</span>
          <div class="message-actions" v-if="message.role === 'assistant' && !isStreaming">
            <button class="btn-save" @click="emit('saveAsNote', message.id)" title="Save as note">
              Save as Note
            </button>
          </div>
        </div>
        <details v-if="message.thinking" class="thinking-block">
          <summary class="thinking-summary">Reasoning</summary>
          <pre class="thinking-text">{{ message.thinking }}</pre>
        </details>
        <div class="message-content prose" v-html="rendered"></div>
        <div v-if="message.tool_calls?.length" class="tool-calls">
          <ToolCallCard
            v-for="(tc, i) in message.tool_calls"
            :key="i"
            :tool-call="tc"
          />
        </div>
        <div
          v-if="message.context_note_id"
          class="context-badge"
        >
          <router-link :to="`/notes/${message.context_note_id}`">
            {{ message.context_note_title || `Note #${message.context_note_id}` }}
          </router-link>
        </div>
      </div>
      <span v-if="formattedTime" class="message-timestamp">{{ formattedTime }}</span>
      <div v-if="timingParts.length" class="message-timing">
        <span class="timing-icon">⏱</span>
        <span v-for="(part, i) in timingParts" :key="i" class="timing-part">
          <span v-if="i > 0" class="timing-sep">·</span>{{ part }}
        </span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-message {
  display: flex;
  margin-bottom: 0.75rem;
}
.role-user {
  justify-content: flex-end;
}
.role-assistant {
  justify-content: flex-start;
}

.message-group {
  max-width: 80%;
}

.message-bubble {
  padding: 0.75rem 1rem;
  border-radius: 18px;
}

/* User prompts: recessed, muted — margin notes */
.role-user .message-bubble {
  background: var(--color-bubble-user-bg);
  border: 1px solid var(--color-bubble-user-border);
  color: var(--color-bubble-user-text);
  border-bottom-right-radius: 4px;
}

/* Assistant responses: elevated, lit — the primary text */
.role-assistant .message-bubble {
  background: var(--color-bg-card);
  border-left: 2px solid var(--color-primary);
  box-shadow: var(--color-bubble-asst-shadow);
  border-bottom-left-radius: 4px;
}

.message-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.25rem;
}
.role-label {
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.03em;
}
.role-user .role-label {
  color: var(--color-text-muted);
  opacity: 0.6;
}
.role-assistant .role-label {
  color: var(--color-primary);
  font-family: 'Fraunces', Georgia, serif;
  font-optical-sizing: auto;
  font-style: italic;
  font-size: 0.8rem;
  text-transform: none;
  letter-spacing: 0;
}

.thinking-block {
  margin-bottom: 0.5rem;
  border-left: 2px solid rgba(129, 140, 248, 0.35);
  border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
  overflow: hidden;
}
.thinking-summary {
  padding: 0.25rem 0.5rem;
  font-size: 0.72rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: var(--color-text-muted);
  cursor: pointer;
  user-select: none;
  list-style: none;
  display: flex;
  align-items: center;
  gap: 0.3rem;
  background: var(--color-bg-secondary);
}
.thinking-summary::-webkit-details-marker { display: none; }
.thinking-summary::before {
  content: "▶";
  font-size: 0.6rem;
  transition: transform 0.15s;
}
details[open] .thinking-summary::before {
  transform: rotate(90deg);
}
.thinking-text {
  margin: 0;
  padding: 0.5rem;
  font-size: 0.8rem;
  line-height: 1.5;
  color: var(--color-text-secondary);
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  background: var(--color-bg-secondary);
}
.message-content {
  font-size: 0.95rem;
  line-height: 1.55;
  word-break: break-word;
}
.message-content :deep(p:last-child) {
  margin-bottom: 0;
}


.message-actions {
  display: flex;
  gap: 0.5rem;
}
.btn-save {
  font-size: 0.7rem;
  padding: 0.1rem 0.4rem;
  background: transparent;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  color: var(--color-text-secondary);
  cursor: pointer;
}
.btn-save:hover {
  background: var(--color-primary);
  color: #fff;
  border-color: var(--color-primary);
}
.tool-calls {
  display: flex;
  flex-wrap: wrap;
  gap: 0.3rem;
  margin-top: 0.4rem;
}
.context-badge {
  margin-top: 0.4rem;
  font-size: 0.75rem;
}
.context-badge a {
  color: var(--color-primary);
  text-decoration: none;
}
.role-user .context-badge a {
  color: rgba(255, 255, 255, 0.8);
}
.context-badge a:hover {
  text-decoration: underline;
}

.message-timestamp {
  display: block;
  font-size: 0.7rem;
  color: var(--color-text-muted);
  margin-top: 0.15rem;
  padding: 0 0.5rem;
}
.message-timing {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.2rem;
  padding: 0.1rem 0.5rem 0;
  font-size: 0.68rem;
  color: var(--color-text-muted);
  opacity: 0.7;
}
.timing-icon {
  font-size: 0.65rem;
}
.timing-part {
  white-space: nowrap;
}
.timing-sep {
  margin-right: 0.2rem;
  opacity: 0.5;
}

/* ── Briefing intermediate row (no bubble) ──────────────── */
.briefing-intermediate-row {
  margin-bottom: 0.5rem;
}

/* ── Slot badge (morning/midday/afternoon/full) ─────────── */
.slot-badge {
  font-size: 0.65rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0.1rem 0.45rem;
  border-radius: 999px;
  background: color-mix(in srgb, var(--color-primary) 14%, transparent);
  color: var(--color-primary);
  border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
  margin-left: 0.5rem;
}
.slot-badge-update {
  background: color-mix(in srgb, var(--color-text-muted) 12%, transparent);
  color: var(--color-text-muted);
  border-color: var(--color-border);
}

/* ── Slot update bubbles: softer treatment than compilation ── */
.slot-update .message-bubble.bubble-slot {
  background: transparent;
  border-left: 2px solid var(--color-border);
  box-shadow: none;
}
.slot-update .message-bubble.bubble-slot .message-content {
  font-size: 0.88rem;
  color: var(--color-text-secondary);
}
</style>
