let hostEventCount = 0;
function hideElementHeartbeat(id, eventCount) {
  let element = document.getElementById(id);
  if (eventCount == hostEventCount) {
    element.classList.add("hidden");
  } else {
    hostEventCount = eventCount;
  }

  setTimeout(() => {
    let element = document.getElementById(id);
    element.classList.add("hidden");
  }, "15000");
}

function copyShortcode(button) {
  var input = button.previousElementSibling;
  if (input && input.select) {
    input.select();
    navigator.clipboard.writeText(input.value);
  }
}

function copyCodeText(button) {
  var codeDiv = button.previousElementSibling;
  if (codeDiv) {
    var text = codeDiv.textContent.trim();
    navigator.clipboard.writeText(text);
  }
}

function evusel_call_feed() {
  fetch("/wp-json/evusel/run-cron", {
    method: "GET",
    credentials: "same-origin",
    headers: {
      "X-WP-Nonce": evusel_ajax_obj.rest_nonce,
    },
  });
}

function resetSliderSettings() {
  var slidesSelect = document.querySelector(
    'select[name="evusel_settings[shortcodes][slider][no_of_slides]"]'
  );
  if (slidesSelect) slidesSelect.value = "5";

  var layoutRadio = document.querySelector(
    'input[name="evusel_settings[shortcodes][slider][layout]"][value="full_width"]'
  );
  if (layoutRadio) layoutRadio.checked = true;

  var navRadio = document.querySelector(
    'input[name="evusel_settings[shortcodes][slider][navigation]"][value="arrows"]'
  );
  if (navRadio) navRadio.checked = true;

  var autoplayCheck = document.querySelector(
    'input[name="evusel_settings[shortcodes][slider][autoplay]"]'
  );
  if (autoplayCheck) autoplayCheck.checked = true;

  var fullwidthCheck = document.querySelector(
    'input[name="evusel_settings[shortcodes][slider][fullwidth]"]'
  );
  if (fullwidthCheck) fullwidthCheck.checked = true;
}

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

  // Option to copy shortcode text with one click
  $(".copy-shortcode").on("click", function () {
    var shortcodeInfoInput = $(this).prev().first();
    var that = this;

    navigator.clipboard.writeText(shortcodeInfoInput.val());

    $(this).text("Copied!");

    setTimeout(function () {
      $(that).text("Copy text");
    }, 2000);
  });

  // Time format for ACF fields
  if (typeof acf != "undefined") {
    acf.add_filter("time_picker_args", function (args, $field) {
      args.timeFormat = "h:mm TT";
      args.altTimeFormat = "h:mm TT";
      args.stepMinute = 15;
      args.showSecond = false;
      return args;
    });
  }

  // Color picker
  $(".spectrum").spectrum({
    preferredFormat: "hex",
    showInput: true,
  });

  // Select image from Wordpress Media Library
  $("#seetickets_media_manager").click(function (e) {
    e.preventDefault();
    var image_frame;
    if (image_frame) {
      image_frame.open();
    }
    // Define image_frame as wp.media object
    image_frame = wp.media({
      title: "Select Media",
      multiple: false,
      library: {
        type: "image",
      },
    });

    image_frame.on("close", function () {
      // On close, get selections and save to the hidden input plus other AJAX stuff to refresh the image preview
      var selection = image_frame.state().get("selection");
      var gallery_ids = new Array();
      var my_index = 0;
      selection.each(function (attachment) {
        gallery_ids[my_index] = attachment["id"];
        my_index++;
      });
      var ids = gallery_ids.join(",");
      jQuery("input#seetickets_default_image_id").val(ids);
      Refresh_Image(ids);
    });

    image_frame.on("open", function () {
      // On open, get the id from the hidden input and select the appropiate images in the media manager
      var selection = image_frame.state().get("selection");
      var ids = jQuery("input#seetickets_default_image_id").val().split(",");
      ids.forEach(function (id) {
        var attachment = wp.media.attachment(id);
        attachment.fetch();
        selection.add(attachment ? [attachment] : []);
      });
    });

    image_frame.open();
  });

  // Reset default event image
  $("#seetickets_reset_default_image").on("click", function () {
    $("#seetickets_default_image_id").val("");
    $("#seetickets-preview-event-image").attr(
      "src",
      evusel_ajax_obj.defaultEvuselEventImage
    );
  });

  // Reset colors to defaults
  $("#seetickets_reset_default_colors").on("click", function () {
    $(
      'input[name="evusel_settings[color_theme][button_background_color]"]'
    ).spectrum("set", evusel_ajax_obj.defaultButtonBackgroundColor);
    $('input[name="evusel_settings[color_theme][button_text_color]"]').spectrum(
      "set",
      evusel_ajax_obj.defaultButtonTextColor
    );
    $(
      'input[name="evusel_settings[color_theme][button_text_hover_color]"]'
    ).spectrum("set", evusel_ajax_obj.defaultButtonTextHoverColor);
    $('input[name="evusel_settings[color_theme][background_color]"]').spectrum(
      "set",
      evusel_ajax_obj.defaultBackgroundColor
    );
    $('input[name="evusel_settings[color_theme][text_color]"]').spectrum(
      "set",
      evusel_ajax_obj.defaultTextColor
    );
  });

  // OLD HANDLER - DISABLED to prevent conflicts with our new implementation
  // Handling multiple client IDs
  $("button.delete-client-credentials").off("click");
  $("button.delete-client-credentials").on("click", function (e) {
    // Prevent any further handling
    e.preventDefault();
    e.stopPropagation();

    // Just remove the credential element
    $(this).closest(".api-credential-unit").remove();
  });

  document.addEventListener("DOMContentLoaded", function () {
    // Remove readonly and disabled attributes from all API credential inputs
    function makeCredentialInputsEditable() {
      document.querySelectorAll(".credential-input input").forEach((input) => {
        input.removeAttribute("readonly");
        input.removeAttribute("disabled");
      });
    }

    // Call immediately to fix existing inputs
    makeCredentialInputsEditable();
  });

  // Prevent users from entering numbers over max and below min values for number input fields
  $("input[type=number]").on("change", function () {
    let val = Number($(this).val());
    let max = Number($(this).attr("max"));
    let min = Number($(this).attr("min"));
    if (val > max) {
      $(this).val(max);
    }
    if (val < min) {
      $(this).val(min);
    }
  });

  /** Refresh shortcode field content immediately after changing settings */

  // Search shortcode
  const searchSelector =
    '[name="evusel_settings[shortcodes][event_search][search_parameters][]"]';
  $(searchSelector).on("change", function () {
    const values = $.map($(`${searchSelector}:checked`), function (v) {
      return v.value;
    });
    $("#event-search-shortcode-input").val(
      `[${evusel_ajax_obj.eventSearchShortcode} fields='${values.join(",")}']`
    );
  });

  $("#category-view-type").on("change", function () {
    var inputField = $("#category-filter-shortcode-input");
    if ($(this).val() === "g") {
      inputField.val(inputField.val().replace("list", "grid"));
    } else {
      inputField.val(inputField.val().replace("grid", "list"));
    }
  });
  $("#tag-view-type").on("change", function () {
    var inputField = $("#tag-filter-shortcode-input");
    if ($(this).val() === "g") {
      inputField.val(inputField.val().replace("list", "grid"));
    } else {
      inputField.val(inputField.val().replace("grid", "list"));
    }
  });

  if ($("#seetickets_css").length) {
    wp.codeEditor.initialize($("#seetickets_css"), evusel_code_editor_settings);
  }
  // Multiselect fields
  $(".shortcode-multiselect").on("change", function () {
    const fieldName = $(this).data("field-name");
    const shortcode = $(this).data("shortcode");
    const joinedValues = $(this).val().join(",");

    switch (fieldName) {
      case "tags":
        var type = "type=";
        type += $("#tag-view-type").val() === "l" ? "list" : "grid";
        break;
      case "categories":
        var type = "type=";
        type += $("#category-view-type").val() === "l" ? "list" : "grid";
        break;
      default:
        var type = "";
        break;
    }

    const values = `[${shortcode} ${fieldName}='${joinedValues}' ${type}]`;
    $(this).parents("tr").prev().find("input.shortcode-info-input").val(values);
  });

  /** End shortcode refresh */

  $("select#list-view-type").on("change", toggleListViewRelatedSettings);

  $("[name='evusel_settings[button_status_override]']").autocomplete({
    source: evusel_ajax_obj.statusOverrideSuggestions,
  });

  $("ul.event-card-elements-order").sortable();

  $("#convert-webp").on("click", function () {
    if (confirm("Do you want to start converting images?")) {
      $("#convert-webp-spinner").show();
      $.ajax({
        type: "POST",
        url: evusel_ajax_obj.ajax_url,
        dataType: "html",
        data: {
          action: "evusel_convert_to_webp",
          nonce: evusel_ajax_obj.nonce,
        },
        success: function (response) {
          $("#convert-webp-spinner").hide();
          alert(response);
        },
        error: function (response) {
          console.log("error", response);
          alert("There has been an error while converting files.");
        },
      });
    }
  });

  $(".ajax-run-feed").on("click", function () {
    let dashboardForm = $("#alerts-container");
    let id = +new Date();
    let statusNotice = $(
      "<div id=" +
        id +
        ' class="notice notice-warning is-dismissible notice-warning-started "><p>Import job started. Depending on the number of events, the process might take a while.</p><button type="button" class="notice-dismiss"></button></div>'
    );
    statusNotice.on("click.wp-dismiss-notice", initCloseDismissableNotice);
    hideElementHeartbeat(id, "firstCall");
    dashboardForm.before(statusNotice);
    $("#feed-status").html("In Progress");

    $.get(evusel_ajax_obj.cronEndpoint)
      .done(function (res) {
        let responseNotice = $(
          '<div class="notice  notice-warning is-dismissible notice-warning-started"><p></p><button type="button" class="notice-dismiss"></button></div>'
        );
        responseNotice.find("p").html(res.message);
        responseNotice.on(
          "click.wp-dismiss-notice",
          initCloseDismissableNotice
        );
        dashboardForm.before(responseNotice);
      })
      .fail(function (res) {
        console.error(res);
      });
  });

  $("#ajax-save").on("click", function () {
    let dashboardForm = $("#alerts-container");
    let id = +new Date();
    let statusNotice = $(
      "<div id=" +
        id +
        ' class="notice notice-warning is-dismissible notice-warning-started "><p>SAVE</p><button type="button" class="notice-dismiss"></button></div>'
    );
    statusNotice.on("click.wp-dismiss-notice", initCloseDismissableNotice);
    hideElementHeartbeat(id, "firstCall");
    dashboardForm.before(statusNotice);
    $("#feed-status").html("In Progress");

    $.get(evusel_ajax_obj.cronEndpoint)
      .done(function (res) {
        let responseNotice = $(
          '<div class="notice notice-warning notice-warning-started is-dismissible "><p></p><button type="button" class="notice-dismiss"></button></div>'
        );
        responseNotice.find("p").html(res.message);
        responseNotice.on(
          "click.wp-dismiss-notice",
          initCloseDismissableNotice
        );
        dashboardForm.before(responseNotice);
      })
      .fail(function (res) {
        console.error(res);
      });
  });

  // Disable any handlers for the old button ID
  $("#seetickets-add-new-client-id").off("click");

  // API Credentials handlers
  function handleDeleteCredential(e) {
    e.preventDefault();
    e.stopPropagation();
    var unit = $(this).closest(".api-credential-unit");
    if (unit.length) {
      unit.remove();
    }
  }

  function setupCredentialDeleteHandlers() {
    $(".delete-credential-btn").off("click", handleDeleteCredential);
    $(".delete-credential-btn").on("click", handleDeleteCredential);
  }

  var addButton = $("#add-new-credential-btn-2023");
  if (addButton.length) {
    addButton.on("click", function (e) {
      e.preventDefault();
      e.stopPropagation();

      var credentials = $(".api-credential-unit");
      var newIndex = credentials.length;

      var template =
        '<div class="api-credential-unit">' +
        '<div class="credential-input">' +
        "<label>API KEY</label>" +
        '<input type="text" class="custom-label-input api-input-field" ' +
        'data-group="' +
        newIndex +
        '" ' +
        'name="evusel_settings[api][client_credentials][' +
        newIndex +
        '][api_key]" />' +
        "</div>" +
        '<div class="credential-input">' +
        "<label>API SECRET</label>" +
        '<input type="password" class="custom-label-input api-input-field" ' +
        'data-group="' +
        newIndex +
        '" ' +
        'name="evusel_settings[api][client_credentials][' +
        newIndex +
        '][api_secret]" />' +
        "</div>" +
        '<div class="credential-input">' +
        "<label>CLIENT ID</label>" +
        '<input type="text" class="custom-label-input api-input-field" ' +
        'data-group="' +
        newIndex +
        '" ' +
        'name="evusel_settings[api][client_credentials][' +
        newIndex +
        '][client_id]" />' +
        "</div>" +
        '<div class="credential-action">' +
        '<button type="button" class="delete-credential-btn see-delete-all btn-delete-credential" ' +
        'title="Delete credentials">Delete</button>' +
        "</div>" +
        "</div>";

      var container = $(".api-credentials-container");
      if (container.length) {
        container.append(template);
        setupCredentialDeleteHandlers();

        var newInputs = container
          .find(".api-credential-unit")
          .last()
          .find(".credential-input input");
        newInputs.removeAttr("readonly").removeAttr("disabled");
      }
    });
  }

  setupCredentialDeleteHandlers();
});

