var WPFormsPersianSms =
  window.WPFormsPersianSms ||
  (function (document, window, $, l10n) {
    /**
     * Elements holder.
     *
     * @type {Object}
     */
    const el = {};

    /**
     * Runtime variables.
     *
     * @type {Object}
     */
    const vars = {
      patternBasedProviders: [
        "sms_payamak_pattern",
        "melipayamak_pattern",
        "kavenegar_pattern",
        "farazsms_pattern",
        "ippanel_pattern",
      ],
      singleRecipientProviders: [
        "sms_payamak_pattern",
        "melipayamak_pattern",
        "kavenegar_pattern",
        "ippanel_pattern",
      ],
      apiKeyProviders: [
        "kavenegar",
        "kavenegar_pattern",
        "sms_payamak_new",
        "sms_payamak_pattern",
        "ippanel_pattern",
        "pars_green",
      ],
    };

    /**
     * Public functions and properties.
     */
    const app = {
      /**
       * Start the engine.
       */
      init() {
        $(app.ready);
      },

      /**
       * Document ready.
       */
      ready() {
        app.setup();
        app.bindEvents();
        app.initializeFields();
      },

      /**
       * Setup. Prepare some variables.
       */
      setup() {
        // Cache DOM elements.
        el.$document = $(document);
        el.$body = $("body");
        el.$smsEnable = $('.wpforms-persian-sms-enable input[type="checkbox"]');
        el.$panelType = $(".wpforms-persian-sms-panel-type select");
        el.$apiKey = $(".wpforms-persian-sms-api-key");
        el.$username = $(".wpforms-persian-sms-username");
        el.$password = $(".wpforms-persian-sms-password");
        el.$lineNumber = $(".wpforms-persian-sms-line-number");
        el.$messageBody = $(".wpforms-persian-sms-message-body");
        el.$patternId = $(".wpforms-persian-sms-pattern-id");
        el.$patternVariables = $(".wpforms-persian-sms-pattern-variables");
        el.$patternHelp = $(".wpforms-persian-sms-pattern-help");
        el.$persianSmsWrapper = $(".wpforms-panel-persian-sms-wrapper");
      },

      /**
       * Initialize fields on page load.
       */
      initializeFields() {
        // Initialize UI based on current selection.
        app.togglePatternFields();
        app.toggleCredentialFields();
        app.updatePatternHelp();

        // Handle initial toggle.
        app.settingsToggle.call(el.$smsEnable[0]);
      },

      /**
       * Bind events.
       */
      bindEvents() {
        // Toggle SMS panel when enable/disable checkbox is clicked.
        el.$document.on(
          "click",
          '.wpforms-persian-sms-enable input[type="checkbox"]',
          app.settingsToggle
        );

        // Handle panel type change.
        el.$panelType.on("change", function () {
          app.togglePatternFields();
          app.toggleCredentialFields();
          app.maybeShowSingleRecipientAlert();
          app.updatePatternHelp();
        });
      },

      /**
       * Toggle settings visibility based on SMS enable checkbox.
       */
      settingsToggle() {
        el.$persianSmsWrapper.toggle($(this).prop("checked"));
      },

      /**
       * Toggle fields based on whether a pattern-based provider is selected.
       */
      togglePatternFields() {
        const selectedProvider = el.$panelType.val();
        const isPatternBased =
          vars.patternBasedProviders.includes(selectedProvider);

        // Toggle regular SMS fields.
        el.$messageBody.toggle(!isPatternBased);

        // Toggle pattern-specific fields.
        el.$patternId.toggle(isPatternBased);
        el.$patternVariables.toggle(isPatternBased);
        el.$patternHelp.toggle(isPatternBased);

        // Special case for farazsms pattern that still needs line number.
        if (selectedProvider === "farazsms_pattern") {
          el.$lineNumber.show();
        } else if (isPatternBased) {
          el.$lineNumber.toggle(selectedProvider === "farazsms_pattern");
        } else {
          el.$lineNumber.show();
        }
      },

      /**
       * Toggle credential fields based on provider selection.
       */
      toggleCredentialFields() {
        const selectedProvider = el.$panelType.val();
        const usesApiKey = vars.apiKeyProviders.includes(selectedProvider);

        // Toggle API Key field.
        el.$apiKey.toggle(usesApiKey);

        // Toggle username/password fields.
        el.$username.toggle(
          !usesApiKey || selectedProvider === "farazsms_pattern"
        );
        el.$password.toggle(
          !usesApiKey || selectedProvider === "farazsms_pattern"
        );
      },

      /**
       * Show alert for single recipient providers.
       */
      maybeShowSingleRecipientAlert() {
        const selectedProvider = el.$panelType.val();
        if (vars.singleRecipientProviders.includes(selectedProvider)) {
          app.doAlert(l10n.single_recipient_alert);
        }
      },

      /**
       * Update pattern help text based on selected provider.
       */
      updatePatternHelp() {
        const selectedProvider = el.$panelType.val();
        let helpText = "";

        // Set provider-specific help text.
        switch (selectedProvider) {
          case "kavenegar_pattern":
            helpText = l10n.kavenegar_variables_info;
            break;
          case "sms_payamak_pattern":
            helpText = l10n.smsir_variables_info;
            break;
          case "farazsms_pattern":
            helpText = l10n.farazsms_variables_info;
            break;
          case "ippanel_pattern":
            helpText = l10n.ippanel_variables_info;
            break;
          case "melipayamak_pattern":
            helpText = l10n.melipayamak_variables_info;
            break;
        }

        // Update help text.
        el.$patternHelp.html(helpText);
        el.$patternHelp.toggle(!!helpText);
      },

      /**
       * Creates a pop up alert.
       *
       * @param {string} alertContent The body content for the alert.
       * @param {string} alertTitle   The title of the alert.
       * @param {string} alertType    Type of alert. Allowed Types: green, blue, orange, red.
       */
      doAlert(
        alertContent,
        alertTitle = wpforms_builder.heads_up,
        alertType = "orange"
      ) {
        $.alert({
          title: alertTitle,
          content: alertContent,
          icon: "fa fa-exclamation-circle",
          type: alertType,
          buttons: {
            confirm: {
              text: wpforms_builder.ok,
              btnClass: "btn-confirm",
              keys: ["enter"],
            },
          },
        });
      },
    };

    return app;
  })(document, window, jQuery, wpforms_builder_persian_sms);

WPFormsPersianSms.init();
