(function() {
    let mowcpsSuppliers = [];
    let mowcpsSelectedSuppliers = new Set();
    let mowcpsModalHTML = '';

    // Load external HTML template
    async function mowcpsLoadModalHTML() {
        try {
            const response = await fetch(window.MOWCPSData.pluginUrl + 'views/assets/templates/delete-modal.html');
            mowcpsModalHTML = await response.text();
        } catch (error) {
            console.warn('Could not load external HTML template, using fallback');
            mowcpsModalHTML = `
                <div id="mowcps-modal-overlay">
                    <div id="mowcps-modal">
                        <div id="mowcps-modal-header">
                            <h2 id="mowcps-modal-title">Delete miniOrange Synced Products</h2>
                            <p id="mowcps-modal-description">Select suppliers whose products you want to delete.</p>
                        </div>
                        <div id="mowcps-modal-body">
                            <div id="mowcps-loading">Loading suppliers...</div>
                            <div id="mowcps-error"></div>
                            <div id="mowcps-supplier-list">
                                <label id="mowcps-select-all-label">
                                    <input type="checkbox" id="mowcps-select-all" checked> Select All
                                </label>
                                <div id="mowcps-suppliers"></div>
                            </div>
                        </div>
                        <div id="mowcps-modal-footer">
                            <button id="mowcps-cancel-btn">Cancel</button>
                            <button id="mowcps-delete-btn" disabled>Delete Selected</button>
                        </div>
                    </div>
                </div>
            `;
        }
    }

    // Load CSS if not already loaded
    function mowcpsLoadModalCSS() {
        if (!document.getElementById('mowcps-modal-css')) {
            const link = document.createElement('link');
            link.id = 'mowcps-modal-css';
            link.rel = 'stylesheet';
            link.href = window.MOWCPSData.pluginUrl + 'views/public/css/delete-modal.css';
            document.head.appendChild(link);
        }
    }

    async function mowcpsFetchSuppliers() {
        try {
            const response = await fetch(`${window.MOWCPSData.restUrl}/suppliers/with-products`, {
                headers: { 'X-WP-Nonce': window.MOWCPSData.restNonce }
            });
            
            if (!response.ok) throw new Error('Failed to fetch suppliers with products');
            
            const data = await response.json();
            mowcpsSuppliers = data.data || [];
            mowcpsSelectedSuppliers = new Set(mowcpsSuppliers.map(s => s.uuid));
            mowcpsRenderSuppliers();
        } catch (error) {
            mowcpsShowError('Failed to load suppliers with products: ' + error.message);
        }
    }

    function mowcpsRenderSuppliers() {
        document.getElementById('mowcps-loading').style.display = 'none';
        document.getElementById('mowcps-supplier-list').style.display = 'block';
        
        if (mowcpsSuppliers.length === 0) {
            document.getElementById('mowcps-suppliers').innerHTML = '<p style="color: #666; font-style: italic;">No suppliers with synced products found.</p>';
            return;
        }
        
        document.getElementById('mowcps-suppliers').innerHTML = mowcpsSuppliers.map(supplier => `
            <label class="mowcps-supplier-label">
                <input type="checkbox" value="${supplier.uuid}" ${mowcpsSelectedSuppliers.has(supplier.uuid) ? 'checked' : ''} class="mowcps-supplier-checkbox">
                ${supplier.name}
            </label>
        `).join('');
        
        mowcpsUpdateStates();
    }

    function mowcpsShowError(message) {
        document.getElementById('mowcps-loading').style.display = 'none';
        const errorEl = document.getElementById('mowcps-error');
        errorEl.textContent = message;
        errorEl.style.display = 'block';
    }

    function mowcpsUpdateStates() {
        const selectAllEl = document.getElementById('mowcps-select-all');
        const deleteBtn = document.getElementById('mowcps-delete-btn');
        const selectedCount = mowcpsSelectedSuppliers.size;
        
        selectAllEl.checked = selectedCount === mowcpsSuppliers.length && mowcpsSuppliers.length > 0;
        selectAllEl.indeterminate = selectedCount > 0 && selectedCount < mowcpsSuppliers.length;
        
        deleteBtn.disabled = selectedCount === 0;
        deleteBtn.style.background = selectedCount === 0 ? '#ccc' : '#1976d2';
    }

    function mowcpsHandleSupplierToggle(uuid, checked) {
        if (checked) mowcpsSelectedSuppliers.add(uuid);
        else mowcpsSelectedSuppliers.delete(uuid);
        mowcpsUpdateStates();
    }

    function mowcpsHandleSelectAllToggle(checked) {
        mowcpsSelectedSuppliers = checked ? new Set(mowcpsSuppliers.map(s => s.uuid)) : new Set();
        document.querySelectorAll('.mowcps-supplier-checkbox').forEach(cb => cb.checked = checked);
        mowcpsUpdateStates();
    }

    async function mowcpsDeleteSelectedProducts() {
        if (mowcpsSelectedSuppliers.size === 0) return alert('No suppliers selected!');

        const selectedNames = mowcpsSuppliers.filter(s => mowcpsSelectedSuppliers.has(s.uuid)).map(s => s.name);
        if (!confirm(`Deleting products from: ${selectedNames.join(', ')}`)) return;

        const deleteBtn = document.getElementById('mowcps-delete-btn');
        deleteBtn.disabled = true;
        deleteBtn.classList.add('loading');
        deleteBtn.textContent = 'Deleting Products...';

        try {
            // Use the new REST API endpoint
            const response = await fetch(`${window.MOWCPSData.restUrl}/suppliers/delete-products`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': window.MOWCPSData.restNonce
                },
                body: JSON.stringify({
                    supplier_uuids: Array.from(mowcpsSelectedSuppliers)
                })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || 'Delete request failed');
            }

            const result = await response.json();
            
            // Show success message
            alert(result.data.message || 'Products deletion started successfully!');
            
            // Close modal and reload page to show admin notice
            mowcpsCloseModal();
            window.location.reload();
            
        } catch (error) {
            alert('Error: ' + error.message);
            deleteBtn.disabled = false;
            deleteBtn.classList.remove('loading');
            deleteBtn.textContent = 'Delete Selected Products';
        }
    }

    async function mowcpsOpenModal() {
        // Load CSS
        mowcpsLoadModalCSS();
        
        // Load HTML if not already loaded
        if (!mowcpsModalHTML) {
            await mowcpsLoadModalHTML();
        }
        
        let modalEl = document.getElementById('mowcps-modal-overlay');
        if (!modalEl) {
            document.body.insertAdjacentHTML('beforeend', mowcpsModalHTML);
            modalEl = document.getElementById('mowcps-modal-overlay');
            
            // Event listeners
            document.getElementById('mowcps-cancel-btn').addEventListener('click', mowcpsCloseModal);
            document.getElementById('mowcps-delete-btn').addEventListener('click', mowcpsDeleteSelectedProducts);
            document.getElementById('mowcps-select-all').addEventListener('change', (e) => mowcpsHandleSelectAllToggle(e.target.checked));
            document.getElementById('mowcps-suppliers').addEventListener('change', (e) => {
                if (e.target.classList.contains('mowcps-supplier-checkbox')) {
                    mowcpsHandleSupplierToggle(e.target.value, e.target.checked);
                }
            });
            modalEl.addEventListener('click', (e) => {
                if (e.target.id === 'mowcps-modal-overlay') mowcpsCloseModal();
            });
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && modalEl.style.display === 'block') mowcpsCloseModal();
            });
        }
        
        mowcpsSelectedSuppliers.clear();
        mowcpsSuppliers = [];
        modalEl.style.display = 'block';
        mowcpsFetchSuppliers();
    }

    function mowcpsCloseModal() {
        const modalEl = document.getElementById('mowcps-modal-overlay');
        if (modalEl) modalEl.style.display = 'none';
    }

    // Expose the modal functionality globally
    window.MOWCPSDeleteModal = {
        open: mowcpsOpenModal,
        close: mowcpsCloseModal
    };
    
    // Also expose the direct function for compatibility
    window.openDeleteProductsModal = mowcpsOpenModal;

})();
