let isFilterVisible = false;

function iafwzdesk_addList_to_filter() {
    iafwzdesk_clearAll();
    // Determine the fields source
    const fields = cf7Fields && cf7Fields.length > 0 ? cf7Fields : formFieldList;

    if (!fields || fields.length === 0) {
        return;
    }

    // Target the <select> element
    const selectElement = document.querySelector('.iafwzdesk-setup-filter-field');

    if (!selectElement) {
        return;
    }

    // Populate the <select> with additional options
    fields.forEach(row => {
        const value = row[0].toString();
        const displayName = row[1];

        // Skip rows where value starts with "iafwzdesk_"
        if (!value.startsWith("iafwzdesk_")) {
            // Check if the option already exists
            const existingOption = Array.from(selectElement.options).find(option => option.value === value);

            if (!existingOption) {
                const option = document.createElement('option');
                option.value = value; // Set the value
                option.textContent = displayName; // Set the display text
                selectElement.appendChild(option); // Add the option to the <select>
            }
        }
    });
}



function iafwzdesk_toggleFilterArea() {
    const filterContent = document.querySelector('.iafwzdesk-setup-filter-content');
    const toggleArrow = document.getElementById('iafwzdesk-setup-filter-arrow');

    if (isFilterVisible) {
        filterContent.style.display = 'none';
        toggleArrow.textContent = '▼';
    } else {
        filterContent.style.display = 'block';
        toggleArrow.textContent = '▲';
    }
    isFilterVisible = !isFilterVisible;
}

function iafwzdesk_addFilter(element) {
    const filterGroup = element.closest('.iafwzdesk-setup-filter-group');
    const filterRow = filterGroup.querySelector('.iafwzdesk-setup-filter-row').cloneNode(true);

    // Reset the values of the cloned row and clear any red borders
    filterRow.querySelectorAll('.iafwzdesk-setup-filter-field, .iafwzdesk-setup-filter-condition, .iafwzdesk-setup-filter-value').forEach(input => {
        input.value = "";
        input.style.border = ""; // Clear the red border
        if (input.tagName === "SELECT") {
            input.selectedIndex = 0;
        }
    });

    // Clear red borders from all rows' inputs and selects
    filterGroup.querySelectorAll('input, select').forEach(el => {
        el.style.border = ""; // Remove red border
    });

    // Add logic dropdown between rows
    const logicRow = document.createElement('div');
    logicRow.classList.add('iafwzdesk-setup-filter-logic-row');
    logicRow.innerHTML = `
        <select class="iafwzdesk-setup-filter-logic-select">
            <option value="AND">AND</option>
            <option value="OR">OR</option>
        </select>
    `;

    // Append the new filter row and logic row
    const lastRow = element.closest('.iafwzdesk-setup-filter-row');
    lastRow.after(logicRow, filterRow);
}


function iafwzdesk_removeFilter(element) {
    const filterGroup = element.closest('.iafwzdesk-setup-filter-group');
    const filterRow = element.closest('.iafwzdesk-setup-filter-row');

    if (filterGroup.querySelectorAll('.iafwzdesk-setup-filter-row').length > 1) {
        const logicRow = filterRow.previousElementSibling?.classList.contains('iafwzdesk-setup-filter-logic-row')
            ? filterRow.previousElementSibling
            : filterRow.nextElementSibling?.classList.contains('iafwzdesk-setup-filter-logic-row')
            ? filterRow.nextElementSibling
            : null;

        // Remove logic row if it exists
        if (logicRow) logicRow.remove();
        filterRow.remove();
    } else {
        alert('At least one filter is required.');
    }
}

function iafwzdesk_clearAll() {
    const fields = cf7Fields && cf7Fields.length > 0 ? cf7Fields : formFieldList;

    if (!fields || fields.length === 0) {
        return;
    }
    const filterGroupContainer = document.getElementById('iafwzdesk-setup-filter-group-container');

    // Reset filter container to only one row
    filterGroupContainer.innerHTML = `
        <div class="iafwzdesk-setup-filter-group">
            <div class="iafwzdesk-setup-filter-row">
                <select class="iafwzdesk-setup-filter-field">
                    <option value="" disabled selected>Select Field</option>
                    ${fields
                        .filter(field => !field[0].toString().startsWith('iafwzdesk_')) // Exclude fields starting with "iafwzdesk_"
                        .map(field => `<option value="${field[0]}">${field[1]}</option>`) // Use index 0 as value, 1 as label
                        .join('')}
                </select>
                <select class="iafwzdesk-setup-filter-condition">
                    <option value="" disabled selected>Choose Condition</option>
                     <option value="contains">Contains</option>
                                    <option value="not_contains">Does Not Contain</option>
                                    <option value="equals">Equals</option>
                                    <option value="not_equals">Does Not Equal</option>
                                    <option value="starts_with">Starts With</option>
                                    <option value="ends_with">Ends With</option>
                                    <option value="greater_than">Greater Than</option>
                                    <option value="less_than">Less Than</option>
                                    <option value="is_empty">Is Empty</option>
                                    <option value="is_not_empty">Is Not Empty</option>
                </select>
                <input type="text" class="iafwzdesk-setup-filter-value" placeholder="Enter value" />
                <div class="iafwzdesk-setup-filter-actions">
                    <button class="iafwzdesk-setup-filter-add-icon" onclick="iafwzdesk_addFilter(this)">+</button>
                    <button class="iafwzdesk-setup-filter-close-icon" onclick="iafwzdesk_removeFilter(this)">×</button>
                </div>
            </div>
        </div>
    `;

    // Keep the filter area open
    const filterContent = document.querySelector('.iafwzdesk-setup-filter-content');
    if (filterContent) {
        //  filterContent.style.display = 'block';
    }
    isFilterVisible = false; // Ensure global visibility variable is updated
}

