document.addEventListener('DOMContentLoaded', function () {

    /**
     * -------------------------------
     * Multipage Navigation
     * -------------------------------
     */
    const form = document.querySelector('.wefb-frontend-form');
    if (form) {
        const pages = form.querySelectorAll('.wefb-page');
        let currentPage = 0;

        function showPage(index) {
            pages.forEach((page, i) => {
                page.style.display = (i === index) ? '' : 'none';
            });
            currentPage = index;
        }

        form.addEventListener('click', function (e) {
            if (e.target.classList.contains('wefb-next')) {
                e.preventDefault();
                if (currentPage < pages.length - 1) {
                    showPage(currentPage + 1);
                }
            }
            if (e.target.classList.contains('wefb-prev')) {
                e.preventDefault();
                if (currentPage > 0) {
                    showPage(currentPage - 1);
                }
            }
        });

        if (pages.length > 0) {
            showPage(0); // start at first page
        }
    }

    /**
     * -------------------------------
     * Conditional Logic
     * -------------------------------
     */
    const conditionalFields = document.querySelectorAll('.wefb-field[data-conditional]');
    if (conditionalFields.length) {

        function checkCondition(fieldEl) {
            let condRaw = fieldEl.getAttribute('data-conditional');
            if (!condRaw) return;

            let cond;
            try {
                cond = JSON.parse(condRaw);
            } catch (err) {
                return;
            }

            if (!cond.enabled) return;

            const targetField = document.querySelector(`[data-id="${cond.field}"]`);
            if (!targetField) return;

            const targetInputs = targetField.querySelectorAll('input, select, textarea');
            if (!targetInputs.length) return;

            const firstInput = targetInputs[0];
            let val = '';

            if (firstInput.type === 'radio') {
                const checkedRadio = targetField.querySelector('input[type="radio"]:checked');
                if (checkedRadio) val = checkedRadio.value;
            } else if (firstInput.type === 'checkbox') {
                const checkedValues = Array.from(targetField.querySelectorAll('input[type="checkbox"]:checked')).map(input => input.value);
                val = checkedValues;
            } else if (firstInput.tagName === 'SELECT' && firstInput.multiple) {
                val = Array.from(firstInput.selectedOptions || []).map(option => option.value);
            } else {
                val = firstInput.value;
            }

            let show = false;
            switch (cond.operator) {
                case 'equals':
                    show = Array.isArray(val) ? val.includes(cond.value) : (val == cond.value);
                    break;
                case 'not_equals':
                    show = Array.isArray(val) ? !val.includes(cond.value) : (val != cond.value);
                    break;
                case 'contains':
                    show = Array.isArray(val) ? val.includes(cond.value) : (val && val.indexOf(cond.value) !== -1);
                    break;
                case 'not_contains':
                    show = Array.isArray(val) ? !val.includes(cond.value) : (val && val.indexOf(cond.value) === -1);
                    break;
                default:
                    break;
            }

            fieldEl.style.display = show ? '' : 'none';
        }

        function bindConditionEvents() {
            conditionalFields.forEach(fieldEl => {
                let condRaw = fieldEl.getAttribute('data-conditional');
                if (!condRaw) return;

                let cond;
                try {
                    cond = JSON.parse(condRaw);
                } catch (err) {
                    return;
                }

                if (!cond.enabled) return;

                const targetField = document.querySelector(`[data-id="${cond.field}"]`);
                if (!targetField) return;

                const inputs = targetField.querySelectorAll('input, select, textarea');
                inputs.forEach(inp => {
                    inp.addEventListener('input', () => checkCondition(fieldEl));
                    inp.addEventListener('change', () => checkCondition(fieldEl));
                });

                // Initial check
                checkCondition(fieldEl);
            });
        }

        bindConditionEvents();
    }

});

