// multi select init Below.
document.multiselect('.metaDropDown');

// Showing Warning message 
document.querySelectorAll('.trelloBoard, .trello_list, .trello_due_date, .trello_label_colour').forEach(element => {
    element.addEventListener('click', function () {
        const trelloAccessCode = document.querySelector('#trello_api').value;
        if (!trelloAccessCode) {
            document.querySelector('#save_settings').style.borderColor = 'red';
            document.querySelector('#trello_api').style.borderColor = 'red';
            alert('Please save Trello access code, before selecting the Trello Board or List!!');
        }
    });
});

// Consolidated listener for Trello Board changes
document.querySelectorAll('.trelloBoard').forEach(element => {
    element.addEventListener('change', async function (e) {
        // 1. Identify Target Dropdowns
        const listFieldsID = `#${e.target.id}_trello_list`;
        const colorFieldsID = `#${e.target.id}_trello_label_colour`;
        const boardID = e.target.value;

        if (boardID) {
            // Disable fields while loading
            const listField = document.querySelector(listFieldsID);
            const colorField = document.querySelector(colorFieldsID);
            
            if (listField) listField.disabled = true;
            if (colorField) colorField.disabled = true;

            const ajaxData = {
                action: 'wootrello_ajax_response', // We use one single action
                boardID: boardID,
                security: wootrello_data.security
            };

            try {
                const response = await fetch(wootrello_data.wootrelloAjaxURL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams(ajaxData)
                });

                const data = await response.json();

                console.log('AJAX Response:', data); // Debug logging

                // Check if the server returned success (data[0])
                // The PHP returns array(TRUE, lists, labels) which becomes [true, {}, {}] in JSON
                if (data[0] === true || data[0] === 1 || data[0] === "1") {
                    
                    // 2. Populate Trello Lists (from data[1])
                    if (listField && data[1]) {
                        let listOptions = '<option value="" selected disabled hidden> -- Select Trello List -- </option>';
                        Object.entries(data[1]).forEach(([key, value]) => {
                            listOptions += `<option value="${key}">${value}</option>`;
                        });
                        listField.innerHTML = listOptions;
                        listField.disabled = false;
                    }

                    // 3. Populate Trello Labels/Colors (from data[2])
                    if (colorField && data[2]) {
                        let colorOptions = '<option value="" selected disabled hidden> -- Colour -- </option>';
                        // Check if data[2] is an object with entries
                        if (typeof data[2] === 'object' && data[2] !== null) {
                            Object.entries(data[2]).forEach(([id, text]) => {
                                colorOptions += `<option value="${id}">${text}</option>`;
                            });
                            colorField.innerHTML = colorOptions;
                            colorField.disabled = false;
                        } else {
                            console.error('Label data is not in expected format:', data[2]);
                        }
                    } else {
                        console.error('Color field not found or data[2] is missing');
                    }
                } else {
                    alert(`Error: ${data[1] || 'Unknown error occurred'}`);
                }
            } catch (error) {
                console.error('AJAX Error:', error);
                alert('Failed to fetch board data. Please check the console for details.');
            }
        }
    });
});

// Single Order Page
if (document.getElementById('wootrelloCreateCard')) {
    document.getElementById('wootrelloCreateCard').addEventListener('click', async function () {
        const wooTrelloRelSettings = document.getElementById('wooTrelloRelSettings').value;
        const wootrelloOrderId = document.getElementById('wootrello_order_id').value;
        const wootrelloNonce = document.getElementById('wootrello_nonce').value;
        // If wooTrelloRelSettings and orderID are not empty
        if (wooTrelloRelSettings && wootrelloOrderId) {
            const ajaxDataTwo = {
                action: 'wootrello_ajax_single_order',
                orderID: wootrelloOrderId,
                relatedSettings: wooTrelloRelSettings,
                security: wootrelloNonce
            };
            // 
            try {
                // AJAX request
                const response = await fetch(wootrello_data.wootrelloAjaxURL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams(ajaxDataTwo)
                });

                const wootrelloResponse = await response.json();
                console.log(wootrelloResponse);
            } catch (error) {
                console.error('Error:', error);
            }
        } else {
            alert('Please select the Dropdown! or order ID is Empty!');
        }
    });
}

// Deleting Single order Trello History
if (document.getElementById('wooTrelloDeleteHistory')) {
    document.getElementById('wooTrelloDeleteHistory').addEventListener('click', async function () {
        const wootrelloOrderId = document.getElementById('wootrello_order_id').value;
        const wootrelloNonce = document.getElementById('wootrello_nonce').value;
        // 
        if (wootrelloOrderId && wootrelloNonce) {
            const deleteData = {
                action: 'wootrello_ajax_delete_history',
                orderID: wootrelloOrderId,
                security: wootrelloNonce
            };

            try {
                const response = await fetch(wootrello_data.wootrelloAjaxURL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams(deleteData)
                });

                const deleteResponse = await response.json();
                console.log(deleteResponse);
                document.getElementById('trelloHistoryContent').style.display = 'none';
            } catch (error) {
                console.error('Error:', error);
            }
        } else {
            alert('ID or Nonce not Empty.');
        }
    });
}