// Heartbeat
jQuery(document).on("heartbeat-tick", function (event, data) {
  if (data.seetickets_feed_status === false) {
    $("#feed-status").css(see - feed - state - ready);
    jQuery("#feed-status").html("Ready");

    return;
  }
  if (data.seetickets_feed_status.status === "finished") {
    let dashboardForm = jQuery("#alerts-container");
    let id = +new Date();
    let heartbeatNotice = jQuery(
      `<div id='${id}' class="notice notice-warning notice-warning-started is-dismissible"><p>Finished running the import, processed ${data.seetickets_feed_status.processed_event_count} events from the feed(s).</p><button type="button" class="notice-dismiss"></button></div>`
    );
    heartbeatNotice.on("click.wp-dismiss-notice", initCloseDismissableNotice);
    dashboardForm.before(heartbeatNotice);
    hideElementHeartbeat(id, data.seetickets_feed_status.processed_event_count);

    jQuery("#feed-status").html("Ready");
  } else if (data.seetickets_feed_status.status === "in_progress") {
    jQuery("#feed-status").html("In Progress");
  }
});

function initCloseDismissableNotice(event) {
  event.preventDefault();
  jQuery(this).fadeTo(100, 0, function () {
    jQuery(this).slideUp(100, function () {
      jQuery(this).remove();
    });
  });
}

