/**
 * fast-nav.js - Navigasi tanpa reload penuh menggunakan NProgress + fetch
 * Versi 2.0 - Support custom content selector dan superadmin layout
 */
(function () {
    'use strict';

    // Konfigurasi NProgress
    NProgress.configure({
        minimum: 0.15,
        easing: 'ease',
        speed: 250,
        showSpinner: false,
        trickleSpeed: 400
    });

    // State navigasi
    var isNavigating = false;
    var currentUrl = window.location.href;

    // Cache untuk halaman yang sudah dikunjungi
    var pageCache = {};
    var MAX_CACHE = 10;
    var cacheKeys = [];

    // Ambil selector konten utama (support custom dari superadmin)
    function getContentSelector() {
        // Prioritaskan custom selector (set sebelum script ini diload)
        if (window.__fastNavContentSelector) {
            var el = document.querySelector(window.__fastNavContentSelector);
            if (el) return window.__fastNavContentSelector;
        }
        // Default selectors
        if (document.querySelector('main.page-content')) return 'main.page-content';
        if (document.querySelector('.page-content')) return '.page-content';
        return null;
    }

    function saveToCache(url, html) {
        if (cacheKeys.length >= MAX_CACHE) {
            var oldKey = cacheKeys.shift();
            delete pageCache[oldKey];
        }
        pageCache[url] = html;
        cacheKeys.push(url);
    }

    function getFromCache(url) {
        return pageCache[url] || null;
    }

    // Apakah URL ini bisa di-intercept?
    function canIntercept(url) {
        try {
            var parsed = new URL(url, window.location.href);
            if (parsed.origin !== window.location.origin) return false;
            var path = parsed.pathname;
            // Jangan intercept download, PDF, export, cetak
            if (/\.(pdf|xlsx|xls|csv|zip|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/i.test(path)) return false;
            if (/export|download|cetak|kuitansi-pdf|pdf$/i.test(path)) return false;
            // Jangan intercept logout (POST), tapi ini GET check
            if (/logout/i.test(path)) return false;
            // Jangan intercept anchor saja di halaman yang sama
            if (parsed.hash && parsed.pathname === window.location.pathname && parsed.search === window.location.search) return false;
            return true;
        } catch (e) {
            return false;
        }
    }

    // Parse dan ekstrak bagian dari HTML response
    function extractFromHtml(html, selector) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
        var el = doc.querySelector(selector);
        return { element: el, title: doc.title };
    }

    // Update active nav items berdasarkan URL baru
    function updateActiveNavItems(url) {
        var parsed = new URL(url);
        var path = parsed.pathname;

        document.querySelectorAll('.nav-item').forEach(function (item) {
            var href = item.getAttribute('href');
            if (!href) return;
            // Cek apakah path cocok dengan href
            var isActive = path === href || path.startsWith(href + '/') || path.startsWith(href + '?');
            // Handle wildcard-like matching (e.g., admin/user* matches admin/user/create)
            if (!isActive && href !== '/') {
                isActive = path.startsWith(href);
            }
            item.classList.toggle('active', isActive);
        });

        // Untuk topbar title
        var topbarTitle = document.querySelector('.topbar-title');
        if (topbarTitle) {
            // Update dari title elemen di halaman baru (sudah di-set via document.title)
        }
    }

    // Terapkan konten baru ke halaman
    function applyContent(newContent, title, url) {
        var selector = getContentSelector();
        var contentEl = selector ? document.querySelector(selector) : null;
        if (!contentEl || !newContent) {
            window.location.href = url;
            return;
        }

        // Fade out
        contentEl.style.transition = 'opacity 0.12s ease';
        contentEl.style.opacity = '0';
        contentEl.style.pointerEvents = 'none';

        setTimeout(function () {
            // Ganti konten
            contentEl.innerHTML = newContent.innerHTML;
            document.title = title;

            // Update URL di browser
            history.pushState({ url: url, fastNav: true }, title, url);
            currentUrl = url;

            // Update sidebar active state
            updateActiveNavItems(url);

            // Scroll ke atas
            if (selector === '.page-content' || selector === 'main.page-content') {
                window.scrollTo({ top: 0, behavior: 'instant' });
            } else {
                // Superadmin: scroll container konten
                contentEl.scrollTop = 0;
            }

            // Re-run inline scripts
            reinitScripts(contentEl);

            // Fade in
            requestAnimationFrame(function () {
                contentEl.style.opacity = '1';
                contentEl.style.pointerEvents = '';
            });

            // Selesai loading
            NProgress.done();
            isNavigating = false;

        }, 120);
    }

    // Re-init inline scripts di konten baru
    function reinitScripts(container) {
        var scripts = container.querySelectorAll('script:not([src])');
        scripts.forEach(function (oldScript) {
            var newScript = document.createElement('script');
            newScript.textContent = oldScript.textContent;
            oldScript.parentNode.replaceChild(newScript, oldScript);
        });
    }

    // Fungsi navigasi utama
    function navigate(url, useCache) {
        if (isNavigating) return;
        if (url === currentUrl) return;

        var contentSelector = getContentSelector();
        if (!contentSelector) {
            window.location.href = url;
            return;
        }

        isNavigating = true;
        NProgress.start();

        // Cek cache dulu
        if (useCache !== false) {
            var cached = getFromCache(url);
            if (cached) {
                var result = extractFromHtml(cached, contentSelector);
                if (result.element) {
                    applyContent(result.element, result.title, url);
                    return;
                }
            }
        }

        // Fetch halaman baru
        fetch(url, {
            headers: {
                'X-Requested-With': 'FastNav',
                'Accept': 'text/html,application/xhtml+xml',
                'X-FastNav': '1'
            },
            credentials: 'same-origin'
        })
        .then(function (response) {
            // Redirect otomatis (session expired -> login page)
            if (response.redirected) {
                window.location.href = response.url;
                return null;
            }
            if (!response.ok) {
                window.location.href = url;
                return null;
            }
            return response.text();
        })
        .then(function (html) {
            if (!html) return;

            saveToCache(url, html);
            var result = extractFromHtml(html, contentSelector);
            if (result.element) {
                applyContent(result.element, result.title, url);
            } else {
                // Layout berbeda (login page, dll), full reload
                window.location.href = url;
            }
        })
        .catch(function (err) {
            console.warn('[FastNav] Fetch error, falling back:', err);
            NProgress.done();
            isNavigating = false;
            window.location.href = url;
        });
    }

    // Intercept semua klik link
    document.addEventListener('click', function (e) {
        var target = e.target.closest('a[href]');
        if (!target) return;
        if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
        if (target.target === '_blank') return;
        if (target.hasAttribute('download')) return;
        if (target.getAttribute('data-no-fastnav') !== null) return;

        var href = target.getAttribute('href');
        if (!href) return;
        if (href.startsWith('#')) {
            // Scroll to anchor dalam halaman
            return;
        }
        if (href.startsWith('javascript:') || href.startsWith('mailto:') || href.startsWith('tel:')) return;

        var url = target.href;
        if (!canIntercept(url)) return;

        e.preventDefault();
        navigate(url);
    }, true);

    // Handle back/forward browser
    window.addEventListener('popstate', function (e) {
        if (e.state && e.state.fastNav) {
            navigate(window.location.href, true);
        } else {
            // State normal, biarkan browser handle atau reload
            var url = window.location.href;
            navigate(url, true);
        }
    });

    // NProgress selesai saat DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            NProgress.done();
        });
    } else {
        NProgress.done();
    }

    // Preload halaman saat hover link (100ms delay agar tidak berlebihan)
    var preloadTimer = null;
    var lastPreloadUrl = null;

    document.addEventListener('mouseover', function (e) {
        var target = e.target.closest('a[href]');
        if (!target) return;
        var href = target.href;
        if (!href || !canIntercept(href)) return;
        if (getFromCache(href)) return;
        if (href === lastPreloadUrl) return;

        clearTimeout(preloadTimer);
        lastPreloadUrl = href;
        preloadTimer = setTimeout(function () {
            fetch(href, {
                headers: {
                    'X-Requested-With': 'FastNav-Preload',
                    'X-FastNav': '1'
                },
                credentials: 'same-origin'
            }).then(function (r) {
                return r.ok ? r.text() : null;
            }).then(function (html) {
                if (html) saveToCache(href, html);
            }).catch(function () {});
        }, 80);
    });

    document.addEventListener('mouseout', function () {
        clearTimeout(preloadTimer);
    });

    // Expose untuk debugging
    window.__fastNav = {
        navigate: navigate,
        cache: pageCache,
        getContentSelector: getContentSelector
    };

})();
