/* Seazonify Admin Scripts */
jQuery(document).ready(function($) {
    let currentEmail = '';
    const nonce = seazonifyAdmin.nonce;

    // Helper: Show Feedback
    function showFeedback(msg, type = 'error') {
        const $fb = $('#onboarding-feedback');
        $fb.text(msg).removeClass('error success').addClass(type).show();
    }

    // Helper: Go to Step
    function goToStep(step) {
        $('.onboarding-step').removeClass('active');
        $(`#step-${step}`).addClass('active');
        $('.step-dot').removeClass('active');
        $(`.step-dot[data-step="${step}"]`).addClass('active');
    }

    // OTP Input Handling
    $('.otp-digit').on('keyup paste', function(e) {
        const $this = $(this);
        let val = $this.val();

        // Handle Paste
        if (e.type === 'paste') {
           const data = (e.originalEvent || e).clipboardData.getData('text');
           const digits = data.split('').filter(c => /\d/.test(c));
           $('.otp-digit').each((i, el) => {
               if (digits[i]) $(el).val(digits[i]);
           });
           updateOTPVal();
           return;
        }

        // Handle Backspace
        if (e.keyCode === 8 && !val) {
            $this.prev('.otp-digit').focus();
        } else if (val && /\d/.test(val)) {
            $this.next('.otp-digit').focus();
        }

        updateOTPVal();
    });

    function updateOTPVal() {
        let otp = '';
        $('.otp-digit').each((i, el) => otp += $(el).val());
        $('#seazonify-otp').val(otp);
        $('#btn-verify-otp').prop('disabled', otp.length !== 6);
    }

    // Step 1: Init Connect
    $('#btn-init-connect').on('click', function() {
        const $btn = $(this);
        const email = $('#seazonify-email').val();
        
        if (!email) return showFeedback('Please enter a valid email');

        $btn.addClass('loading').prop('disabled', true);
        $('#onboarding-feedback').hide();

        $.post(seazonifyAdmin.ajax_url, {
            action: 'seazonify_init_connect',
            nonce: nonce,
            email: email
        }, function(res) {
            console.log('[SEAZONIFY] init-connect raw response:', res);
            $btn.removeClass('loading').prop('disabled', false);
            if (res.success) {
                currentEmail = email;
                console.log('[SEAZONIFY] currentEmail set to:', currentEmail);
                $('#display-email').text(email);
                goToStep(2);
            } else {
                const errorMsg = res.data && res.data.message ? res.data.message : 'Connection failed. Please check if your site can reach Seazonify.com';
                showFeedback(errorMsg);
            }
        });
    });

    // Step 2: Verify OTP
    $('#btn-verify-otp').on('click', function() {
        const $btn = $(this);
        const otp = $('#seazonify-otp').val();

        $btn.addClass('loading').prop('disabled', true);
        $('#onboarding-feedback').hide();

        console.log('[SEAZONIFY] verify-connect sending:', { email: currentEmail, otp: otp });
        $.post(seazonifyAdmin.ajax_url, {
            action: 'seazonify_verify_connect',
            nonce: nonce,
            email: currentEmail,
            otp: otp,
            platform: 'wordpress',
            siteUrl: location.origin
        }, function(res) {
            console.log('[SEAZONIFY] verify-connect raw response:', res);
            $btn.removeClass('loading').prop('disabled', false);
            if (res.success) {
                if (res.data.registered) {
                    showFeedback('Success! Connecting...', 'success');
                    setTimeout(() => {
                        window.location.href = seazonifyAdmin.dashboard_url;
                    }, 1500);
                } else {
                    // Show Step 3
                    $('.registration-line, .registration-dot').show();
                    goToStep(3);
                }
            } else {
                showFeedback(res.data.message);
            }
        });
    });

    // Step 3: Complete Registration
    $('#btn-complete-reg').on('click', function() {
        const $btn = $(this);
        const name = $('#seazonify-name').val();
        const password = $('#seazonify-password').val();

        if (!name || !password) return showFeedback('All fields are required');

        $btn.addClass('loading').prop('disabled', true);
        $('#onboarding-feedback').hide();

        $.post(seazonifyAdmin.ajax_url, {
            action: 'seazonify_complete_registration',
            nonce: nonce,
            email: currentEmail,
            name: name,
            password: password,
            platform: 'wordpress',
            siteUrl: location.origin
        }, function(res) {
            $btn.removeClass('loading').prop('disabled', false);
            if (res.success) {
                showFeedback('Account created! Connecting...', 'success');
                setTimeout(() => {
                    window.location.href = seazonifyAdmin.dashboard_url;
                }, 1500);
            } else {
                showFeedback(res.data.message);
            }
        });
    });

    $('#btn-back-to-1').on('click', () => goToStep(1));

    // --- Settings Page Logic ---
    // Authentic Tab Navigation
    $('.sz-v6-nav-item').on('click', function() {
        const tab = $(this).data('tab');
        $('.sz-v6-nav-item').removeClass('active');
        $(this).addClass('active');
        $('.sz-v6-section').removeClass('active');
        $('#tab-' + tab).addClass('active');
        window.location.hash = tab;
    });

    // Hash Handler
    if (window.location.hash) {
        $(`.sz-v6-nav-item[data-tab="${window.location.hash.substring(1)}"]`).each(function() {
            $(this).click();
        });
    }

    // Save Bridge
    $('#sz-v6-save-btn').on('click', function() {
        const $btn = $(this);
        $btn.css('opacity', '0.5').text('Saving...');
        $('#sz-actual-submit').click();
    });

    // Conditional UI
    function toggleConditional() {
        const $select = $('#sz-display-on');
        if (!$select.length) return;
        const val = $select.val();
        $('.sz-v6-conditional').each(function() {
            const rules = ($(this).data('show-if') || '').split(',');
            if (rules.includes(val)) {
                $(this).slideDown(200);
            } else {
                $(this).hide();
            }
        });
    }
    $('#sz-display-on').on('change', toggleConditional);
    toggleConditional();

    // Deactivation
    $('#sz-v6-deactivate').on('click', function() {
        if (confirm('Are you sure you want to log out from Seazonify? Your settings and active effects will be preserved and will continue to work.')) {
            $('#sz-v6-disconnect-form').submit();
        }
    });

    // Update Message
    if (window.location.search.includes('settings-updated=true')) {
        const $msg = $('#sz-v6-save-msg');
        $msg.removeClass('hidden').delay(3000).fadeOut();
    }
});