document.addEventListener("DOMContentLoaded", function () {
    const forms = document.querySelectorAll(".wefb-frontend-form");

    forms.forEach(form => {
        initPasswordUI(form);

        form.addEventListener("submit", function (e) {
            let valid = true;
            const validatedGroups = new Set();

            // Remove old errors
            form.querySelectorAll(".wefb-error").forEach(err => err.remove());
            form.querySelectorAll(".wefb-error-input").forEach(input => input.classList.remove("wefb-error-input"));
            clearSummary(form);

            // Loop through required fields
            form.querySelectorAll("[required]").forEach(field => {
                if (!isFieldVisible(field) || field.disabled) {
                    return;
                }

                const type = (field.type || "").toLowerCase();
                const name = field.getAttribute("name") || "";

                if (type === "radio" || type === "checkbox") {
                    if (!name || validatedGroups.has(name)) {
                        return;
                    }
                    validatedGroups.add(name);
                    const group = form.querySelectorAll(`[name="${cssEscape(name)}"]`);
                    const isChecked = Array.from(group).some(input => input.checked);
                    if (!isChecked) {
                        valid = false;
                        showGroupError(form, field, name, "This field is required");
                    }
                    return;
                }

                if (field.tagName === "SELECT" && field.multiple) {
                    if (!field.selectedOptions || field.selectedOptions.length === 0) {
                        valid = false;
                        showError(field, "This field is required");
                    }
                    return;
                }

                if (!String(field.value || "").trim()) {
                    valid = false;
                    showError(field, "This field is required");
                } else if (type === "email" && !isValidEmail(field.value)) {
                    valid = false;
                    showError(field, "Please enter a valid email");
                } else if (type === "number" && isNaN(field.value)) {
                    valid = false;
                    showError(field, "Please enter a valid number");
                } else if (field.maxLength > 0 && String(field.value || "").length > field.maxLength) {
                    valid = false;
                    showError(field, "Maximum length exceeded");
                } else if (field.dataset.passwordRole === 'user_pass') {
                    const passwordPolicyError = validatePasswordPolicyField(field);
                    if (passwordPolicyError) {
                        valid = false;
                        showError(field, passwordPolicyError);
                    }
                }
            });

            const passwordInput = form.querySelector('input[data-password-role="user_pass"]');
            const confirmInput = form.querySelector('input[data-password-role="confirm_pass"]');
            if (passwordInput && confirmInput && isFieldVisible(confirmInput)) {
                if (String(confirmInput.value || '').trim() !== String(passwordInput.value || '').trim()) {
                    valid = false;
                    showError(confirmInput, 'Password and confirm password do not match.');
                }
            }

            if (!valid) {
                e.preventDefault();
                const summaryMessage =
                    (window.wpefb_error_object && window.wpefb_error_object.review_highlighted_fields)
                        ? window.wpefb_error_object.review_highlighted_fields
                        : "Please review the highlighted required fields.";
                showSummary(form, summaryMessage);
            }
        });
    });

    function initPasswordUI(form) {
        const toggleButtons = form.querySelectorAll('.wefb-password-toggle');
        toggleButtons.forEach(button => {
            button.addEventListener('click', function () {
                const targetId = button.getAttribute('data-target');
                if (!targetId) return;
                const input = form.querySelector('#' + cssEscape(targetId));
                if (!input) return;
                if (input.type === 'password') {
                    input.type = 'text';
                    button.textContent = 'Hide';
                } else {
                    input.type = 'password';
                    button.textContent = 'Show';
                }
            });
        });

        const passwordInputs = form.querySelectorAll('input[data-password-role="user_pass"]');
        passwordInputs.forEach(input => {
            input.addEventListener('input', function () {
                updatePasswordStrength(form, input);
            });
            updatePasswordStrength(form, input);
        });
    }

    function showError(field, message) {
        field.classList.add("wefb-error-input");

        const error = document.createElement("div");
        error.className = "wefb-error";
        error.textContent = message;

        field.parentNode.appendChild(error);
    }

    function showGroupError(form, field, name, message) {
        const group = form.querySelectorAll(`[name="${cssEscape(name)}"]`);
        group.forEach(input => input.classList.add("wefb-error-input"));

        const wrapper = field.closest(".wefb-field") || field.parentNode;
        if (!wrapper) return;

        const existing = wrapper.querySelector(".wefb-error");
        if (existing) {
            existing.textContent = message;
            return;
        }

        const error = document.createElement("div");
        error.className = "wefb-error";
        error.textContent = message;
        wrapper.appendChild(error);
    }

    function showSummary(form, message) {
        let summary = form.querySelector(".wefb-inline-summary");
        if (!summary) {
            summary = document.createElement("div");
            summary.className = "wefb-errors wefb-inline-summary";
            summary.setAttribute("role", "alert");
            form.prepend(summary);
        }
        summary.textContent = message;
    }

    function clearSummary(form) {
        const summary = form.querySelector(".wefb-inline-summary");
        if (summary) {
            summary.remove();
        }
    }

    function isFieldVisible(field) {
        const wrapper = field.closest(".wefb-field");
        if (!wrapper) {
            return true;
        }
        if (wrapper.offsetParent === null) {
            return false;
        }
        return true;
    }

    function cssEscape(name) {
        if (window.CSS && typeof window.CSS.escape === "function") {
            return window.CSS.escape(name);
        }
        return name.replace(/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, "\\$&");
    }

    function isValidEmail(email) {
        // Simple email regex
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    function getPasswordPolicy(input) {
        const minLength = parseInt(input.dataset.passwordMinLength || '8', 10);
        return {
            minLength: Number.isFinite(minLength) && minLength > 0 ? minLength : 8,
            requireUppercase: input.dataset.passwordRequireUppercase === '1',
            requireLowercase: input.dataset.passwordRequireLowercase !== '0',
            requireNumber: input.dataset.passwordRequireNumber === '1',
            requireSpecial: input.dataset.passwordRequireSpecial === '1'
        };
    }

    function validatePasswordPolicyField(input) {
        const value = String(input.value || '');
        const policy = getPasswordPolicy(input);
        if (!value) return null;
        if (value.length < policy.minLength) {
            return 'Password must be at least ' + policy.minLength + ' characters long.';
        }
        if (policy.requireUppercase && !/[A-Z]/.test(value)) {
            return 'Password must include at least one uppercase letter.';
        }
        if (policy.requireLowercase && !/[a-z]/.test(value)) {
            return 'Password must include at least one lowercase letter.';
        }
        if (policy.requireNumber && !/\d/.test(value)) {
            return 'Password must include at least one number.';
        }
        if (policy.requireSpecial && !/[^A-Za-z0-9]/.test(value)) {
            return 'Password must include at least one special character.';
        }
        return null;
    }

    function updatePasswordStrength(form, input) {
        if (input.dataset.passwordShowStrength !== '1') {
            return;
        }
        const targetId = input.getAttribute('id');
        if (!targetId) {
            return;
        }
        const indicator = form.querySelector('.wefb-password-strength[data-for="' + cssEscape(targetId) + '"] .wefb-password-strength-value');
        if (!indicator) {
            return;
        }

        const value = String(input.value || '');
        let score = 0;
        if (value.length >= 8) score++;
        if (/[A-Z]/.test(value)) score++;
        if (/[a-z]/.test(value)) score++;
        if (/\d/.test(value)) score++;
        if (/[^A-Za-z0-9]/.test(value)) score++;

        let label = 'Weak';
        let cssClass = 'wefb-strength-weak';
        if (score >= 5) {
            label = 'Strong';
            cssClass = 'wefb-strength-strong';
        } else if (score >= 3) {
            label = 'Medium';
            cssClass = 'wefb-strength-medium';
        }

        indicator.textContent = label;
        indicator.classList.remove('wefb-strength-weak', 'wefb-strength-medium', 'wefb-strength-strong');
        indicator.classList.add(cssClass);
    }

    // Remove error style on input change
    document.querySelectorAll(".wefb-frontend-form input, .wefb-frontend-form textarea, .wefb-frontend-form select")
        .forEach(el => {
            el.addEventListener("input", () => {
                const form = el.closest(".wefb-frontend-form");
                const type = (el.type || "").toLowerCase();
                const name = el.getAttribute("name") || "";
                if ((type === "radio" || type === "checkbox") && form && name) {
                    form.querySelectorAll(`[name="${cssEscape(name)}"]`).forEach(input => input.classList.remove("wefb-error-input"));
                    const wrapper = el.closest(".wefb-field");
                    const err = wrapper ? wrapper.querySelector(".wefb-error") : null;
                    if (err) err.remove();
                } else {
                    el.classList.remove("wefb-error-input");
                    const err = el.parentNode.querySelector(".wefb-error");
                    if (err) err.remove();
                }
                if (form && !form.querySelector(".wefb-error")) {
                    clearSummary(form);
                }
            });
            el.addEventListener("change", () => {
                const form = el.closest(".wefb-frontend-form");
                const type = (el.type || "").toLowerCase();
                const name = el.getAttribute("name") || "";
                if ((type === "radio" || type === "checkbox") && form && name) {
                    form.querySelectorAll(`[name="${cssEscape(name)}"]`).forEach(input => input.classList.remove("wefb-error-input"));
                    const wrapper = el.closest(".wefb-field");
                    const err = wrapper ? wrapper.querySelector(".wefb-error") : null;
                    if (err) err.remove();
                } else {
                    el.classList.remove("wefb-error-input");
                    const err = el.parentNode.querySelector(".wefb-error");
                    if (err) err.remove();
                }
                if (form && !form.querySelector(".wefb-error")) {
                    clearSummary(form);
                }
            });
        });
});
