
<style>
    .unsaved-modal-overlay {
        position: fixed;
        inset: 0;
        background-color: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
        z-index: 99999;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        visibility: hidden;
        transition: all 0.2s ease-out;
    }

    .unsaved-modal-overlay.active {
        opacity: 1;
        visibility: visible;
    }

    .unsaved-modal {
        background: white;
        border-radius: 16px;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        max-width: 420px;
        width: 90%;
        transform: scale(0.95) translateY(10px);
        transition: all 0.2s ease-out;
        overflow: hidden;
    }

    .unsaved-modal-overlay.active .unsaved-modal {
        transform: scale(1) translateY(0);
    }

    .unsaved-modal-header {
        padding: 24px 24px 0;
        display: flex;
        align-items: flex-start;
        gap: 16px;
    }

    .unsaved-modal-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    .unsaved-modal-icon svg {
        width: 24px;
        height: 24px;
        color: #d97706;
    }

    .unsaved-modal-content {
        flex: 1;
    }

    .unsaved-modal-title {
        font-size: 18px;
        font-weight: 600;
        color: #111827;
        margin: 0 0 8px;
        font-family: 'Inter', system-ui, sans-serif;
    }

    .unsaved-modal-message {
        font-size: 14px;
        color: #6b7280;
        margin: 0;
        line-height: 1.5;
        font-family: 'Inter', system-ui, sans-serif;
    }

    .unsaved-modal-actions {
        padding: 24px;
        display: flex;
        gap: 12px;
        justify-content: flex-end;
    }

    .unsaved-modal-btn {
        padding: 10px 20px;
        border-radius: 10px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.15s ease;
        font-family: 'Inter', system-ui, sans-serif;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .unsaved-modal-btn-cancel {
        background: #f3f4f6;
        color: #374151;
    }

    .unsaved-modal-btn-cancel:hover {
        background: #e5e7eb;
    }

    .unsaved-modal-btn-confirm {
        background: linear-gradient(135deg, #6366f1, #4f46e5);
        color: white;
        box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.3);
    }

    .unsaved-modal-btn-confirm:hover {
        background: linear-gradient(135deg, #4f46e5, #4338ca);
        transform: translateY(-1px);
        box-shadow: 0 6px 10px -1px rgba(99, 102, 241, 0.4);
    }

    .dark .unsaved-modal {
        background: #1f2937;
    }

    .dark .unsaved-modal-icon {
        background: linear-gradient(135deg, #78350f, #92400e);
    }

    .dark .unsaved-modal-icon svg {
        color: #fbbf24;
    }

    .dark .unsaved-modal-title {
        color: #f9fafb;
    }

    .dark .unsaved-modal-message {
        color: #9ca3af;
    }

    .dark .unsaved-modal-btn-cancel {
        background: #374151;
        color: #e5e7eb;
    }

    .dark .unsaved-modal-btn-cancel:hover {
        background: #4b5563;
    }
</style>


<div id="unsavedChangesModal" class="unsaved-modal-overlay">
    <div class="unsaved-modal">
        <div class="unsaved-modal-header">
            <div class="unsaved-modal-icon">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                </svg>
            </div>
            <div class="unsaved-modal-content">
                <h3 class="unsaved-modal-title">Perubahan Belum Disimpan</h3>
                <p class="unsaved-modal-message">Anda memiliki perubahan yang belum disimpan. Apakah Anda yakin ingin meninggalkan halaman ini? Perubahan yang belum disimpan akan hilang.</p>
            </div>
        </div>
        <div class="unsaved-modal-actions">
            <button type="button" class="unsaved-modal-btn unsaved-modal-btn-cancel" id="unsavedModalCancel">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
                Tetap di Halaman
            </button>
            <button type="button" class="unsaved-modal-btn unsaved-modal-btn-confirm" id="unsavedModalConfirm">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" width="16" height="16">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9" />
                </svg>
                Tinggalkan Halaman
            </button>
        </div>
    </div>
</div>

<script>
(function() {
    'use strict';

    const modal = document.getElementById('unsavedChangesModal');
    const cancelBtn = document.getElementById('unsavedModalCancel');
    const confirmBtn = document.getElementById('unsavedModalConfirm');

    let pendingNavigation = null;
    let formHasChanges = false;
    let initialFormData = new Map();
    let isNavigating = false;

    // Debounce function
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // Get form signature (for tracking changes)
    function getFormSignature(form) {
        const inputs = form.querySelectorAll('input, select, textarea');
        const values = {};
        inputs.forEach(input => {
            const name = input.name || input.id || Math.random().toString(36).substr(2, 9);
            if (input.type === 'checkbox' || input.type === 'radio') {
                values[name] = input.checked;
            } else if (input.type === 'file') {
                values[name] = input.files.length;
            } else {
                values[name] = input.value;
            }
        });
        return JSON.stringify(values);
    }

    // Track form changes
    function trackFormChanges() {
        const forms = document.querySelectorAll('form');
        forms.forEach(form => {
            // Skip forms that are already tracked
            if (form.dataset.unsavedTracked === 'true') return;

            form.dataset.unsavedTracked = 'true';
            const formId = form.id || 'form-' + Math.random().toString(36).substr(2, 9);
            form.dataset.formId = formId;

            // Store initial form signature
            setTimeout(() => {
                initialFormData.set(formId, getFormSignature(form));
            }, 100);

            // Listen for input changes (debounced)
            const checkChanges = debounce(function() {
                const currentSignature = getFormSignature(form);
                const initialSignature = initialFormData.get(formId);
                formHasChanges = currentSignature !== initialSignature;
            }, 100);

            form.addEventListener('input', checkChanges);
            form.addEventListener('change', checkChanges);

            // Reset flag on form submit
            form.addEventListener('submit', function() {
                formHasChanges = false;
                isNavigating = true;
            });
        });
    }

    // Show modal function
    function showModal(callback) {
        pendingNavigation = callback;
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
        // Focus the cancel button for accessibility
        setTimeout(() => cancelBtn.focus(), 100);
    }

    // Hide modal function
    function hideModal() {
        modal.classList.remove('active');
        document.body.style.overflow = '';
        pendingNavigation = null;
    }

    // Cancel button - stay on page
    cancelBtn.addEventListener('click', function() {
        hideModal();
    });

    // Confirm button - proceed with navigation
    confirmBtn.addEventListener('click', function() {
        formHasChanges = false;
        isNavigating = true;
        if (pendingNavigation) {
            const nav = pendingNavigation;
            hideModal();
            nav();
        } else {
            hideModal();
        }
    });

    // Close on overlay click
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            hideModal();
        }
    });

    // Close on Escape key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && modal.classList.contains('active')) {
            hideModal();
        }
    });

    // Intercept regular link clicks (for wire:navigate links)
    document.addEventListener('click', function(e) {
        if (isNavigating) return;

        const link = e.target.closest('a[href]');
        if (!link || !formHasChanges) return;

        const href = link.getAttribute('href');

        // Skip certain links
        if (!href ||
            href.startsWith('#') ||
            href.startsWith('javascript:') ||
            href.startsWith('mailto:') ||
            href.startsWith('tel:') ||
            link.hasAttribute('download') ||
            link.target === '_blank') {
            return;
        }

        // Skip if it's a Filament action button (save, cancel, etc)
        if (link.closest('.fi-ac-btn-action') ||
            link.closest('[wire\\:click]') ||
            link.closest('button')) {
            return;
        }

        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        const hasWireNavigate = link.hasAttribute('wire:navigate');

        showModal(function() {
            isNavigating = true;
            if (hasWireNavigate && typeof Livewire !== 'undefined' && Livewire.navigate) {
                Livewire.navigate(href);
            } else {
                window.location.href = href;
            }
        });
    }, true);

    // Intercept browser back/forward and page close
    window.addEventListener('beforeunload', function(e) {
        if (formHasChanges && !isNavigating) {
            e.preventDefault();
            e.returnValue = 'Anda memiliki perubahan yang belum disimpan.';
            return e.returnValue;
        }
    });

    // Handle Livewire navigation events
    document.addEventListener('livewire:navigate', function(e) {
        if (formHasChanges && !isNavigating) {
            e.preventDefault();
            showModal(function() {
                formHasChanges = false;
                isNavigating = true;
                if (e.detail && e.detail.url) {
                    Livewire.navigate(e.detail.url);
                }
            });
        }
    });

    // Reset state after successful navigation
    document.addEventListener('livewire:navigated', function() {
        formHasChanges = false;
        isNavigating = false;
        initialFormData.clear();
        // Re-track forms on new page
        setTimeout(trackFormChanges, 200);
    });

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', trackFormChanges);
    } else {
        trackFormChanges();
    }

    // Re-track on Livewire updates
    if (typeof Livewire !== 'undefined') {
        Livewire.hook('morph.updated', () => {
            setTimeout(trackFormChanges, 100);
        });
    }

    // Also re-track on Alpine init (for dynamic components)
    document.addEventListener('alpine:initialized', function() {
        setTimeout(trackFormChanges, 200);
    });
})();
</script>
<?php /**PATH /Users/syahrilfadli/Documents/App - Syahril/presensi-nizhamia/backend/resources/views/filament/scripts/unsaved-changes-modal.blade.php ENDPATH**/ ?>