jQuery(document).ready(function ($) {
  "use strict";

  /**
   * Tab show and hide
   */
  $(".ciws-colorpicker").wpColorPicker();
  $("body").on("click", ".ciws-wrap .nav-tab", function () {
    var settings_ref = $(this).data("settings-ref");
    $(".ciws-wrap .nav-tab").removeClass("nav-tab-active");
    $(this).addClass("nav-tab-active");
    $(".ciws-settings-section").hide();
    $(
      '.ciws-settings-section[data-settings-ref="' + settings_ref + '"]'
    ).show();
    if (settings_ref == "help" || settings_ref == "about") {
      $(".ciws-settings-action").hide();
    } else {
      $(".ciws-settings-action").show();
    }
  });

  $("body").on("click", ".ciws-icon-prev", function () {
    var dataLogo = $(this).find("img").data("logo") || "ciws-whatsapp";

    // Find the closest floating image
    var floatingImg = $(".ciws-floating-icon-wrap img");

    if (floatingImg.length === 0) {
      console.warn("Floating image not found.");
      return;
    }

    var currentSrc = floatingImg.attr("src");
    if (!currentSrc) {
      console.warn("Floating image src is empty or undefined.");
      return;
    }

    var basePath = currentSrc.substring(0, currentSrc.lastIndexOf("/") + 1);
    var newSrc = basePath + dataLogo + ".svg";

    // Update the image src
    floatingImg.attr("src", newSrc);
    $(".floating-icon-img").val(dataLogo);
    // Update active class
    $(this).siblings().removeClass("ciws-active");
    $(this).addClass("ciws-active");
  });
    /**
   * account sorting 
   */
    $('#ciws-selected-accounts').sortable({
      update: function () {
          let ids = [];
          $('#ciws-selected-accounts .ciws-selected-account-item').each(function () {
              ids.push($(this).data('id'));
          });
          $('#ciws-selected-accounts-input').val(ids.join(','));
      }
  });
  /**
   * Open Media Uploader
   */
  $("body").on("click", ".ciws-profile-button", function () {
    var selector = $(this);

    var image = wp
      .media({
        title: "Upload Image",
        // mutiple: true if you want to upload multiple files at once
        multiple: false,
      })
      .open()
      .on("select", function (e) {
        // This will return the selected image from the Media Uploader, the result is an object
        var uploaded_image = image.state().get("selection").first();
        // We convert uploaded_image to a JSON object to make accessing it easier
        // Output to the console uploaded_image
        console.log(uploaded_image);
        var image_url = uploaded_image.toJSON().url;
        var image_id = uploaded_image.toJSON().id;
        // Let's assign the url value to the input field
        selector.parent().find('input[type="hidden"]').val(image_url);
        selector
          .parent()
          .find(".profile-image-preview")
          .html('<img src="' + image_url + '"/>');
      });
  });

  /**
   * url button event
   */

  // Handle clicks for the "URL for Desktop" buttons
  $("body").on("click", ".ciws-btn-web", function () {
    var selectedValue = $(this).val();

    $("#url_for_desktop").val(selectedValue); // Update hidden input for Desktop

    // Optional: Add a class to highlight the selected button
    $(".ciws-btn-web").removeClass("ciws-url-active");
    $(this).addClass("ciws-url-active");
  });

  // Handle clicks for the "URL for Mobile" buttons
  $(".ciws-btn-mob").on("click", function () {
    var selectedValue = $(this).val();
    $("#url_for_mobile").val(selectedValue); // Update hidden input for Mobile

    // Optional: Add a class to highlight the selected button
    $(".ciws-btn-mob").removeClass("ciws-url-active");
    $(this).addClass("ciws-url-active");
  });

  /**
   * shortcode template number change event
   */
  $("body").on("change", ".ciws-template-dropdown", function () {
    var template = $(this).val();

    // Find the ciws-button-wrapper element
    var buttonWrapper = $(".ciws-button-wrapper");
    buttonWrapper.attr(
      "class",
      "ciws-button-wrapper ciws-preview-class " + template
    );

    $(".ciws-each-template-preview-wrap").hide();
    $(
      '.ciws-each-template-preview-wrap[data-template-ref="' + template + '"]'
    ).show();
  });

  /**
   * customize option show/hide
   */

  $("body").on("change", ".ciws-customize-status", function () {
    if (this.checked) {
      $(".ciws-customize-status-hide").show();
    } else {
      $(".ciws-customize-status-hide").hide();
    }
  });

  $(".ciws-floating-box-title").on("input", function () {
    var newHeading = $(this).val();

    $(".ciws-floating-box-text").html(newHeading);
  });

  $(".ciws-floating-box-sub-title").on("input", function () {
    var newHeading = $(this).val();

    $(".ciws-floating-box-sub-text").html(newHeading);
  });

  $(".ciws-floating-box-reply-title").on("input", function () {
    // Get the value of the input field
    var newHeading = $(this).val();

    // Update the content of the ciws-floating-btn-title element
    $(".ciws-reply-txt").html(newHeading);
  });

  /**
   * shortcode customize color event
   */

  $("body").on("change", ".ciws-shortcode-customize-status", function () {
    if (!this.checked) {
      $(".ciws-btn-content-wrap").css("color", "#ffffff");
      $(".ciws-shortcode-btn-fill").css("background", "#5bd26d"); // Removed the incorrect quotes
    } else {
      
      var shortcodefillColor = $(".ciws-button-fill").val();
      var shortcodetextColor = $(".ciws-button-text-color").val();
      
      $(".ciws-btn-content-wrap").css("color", shortcodetextColor);
      $(".ciws-shortcode-btn-fill").css("background", shortcodefillColor);
    }
  });

  /**
   * floating customize color event
   */

  $("body").on("change", ".ciws-customize-status", function () {
    if (!this.checked) {
      $(".ciws-box-header-wrap").removeAttr("style");
      $(".ciws-floating-box-text").removeAttr("style");
      $(".ciws-floating-box-sub-text").removeAttr("style");
      $(".ciws-floating-icon-wrap").removeAttr("style");
      $(".ciws-floating-btn-info-wrap").removeAttr("style");
      $(".ciws-floating-btn-title").removeAttr("style");

      $(".ciws-floating-btn-title").css("color", "#ffffff");
      $(".ciws-btn-fill-color").css("background-color", "#5bd26d");

      $(".ciws-floating-icon-wrap").css("background-color", "#5bd26d");
      $(".ciws-floating-btn-info-wrap").css("background-color", "#5bd26d");
      $(".ciws-box-header-wrap").removeAttr("style");
      $(".ciws-greeting-header-wrap").removeAttr("style");
      $(".ciws-button").removeAttr("style");

      $(".ciws-greeting-heading").removeAttr("style");
      $(".ciws-btn-title").removeAttr("style");
    } else {
      var fillColor = $(".ciws-floating-button-fill").val();
      var textColor = $(".ciws-floating-button-text-color").val();

      $(".ciws-floating-box-text").css("color", textColor);
      $(".ciws-floating-box-sub-text").css("color", textColor);
      $(".ciws-floating-btn-info-wrap").css("background-color", fillColor);
      $(".ciws-floating-btn-title").css("color", textColor);
      $(".ciws-btn-fill-color").css("background-color", fillColor);
      $(".ciws-floating-icon-wrap").css("background-color", fillColor);

      $(".ciws-box-header-wrap").css("background-color", fillColor);
    }
  });

  /**
   * shortcode customize show/hide
   */

  $("body").on("change", ".ciws-shortcode-customize-status", function () {
    if (this.checked) {
      $(".ciws-shortcode-customize-status-hide").show();
    } else {
      $(".ciws-shortcode-customize-status-hide").hide();
    }
  });
  $("body").on("change", ".ciws-account-field-name", function () {
    var acc_name = $(this).val();
    $(".ciws-account-name").html(acc_name);
  });
  /**
   * floating template change in preview
   */
  $("body").on("change", ".ciws-floating-template-dropdown", function () {
    var template = $(this).val();

    // Find the ciws-floating-button-wrapper element
    var buttonWrapper = $(".ciws-floating-button-wrapper");
    buttonWrapper.attr(
      "class",
      "ciws-floating-button-wrapper ciws-floating-right " + template
    );
  });

  /**
   * position preview
   */
  $("body").on("change", ".ciws-floating-position-dropdown", function () {
    var selectedPosition = $(this).val();
    // Find the ciws-floating-button-wrapper element
    var buttonWrapper = $(".ciws-floating-button-wrapper"); // Target the div

    // Remove any existing 'ciws-floating-right' or 'ciws-floating-left' class
    buttonWrapper.removeClass("ciws-floating-right ciws-floating-left");

    // Add the selected class
    buttonWrapper.addClass(selectedPosition);
  });

  $(".ciws-button-fill").wpColorPicker({
    change: function (event, ui) {
      var color = ui.color.toString();
      $(".ciws-button").css("background-color", color);
    },
  });

  $(".ciws-button-text-color").wpColorPicker({
    change: function (event, ui) {
      var color = ui.color.toString();
      $(".ciws-btn-content-wrap").css("color", color);
    },
  });

  $(".ciws-floating-button-fill").wpColorPicker({
    change: function (event, ui) {
      var color = ui.color.toString();

      $(".ciws-floating-icon-wrap").css("background-color", color);
      $(".ciws-floating-btn-info-wrap").css("background-color", color);
      $(".ciws-box-header-wrap").css("background-color", color);
      $(".ciws-greeting-header-wrap").css("background-color", color);
      $(".ciws-button").css("background-color", color);
    },
  });

  $(".ciws-floating-button-text-color").wpColorPicker({
    change: function (event, ui) {
      var color = ui.color.toString();
      $(".ciws-floating-btn-title").css("color", color);
      $(".ciws-floating-box-text").css("color", color);
      $(".ciws-floating-box-sub-text").css("color", color);
      $(".ciws-greeting-heading").css("color", color);
      $(".ciws-btn-title").css("color", color);
    },
  });

  $("body").on("click", ".ciws-save-btn", function () {
    $(".ciws-form").submit();
  });

  $(".floating-button-heading").on("input", function () {
    // Get the value of the input field
    var newHeading = $(this).val();

    // Update the content of the ciws-floating-btn-title element
    $(".ciws-floating-btn-title").html(newHeading);
  });

  $("body").on("click", ".ciws-save-btn", function () {
    $(".ciws-form").submit();
  });

  $(".shortcode-button-heading").on("input", function () {
    // Get the value of the input field
    var newHeading = $(this).val();

    // Update the content of the ciws-floating-btn-title element
    $(".ciws-btn-title").html(newHeading);
  });

  /**
   * shortcode copy event
   */
  $("body").on("click", ".ciws-clipboard-copy", function () {
    const shortcodeText = $(this)
      .siblings(".ciws-shortcode-preview")
      .text()
      .trim();

    const $ciwstempInput = $("<input>");
    $("body").append($ciwstempInput);
    $ciwstempInput.val(shortcodeText).select();

    document.execCommand("copy");
    $ciwstempInput.remove();

    const $icon = $(this).find("i");
    $icon.removeClass("fa-clipboard-list").addClass("fa-check-circle");

    if (!$(".ciws-copied-msg").length) {
      const $ciws_message = $('<span class="ciws-copied-msg">Copied!</span>');
      $(this).parent().append($ciws_message);

      setTimeout(() => {
        $icon.removeClass("fa-check-circle").addClass("fa-clipboard-list");
        $ciws_message.fadeOut(8000, function () {
          $(this).remove();
        });
      }, 1500);
    }
  });

  // Validate on input
  $("#account-number").on("input", function () {
    const phoneNumber = $(this).val().trim();

    if (phoneNumber === "") {
      $("#error-message").hide();
      $(this).removeClass("invalid");
    } else if (!/^\+\d{1,15}$/.test(phoneNumber)) {
      $("#error-message")
        .text(
          "Invalid phone number format. Please include a country code starting with +."
        )
        .show();
      $(this).addClass("invalid");
    } else {
      $("#error-message").hide();
      $(this).removeClass("invalid");
    }
  });

  $("form").on("submit", function (event) {
    const $accountNumber = $("#account-number");

    if ($accountNumber.length > 0) {
      const phoneNumber = $accountNumber.val().trim();

      if (!/^\+\d{1,15}$/.test(phoneNumber)) {
        event.preventDefault();
        alert("Please enter a valid phone number with a country code.");
        $accountNumber.focus().addClass("invalid");
      }
    }
  });

  $("body").on("click", ".ciws-position-image", function () {
    $(".ciws-position-image-wrap").removeClass("ciws-selected");
    $(this).find(".ciws-position-image-wrap").addClass("ciws-selected");
    var selected_position = $(this).find("img").data("position");

    $(
      '.ciws-buton-position-dropdown option[value="' + selected_position + '"]'
    ).prop("selected", true);
    return false;
  });

  /**
   * box status
   */

  $("body").on("change", ".ciws-radio-toggle", function () {
    var selectedValue = $(this).val();

    if (selectedValue === "floating") {
      //$(".ciws-floating-box-template").show();
      $(".ciws-mulitple-account").show();
      $(".ciws-single-account").hide();
    } else if (selectedValue === "none" || selectedValue === "greeting" ) {
      $(".ciws-single-account").show();

      $(".ciws-mulitple-account").hide();
    }
  });

  // Search input
  $("#ciws-account-search").on("keyup", function () {
    var searchTerm = $(this).val();
    let dropdown = $("#ciws-account-dropdown");
    if (searchTerm.length > 2) {
      $.ajax({
        url: ajaxurl, // WordPress AJAX URL
        type: "POST",
        data: {
          action: "search_accounts",
          search: searchTerm,
        },
        success: function (response) {
          if (response.success) {
            dropdown.empty(); // Clear previous results
            $.each(response.data, function (index, account) {
              if (
                $(
                  '#ciws-account-dropdown .ciws-dropdown-item[data-id="' +
                    account.account_id +
                    '"]'
                ).length === 0
              ) {
                dropdown.append(
                  `<div class="ciws-dropdown-item" data-id="${account.account_id}" data-name="${account.account_name}">
                                      ${account.account_name}
                                  </div>`
                );
              }
            });
          }
        },
      });
    } else {
      dropdown.empty();
    }
  });

  var selectedAccounts = [];

  // Initialize selectedAccounts on page load
  $(document).ready(function () {
    initializeSelectedAccounts();
  });

  function initializeSelectedAccounts() {
    const inputVal = $("#ciws-selected-accounts-input").val();
    selectedAccounts = inputVal
      .split(",")
      .map((id) => id.trim())
      .filter((id) => id !== "");
  }

  // Update the hidden input field
  function updateHiddenInput() {
    const updatedValue = selectedAccounts.join(",");
    $("#ciws-selected-accounts-input").val(updatedValue);
  }

  // Click on dropdown item to add account
  $(document).on("click", ".ciws-dropdown-item", function () {
    var accountId = String($(this).data("id"));
    var accountName = $(this).data("name");

    if (!selectedAccounts.includes(accountId)) {
      selectedAccounts.push(accountId);

      $("#ciws-selected-accounts").append(
        `<li class="ciws-selected-account-item" data-id="${accountId}">
            ${accountName}
            <button class="ciws-remove-account"><span class="dashicons dashicons-trash"></span></button>
        </li>`
      );

      updateHiddenInput();
    }

    // Optional: Clear dropdown list after selection
    $("#ciws-account-dropdown").empty();
  });

  // Remove selected account
  $(document).on("click", ".ciws-remove-account", function () {
    var listItem = $(this).closest(".ciws-selected-account-item"); // Find the list item
    var accountId = listItem.data("id").toString(); // Get the account ID as a string

    // Remove the accountId from selectedAccounts array
    selectedAccounts = selectedAccounts.filter((id) => id !== accountId);

    // Remove the list item from the UI
    listItem.remove();

    // Update the hidden input field
    updateHiddenInput();
  });
  $("a.ciws-floating-box").click(function () {
    $(".ciws-floating-box-wrap").toggle();
  });

  /**
   * backend floating box template demo event
   */

  $("body").on("change", ".ciws-floating-box-template-dropdown", function () {
    let selectedTemplateClass = $(this).val();

    $(".ciws-floating-button-wrapper")
      .removeClass(function (index, className) {
        return (className.match(/(^|\s)ciws-box-template-\S+/g) || []).join(
          " "
        );
      })
      .addClass(selectedTemplateClass);

    $(".ciws-floating-box-wrap").trigger("click");
    $(".ciws-floating-box-wrap").show();

    let $targetDiv = $(".ciws-floating-template-check");

    $targetDiv.each(function () {
      let classes = $(this).attr("class").split(" ");
      if (classes.length > 1) {
        classes[1] = selectedTemplateClass;
      }
      $(this).attr("class", classes.join(" "));
    });
  });
    $(".ciws-close-btn").click(function () {
    $(".ciws-floating-box-wrap").hide();
  });
      $("a.ciws-floating-box").click(function () {
    $(".ciws-greeting-box-wrap").toggle();
  });
      $(".ciws-close-btn.ciws-gretting-close").click(function () {
    $(".ciws-greeting-box-wrap").hide();
  });
});
