import { create } from 'zustand';
import { useWebSocketStore } from './ws';

interface TypingUser {
  userId: string;
  username: string;
  channelId: string;
  timeout: ReturnType<typeof setTimeout>;
}

interface TypingState {
  typingUsers: Record<string, TypingUser[]>;
  sendTypingStart: (channelId: string) => void;
  _handleTypingEvent: (data: { channel_id: string; user_id: string; username: string }) => void;
}

export const useTypingStore = create<TypingState>((set, get) => ({
  typingUsers: {},

  sendTypingStart: (channelId) => {
    const ws = useWebSocketStore.getState();
    if (ws.connected) {
      ws.send({ type: 'TYPING_START', data: { channel_id: channelId } });
    }
  },

  _handleTypingEvent: (data) => {
    const { channel_id, user_id, username } = data;

    const existing = get().typingUsers[channel_id] || [];
    const existingUser = existing.find(u => u.userId === user_id);
    if (existingUser) {
      clearTimeout(existingUser.timeout);
    }

    const timeout = setTimeout(() => {
      set(state => ({
        typingUsers: {
          ...state.typingUsers,
          [channel_id]: (state.typingUsers[channel_id] || []).filter(u => u.userId !== user_id),
        },
      }));
    }, 6000);

    set(state => ({
      typingUsers: {
        ...state.typingUsers,
        [channel_id]: [
          ...(state.typingUsers?.[channel_id] || []).filter((u: { userId: string }) => u.userId !== user_id),
          { userId: user_id, username, channelId: channel_id, timeout },
        ],
      },
    }));
  },
}));