function toggleListViewRelatedSettings() {
  let val = jQuery(this).val();
  if (val === "l") {
    jQuery("#list_column_amount").hide();
    jQuery("#list_alternating_view").show();
    jQuery("#grid-navigation-type").hide();
    jQuery("#list-shortcode-input").val(
      `[${evusel_ajax_obj.listViewShortcode} type=list]`
    );
  } else if (val === "g") {
    jQuery("#list_column_amount").show();
    jQuery("#list_alternating_view").hide();
    jQuery("#grid-navigation-type").show();
    jQuery("#list-shortcode-input").val(
      `[${evusel_ajax_obj.listViewShortcode} type=grid]`
    );
  }
}

function initDeleteClientCredentialsAction(button) {
  // Only remove the credential, don't do anything else
  jQuery(button).parents("#api-credential-unit").remove();

  // Prevent other handlers from accidentally adding rows
  return false;
}

function Refresh_Image(the_id) {
  var data = {
    action: "evusel_get_default_event_image",
    default_image_id: the_id,
    nonce: evusel_ajax_obj.nonce,
  };

  jQuery.get(evusel_ajax_obj.ajax_url, data, function (response) {
    if (response.success === true) {
      jQuery("#seetickets-preview-event-image").attr(
        "src",
        response.data.image
      );
    }
  });
}

