(function($) {
    'use strict';

    var zacls = {
        charts: {},

        init: function() {
            this.bindEvents();
            this.loadAnalytics();
            this.setupWizard();
        },

        bindEvents: function() {
            $('#zacls-settings-form').on('submit', this.saveSettings);
            $('.zacls-clear-logs').on('click', this.clearLogs);
            $(document).on('click', '.zacls-unblock-ip', this.unblockIP);
            $(document).on('click', '.zacls-block-ip-btn', this.blockIPFromLog);
            $('#zacls-block-ip-form').on('submit', this.blockIP);
            $(document).on('click', '.zacls-whitelist-ip', this.whitelistIP);
            $('#zacls-whitelist-form').on('submit', this.whitelistAdd);
            $(document).on('click', '.zacls-remove-whitelist', this.whitelistRemove);
            $('#zacls-whitelist-current').on('click', this.whitelistCurrent);
            $('#zacls-fetch-cloudflare-ips').on('click', this.fetchCloudflare);
            $(document).on('click', '.zacls-clear-audit-logs', this.clearAuditLogs);
            $(document).on('click', '.zacls-activate-lockdown', this.activateLockdown);
            $(document).on('click', '.zacls-deactivate-lockdown', this.deactivateLockdown);
            $(document).on('click', '.zacls-terminate-session', this.terminateSession);
            $(document).on('click', '.zacls-run-file-scan', this.runFileScan);
            $(document).on('click', '.zacls-run-vuln-scan', this.runVulnScan);
            $(document).on('click', '.zacls-dismiss-notif', this.dismissNotification);
            $(document).on('click', '.zacls-apply-recommended', this.applyRecommended);
            $(document).on('click', '.zacls-wizard-next', this.wizardNext);
            $(document).on('click', '.zacls-wizard-prev', this.wizardPrev);
            $(document).on('change', '.zacls-wizard-toggle', this.wizardToggle);
            $(document).on('click', '.zacls-refresh-analytics', this.loadAnalytics);
            $('.zacls-analytics-period .button').on('click', this.switchPeriod);
        },

        saveSettings: function(e) {
            e.preventDefault();
            var $form = $(this), $btn = $form.find('.zacls-save-settings');
            var data = $form.serializeArray(), settings = {};

            $.each(data, function(i, field) {
                var name = field.name.replace(/^settings\[/, '').replace(/\]\[/g, '|').replace(/\]$/, '');
                var parts = name.split('|');
                if (parts.length === 1) { settings[parts[0]] = field.value; }
                else if (parts.length === 2) {
                    if (!settings[parts[0]]) settings[parts[0]] = {};
                    settings[parts[0]][parts[1]] = field.value;
                }
                else if (parts.length === 3) {
                    if (!settings[parts[0]]) settings[parts[0]] = {};
                    if (!settings[parts[0]][parts[1]]) settings[parts[0]][parts[1]] = {};
                    settings[parts[0]][parts[1]][parts[2]] = field.value;
                }
            });

            ['zacls_2fa_enabled','zacls_block_wp_login','zacls_device_tracking','zacls_cloudflare_enabled','zacls_tor_detection','zacls_geoip_enabled'].forEach(function(key) {
                var $cb = $('input[name="settings[' + key + ']"]');
                if ($cb.length && !$cb.prop('checked')) settings[key] = 'no';
            });

            ['require_upper','require_lower','require_number','require_special'].forEach(function(key) {
                var $cb = $('input[name="settings[zacls_password_policy][' + key + ']"]');
                if ($cb.length && !$cb.prop('checked')) {
                    if (!settings.zacls_password_policy) settings.zacls_password_policy = {};
                    settings.zacls_password_policy[key] = 'no';
                }
            });

            ['failed_login','new_ip_login','ip_blocked'].forEach(function(key) {
                var $cb = $('input[name="settings[zacls_email_notifications][' + key + ']"]');
                if ($cb.length && !$cb.prop('checked')) {
                    if (!settings.zacls_email_notifications) settings.zacls_email_notifications = {};
                    settings.zacls_email_notifications[key] = 'no';
                }
            });

            var forcedRoles = [];
            $('input[name="settings[zacls_2fa_forced_roles][]"]:checked').each(function() { forcedRoles.push($(this).val()); });
            settings.zacls_2fa_forced_roles = forcedRoles;

            $btn.prop('disabled', true).text(zaclsData.i18n.saved);
            $.post(zaclsData.ajaxUrl, { action: 'zacls_save_settings', nonce: zaclsData.nonce, settings: settings },
                function(response) {
                    if (response.success) {
                        $btn.text(zaclsData.i18n.saved);
                        setTimeout(function() { $btn.prop('disabled', false).text('Save Settings'); }, 2000);
                    } else {
                        alert(response.data.message || zaclsData.i18n.error);
                        $btn.prop('disabled', false).text('Save Settings');
                    }
                }, 'json').fail(function() { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Save Settings'); });
        },

        clearLogs: function() {
            if (!confirm(zaclsData.i18n.confirmClear)) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_clear_logs', nonce: zaclsData.nonce },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        unblockIP: function() {
            if (!confirm(zaclsData.i18n.confirmUnblock)) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_unblock_ip', nonce: zaclsData.nonce, ip: $(this).data('ip') },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        blockIPFromLog: function() {
            if (!confirm(zaclsData.i18n.confirmBlock)) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_block_ip', nonce: zaclsData.nonce, ip: $(this).data('ip') },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        blockIP: function(e) {
            e.preventDefault();
            var ip = $('#zacls-new-block-ip').val().trim(), reason = $('#zacls-block-reason').val().trim();
            if (!ip) { alert('Please enter an IP address.'); return; }
            $.post(zaclsData.ajaxUrl, { action: 'zacls_block_ip', nonce: zaclsData.nonce, ip: ip, reason: reason },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        whitelistIP: function() {
            $.post(zaclsData.ajaxUrl, { action: 'zacls_whitelist_ip', nonce: zaclsData.nonce, ip: $(this).data('ip'), reason: 'Whitelisted from IP list' },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        whitelistAdd: function(e) {
            e.preventDefault();
            var ip = $('#zacls-whitelist-ip').val().trim(), reason = $('#zacls-whitelist-reason').val().trim();
            if (!ip) { alert('Please enter an IP address.'); return; }
            $.post(zaclsData.ajaxUrl, { action: 'zacls_whitelist_ip', nonce: zaclsData.nonce, ip: ip, reason: reason },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        whitelistRemove: function() {
            var ip = $(this).data('ip');
            if (!confirm('Remove ' + ip + ' from whitelist?')) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_unblock_ip', nonce: zaclsData.nonce, ip: ip },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        whitelistCurrent: function() {
            $('#zacls-whitelist-ip').val($(this).data('current-ip') || '');
            $('#zacls-whitelist-reason').val('My IP address');
            $('#zacls-whitelist-form').submit();
        },

        clearAuditLogs: function() {
            if (!confirm('Are you sure you want to clear all audit logs?')) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_clear_audit_logs', nonce: zaclsData.nonce },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        fetchCloudflare: function() {
            var $btn = $(this).prop('disabled', true).text('Fetching...');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_fetch_cloudflare_ips', nonce: zaclsData.nonce },
                function(r) {
                    if (r.success) { alert(r.data.message); location.reload(); }
                    else { alert(r.data.message || zaclsData.i18n.error); $btn.prop('disabled', false).text('Fetch Cloudflare IP Ranges'); }
                }, 'json').fail(function() { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Fetch Cloudflare IP Ranges'); });
        },

        activateLockdown: function() {
            if (!confirm(zaclsData.i18n.confirmLockdown)) return;
            var reason = $('#zacls-lockdown-reason').val() || '';
            var ips = [];
            $('.zacls-lockdown-whitelist-ip:checked').each(function() { ips.push($(this).val()); });
            $.post(zaclsData.ajaxUrl, { action: 'zacls_activate_lockdown', nonce: zaclsData.nonce, reason: reason, whitelist_ips: ips },
                function(r) { if (r.success) { alert(r.data.message); location.reload(); } else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        deactivateLockdown: function() {
            $.post(zaclsData.ajaxUrl, { action: 'zacls_deactivate_lockdown', nonce: zaclsData.nonce },
                function(r) { if (r.success) { alert(r.data.message); location.reload(); } else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        terminateSession: function() {
            if (!confirm(zaclsData.i18n.confirmTerminate)) return;
            $.post(zaclsData.ajaxUrl, { action: 'zacls_terminate_session', nonce: zaclsData.nonce, session_id: $(this).data('session') },
                function(r) { if (r.success) location.reload(); else alert(r.data.message || zaclsData.i18n.error); }, 'json');
        },

        runFileScan: function() {
            var $btn = $(this).prop('disabled', true).text('Scanning...');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_run_file_scan', nonce: zaclsData.nonce },
                function(r) {
                    if (r.success) { location.reload(); }
                    else { alert(r.data.message || zaclsData.i18n.error); $btn.prop('disabled', false).text('Run File Scan'); }
                }, 'json').fail(function() { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Run File Scan'); });
        },

        runVulnScan: function() {
            var $btn = $(this).prop('disabled', true).text('Scanning...');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_run_vuln_scan', nonce: zaclsData.nonce },
                function(r) {
                    if (r.success) { location.reload(); }
                    else { alert(r.data.message || zaclsData.i18n.error); $btn.prop('disabled', false).text('Scan Plugins'); }
                }, 'json').fail(function() { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Scan Plugins'); });
        },

        dismissNotification: function() {
            var $item = $(this).closest('.zacls-notif-item');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_dismiss_notification', nonce: zaclsData.nonce, id: $(this).data('id') },
                function(r) { if (r.success) $item.fadeOut(300, function() { $(this).remove(); }); }, 'json');
        },

        applyRecommended: function() {
            var $btn = $(this).prop('disabled', true).text('Applying...');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_apply_recommended', nonce: zaclsData.nonce },
                function(r) {
                    if (r.success) { alert(r.data.message); location.reload(); }
                    else { alert(r.data.message || zaclsData.i18n.error); $btn.prop('disabled', false).text('Apply All Recommendations'); }
                }, 'json').fail(function() { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Apply All Recommendations'); });
        },

        loadAnalytics: function(period) {
            if ($('.zacls-analytics-section').length === 0 && $('.zacls-stats-grid').length === 0) return;
            var days = period || 14;
            if ($('.zacls-analytics-period .button.active').length) {
                days = parseInt($('.zacls-analytics-period .button.active').data('days')) || 14;
            }
            $('.zacls-loading-analytics').removeClass('hidden');
            $.post(zaclsData.ajaxUrl, { action: 'zacls_get_analytics', nonce: zaclsData.nonce, days: days },
                function(r) {
                    $('.zacls-loading-analytics').addClass('hidden');
                    if (r.success && r.data) {
                        zacls.renderCharts(r.data);
                    }
                }, 'json');
        },

        switchPeriod: function() {
            $('.zacls-analytics-period .button').removeClass('active');
            $(this).addClass('active');
            zacls.loadAnalytics();
        },

        renderCharts: function(data) {
            if (!data.activity || !data.activity.length) return;
            var $container = $('#zacls-activity-chart');
            if (!$container.length) return;
            $container.empty();

            var maxVal = 1;
            data.activity.forEach(function(d) { maxVal = Math.max(maxVal, parseInt(d.total) || 0); });
            if (maxVal < 1) maxVal = 1;

            data.activity.forEach(function(d) {
                var total = parseInt(d.total) || 0;
                var failed = parseInt(d.failed) || 0;
                var success = total - failed;
                var heightPct = Math.max((total / maxVal) * 100, 2);
                var isToday = d.label && d.label.indexOf('Today') >= 0;

                var $wrapper = $('<div class="zacls-chart-bar-wrapper' + (isToday ? ' chart-today' : '') + '">').appendTo($container);
                var $tooltip = $('<div class="zacls-chart-tooltip">' + (d.label || '') + ' - Failed: ' + failed + ', Success: ' + success + '</div>').appendTo($wrapper);
                var $bar = $('<div class="zacls-chart-bar" style="height:' + heightPct + '%">').appendTo($wrapper);

                if (total > 0) {
                    var failedPct = (failed / total) * 100;
                    var successPct = 100 - failedPct;
                    $bar.css('background', 'linear-gradient(180deg, #00ba37 0%, #00a32a ' + successPct + '%, #e65054 ' + successPct + '%, #d63638 100%)');
                } else {
                    $bar.css('background', 'linear-gradient(180deg, #e5f5fa, #c3c4c7)');
                }

                $('<div class="chart-label">' + (d.short_label || d.label || '') + '</div>').appendTo($wrapper);
            });
        },

        setupWizard: function() {
            if ($('.zacls-wizard-step').length === 0) return;
            var $steps = $('.zacls-wizard-step');
            var $indicators = $('.wizard-step-indicator');
            var current = 0;

            $steps.hide().first().show();
            $indicators.first().addClass('active');

            this.wizardGoTo = function(index) {
                $steps.hide().eq(index).show();
                $indicators.removeClass('active').addClass('completed').filter(function(i) {
                    return i <= index;
                }).removeClass('completed');
                $indicators.eq(index).addClass('active');
                current = index;
                $('.zacls-wizard-prev').toggle(index > 0);
                $('.zacls-wizard-next').toggle(index < $steps.length - 1);
                $('.zacls-wizard-finish').toggle(index === $steps.length - 1).hide();
                if (index === $steps.length - 1) $('.zacls-wizard-finish').show();
            };

            this.wizardNext = function() {
                if (current < $steps.length - 1) zacls.wizardGoTo(current + 1);
            };

            this.wizardPrev = function() {
                if (current > 0) zacls.wizardGoTo(current - 1);
            };

            this.wizardToggle = function() {
                var $cb = $(this);
                $cb.closest('.zacls-wizard-step').find('.zacls-wizard-save-btn').show();
            };

            $('.zacls-wizard-step .zacls-wizard-save-btn').on('click', function() {
                var $btn = $(this);
                var step = $btn.data('step');
                var enabled = $btn.closest('.zacls-wizard-step').find('.zacls-wizard-toggle').is(':checked');
                $btn.prop('disabled', true).text('Saved');
                $.post(zaclsData.ajaxUrl, { action: 'zacls_save_wizard_step', nonce: zaclsData.nonce, step: step, enabled: enabled },
                    function(r) {
                        if (!r.success) { alert(zaclsData.i18n.error); $btn.prop('disabled', false).text('Save'); }
                    }, 'json');
            });
        }
    };

    $(document).ready(function() { zacls.init(); });

})(jQuery);
