<template>
    <MessageFrame role="assistant" :copyContent="msg.content">
        <div v-html="parseMd(content)"></div>
        <template #footer>
            <span class="footer-name">{{ displayName }}</span>
            <button v-if="!msg.streaming && msg.content" class="tts-btn" :class="{ active: ttsPlayer.isPlayingMsg(msg) }" @click.stop="ttsPlayer.play(msg, msg._sourceIndex ?? 0)" title="Listen">
                <span v-if="ttsPlayer.isPlayingMsg(msg) && ttsPlayer.state.value === 'loading'" class="tts-spinner"></span>
                <SpeakerWaveIcon v-else class="w-3.5 h-3.5" />
            </button>
            <span v-if="msg.streaming && tools.length === 0" class="footer-status"> ...</span>
            <span v-else-if="!msg.streaming && tools.length === 0" class="footer-status"> | {{ msgTimeLabel }}</span>
            <span v-if="tools.length > 0" class="footer-tools">
                <span
                    v-for="tool in tools"
                    :key="tool.id"
                    class="footer-tool-icon"
                    :class="tool.state"
                    :title="`${tool.label} [${tool.state}]`"
                ><ToolIcon :tool="tool.tool || ''" /></span>
            </span>
            <span v-if="msg.truncated" class="truncated-notice"><ExclamationTriangleIcon class="w-4 h-4 inline" /> Output limit reached — response was cut off</span>
        </template>
    </MessageFrame>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { ExclamationTriangleIcon, SpeakerWaveIcon } from '@heroicons/vue/20/solid';
import MessageFrame from './MessageFrame.vue';
import { useChatStore } from '../store/chat';
import { parseMd } from '../composables/useMessages';
import type { Agent } from '../composables/agents';
import ToolIcon from './ToolIcon.vue';
import { useTtsPlayer } from '../composables/useTtsPlayer';
import { relativeTime } from '../utils/relativeTime';

const chatStore = useChatStore();
const ttsPlayer = useTtsPlayer();

const props = defineProps<{
    msg: any;
    agentDisplayName: string;
    isAgentRunning: boolean;
    allAgents: Agent[];
    getToolsForTurn: (corrId: string | null | undefined) => any[];
    hudVersion: number;  // increments on every HUD tree mutation — reactive dep
}>();

const displayName = computed(() => {
    const id = props.msg.agentId;
    if (id) {
        const agent = props.allAgents?.find((a: any) => a.id === id);
        return (agent ? agent.name : id).toUpperCase();
    }
    return props.agentDisplayName;
});

const msgTimeLabel = computed(() => {
    if (props.msg.timestamp) {
        return relativeTime(props.msg.timestamp);
    }
    return 'Done';
});

const content = computed(() => {
    if (props.msg.streaming) {
        return chatStore.streamingMessageVisibleContent + '<span class="typing-dots">...</span>';
    }
    return props.msg.content;
});

// Tool list for this message's turn — live during streaming, frozen after
// hudVersion is a primitive counter that increments on every HUD mutation,
// so Vue properly tracks it as a reactive dep (array identity doesn't change)
const tools = computed(() => {
    void props.hudVersion;
    return props.getToolsForTurn(props.msg.turnCorrId);
});

// TTS handled by global useTtsPlayer composable
</script>

<style scoped>
.footer-name {
    font-weight: 500;
}
.footer-status {
    opacity: 0.6;
}
.footer-tools {
    display: inline-flex;
    flex-wrap: wrap;
    gap: 0.2rem;
    margin-left: 0.4rem;
    vertical-align: middle;
}
.footer-tool-icon {
    line-height: 1;
    opacity: 0.45;
    cursor: default;
    transition: opacity 0.15s;
}
.footer-tool-icon.running {
    opacity: 1;
    animation: pulse-icon 1.2s infinite;
}
.footer-tool-icon.error {
    opacity: 1;
    filter: sepia(1) saturate(5) hue-rotate(300deg);
}
.footer-tool-icon.done {
    opacity: 0.45;
}
@keyframes pulse-icon {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.4; }
}
.truncated-notice {
    display: block;
    margin-top: 4px;
    color: #e5a950;
    opacity: 0.85;
}

/* TTS */
.tts-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 22px;
    height: 22px;
    border-radius: 50%;
    border: none;
    background: transparent;
    color: var(--text-dim);
    cursor: pointer;
    margin-left: 0.3rem;
    padding: 0;
    opacity: 0.5;
    transition: opacity 0.15s, color 0.15s;
    vertical-align: middle;
}
.tts-btn:hover { opacity: 1; color: var(--text); }
.tts-btn.active { opacity: 1; color: var(--accent); }
.tts-btn.loading { opacity: 0.7; cursor: wait; }
.tts-spinner {
    width: 12px;
    height: 12px;
    border: 2px solid var(--text-dim);
    border-top-color: transparent;
    border-radius: 50%;
    animation: spin-tts 0.6s linear infinite;
}
@keyframes spin-tts { to { transform: rotate(360deg); } }
</style>
