/* global jQuery */
(function ($) {
  "use strict";

  const contextMap = {
    dashboard: {
      title: "Dashboard",
      links: [
        { icon: "bi-grid-1x2-fill", label: "Overview", active: true },
        { icon: "bi-graph-up-arrow", label: "Learning Stats" },
        { icon: "bi-calendar-check", label: "Today Schedule" },
        { icon: "bi-megaphone", label: "Announcements" }
      ]
    },
    courses: {
      title: "My Courses",
      links: [
        { icon: "bi-book-half", label: "All Courses", active: true },
        { icon: "bi-play-circle", label: "In Progress" },
        { icon: "bi-check2-circle", label: "Completed" },
        { icon: "bi-clock-history", label: "Recently Viewed" }
      ]
    },
    certificates: {
      title: "Certificates",
      links: [
        { icon: "bi-patch-check", label: "My Certificates", active: true },
        { icon: "bi-download", label: "Download Center" },
        { icon: "bi-shield-check", label: "Verification" }
      ]
    },
    messages: {
      title: "Messages",
      links: [
        { icon: "bi-inbox", label: "Inbox", active: true },
        { icon: "bi-send", label: "Sent" },
        { icon: "bi-star", label: "Starred" },
        { icon: "bi-archive", label: "Archived" }
      ]
    },
    orders: {
      title: "Orders",
      links: [
        { icon: "bi-bag-check", label: "Order History", active: true },
        { icon: "bi-receipt", label: "Invoices" },
        { icon: "bi-credit-card", label: "Payment Methods" }
      ]
    }
  };

  function togglePassword(selector, $btn) {
    const $input = $(selector);
    if (!$input.length) return;

    const isPassword = $input.attr("type") === "password";
    $input.attr("type", isPassword ? "text" : "password");
    $btn.find("i").attr("class", isPassword ? "bi bi-eye-slash" : "bi bi-eye");
  }

  function renderContext(section) {
    if (!$("#contextTitle").length || !$("#contextLinks").length) return;

    const data = contextMap[section] || contextMap.dashboard;
    const $title = $("#contextTitle");
    const $links = $("#contextLinks");

    $title.text(data.title);
    const html = data.links
      .map(function (item) {
        const activeClass = item.active ? " is-active" : "";
        return (
          '<a href="#" class="context-link' +
          activeClass +
          '">' +
          '<i class="bi ' +
          item.icon +
          '"></i>' +
          "<span>" +
          item.label +
          "</span></a>"
        );
      })
      .join("");

    $links.html(html);
  }

  function closeSidebarOnMobile() {
    if (window.matchMedia("(max-width: 991.98px)").matches) {
      $("body").removeClass("sidebar-open");
    }
  }

  function initDashboard() {
    if (!$(".top-link").length) return;

    renderContext("dashboard");

    $(".top-link").on("click", function (e) {
      e.preventDefault();
      const section = $(this).data("section");
      $(".top-link").removeClass("is-active");
      $(this).addClass("is-active");
      renderContext(section);
      closeSidebarOnMobile();
    });

    $("#sidebarToggle, #layoutOverlay").on("click", function () {
      $("body").toggleClass("sidebar-open");
    });

    $("#sidebarClose").on("click", function () {
      $("body").removeClass("sidebar-open");
    });

    $("#contextLinks").on("click", ".context-link", function (e) {
      e.preventDefault();
      $("#contextLinks .context-link").removeClass("is-active");
      $(this).addClass("is-active");
      closeSidebarOnMobile();
    });

    $(window).on("resize", function () {
      if (window.matchMedia("(min-width: 992px)").matches) {
        $("body").removeClass("sidebar-open");
      }
    });
  }

  function initWelcomePopup() {
    const $popup = $("#welcomePopup");
    if (!$popup.length) return;

    const params = new URLSearchParams(window.location.search);
    if (params.get("succ") !== "1") return;

//    $popup.fadeIn();
//    setTimeout(function () {
//      $popup.fadeOut();
//    }, 2000);
//
//    window.history.replaceState({}, document.title, window.location.pathname);
  }

  function initAuthForms() {
    const $feedback = $("#formFeedback");

    $(".toggle-pass").on("click", function () {
      togglePassword($(this).data("target"), $(this));
    });

    $("#instructorLoginForm").on("submit", function (e) {
      const email = $("#email")[0];
      const $emailError = $("#emailError");

      if (email && email.validity.valueMissing) {
        $emailError.text("Enter Email Id.");
      } else if (email && email.validity.typeMismatch) {
        $emailError.text("Enter Valid Email Id.");
      }

      if (!this.checkValidity()) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass("was-validated");
        $feedback
          .removeClass("d-none alert-success")
          .addClass("alert-danger")
          .text("Enter Your Email Id and Password.");
      } else {
        $(this).addClass("was-validated");
      }
    });

    $("#instructorRegisterForm").on("submit", function (e) {
      if (!this.checkValidity()) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass("was-validated");
        $feedback
          .removeClass("d-none alert-success")
          .addClass("alert-danger")
          .text("All Fields Are Required.");
      } else {
        $(this).addClass("was-validated");
      }
    });
  }

  function initChangePasswordForm() {
    const $form = $("#change_password");
    const $feedback = $("#formFeedback");
    if (!$form.length) return;

    $form.on("submit", function (e) {
      e.preventDefault();

      const newPass = $("#newpassword").val();
      const cnfPass = $("#cnfpassword").val();

      if (!this.checkValidity()) {
        e.stopPropagation();
        $form.addClass("was-validated");
        $feedback
          .removeClass("d-none alert-success")
          .addClass("alert-danger")
          .text("All Fields Are Required.");
        return;
      }

      if (newPass !== cnfPass) {
        $("#cnfpassword").focus().addClass("is-invalid");
        $feedback
          .removeClass("d-none alert-success")
          .addClass("alert-danger")
          .text("New Password and Confirm Password do not match.");
        return;
      }

      $("#cnfpassword").removeClass("is-invalid");
      $feedback
        .removeClass("d-none alert-danger")
        .addClass("alert-success")
        .text("Password changed successfully.");
      this.submit();
    });

    $("#cnfpassword").on("keyup", function () {
      if ($("#newpassword").val() === $("#cnfpassword").val()) {
        $("#cnfpassword").removeClass("is-invalid");
        $("#formFeedback").addClass("d-none");
      }
    });
  }

  $(function () {
    initDashboard();
    initWelcomePopup();
    initAuthForms();
    initChangePasswordForm();
  });
})(jQuery);
