let isFilterVisible = false;

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

    if (!fields || fields.length === 0) {
        console.error('No fields available to populate the select element.');
        return;
    }

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

    if (!selectElement) {
        console.error('Select element not found.');
        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 "iafwzc_"
        if (!value.startsWith("iafwzc_")) {
            // 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 iafwzc_toggleFilterArea() {
    const filterContent = document.querySelector('.iafwzc-setup-filter-content');
    const toggleArrow = document.getElementById('iafwzc-setup-filter-arrow');

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

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

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


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

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

    if (!fields || fields.length === 0) {
        console.error('No fields available to populate the select element.');
        return;
    }
    const filterGroupContainer = document.getElementById('iafwzc-setup-filter-group-container');

    // Reset filter container to only one row
    const $filterGroup = document.createElement('div');
    $filterGroup.className = 'iafwzc-setup-filter-group';
    const $filterRow = document.createElement('div');
    $filterRow.className = 'iafwzc-setup-filter-row';

    const $fieldSelect = document.createElement('select');
    $fieldSelect.className = 'iafwzc-setup-filter-field';
    const $defaultOpt = document.createElement('option');
    $defaultOpt.value = '';
    $defaultOpt.disabled = true;
    $defaultOpt.selected = true;
    $defaultOpt.textContent = 'Select Field';
    $fieldSelect.appendChild($defaultOpt);
    fields.filter(field => !field[0].toString().startsWith('iafwzc_')).forEach(field => {
        const opt = document.createElement('option');
        opt.value = field[0];
        opt.textContent = field[1];
        $fieldSelect.appendChild(opt);
    });

    const $condSelect = document.createElement('select');
    $condSelect.className = 'iafwzc-setup-filter-condition';
    [
        ['', 'Choose Condition', true],
        ['contains', 'Contains'],
        ['not_contains', 'Does Not Contain'],
        ['equals', 'Equals'],
        ['not_equals', 'Does Not Equal'],
        ['starts_with', 'Starts With'],
        ['ends_with', 'Ends With'],
        ['greater_than', 'Greater Than'],
        ['less_than', 'Less Than'],
        ['is_empty', 'Is Empty'],
        ['is_not_empty', 'Is Not Empty'],
    ].forEach(([val, label, disabled]) => {
        const opt = document.createElement('option');
        opt.value = val;
        opt.textContent = label;
        if (disabled) { opt.disabled = true; opt.selected = true; }
        $condSelect.appendChild(opt);
    });

    const $valueInput = document.createElement('input');
    $valueInput.type = 'text';
    $valueInput.className = 'iafwzc-setup-filter-value';
    $valueInput.placeholder = 'Enter value';

    const $actions = document.createElement('div');
    $actions.className = 'iafwzc-setup-filter-actions';
    const $addBtn = document.createElement('button');
    $addBtn.className = 'iafwzc-setup-filter-add-icon';
    $addBtn.setAttribute('onclick', 'iafwzc_addFilter(this)');
    $addBtn.textContent = '+';
    const $removeBtn = document.createElement('button');
    $removeBtn.className = 'iafwzc-setup-filter-close-icon';
    $removeBtn.setAttribute('onclick', 'iafwzc_removeFilter(this)');
    $removeBtn.textContent = '×';
    $actions.appendChild($addBtn);
    $actions.appendChild($removeBtn);

    $filterRow.appendChild($fieldSelect);
    $filterRow.appendChild($condSelect);
    $filterRow.appendChild($valueInput);
    $filterRow.appendChild($actions);
    $filterGroup.appendChild($filterRow);

    filterGroupContainer.innerHTML = '';
    filterGroupContainer.appendChild($filterGroup);

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

function iafwzc_readFilterConditions() {
    const filterGroup = document.querySelector('.iafwzc-setup-filter-group');
    const filterRows = filterGroup.querySelectorAll('.iafwzc-setup-filter-row');
    const logicRows = filterGroup.querySelectorAll('.iafwzc-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('.iafwzc-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzc-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzc-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('.iafwzc-setup-filter-field');
        const conditionElement = row.querySelector('.iafwzc-setup-filter-condition');
        const valueElement = row.querySelector('.iafwzc-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('.iafwzc-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) {
        console.error('Validation failed: Please fill in all fields and logic for each row.');
        return false;
    }

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





function iafwzc_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)) {
            // console.error('Parsed filterList is not an array:', filterList);
            return;
        }

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

        if (!filterGroupContainer || !filterTemplate) {
            // console.error('Filter group container or template not found.');
            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('.iafwzc-setup-filter-field');
        const conditionSelectTemplate = rowTemplate.querySelector('.iafwzc-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('.iafwzc-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('.iafwzc-setup-filter-condition');
            if (conditionSelectTemplate && conditionSelect) {
                conditionSelect.innerHTML = conditionSelectTemplate.innerHTML; // Copy options
                conditionSelect.value = filter.condition || '';
            }

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

