jQuery(document).ready(function ($) {
  const $wrapper = $(".bible-schedule-wrapper");
  if ($wrapper.length === 0) return;

  const $container = $wrapper.find(".bible-schedule");
  const $daysPanel = $("#days-panel");
  const $daysList = $daysPanel.find(".days-list");
  const $loader = $wrapper.find(".bible-schedule-loader");
  const $navigation = $wrapper.find(".bible-schedule-navigation");
  const $currentDay = $wrapper.find("#current-day");
  const $bgSelect = $("#bible-bg-select");

  let isFetching = false;

  const getBrowserDayOfYear = () => {
    const now = new Date();
    const start = new Date(now.getFullYear(), 0, 0);
    const diff =
      now -
      start +
      (start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000;
    return Math.floor(diff / (1000 * 60 * 60 * 24));
  };

  const scrollToToday = () => {
    const $todayButton = $daysPanel.find(".is-today");
    if ($todayButton.length && $daysList.length) {
      const targetScroll =
        $todayButton.offset().top -
        $daysList.offset().top +
        $daysList.scrollTop();
      $daysList.animate({ scrollTop: targetScroll }, 500);
    }
  };

  const loadDay = (selectedDay) => {
    if (isFetching) return;

    isFetching = true;
    $daysPanel.removeClass("open");
    $loader.show();
    $container.hide();
    $navigation.hide();
    $currentDay.hide();

    const data = {
      action: "bibldare_load_bible_schedule",
      nonce: bibldareData.nonce,
      day: selectedDay,
      lang: $container.attr("data-lang") || bibldareData.lang,
      version: $container.attr("data-version") || bibldareData.version,
      background: $container.attr("data-background") || bibldareData.background,
      custom_background_color: $container.attr("data-custom-background-color") || bibldareData.custom_background_color || "",
      text_color: $container.attr("data-text-color") || bibldareData.text_color || "",
      timezone: $container.attr("data-timezone") || "",
    };

    $.post(bibldareData.ajaxUrl, data, function (response) {
      if (response.success) {
        $container.html(response.data.html).fadeIn();
        $currentDay.text(response.data.formatedDate).fadeIn();
        $navigation.fadeIn();

        $container.attr("data-day", selectedDay);
        $("#prev-day, #next-day").attr("data-day", selectedDay);
      }
    }).always(() => {
      isFetching = false;
      $loader.hide();
    });
  };

  $("#open-days").on("click", function (e) {
    e.stopPropagation();
    $daysPanel.toggleClass("open");
    if ($daysPanel.hasClass("open")) {
      setTimeout(scrollToToday, 100);
    }
  });

  $("#close-days").on("click", () => $daysPanel.removeClass("open"));

  $(document).on("click", function (e) {
    if (
      !$daysPanel.is(e.target) &&
      $daysPanel.has(e.target).length === 0 &&
      !$("#open-days").is(e.target)
    ) {
      $daysPanel.removeClass("open");
    }
  });

  $daysPanel.on("click", ".day-item", function () {
    loadDay($(this).data("day"));
  });

  $("#prev-day").on("click", function () {
    loadDay(parseInt($container.attr("data-day")) - 1);
  });

  $("#next-day").on("click", function () {
    loadDay(parseInt($container.attr("data-day")) + 1);
  });

  $bgSelect.on("change", function () {
    const bg = $(this).val();
    $container.attr("data-background", bg);

    $("#prev-day, #next-day")
      .removeClass("bible-bg-white bible-bg-black bible-bg-cream")
      .addClass("bible-bg-" + bg);

    loadDay(parseInt($container.attr("data-day")));
  });

  const browserToday = getBrowserDayOfYear();
  const cachedDay = parseInt($container.attr("data-day"));

  if (browserToday !== cachedDay) {
    $daysPanel.find(".day-item").removeClass("is-today").removeAttr("id");
    const $actualTodayItem = $daysPanel.find(
      `.day-item[data-day="${browserToday}"]`
    );
    $actualTodayItem.addClass("is-today").attr("id", "today-scroll-target");
    loadDay(browserToday);
  } else {
    loadDay(cachedDay);
  }

  scrollToToday();
});
