import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface UnreadState {
    counts: Record<string, number>;
    /** Group GUID currently open in chat — incoming messages must not count as unread */
    activeGroupId: string | null;
}

const initialState: UnreadState = {
    counts: {},
    activeGroupId: null,
};

const unreadSlice = createSlice({
    name: "unread",
    initialState,
    reducers: {
        setUnreadCounts: (state, action: PayloadAction<Record<string, number>>) => {   
            const next: Record<string, number> = {};
            Object.entries(action.payload || {}).forEach(([key, value]) => {
                const id = String(key || "").replace(/^group_/, "");
                if (!id || typeof value !== "number") return;
                next[id] = Math.max(next[id] || 0, value);
            });
            state.counts = next;
            if (state.activeGroupId) {
                state.counts[state.activeGroupId] = 0;
            }
        },
        incrementUnread: (state, action: PayloadAction<string>) => {
            const groupId = String(action.payload || "").replace(/^group_/, "");
            if (!groupId) return;
            if (state.activeGroupId && String(state.activeGroupId).replace(/^group_/, "") === groupId) {
                state.counts[groupId] = 0;
                delete state.counts[`group_${groupId}`];
                return;
            }
            state.counts[groupId] = (state.counts[groupId] || 0) + 1;
            delete state.counts[`group_${groupId}`];
        },
        resetUnread: (state, action: PayloadAction<string>) => {
            const groupId = String(action.payload || "").replace(/^group_/, "");
            if (!groupId) return;
            state.counts[groupId] = 0;
            delete state.counts[`group_${groupId}`];
        },
        setActiveGroupId: (state, action: PayloadAction<string | null>) => {
            const raw = action.payload ? String(action.payload) : null;
            state.activeGroupId = raw ? raw.replace(/^group_/, "") : null;
            if (state.activeGroupId) {
                state.counts[state.activeGroupId] = 0;
                delete state.counts[`group_${state.activeGroupId}`];
            }
        },
    },
});

export const { setUnreadCounts, incrementUnread, resetUnread, setActiveGroupId } =
    unreadSlice.actions;
export default unreadSlice.reducer;
