<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 type { Message } from "@/types/chat";

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>);

// Hide LEGACY system-role daily_prep messages from earlier versions. The
// current journal prep is a normal assistant message (renders with proper
// bubble styling). Old system-role rows lurking in existing conversations
// would render as a flat unstyled block — filter them.
const hideMessage = computed(() =>
  props.message.role === "system" && metadata.value.kind === "daily_prep"
);

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>
  <div v-if="!hideMessage" class="chat-message" :class="`role-${message.role}`">
    <div class="message-group">
      <div class="message-bubble">
        <div class="message-header">
          <span class="role-label">{{ roleLabel }}</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: 500;
  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-size: 0.8rem;
  text-transform: none;
  letter-spacing: 0;
}

.thinking-block {
  margin-bottom: 0.5rem;
  border-left: 2px solid rgba(91, 74, 138, 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: 500;
  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);
}
/* Long-form line-height (1.7) on assistant bubbles per the design system —
   chat is a reading surface, not a snippet stream. User bubbles stay tighter. */
.role-assistant .message-content {
  line-height: 1.7;
}

.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;
}

</style>
