import { useState, useEffect } from 'react'; import type { Conversation } from '../types'; export const useConversations = () => { const [conversations, setConversations] = useState([]); const [loading, setLoading] = useState(true); // Cargar conversaciones del localStorage (temporal hasta tener backend) useEffect(() => { loadConversations(); }, []); const loadConversations = () => { try { const stored = localStorage.getItem('conversations'); if (stored) { const parsed = JSON.parse(stored); setConversations(parsed.map((c: any) => ({ ...c, createdAt: new Date(c.createdAt), updatedAt: new Date(c.updatedAt), }))); } } catch (error) { console.error('Error loading conversations:', error); } finally { setLoading(false); } }; const createConversation = (firstMessage: string): Conversation => { // Generar título del chat basado en el primer mensaje (máximo 50 caracteres) const title = firstMessage.length > 50 ? firstMessage.substring(0, 47) + '...' : firstMessage; const newConversation: Conversation = { id: `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, title, createdAt: new Date(), updatedAt: new Date(), messageCount: 1, }; const updated = [newConversation, ...conversations]; setConversations(updated); saveConversations(updated); return newConversation; }; const updateConversationTitle = (id: string, newTitle: string) => { const updated = conversations.map(conv => conv.id === id ? { ...conv, title: newTitle, updatedAt: new Date() } : conv ); setConversations(updated); saveConversations(updated); }; const deleteConversation = (id: string) => { const updated = conversations.filter(conv => conv.id !== id); setConversations(updated); saveConversations(updated); // También eliminar mensajes asociados localStorage.removeItem(`messages_${id}`); }; const saveConversations = (convs: Conversation[]) => { localStorage.setItem('conversations', JSON.stringify(convs)); }; return { conversations, loading, createConversation, updateConversationTitle, deleteConversation, refreshConversations: loadConversations, }; };