// 用户中心JS
var countdown = 0;
var countdownTimer = null;

$(document).ready(function(){
    // 安全选项卡切换
    $('.security-tabs button').on('click', function(){
        $('.security-tabs button').removeClass('active');
        $(this).addClass('active');
        $('.security-tab-content').removeClass('active');
        $('#' + $(this).data('tab')).addClass('active');
    });

    // 个人资料表单
    $('#profileForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 保存中...');
        
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.msg(response.msg, {icon: 1});
                    if(response.new_csrf){
                        $('input[name="csrf_token"]').val(response.new_csrf);
                    }
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // 密码修改表单
    $('#passwordForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 修改中...');
        
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.msg(response.msg, {icon: 1}, function(){
                        if(response.redirect){
                            window.location.href = response.redirect;
                        }
                    });
                    if(response.new_csrf){
                        $('input[name="csrf_token"]').val(response.new_csrf);
                    }
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // 卡密兑换表单
    $('#redeemForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 兑换中...');
        
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.msg(response.msg, {icon: 1});
                    if(response.new_csrf){
                        $('input[name="csrf_token"]').val(response.new_csrf);
                    }
                    setTimeout(function(){ location.reload(); }, 1500);
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // 邮箱绑定表单
    $('#bindEmailForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 绑定中...');
        
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.msg(response.msg, {icon: 1}, function(){
                        location.reload();
                    });
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // 邮箱解绑表单
    $('#unbindEmailForm').on('submit', function(e){
        e.preventDefault();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 解绑中...');
        
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.msg(response.msg, {icon: 1}, function(){
                        location.reload();
                    });
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
                submitBtn.prop('disabled', false).html(originalText);
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Handle tab parameter for redeem
    $(function(){
        var urlParams = new URLSearchParams(window.location.search);
        if(urlParams.get('tab') === 'redeem') {
            var redeemSection = $('#redeemForm').closest('.section-card');
            if(redeemSection.length) {
                setTimeout(function(){
                    $('html, body').animate({
                        scrollTop: redeemSection.offset().top - 80
                    }, 300);
                }, 100);
            }
        }
    });
});

// 第三方账号绑定
function bindSocial(type) {
    var ii = layer.load(2, {shade:[0.1,'#fff']});
    $.ajax({
        type: 'POST',
        url: 'login.php?act=connect',
        data: { type: type, bind_mode: 'bind', csrf_token: $('input[name="csrf_token"]').val() },
        dataType: 'json',
        success: function(res) {
            layer.close(ii);
            if(res.code === 0) {
                window.location.href = res.url;
            } else {
                layer.msg(res.msg, {icon: 2});
            }
        },
        error: function() {
            layer.close(ii);
            layer.msg('网络错误，请稍后重试', {icon: 2});
        }
    });
}

// 第三方账号解绑
function unbindSocial(type) {
    layer.confirm('确定要解绑' + (type === 'qq' ? 'QQ' : '微信') + '账号吗？', {icon: 3, title: '提示'}, function(index) {
        $.ajax({
            type: 'POST',
            url: 'user_center.php',
            data: { action: 'unbind_social', social_type: type, csrf_token: $('input[name="csrf_token"]').val() },
            dataType: 'json',
            success: function(res) {
                if(res.code === 0) {
                    layer.msg(res.msg, {icon: 1}, function(){
                        location.reload();
                    });
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            },
            error: function() {
                layer.msg('网络错误，请稍后重试', {icon: 2});
            }
        });
        layer.close(index);
    });
}

// 发送绑定验证码
function sendBindCode() {
    var email = $('#bindEmail').val();
    
    if(!email){
        layer.msg('请输入邮箱地址', {icon: 2});
        return;
    }
    
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
        layer.msg('邮箱格式不正确', {icon: 2});
        return;
    }
    
    var btn = $('#btnSendBindCode');
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 发送中...');
    
    $.ajax({
        type: 'POST',
        url: 'user_center.php',
        data: {action: 'send_bind_code', email: email, csrf_token: $('input[name="csrf_token"]').val()},
        dataType: 'json',
        success: function(response) {
            if(response.code === 0){
                layer.msg(response.msg, {icon: 1});
                startBindCountdown();
            } else {
                layer.msg(response.msg, {icon: 2});
                btn.prop('disabled', false).html('获取验证码');
            }
        },
        error: function() {
            layer.msg('网络错误，请稍后重试', {icon: 2});
            btn.prop('disabled', false).html('获取验证码');
        }
    });
}

// 发送解绑验证码
function sendUnbindCode() {
    var email = $('#unbindEmail').val();
    
    if(!email){
        layer.msg('请输入邮箱地址', {icon: 2});
        return;
    }
    
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
        layer.msg('邮箱格式不正确', {icon: 2});
        return;
    }
    
    var btn = $('#btnSendUnbindCode');
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 发送中...');
    
    $.ajax({
        type: 'POST',
        url: 'user_center.php',
        data: {action: 'send_unbind_code', email: email, csrf_token: $('input[name="csrf_token"]').val()},
        dataType: 'json',
        success: function(response) {
            if(response.code === 0){
                layer.msg(response.msg, {icon: 1});
                startUnbindCountdown();
            } else {
                layer.msg(response.msg, {icon: 2});
                btn.prop('disabled', false).html('获取验证码');
            }
        },
        error: function() {
            layer.msg('网络错误，请稍后重试', {icon: 2});
            btn.prop('disabled', false).html('获取验证码');
        }
    });
}

// 绑定验证码倒计时
function startBindCountdown() {
    countdown = 60;
    var btn = $('#btnSendBindCode');
    
    countdownTimer = setInterval(function(){
        countdown--;
        if(countdown <= 0){
            clearInterval(countdownTimer);
            btn.prop('disabled', false).html('获取验证码');
        } else {
            btn.html(countdown + '秒后重试');
        }
    }, 1000);
}

// 解绑验证码倒计时
function startUnbindCountdown() {
    countdown = 60;
    var btn = $('#btnSendUnbindCode');
    
    countdownTimer = setInterval(function(){
        countdown--;
        if(countdown <= 0){
            clearInterval(countdownTimer);
            btn.prop('disabled', false).html('获取验证码');
        } else {
            btn.html(countdown + '秒后重试');
        }
    }, 1000);
}
