// OrangeHRM Admin Panel JavaScript

document.addEventListener('DOMContentLoaded', function() {
    // Initialize the admin panel
    initializeAdminPanel();
    
    // Set up event listeners
    setupEventListeners();
    
    // Load initial data
    loadDashboardData();
});

// Initialize Admin Panel
function initializeAdminPanel() {
    console.log('OrangeHRM Admin Panel Initialized');
    
    // Set active section based on URL hash
    const hash = window.location.hash.substring(1);
    if (hash) {
        showSection(hash);
    }
    
    // Start auto-refresh for notifications
    startAutoRefresh();
}

// Auto-refresh functionality
let autoRefreshInterval;

function startAutoRefresh() {
    // Check for new notifications every 30 seconds
    autoRefreshInterval = setInterval(() => {
        checkNotifications();
        
        // If we're on the quotes section, refresh the data
        const quotesSection = document.getElementById('quotes-section');
        if (quotesSection && quotesSection.style.display !== 'none') {
            loadQuotesData();
        }
    }, 30000); // 30 seconds
}

function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
    }
}

// Setup Event Listeners
function setupEventListeners() {
    // Sidebar toggle
    document.getElementById('sidebarCollapse').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
        document.getElementById('content').classList.toggle('active');
    });
    
    // Navigation menu items
    const navItems = document.querySelectorAll('[data-section]');
    navItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const section = this.getAttribute('data-section');
            showSection(section);
            
            // Update active state
            navItems.forEach(nav => nav.parentElement.classList.remove('active'));
            this.parentElement.classList.add('active');
        });
    });
    
    // Form submissions
    document.getElementById('starter-form').addEventListener('submit', function(e) {
        e.preventDefault();
        updateStarterPlan();
    });
    
    document.getElementById('advanced-form').addEventListener('submit', function(e) {
        e.preventDefault();
        updateAdvancedPlan();
    });
    
    // Module table edit buttons
    const editButtons = document.querySelectorAll('#modules-table .btn-warning');
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            editModule(this);
        });
    });
}

// Show Section
function showSection(sectionName) {
    // Hide all sections
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.style.display = 'none';
    });
    
    // Show selected section
    const targetSection = document.getElementById(sectionName + '-section');
    if (targetSection) {
        targetSection.style.display = 'block';
        
        // Load section-specific data
        loadSectionData(sectionName);
    }
    
    // Update URL hash
    window.location.hash = sectionName;
}

// Load Section Data
function loadSectionData(sectionName) {
    switch(sectionName) {
        case 'dashboard':
            loadDashboardData();
            break;
        case 'pricing':
            loadPricingData();
            break;
        case 'quotes':
            loadQuotesData();
            break;
        case 'analytics':
            loadAnalyticsData();
            break;
        default:
            console.log('Loading data for section:', sectionName);
    }
}

// Load Dashboard Data
function loadDashboardData() {
    if (!window.dataManager) return;
    
    // Get analytics data
    const analytics = window.dataManager.getAnalytics();
    const quoteStats = window.dataManager.getQuoteStatistics();
    const planStats = window.dataManager.getPlanStatistics();
    
    // Update dashboard statistics
    updateDashboardStats(analytics, quoteStats, planStats);
    
    // Load recent quotes
    loadDashboardQuotes();
    
    // Update plan popularity chart
    updatePlanChart(planStats);
}

// Update Dashboard Statistics
function updateDashboardStats(analytics, quoteStats, planStats) {
    // Update main stats cards
    animateValue('active-plans', 0, 2, 1000); // Always 2 plans
    animateValue('quote-requests', 0, quoteStats.total, 1000);
    animateValue('active-users', 0, analytics.active_users / 1000000, 1000, true); // Convert to millions
    animateValue('countries', 0, analytics.countries, 1000);
    
    // Update conversion metrics
    document.getElementById('conversion-rate').textContent = analytics.conversion_rate + '%';
    document.getElementById('response-time').textContent = analytics.avg_response_time + 'h';
    document.getElementById('growth-rate').textContent = analytics.monthly_growth + '%';
}

// Animate Number Counting
function animateValue(id, start, end, duration) {
    const element = document.getElementById(id);
    if (!element) return;
    
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
            element.textContent = end;
            clearInterval(timer);
        } else {
            element.textContent = Math.round(current);
        }
    }, 16);
}

