document.addEventListener("DOMContentLoaded", function () {
    (function ($) {
        'use strict';

        function fetch_oath2_admin_ajax_handle(data, is_formular = true, callback) {
            let formData = new FormData();
            if (is_formular) {
                let input = new FormData(data);
                for (let [name, value] of input) {
                    formData.append(name, value);
                }
            } else {
                for (let [name, value] of Object.entries(data)) {
                    formData.append(name, value);
                }
            }
            formData.append('_ajax_nonce', oauth2Client.nonce);
            formData.append('action', 'Oauth2Client');

            fetch(oauth2Client.ajax_url, {
                method: 'POST',
                body: formData
            }).then((response) => response.json())
                .then((result) => {
                    if (typeof callback === 'function') {
                        document.addEventListener("load", callback(result));
                    }
                })
                .catch((error) => {
                    console.error('Error:', error);
                });
        }

        $(document).on('dblclick', '.dblclick', function () {
            $(this).removeAttr('readonly')
        });

        let oAuth2ClientSendFormTimeout;
        $(document).on('input propertychange change', '.instagram-autosafe-form', function () {
            let formData = $(this).closest("form").get(0);
            let target = $(this).attr('data-target');
            let spin = $(target);
            spin.html('');
            spin.addClass('wait');
            clearTimeout(oAuth2ClientSendFormTimeout);
            oAuth2ClientSendFormTimeout = setTimeout(function () {
                fetch_oath2_admin_ajax_handle(formData, true, oath2_client_formular_autosave_callback);
            }, 1000);
        });

        function oath2_client_formular_autosave_callback(data) {
            switch (data.type) {
                case'oauth_settings_handle':
                    let srvUrlShow = $('#authInfo');
                    $('#authorizeUrl').html(data.auth_url);
                    $('#tokenUrl').html(data.token_url);
                    if (data.srv_url) {
                        srvUrlShow.removeClass('d-none');
                    } else {
                        srvUrlShow.addClass('d-none');
                    }
                    show_ajax_spinner(data, '.plugin-settings');
                    break;
                case'oauth_plugin_settings':
                    show_ajax_spinner(data, '.plugin-settings');
                    break;
            }
        }

        $(document).on('submit', '.form-submit-action', function (event) {
            let button = event.originalEvent.submitter;
            let formData = $(this).closest("form").get(0);
            if (formData.checkValidity()) {
                if (button.hasAttribute('data-spin')) {
                    document.querySelector(button.getAttribute('data-spin')).classList.remove('box-hidden')
                }
                event.preventDefault()
                event.stopPropagation()
                fetch_oath2_admin_ajax_handle(formData, true, btn_submit_form_callback)
            }
            event.preventDefault();
        })

        function btn_submit_form_callback(data) {
            let submitForm = $('.form-submit-action');
            switch (data.type) {
                case 'free_product_download':
                    $(data.target).addClass('box-hidden');
                    if (data.status) {
                        let btn = $('.btn-activate-' + data.handle);
                        submitForm.trigger('reset');
                        $('.product-select-' + data.handle + ' option[value="' + data.id + '"]').remove();
                        btn.removeClass('d-none');
                        btn.attr('data-slug', data.slug);
                        swal_alert_response(data)
                        $('.btn-submit').prop('disabled', true);
                    } else {
                        warning_message(data.msg)
                    }

                    break;
            }
        }

        $(document).on('change', '.product-select', function () {
            let parentForm = $(this).parents('form');
            let btn = $('.btn-submit ', parentForm)
            $('.btn-activate').addClass('d-none');
            if ($(this).val()) {
                btn.prop('disabled', false);
            } else {
                btn.prop('disabled', true);
            }
        })

        //
        $(document).on('click', '.btn-action', function () {

            let target;
            $(this).attr('data-target') ? target = $(this).attr('data-target') : target = '';
            let type = $(this).attr('data-type');
            let formData;
            switch (type) {
                case 'plugin_settings':
                    menu_bs_toggle(target, $(this))
                    break;
                case 'oauth_settings':
                    menu_bs_toggle(target, $(this))
                    break;
                case'checkScope':
                    if ($(this).prev().prop('checked')) {
                        $(this).removeClass('active')
                    } else {
                        $(this).addClass('active')
                    }
                    break;
                case 'api_client_reset':
                    formData = {
                        'method': type
                    }
                    swal_validate_pin(formData).then((result) => {
                        if (result) {
                        }
                    });
                    return false;

                case 'api_update_scope':
                    $('.scope-update').addClass('wait')
                    formData = {
                        'method': type
                    }
                    break;
                case 'get_api_basic':
                    menu_bs_toggle(target, $(this), '.btn-scope')
                    break;
                case 'get_api_media':
                case 'get_api_product':
                    formData = {
                        'method': type,
                        'handle': $(this).attr('data-handle') || '',
                        'target': $(this).attr('data-target') || 0,
                        'toggle': $(this).attr('data-toggle') || 1,
                        'page': $(this).attr('data-page') || 1,
                    }
                    break;
                case 'product_activate':
                    formData = {
                        'method': type,
                        'handle': $(this).attr('data-handle'),
                        'slug': $(this).attr('data-slug')
                    }
                    break;
                case 'download_lizenz_product':
                    formData = {
                        'method': type,
                        'lizenz': $(this).attr('data-lizenz')
                    }
                    break;
                case'activate_lizenz_product':
                    formData = {
                        'method': type,
                        'slug': $(this).attr('data-slug'),
                        'handle': $(this).attr('data-handle'),
                        'lizenz': $(this).attr('data-lizenz'),
                        'is_file': $(this).attr('data-is-file')
                    }
                    break;
                case'add_spin':
                    $('i ', $(this)).addClass('spin');
                    break;
                case'toggle-news':
                      if($(this).hasClass('active')){
                          $(this).removeClass('active')
                      } else {
                          $(this).addClass('active')
                      }
                    break;


            }
            if (formData) {
                fetch_oath2_admin_ajax_handle(formData, false, btn_action_callback)
            }
        });


        function btn_action_callback(data) {
            switch (data.type) {
                case 'api_client_logout':
                case 'api_update_scope':
                    $('.scope-update').removeClass('wait')
                    if (data.status) {
                        window.location.href = data.redirect;
                    } else {
                        swal_alert_response(data)
                    }
                    break;

                case 'get_api_media':
                    if (data.status) {
                        $('#media_api_callback').html(data.template)
                        if (data.toggle) {
                            menu_bs_toggle(data.target, $('.get_api_' + data.handle), '.btn-scope');
                        }
                    } else {
                        warning_message(data.msg)
                    }
                    break;
                case 'get_api_product':
                    if (data.status) {
                        $('#colOauthCallbackProduct').html(data.template)
                        menu_bs_toggle(data.target, $('.get_api_' + data.handle), '.btn-scope');
                    } else {
                        warning_message(data.msg)
                    }

                    break;
                case 'product_activate':
                    if (data.status) {
                        swal_alert_response(data)
                        $('.btn-activate').addClass('d-none');
                    } else {
                        warning_message(data.msg)
                    }
                    break;
                case 'activate_lizenz_product':
                    if (data.status) {
                       window.location.reload();
                    } else {
                        warning_message(data.msg)
                    }
                    break;

            }
        }


        function menu_bs_toggle(target, self, btn = '') {
            let btnToggle;
            if (btn) {
                btnToggle = $(btn);

            } else {
                btnToggle = $('.btn-toggle');
            }

            btnToggle.prop('disabled', false);
            self.prop('disabled', true);
            new bootstrap.Collapse(target, {
                toggle: true,
                parent: '#collParent'
            })
        }

        let appShowCopiedTimeout;
        $(document).on('click', '.copy-action', function (e) {
            let target = $(this).attr('data-target');
            $('.copied').removeClass('show-copied')
            let next = $(this).next();
            let copyText = document.querySelector(target);
            let el = document.createElement('textarea');
            el.value = copyText.value;
            el.setAttribute('readonly', '');
            el.style = {position: 'absolute', left: '-100vw'};
            document.body.appendChild(el);
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);
            clearTimeout(appShowCopiedTimeout);
            next.addClass('show-copied')
            appShowCopiedTimeout = setTimeout(function () {
                next.removeClass('show-copied')
            }, 2500)
            e.preventDefault();
        });

        function success_message(msg) {
            let x = document.getElementById("snackbar-success");
            x.innerHTML = msg;
            x.className = "show";
            setTimeout(function () {
                x.className = x.className.replace("show", "");
            }, 3000);
        }

        function warning_message(msg) {
            let x = document.getElementById("snackbar-warning");
            x.innerHTML = msg;
            x.className = "show";
            setTimeout(function () {
                x.className = x.className.replace("show", "");
            }, 3000);
        }

        function show_ajax_spinner(data, target = '') {
            let msg = '';
            if (data.status) {
                msg = '<i class="text-success fw-bold bi bi-check2-circle"></i>&nbsp; Saved! Last: ' + data.msg;
            } else {
                msg = '<i class="text-danger bi bi-exclamation-triangle"></i>&nbsp; ' + data.msg;
            }
            let spinner = document.querySelector(target + '.ajax-status-spinner');
            spinner.classList.remove('wait');
            spinner.innerHTML = msg;
        }

        function swal_alert_response(data) {
            if (data.status) {
                Swal.fire({
                    position: 'top-end',
                    title: data.title,
                    text: data.msg,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false,
                    showClass: {
                        popup: 'animate__animated animate__fadeInDown'
                    },
                    customClass: {
                        popup: 'bg-light'
                    },
                    hideClass: {
                        popup: 'animate__animated animate__fadeOutUp'
                    }
                }).then();
            } else {
                Swal.fire({
                    position: 'center',
                    title: data.title,
                    text: data.msg,
                    icon: 'error',
                    timer: 3000,
                    showConfirmButton: false,
                    showClass: {
                        popup: 'animate__animated animate__fadeInDown'
                    },
                    customClass: {
                        popup: 'swal-error-container'
                    },
                    hideClass: {
                        popup: 'animate__animated animate__fadeOutUp'
                    }
                }).then();
            }
        }

        let clockBase = $('#basicStartClock');
        if (clockBase) {
            let start = new Date();
            start.setDate(start.getDate());
            start.setHours(0, 0, 0, 0)
            let now = new Date();
            let diff = (now.getTime() - start.getTime()) / 1000;
            let clock = clockBase.FlipClock(diff, {
                clockFace: 'HourlyCounter',
                countdown: false,
                showSeconds: true,
                language: 'de-de',
            });

        }


        async function swal_validate_pin(form, formular = false) {

            const {value: pin} = await Swal.fire({
                title: 'Passwort zum Ausführen',
                html: '',
                input: 'text',
                inputPlaceholder: 'Passwort zur Ausführung eingeben',
                reverseButtons: true,
                inputLabel: 'Geben Sie das Passwort für die Ausführung ein.',
                validationMessage: 'Das eingegebene Passwort ist falsch!',
                confirmButtonText: 'Ausführen',
                showCancelButton: true,
                cancelButtonText: 'Abbrechen',
                showClass: {
                    popup: 'animate__animated animate__fadeInDown'
                },
                customClass: {
                    popup: 'swal-delete-container no-trash'
                },

                inputValidator: (value) => {
                    return new Promise((resolve) => {
                        if (formular) {
                            $('#securityPin ', form).val(value)
                        } else {
                            form['pin'] = value;
                        }
                        fetch_oath2_admin_ajax_handle(form, formular, btn_execute_callback)

                        function btn_execute_callback(data) {
                            if (data.status) {
                                resolve()
                                success_message(data.msg);
                                switch (data.type) {
                                    case 'api_client_reset':
                                        resolve()
                                        success_message(data.msg);
                                        window.location.href = data.redirect;
                                        break;
                                }
                            } else {
                                if (data.msg) {
                                    warning_message(data.msg);
                                }
                                resolve('Das eingegebene Passwort ist falsch!')
                            }
                        }
                    });
                }
            });
            return true;
        }

    })(jQuery);
});
