/* jshint esversion: 6 */
/* globals ajaxurl, flowdino_ajax, flowdino_data */

// Fonctions globales pour les notifications
function showFlowDinoNotification(message, type, duration) {
    if (typeof type === 'undefined') { type = 'info'; }
    if (typeof duration === 'undefined') { duration = 5000; }

    var existingNotifs = document.querySelectorAll('.flowdino-notification');
    existingNotifs.forEach(function(notif) { notif.remove(); });

    var notification = document.createElement('div');
    notification.className = 'flowdino-notification flowdino-notification-' + type;
    notification.innerHTML =
        '<div class="flowdino-notification-content">' +
        '<span class="flowdino-notification-icon">' + getNotificationIcon(type) + '</span>' +
        '<span class="flowdino-notification-message">' + message + '</span>' +
        '<button class="flowdino-notification-close" onclick="this.parentElement.parentElement.remove()">&times;</button>' +
        '</div>';

    notification.style.cssText =
        'position:fixed;top:20px;right:20px;z-index:100001;min-width:300px;max-width:500px;' +
        'border-radius:8px;box-shadow:0 4px 20px rgba(0,0,0,0.15);animation:flowdinoSlideIn 0.3s ease-out;' +
        'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';

    var colors = {
        'info':    { bg: '#e3f2fd', border: '#2196f3', text: '#0d47a1' },
        'success': { bg: '#e8f5e8', border: '#4caf50', text: '#1b5e20' },
        'warning': { bg: '#fff3e0', border: '#ff9800', text: '#e65100' },
        'error':   { bg: '#ffebee', border: '#f44336', text: '#c62828' }
    };

    var color = colors[type] || colors['info'];
    notification.style.backgroundColor = color.bg;
    notification.style.border = '2px solid ' + color.border;
    notification.style.color = color.text;

    var content = notification.querySelector('.flowdino-notification-content');
    content.style.cssText = 'display:flex;align-items:center;padding:12px 16px;gap:10px;';

    var icon = notification.querySelector('.flowdino-notification-icon');
    icon.style.cssText = 'font-size:18px;flex-shrink:0;';

    var messageEl = notification.querySelector('.flowdino-notification-message');
    messageEl.style.cssText = 'flex:1;font-size:14px;line-height:1.4;';

    var closeBtn = notification.querySelector('.flowdino-notification-close');
    closeBtn.style.cssText = 'background:none;border:none;font-size:18px;cursor:pointer;padding:0;margin:0;color:' + color.text + ';opacity:0.7;flex-shrink:0;';
    closeBtn.onmouseover = function() { closeBtn.style.opacity = '1'; };
    closeBtn.onmouseout  = function() { closeBtn.style.opacity = '0.7'; };

    document.body.appendChild(notification);

    if (duration > 0) {
        setTimeout(function() {
            if (notification.parentElement) {
                notification.style.animation = 'flowdinoSlideOut 0.3s ease-in';
                setTimeout(function() { notification.remove(); }, 300);
            }
        }, duration);
    }

    return notification;
}

function getNotificationIcon(type) {
    var icons = { 'info': 'ℹ️', 'success': '✅', 'warning': '⚠️', 'error': '❌' };
    return icons[type] || icons['info'];
}

