// stores/antreanMasukScreenStore.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useAntreanMasukScreenStore = defineStore('antreanMasukScreen', () => {
  // Initial antrean masuk screen items data
  const antreanMasukScreenItems = ref([
    {
      id: 1,
      namaScreen: "Layar Antrean Masuk 1",
      nomorScreen: "AM-001",
      loket: [1, 2], // Array of loket IDs
    },
    {
      id: 2,
      namaScreen: "Layar Antrean Masuk 2",
      nomorScreen: "AM-002",
      loket: [3, 4],
    },
  ]);

  // Computed
  const getAntreanMasukScreenById = (id) => {
    return computed(() => {
      const targetId = Number(id);
      return antreanMasukScreenItems.value.find((s) => Number(s.id) === targetId);
    });
  };

  const getAllAntreanMasukScreens = computed(() => antreanMasukScreenItems.value);

  // Actions
  const addAntreanMasukScreen = (screenPayload) => {
    // Ensure we get a valid ID even if antreanMasukScreenItems is empty
    const maxId = antreanMasukScreenItems.value.length > 0 
      ? Math.max(...antreanMasukScreenItems.value.map(s => s.id), 0) 
      : 0;
    const newId = maxId + 1;
    // Pastikan id baru tidak tertimpa payload (payload.id bisa null)
    const newScreen = {
      ...screenPayload,
      id: newId,
    };
    antreanMasukScreenItems.value.push(newScreen);
    return { success: true, message: `Screen ${newScreen.namaScreen} berhasil ditambahkan`, data: newScreen };
  };

  const updateAntreanMasukScreen = (screenPayload) => {
    const index = antreanMasukScreenItems.value.findIndex(s => s.id === screenPayload.id);
    if (index !== -1) {
      antreanMasukScreenItems.value[index] = {
        ...antreanMasukScreenItems.value[index],
        ...screenPayload,
      };
      return { success: true, message: `Konfigurasi ${screenPayload.namaScreen} berhasil disimpan` };
    }
    return { success: false, message: 'Screen tidak ditemukan' };
  };

  const deleteAntreanMasukScreen = (screenId) => {
    const index = antreanMasukScreenItems.value.findIndex(s => s.id === screenId);
    if (index !== -1) {
      const screenName = antreanMasukScreenItems.value[index].namaScreen;
      antreanMasukScreenItems.value.splice(index, 1);
      return { success: true, message: `Screen ${screenName} berhasil dihapus` };
    }
    return { success: false, message: 'Screen tidak ditemukan' };
  };

  return {
    // State
    antreanMasukScreenItems,
    
    // Computed
    getAllAntreanMasukScreens,
    getAntreanMasukScreenById,
    
    // Actions
    addAntreanMasukScreen,
    updateAntreanMasukScreen,
    deleteAntreanMasukScreen,
  };
}, {
  persist: {
    key: 'antrean-masuk-screen-store-state',
    storage: typeof window !== 'undefined' ? localStorage : undefined,
    paths: ['antreanMasukScreenItems'],
  },
});
