<template>
    <div class="agents-view flex flex-col h-full overflow-hidden bg-bg" v-if="isLoggedIn">
      <!-- NO_AGENT_SELECTED or overview mode: show agent picker -->
      <div v-show="showPicker" class="agent-picker">
        <div class="agent-picker-content">
          <p class="agent-picker-title">Select an agent</p>
          <div v-for="seg in agentSegments" :key="seg.key" class="agent-picker-segment">
            <div class="agent-picker-segment-label">{{ seg.key }}</div>
            <div v-for="agent in seg.agents" :key="agent.id" class="agent-picker-row">
              <button class="agent-picker-btn" @click="pickAgent(agent.id, 'private')" :title="agent.name + ' (private)'">
                <span class="sidebar-room-dot" :class="`dot-${agent.role}`"></span>
                <span class="agent-picker-name">{{ agent.name }}</span>
              </button>
              <div class="agent-picker-modes">
                <button v-if="agent.modes?.includes('private')" class="agent-picker-mode" @click="pickAgent(agent.id, 'private')" title="Private">
                  <LockClosedIcon class="w-3.5 h-3.5" />
                </button>
                <button v-if="agent.modes?.includes('public')" class="agent-picker-mode" @click="pickAgent(agent.id, 'public')" title="Public">
                  <UserGroupIcon class="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="!showPicker" class="page flex flex-col flex-1 min-h-0">
        <div class="chat-frame flex-1 flex flex-col overflow-visible relative">
          <div class="content flex-1 min-h-0">
            <OverlayScrollbarsComponent class="messages h-full pb-4 flex flex-col gap-3 relative" :class="{ 'is-switching': isHidden }" :options="scrollbarOptions" ref="messagesEl" element="div">
                <!-- Previous sessions (server-fetched, fully interactive) -->
                <template v-if="prevSessions.length">
                    <!-- Load more button -->
                    <button v-if="prevHasMore" class="prev-load-more" @click="fetchPreviousSession(true)" :disabled="prevLoading">
                        {{ prevLoading ? 'Loading...' : 'Load older session' }}
                    </button>

                    <template v-for="(session, si) in prevSessions" :key="'ps-'+si">
                        <div class="prev-session-header">
                            Session {{ prevSessions.length - si }}{{ session.timeLabel ? ' \u2014 ' + session.timeLabel : '' }}
                        </div>
                        <div class="prev-session-wrapper">
                            <template v-for="(msg, mi) in session.messages" :key="'prev-'+si+'-'+mi">
                                <UserMessage v-if="msg.role === 'user'" :msg="msg" />
                                <AssistantMessage
                                    v-else-if="msg.role === 'assistant'"
                                    :msg="msg"
                                    :agentDisplayName="getFormattedAgentName(msg.agentId || selectedAgent)"
                                    :isAgentRunning="false"
                                    :allAgents="allAgents"
                                    :getToolsForTurn="() => []"
                                    :hudVersion="0"
                                />
                            </template>
                        </div>
                    </template>

                    <div class="session-divider">
                        <span class="session-divider-text">Current session</span>
                    </div>
                </template>
                <template v-for="(msg, i) in groupedVisibleMsgs" :key="i">
                    <!-- Branch 0: NO_SESSION marker -->
                    <div v-if="msg.type === 'no_session'" class="no-session-center">— NO SESSION —</div>

                    <!-- Branch 1: System, Groups, and Headlines (skip footer headlines — rendered below) -->
                    <SystemMessage 
                        v-if="msg.type !== 'no_session' && (msg.role === 'system' || msg.role === 'system_group' || msg.type === 'headline') && msg.position !== 'footer'"
                        :msg="msg"
                    />
                    <!-- Load more button: after the first header headline -->
                    <button v-if="hasMore && msg.type === 'headline' && msg.position !== 'footer' && i === 0" class="load-more-btn" @click="loadMore">↑ Load previous messages</button>
                    
                    <!-- Branch 1b: Session Context (injected prompt) -->
                    <div v-else-if="msg.role === 'session_context'" class="session-context-badge">
                        <span class="session-context-text">{{ msg.content }}</span>
                    </div>

                    <!-- Branch 2: User Messages -->
                    <UserMessage
                        v-else-if="msg.role === 'user'"
                        :msg="msg"
                    />

                    <!-- Branch 3: Thinking Messages -->
                    <div v-else-if="msg.role === 'thinking'" class="message thinking">
                        <details :open="!msg.collapsed">
                            <summary><ChatBubbleBottomCenterTextIcon class="w-4 h-4 inline" /> thinking…</summary>
                            <pre class="thinking-content">{{ typeof msg.content === 'object' ? msg.content.value : msg.content }}</pre>
                        </details>
                    </div>

                    <!-- Branch 4: Assistant Messages -->
                    <AssistantMessage
                        v-else-if="msg.role === 'assistant'"
                        :msg="msg"
                        :agentDisplayName="getFormattedAgentName(msg.agentId)"
                        :isAgentRunning="isAgentRunning"
                        :allAgents="allAgents"
                        :getToolsForTurn="getToolsForTurn"
                        :hudVersion="hudVersion"
                    />

                    <!-- SM status bar: after last real message, before any footer headline -->
                    <div v-if="i === lastRealMsgIdx" class="sm-status-bar">
                        <div class="sm-dot" :class="smState"></div>
                        <span class="sm-status-label">{{ smLabel }}</span>
                    </div>
                </template>



                <!-- SM badge fallback: shown when there are no real messages -->
                <div v-if="lastRealMsgIdx === -1" class="sm-status-bar">
                    <div class="sm-dot" :class="smState"></div>
                    <span class="sm-status-label">{{ smLabel }}</span>
                </div>

                <!-- Footer headline -->
                <SystemMessage v-if="footerHeadline" :msg="footerHeadline" />

                <!-- Controls: immediately after last message -->
                <div class="msg-controls" ref="controlsEl">
                    <HudControls
                        :smState="smState"
                        :connected="connected"
                        :isAgentRunning="chatStore.isRunning"
                        :handoverPending="chatStore.handoverPending"
                        :isPublic="selectedMode === 'public'"
                        @new="onNew"
                        @handover="chatStore.handover()"
                        @confirm-new="onConfirmNew"
                        @stay="chatStore.stay()"
                    />
                </div>

                <!-- Spacer: separate element so measurements don't oscillate -->
                <div class="scroll-spacer" :style="{ height: spacerHeight + 'px', flexShrink: 0 }"></div>
            </OverlayScrollbarsComponent>
          </div>

            <div class="input-area"
                @dragover.prevent="onDragOver"
                @dragleave.prevent="onDragLeave"
                @drop.prevent="onDrop">
                <!-- Mic denied hint -->
                <div v-if="micDenied" class="mic-denied-hint">Mic access denied — enable in browser settings</div>
                <!-- Recording indicator -->
                <div v-if="isRecording" class="recording-strip">
                    <span class="rec-dot"></span>
                    <div class="rec-level-bar"><div class="rec-level-fill" :style="{ width: (audioLevel * 100) + '%' }"></div></div>
                    <span class="rec-time">{{ formatDuration(duration) }}</span>
                    <button class="rec-cancel" @click.stop="cancelRecording" title="Cancel">&times;</button>
                </div>
                <!-- Attachment thumbnails -->
                <div v-if="attachments.length" class="attachment-strip">
                    <div v-for="(att, i) in attachments" :key="i" class="attachment-thumb" :class="{ 'audio-thumb': att.mimeType.startsWith('audio/') }">
                        <template v-if="att.mimeType.startsWith('audio/')">
                            <span class="audio-icon">&#9835;</span>
                            <span class="audio-name">{{ att.fileName }}</span>
                        </template>
                        <img v-else :src="att.preview" :alt="att.fileName" />
                        <button class="remove-att" @click.stop="removeAttachment(i)">&times;</button>
                    </div>
                </div>
                <div class="input-box" :class="{ 'drag-over': isDragOver }" @click="inputEl?.focus()">
                    <button class="attach-btn" @click.stop="fileInputEl?.click()" title="Attach file">
                        <PaperClipIcon class="w-4 h-4" />
                    </button>
                    <button class="mic-btn" :class="{ recording: isRecording }" @click.stop="toggleRecording" :title="isRecording ? 'Stop recording' : 'Record audio'">
                        <MicrophoneIcon class="w-4 h-4" />
                    </button>
                        <input type="file" ref="fileInputEl" class="hidden" accept="image/jpeg,image/png,image/gif,image/webp,application/pdf,audio/webm,audio/mp4,audio/ogg,audio/mpeg,audio/wav" multiple @change="onFileSelect" />
                    <textarea
                        ref="inputEl"
                        v-model="input"
                        @keydown="(e: KeyboardEvent) => {
                            if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
                        }"
                        @input="autoGrow(); onInputChange()"
                        @paste="onPaste"
                        placeholder="Message..."
                        rows="1"
                        class="chat-input"
                        :class="{ shake: isShaking }"
                    ></textarea>
                    <!-- Stop button during agent run (subtle, right side) -->
                    <button v-if="smState === 'AGENT_RUNNING' || smState === 'STOP_PENDING'"
                        class="stop-btn"
                        :disabled="smState === 'STOP_PENDING'"
                        @click="chatStore.stop()"
                        :title="smState === 'STOP_PENDING' ? 'Stopping...' : 'Stop'">
                        <StopIcon class="w-3.5 h-3.5" />
                    </button>
                    <!-- Send button -->
                    <button class="send-btn" @click="send"
                        :disabled="!connected || sending || (!input.trim() && !hasAttachments())">
                        <ArrowUpIcon v-if="!sending" class="w-4 h-4" />
                        <span v-else style="font-size:11px">…</span>
                    </button>
                </div>
            </div>
        </div>
      </div>
    </div>

    <div v-else class="not-logged-in">
        <p><LockClosedIcon class="w-5 h-5 inline" /> Not logged in</p>
        <RouterLink to="/login">Sign in →</RouterLink>
    </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'AgentsView' });