// Load Dashboard Quotes
function loadDashboardQuotes() {
    const quotes = window.dataManager.getQuotes();
    const tbody = document.getElementById('dashboard-quotes-tbody');
    if (!tbody) return;
    
    // Get latest 5 quotes
    const latestQuotes = quotes
        .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
        .slice(0, 5);
    
    tbody.innerHTML = '';
    
    latestQuotes.forEach(quote => {
        const row = document.createElement('tr');
        const date = new Date(quote.timestamp);
        const formattedDate = date.toLocaleDateString();
        
        row.innerHTML = `
            <td><strong>${quote.company}</strong></td>
            <td>${quote.name}</td>
            <td><span class="badge bg-${quote.selected_plan === 'starter' ? 'success' : 'primary'}">${capitalizeFirst(quote.selected_plan)}</span></td>
            <td>${formattedDate}</td>
            <td><span class="badge bg-${getStatusColor(quote.status)}">${capitalizeFirst(quote.status)}</span></td>
        `;
        tbody.appendChild(row);
    });
}

// Update Quotes Table
function updateQuotesTable(quotes) {
    const tbody = document.querySelector('#dashboard-section table tbody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    quotes.forEach(quote => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${quote.company}</td>
            <td>${quote.email}</td>
            <td>${quote.plan}</td>
            <td>${quote.date}</td>
            <td><span class="badge bg-${getStatusColor(quote.status)}">${capitalizeFirst(quote.status)}</span></td>
        `;
        tbody.appendChild(row);
    });
}

// Get Status Color
function getStatusColor(status) {
    switch(status) {
        case 'pending': return 'warning';
        case 'contacted': return 'success';
        case 'converted': return 'primary';
        default: return 'secondary';
    }
}

// Capitalize First Letter
function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// Load Pricing Data
function loadPricingData() {
    if (!window.dataManager) return;
    
    const pricing = window.dataManager.getPricing();
    
    // Update starter plan form
    if (pricing.starter) {
        document.getElementById('starter-name').value = pricing.starter.name || 'Starter (Open Source)';
        document.getElementById('starter-description').value = pricing.starter.description || '';
        document.getElementById('starter-audience').value = pricing.starter.target_audience || '';
        document.getElementById('starter-features').value = pricing.starter.features ? pricing.starter.features.join(', ') : '';
    }
    
    // Update advanced plan form
    if (pricing.advanced) {
        document.getElementById('advanced-name').value = pricing.advanced.name || 'Advanced (Enterprise)';
        document.getElementById('advanced-base-price').value = pricing.advanced.base_price || 4.00;
        document.getElementById('advanced-description').value = pricing.advanced.description || '';
        document.getElementById('advanced-trial').value = pricing.advanced.free_trial || '';
        document.getElementById('advanced-features').value = pricing.advanced.features ? pricing.advanced.features.join(', ') : '';
    }
}

// Update Starter Plan
function updateStarterPlan() {
    if (!window.dataManager) return;
    
    const formData = new FormData(document.getElementById('starter-form'));
    const data = {
        name: formData.get('name'),
        description: formData.get('description'),
        target_audience: formData.get('target_audience'),
        features: formData.get('features').split(',').map(f => f.trim())
    };
    
    // Show loading state
    showNotification('Updating Starter Plan...', 'info');
    
    // Update data
    window.dataManager.updatePricing('starter', data);
    
    setTimeout(() => {
        showNotification('Starter Plan updated successfully!', 'success');
    }, 1000);
}

// Update Advanced Plan
function updateAdvancedPlan() {
    if (!window.dataManager) return;
    
    const formData = new FormData(document.getElementById('advanced-form'));
    const data = {
        name: formData.get('name'),
        base_price: parseFloat(formData.get('base_price')),
        description: formData.get('description'),
        free_trial: formData.get('free_trial'),
        features: formData.get('features').split(',').map(f => f.trim())
    };
    
    // Show loading state
    showNotification('Updating Advanced Plan...', 'info');
    
    // Update data
    window.dataManager.updatePricing('advanced', data);
    
    setTimeout(() => {
        showNotification('Advanced Plan updated successfully!', 'success');
    }, 1000);
}

// Edit Module
function editModule(button) {
    const row = button.closest('tr');
    const cells = row.querySelectorAll('td');
    
    const moduleName = cells[0].textContent;
    const currentPrice = cells[1].textContent;
    
    // Create edit modal (simplified for this example)
    const newPrice = prompt(`Update price for ${moduleName}:`, currentPrice.replace('$', ''));
    
    if (newPrice !== null && newPrice !== '') {
        cells[1].textContent = `$${parseFloat(newPrice).toFixed(2)}`;
        showNotification(`${moduleName} price updated to $${parseFloat(newPrice).toFixed(2)}`, 'success');
    }
}

// Add New Module
function addModule() {
    const moduleName = prompt('Enter module name:');
    if (!moduleName) return;
    
    const price = prompt('Enter price (PEPM):');
    if (!price) return;
    
    const table = document.getElementById('modules-table').getElementsByTagName('tbody')[0];
    const newRow = table.insertRow();
    
    newRow.innerHTML = `
        <td>${moduleName}</td>
        <td>$${parseFloat(price).toFixed(2)}</td>
        <td><input type="checkbox" disabled></td>
        <td><input type="checkbox" checked></td>
        <td><button class="btn btn-sm btn-warning" onclick="editModule(this)">Edit</button></td>
    `;
    
    showNotification(`Module "${moduleName}" added successfully!`, 'success');
}

// Load Quotes Data
function loadQuotesData() {
    console.log('Loading quotes data...');
    
    // Get quotes from localStorage
    const quotes = JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
    
    // Update statistics
    updateQuoteStatistics(quotes);
    
    // Update quotes table
    updateQuotesTable(quotes);
    
    // Check for new notifications
    checkNotifications();
}

// Update Quote Statistics
function updateQuoteStatistics(quotes) {
    const stats = {
        pending: quotes.filter(q => q.status === 'pending').length,
        contacted: quotes.filter(q => q.status === 'contacted').length,
        converted: quotes.filter(q => q.status === 'converted').length,
        total: quotes.length
    };
    
    // Update the dashboard cards
    animateValue('pending-count', 0, stats.pending, 500);
    animateValue('contacted-count', 0, stats.contacted, 500);
    animateValue('converted-count', 0, stats.converted, 500);
    animateValue('total-count', 0, stats.total, 500);
}

// Update Quotes Table
function updateQuotesTable(quotes) {
    const tbody = document.getElementById('quotes-tbody');
    const noQuotes = document.getElementById('no-quotes');
    
    if (!tbody) return;
    
    if (quotes.length === 0) {
        tbody.innerHTML = '';
        noQuotes.style.display = 'block';
        return;
    }
    
    noQuotes.style.display = 'none';
    tbody.innerHTML = '';
    
    // Sort quotes by date (newest first)
    const sortedQuotes = quotes.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    
    sortedQuotes.forEach((quote, index) => {
        const row = document.createElement('tr');
        const date = new Date(quote.timestamp);
        const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
        
        row.innerHTML = `
            <td><strong>${quote.company}</strong></td>
            <td>${quote.name}<br><small class="text-muted">${quote.job_title}</small></td>
            <td><a href="mailto:${quote.email}">${quote.email}</a></td>
            <td>${quote.phone}</td>
            <td>${quote.employees}</td>
            <td><span class="badge bg-${quote.selected_plan === 'starter' ? 'success' : 'primary'}">${capitalizeFirst(quote.selected_plan)}</span></td>
            <td>${formatModules(quote.modules)}</td>
            <td>${formattedDate}</td>
            <td><span class="badge bg-${getStatusColor(quote.status)}">${capitalizeFirst(quote.status)}</span></td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewQuoteDetails(${index})" title="View Details">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="updateQuoteStatus(${index}, 'contacted')" title="Mark as Contacted">
                        <i class="fas fa-phone"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="updateQuoteStatus(${index}, 'converted')" title="Mark as Converted">
                        <i class="fas fa-check"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteQuote(${index})" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// Format Modules Display
function formatModules(modules) {
    if (!modules || modules.length === 0) return 'None';
    
    const moduleNames = {
        'recruitment': 'Recruitment',
        'onboarding': 'Onboarding',
        'performance': 'Performance',
        'time_attendance': 'Time & Attendance',
        'leave': 'Leave Management',
        'payroll': 'Payroll'
    };
    
    return modules.slice(0, 2).map(m => moduleNames[m] || m).join(', ') + 
           (modules.length > 2 ? ` +${modules.length - 2}` : '');
}

// View Quote Details
function viewQuoteDetails(index) {
    const quotes = JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
    const quote = quotes[index];
    
    if (!quote) return;
    
    // Create modal for quote details
    const modalHtml = `
        <div class="modal fade" id="quoteDetailsModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Quote Request Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Company Information</h6>
                                <p><strong>Company:</strong> ${quote.company}</p>
                                <p><strong>Industry:</strong> ${capitalizeFirst(quote.industry)}</p>
                                <p><strong>Employees:</strong> ${quote.employees}</p>
                                <p><strong>Country:</strong> ${quote.country}</p>
                            </div>
                            <div class="col-md-6">
                                <h6>Contact Information</h6>
                                <p><strong>Name:</strong> ${quote.name}</p>
                                <p><strong>Title:</strong> ${quote.job_title}</p>
                                <p><strong>Email:</strong> <a href="mailto:${quote.email}">${quote.email}</a></p>
                                <p><strong>Phone:</strong> ${quote.phone}</p>
                            </div>
                        </div>
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <h6>Plan Selection</h6>
                                <p><strong>Interested Plan:</strong> <span class="badge bg-${quote.selected_plan === 'starter' ? 'success' : 'primary'}">${capitalizeFirst(quote.selected_plan)}</span></p>
                                ${quote.modules && quote.modules.length > 0 ? `
                                    <p><strong>Modules:</strong></p>
                                    <ul class="list-unstyled">
                                        ${quote.modules.map(m => `<li><i class="fas fa-check text-success"></i> ${formatModules([m])}</li>`).join('')}
                                    </ul>
                                ` : ''}
                            </div>
                            <div class="col-md-6">
                                <h6>Additional Information</h6>
                                <p><strong>Status:</strong> <span class="badge bg-${getStatusColor(quote.status)}">${capitalizeFirst(quote.status)}</span></p>
                                <p><strong>Submitted:</strong> ${new Date(quote.timestamp).toLocaleString()}</p>
                                ${quote.message ? `<p><strong>Message:</strong> ${quote.message}</p>` : ''}
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-success" onclick="updateQuoteStatus(${index}, 'contacted'); bootstrap.Modal.getInstance(document.getElementById('quoteDetailsModal')).hide();">Mark as Contacted</button>
                        <button type="button" class="btn btn-info" onclick="updateQuoteStatus(${index}, 'converted'); bootstrap.Modal.getInstance(document.getElementById('quoteDetailsModal')).hide();">Mark as Converted</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('quoteDetailsModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to page and show it
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    const modal = new bootstrap.Modal(document.getElementById('quoteDetailsModal'));
    modal.show();
}

// Update Quote Status
async function updateQuoteStatus(index, newStatus) {
    const quotes = JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
    
    if (quotes[index]) {
        // Use the async method from data manager
        if (window.dataManager) {
            await window.dataManager.updateQuoteStatus(quotes[index].id, newStatus);
        }
        
        showNotification(`Quote status updated to ${capitalizeFirst(newStatus)}`, 'success');
        loadQuotesData(); // Refresh the data
    }
}

// Delete Quote
async function deleteQuote(index) {
    if (confirm('Are you sure you want to delete this quote request?')) {
        const quotes = JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
        
        if (quotes[index]) {
            // Use the async method from data manager
            if (window.dataManager) {
                await window.dataManager.deleteQuote(quotes[index].id);
            }
            
            showNotification('Quote request deleted', 'warning');
            loadQuotesData(); // Refresh the data
        }
    }
}

// Check Notifications
function checkNotifications() {
    const notifications = JSON.parse(localStorage.getItem('orangehrm_notifications') || '[]');
    const unreadNotifications = notifications.filter(n => !n.read);
    
    const badge = document.getElementById('notification-badge');
    const notificationsList = document.getElementById('notifications-list');
    const noNotifications = document.getElementById('no-notifications');
    
    if (unreadNotifications.length > 0) {
        badge.textContent = unreadNotifications.length;
        badge.style.display = 'block';
        
        // Update notifications list
        const existingItems = notificationsList.querySelectorAll('li:not(:first-child):not(:nth-child(2))');
        existingItems.forEach(item => item.remove());
        
        unreadNotifications.slice(0, 5).forEach(notification => {
            const li = document.createElement('li');
            li.innerHTML = `
                <a class="dropdown-item" href="#" onclick="handleNotificationClick('${notification.timestamp}')">
                    <div class="d-flex">
                        <div class="flex-shrink-0">
                            <i class="fas fa-${getNotificationIcon(notification.type)} text-${getNotificationColor(notification.type)}"></i>
                        </div>
                        <div class="flex-grow-1 ms-2">
                            <div class="small">${notification.message}</div>
                            <div class="text-muted small">${formatNotificationTime(notification.timestamp)}</div>
                        </div>
                    </div>
                </a>
            `;
            notificationsList.appendChild(li);
        });
        
        noNotifications.style.display = 'none';
    } else {
        badge.style.display = 'none';
        noNotifications.style.display = 'block';
    }
}

// Get Notification Icon
function getNotificationIcon(type) {
    switch(type) {
        case 'new_quote': return 'file-invoice';
        case 'quote_updated': return 'edit';
        default: return 'bell';
    }
}

// Get Notification Color
function getNotificationColor(type) {
    switch(type) {
        case 'new_quote': return 'success';
        case 'quote_updated': return 'primary';
        default: return 'info';
    }
}

// Format Notification Time
function formatNotificationTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffMins < 1440) return `${Math.floor(diffMins / 60)} hours ago`;
    return date.toLocaleDateString();
}

// Handle Notification Click
function handleNotificationClick(timestamp) {
    // Mark notification as read
    const notifications = JSON.parse(localStorage.getItem('orangehrm_notifications') || '[]');
    const notification = notifications.find(n => n.timestamp === timestamp);
    if (notification) {
        notification.read = true;
        localStorage.setItem('orangehrm_notifications', JSON.stringify(notifications));
    }
    
    // Navigate to quotes section
    showSection('quotes');
    checkNotifications();
}

// Refresh Quotes
function refreshQuotes() {
    showNotification('Refreshing quotes...', 'info');
    loadQuotesData();
}

// Export Quotes
function exportQuotes() {
    const quotes = JSON.parse(localStorage.getItem('orangehrm_quotes') || '[]');
    
    if (quotes.length === 0) {
        showNotification('No quotes to export', 'warning');
        return;
    }
    
    // Create CSV content
    const headers = ['Company', 'Name', 'Email', 'Phone', 'Industry', 'Employees', 'Country', 'Plan', 'Modules', 'Message', 'Status', 'Date'];
    const csvContent = [
        headers.join(','),
        ...quotes.map(q => [
            `"${q.company}"`,
            `"${q.name}"`,
            `"${q.email}"`,
            `"${q.phone}"`,
            `"${q.industry}"`,
            `"${q.employees}"`,
            `"${q.country}"`,
            `"${q.selected_plan}"`,
            `"${q.modules ? q.modules.join('; ') : ''}"`,
            `"${q.message || ''}"`,
            `"${q.status}"`,
            `"${new Date(q.timestamp).toLocaleString()}"`
        ].join(','))
    ].join('\n');
    
    // Download CSV file
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `orangehrm_quotes_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
    
    showNotification('Quotes exported successfully', 'success');
}

// Load Analytics Data
function loadAnalyticsData() {
    console.log('Loading analytics data...');
    // This would typically fetch analytics data from an API
}

// Show Notification
function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 5000);
}