function showFlowDinoConfirm(message, onConfirm, onCancel) {
    var existingConfirms = document.querySelectorAll('.flowdino-confirm-dialog');
    existingConfirms.forEach(function(c) { c.remove(); });

    var overlay = document.createElement('div');
    overlay.className = 'flowdino-confirm-overlay';
    overlay.style.cssText =
        'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);' +
        'z-index:100000;display:flex;align-items:center;justify-content:center;';

    var dialog = document.createElement('div');
    dialog.className = 'flowdino-confirm-dialog';
    dialog.style.cssText =
        'background:white;border-radius:8px;padding:24px;box-shadow:0 8px 40px rgba(0,0,0,0.3);' +
        'max-width:400px;min-width:300px;animation:flowdinoFadeIn 0.3s ease-out;' +
        'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';

    dialog.innerHTML =
        '<div class="flowdino-confirm-content">' +
        '<div class="flowdino-confirm-icon" style="text-align:center;margin-bottom:16px;font-size:24px;">❓</div>' +
        '<div class="flowdino-confirm-message" style="text-align:center;margin-bottom:24px;font-size:16px;line-height:1.4;color:#333;">' + message + '</div>' +
        '<div class="flowdino-confirm-buttons" style="display:flex;gap:12px;justify-content:center;">' +
        '<button class="flowdino-confirm-cancel" style="padding:10px 20px;border:2px solid #ddd;background:white;color:#666;border-radius:6px;cursor:pointer;font-size:14px;font-weight:500;">' +
        flowdino_data.i18n.cancel + '</button>' +
        '<button class="flowdino-confirm-ok" style="padding:10px 20px;border:2px solid #2563eb;background:#2563eb;color:white;border-radius:6px;cursor:pointer;font-size:14px;font-weight:500;">' +
        flowdino_data.i18n.confirm + '</button>' +
        '</div></div>';

    var cancelBtn = dialog.querySelector('.flowdino-confirm-cancel');
    var okBtn     = dialog.querySelector('.flowdino-confirm-ok');

    cancelBtn.onmouseover = function() { cancelBtn.style.background = '#f5f5f5'; };
    cancelBtn.onmouseout  = function() { cancelBtn.style.background = 'white'; };
    okBtn.onmouseover = function() { okBtn.style.background = '#1d4ed8'; };
    okBtn.onmouseout  = function() { okBtn.style.background = '#2563eb'; };

    var closeDialog = function() {
        overlay.style.animation = 'flowdinoFadeOut 0.3s ease-in';
        setTimeout(function() { overlay.remove(); }, 300);
    };

    cancelBtn.onclick = function() { closeDialog(); if (onCancel) { onCancel(); } };
    okBtn.onclick     = function() { closeDialog(); if (onConfirm) { onConfirm(); } };

    overlay.onclick = function(e) {
        if (e.target === overlay) { closeDialog(); if (onCancel) { onCancel(); } }
    };

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);
    setTimeout(function() { okBtn.focus(); }, 100);
    return overlay;
}

// Fonction de synchronisation
function submitSelectedProducts() {
    var checkedBoxes = document.querySelectorAll('input[name="selected_products[]"]:checked');

    if (checkedBoxes.length === 0) {
        showFlowDinoNotification(flowdino_data.i18n.select_one_product, 'warning', 5000);
        return;
    }

    var selectedProducts = [];
    checkedBoxes.forEach(function(checkbox) { selectedProducts.push(checkbox.value); });

    showSyncBanner(selectedProducts);
    proceedWithSync(selectedProducts);
}

function showSyncBanner(selectedProducts) {
    var banner = document.getElementById('flowdino-sync-banner');

    var bannerHtml = '<div style="background:#2563eb;color:white;padding:20px;border-radius:8px;box-shadow:0 4px 15px rgba(102,126,234,0.3);">';

    bannerHtml += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">';
    bannerHtml += '<h3 style="margin:0;color:white;"><span class="dashicons dashicons-update" style="vertical-align:middle;margin-right:10px;"></span>';
    bannerHtml += flowdino_data.i18n.sync_in_progress + '</h3>';
    bannerHtml += '<div id="sync-selected-count" style="background:rgba(255,255,255,0.2);padding:8px 15px;border-radius:20px;font-weight:bold;">';
    bannerHtml += selectedProducts.length + ' ' + flowdino_data.i18n.products_selected + '</div>';
    bannerHtml += '</div>';

    bannerHtml += '<div id="sync-status" style="margin-bottom:15px;font-size:16px;">';
    bannerHtml += flowdino_data.i18n.checking_compliance + '</div>';

    bannerHtml += '<div style="margin-bottom:15px;">';
    bannerHtml += '<div style="display:flex;justify-content:space-between;margin-bottom:5px;">';
    bannerHtml += '<span>' + flowdino_data.i18n.progression + '</span>';
    bannerHtml += '<span id="sync-progress-text">0%</span></div>';
    bannerHtml += '<div style="background:rgba(255,255,255,0.2);border-radius:10px;height:8px;overflow:hidden;">';
    bannerHtml += '<div id="sync-progress-bar" style="background:#4ade80;height:100%;width:0%;border-radius:10px;transition:width 0.3s ease;"></div>';
    bannerHtml += '</div></div>';

    bannerHtml += '<div id="sync-errors" style="display:none;background:rgba(220,53,69,0.9);padding:15px;border-radius:5px;margin-top:15px;">';
    bannerHtml += '<h4 style="margin:0 0 10px 0;color:white;"><span class="dashicons dashicons-warning" style="vertical-align:middle;margin-right:5px;"></span>';
    bannerHtml += flowdino_data.i18n.products_in_error + '</h4>';
    bannerHtml += '<div id="sync-errors-content"></div></div>';

    bannerHtml += '<div id="sync-results" style="display:none;margin-top:15px;"></div>';
    bannerHtml += '</div>';

    banner.innerHTML = bannerHtml;
    banner.style.display = 'block';
    banner.scrollIntoView({ behavior: 'smooth' });
}

