// Agency Panel JavaScript
document.addEventListener('DOMContentLoaded', function () {
    // Initialize agency panel
    initializeSidebar();
    initializeDropdowns();
    initializeAlerts();
    initializeTooltips();
});

// Sidebar functionality
function initializeSidebar() {
    const sidebar = document.getElementById('agencySidebar');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const mobileSidebarToggle = document.getElementById('mobileSidebarToggle');
    const sidebarBackdrop = document.getElementById('sidebarBackdrop');
    const mainContent = document.querySelector('.main-content');

    // Desktop sidebar toggle
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function () {
            sidebar.classList.toggle('collapsed');
            localStorage.setItem('sidebar-collapsed', sidebar.classList.contains('collapsed'));
        });
    }

    // Mobile sidebar toggle
    if (mobileSidebarToggle) {
        mobileSidebarToggle.addEventListener('click', function () {
            sidebar.classList.add('show');
            sidebarBackdrop.classList.add('show');
            document.body.style.overflow = 'hidden';
        });
    }

    // Close mobile sidebar
    if (sidebarBackdrop) {
        sidebarBackdrop.addEventListener('click', function () {
            closeMobileSidebar();
        });
    }

    // Handle escape key for mobile sidebar
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && sidebar.classList.contains('show')) {
            closeMobileSidebar();
        }
    });

    // Restore sidebar state from localStorage
    const sidebarCollapsed = localStorage.getItem('sidebar-collapsed');
    if (sidebarCollapsed === 'true') {
        sidebar.classList.add('collapsed');
    }

    // Close mobile sidebar on window resize
    window.addEventListener('resize', function () {
        if (window.innerWidth >= 992) {
            closeMobileSidebar();
        }
    });

    function closeMobileSidebar() {
        sidebar.classList.remove('show');
        sidebarBackdrop.classList.remove('show');
        document.body.style.overflow = '';
    }
}

// Initialize Bootstrap dropdowns
function initializeDropdowns() {
    // Auto-close dropdowns when clicking outside
    document.addEventListener('click', function (e) {
        const dropdowns = document.querySelectorAll('.dropdown-menu.show');
        dropdowns.forEach(dropdown => {
            if (!dropdown.closest('.dropdown').contains(e.target)) {
                const dropdownInstance = bootstrap.Dropdown.getInstance(dropdown.previousElementSibling);
                if (dropdownInstance) {
                    dropdownInstance.hide();
                }
            }
        });
    });
}

// Auto-hide alerts after 5 seconds
function initializeAlerts() {
    const alerts = document.querySelectorAll('.alert:not(.alert-permanent)');
    alerts.forEach(alert => {
        setTimeout(() => {
            if (alert.classList.contains('fade')) {
                alert.classList.remove('show');
                setTimeout(() => alert.remove(), 150);
            } else {
                alert.remove();
            }
        }, 10000); // Increased from 5000 to 10000 for better readability
    });
}

