<?php
// Only show breadcrumb on Enhanced Package Detail Template
if (is_singular(array('romantic_package', 'travel_package')) && get_page_template_slug(get_queried_object_id()) === 'single-package.php') : ?>
    <div class="breadcrumb mx-auto" data-aos="fade-up" id="breadcrumb-container">
        <!-- Breadcrumb items will be populated by JavaScript -->
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        initializeBreadcrumb();
    });

    function initializeBreadcrumb() {
        const homeUrl = '<?php echo home_url(); ?>';
        const currentUrl = window.location.href;
        const currentTitle = '<?php echo esc_js(get_the_title()); ?>';

        let breadcrumbTrail = getBreadcrumbTrail();

        const currentPageIndex = breadcrumbTrail.findIndex(item => item.url === currentUrl);

        if (currentPageIndex !== -1) {
            breadcrumbTrail = breadcrumbTrail.slice(0, currentPageIndex + 1);
        } else {
            breadcrumbTrail.push({ title: currentTitle, url: currentUrl });
        }

        const maxBreadcrumbLength = 10;
        if (breadcrumbTrail.length > maxBreadcrumbLength) {
            breadcrumbTrail = breadcrumbTrail.slice(-maxBreadcrumbLength);
        }

        saveBreadcrumbTrail(breadcrumbTrail);
        displayBreadcrumb(breadcrumbTrail, homeUrl);
    }

    function getBreadcrumbTrail() {
        const stored = sessionStorage.getItem('breadcrumbTrail');
        if (stored) {
            try {
                return JSON.parse(stored);
            } catch (e) {
                console.warn('Error parsing breadcrumb trail:', e);
            }
        }
        return [];
    }

    function saveBreadcrumbTrail(trail) {
        try {
            sessionStorage.setItem('breadcrumbTrail', JSON.stringify(trail));
        } catch (e) {
            console.warn('Error saving breadcrumb trail:', e);
        }
    }

    function displayBreadcrumb(trail, homeUrl) {
        const container = document.getElementById('breadcrumb-container');
        if (!container) return;

        let breadcrumbHtml = `<a href="${homeUrl}" class="breadcrumb-item" data-breadcrumb-home="true">Home</a>`;

        trail.forEach((item, index) => {
            if (item.url === homeUrl || item.url === homeUrl + '/') return;

            breadcrumbHtml += ' <span class="separator">/</span> ';
            if (index < trail.length - 1) {
                breadcrumbHtml += `<a href="${item.url}" class="breadcrumb-item">${item.title}</a>`;
            } else {
                breadcrumbHtml += `<span class="breadcrumb-current">${item.title}</span>`;
            }
        });

        container.innerHTML = breadcrumbHtml;
    }
    </script>
<?php endif; ?>