/**
 * Admin JavaScript
 *
 * @package Spin_Wheel
 */

(function ($) {
  "use strict";

  $(document).ready(function () {
    // Initialize color pickers
    if ($.fn.wpColorPicker) {
      $(".swp-color-picker").wpColorPicker();
    }

    // WordPress Media Uploader for Prize Images
    let mediaUploader;

    $(document).on("click", ".swp-upload-image", function (e) {
      e.preventDefault();

      const $button = $(this);
      const $input = $button.siblings(".swp-image-url");
      const $preview = $button.siblings(".swp-image-preview");

      // If the media uploader already exists, reopen it
      if (mediaUploader) {
        mediaUploader.open();
        return;
      }

      // Create the media uploader
      mediaUploader = wp.media({
        title: "Select Prize Image",
        button: {
          text: "Use this image",
        },
        multiple: false,
        library: {
          type: "image",
        },
      });

      // When an image is selected, run a callback
      mediaUploader.on("select", function () {
        const attachment = mediaUploader
          .state()
          .get("selection")
          .first()
          .toJSON();

        // Set the image URL in the input field
        $input.val(attachment.url);

        // Show/update preview
        if ($preview.length) {
          $preview.find("img").attr("src", attachment.url);
        } else {
          $button
            .parent()
            .append(
              '<div class="swp-image-preview" style="margin-top: 10px;">' +
              '<img src="' +
              attachment.url +
              '" style="max-width: 100px; max-height: 100px; border: 1px solid #ddd; padding: 5px;">' +
              "</div>"
            );
        }
      });

      // Open the uploader
      mediaUploader.open();
    });

    // Prize Management
    let prizeIndex = $("#swp-prizes-container .swp-prize-item").length;

    // Add Prize
    $("#swp-add-prize").on("click", function () {
      const template = $("#swp-prize-template").html();
      const html = template
        .replace(/{{index}}/g, prizeIndex)
        .replace(/{{number}}/g, prizeIndex + 1);

      $("#swp-prizes-container").append(html);

      // Reinitialize color pickers for new prize
      $("#swp-prizes-container").find(".swp-color-picker").wpColorPicker();

      prizeIndex++;
    });

    // Remove Prize
    $(document).on("click", ".swp-remove-prize", function () {
      if (confirm(swpAdminData.confirmDelete || "Are you sure?")) {
        $(this).closest(".swp-prize-item").remove();
        updatePrizeNumbers();
      }
    });

    // Update prize numbers after removal
    function updatePrizeNumbers() {
      $("#swp-prizes-container .swp-prize-item").each(function (index) {
        $(this)
          .find(".swp-prize-number")
          .text((swpAdminData.prizeNumber || "Prize #%s").replace("%s", index + 1));
      });
    }

    // Shortcode metabox: toggle panels (save still required to persist Auto Embed)
    (function () {
      var $mode = $("#swp_usage_mode");
      if (!$mode.length) {
        return;
      }
      var $short = $("#swp-usage-panel-shortcode");
      var $auto = $("#swp-usage-panel-auto");
      function syncPanels() {
        var v = $mode.val();
        if (v === "auto_embed") {
          $short.prop("hidden", true);
          $auto.prop("hidden", false);
        } else {
          $short.prop("hidden", false);
          $auto.prop("hidden", true);
        }
      }
      $mode.on("change", syncPanels);
      syncPanels();
    })();

    // Copy Shortcode
    $(".swp-copy-shortcode").on("click", function () {
      const text = $(this).data("clipboard-text");

      // Create temporary textarea
      const $temp = $("<textarea>");
      $("body").append($temp);
      $temp.val(text).select();
      document.execCommand("copy");
      $temp.remove();

      // Show feedback
      const $btn = $(this);
      const originalText = $btn.text();
      $btn.text(swpAdminData.copied || "Copied!");

      setTimeout(function () {
        $btn.text(originalText);
      }, 2000);
    });

    // Copy Shortcode from Table Column
    $(document).on("click", ".swp-copy-btn", function (e) {
      e.preventDefault();
      const text = $(this).data("clipboard-text");

      // Create temporary textarea
      const $temp = $("<textarea>");
      $("body").append($temp);
      $temp.val(text).select();
      document.execCommand("copy");
      $temp.remove();

      // Show feedback
      const $btn = $(this);
      const $icon = $btn.find(".dashicons");

      // Save original icon class
      const originalClass = $icon.attr("class");

      // Change to checkmark and add copied class
      $icon.removeClass("dashicons-admin-page").addClass("dashicons-yes");
      $btn.addClass("copied");

      setTimeout(function () {
        $icon.attr("class", originalClass);
        $btn.removeClass("copied");
      }, 2000);
    });

    // Select Winner
    $(".swp-select-winner").on("click", function () {
      const $btn = $(this);
      const entryId = $btn.data("entry-id");

      if (
        !confirm(
          swpAdminData.confirmWinner ||
          "Are you sure you want to select this entry as winner?"
        )
      ) {
        return;
      }

      $btn.prop("disabled", true).text(swpAdminData.processing || "Processing...");

      $.ajax({
        url: swpAdminData.ajaxUrl,
        type: "POST",
        data: {
          action: "swp_select_winner",
          nonce: swpAdminData.nonce,
          entry_id: entryId,
        },
        success: function (response) {
          if (response.success) {
            // Update UI
            const $row = $btn.closest("tr");
            $row
              .find("td:nth-last-child(2)")
              .html('<span class="swp-badge swp-badge-success">' + (swpAdminData.winner || "Winner") + '</span>');
            $btn.replaceWith(
              '<span class="dashicons dashicons-yes-alt" style="color: #46b450;"></span>'
            );

            alert(swpAdminData.winnerSelectedNotified || "Winner selected and notified successfully!");
          } else {
            alert(response.data.message || (swpAdminData.errorSelectingWinner || "Error selecting winner"));
            $btn.prop("disabled", false).text(swpAdminData.selectWinner);
          }
        },
        error: function () {
          alert("An error occurred");
          $btn.prop("disabled", false).text(swpAdminData.selectWinner);
        },
      });
    });

    // Auto-submit filter form when wheel selected
    $("#swp-wheel-select").on("change", function () {
      // Mark that wheel was changed so form submits normally (to update URL)
      $(this).closest("form").data('wheel-changed', true).submit();
    });

    // Validate probability totals
    $(document).on("submit", "#post", function (e) {
      const $form = $(this);
      const $prizes = $form.find(".swp-prize-item");

      if ($prizes.length === 0) {
        return true;
      }

      let totalProbability = 0;
      $prizes.each(function () {
        const prob =
          parseFloat($(this).find('input[name*="[probability]"]').val()) || 0;
        totalProbability += prob;
      });

      if (Math.abs(totalProbability - 100) > 0.1) {
        alert(
          "Warning: Prize probabilities should total 100%. Current total: " +
          totalProbability.toFixed(1) +
          "%"
        );
      }
    });

    // Accordion and slider functionality moved to admin-modern.js for modern editor

    // ===================================================================
    // AJAX Pagination for Entries Table
    // ===================================================================

    if ($(".swp-entries-page").length && $("#swp-wheel-select").val()) {
      let currentPage = 1;
      let perPage = parseInt($("#entries-per-page").val()) || 10;

      // Function to load entries via AJAX
      function loadEntriesAjax(page, resetPage = false) {
        if (resetPage) {
          page = 1;
        }

        const wheelId = $("#swp-wheel-select").val();
        if (!wheelId) {
          return;
        }

        const statusFilter = $("#swp-status-filter").val() || "";
        const searchQuery = $("#swp-search-query").val() || "";

        // Show loading spinner and overlay (center of screen)
        $(".swp-loading-overlay").addClass("active");
        $(".swp-loading-spinner").fadeIn(200);

        // Hide any existing error messages
        $(".swp-ajax-error").remove();

        // AJAX request
        $.ajax({
          url: swpAdminData.ajaxUrl,
          type: "POST",
          data: {
            action: "swp_load_entries_pagination",
            nonce: swpAdminData.nonce,
            wheel_id: wheelId,
            status_filter: statusFilter,
            search_query: searchQuery,
            paged: page,
            per_page: perPage,
          },
          success: function (response) {
            if (response.success) {
              // Update table body
              $(".swp-entries-table tbody").html(response.data.table_html);

              // Show/hide entries header based on whether there are entries
              if (response.data.total_filtered > 0) {
                // Show entries header if hidden
                if ($(".swp-entries-header").length === 0) {
                  $(".swp-entries-table-wrapper h2").after('<div class="swp-entries-header"><div class="swp-filter-group swp-search-group"><div class="swp-search-input-wrapper"><span class="dashicons dashicons-search swp-search-icon"></span><input type="text" id="swp-search-query" placeholder="Search by name, email.." class="swp-search-input"><button type="button" class="swp-clear-search" title="Clear search" style="display:none;"><span class="dashicons dashicons-dismiss"></span></button></div></div><div class="swp-bulk-actions" style="display: none;"><select id="swp-bulk-action-select" class="swp-bulk-action-select"><option value="">Bulk Actions</option><option value="delete">Delete Selected</option></select><button type="button" id="swp-apply-bulk-action" class="button">Apply</button><span class="swp-selected-count"></span></div><div id="swp-pagination-top"></div></div>');
                }
                $(".swp-entries-header").show();

                // Update top pagination
                if (response.data.pagination_top_html) {
                  if ($("#swp-pagination-top").length === 0) {
                    $(".swp-entries-header").append('<div id="swp-pagination-top"></div>');
                  }
                  $("#swp-pagination-top").html(response.data.pagination_top_html).show();
                } else {
                  $("#swp-pagination-top").remove();
                }

                // Update bottom pagination
                if (response.data.pagination_bottom_html) {
                  if ($("#swp-pagination-bottom").length === 0) {
                    $(".swp-entries-table").after('<div id="swp-pagination-bottom"></div>');
                  }
                  $("#swp-pagination-bottom").html(response.data.pagination_bottom_html).show();
                } else {
                  $("#swp-pagination-bottom").remove();
                }
              } else {
                // Remove entries header when no entries
                $(".swp-entries-header").remove();
                $("#swp-pagination-bottom").remove();
              }

              // Update current page
              currentPage = response.data.current_page;

              // Update export filtered button with current count
              updateExportFilteredButton(response.data.total_filtered);

              // Scroll to top of table smoothly
              const $tableWrapper = $(".swp-entries-table-wrapper");
              if ($tableWrapper.length > 0) {
                $("html, body").animate(
                  {
                    scrollTop: $tableWrapper.offset().top - 100,
                  },
                  300
                );
              }
            } else {
              showAjaxError(response.data.message || "Error loading entries");
            }
          },
          error: function (xhr, status, error) {
            showAjaxError(
              "An error occurred while loading entries. Please try again."
            );
            console.error("AJAX Error:", error);
          },
          complete: function () {
            // Hide loading spinner and overlay
            $(".swp-loading-spinner").fadeOut(200);
            $(".swp-loading-overlay").removeClass("active");
          },
        });
      }

      // Show error message
      function showAjaxError(message) {
        const errorHtml =
          '<div class="notice notice-error swp-ajax-error" style="margin: 20px 0;"><p>' +
          message +
          "</p></div>";
        $(".swp-entries-table-wrapper").before(errorHtml);

        // Auto-hide after 5 seconds
        setTimeout(function () {
          $(".swp-ajax-error").fadeOut(function () {
            $(this).remove();
          });
        }, 5000);
      }

      // Update export filtered button with count
      function updateExportFilteredButton(filteredCount) {
        const $button = $("#swp-export-filtered");
        if (filteredCount > 0) {
          $button.prop("disabled", false);
          $button.html(
            '<span class="dashicons dashicons-download"></span> Export Filtered CSV (' +
            filteredCount.toLocaleString() +
            ")"
          );
        } else {
          $button.prop("disabled", true);
          $button.html(
            '<span class="dashicons dashicons-download"></span> Export Filtered CSV'
          );
        }
      }

      // Handle pagination link clicks
      $(document).on("click", ".swp-pagination-link", function (e) {
        e.preventDefault();
        const page = parseInt($(this).data("page"));
        if (
          page &&
          page !== currentPage &&
          !$(this).hasClass("swp-current-page")
        ) {
          loadEntriesAjax(page);
        }
      });

      // Handle per-page selector change
      $(document).on("change", "#entries-per-page", function () {
        perPage = parseInt($(this).val());
        loadEntriesAjax(1, true); // Reset to first page
      });

      // Handle status filter change
      $(document).on("change", "#swp-status-filter", function () {
        loadEntriesAjax(1, true); // Reset to first page
      });

      // Handle search with debounce
      let searchTimeout;
      $(document).on("input", "#swp-search-query", function () {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function () {
          loadEntriesAjax(1, true); // Reset to first page
        }, 500); // 500ms delay
      });

      // Handle search form submit
      $(document).on("submit", "#swp-filter-form", function (e) {
        // Allow normal form submit if wheel was just changed (to update URL)
        // This is important to maintain wheel selection across page reloads
        if ($(this).data('wheel-changed')) {
          $(this).removeData('wheel-changed');
          return true; // Allow normal form submission
        }

        e.preventDefault();
        loadEntriesAjax(1, true);
      });

      // Keyboard navigation for pagination (optional)
      $(document).on("keydown", function (e) {
        // Only if not typing in input/textarea
        if ($(e.target).is("input, textarea, select")) {
          return;
        }

        if (e.key === "ArrowLeft" && currentPage > 1) {
          e.preventDefault();
          loadEntriesAjax(currentPage - 1);
        } else if (e.key === "ArrowRight") {
          const $nextBtn = $(".swp-next-page").first();
          if ($nextBtn.length) {
            e.preventDefault();
            const nextPage = parseInt($nextBtn.data("page"));
            if (nextPage) {
              loadEntriesAjax(nextPage);
            }
          }
        }
      });

      // Initialize export button on page load
      // Count visible table rows (excluding "no entries" message)
      const initialRowCount = $(".swp-entries-table tbody tr").length;
      const hasEntries =
        initialRowCount > 0 &&
        !$(".swp-entries-table tbody tr td[colspan]").length;
      if (hasEntries) {
        updateExportFilteredButton(initialRowCount);
      }
    }

  });
})(jQuery);

