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

interface SelectedReelIdState {
  id: string | null;           // The ID of the Reel/Post
  share_count: string;
  username?: string;           // Username for profile navigation
  profile_pic?: string;
  user_id?: string;            // ID of the user who owns the Reel
  currentMenu: "more" | "share" | null; 
}

const initialState: SelectedReelIdState = {
  id: null,
  share_count: "0",
  username: undefined,
  profile_pic: undefined,
  user_id: undefined,
  currentMenu: null,
};

const ReelIdSlice = createSlice({
  name: "ReelId",
  initialState,
  reducers: {
    // Standardize the payload to ensure username is captured
    setReelId: (
      state,
      action: PayloadAction<{
        id: string;
        share_count?: number | string;
        username?: string;
        profile_pic?: string;
        user_id?: string;
      }>
    ) => {
      state.id = action.payload.id;
      state.share_count = String(action.payload.share_count ?? "0");
      state.username = action.payload.username;
      state.profile_pic = action.payload.profile_pic;
      state.user_id = action.payload.user_id;
    },

    // Switch between "more" (three dots) and "share" menus
    setMenuType: (state, action: PayloadAction<"more" | "share" | null>) => {
      state.currentMenu = action.payload;
    },

    // Reset state when closing menus or changing views
    clearReelId: (state) => {
      state.id = null;
      state.share_count = "0";
      state.username = undefined;
      state.profile_pic = undefined;
      state.user_id = undefined;
      state.currentMenu = null;
    },

    incrementShareCount: (state) => {
      const currentCount = parseInt(state.share_count || "0", 10);
      state.share_count = String(currentCount + 1);
    },

    setShareCount: (state, action: PayloadAction<number | string>) => {
      state.share_count = String(action.payload);
    },
  },
});

export const {
  setReelId,
  setMenuType,
  clearReelId,
  incrementShareCount,
  setShareCount,
} = ReelIdSlice.actions;

export default ReelIdSlice.reducer;