llmApp.directive("bsArray", [
  "DescParamsService",
  "PLUGIN_PATHS",
  function (DescParamsService, PLUGIN_PATHS) {
    return {
      restrict: "E",
      scope: {
        config: "=",
        configProperty: "@",
        description: "@",
        allowWrap: "<",
        width: "@",
        labelButton: "@",
        fieldRequired: "<",
        formName: "=",
        labelText: "@",
        validationMessage: "@",
      },
      templateUrl: PLUGIN_PATHS.WEBAPP + "bs-array-template.html",
      controller: [
        "$scope",
        function ($scope) {
          $scope.isDragging = {};

          // Helper function to check if array is empty or contains only empty strings
          $scope.isArrayEmpty = function () {
            if (
              !$scope.config[$scope.configProperty] ||
              $scope.config[$scope.configProperty].length === 0
            ) {
              return true;
            }
            // Check if all items are empty strings
            return $scope.config[$scope.configProperty].every(function (item) {
              return !item || item.trim() === "";
            });
          };

          //get default array from params
          if (!$scope.config[$scope.configProperty]) {
            const defaultValue = DescParamsService.getDefaultValue(
              $scope.configProperty
            );

            //if we've found a default value
            if (defaultValue) {
              //Use angular.copy() to create a new, independent array
              $scope.config[$scope.configProperty] = angular.copy(defaultValue);
            } else {
              $scope.config[$scope.configProperty] = [];
            }
          }

          // Initialize validation model
          $scope.arrayValidationModel = $scope.isArrayEmpty() ? "" : "valid";

          // Watch for validation updates
          $scope.$watch(
            function () {
              return $scope.config
                ? $scope.config[$scope.configProperty]
                : undefined;
            },
            function () {
              // Update validation model whenever array changes
              $scope.arrayValidationModel = $scope.isArrayEmpty()
                ? ""
                : "valid";
            },
            true
          );

          // Add a new empty feedback option
          $scope.addItem = function () {
            //Fallback option
            if (!$scope.config[$scope.configProperty]) {
              $scope.config[$scope.configProperty] = [];
            }
            $scope.config[$scope.configProperty].push("");
          };

          // Remove a feedback option
          $scope.removeItem = function (index) {
            $scope.config[$scope.configProperty].splice(index, 1);
          };
        },
      ],
    };
  },
]);
