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

export type LayoutMode = 'top' | 'sidebar';

/**
 * Row height in tables. Officers who work a queue all day want more rows per
 * screen; occasional users want the breathing room.
 */
export type Density = 'comfortable' | 'compact';

interface PreferencesState {
  layoutMode: LayoutMode;
  density: Density;
}

const PREFERENCES_KEY = 'ema-backoffice-preferences';

const loadPreferences = (): PreferencesState => {
  try {
    const stored = localStorage.getItem(PREFERENCES_KEY);
    if (stored) {
      // Merge over the defaults so a preferences blob written before a new
      // key existed does not come back with that key undefined.
      return { layoutMode: 'sidebar', density: 'comfortable', ...JSON.parse(stored) };
    }
  } catch {
    // Corrupt or unavailable storage (private mode) — fall through to the default.
  }
  // The sidebar is the grouped, scannable layout; the top strip puts all
  // ~20 destinations in one horizontally-scrolling row.
  return { layoutMode: 'sidebar', density: 'comfortable' };
};

const savePreferences = (state: PreferencesState) => {
  try {
    localStorage.setItem(PREFERENCES_KEY, JSON.stringify(state));
  } catch {
    // Storage full or unavailable — the preference just will not persist.
  }
};

const initialState: PreferencesState = loadPreferences();

const preferencesSlice = createSlice({
  name: 'preferences',
  initialState,
  reducers: {
    setLayoutMode(state, action: PayloadAction<LayoutMode>) {
      state.layoutMode = action.payload;
      savePreferences(state);
    },
    setDensity(state, action: PayloadAction<Density>) {
      state.density = action.payload;
      savePreferences(state);
    },
  },
});

export const { setLayoutMode, setDensity } = preferencesSlice.actions;
export const preferencesReducer = preferencesSlice.reducer;
