import $ from "jquery";
import select2 from "select2";
import { createSelect2Config } from "../config/select2Config.js";
import { universalHandler } from "../handlers/universalHandler.js";

function getFieldNames(module) {
  const moduleMapping = {
    power_widget: {
      selectedProducts: "firevert_power_widget_products_selected[]",
      excludedProducts: "firevert_power_widget_products_excluded[]",
    },
    promo_time_widget: {
      selectedProducts: "firevert_promo_time_widget_selected_products[]",
      excludedProducts: "firevert_promo_time_widget_excluded_products[]",
    },
    spectator_views: {
      selectedProducts: "firevert_spectator_views_selected_products[]",
      excludedProducts: "firevert_spectator_views_excluded_products[]",
    },
  };

  return moduleMapping[module] || {};
}

export default function productsSelect() {
  const form = $(".firevert-form");
  const module = form.data("module");

  if (!module) {
    console.warn("No data-module attribute found on form");
    return;
  }

  const fieldNames = getFieldNames(module);

  const select2Config = createSelect2Config(
    "/wp-json/firevert/v1/core/products",
    form.data("search-products-placeholder")
  );

  $("select.firevert-select2-exclude-products").select2(select2Config);
  $("select.firevert-select2-selected-products").select2(select2Config);

  if (fieldNames.selectedProducts) {
    universalHandler({
      addButtonSelector: ".add-selected-product",
      selectSelector: ".firevert-select2-selected-products",
      repeaterSelector: "#selected-products-repeater",
      inputName: fieldNames.selectedProducts,
      containerSelector: "#add-selected-product-container",
      removeButtonSelector: ".remove-selected-product",
    });
  }

  if (fieldNames.excludedProducts) {
    universalHandler({
      addButtonSelector: ".add-excluded-product",
      selectSelector: ".firevert-select2-exclude-products",
      repeaterSelector: "#excluded-products-repeater",
      inputName: fieldNames.excludedProducts,
      containerSelector: "#add-excluded-product-container",
      removeButtonSelector: ".remove-excluded-product",
    });
  }
}
