import { defineStore } from "pinia";

export const useStore = defineStore("maindev", {
  state: () => ({
    viewport: undefined,
    login: undefined,
    dealer: undefined,
    token: undefined,
    common: undefined,
    settings: [],
    showmodal: undefined,
    snackbar: undefined,
    productdocument: undefined,
    applicationstatus: undefined,
    applicationproduct: undefined,
    lastlegendfiltertab: 'Giỏ hàng',
    layersetting: undefined,
    country: undefined,
    lang: "vi",
    branch: {},
    rights: [],
    product: [],
    cart: [],
    selectedPaymentSchedulesForEmailInDue: [],
    selectedPaymentSchedulesForEmailInOverdue: [],
    selectedProductsForHandoverEmail: [],
  }),
  
  actions: {
    commit(name, data) {
      this[name] = data;
    },
    
    removeSnackbar() {
      this.snackbar = undefined;
    },
    
    updateProduct(products) {
      this.product = products;
    },
    
    updateCart(carts) {
      this.cart = carts;
    },
    
    updateSingleProduct(updatedProduct) {
      const index = this.product.findIndex(p => p.id === updatedProduct.id);
      if (index !== -1) {
        this.product[index] = updatedProduct;
      } else {
        this.product.push(updatedProduct);
      }
    },
    
    removeProduct(productId) {
      this.product = this.product.filter(p => p.id !== productId);
    },
  },
  
  persist: {
    pick: [
      "token", 
      "login", 
      "lang", 
      "dealer", 
      "lastlegendfiltertab", 
      "layersetting"
    ],
    storage: piniaPluginPersistedstate.localStorage(),
  },
});