// Global dropdown toggle function for product list
window.toggleDropdown = function(id) {
    const dropdownContent = document.getElementById(id);
    if (!dropdownContent) return;

    const dropdownBtn = dropdownContent.previousElementSibling;
    const isExpanded = dropdownContent.classList.contains('show');

    // Close all other open dropdowns
    document.querySelectorAll('.dropdown-content.show').forEach(openDropdown => {
        if (openDropdown.id !== id) {
            openDropdown.classList.remove('show');
            const otherBtn = openDropdown.previousElementSibling;
            if (otherBtn) otherBtn.setAttribute('aria-expanded', 'false');
        }
    });

    // Toggle current dropdown
    dropdownContent.classList.toggle('show');
    if (dropdownBtn) dropdownBtn.setAttribute('aria-expanded', !isExpanded);

    // Close dropdown if clicked outside
    if (!isExpanded) {
        document.addEventListener('click', function closeDropdown(event) {
            if (!dropdownContent.contains(event.target) && !dropdownBtn.contains(event.target)) {
                dropdownContent.classList.remove('show');
                if (dropdownBtn) dropdownBtn.setAttribute('aria-expanded', 'false');
                document.removeEventListener('click', closeDropdown);
            }
        }, { once: true });
    }
};

// Global function to update product fields via AJAX
window.updateProductField = function(productId, field, value, iteration) {
    const dropdownBtn = document.getElementById(`${field}-btn-${iteration}`)
                        || (field === 'status' ? document.getElementById(`status-badge-${iteration}`).closest('.dropdown-btn') : null);

    if (!dropdownBtn) return;

    const originalContent = dropdownBtn.innerHTML;

    // Show loading indicator
    if (field !== 'status') {
        dropdownBtn.innerHTML = '<span><i class="fas fa-spinner fa-spin"></i> Updating...</span>';
    } else {
        const badge = document.getElementById(`status-badge-${iteration}`);
        if (badge) badge.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    }

    const formData = new FormData();
    formData.append(field, value);
    formData.append('_method', 'PUT');

    // Use the URL template defined in the Blade file for a more robust link
    const url = window.productUpdateUrl.replace('PRODUCT_ID_PLACEHOLDER', productId);

    fetch(url, {
        method: 'POST', // Use POST for FormData with method spoofing
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(response => {
        // Check if the response is successful (2xx) or a validation error (422)
        if (response.ok || response.status === 422) {
            return response.json();
        }
        // For other server errors (like 500), throw an error to be caught by .catch()
        return response.text().then(text => { throw new Error(text || 'Server error') });
    })
    .then(data => {
        if (data.errors) {
            // Handle validation errors
            const firstError = Object.values(data.errors)[0][0];
            if (window.showToast) window.showToast(firstError || 'Validation failed.', 'error');
            dropdownBtn.innerHTML = originalContent; // Restore on failure
        } else if (data.success) {
            if (field === 'status') {
                const badge = document.getElementById(`status-badge-${iteration}`);
                if (badge) badge.textContent = value;
                // Update badge color
                badge.className = 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full ';
                const colorClasses = {
                    'In Warehouse': 'bg-blue-100 text-blue-800',
                    'Shipped': 'bg-yellow-100 text-yellow-800',
                    'Delivered': 'bg-green-100 text-green-800',
                    'Sold': 'bg-purple-100 text-purple-800',
                    'Returned': 'bg-red-100 text-red-800',
                };
                badge.classList.add(...(colorClasses[value] || 'bg-gray-100 text-gray-800').split(' '));
                // Restore the chevron
                dropdownBtn.innerHTML = `<span id="status-badge-${iteration}" class="${badge.className}">${value}</span><i class="fas fa-chevron-down text-xs ml-1"></i>`;
            } else {
                dropdownBtn.innerHTML = `<span>${value}</span><i class="fas fa-chevron-down text-xs ml-1"></i>`;
            }
            // Assuming you have a global showToast function like in admin.index.blade.php
            if (window.showToast) {
                window.showToast(data.message || 'Product updated successfully!', 'success');
            } else {
                alert('Product updated successfully!');
            }
        } else {
            if (window.showToast) window.showToast(data.message || 'Error updating product.', 'error');
            dropdownBtn.innerHTML = originalContent; // Restore on failure
        }
    })
    .catch(error => {
        console.error('Update Error:', error);
        if (window.showToast) window.showToast('An error occurred while updating the product.', 'error');
        dropdownBtn.innerHTML = originalContent; // Restore on error
    })
    .finally(() => {
        // Close the dropdown
        const dropdownContent = document.getElementById(`${field}-dropdown-${iteration}`);
        if (dropdownContent) dropdownContent.classList.remove('show');
    });
};

// Add ARIA attributes on page load for dropdowns
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.dropdown-btn').forEach(btn => {
        btn.setAttribute('aria-haspopup', 'true');
        btn.setAttribute('aria-expanded', 'false');
    });
    document.querySelectorAll('.dropdown-content').forEach(content => {
        content.setAttribute('role', 'menu');
    });
    document.querySelectorAll('.dropdown-content a').forEach(link => {
        link.setAttribute('role', 'menuitem');
    });
});