document.addEventListener("DOMContentLoaded", function () {
  var calOutlined = document.getElementById(
    "radio-material-list-style-outlined"
  );
  var calElevated = document.getElementById(
    "radio-material-list-style-elevated"
  );
  var hiddenOutlined = document.getElementById(
    "hidden-material-list-style-outlined-list"
  );
  var hiddenElevated = document.getElementById(
    "hidden-material-list-style-elevated-list"
  );

  if (calOutlined && calElevated && hiddenOutlined && hiddenElevated) {
    function updateHiddenMaterialStyle() {
      if (calOutlined.checked) {
        hiddenOutlined.disabled = false;
        hiddenElevated.disabled = true;
      } else if (calElevated.checked) {
        hiddenOutlined.disabled = true;
        hiddenElevated.disabled = false;
      }
    }
    calOutlined.addEventListener("change", updateHiddenMaterialStyle);
    calElevated.addEventListener("change", updateHiddenMaterialStyle);
    updateHiddenMaterialStyle();
  }
});

document
  .getElementById("seetickets_reset_default_colors")
  .addEventListener("click", function () {
    const colorInputs = document.querySelectorAll(
      '.color-picker-container input[type="color"]'
    );
    colorInputs.forEach((input) => {
      const originalValue = input.getAttribute("data-original");
      input.value = originalValue;

      // Update the displayed hex value
      const id = input.id.replace("color-picker-", "").replace("-output", "");
      document.getElementById(id + "-value").textContent = originalValue;
    });
  });