// Export Data (for analytics section)
function exportData(format) {
    showNotification(`Exporting data as ${format.toUpperCase()}...`, 'info');
    
    // Simulate export process
    setTimeout(() => {
        showNotification(`Data exported successfully as ${format.toUpperCase()}!`, 'success');
    }, 2000);
}

// Filter Data
function filterData(section, filters) {
    console.log(`Filtering ${section} data with:`, filters);
    // This would implement filtering logic
}

// Search Data
function searchData(section, query) {
    console.log(`Searching ${section} for:`, query);
    // This would implement search logic
}

// Validate Form
function validateForm(formId) {
    const form = document.getElementById(formId);
    const inputs = form.querySelectorAll('input[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;
}

// Format Currency
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

// Format Date
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('en-US', options);
}

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

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

// Initialize modals
function initializeModals() {
    const modalTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="modal"]'));
    modalTriggerList.map(function (modalTriggerEl) {
        return new bootstrap.Modal(modalTriggerEl);
    });
}

// Handle keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + S to save
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        // Find the active form and submit it
        const activeSection = document.querySelector('.content-section:not([style*="display: none"])');
        const form = activeSection ? activeSection.querySelector('form') : null;
        if (form) {
            form.dispatchEvent(new Event('submit'));
        }
    }
    
    // Escape to close modals
    if (e.key === 'Escape') {
        const openModal = document.querySelector('.modal.show');
        if (openModal) {
            bootstrap.Modal.getInstance(openModal).hide();
        }
    }
});

