class RiderManager {
    constructor(app) {
        this.app = app;
        this.statsPoller = null;
        this.pollingInterval = 30000; // 30 seconds
        this.knownDeliveryIds = new Set();
        this.recentDeliveryIds = new Set(); // For the "New" badge
        this.notificationSound = new Audio('assets/sounds/new-order.wav'); // Ensure this file exists in your assets folder
        this.activeNotificationModal = null;
    }

    init() {
        // Request notification permission for system-level alerts
        if ("Notification" in window) {
            Notification.requestPermission().then(permission => {
                if (permission === "granted" && 'serviceWorker' in navigator) {
                    this.subscribeToPush();
                }
            });
        }
    }

    async subscribeToPush() {
        try {
            const registration = await navigator.serviceWorker.ready;
            const subscription = await registration.pushManager.subscribe({
                userVisibleOnly: true,
                // You will need a public VAPID key from your server
                applicationServerKey: 'YOUR_PUBLIC_VAPID_KEY_HERE'
            });

            // Send subscription to server
            await fetch('api/notifications/subscribe.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(subscription)
            });

            console.log('User is subscribed to Push Notifications');
        } catch (err) {
            console.error('Failed to subscribe to push:', err);
        }
    }

    async loadDashboardData() {
        try {
            const response = await fetch('api/riders/deliveries.php');
            const data = await response.json();

            if (data.success) {
                const available = data.available_deliveries || [];
                this._checkForNewDeliveries(available);

                this._renderAvailableDeliveries(available);
                this._renderMyDeliveries(data.my_deliveries || []);
            } else {
                this._showErrorInContainer('available-deliveries', data.message);
                this._showErrorInContainer('my-deliveries', data.message);
            }
        } catch (error) {
            console.error('Error loading rider deliveries:', error);
            this._showErrorInContainer('available-deliveries', 'Error loading deliveries');
            this._showErrorInContainer('my-deliveries', 'Error loading deliveries');
        }
    }

    _renderAvailableDeliveries(deliveries) {
        const container = document.getElementById('available-deliveries');
        if (!container) return;

        if (deliveries.length > 0) {
            container.innerHTML = deliveries.map(delivery => {
                const isNew = this.recentDeliveryIds.has(delivery.id);
                return `
                <div class="delivery-card">
                    <div class="delivery-info">
                        <h4>${isNew ? '<span class="new-badge">NEW</span> ' : ''}${delivery.package_description}</h4>
                        <p><strong>From:</strong> ${delivery.pickup_location}</p>
                        <p><strong>To:</strong> ${delivery.delivery_location}</p>
                        <p><strong>Customer:</strong> ${delivery.customer_name} (${delivery.customer_phone})</p>
                        <p><strong>Distance:</strong> ${delivery.distance || 'N/A'} km</p>
                        <p><strong>Price:</strong> $${delivery.price || '0.00'}</p>
                    </div>
                    <div class="slider-wrapper">
                        ${this._createSliderHTML('Slide to Accept', 'accept', delivery.id)}
                    </div>
                </div>
            `;
            }).join('');

            this._attachSliderListeners(container);
        } else {
            container.innerHTML = '<p>No available deliveries at the moment.</p>';
        }
    }

    _renderMyDeliveries(deliveries) {
        const container = document.getElementById('my-deliveries');
        if (!container) return;

        if (deliveries.length > 0) {
            container.innerHTML = deliveries.map(delivery => `
                <div class="delivery-card">
                    <div class="delivery-info">
                        <h4>${delivery.package_description}</h4>
                        <p><strong>From:</strong> ${delivery.pickup_location}</p>
                        <p><strong>To:</strong> ${delivery.delivery_location}</p>
                        <p><strong>Customer:</strong> ${delivery.customer_name}</p>
                        <p><strong>Status:</strong> ${delivery.status}</p>
                        <p><strong>Price:</strong> $${delivery.price || '0.00'}</p>
                    </div>
                    <div class="delivery-actions" style="width: 100%;">
                        ${this._getNextActionSlider(delivery)}
                    </div>
                </div>
            `).join('');

            this._attachSliderListeners(container);
        } else {
            container.innerHTML = '<p>You have no active deliveries.</p>';
        }
    }

    _createSliderHTML(text, action, id, status = '') {
        return `
            <div class="slide-button-container">
                <input type="range" min="0" max="100" value="0" class="slide-button-input" 
                       data-action="${action}" data-id="${id}" data-status="${status}">
                <div class="slide-button-text">${text} <i class="fas fa-chevron-right"></i></div>
                <div class="slide-button-track"></div>
            </div>
        `;
    }

    _getNextActionSlider(delivery) {
        switch (delivery.status) {
            case 'accepted':
                return this._createSliderHTML('Slide to Pick Up', 'update', delivery.id, 'picked_up');
            case 'picked_up':
                return this._createSliderHTML('Slide to Start Transit', 'update', delivery.id, 'in_transit');
            case 'in_transit':
                return this._createSliderHTML('Slide to Delivered', 'update', delivery.id, 'delivered');
            case 'delivered':
                return '<div class="status-badge status-delivered"><i class="fas fa-check"></i> Completed</div>';
            default:
                return '';
        }
    }

    _attachSliderListeners(container) {
        container.querySelectorAll('.slide-button-input').forEach(slider => {
            slider.addEventListener('input', (e) => {
                const val = parseInt(e.target.value);
                // Visual feedback could go here (opacity of text etc)
                e.target.parentElement.querySelector('.slide-button-track').style.width = val + '%';

                if (val >= 100) {
                    e.target.disabled = true;
                    const action = e.target.dataset.action;
                    const id = e.target.dataset.id;

                    if (action === 'accept' || action === 'accept-modal') {
                        this.acceptDelivery(id, action === 'accept-modal');
                    } else if (action === 'update') {
                        const status = e.target.dataset.status;
                        this.updateDeliveryStatus(id, status);
                    }
                }
            });

            // Reset if released before 100
            slider.addEventListener('change', (e) => {
                if (parseInt(e.target.value) < 100) {
                    e.target.value = 0;
                    e.target.parentElement.querySelector('.slide-button-track').style.width = '0%';
                }
            });
        });
    }

    _showErrorInContainer(containerId, message) {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `<p>${message || 'Error loading deliveries'}</p>`;
        }
    }

    _checkForNewDeliveries(deliveries) {
        // If set is empty, it's the first load, so don't notify
        const isFirstLoad = this.knownDeliveryIds.size === 0;
        let newDeliveries = [];

        deliveries.forEach(d => {
            if (!this.knownDeliveryIds.has(d.id)) {
                this.knownDeliveryIds.add(d.id);
                if (!isFirstLoad) {
                    newDeliveries.push(d);
                    this.recentDeliveryIds.add(d.id);
                }
            }
        });

        if (newDeliveries.length > 0) {
            this._playNotificationSound();
            // Show popup modal for the latest delivery found
            const latest = newDeliveries[newDeliveries.length - 1];
            this._showNewDeliveryModal(latest);

            // Trigger Browser System Notification
            this._showSystemNotification(latest);
        }
    }

    _showNewDeliveryModal(delivery) {
        // Prevent multiple modals if another is already open
        if (this.activeNotificationModal) return;

        const descSnippet = delivery.package_description.length > 80
            ? delivery.package_description.substring(0, 80) + '...'
            : delivery.package_description;

        const content = `
            <div class="new-delivery-alert">
                <div class="delivery-details-brief">
                    <p><i class="fas fa-map-marker-alt" style="color: var(--primary-red)"></i> <strong>From:</strong> ${delivery.pickup_location}</p>
                    <p><i class="fas fa-flag-checkered" style="color: var(--primary-blue)"></i> <strong>To:</strong> ${delivery.delivery_location}</p>
                    <p><i class="fas fa-box"></i> <strong>Items:</strong> ${descSnippet}</p>
                    <p><i class="fas fa-tag"></i> <strong>Price:</strong> $${delivery.price || '0.00'}</p>
                </div>
                <div class="slider-wrapper mt-3">
                    ${this._createSliderHTML('Slide to Accept', 'accept-modal', delivery.id)}
                </div>
            </div>
        `;

        this.activeNotificationModal = new Modal({
            title: '<i class="fas fa-bell"></i> New Delivery!',
            content: content,
            size: 'small-modal'
        });

        const modalElement = this.activeNotificationModal.show();
        this._attachSliderListeners(modalElement);
    }

    _showSystemNotification(delivery) {
        if ("Notification" in window && Notification.permission === "granted") {
            new Notification("New Delivery Available!", {
                body: `From: ${delivery.pickup_location}\nTo: ${delivery.delivery_location}`,
                icon: 'assets/images/logo-icon.png' // Use your app icon
            });
        }
    }

    _playNotificationSound() {
        this.notificationSound.play().catch(e => console.log('Audio play failed (user interaction needed first):', e));
    }

    startPolling() {
        this.stopPolling(); // Ensure no multiple pollers are running

        // Load immediately on start
        this.loadRiderStats(); // Load immediately
        this.loadDashboardData();

        this.statsPoller = setInterval(() => {
            this.loadRiderStats();
            this.loadDashboardData(); // Also refresh the delivery lists
        }, this.pollingInterval);
        console.log('Rider dashboard polling started.');
    }

    stopPolling() {
        clearInterval(this.statsPoller);
        this.statsPoller = null;
        console.log('Rider dashboard polling stopped.');
    }

    async loadRiderStats() {
        try {
            const response = await fetch('api/riders/stats.php');
            const data = await response.json();

            if (data.success && data.stats) {
                const pendingEl = document.getElementById('pending-deliveries');
                const activeEl = document.getElementById('active-deliveries');
                const completedEl = document.getElementById('completed-deliveries');

                if (pendingEl) pendingEl.textContent = data.stats.pending || 0;
                if (activeEl) activeEl.textContent = data.stats.active || 0;
                if (completedEl) completedEl.textContent = data.stats.completed || 0;
            }
        } catch (error) {
            console.error('Error loading rider stats:', error);
        }
    }

    async acceptDelivery(deliveryId, fromModal = false) {
        try {
            const response = await fetch('api/riders/accept.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ delivery_id: deliveryId })
            });

            const data = await response.json();

            if (data.success) {
                this.app.notifier.show('Delivery accepted successfully!', 'success');

                if (fromModal && this.activeNotificationModal) {
                    this.activeNotificationModal.close();
                    this.activeNotificationModal = null;
                    // Redirect to Rider Dashboard so they can see their new task
                    this.app.loadRiderDashboard();
                } else {
                    this.loadDashboardData();
                    this.loadRiderStats();
                }
            } else {
                // This handles the concurrency issue (e.g. "Delivery already accepted by another rider")
                this.app.notifier.show(data.message, 'error');

                if (fromModal && this.activeNotificationModal) {
                    this.activeNotificationModal.close();
                    this.activeNotificationModal = null;
                }
                this.loadDashboardData(); // Reset UI on error
            }
        } catch (error) {
            console.error('Error accepting delivery:', error);
            this.app.notifier.show('Failed to accept delivery. Please try again.', 'error');
            this.loadDashboardData(); // Reset UI on error
        }
    }

    async updateDeliveryStatus(deliveryId, status) {
        try {
            const response = await fetch('api/riders/update_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    delivery_id: deliveryId,
                    status: status
                })
            });

            const data = await response.json();

            if (data.success) {
                this._renderMyDeliveries(data.deliveries); // API could return the updated list
                this.loadRiderStats();
            } else {
                this.app.notifier.show('Error: ' + data.message, 'error');
                this.loadDashboardData(); // Reset UI on error
            }
        } catch (error) {
            console.error('Error updating delivery status:', error);
            this.app.notifier.show('Failed to update delivery status. Please try again.', 'error');
            this.loadDashboardData(); // Reset UI on error
        }
    }
}