import { ref, watch, nextTick, onMounted, onUnmounted, computed, toRef } from 'vue';
import { useRoute } from 'vue-router';
import { useChatStore } from '../store/chat';
import { ws, auth, agents } from '../store';
import { useUI } from '../composables/ui';
import { useAgentSocket } from '../composables/useAgentSocket';
import { useMessages } from '../composables/useMessages';
import { useMessageGrouping } from '../composables/useMessageGrouping';
import { useInputAutogrow } from '../composables/useInputAutogrow';
import { useAgentDisplay } from '../composables/useAgentDisplay';
import { OverlayScrollbarsComponent } from 'overlayscrollbars-vue';
import { scrollbarOptions } from '../composables/useScrollbar';
import { ArrowUpIcon, StopIcon, LockClosedIcon, ChatBubbleBottomCenterTextIcon, PaperClipIcon, MicrophoneIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
import { useAttachments } from '../composables/useAttachments';
import { useAudioRecorder } from '../composables/useAudioRecorder';
import UserMessage from '../components/UserMessage.vue';
import AssistantMessage from '../components/AssistantMessage.vue';
import SystemMessage from '../components/SystemMessage.vue';
import HudControls from '../components/HudControls.vue';
import { agentLogo as getAgentLogo } from '../composables/useTheme';

import router from '../router';
import { relativeTime } from '../utils/relativeTime';
import { getApiBase } from '../utils/apiBase';

const agentsRoute = useRoute();
const chatStore = useChatStore();

// Show picker when route has no ?agent= param (overview mode)
const showPicker = computed(() => !agentsRoute.query.agent);

// When navigating to /agents without params, clear selection so picker shows
watch(() => agentsRoute.query.agent, (val) => {
    if (!val && agentsRoute.name === 'agents') {
        // Don't clear selectedAgent ref — just show picker via showPicker computed
    }
}, { immediate: true });
// Previous sessions (server-fetched, supports load-more)
interface PrevSession { messages: any[]; timestamp: string | null; timeLabel: string }
const prevSessions = ref<PrevSession[]>([]);
const prevHasMore = ref(false);
const prevLoading = ref(false);
const prevSkip = ref(0);

// Flat list for template convenience
const prevMessages = computed(() => prevSessions.value.flatMap(s => s.messages));

async function fetchPreviousSession(loadMore = false) {
    if (!selectedAgent.value || prevLoading.value) return;
    prevLoading.value = true;
    try {
        const token = localStorage.getItem('nyx_session') || localStorage.getItem('titan_token') || '';
        const skip = loadMore ? prevSkip.value : 0;
        const apiBase = getApiBase();
        const res = await fetch(`${apiBase}/api/session-history?agent=${selectedAgent.value}&mode=${selectedMode.value}&skip=${skip}&count=1`, {
            headers: { 'Authorization': `Bearer ${token}` },
        });
        if (!res.ok) return;
        const data = await res.json();
        const newSessions: PrevSession[] = (data.sessions || []).map((s: any) => ({
            messages: (s.entries || []).map((e: any) => ({
                role: e.role,
                content: e.content,
                timestamp: e.timestamp,
                agentId: selectedAgent.value,
                streaming: false,
            })),
            timestamp: s.resetTimestamp,
            timeLabel: s.resetTimestamp ? relativeTime(s.resetTimestamp) : '',
        }));
        if (loadMore) {
            prevSessions.value = [...newSessions, ...prevSessions.value];
        } else {
            prevSessions.value = newSessions;
        }
        prevSkip.value = skip + newSessions.length;
        prevHasMore.value = data.hasMore ?? false;
    } catch { /* silently fail */ }
    finally { prevLoading.value = false; }
}
const { connected, status, send: wsSend, switchAgent: wsSwitchAgent } = ws;
const { version } = useUI(status);
const beVersion = ref('');
const { isLoggedIn } = auth;
const { selectedAgent, selectedMode, filteredAgents, defaultAgent, allAgents } = agents;

// Agent picker segments
const SEGMENTS = ['personal', 'common', 'private', 'public'] as const;
const agentSegments = computed(() =>
    SEGMENTS
        .map(key => ({
            key,
            agents: filteredAgents.value
                .filter((a: any) => (a.segment ?? 'utility') === key)
                .sort((a: any, b: any) => a.name.localeCompare(b.name)),
        }))
        .filter(s => s.agents.length > 0)
);

function pickAgent(agentId: string, mode: string) {
    selectedAgent.value = agentId;
    selectedMode.value = mode as 'private' | 'public';
    sessionStorage.setItem('agent', agentId);
    sessionStorage.setItem('agent_mode', mode);
    // Update URL with query params so showPicker switches to chat
    router.push({ name: 'agents', query: { agent: agentId, mode } });
    if (ws.connected.value) {
        ws.switchAgent(agentId, mode);
    } else {
        ws.connect(selectedAgent, auth.isLoggedIn, auth.loginError, selectedMode);
    }
}

const agentLogo = computed(() => getAgentLogo(selectedAgent.value));

const { sending, input, messagesEl, scrollToBottom, scrollIfAtBottom, send: _send, onInputChange, navigateHistory, restoreLastSent } = useMessages(wsSend);

const controlsEl = ref<HTMLElement | null>(null);
const spacerEl = ref<HTMLElement | null>(null);
const smState = toRef(chatStore, 'smState');
const channelState = toRef(chatStore, 'channelState');
const connectionState = toRef(chatStore, 'connectionState');
const smLabel = toRef(chatStore, 'smLabel');
// UI hidden when not synced (replaces isSwitching hack)
const isHidden = computed(() => connectionState.value !== 'SYNCED');
const footerHeadline = computed(() => {
    const msgs = groupedVisibleMsgs.value
    const last = msgs[msgs.length - 1]
    return last?.position === 'footer' ? last : null
})

const lastRealMsgIdx = computed(() => {
    const msgs = groupedVisibleMsgs.value
    for (let i = msgs.length - 1; i >= 0; i--) {
        if (msgs[i].type !== 'headline') return i
    }
    return -1
})


const VISIBLE_PAGE = 50;
const visibleCount = ref(VISIBLE_PAGE);

const { groupedVisibleMsgs, hasMore, loadMore, getFormattedAgentName } = useMessageGrouping(
    computed(() => chatStore.messages),
    visibleCount,
    selectedAgent,
    allAgents,
    toRef(chatStore, 'sessionKey'),
);

const sentMessages = new Set<string>();
const lastUsage = ref<null | any>(null);
const pendingClearRef = ref(false);

const { mount, lastSystemMsg, hudTree, hudVersion, getToolsForTurn, hudSnapshot, toolCallMapSnapshot, hasActiveStreamingMessage, sessionHistoryComplete } = useAgentSocket(visibleCount, lastUsage, pendingClearRef, sentMessages, restoreLastSent);

// Expose to devtools / console
if (typeof window !== 'undefined') {
    (window as any).__hudSnapshot = hudSnapshot;
    (window as any).__toolCallMap = toolCallMapSnapshot;
}

const viewActive = computed(() => agentsRoute.name === 'agents');

// --- Scroll logic ---
// On user send: scroll so user message sits at top of viewport.
// During streaming: no auto-scroll — user controls their own viewport.
// On new session (not user send): scroll to bottom.

let userSendInFlight = false;

// Dynamic spacer: just enough to scroll last user msg to viewport top, never more.
// Recalculated on message changes and viewport resize.
const spacerHeight = ref(0);

function getViewport(): HTMLElement | null {
    const el = messagesEl.value;
    if (!el) return null;
    const root = el.$el || el;
    return root.querySelector('[data-overlayscrollbars-viewport]') as HTMLElement | null;
}

// Synchronous spacer recalc — call within rAF for accurate layout measurements.
// Goal: user can scroll last user msg to top of viewport, but NOT scroll past controls.
function recalcSpacerSync(): number {
    const viewport = getViewport();
    if (!viewport) return 0;
    const controls = (controlsEl.value || viewport.querySelector('.msg-controls')) as HTMLElement | null;
    if (!controls) return 0;
    const userMsgs = viewport.querySelectorAll('.message.user');
    const last = userMsgs[userMsgs.length - 1] as HTMLElement;
    if (!last) return 0;
    // Convert viewport-relative rects to scroll-content positions
    const vpRect = viewport.getBoundingClientRect();
    const st = viewport.scrollTop;
    const msgTop = last.getBoundingClientRect().top - vpRect.top + st;
    const ctrlBottom = controls.getBoundingClientRect().bottom - vpRect.top + st;
    // When scrolled so user msg is at top (with 40px breathing room),
    // controls should sit at viewport bottom:
    //   scrollTop = msgTop - 40
    //   visible range = [msgTop-40 .. msgTop-40+vpH]
    //   need ctrlBottom + spacer = msgTop - 40 + vpH
    const vpH = viewport.clientHeight;
    const needed = msgTop - 40 + vpH;
    const h = Math.max(0, needed - ctrlBottom);
    spacerHeight.value = h;
    return h;
}

// Recalc spacer on a simple interval — reactive watchers proved unreliable across HMR
let _spacerInterval: ReturnType<typeof setInterval> | null = null;
onMounted(() => {
    _spacerInterval = setInterval(recalcSpacerSync, 200);
    onUnmounted(() => { if (_spacerInterval) clearInterval(_spacerInterval); });
});

function scrollToUserMsg(smooth = true) {
    // Ensure spacer is sized BEFORE scrolling.
    // Double nextTick: first for Vue DOM update, second for OverlayScrollbars.
    nextTick(() => nextTick(() => {
        recalcSpacerSync();
        // Wait one more tick for Vue to apply the spacerHeight change to DOM
        nextTick(() => {
            const viewport = getViewport();
            if (!viewport) return;
            void viewport.offsetHeight; // force reflow
            const userMsgs = viewport.querySelectorAll('.message.user');
            const last = userMsgs[userMsgs.length - 1] as HTMLElement;
            if (!last) return;
            const vpRect = viewport.getBoundingClientRect();
            const msgRect = last.getBoundingClientRect();
            const offset = viewport.scrollTop + (msgRect.top - vpRect.top) - 40;
            viewport.scrollTo({ top: Math.max(0, offset), behavior: smooth ? 'smooth' : 'instant' });
        });
    }));
}

// Connection SM: when SYNCED, scroll to bottom and fetch previous session
watch(connectionState, (val) => {
    if (!viewActive.value) return;
    if (val === 'SYNCED') {
        if (!prevMessages.value.length) fetchPreviousSession();
        scrollToBottom();
    }
});

// Channel SM: handle agent done
watch(channelState, (val, prev) => {
    if (!viewActive.value) return;
    if (prev === 'AGENT_RUNNING' && (val === 'READY' || val === 'FRESH')) {
        userSendInFlight = false;
    }
    if (val === 'AGENT_RUNNING' && prev !== 'AGENT_RUNNING') {
        if (!userSendInFlight) {
            scrollToBottom();
        }
    }
});

function send() {
    const content = input.value.trim();
    const hasAtt = hasAttachments();
    if (!content && !hasAtt) { triggerShake(); return; }
    chatStore.truncatedWarning = false;
    const ch = channelState.value;
    const conn = connectionState.value;
    if (conn !== 'SYNCED') {
        chatStore.pushSystem('Not connected yet -- please wait.', selectedAgent.value);
        triggerShake();
    } else if (ch === 'READY' || ch === 'FRESH') {
        if (content) sentMessages.add(content);
        userSendInFlight = true;
        const payload = hasAtt ? toPayload() : undefined;
        _send(payload);
        clearAttachments();
        scrollToUserMsg();
    } else if (ch === 'AGENT_RUNNING') {
        chatStore.queuedThought = content;
        input.value = '';
        clearAttachments();
        chatStore.pushSystem('Queued -- will send when agent finishes.', selectedAgent.value);
    } else if (ch === 'NO_SESSION') {
        triggerShake();
    } else {
        triggerShake();
    }
}

// Action handlers that scroll to top for visual feedback
function onNew() {
    chatStore.newSession();
    scrollToBottom(); // after clear, scroll to bottom shows fresh state
}
function onConfirmNew() {
    chatStore.confirmNew();
    scrollToBottom();
}

const { inputEl, isShaking, autoGrow, triggerShake } = useInputAutogrow(input);
const { isAgentRunning } = useAgentDisplay(selectedAgent, defaultAgent, allAgents);

// Attachments
const { attachments, addFiles, removeAttachment, clearAttachments, toPayload, hasAttachments } = useAttachments();
const fileInputEl = ref<HTMLInputElement | null>(null);
const isDragOver = ref(false);

// Audio recorder
const { isRecording, duration, audioLevel, micDenied, startRecording, stopRecording, cancelRecording, formatDuration } = useAudioRecorder();

async function toggleRecording() {
    if (isRecording.value) {
        const file = await stopRecording();
        if (file) addFiles([file]);
    } else {
        await startRecording();
    }
}

function onFileSelect(e: Event) {
    const input = e.target as HTMLInputElement;
    if (input.files?.length) addFiles(input.files);
    input.value = ''; // reset so same file can be re-selected
}

function onPaste(e: ClipboardEvent) {
    const items = e.clipboardData?.files;
    if (items?.length) {
        const media = Array.from(items).filter(f => f.type.startsWith('image/') || f.type.startsWith('audio/'));
        if (media.length) {
            e.preventDefault();
            addFiles(media);
        }
    }
}

// Debug: send a known 10x10 red PNG directly
function sendTestImage() {
    const TEST_PNG_B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFklEQVQYV2P8z8BQz0BhwMgwqpCuCgEAMNwEAVnOp/0AAAAASUVORK5CYII=';
    const testText = input.value.trim() || 'What color is this small square image? Answer with just the color name.';
    input.value = testText;
    // Directly build and send the payload
    const attachmentPayload = [{ type: 'image', mimeType: 'image/png', content: TEST_PNG_B64, fileName: 'test-red-10x10.png' }];
    chatStore.truncatedWarning = false;
    sentMessages.add(testText);
    userSendInFlight = true;
    _send(attachmentPayload);
    scrollToUserMsg();
}

function onDragOver(e: DragEvent) {
    if (e.dataTransfer?.types.includes('Files')) isDragOver.value = true;
}
function onDragLeave() { isDragOver.value = false; }
function onDrop(e: DragEvent) {
    isDragOver.value = false;
    if (e.dataTransfer?.files.length) addFiles(e.dataTransfer.files);
}

watch([selectedAgent, selectedMode], ([agent, mode], [oldAgent, oldMode]) => {
    if (agent !== oldAgent || mode !== oldMode) {
        // Connection SM handles visibility via isHidden (no manual isSwitching needed)
        sessionStorage.setItem('agent', agent);
        lastUsage.value = null;
        sentMessages.clear();
        prevSessions.value = [];
        prevHasMore.value = false;
        prevSkip.value = 0;
        chatStore.resetLocalSession();
        // ws.switchAgent called explicitly by sidebar handleRoomClick
    }
});

onMounted(() => {
    chatStore.setWsSend(wsSend);
    const unsubscribe = mount();
    // Fetch previous session if already synced (e.g. HMR reload)
    if (connectionState.value === 'SYNCED') fetchPreviousSession();
    // Recalc spacer on viewport resize
    const viewport = getViewport();
    let ro: ResizeObserver | null = null;
    if (viewport) {
        ro = new ResizeObserver(() => recalcSpacerSync());
        ro.observe(viewport);
    }
    recalcSpacerSync();
    onUnmounted(() => { unsubscribe(); ro?.disconnect(); });
});
</script>

<style scoped>
/* Hide messages during agent switch to prevent scroll flicker */
.messages.is-switching { opacity: 0; }

/* Agent picker (no agent selected) */
.agent-picker {
    flex: 1;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: 2rem 1rem;
    overflow-y: auto;
}
.agent-picker-content {
    width: 100%;
    max-width: 400px;
}
.agent-picker-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text);
    margin-bottom: 1rem;
}
.agent-picker-segment {
    margin-bottom: 1rem;
}
.agent-picker-segment-label {
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-dim);
    opacity: 0.5;
    padding: 0 0.5rem 0.25rem;
}
.agent-picker-row {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}
.agent-picker-btn {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.4rem 0.5rem;
    border: none;
    background: none;
    color: var(--text);
    cursor: pointer;
    border-radius: 6px;
    transition: background 0.15s;
    font-size: var(--text-base);
}
.agent-picker-btn:hover {
    background: var(--hover-bg, rgba(255,255,255,0.05));
}
.agent-picker-name {
    font-weight: 500;
}
.agent-picker-modes {
    display: flex;
    gap: 2px;
    flex-shrink: 0;
}
.agent-picker-mode {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: none;
    color: var(--text-dim);
    cursor: pointer;
    border-radius: 6px;
    transition: background 0.15s, color 0.15s;
    opacity: 0.5;
}
.agent-picker-mode:hover {
    opacity: 1;
    background: var(--hover-bg, rgba(255,255,255,0.05));
    color: var(--text);
}