// Auto-save functionality
let autoSaveTimer;
function setupAutoSave() {
    const forms = document.querySelectorAll('form');
    
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, textarea, select');
        
        inputs.forEach(input => {
            input.addEventListener('input', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(() => {
                    // Auto-save logic here
                    console.log('Auto-saving form data...');
                }, 2000);
            });
        });
    });
}

// Meeting Requests Management
function loadMeetingRequests() {
    const adminData = JSON.parse(localStorage.getItem('payonline_admin_data') || '{}');
    const meetingRequests = adminData.meeting_requests || [];
    
    updateMeetingStatistics(meetingRequests);
    displayMeetingRequests(meetingRequests);
}

function updateMeetingStatistics(requests) {
    const total = requests.length;
    const pending = requests.filter(r => r.status === 'pending').length;
    const scheduled = requests.filter(r => r.status === 'scheduled').length;
    
    // Calculate this month's requests
    const currentMonth = new Date().getMonth();
    const currentYear = new Date().getFullYear();
    const monthly = requests.filter(r => {
        const requestDate = new Date(r.created_at);
        return requestDate.getMonth() === currentMonth && requestDate.getFullYear() === currentYear;
    }).length;
    
    // Update dashboard
    document.getElementById('total-meeting-requests').textContent = total;
    document.getElementById('pending-meetings').textContent = pending;
    document.getElementById('scheduled-meetings').textContent = scheduled;
    document.getElementById('monthly-meetings').textContent = monthly;
}