function updateSyncProgress(current, total, message) {
    var progressBar  = document.getElementById('sync-progress-bar');
    var progressText = document.getElementById('sync-progress-text');
    var statusDiv    = document.getElementById('sync-status');
    var percentage   = Math.round((current / total) * 100);

    if (progressBar)  { progressBar.style.width = percentage + '%'; }
    if (progressText) { progressText.textContent = percentage + '%'; }
    if (statusDiv)    { statusDiv.textContent = message; }
}

function showSyncErrors(errors) {
    var errorsDiv     = document.getElementById('sync-errors');
    var errorsContent = document.getElementById('sync-errors-content');

    if (errors.length === 0) { errorsDiv.style.display = 'none'; return; }

    var errorHtml = '';
    errors.forEach(function(error) {
        errorHtml += '<div style="background:rgba(255,255,255,0.1);padding:10px;margin:5px 0;border-radius:3px;">';
        errorHtml += '<strong>' + error.name + '</strong>';
        if (error.sku) { errorHtml += ' (' + error.sku + ')'; }
        errorHtml += '<br><small>' + error.errors.join(', ') + '</small></div>';
    });

    errorsContent.innerHTML = errorHtml;
    errorsDiv.style.display = 'block';
}

function showSyncResults(results) {
    var resultsDiv = document.getElementById('sync-results');

    var resultHtml = '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:15px;text-align:center;">';

    resultHtml += '<div style="background:rgba(72,187,120,0.9);padding:15px;border-radius:5px;">';
    resultHtml += '<div style="font-size:24px;font-weight:bold;">' + results.success + '</div>';
    resultHtml += '<div style="font-size:14px;">' + flowdino_data.i18n.synced + '</div></div>';

    if (results.created > 0) {
        resultHtml += '<div style="background:rgba(34,197,94,0.9);padding:15px;border-radius:5px;">';
        resultHtml += '<div style="font-size:24px;font-weight:bold;">' + results.created + '</div>';
        resultHtml += '<div style="font-size:14px;">' + flowdino_data.i18n.created + '</div></div>';
    }

    if (results.updated > 0) {
        resultHtml += '<div style="background:rgba(59,130,246,0.9);padding:15px;border-radius:5px;">';
        resultHtml += '<div style="font-size:24px;font-weight:bold;">' + results.updated + '</div>';
        resultHtml += '<div style="font-size:14px;">' + flowdino_data.i18n.updated + '</div></div>';
    }

    if (results.errors > 0) {
        resultHtml += '<div style="background:rgba(220,53,69,0.9);padding:15px;border-radius:5px;">';
        resultHtml += '<div style="font-size:24px;font-weight:bold;">' + results.errors + '</div>';
        resultHtml += '<div style="font-size:14px;">' + flowdino_data.i18n.in_error + '</div></div>';
    }

    if (results.skipped > 0) {
        resultHtml += '<div style="background:rgba(255,193,7,0.9);padding:15px;border-radius:5px;color:#856404;">';
        resultHtml += '<div style="font-size:24px;font-weight:bold;">' + results.skipped + '</div>';
        resultHtml += '<div style="font-size:14px;">' + flowdino_data.i18n.non_compliant + '</div></div>';
    }

    resultHtml += '</div>';

    if (results.errorDetails && results.errorDetails.length > 0) {
        resultHtml += '<div style="margin-top:20px;background:rgba(220,53,69,0.1);padding:15px;border-radius:5px;">';
        resultHtml += '<h4 style="margin:0 0 10px 0;color:#dc3545;"><span class="dashicons dashicons-warning" style="vertical-align:middle;margin-right:5px;"></span>';
        resultHtml += flowdino_data.i18n.error_details + '</h4>';
        results.errorDetails.forEach(function(errorDetail) {
            resultHtml += '<div style="background:rgba(255,255,255,0.8);padding:10px;margin:5px 0;border-radius:3px;color:#333;">';
            resultHtml += '<strong>' + errorDetail.product + '</strong><br>';
            resultHtml += '<small style="color:#dc3545;">' + errorDetail.error + '</small></div>';
        });
        resultHtml += '</div>';
    }

    resultHtml += '<div style="text-align:center;margin-top:20px;">';
    resultHtml += '<button onclick="hideSyncBanner()" class="button" style="background:rgba(255,255,255,0.2);color:white;border:1px solid rgba(255,255,255,0.3);padding:10px 20px;">';
    resultHtml += flowdino_data.i18n.close + '</button></div>';

    resultsDiv.innerHTML = resultHtml;
    resultsDiv.style.display = 'block';
}