// Initialize tooltips
function initializeTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// Utility functions
const AgencyPanel = {
    // Show loading state
    showLoading: function (element) {
        if (element) {
            element.classList.add('loading');
        }
    },

    // Hide loading state
    hideLoading: function (element) {
        if (element) {
            element.classList.remove('loading');
        }
    },

    // Show notification
    showNotification: function (message, type = 'info', duration = 4000) {
        const alertClass = `alert-${type}`;
        const iconClass = {
            'success': 'fas fa-check-circle',
            'danger': 'fas fa-exclamation-circle',
            'warning': 'fas fa-exclamation-triangle',
            'info': 'fas fa-info-circle'
        }[type] || 'fas fa-info-circle';

        const alertHTML = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                <i class="${iconClass} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;

        const contentArea = document.querySelector('.content-area');
        if (contentArea) {
            contentArea.insertAdjacentHTML('afterbegin', alertHTML);

            // Auto-hide notification
            const newAlert = contentArea.querySelector('.alert');
            setTimeout(() => {
                if (newAlert && newAlert.classList.contains('show')) {
                    newAlert.classList.remove('show');
                    setTimeout(() => newAlert.remove(), 150);
                }
            }, duration);
        }
    },

    // Confirm dialog
    confirm: function (message, title = 'Onay') {
        return new Promise((resolve) => {
            if (confirm(`${title}\n\n${message}`)) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    },

    // Format number with thousand separators
    formatNumber: function (number) {
        return new Intl.NumberFormat('tr-TR').format(number);
    },

    // Format currency
    formatCurrency: function (amount, currency = 'TRY') {
        return new Intl.NumberFormat('tr-TR', {
            style: 'currency',
            currency: currency
        }).format(amount);
    },

    // Format date
    formatDate: function (date, options = {}) {
        const defaultOptions = {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        };
        return new Intl.DateTimeFormat('tr-TR', {...defaultOptions, ...options}).format(new Date(date));
    },

    // Debounce function
    debounce: function (func, wait, immediate) {
        let timeout;
        return function executedFunction() {
            const context = this;
            const args = arguments;
            const later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    },

    // AJAX helper
    ajax: function (url, options = {}) {
        const defaults = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
            }
        };

        const config = {...defaults, ...options};

        if (config.data && config.method !== 'GET') {
            config.body = JSON.stringify(config.data);
        }

        return fetch(url, config)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .catch(error => {
                console.error('AJAX Error:', error);
                this.showNotification('Bir hata oluştu. Lütfen tekrar deneyin.', 'danger');
                throw error;
            });
    }
};

// Export to global scope
window.AgencyPanel = AgencyPanel;

// Auto-refresh notifications every 5 minutes
setInterval(function () {
    // Uncomment when notification endpoint is ready
    // refreshNotifications();
}, 5 * 60 * 1000);

function refreshNotifications() {
    // Fetch new notifications and update the dropdown
    AgencyPanel.ajax('/agency/notifications/unread')
        .then(data => {
            updateNotificationBadge(data.count);
            updateNotificationDropdown(data.notifications);
        })
        .catch(error => {
            console.log('Notification refresh failed:', error);
        });
}

function updateNotificationBadge(count) {
    const badge = document.querySelector('.notification-badge');
    if (badge) {
        if (count > 0) {
            badge.textContent = count > 99 ? '99+' : count;
            badge.style.display = 'inline-block';
        } else {
            badge.style.display = 'none';
        }
    }
}

function updateNotificationDropdown(notifications) {
    const dropdown = document.querySelector('.notification-dropdown');
    if (dropdown && notifications) {
        // Update notification items
        // Implementation depends on notification structure
    }
}

// Form validation helpers
function validateForm(formElement) {
    const inputs = formElement.querySelectorAll('input[required], select[required], textarea[required]');
    let isValid = true;

    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('is-invalid');
            isValid = false;
        } else {
            input.classList.remove('is-invalid');
        }
    });

    return isValid;
}

// Real-time input validation
document.addEventListener('input', function (e) {
    if (e.target.hasAttribute('required')) {
        if (e.target.value.trim()) {
            e.target.classList.remove('is-invalid');
        }
    }
});

// Handle form submissions with loading states
document.addEventListener('submit', function (e) {
    const form = e.target;
    if (form.classList.contains('ajax-form')) {
        e.preventDefault();
        handleAjaxForm(form);
    } else if (form.classList.contains('validate-form')) {
        if (!validateForm(form)) {
            e.preventDefault();
            AgencyPanel.showNotification('Lütfen tüm gerekli alanları doldurun.', 'warning');
        } else {
            const submitBtn = form.querySelector('button[type="submit"]');
            if (submitBtn) {
                AgencyPanel.showLoading(submitBtn);
            }
        }
    }
});

function handleAjaxForm(form) {
    const formData = new FormData(form);
    const submitBtn = form.querySelector('button[type="submit"]');

    if (submitBtn) {
        AgencyPanel.showLoading(submitBtn);
    }

    fetch(form.action, {
        method: form.method,
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
        }
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                AgencyPanel.showNotification(data.message || 'İşlem başarıyla tamamlandı.', 'success');
                if (data.redirect) {
                    setTimeout(() => {
                        window.location.href = data.redirect;
                    }, 1000);
                }
            } else {
                AgencyPanel.showNotification(data.message || 'Bir hata oluştu.', 'danger');
            }
        })
        .catch(error => {
            console.error('Form submission error:', error);
            AgencyPanel.showNotification('Bir hata oluştu. Lütfen tekrar deneyin.', 'danger');
        })
        .finally(() => {
            if (submitBtn) {
                AgencyPanel.hideLoading(submitBtn);
            }
        });
}
