// [DEF:assistantChat:Store]
// @TIER: STANDARD
// @SEMANTICS: assistant, store, ui-state, conversation
// @PURPOSE: Control assistant chat panel visibility and active conversation binding.
// @LAYER: UI
// @RELATION: BINDS_TO -> AssistantChatPanel
// @INVARIANT: conversationId persists while panel toggles unless explicitly reset.
//
// @UX_STATE: Closed -> Panel hidden.
// @UX_STATE: Open -> Panel visible and interactive.

import { writable } from 'svelte/store';

const initialState = {
  isOpen: false,
  conversationId: null,
};

export const assistantChatStore = writable(initialState);

// [DEF:toggleAssistantChat:Function]
// @PURPOSE: Toggle assistant panel visibility.
// @PRE: Store is initialized.
// @POST: isOpen value inverted.
export function toggleAssistantChat() {
  assistantChatStore.update((state) => {
    const next = { ...state, isOpen: !state.isOpen };
    console.log(`[assistantChat][${next.isOpen ? 'Open' : 'Closed'}] toggleAssistantChat`);
    return next;
  });
}
// [/DEF:toggleAssistantChat:Function]

// [DEF:openAssistantChat:Function]
// @PURPOSE: Open assistant panel.
// @PRE: Store is initialized.
// @POST: isOpen = true.
export function openAssistantChat() {
  assistantChatStore.update((state) => {
    const next = { ...state, isOpen: true };
    console.log('[assistantChat][Open] openAssistantChat');
    return next;
  });
}
// [/DEF:openAssistantChat:Function]

// [DEF:closeAssistantChat:Function]
// @PURPOSE: Close assistant panel.
// @PRE: Store is initialized.
// @POST: isOpen = false.
export function closeAssistantChat() {
  assistantChatStore.update((state) => {
    const next = { ...state, isOpen: false };
    console.log('[assistantChat][Closed] closeAssistantChat');
    return next;
  });
}
// [/DEF:closeAssistantChat:Function]

// [DEF:setAssistantConversationId:Function]
// @PURPOSE: Bind current conversation id in UI state.
// @PRE: conversationId is string-like identifier.
// @POST: store.conversationId updated.
export function setAssistantConversationId(conversationId) {
  assistantChatStore.update((state) => {
    console.log('[assistantChat][ConversationBound] setAssistantConversationId');
    return { ...state, conversationId };
  });
}
// [/DEF:setAssistantConversationId:Function]
// [/DEF:assistantChat:Store]