function hideSyncBanner() {
    var banner = document.getElementById('flowdino-sync-banner');
    banner.style.display = 'none';
    location.reload();
}

// ---------------------------------------------------------------
// Pull updates from FlowDino
// ---------------------------------------------------------------
(function() {
    var btn = document.getElementById('flowdino-pull-updates-btn');
    if (!btn) { return; }

    btn.addEventListener('click', function() {
        var dateInput  = document.getElementById('flowdino-pull-date');
        if (!dateInput || !dateInput.value) {
            alert(flowdino_data.i18n.select_date);
            return;
        }

        var rawVal  = dateInput.value.replace('T', ' ');
        // datetime-local gives "YYYY-MM-DD HH:MM" or "YYYY-MM-DD HH:MM:SS" — ensure seconds
        var rawDate = (rawVal.split(':').length === 2) ? rawVal + ':00' : rawVal;
        var resultsDiv = document.getElementById('flowdino-pull-results');
        resultsDiv.style.display = 'block';
        resultsDiv.innerHTML = '<p style="color:#0073aa;"><span class="dashicons dashicons-update spinning" style="animation:spin 1s linear infinite;"></span> ' + flowdino_data.i18n.fetching_updates + '</p>';
        btn.disabled = true;

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'flowdino_fetch_product_updates',
                nonce: flowdino_ajax.fetch_updates_nonce,
                since_date: rawDate
            },
            success: function(response) {
                btn.disabled = false;
                if (response.success) {
                    var d = response.data;
                    var html = '<div style="background:#edfbf0;border:1px solid #5cb85c;border-radius:4px;padding:14px;">';
                    html += '<strong style="color:#3a7d44;">' + flowdino_data.i18n.updates_applied + '</strong><br>';
                    html += '<span style="font-size:13px;">';
                    html += flowdino_data.i18n.products_received + ' <strong>' + d.total_received + '</strong> &nbsp;|&nbsp; ';
                    html += flowdino_data.i18n.wc_updated + ' <strong>' + d.updated + '</strong> &nbsp;|&nbsp; ';
                    html += flowdino_data.i18n.not_found + ' <strong>' + d.skipped + '</strong>';
                    html += '</span>';

                    if (d.details && d.details.length > 0) {
                        html += '<details style="margin-top:10px;font-size:12px;"><summary style="cursor:pointer;">' + flowdino_data.i18n.view_detail + '</summary><ul style="margin:6px 0 0 16px;">';
                        d.details.forEach(function(item) {
                            var icon = item.status === 'updated' ? '✅' : (item.status === 'skipped' ? '⚠️' : '❌');
                            html += '<li>' + icon + ' <strong>' + item.title + '</strong> (' + item.external_key + ') — ' + item.message + '</li>';
                        });
                        html += '</ul></details>';
                    }
                    html += '</div>';
                    resultsDiv.innerHTML = html;
                } else {
                    var msg = (response.data && response.data.message) ? response.data.message : flowdino_data.i18n.unknown_error;
                    resultsDiv.innerHTML = '<div style="background:#fff0f0;border:1px solid #dc3232;border-radius:4px;padding:14px;color:#c00;"><strong>' + flowdino_data.i18n.error_colon + '</strong> ' + msg + '</div>';
                }
            },
            error: function() {
                btn.disabled = false;
                resultsDiv.innerHTML = '<div style="background:#fff0f0;border:1px solid #dc3232;border-radius:4px;padding:14px;color:#c00;">' + flowdino_data.i18n.network_error_fetch + '</div>';
            }
        });
    });
})();

