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: {
      selectedCategories: "firevert_power_widget_products_categories[]",
      excludedCategories:
        "firevert_power_widget_products_excluded_categories[]",
    },
    promo_time_widget: {
      selectedCategories: "firevert_promo_time_widget_product_categories[]",
      excludedCategories: "firevert_promo_time_widget_excluded_categories[]",
    },
    spectator_views: {
      selectedCategories: "firevert_spectator_views_product_categories[]",
      excludedCategories: "firevert_spectator_views_excluded_categories[]",
    },
  };

  return moduleMapping[module] || {};
}

export default function categoriesSelect() {
  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 categoriesSelect2Config = createSelect2Config(
    "/wp-json/firevert/v1/core/product_categories",
    form.data("search-categories-placeholder")
  );

  $("select.firevert-select2-selected-categories").select2(
    categoriesSelect2Config
  );
  $("select.firevert-select2-excluded-categories").select2(
    categoriesSelect2Config
  );

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

  if (fieldNames.excludedCategories) {
    universalHandler({
      addButtonSelector: ".add-excluded-category",
      selectSelector: ".firevert-select2-excluded-categories",
      repeaterSelector: "#excluded-categories-repeater",
      inputName: fieldNames.excludedCategories,
      containerSelector: "#add-excluded-category-container",
      removeButtonSelector: ".remove-excluded-category",
    });
  }
}
