$(document).ready(function () {
    searchIconColorChange();
});

$(window).on("load", function () {
    if (window.location.pathname === "/PoaClassification") {
        const authCookieValue = getCookie("PoaAuthCookie"); 

        if (authCookieValue) {
            setItemInPoaLocalStorage("poaAuthCookie", authCookieValue);
        }
    }
});

function togglerClicked(clickedElement) {
    let nested = $(clickedElement).parent().find(".nested");
    if (nested) {
        $(nested).first().toggleClass("active");
        $(clickedElement).toggleClass('fa-chevron-right fa-chevron-down');
    }
}

let debounceTimeout;
function searchClassifications() {
    clearTimeout(debounceTimeout);

    debounceTimeout = setTimeout(function () {
        getClassifications();
    }, 1000);
}

function getClassifications() {
    $("#poa-loading-classifications").removeAttr("hidden");

    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetClassificationsUrl").val(),
        data: { searchTerm: $("#searchTerm").val() },
        success: function (data) {
            $("#classificationTree").html(data);
            $("#poa-loading-classifications").attr("hidden", "hidden");
        },
        error: function () {
            $("#poa-loading-classifications").attr("hidden", "hidden");
            location.reload();
        }
    });
}

function searchIconColorChange() {
    $('.poa-input-focus').focus(function () {
        $(".poa-icon-focus").css('color', '#FAAF14');
    });

    $('.poa-input-focus').blur(function () {
        $(".poa-icon-focus").css('color', '');
    });
}

function showUserDropdown() {
    $("#poaUserDropdown").attr("hidden", function (_, attr) {
        return !attr;
    });
}

function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
        return parts.pop().split(';').shift();
    }
}

function logout() {
    swapLoadingIcon(true, "poa-logout-btn", "fa fa-sign-out-alt poa-logout-icon");
    removeItemFromPoaLocalStorage("poaAuthCookie");
    window.location.href = $("#LogOutUrl").val();
}