import { create } from 'zustand'; import { api } from '../lib/api.ts'; export type ChannelType = 'text' | 'voice'; export interface Channel { id: string; serverId: string; name: string; type: ChannelType; category: string | null; position: number; } interface ChannelState { channelsByServer: Record; activeChannelId: string | null; isLoading: boolean; error: string | null; fetchChannels: (serverId: string) => Promise; setActiveChannel: (id: string | null) => void; addChannel: (channel: Channel) => void; updateChannel: (channel: Channel) => void; removeChannel: (id: string) => void; } export const useChannelStore = create((set) => ({ channelsByServer: {}, activeChannelId: null, isLoading: false, error: null, fetchChannels: async (serverId) => { set({ isLoading: true, error: null }); try { const channels = await api.get(`/servers/${serverId}/channels`); set((state) => ({ channelsByServer: { ...state.channelsByServer, [serverId]: channels }, isLoading: false, })); } catch (error) { set({ isLoading: false, error: error instanceof Error ? error.message : 'Failed to fetch channels', }); } }, setActiveChannel: (id) => set({ activeChannelId: id }), addChannel: (channel) => set((state) => { const list = state.channelsByServer[channel.serverId] || []; return { channelsByServer: { ...state.channelsByServer, [channel.serverId]: [...list, channel], }, }; }), updateChannel: (channel) => set((state) => { const list = state.channelsByServer[channel.serverId] || []; return { channelsByServer: { ...state.channelsByServer, [channel.serverId]: list.map((c) => (c.id === channel.id ? channel : c)), }, }; }), removeChannel: (id) => set((state) => { const next: Record = {}; for (const serverId of Object.keys(state.channelsByServer)) { next[serverId] = state.channelsByServer[serverId].filter((c) => c.id !== id); } return { channelsByServer: next, activeChannelId: state.activeChannelId === id ? null : state.activeChannelId, }; }), }));