(function($) {
    'use strict';

    var i18n = (window.voladeSDK && voladeSDK.i18n) || {};

    function msg(key, fallback) {
        return i18n[key] || fallback;
    }

    function getSdk() {
        return window.voladeSDK || null;
    }

    function getRedirects() {
        var sdk = getSdk();
        return (sdk && sdk.redirects) || {};
    }

    function parseJsonPayload(raw) {
        if (raw === null || raw === undefined || raw === '') {
            return null;
        }
        if (typeof raw === 'number') {
            if (raw === 0 || raw === -1) {
                return { __wp_die: String(raw) };
            }
            return null;
        }
        if (typeof raw === 'object') {
            return raw;
        }
        if (typeof raw !== 'string') {
            return null;
        }

        var trimmed = raw.trim();
        if (trimmed === '0' || trimmed === '-1') {
            return { __wp_die: trimmed };
        }

        try {
            return JSON.parse(trimmed);
        } catch (e1) {
            var match = trimmed.match(/\{[\s\S]*\}$/);
            if (!match) {
                return null;
            }
            try {
                return JSON.parse(match[0]);
            } catch (e2) {
                return null;
            }
        }
    }

    function isAjaxSuccess(value) {
        return value === true || value === 1 || value === '1';
    }

    function parseAjaxResponse(res, xhr) {
        var payload = parseJsonPayload(res);

        if (payload && payload.__wp_die !== undefined) {
            return { ok: false, message: msg('error_session', 'Session expired. Reload the page.') };
        }

        if (!payload || typeof payload !== 'object') {
            var statusMsg = '';
            if (xhr && xhr.status) {
                if (xhr.status === 403) {
                    statusMsg = msg('error_session', 'Session expired. Reload the page.');
                } else if (xhr.status >= 500) {
                    statusMsg = msg('error_server', 'Server error. Reactivate the plugin or check PHP logs.');
                }
            }
            return { ok: false, message: statusMsg || msg('error_generic', 'An error occurred.') };
        }

        if (isAjaxSuccess(payload.success)) {
            var data = payload.data || {};
            return $.extend({
                ok: true,
                message: data.message || '',
                redirect: data.redirect || ''
            }, data);
        }

        var err = payload.data;
        if (typeof err === 'object' && err && err.message) {
            err = err.message;
        }
        return { ok: false, message: err || msg('error_generic', 'An error occurred.') };
    }

    function voladeAjax(data) {
        var sdk = getSdk();
        if (!sdk || !sdk.ajax_url) {
            return $.Deferred().reject({
                responseText: '',
                status: 0,
                voladeClientError: msg('error_generic', 'Interface not loaded. Reload the page (Ctrl+F5).')
            }).promise();
        }

        return $.ajax({
            url: sdk.ajax_url,
            method: 'POST',
            data: $.extend({ nonce: sdk.nonce }, data || {}),
            dataType: 'text'
        }).then(function(text, status, xhr) {
            var parsed = parseAjaxResponse(text, xhr);
            if (parsed.ok) {
                return parsed;
            }
            return $.Deferred().reject({
                responseText: text,
                status: xhr.status,
                voladeParsed: parsed
            }).promise();
        });
    }

    function setFormMessage($msg, text, type) {
        $msg.removeClass('success error').addClass(type || '');
        $msg.text(text || '');
    }

    function setFormLoading($form, loading) {
        var $btn = $form.find('button[type="submit"]');
        if (loading) {
            $btn.prop('disabled', true).data('volade-label', $btn.text()).text(msg('loading', 'Chargement…'));
        } else {
            $btn.prop('disabled', false);
            if ($btn.data('volade-label')) {
                $btn.text($btn.data('volade-label'));
            }
        }
    }

    function afterAuthSuccess($msg, fallbackMessage, redirect) {
        setFormMessage($msg, fallbackMessage, 'success');
        window.setTimeout(function() {
            window.location.href = redirect || getRedirects().after_login || window.location.href;
        }, 600);
    }

    function handleAuthFailure($msg, $form, xhr) {
        var message = (xhr && xhr.voladeClientError)
            || (xhr && xhr.voladeParsed && xhr.voladeParsed.message)
            || parseAjaxResponse((xhr && (xhr.responseJSON || xhr.responseText)) || '', xhr).message
            || msg('error_network', 'Network error. Try again.');
        setFormMessage($msg, message, 'error');
        if ($form) {
            setFormLoading($form, false);
        }
    }

    // Auth tabs
    $('.volade-tab').on('click', function() {
        var tab = $(this).data('tab');
        $('.volade-tab').removeClass('active');
        $(this).addClass('active');
        $('.volade-auth-form').removeClass('active');
        $('#volade-' + tab + '-form').addClass('active');
    });

    // Login
    $('#volade-login-form').on('submit', function(e) {
        e.preventDefault();
        var $form = $(this);
        var $msg = $form.find('.volade-msg');
        setFormMessage($msg, '');
        setFormLoading($form, true);

        voladeAjax({
            action: 'volade_login',
            login: $form.find('#volade-login').val(),
            password: $form.find('#volade-login-password').val()
        }).done(function(parsed) {
            afterAuthSuccess(
                $msg,
                parsed.message || msg('login_success', 'Signed in. Redirecting…'),
                parsed.redirect || getRedirects().after_login
            );
        }).fail(function(xhr) {
            handleAuthFailure($msg, $form, xhr);
        });
    });

    // Register
    $('#volade-register-form').on('submit', function(e) {
        e.preventDefault();
        var $form = $(this);
        var $msg = $form.find('.volade-msg');
        setFormMessage($msg, '');
        setFormLoading($form, true);

        voladeAjax({
            action: 'volade_register',
            pseudo: $form.find('#volade-pseudo').val(),
            email: $form.find('#volade-email').val(),
            password: $form.find('#volade-register-password').val()
        }).done(function(parsed) {
            afterAuthSuccess(
                $msg,
                parsed.message || msg('register_success', 'Account created. Redirecting…'),
                parsed.redirect || getRedirects().after_register
            );
        }).fail(function(xhr) {
            handleAuthFailure($msg, $form, xhr);
        });
    });

    // Logout
    $('#volade-logout-btn').on('click', function() {
        var $btn = $(this).prop('disabled', true);
        voladeAjax({ action: 'volade_logout' })
            .done(function(parsed) {
                window.location.href = parsed.redirect || getRedirects().auth || window.location.href;
            })
            .fail(function(xhr) {
                $btn.prop('disabled', false);
                alert(
                    (xhr && xhr.voladeParsed && xhr.voladeParsed.message)
                    || msg('error_network', 'Network error. Try again.')
                );
            });
    });

    // Onboarding wizard
    function voladeBindOnboarding() {
        var $onboarding = $('#volade-onboarding');
        if (!$onboarding.length || $onboarding.data('volade-bound')) {
            return;
        }
        $onboarding.data('volade-bound', true);

        var $steps = $onboarding.find('.volade-onboarding-step');
        var $dots = $onboarding.find('.volade-dot');
        var $msg = $onboarding.find('.volade-onboarding-msg');
        var $next = $('#volade-onboarding-next');
        var $finish = $('#volade-onboarding-finish');
        var $skip = $('#volade-onboarding-skip');
        var current = 0;
        var total = $steps.length;
        var ajaxUrl = (window.voladeSDK && voladeSDK.ajax_url) || $onboarding.data('ajax-url');
        var nonce = (window.voladeSDK && voladeSDK.nonce) || $onboarding.data('nonce');
        var discoverUrl = $onboarding.data('redirect') || (window.voladeSDK && voladeSDK.redirects && voladeSDK.redirects.discover) || '';

        function showOnboardingMessage(text, type) {
            $msg.removeClass('error success').addClass(type || '').text(text || '');
        }

        function setActionButtons(stepIdx) {
            var isLast = stepIdx >= total - 1;
            $next.toggleClass('volade-onboarding-hidden', isLast).prop('disabled', false);
            $finish.toggleClass('volade-onboarding-hidden', !isLast).prop('disabled', false);
        }

        function showStep(idx) {
            current = idx;
            $steps.removeClass('active').eq(idx).addClass('active');
            $dots.removeClass('active').eq(idx).addClass('active');
            setActionButtons(idx);
            showOnboardingMessage('');
        }

        function finishOnboarding(action) {
            if (!ajaxUrl || !nonce) {
                showOnboardingMessage(msg('error_generic', 'Interface not loaded. Reload the page (Ctrl+F5).'), 'error');
                return;
            }

            var $btn = action === 'skip' ? $skip : $finish;
            $skip.add($finish).add($next).prop('disabled', true);
            $btn.data('volade-label', $btn.text()).text(msg('processing', 'Processing…'));

            voladeAjax({
                action: action === 'skip' ? 'volade_skip_onboarding' : 'volade_complete_onboarding'
            })
                .done(function(parsed) {
                    $onboarding.fadeOut(200, function() { $(this).remove(); });
                    var redirect = parsed.redirect || discoverUrl;
                    if (redirect) {
                        window.location.href = redirect;
                    }
                })
                .fail(function(xhr) {
                    var message = (xhr && xhr.voladeClientError)
                        || (xhr && xhr.voladeParsed && xhr.voladeParsed.message)
                        || msg('error_network', 'Network error. Try again.');
                    showOnboardingMessage(message, 'error');
                    $skip.add($finish).add($next).prop('disabled', false);
                    if ($btn.data('volade-label')) {
                        $btn.text($btn.data('volade-label'));
                    }
                });
        }

        $onboarding.on('click', '#volade-onboarding-next', function() {
            if (current < total - 1) {
                showStep(current + 1);
            }
        });

        $onboarding.on('click', '#volade-onboarding-skip', function() {
            finishOnboarding('skip');
        });

        $onboarding.on('click', '#volade-onboarding-finish', function() {
            finishOnboarding('complete');
        });

        showStep(0);
    }

    window.voladeBindOnboarding = voladeBindOnboarding;
    $(voladeBindOnboarding);

    // Promouvoir — missions
    var $promote = $('.volade-promote-wrap');
    if ($promote.length) {
        var $toast = $('#volade-mission-toast');
        var toastTimer;
        var isGuestPromote = $promote.data('guestMode') === 1 || $promote.attr('data-guest-mode') === '1';

        $promote.on('click', '.volade-promote-tab', function() {
            var tab = $(this).data('tab');
            if (!tab || $(this).hasClass('is-active')) {
                return;
            }

            $promote.find('.volade-promote-tab').removeClass('is-active').attr({
                'aria-selected': 'false',
                tabindex: '-1'
            });
            $(this).addClass('is-active').attr({
                'aria-selected': 'true',
                tabindex: '0'
            });

            $promote.find('.volade-promote-tab-panel').removeClass('is-active').attr('hidden', true);
            $('#volade-promote-tab-' + tab).addClass('is-active').removeAttr('hidden');
        });

        function showToast(message, isError) {
            $toast.removeClass('is-error is-visible');
            if (isError) {
                $toast.addClass('is-error');
            }
            $toast.text(message).addClass('is-visible');
            window.clearTimeout(toastTimer);
            toastTimer = window.setTimeout(function() {
                $toast.removeClass('is-visible');
            }, 3200);
        }

        function updatePromoteUi(parsed) {
            if (parsed.streak !== undefined && parsed.streak !== '') {
                $('.volade-promote-streak').text(parsed.streak);
            }
            if (parsed.total_xp !== undefined && parsed.total_xp !== '') {
                $('.volade-promote-user-xp').text(parsed.total_xp);
            }
            if (parsed.completed_count !== undefined && parsed.total_missions !== undefined) {
                $('.volade-promote-completed-count').text(parsed.completed_count + '/' + parsed.total_missions);
                $promote.find('.volade-promote-tab[data-tab="missions"] .volade-promote-tab-badge')
                    .not('.volade-promote-tab-badge--streak')
                    .text(parsed.completed_count + '/' + parsed.total_missions);
            }
            if (parsed.streak !== undefined && parsed.streak !== '') {
                $promote.find('.volade-promote-tab-badge--streak').text('🔥 ' + parsed.streak);
            }
            var $today = $('.volade-calendar-day.is-today');
            if ($today.length) {
                $today.addClass('is-checked');
                if (!$today.find('.volade-calendar-check').length) {
                    $today.append('<span class="volade-calendar-check" aria-hidden="true">✓</span>');
                }
            }
            $('.volade-checkin-action').html(
                '<span class="volade-checkin-done">✅ ' + msg('checkin_done', 'Today checked in — come back tomorrow!') + '</span>'
            );
        }

        function renderMissionDone($card, statusLabel) {
            var label = statusLabel || msg('mission_validated', 'Done');
            $card.addClass('is-done');
            $card.find('.volade-mission-action').html(
                '<span class="volade-mission-status done">' +
                '<span class="volade-mission-check" aria-hidden="true">✓</span> ' +
                label +
                '</span>'
            );
        }

        function handleMissionSuccess(parsed, $card, $btn) {
            showToast(parsed.message || msg('mission_done', 'Mission complete!'));
            updatePromoteUi(parsed);
            if ($card && $card.length) {
                renderMissionDone($card, parsed.status_label);
            }
            if ($btn && $btn.length) {
                $btn.prop('disabled', true);
            }
        }

        function handleMissionError(xhr) {
            var message = (xhr && xhr.voladeClientError)
                || (xhr && xhr.voladeParsed && xhr.voladeParsed.message)
                || msg('error_network', 'Network error. Try again.');
            if (isGuestPromote && message.indexOf('authent') !== -1) {
                message = msg('guest_auth_required', 'Connectez-vous pour valider vos missions et cumuler l\'XP.');
            }
            showToast(message, true);
        }

        function completeMission(missionKey, $card) {
            return voladeAjax({
                action: 'volade_complete_mission',
                mission_key: missionKey
            }).done(function(parsed) {
                handleMissionSuccess(parsed, $card);
            }).fail(handleMissionError);
        }

        $('.volade-daily-checkin-btn').on('click', function() {
            var $btn = $(this).prop('disabled', true).text(msg('processing', 'Chargement…'));
            voladeAjax({ action: 'volade_daily_checkin' })
                .done(function(parsed) {
                    handleMissionSuccess(parsed, null, $btn);
                })
                .fail(function(xhr) {
                    handleMissionError(xhr);
                    $btn.prop('disabled', false).text(msg('checkin_cta', 'Valider aujourd\'hui (+10 XP)'));
                });
        });

        $('.volade-mission-copy-btn').on('click', function() {
            var $btn = $(this);
            var link = $btn.data('link');
            var $card = $btn.closest('.volade-mission-card');
            if (!link) {
                return;
            }
            navigator.clipboard.writeText(link).then(function() {
                $btn.text(msg('copied', 'Copied!'));
                completeMission($card.data('mission'), $card);
            });
        });

        $('.volade-mission-start-btn').on('click', function() {
            var $card = $(this).closest('.volade-mission-card');
            var url = $card.data('url');
            var timer = parseInt($card.data('timer'), 10) || 8;
            var $action = $card.find('.volade-mission-action');

            if (url) {
                window.open(url, '_blank', 'noopener,noreferrer');
            }

            if (isGuestPromote) {
                showToast(msg('guest_xp_hint', 'Connectez-vous pour cumuler l\'XP de cette mission.'));
                return;
            }

            $action.empty();
            var $wait = $('<div class="volade-mission-wait" role="status" aria-live="polite"></div>');
            var $bar = $('<div class="volade-mission-wait-bar" aria-hidden="true"><span></span></div>');
            $action.append($wait).append($bar);

            var elapsed = 0;
            function updateWaitUi() {
                $wait.text(
                    msg('mission_wait_progress', 'Patientez…') + ' ' + elapsed + '/' + timer
                );
                $bar.find('span').css('width', Math.round((elapsed / timer) * 100) + '%');
            }

            updateWaitUi();

            var intervalId = window.setInterval(function() {
                elapsed++;
                if (elapsed >= timer) {
                    window.clearInterval(intervalId);
                    $action.empty().append(
                        $('<button type="button" class="volade-btn volade-btn-sm volade-btn-primary volade-mission-claim-btn"></button>')
                            .text(msg('mission_claim', 'Valider'))
                    );
                    return;
                }
                updateWaitUi();
            }, 1000);
        });

        $promote.on('click', '.volade-mission-claim-btn', function() {
            if ($(this).prop('disabled')) {
                return;
            }
            var $card = $(this).closest('.volade-mission-card');
            var $btn = $(this).prop('disabled', true).text(msg('processing', 'Chargement…'));
            completeMission($card.data('mission'), $card).always(function() {
                $btn.prop('disabled', false);
            });
        });
    }

    // Découvrir — recherche et filtres
    var $discoverPage = $('.volade-discover-page');
    if ($discoverPage.length) {
        var $cards = $discoverPage.find('.volade-discover-card-v2');
        var $sections = $discoverPage.find('.volade-discover-category-block');
        var $empty = $('#volade-discover-empty');
        var $count = $('#volade-discover-count');
        var state = { filter: 'all', category: 'all', query: '' };

        function applyDiscoverFilters() {
            var visible = 0;
            $cards.each(function() {
                var $card = $(this);
                var matchQuery = !state.query || ($card.data('search') || '').indexOf(state.query) !== -1;
                var matchFilter = true;
                if (state.filter === 'live') {
                    matchFilter = String($card.data('live')) === '1';
                } else if (state.filter === 'planned') {
                    matchFilter = String($card.data('live')) === '0';
                } else if (state.filter === 'installed') {
                    matchFilter = String($card.data('installed')) === '1';
                }
                var matchCat = state.category === 'all' || $card.data('category') === state.category;
                var show = matchQuery && matchFilter && matchCat;
                $card.toggle(show);
                if (show) {
                    visible++;
                }
            });

            $sections.each(function() {
                var $sec = $(this);
                if (state.category !== 'all' && $sec.data('category-block') !== state.category) {
                    $sec.hide();
                    return;
                }
                var hasVisible = $sec.find('.volade-discover-card-v2:visible').length > 0;
                $sec.toggle(hasVisible);
            });

            $('.volade-discover-featured').toggle(
                state.filter === 'all' && state.category === 'all' && !state.query
            );

            if ($count.length) {
                var shownTpl = msg('plugins_shown', '%d plugins shown');
                $count.text(shownTpl.replace('%d', String(visible)));
            }
            $empty.prop('hidden', visible > 0);
        }

        $('#volade-discover-search').on('input', function() {
            state.query = $(this).val().toLowerCase().trim();
            applyDiscoverFilters();
        });

        $discoverPage.on('click', '.volade-discover-filter', function() {
            $('.volade-discover-filter').removeClass('is-active');
            $(this).addClass('is-active');
            state.filter = $(this).data('filter');
            applyDiscoverFilters();
        });

        $discoverPage.on('click', '.volade-discover-cat', function() {
            $('.volade-discover-cat').removeClass('is-active');
            $(this).addClass('is-active');
            state.category = $(this).data('category');
            applyDiscoverFilters();
        });

        $('#volade-discover-reset').on('click', function() {
            state = { filter: 'all', category: 'all', query: '' };
            $('#volade-discover-search').val('');
            $('.volade-discover-filter').removeClass('is-active').filter('[data-filter="all"]').addClass('is-active');
            $('.volade-discover-cat').removeClass('is-active').filter('[data-category="all"]').addClass('is-active');
            $cards.show();
            $sections.show();
            applyDiscoverFilters();
        });
    }

    // Activité — filtres
    var $activityPage = $('.volade-activity-page');
    if ($activityPage.length) {
        $activityPage.on('click', '.volade-activity-filter', function() {
            var filter = $(this).data('activity-filter');
            $('.volade-activity-filter').removeClass('is-active');
            $(this).addClass('is-active');

            var visible = 0;
            $('.volade-activity-card').each(function() {
                var group = $(this).data('activity-group');
                var show = filter === 'all' || group === filter;
                $(this).toggle(show);
                if (show) {
                    visible++;
                }
            });

            $('.volade-activity-day-group').each(function() {
                $(this).toggle($(this).find('.volade-activity-card:visible').length > 0);
            });

            $('#volade-activity-empty-filter').prop('hidden', visible > 0);
        });
    }

    // RGPD export
    $('#volade-export-data').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this).prop('disabled', true);
        $.post(voladeSDK.ajax_url, {
            action: 'volade_export_data',
            nonce: voladeSDK.nonce
        }, function(res) {
            $btn.prop('disabled', false);
            if (res.success && res.data) {
                var blob = new Blob([JSON.stringify(res.data, null, 2)], { type: 'application/json' });
                var a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = 'volade-export.json';
                a.click();
            } else {
                alert(res.data || msg('export_failed', 'Export failed.'));
            }
        });
    });

})(jQuery);