/* Agent selection + header — layout now in Tailwind classes */
.default-agent-btn { background: none; border: none; color: var(--text-dim); cursor: pointer; padding: 0; opacity: 0.6; transition: color 0.15s, opacity 0.15s; }
.default-agent-btn:hover { opacity: 1; color: var(--text); }
#agent-select { outline: none; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); color: var(--text); font-weight: 600; cursor: pointer; padding: 0.2rem 1.5rem 0.2rem 0.7rem; appearance: none; -webkit-appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 16 16'%3E%3Cpath d='M4 6l4 4 4-4' stroke='%23888' stroke-width='1.5' stroke-linecap='round' fill='none'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 0.5rem center; transition: border-color 0.15s; }
#agent-select:focus { outline: none; box-shadow: none; border-color: var(--focus); }
#agent-select option { background: var(--bg); color: var(--text); }



.input-toolbar { display: flex; align-items: center; justify-content: flex-end; }
.truncated-banner {
  margin: 0 12px 8px;
  padding: 8px 12px;
  background: rgba(234, 179, 8, 0.12);
  border: 1px solid rgba(234, 179, 8, 0.35);
  border-radius: 8px;
  color: #fbbf24;
  line-height: 1.4;
}
.send-btn {
  width: 32px;
  height: 32px;
  min-width: 32px;
  min-height: 32px;
  flex-shrink: 0;
  align-self: flex-end;
  margin-bottom: 1px;
  border-radius: 50%;
  border: none;
  background: var(--send-btn-bg, var(--accent));
  color: var(--send-btn-color, white);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.15s, opacity 0.15s;
  padding: 0;
}
.send-btn svg { display: block; }
.send-btn:hover:not(:disabled) { filter: brightness(1.1); }
.send-btn:disabled { opacity: 0.25; cursor: not-allowed; background: var(--muted); }

