// redux/slices/polylineContextMenuSlice.js
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  isOpen: false,
  position: null,
  forceClose: false,
  timerStart: null,
  countdown: 20,
  countdownActive: false, // **Neu: Redux merkt, ob der Timer aktiv ist**
};

const polylineContextMenuSlice = createSlice({
  name: "polylineContextMenu",
  initialState,
  reducers: {
    openPolylineContextMenu: (state, action) => {
      state.isOpen = true;
      state.position = { lat: action.payload.position.lat, lng: action.payload.position.lng };
      state.forceClose = false;
      state.timerStart = Date.now();
      state.countdown = 20;
      state.countdownActive = true; // **Timer aktiv setzen**
    },
    closePolylineContextMenu: (state) => {
      state.isOpen = false;
      state.position = null;
      state.timerStart = null;
      state.countdown = 0;
      state.countdownActive = false; // **Timer stoppen**
    },
    updateCountdown: (state) => {
      if (state.timerStart && state.countdownActive) {
        const elapsedTime = (Date.now() - state.timerStart) / 1000;
        state.countdown = Math.max(20 - elapsedTime, 0);

        if (state.countdown <= 2) {
          state.isOpen = false;
          state.position = null;
          state.countdownActive = false;
        }
      }
    },
    forceCloseContextMenu: (state) => {
      state.isOpen = false;
      state.position = null;
      state.forceClose = true;
      state.timerStart = null;
      state.countdown = 0;
      state.countdownActive = false;
    },
  },
});

export const { openPolylineContextMenu, closePolylineContextMenu, updateCountdown, forceCloseContextMenu } = polylineContextMenuSlice.actions;
export default polylineContextMenuSlice.reducer;
