document.addEventListener("DOMContentLoaded", async function () {
    let breadcrumbArray = [];

    try {
        const response = await fetch("/api/v1/frontend/breadcrumbs/");

        if (!response.ok) {
            console.error(`HTTP ${response.status}`);
            return;
        }

        breadcrumbArray = await response.json();
    } catch (err) {
        console.error("Failed to load breadcrumbs:", err);
        return;
    }

    // Get the breadcrumb container
    const breadcrumbContainer = document.getElementById("breadCrumb");

    if (!breadcrumbContainer) {
        return;
    }

    // Create the ul element
    const ul = document.createElement("ul");
    ul.classList.add("breadcrumbs", "mb-3");

    // Loop through the array to generate breadcrumb items
    breadcrumbArray.forEach((item, index) => {
        // Create the li for each item
        const li = document.createElement("li");
        li.classList.add("nav-item");

        // Create the anchor tag
        const a = document.createElement("a");

        if (index === breadcrumbArray.length - 1) {
            // Active page
            a.classList.add("active");
        } else {
            a.classList.add("text-info");
            a.href = item.href;
        }

        // Includes icons
        a.innerHTML = item.display;

        li.appendChild(a);
        ul.appendChild(li);

        // Add separator
        if (index < breadcrumbArray.length - 1) {
            const separator = document.createElement("li");
            separator.classList.add("separator");

            const arrowIcon = document.createElement("i");
            arrowIcon.classList.add("fa-solid", "fa-chevron-right");

            separator.appendChild(arrowIcon);
            ul.appendChild(separator);
        }
    });

    breadcrumbContainer.appendChild(ul);
});