;(function ($) {

    class FensePageOptions {

        __find(id, itemOrder, add = true) {
            if (add) {
                $("#form" + id).find(`tr:eq(${itemOrder})`).addClass('hide');
            } else {
                $("#form" + id).find(`tr:eq(${itemOrder})`).removeClass('hide');
            }
        }

        onLoad() {

            const se = $('select[name=FENSE_BPVT_DEVOZON_enable_on_custom]').val();
            const st = $('select[name=FENSE_BPVT_DEVOZON_protection_mode]').val();
            const sy = $('select[name=FENSE_BPVT_DEVOZON_crawlers_bots]').val();

            const whitelisting_enable = $('input[name=FENSE_BPVT_DEVOZON_ip_whitelisting_enable]').prop('checked');
            const blacklisting_enable = $('input[name=FENSE_BPVT_DEVOZON_ip_blacklisting_enable]').prop('checked');

            if (se === 'all') {
                this.__find(1, 3)
                this.__find(1, 4)
                this.__find(1, 5)
                this.__find(1, 6)
            }

            if (st === 'message') {
                this.__find(2, 2)
                this.__find(2, 3)
            }

            if (st === 'redirect') {
                this.__find(2, 1)
                this.__find(2, 3)
            }

            if (st === 'show_content') {
                this.__find(2, 1)
                this.__find(2, 2)
            }

            if (sy === 'yes') {
                this.__find(2, 11, false)
            } else {
                this.__find(2, 11)
            }

            if (blacklisting_enable) {
                this.__find(5, 4, false)
                this.__find(5, 5, false)
            } else {
                this.__find(5, 4)
                this.__find(5, 5)
            }

            if (whitelisting_enable) {
                this.__find(5, 1, false)
                this.__find(5, 2, false)
            } else {
                this.__find(5, 1)
                this.__find(5, 2)
            }

            this.loadEvents()
        }

        saveSettings() {
            if (!this.__checkIpSection()) return false;

            const submit = document.getElementById("submit");
            submit.innerHTML = `<i class="fas fa-floppy-disk"></i> ${this.__getLang(2)} ...`;
            submit.className = 'btn btn-primary mt-4 disabled';

            const total = 5;
            let completed = 0;
            let hasError = false;

            for (let i = 1; i <= total; i++) {
                const form = document.getElementById("form" + i);
                const data = new FormData(form);

                const xhr = new XMLHttpRequest();
                xhr.open("POST", this.__getLang(3));

                xhr.onload = () => {
                    if (xhr.status !== 200) hasError = true;
                    completed++;

                    // wait until ALL 5 have responded
                    if (completed < total) return;

                    submit.innerHTML = `<i class="fas fa-floppy-disk"></i> ` + this.__getLang(4);
                    submit.className = 'btn btn-primary mt-4';

                    if (hasError) {
                        this.__alert(1);
                        return;
                    }

                    this.__alert(5, 'success');

                    $.ajax({
                        type: 'POST',
                        url: this.__getLang(6),
                        data: {action: 'fense_bpvt_save_settings'},
                    }).always(() => {
                        window.location.reload();
                    });
                };

                xhr.onerror = () => {
                    hasError = true;
                    completed++;
                    if (completed === total) {
                        submit.innerHTML = `<i class="fas fa-floppy-disk"></i> ` + this.__getLang(4);
                        submit.className = 'btn btn-primary mt-4';
                        this.__alert(1);
                    }
                };

                xhr.send(data);
            }

            return false;
        }

        __getLang(id) {
            return document.getElementById("fense-bpvt-settings-page").dataset['s' + id] ?? null;
        }

        __alert(id, type = 'danger', input = null) {
            document.getElementById("alert").innerHTML = `<div class="alert alert-${type} alert-border-left alert-dismissible fade show mb-xl-0 mt-4" role="alert">
                            <i class="ri-error-warning-line me-3 align-middle fs-16"></i>
                            ${this.__getLang(id)}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>`;

            setTimeout(() => {
                if (input) input.reportValidity();
            }, 500);

            setTimeout(() => {
                document.getElementById("alert").innerHTML = '';
            }, 3000);
        }

        __checkIpSection() {

            let invalid = false;
            document.getElementById("form5").querySelectorAll('[id^="ip-range-container"] input[type="text"]').forEach(input => {
                if (!this.__isValidIP(input.value)) {

                    window.location.hash = 'ips';

                    const hash = window.location.hash;
                    if (hash) {
                        const trigger = document.querySelector(`.nav-link[href="${hash}"]`);
                        if (trigger) new bootstrap.Tab(trigger).show();
                    }

                    this.__alert(1, 'danger', input);

                    invalid = true;
                }
            });
            return !invalid;
        }

        __isValidIP(ip) {
            const parts = ip.trim().split('.');
            if (parts.length !== 4) return false;
            return parts.every(n => {
                const num = Number(n);
                return String(num) === n && num >= 0 && num <= 255;
            });
        }

        loadEvents() {
            this.__EV_select_enable_on_custom()
            this.__EV_select_protection_mode()
            this.__EV_crawlers_bots()
            this.__EV_ip_whitelisting_enable()
            this.__EV_ip_blacklisting_enable()
            this.__EV_windowHash_Navigate()
        }

        __EV_select_enable_on_custom() {

            const that = this;

            $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_enable_on_custom]', function () {
                const se = $('select[name=FENSE_BPVT_DEVOZON_enable_on_custom]').val();

                if (se === 'all') {
                    that.__find(1, 3)
                    that.__find(1, 4)
                    that.__find(1, 5)
                    that.__find(1, 6)

                } else {
                    that.__find(1, 3, false)
                    that.__find(1, 4, false)
                    that.__find(1, 5, false)
                    that.__find(1, 6, false)
                }
            });
        }

        __EV_select_protection_mode() {

            const that = this;

            $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_protection_mode]', function () {

                const st = $('select[name=FENSE_BPVT_DEVOZON_protection_mode]').val();

                that.__find(2, 1, false)
                that.__find(2, 2, false)
                that.__find(2, 3, false)

                switch (st) {
                    case 'message':
                        that.__find(2, 2)
                        that.__find(2, 3)
                        break;
                    case 'redirect':
                        that.__find(2, 1)
                        that.__find(2, 3)
                        break;
                    case 'show_content':
                        that.__find(2, 1)
                        that.__find(2, 2)
                        break;
                    default:
                    // code block
                }

            });
        }

        __EV_crawlers_bots() {

            const that = this;

            $(document).on('change', 'select[name=FENSE_BPVT_DEVOZON_crawlers_bots]', function () {

                const st = $('select[name=FENSE_BPVT_DEVOZON_crawlers_bots]').val();

                switch (st) {
                    case 'yes':
                        that.__find(2, 11, false)
                        break;
                    case 'no':
                        that.__find(2, 11)
                        break;
                    default:
                    // code block
                }

            });
        }

        __EV_ip_whitelisting_enable() {

            const that = this;

            $(document).on('change', 'input[name=FENSE_BPVT_DEVOZON_ip_whitelisting_enable]', function () {
                switch ($(this).prop('checked')) {
                    case false:
                        that.__find(5, 1)
                        that.__find(5, 2)
                        break;
                    case true:
                        that.__find(5, 1, false)
                        that.__find(5, 2, false)
                        break;
                }
            });
        }

        __EV_ip_blacklisting_enable() {

            const that = this;

            $(document).on('change', 'input[name=FENSE_BPVT_DEVOZON_ip_blacklisting_enable]', function () {
                switch ($(this).prop('checked')) {
                    case false:
                        that.__find(5, 4)
                        that.__find(5, 5)
                        break;
                    case true:
                        that.__find(5, 4, false)
                        that.__find(5, 5, false)
                        break;
                }
            });
        }

        __EV_windowHash_Navigate() {
            // on page load, activate from URL
            const hash = window.location.hash;
            if (hash) {
                const trigger = document.querySelector(`.nav-link[href="${hash}"]`);
                if (trigger) new bootstrap.Tab(trigger).show();
            }

            // when a tab is shown, update the URL
            document.querySelectorAll('a[data-bs-toggle="pill"]').forEach(tab => {
                tab.addEventListener('shown.bs.tab', e => {
                    history.replaceState(null, null, e.target.getAttribute('href'));
                });
            });
        }
    }

    $(function () {
        const loader = new FensePageOptions();

        loader.onLoad();

        $('#submit').on('click', function (e) {
            // handler code
            loader.saveSettings()
        });
    });

})(jQuery);