function displayMeetingRequests(requests) {
    const tbody = document.getElementById('meetings-tbody');
    const noMeetings = document.getElementById('no-meetings');
    
    if (requests.length === 0) {
        tbody.innerHTML = '';
        noMeetings.style.display = 'block';
        return;
    }
    
    noMeetings.style.display = 'none';
    
    tbody.innerHTML = requests.map(request => `
        <tr>
            <td>
                <strong>${request.company_name}</strong>
                ${request.client_code ? `<br><small class="text-muted">Code: ${request.client_code}</small>` : ''}
            </td>
            <td>${request.full_name}</td>
            <td>
                <a href="mailto:${request.email}">${request.email}</a>
            </td>
            <td>
                <a href="tel:${request.phone}">${request.phone}</a>
            </td>
            <td>${request.role || '-'}</td>
            <td>${request.client_code || '-'}</td>
            <td>
                <small>${formatDate(request.created_at)}</small>
            </td>
            <td>
                <span class="badge ${getStatusBadgeClass(request.status)}">
                    ${request.status || 'pending'}
                </span>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewMeetingRequest('${request.id}')" title="View Details">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="updateMeetingStatus('${request.id}', 'scheduled')" title="Mark as Scheduled">
                        <i class="fas fa-check"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteMeetingRequest('${request.id}')" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
        </tr>
    `).join('');
}

