/** * Chat Storage Service * Manages chat list in localStorage for widget persistence */ import { ChatListItem } from '../types/api'; const STORAGE_KEY = 'bcx_chat_list'; const MAX_CHATS = 50; // Maximum number of chats to store export class ChatStorageService { /** * Get all chats from localStorage */ static getChats(): ChatListItem[] { try { const stored = localStorage.getItem(STORAGE_KEY); if (!stored) { return []; } const chats = JSON.parse(stored) as ChatListItem[]; // Sort by timestamp (newest first) return chats.sort((a, b) => new Date(b.lastMessageTimestamp).getTime() - new Date(a.lastMessageTimestamp).getTime()); } catch (error) { console.error('[ChatStorage] Error reading chats from localStorage:', error); return []; } } /** * Save or update a chat in localStorage */ static saveChat(chatId: string, lastMessage: string, lastMessageTimestamp: string): void { try { const chats = this.getChats(); // Find existing chat const existingIndex = chats.findIndex(chat => chat.chatId === chatId); const chatItem: ChatListItem = { chatId, lastMessage, lastMessageTimestamp, }; if (existingIndex >= 0) { // Update existing chat chats[existingIndex] = chatItem; } else { // Add new chat at the beginning chats.unshift(chatItem); } // Limit to MAX_CHATS if (chats.length > MAX_CHATS) { chats.splice(MAX_CHATS); } // Sort by timestamp (newest first) chats.sort((a, b) => new Date(b.lastMessageTimestamp).getTime() - new Date(a.lastMessageTimestamp).getTime()); localStorage.setItem(STORAGE_KEY, JSON.stringify(chats)); } catch (error) { console.error('[ChatStorage] Error saving chat to localStorage:', error); } } /** * Get a specific chat by ID */ static getChat(chatId: string): ChatListItem | null { const chats = this.getChats(); return chats.find(chat => chat.chatId === chatId) || null; } /** * Remove a chat from localStorage */ static removeChat(chatId: string): void { try { const chats = this.getChats(); const filtered = chats.filter(chat => chat.chatId !== chatId); localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered)); } catch (error) { console.error('[ChatStorage] Error removing chat from localStorage:', error); } } /** * Clear all chats from localStorage */ static clearAll(): void { try { localStorage.removeItem(STORAGE_KEY); } catch (error) { console.error('[ChatStorage] Error clearing chats from localStorage:', error); } } }