function proceedWithSync(selectedProducts) {
    updateSyncProgress(5, 100, flowdino_data.i18n.verifying_compliance);

    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'flowdino_check_selected_products_compliance',
            nonce: flowdino_ajax.compliance_nonce,
            product_ids: selectedProducts
        },
        success: function(response) {
            if (response.success) {
                var nonCompliant = response.data.non_compliant;
                var compliant    = response.data.compliant;

                updateSyncProgress(20, 100, flowdino_data.i18n.compliance_verified);

                if (nonCompliant.length > 0) {
                    showSyncErrors(nonCompliant);
                    if (compliant.length > 0) {
                        setTimeout(function() {
                            if (confirm(flowdino_data.i18n.partial_sync_confirm)) {
                                startProductSync(compliant, nonCompliant.length);
                            } else {
                                updateSyncProgress(0, 100, flowdino_data.i18n.sync_cancelled);
                                setTimeout(function() { hideSyncBanner(); }, 2000);
                            }
                        }, 1000);
                    } else {
                        updateSyncProgress(100, 100, flowdino_data.i18n.no_compliant);
                        showSyncResults({ success: 0, errors: 0, skipped: nonCompliant.length, total: selectedProducts.length });
                    }
                } else {
                    startProductSync(selectedProducts, 0);
                }
            } else {
                updateSyncProgress(0, 100, flowdino_data.i18n.error_checking);
                setTimeout(function() { hideSyncBanner(); }, 3000);
            }
        },
        error: function() {
            updateSyncProgress(0, 100, flowdino_data.i18n.network_error_check);
            setTimeout(function() { hideSyncBanner(); }, 3000);
        }
    });
}

function startProductSync(selectedProducts, skippedCount) {
    if (typeof skippedCount === 'undefined') { skippedCount = 0; }

    updateSyncProgress(30, 100, flowdino_data.i18n.starting_sync);

    var syncResults = {
        success: 0,
        errors: 0,
        skipped: skippedCount,
        total: selectedProducts.length,
        created: 0,
        updated: 0,
        errorDetails: []
    };

    var currentIndex = 0;

    function syncNextProduct() {
        if (currentIndex >= selectedProducts.length) {
            updateSyncProgress(100, 100, flowdino_data.i18n.sync_complete);
            setTimeout(function() { showSyncResults(syncResults); }, 1000);
            return;
        }

        var productId = selectedProducts[currentIndex];
        var progress  = 30 + Math.round(((currentIndex + 1) / selectedProducts.length) * 70);

        updateSyncProgress(progress, 100, flowdino_data.i18n.syncing_product + ' ' + (currentIndex + 1) + '/' + selectedProducts.length);

        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'flowdino_sync_single_product',
                nonce: flowdino_ajax.sync_single_nonce,
                product_id: productId
            },
            success: function(response) {
                if (response.success) {
                    syncResults.success++;
                    if (response.data) {
                        if (typeof response.data.updated === 'boolean') {
                            if (response.data.updated === true) { syncResults.updated++; } else { syncResults.created++; }
                        } else if (response.data.action) {
                            if (response.data.action === 'updated') { syncResults.updated++; }
                            else if (response.data.action === 'created') { syncResults.created++; }
                        } else if (typeof response.data.created === 'boolean' || typeof response.data.updated === 'boolean') {
                            if (response.data.created === true) { syncResults.created++; }
                            else if (response.data.updated === true) { syncResults.updated++; }
                            else { syncResults.created++; }
                        } else {
                            syncResults.created++;
                        }
                    } else {
                        syncResults.created++;
                    }
                } else {
                    syncResults.errors++;
                    var errorMessage = flowdino_data.i18n.unknown_error_en;
                    var productName  = 'Product ' + productId;
                    var debugInfo    = '';
                    if (response.data) {
                        if (response.data.product_name) { productName = response.data.product_name; }
                        if (response.data.message)      { errorMessage = response.data.message; }
                        if (response.data.error_details){ debugInfo = ' (' + response.data.error_details + ')'; }
                    }
                    syncResults.errorDetails.push({ product: productName, error: errorMessage + debugInfo, details: response.data || {} });
                }
                currentIndex++;
                setTimeout(syncNextProduct, 500);
            },
            error: function(xhr, status, error) {
                syncResults.errors++;
                var errorMessage = flowdino_data.i18n.network_error_sync;
                if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                    errorMessage = xhr.responseJSON.data.message;
                }
                syncResults.errorDetails.push({ product: 'Product ' + productId, error: errorMessage + ' (' + status + ': ' + error + ')', details: { xhr_status: status, xhr_error: error, response: xhr.responseJSON } });
                currentIndex++;
                setTimeout(syncNextProduct, 500);
            }
        });
    }

    syncNextProduct();
}

