let isFilterVisible = false;

function iafwzcai_addList_to_filter() {
    iafwzcai_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('.iafwzcai-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 "iafwzcai_"
        if (!value.startsWith("iafwzcai_")) {
            // 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 iafwzcai_toggleFilterArea() {
    const filterContent = document.querySelector('.iafwzcai-setup-filter-content');
    const toggleArrow = document.getElementById('iafwzcai-setup-filter-arrow');

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

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

    // Reset the values of the cloned row and clear any red borders
    filterRow.querySelectorAll('.iafwzcai-setup-filter-field, .iafwzcai-setup-filter-condition, .iafwzcai-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('iafwzcai-setup-filter-logic-row');
    logicRow.innerHTML = `
        <select class="iafwzcai-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('.iafwzcai-setup-filter-row');
    lastRow.after(logicRow, filterRow);
}


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

    if (filterGroup.querySelectorAll('.iafwzcai-setup-filter-row').length > 1) {
        const logicRow = filterRow.previousElementSibling?.classList.contains('iafwzcai-setup-filter-logic-row')
            ? filterRow.previousElementSibling
            : filterRow.nextElementSibling?.classList.contains('iafwzcai-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 iafwzcai_clearAll() {
    const fields = cf7Fields && cf7Fields.length > 0 ? cf7Fields : formFieldList;

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

    // Reset filter container to only one row
    filterGroupContainer.innerHTML = `
        <div class="iafwzcai-setup-filter-group">
            <div class="iafwzcai-setup-filter-row">
                <select class="iafwzcai-setup-filter-field">
                    <option value="" disabled selected>Select Field</option>
                    ${fields
                        .filter(field => !field[0].toString().startsWith('iafwzcai_')) // Exclude fields starting with "iafwzcai_"
                        .map(field => `<option value="${field[0]}">${field[1]}</option>`) // Use index 0 as value, 1 as label
                        .join('')}
                </select>
                <select class="iafwzcai-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="iafwzcai-setup-filter-value" placeholder="Enter value" />
                <div class="iafwzcai-setup-filter-actions">
                    <button class="iafwzcai-setup-filter-add-icon" onclick="iafwzcai_addFilter(this)">+</button>
                    <button class="iafwzcai-setup-filter-close-icon" onclick="iafwzcai_removeFilter(this)">×</button>
                </div>
            </div>
        </div>
    `;

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

function iafwzcai_readFilterConditions() {
    const filterGroup = document.querySelector('.iafwzcai-setup-filter-group');
    const filterRows = filterGroup.querySelectorAll('.iafwzcai-setup-filter-row');
    const logicRows = filterGroup.querySelectorAll('.iafwzcai-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('.iafwzcai-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzcai-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzcai-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('.iafwzcai-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzcai-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzcai-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('.iafwzcai-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 iafwzcai_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('.iafwzcai-setup-filter-group');
        const filterTemplate = document.querySelector('.iafwzcai-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('.iafwzcai-setup-filter-field');
        const conditionSelectTemplate = rowTemplate.querySelector('.iafwzcai-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('.iafwzcai-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('.iafwzcai-setup-filter-condition');
            if (conditionSelectTemplate && conditionSelect) {
                conditionSelect.innerHTML = conditionSelectTemplate.innerHTML; // Copy options
                conditionSelect.value = filter.condition || '';
            }

            // Populate value input
            const valueInput = filterRow.querySelector('.iafwzcai-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 = 'iafwzcai-setup-filter-logic-row';
                logicRow.innerHTML = `
                    <select class="iafwzcai-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('.iafwzcai-setup-filter-content');
            if (filterContent) {
                filterContent.style.display = 'block';
            }
            isFilterVisible = true;
        });
    } catch (error) {
    }
}

