/**
 * Constructor Redux Slice
 *
 * Manages persistent UI state for the tour constructor.
 * This state persists across navigation, so users return to their
 * previous editor configuration.
 *
 * Note: Page data and elements are NOT stored here - they use
 * React Query for caching. This slice only handles UI preferences.
 */

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type {
  EditorMenuItem,
  EditorTab,
  ConstructorState,
} from '../../types/constructor';

// ============================================================================
// Initial State
// ============================================================================

const initialState: ConstructorState = {
  editorTab: 'general',
  isMenuOpen: true,
  isEditorCollapsed: false,
  selectedMenuItem: 'none',
  lastActivePageId: {},
  isSidebarCollapsed: false,
};

// ============================================================================
// Slice
// ============================================================================

const constructorSlice = createSlice({
  name: 'constructor',
  initialState,
  reducers: {
    /**
     * Set the active editor tab
     */
    setEditorTab: (state, action: PayloadAction<EditorTab>) => {
      state.editorTab = action.payload;
    },

    /**
     * Toggle or set menu open state
     */
    setMenuOpen: (state, action: PayloadAction<boolean>) => {
      state.isMenuOpen = action.payload;
    },

    /**
     * Toggle or set editor collapsed state
     */
    setEditorCollapsed: (state, action: PayloadAction<boolean>) => {
      state.isEditorCollapsed = action.payload;
    },

    /**
     * Set the selected menu item
     */
    setSelectedMenuItem: (state, action: PayloadAction<EditorMenuItem>) => {
      state.selectedMenuItem = action.payload;
    },

    /**
     * Remember the last active page for a project
     */
    setLastActivePageId: (
      state,
      action: PayloadAction<{ projectId: string; pageId: string }>,
    ) => {
      state.lastActivePageId[action.payload.projectId] = action.payload.pageId;
    },

    /**
     * Toggle or set sidebar collapsed state
     */
    setSidebarCollapsed: (state, action: PayloadAction<boolean>) => {
      state.isSidebarCollapsed = action.payload;
    },

    /**
     * Reset constructor state (e.g., when switching projects)
     */
    resetConstructorUI: (state) => {
      state.editorTab = 'general';
      state.selectedMenuItem = 'none';
      state.isEditorCollapsed = false;
    },
  },
});

// ============================================================================
// Exports
// ============================================================================

export const {
  setEditorTab,
  setMenuOpen,
  setEditorCollapsed,
  setSelectedMenuItem,
  setLastActivePageId,
  setSidebarCollapsed,
  resetConstructorUI,
} = constructorSlice.actions;

export default constructorSlice.reducer;
