/**
 * store.ts — Shared singleton state
 *
 * Singleton composables that need a single instance across all views.
 * All chat/session state lives in store/chat.ts (Pinia).
 */

import { ref, reactive } from 'vue';
import { useWebSocket } from './composables/ws';
import { useAgents } from './composables/agents';
import { useAuth } from './composables/auth';
import { useViewerStore } from './store/viewer';

// Viewer last-selected path — reactive singleton so App.vue nav link stays current
export const lastViewerPath = ref(localStorage.getItem('viewer_last_path') || '');

// Viewer tree open-state — Set of paths that are currently expanded
// In-memory only; survives tab switches, resets on full page reload
export const viewerOpenDirs = reactive(new Set<string>());

// WebSocket — single connection shared across all views
export const ws = useWebSocket();

// Takeover (capture, breakout, commands) — singleton via ws
export const takeover = ws.getTakeover();

// Agents — depends on ws.connected
export const agents = useAgents(ws.connected);
agents.setCurrentUser(ws.currentUser);

// Auth — on login, connect WS (sends auth — BE returns agent list even without agent selected)
export const auth = useAuth(() => {
    ws.connect(agents.selectedAgent, auth.isLoggedIn, auth.loginError, agents.selectedMode);
    // Pre-warm viewer token in background so agent→viewer is instant
    useViewerStore().acquire();
});

// Re-export viewer store accessor for use in views
export { useViewerStore };