function getStatusBadgeClass(status) {
    switch (status) {
        case 'scheduled': return 'bg-success';
        case 'cancelled': return 'bg-danger';
        case 'pending': return 'bg-warning';
        default: return 'bg-secondary';
    }
}

function viewMeetingRequest(requestId) {
    const adminData = JSON.parse(localStorage.getItem('payonline_admin_data') || '{}');
    const request = adminData.meeting_requests.find(r => r.id === requestId);
    
    if (!request) return;
    
    // Create modal content
    const modalContent = `
        <div class="modal fade" id="meetingRequestModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Meeting Request Details</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Company Information</h6>
                                <p><strong>Company:</strong> ${request.company_name}</p>
                                <p><strong>Client Code:</strong> ${request.client_code || 'N/A'}</p>
                                <p><strong>Contact Person:</strong> ${request.full_name}</p>
                                <p><strong>Role:</strong> ${request.role || 'N/A'}</p>
                            </div>
                            <div class="col-md-6">
                                <h6>Contact Information</h6>
                                <p><strong>Email:</strong> <a href="mailto:${request.email}">${request.email}</a></p>
                                <p><strong>Phone:</strong> <a href="tel:${request.phone}">${request.phone}</a></p>
                                <p><strong>Zip Code:</strong> ${request.zip_code || 'N/A'}</p>
                                <p><strong>Date:</strong> ${formatDate(request.created_at)}</p>
                            </div>
                        </div>
                        ${request.message ? `
                            <div class="mt-3">
                                <h6>Message</h6>
                                <div class="border rounded p-3 bg-light">
                                    ${request.message}
                                </div>
                            </div>
                        ` : ''}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-success" onclick="updateMeetingStatus('${request.id}', 'scheduled')">
                            Mark as Scheduled
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    const existingModal = document.getElementById('meetingRequestModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // Add modal to page and show it
    document.body.insertAdjacentHTML('beforeend', modalContent);
    const modal = new bootstrap.Modal(document.getElementById('meetingRequestModal'));
    modal.show();
}

function updateMeetingStatus(requestId, newStatus) {
    const adminData = JSON.parse(localStorage.getItem('payonline_admin_data') || '{}');
    const requestIndex = adminData.meeting_requests.findIndex(r => r.id === requestId);
    
    if (requestIndex !== -1) {
        adminData.meeting_requests[requestIndex].status = newStatus;
        localStorage.setItem('payonline_admin_data', JSON.stringify(adminData));
        
        // Refresh the display
        loadMeetingRequests();
        
        // Close modal if open
        const modal = bootstrap.Modal.getInstance(document.getElementById('meetingRequestModal'));
        if (modal) modal.hide();
        
        // Show notification
        showNotification('Meeting request status updated successfully!', 'success');
    }
}

function deleteMeetingRequest(requestId) {
    if (!confirm('Are you sure you want to delete this meeting request?')) return;
    
    const adminData = JSON.parse(localStorage.getItem('payonline_admin_data') || '{}');
    adminData.meeting_requests = adminData.meeting_requests.filter(r => r.id !== requestId);
    localStorage.setItem('payonline_admin_data', JSON.stringify(adminData));
    
    loadMeetingRequests();
    showNotification('Meeting request deleted successfully!', 'success');
}

function refreshMeetingRequests() {
    loadMeetingRequests();
    showNotification('Meeting requests refreshed!', 'info');
}

function exportMeetingRequests() {
    const adminData = JSON.parse(localStorage.getItem('payonline_admin_data') || '{}');
    const requests = adminData.meeting_requests || [];
    
    if (requests.length === 0) {
        showNotification('No meeting requests to export!', 'warning');
        return;
    }
    
    // Create CSV content
    const headers = ['Company', 'Contact Person', 'Email', 'Phone', 'Role', 'Client Code', 'Date', 'Status', 'Message'];
    const csvContent = [
        headers.join(','),
        ...requests.map(r => [
            `"${r.company_name}"`,
            `"${r.full_name}"`,
            `"${r.email}"`,
            `"${r.phone}"`,
            `"${r.role || ''}"`,
            `"${r.client_code || ''}"`,
            `"${formatDate(r.created_at)}"`,
            `"${r.status || 'pending'}"`,
            `"${(r.message || '').replace(/"/g, '""')}"`
        ].join(','))
    ].join('\n');
    
    // Download CSV file
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `meeting_requests_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
    
    showNotification('Meeting requests exported successfully!', 'success');
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}

// Update the loadDashboardData function to include meeting requests
function loadDashboardData() {
    loadQuotesData();
    loadMeetingRequests();
    updateDashboardStats();
}

// Initialize everything when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeTooltips();
    initializeModals();
    setupAutoSave();
});

// Handle page visibility changes
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('Page is hidden - pause auto-refresh');
        // Pause any auto-refresh or real-time updates
    } else {
        console.log('Page is visible - resume auto-refresh');
        // Resume any auto-refresh or real-time updates
        loadDashboardData();
    }
});

// Error handling
window.addEventListener('error', function(e) {
    console.error('JavaScript error:', e.error);
    showNotification('An error occurred. Please try again.', 'danger');
});

// Performance monitoring
function logPerformance() {
    if (window.performance && window.performance.timing) {
        const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart;
        console.log(`Page load time: ${loadTime}ms`);
    }
}

window.addEventListener('load', logPerformance);