document.addEventListener("DOMContentLoaded", function () {
  const toggle = document.getElementById("force-button-toggle");
  const input = document.getElementById("force-button-input");
  const helperText = document.getElementById("helper-text");

  // Initial state check
  if (!input.value.trim()) {
    toggle.checked = false;
  }

  function checkHelperText() {
    if (toggle.checked && input.value.trim() === "") {
      helperText.style.display = "block";
    } else {
      helperText.style.display = "none";
    }
  }

  toggle.addEventListener("change", function () {
    if (!toggle.checked) {
      // Clear input when toggle is turned off
      input.value = "";
      helperText.style.display = "none";
    } else {
      // Show validation if toggle is turned on with empty input
      checkHelperText();
    }
  });

  input.addEventListener("input", function () {
    if (input.value.trim() === "") {
      toggle.checked = false;
    } else {
      toggle.checked = true;
    }
    checkHelperText();
  });

  // Check initial state
  checkHelperText();
});

const myTimeout = setTimeout(myGreeting, 5000);
function myGreeting() {
  document.getElementById("save-notification").style.display = "none";
}

function setMenuCurrentPage(input) {
  const url = new URL(window.location);
  url.searchParams.set("module", input);
  window.history.pushState({}, "", url);
}

function getQueryParameters() {
  let queryString = location.search.slice(1),
    params = {};

  queryString.replace(/([^=]*)=([^&]*)&*/g, (_, key, value) => {
    params[key] = value;
  });

  return params;
}

window.onload = function () {
  let stateMenu = getQueryParameters();
  goTo("undefined");
  goTo(stateMenu.module);
};

function goTo(input) {
  setMenuCurrentPage(input);
  var settingButtonItem = document.getElementById("settings-button");
  var eventListingsMenuItem = document.getElementById("event-listings");
  var menuFilterItem = document.getElementById("menu-filters");
  var customEventItem = document.getElementById("custom-event");

  if (input == "undefined") {
    settingButtonItem.classList.add("dispevli-menu-item-active");
    eventListingsMenuItem.classList.remove("dispevli-menu-item-active");
    menuFilterItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.remove("dispevli-menu-item-active");
    settingButtonItem.classList.add("dispevli-menu-item-active");
    eventListingsMenuItem.classList.remove("dispevli-menu-item-active");
    menuFilterItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.remove("dispevli-menu-item-active");
    document.getElementById("settings-container").style.display = "block";
    document.getElementById("event-listing-container").style.display = "none";
    document.getElementById("filters-container").style.display = "none";
    document.getElementById("color-selection-setup").style.display = "none";
  }

  if (input == "settings") {
    settingButtonItem.classList.add("dispevli-menu-item-active");
    eventListingsMenuItem.classList.remove("dispevli-menu-item-active");
    menuFilterItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.remove("dispevli-menu-item-active");
    document.getElementById("settings-container").style.display = "block";
    document.getElementById("event-listing-container").style.display = "none";
    document.getElementById("filters-container").style.display = "none";
    document.getElementById("color-selection-setup").style.display = "none";
  }

  if (input == "event-listings") {
    settingButtonItem.classList.remove("dispevli-menu-item-active");
    menuFilterItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.remove("dispevli-menu-item-active");
    eventListingsMenuItem.classList.add("dispevli-menu-item-active");
    document.getElementById("settings-container").style.display = "none";
    document.getElementById("event-listing-container").style.display = "block";
    document.getElementById("filters-container").style.display = "none";
    document.getElementById("color-selection-setup").style.display = "none";
  }

  if (input == "menu-filters") {
    menuFilterItem.classList.add("dispevli-menu-item-active");
    settingButtonItem.classList.remove("dispevli-menu-item-active");
    eventListingsMenuItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.remove("dispevli-menu-item-active");
    document.getElementById("settings-container").style.display = "none";
    document.getElementById("event-listing-container").style.display = "none";
    document.getElementById("filters-container").style.display = "block";
    document.getElementById("color-selection-setup").style.display = "none";
  }

  if (input == "custom-event") {
    settingButtonItem.classList.remove("dispevli-menu-item-active");
    eventListingsMenuItem.classList.remove("dispevli-menu-item-active");
    menuFilterItem.classList.remove("dispevli-menu-item-active");
    customEventItem.classList.add("dispevli-menu-item-active");
    document.getElementById("settings-container").style.display = "none";
    document.getElementById("event-listing-container").style.display = "none";
    document.getElementById("filters-container").style.display = "none";
    document.getElementById("color-selection-setup").style.display = "block";
  }
}