// Initialisation jQuery
jQuery(document).ready(function($) {
    var checkboxes        = document.querySelectorAll('input[name="selected_products[]"]');
    var selectAllCheckbox = document.getElementById('cb-select-all-1');
    var floatingBtn       = document.getElementById('flowdino-floating-sync-btn');
    var selectedCountSpan = document.getElementById('selected-count');

    function updateFloatingButton() {
        var checkedBoxes = document.querySelectorAll('input[name="selected_products[]"]:checked');
        var count = checkedBoxes.length;
        if (floatingBtn && selectedCountSpan) { selectedCountSpan.textContent = count; }
    }

    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            checkboxes.forEach(function(checkbox) { checkbox.checked = selectAllCheckbox.checked; });
            updateFloatingButton();
        });
    }

    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            updateFloatingButton();
            var total   = checkboxes.length;
            var checked = document.querySelectorAll('input[name="selected_products[]"]:checked').length;
            if (selectAllCheckbox) { selectAllCheckbox.checked = total === checked; }
        });
    });

    updateFloatingButton();

    var productRows = document.querySelectorAll('.wp-list-table tbody tr');
    productRows.forEach(function(row) {
        row.style.cursor = 'pointer';
        row.addEventListener('click', function(e) {
            if (e.target.type === 'checkbox' ||
                e.target.closest('.flowdino-edit-product-btn') ||
                e.target.tagName === 'A' ||
                e.target.closest('a')) { return; }
            var checkbox = row.querySelector('input[name="selected_products[]"]');
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                checkbox.dispatchEvent(new Event('change'));
            }
        });
        row.addEventListener('mouseenter', function() {
            if (!this.querySelector('input[name="selected_products[]"]').checked) { this.style.backgroundColor = '#f8f9fa'; }
        });
        row.addEventListener('mouseleave', function() {
            if (!this.querySelector('input[name="selected_products[]"]').checked) { this.style.backgroundColor = ''; }
        });
    });

    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            var row = this.closest('tr');
            var isVariation = row && row.dataset && row.dataset.variation === 'true';
            if (this.checked) {
                row.style.backgroundColor = '#e3f2fd';
                row.style.borderLeft = '3px solid #2563eb';
            } else {
                row.style.backgroundColor = '';
                row.style.borderLeft = isVariation ? '3px solid #0073aa' : '';
            }
        });
    });

    if (floatingBtn) {
        floatingBtn.addEventListener('mouseenter', function() { this.style.transform = 'scale(1.05)'; this.style.background = '#1d4ed8'; });
        floatingBtn.addEventListener('mouseleave', function() { this.style.transform = 'scale(1)';    this.style.background = '#2563eb'; });
    }
});