function iafwzdesk_readFilterConditions() {
    const filterGroup = document.querySelector('.iafwzdesk-setup-filter-group');
    const filterRows = filterGroup.querySelectorAll('.iafwzdesk-setup-filter-row');
    const logicRows = filterGroup.querySelectorAll('.iafwzdesk-setup-filter-logic-row');

    const result = [];
    let hasErrors = false; // Track if any errors occur
    
    // Check if there is exactly one row
    if (filterRows.length === 1) {
        const row = filterRows[0];
        const fieldElement = row.querySelector('.iafwzdesk-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzdesk-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzdesk-setup-filter-value');

        const field = fieldElement ? fieldElement.value.trim() : null;
        const condition = conditionElement ? conditionElement.value.trim() : null;
        const value = valueElement ? valueElement.value.trim() : '';

        // If the single row is completely empty, return an empty array
        if (!field && !condition && !value) {
            return null;
        }
    }

    // Iterate through filter rows and logic rows
    filterRows.forEach((row, index) => {
        const fieldElement = row.querySelector('.iafwzdesk-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzdesk-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzdesk-setup-filter-value');

        const field = fieldElement ? fieldElement.value.trim() : null;
        const condition = conditionElement ? conditionElement.value.trim() : null;
        const value = valueElement ? valueElement.value.trim() : '';

        // Highlight missing fields
        if (!field) {
            fieldElement.style.border = '0.5px solid red';
            hasErrors = true;
        } else {
            fieldElement.style.border = '';
        }

        if (!condition) {
            conditionElement.style.border = '0.5px solid red';
            hasErrors = true;
        } else {
            conditionElement.style.border = '';
        }

        if (!value) {
            valueElement.style.border = '0.5px solid red';
            hasErrors = true;
        } else {
            valueElement.style.border = '';
        }

        // Determine logic value for this row (if not the last row)
        let logic = null;
        if (index < logicRows.length) {
            const logicSelect = logicRows[index].querySelector('.iafwzdesk-setup-filter-logic-select');
            logic = logicSelect ? logicSelect.value.trim() : null;

            // Highlight missing logic
            if (!logic) {
                logicSelect.style.border = '0.5px solid red';
                hasErrors = true;
            } else {
                logicSelect.style.border = '';
            }
        }

        // Add valid row to the result
        if (field && condition && value) {
            result.push({
                field,
                condition,
                value,
                logic,
            });
        }
    });

    // If any errors exist, return false
    if (hasErrors) {
        return false;
    }

    // Return the valid result if no errors
    return result;
}





function iafwzdesk_createFilterUI(filterList) {
    try {
        // Parse the string into a JavaScript object
        if (typeof filterList === 'string') {
            filterList = JSON.parse(filterList);
        }

        // Ensure filterList is now an array
        if (!Array.isArray(filterList)) {
            return;
        }

        const filterGroupContainer = document.querySelector('.iafwzdesk-setup-filter-group');
        const filterTemplate = document.querySelector('.iafwzdesk-setup-filter-row');

        if (!filterGroupContainer || !filterTemplate) {
            return;
        }
        // Clone the template row including the options
        const rowTemplate = filterTemplate.cloneNode(true);
        rowTemplate.style.display = ''; // Make the row visible

        // Ensure dropdown options are cloned
        const fieldSelectTemplate = rowTemplate.querySelector('.iafwzdesk-setup-filter-field');
        const conditionSelectTemplate = rowTemplate.querySelector('.iafwzdesk-setup-filter-condition');

        // Clear existing UI
        filterGroupContainer.innerHTML = '';

        // Use the cloned template for all rows
        filterList.forEach((filter, index) => {
            const filterRow = rowTemplate.cloneNode(true); // Clone the row template
           
            // Manually clone and append options for the first dropdown
            const fieldSelect = filterRow.querySelector('.iafwzdesk-setup-filter-field');
            if (fieldSelectTemplate && fieldSelect) {
                fieldSelect.innerHTML = fieldSelectTemplate.innerHTML; // Copy options
                fieldSelect.value = filter.field || '';
            }

            // Manually clone and append options for the second dropdown
            const conditionSelect = filterRow.querySelector('.iafwzdesk-setup-filter-condition');
            if (conditionSelectTemplate && conditionSelect) {
                conditionSelect.innerHTML = conditionSelectTemplate.innerHTML; // Copy options
                conditionSelect.value = filter.condition || '';
            }

            // Populate value input
            const valueInput = filterRow.querySelector('.iafwzdesk-setup-filter-value');
            if (valueInput) {
                valueInput.value = filter.value || '';
            }

            // Add the updated row to the container
            filterGroupContainer.appendChild(filterRow);

            // Add logic row if not the last filter
            if (index < filterList.length - 1) {
                const logicRow = document.createElement('div');
                logicRow.className = 'iafwzdesk-setup-filter-logic-row';
                logicRow.innerHTML = `
                    <select class="iafwzdesk-setup-filter-logic-select">
                        <option value="AND" ${filter.logic === 'AND' ? 'selected' : ''}>AND</option>
                        <option value="OR" ${filter.logic === 'OR' ? 'selected' : ''}>OR</option>
                    </select>
                `;
                filterGroupContainer.appendChild(logicRow);
            }
            const filterContent = document.querySelector('.iafwzdesk-setup-filter-content');
            if (filterContent) {
                filterContent.style.display = 'block';
            }
            isFilterVisible = true;
        });
    } catch (error) {
    }
}