/* Controls: right after last message, always nearby */
.msg-controls {
  flex: 0 0 auto;
  display: flex;
  justify-content: center;
  padding: 8px 0;
}


/* Stop button — subtle, next to send */
.stop-btn {
  width: 28px;
  height: 28px;
  flex-shrink: 0;
  align-self: flex-end;
  margin-bottom: 3px;
  border-radius: 6px;
  border: none;
  background: transparent;
  color: var(--text-dim);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.15s, background 0.15s;
  padding: 0;
  opacity: 0.6;
}
.stop-btn:hover:not(:disabled) { opacity: 1; color: var(--text); background: var(--hover-bg, rgba(255,255,255,0.05)); }
.stop-btn:disabled { opacity: 0.2; cursor: not-allowed; }
.sm-status-bar { display: flex; align-items: center; gap: 0.4rem; padding: 0.1rem 0 0.1rem 0.75rem; }
.sm-dot { width: 6px; height: 6px; border-radius: 50%; background: #64748b; flex-shrink: 0; }
.sm-dot.AGENT_RUNNING, .sm-dot.STOP_PENDING { background: #3b82f6; box-shadow: 0 0 6px #3b82f6; animation: pulse 2s infinite; }
.sm-dot.HANDOVER_PENDING { background: #f59e0b; }
.sm-dot.IDLE { background: #22c55e; }
.sm-dot.ERROR { background: #ef4444; }
.sm-dot.NO_SESSION { background: #f59e0b; animation: pulse 2s infinite; }
/* --- Previous sessions (server-fetched) --- */
.prev-load-more {
    display: block;
    margin: 4px auto 8px;
    padding: 4px 16px;
    font-size: 0.72rem;
    color: var(--text-dim);
    background: none;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    cursor: pointer;
    opacity: 0.6;
    transition: opacity 0.15s, border-color 0.15s;
}
.prev-load-more:hover:not(:disabled) { opacity: 1; border-color: var(--accent); }
.prev-load-more:disabled { cursor: default; }
.prev-session-header {
    text-align: center;
    font-size: 0.72rem;
    color: var(--text-dim);
    opacity: 0.5;
    padding: 8px 0 4px;
    user-select: none;
}
.prev-session-wrapper {
    opacity: 0.6;
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.session-divider {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 0;
}
.session-divider::before,
.session-divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: var(--border);
}
.session-divider-text {
    font-size: 0.7rem;
    color: var(--text-dim);
    opacity: 0.5;
    white-space: nowrap;
    user-select: none;
}

.no-session-center {
  text-align: center;
  font-weight: 700;
  color: var(--text-dim);
  opacity: 0.45;
  padding: 1.5rem 0;
}
.session-context-badge {
  display: flex;
  align-self: center;
  max-width: 85%;
  padding: 0.35rem 0.75rem;
  margin: -0.25rem 0;
  background: rgba(219, 39, 119, 0.08);
  border: 1px solid rgba(219, 39, 119, 0.25);
  border-radius: 8px;
}
.session-context-text {
  font-size: 0.75rem;
  font-weight: 500;
  color: rgba(219, 39, 119, 0.7);
  line-height: 1.3;
}
.sm-status-label { font-weight: 600; color: var(--text-dim); }
@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.4; } 100% { opacity: 1; } }

.load-more-btn { 
  align-self: center;
  margin-bottom: 0.25rem;
  background: var(--bg-dim);
  border: 1px solid var(--border);
  color: var(--text-dim);
  padding: 0.4rem 1rem;
  border-radius: 20px;
  cursor: pointer;
}

/* Mobile: larger touch targets */
@media (max-width: 480px) {
  .send-btn {
    width: 44px;
    height: 44px;
    min-width: 44px;
    min-height: 44px;
  }
}

/* --- Attachment UI --- */
.attach-btn {
  width: 32px;
  height: 32px;
  min-width: 32px;
  min-height: 32px;
  flex-shrink: 0;
  align-self: flex-end;
  margin-bottom: 1px;
  border-radius: 50%;
  border: none;
  background: transparent;
  color: var(--text-dim);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.15s;
  padding: 0;
}
.attach-btn:hover { color: var(--text); }

.attachment-strip {
  display: flex;
  gap: 6px;
  padding: 6px 4px 2px;
  overflow-x: auto;
  flex-shrink: 0;
}
.attachment-thumb {
  position: relative;
  width: 56px;
  height: 56px;
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid var(--border);
}
.attachment-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.remove-att {
  position: absolute;
  top: 1px;
  right: 1px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: none;
  background: rgba(0,0,0,0.6);
  color: #fff;
  font-size: 12px;
  line-height: 1;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
.remove-att:hover { background: rgba(239,68,68,0.8); }

.input-box.drag-over {
  outline: 2px dashed var(--accent);
  outline-offset: -2px;
  background: rgba(59,130,246,0.05);
}

.hidden { display: none; }

/* --- Mic button --- */
.mic-btn {
  width: 32px;
  height: 32px;
  min-width: 32px;
  min-height: 32px;
  flex-shrink: 0;
  align-self: flex-end;
  margin-bottom: 1px;
  border-radius: 50%;
  border: none;
  background: transparent;
  color: var(--text-dim);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.15s, background 0.15s;
  padding: 0;
}
.mic-btn:hover { color: var(--text); }
.mic-btn.recording {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.12);
  animation: pulse-mic 1.2s infinite;
}
@keyframes pulse-mic {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* --- Mic denied hint --- */
.mic-denied-hint {
  padding: 6px 12px;
  font-size: 0.78rem;
  color: #e06c75;
  background: rgba(224, 108, 117, 0.1);
  border-radius: 8px 8px 0 0;
  text-align: center;
  animation: fadeInOut 5s ease-in-out forwards;
}
@keyframes fadeInOut { 0% { opacity: 0; } 10% { opacity: 1; } 80% { opacity: 1; } 100% { opacity: 0; } }

/* --- Recording indicator --- */
.recording-strip {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 10px 2px;
  flex-shrink: 0;
}
.rec-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ef4444;
  flex-shrink: 0;
  animation: pulse-mic 1s infinite;
}
.rec-level-bar {
  flex: 1;
  height: 4px;
  background: rgba(239, 68, 68, 0.15);
  border-radius: 2px;
  overflow: hidden;
  max-width: 120px;
}
.rec-level-fill {
  height: 100%;
  background: #ef4444;
  border-radius: 2px;
  transition: width 0.08s linear;
}
.rec-time {
  font-size: 0.8rem;
  font-weight: 600;
  color: #ef4444;
  font-variant-numeric: tabular-nums;
}
.rec-cancel {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: none;
  background: rgba(239, 68, 68, 0.15);
  color: #ef4444;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
.rec-cancel:hover { background: rgba(239, 68, 68, 0.3); }

/* --- Audio attachment thumb --- */
.attachment-thumb.audio-thumb {
  width: auto;
  min-width: 56px;
  max-width: 160px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 0 8px;
  background: var(--surface);
}
.audio-icon {
  font-size: 1.1rem;
  opacity: 0.6;
}
.audio-name {
  font-size: 0.65rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--text-dim);
}
</style>
