var endpoint = 'https://pageloadtimer.selectorshub.info/';

let resendTimer; 
var allow = false;
var isLoggedIn = false

function startCountdown() {
    let timeLeft = 60;
    const $btn = $("#resend_btn");

    // Disable button and show timer
    $btn.prop("disabled", true).css("opacity", "0.6");
    $btn.val(`Resend in ${timeLeft}s`);

    // Start interval countdown
    resendTimer = setInterval(function() {
        timeLeft--;
        $btn.val(`Resend in ${timeLeft}s`);

        if (timeLeft <= 0) {
            clearInterval(resendTimer);
            $btn.prop("disabled", false).css("opacity", "1");
            $btn.val("Resend verification code");
        }
    }, 1000);
}

 function checkSessionId() {
     chrome.storage.local.get(['ttlt', 'expiry_date'], (e) => {
  
         if (typeof e.ttlt == 'undefined' || e.ttlt == 'undefined' || e.ttlt ==  null || e.ttlt ==  '') {
         
            isLoggedIn = false
            allow = false;
            if (!e.expiry_date){
                
                try {
                    fetch(endpoint+"user/limit")
                        .then((res) => res.json())
                        .then((data) => {
                          if (!data || typeof data.free_access !== "number") {
                            throw new Error("Invalid response: free_days missing or not a number");
                            }

                            const today = new Date();

                            // Clone today's date for expiry
                            const expiry = new Date(today);
                            const randomExtraDays = Math.floor(Math.random() * 7) + 1;
                            expiry.setDate(today.getDate() + data.free_access + randomExtraDays);

                            if (isNaN(expiry.getTime())) {
                            throw new Error("Expiry date calculation failed");
                            }
                            chrome.storage.local.set(
                            {
                                start_date: today.toISOString(),
                                expiry_date: expiry.toISOString(),
                                has_free_access: true,
                                free_days: data.free_access,
                            },
                            () => {
                                if (chrome.runtime.lastError) {
                                   // console.error("Failed to save data:", chrome.runtime.lastError);
                                } else {

                                    const now = new Date();
                                    const expiry = new Date(e.expiry_date);

                                    if (now > expiry) {
                                        allow = false;
                                        chrome.storage.local.set({ has_free_access: false });
                                    }else{
                                        allow = true;
                                    }
                                    //console.log(allow)
                                    showPt(allow, isLoggedIn)
                                    if(!allow){
                                        setTimeout(()=>{
                                            openLoginForm()
                                        },3000)
                                    }
                                    return false;
                                }
                            }
                            );
                        })
                        .catch((err) => {
                           // console.error("Failed to fetch free days:", err);
                        });

                }catch (err) {
                   // console.error(`Error during ${type} fetch:`, err);
                }
            }else{
                const now1 = new Date();
                const expiry = new Date(e.expiry_date);
                if (now1 > expiry) {
                    allow = false;
                    chrome.storage.local.set({ has_free_access: false });
                    
                }else{
                    allow = true;
                }
                showPt(allow, isLoggedIn)

                if(!allow){
                    setTimeout(()=>{
                        openLoginForm()
                    },3000)
                }
            }

           
         }else{
            checkUser(e.ttlt)
         }
     }); 
 }
 
 function showPt(allow, loggedin){
   
     if(allow && loggedin){
        $('.stat-can').css('height', 'unset')
        $('.stat-can').css('overflow-y', 'unset')
        $('.profile-btn').show()
        $('.login-btn').hide()
        $('.ad-container').addClass('hidden')

     }else if(allow && !loggedin){
      
        $('.ad-container').addClass('hidden')
        $('.profile-btn').hide()
        $('.login-btn').show()
        $('.stat-can').css('height', '250px')
        $('.stat-can').css('overflow-y', 'scroll')

     }else if(!allow && !loggedin){
       
        $('.profile-btn').hide()
        $('.login-btn').show()
        $('.stat-can').css('height', '250px')
        $('.stat-can').css('overflow-y', 'scroll')
    
        fetchProductUpdates()
     }else if(!allow && loggedin){
        $('.stat-can').css('height', '250px')
        $('.stat-can').css('overflow-y', 'scroll')
        $('.profile-btn').show()
        $('.login-btn').hide()
        fetchProductUpdates()
     }

}

 $(document).ready(function () {

    $('.login-btn').on('click', function() {
        $('#loginModal').fadeIn(200);
        $('#register_form').show()
        $('.profile-tab').hide()
        $('#open_login').click()
    });

    $(document).on('click', '.back-btn', function() {
        // Get which screen to show
        const nextScreen = $(this).attr('data-next');
      
        if (nextScreen === 'login') {
            $('#loginModal').css("display", "none");
            $('.back-btn').attr('data-next', "home")   
        } else if (nextScreen === 'register') {
            $('.register-container').hide()
            $('#login-container').show()
            $('.back-btn').attr('data-next', "login")  
            $('#open_login').show()
             $('#forgot_pass').hide()
        }else if (nextScreen === 'forgtpass') {
            $('#open_login').click() 
        }
    });


     $(".profile-btn").on("click", () => {
        $('#register_form').hide()
        $('.profile-tab').show()
        $("#loginModal").show()
    })


    $("#show_reg_form").on("click", () => {
        // $("#show_reg_form").hide()
        $('.register-container').show()
        $('#login-container').hide()
        $('.back-btn').attr("data-next","register")
        showRegForm()
    })

     $(document).on('click','#forgot_pass',function(){
        $('.back-btn').attr("data-next","forgtpass")
        $('.email-container, .forgetbtn, #open_login').show()
        $('.licence-container, #submit_btn, #forgot_pass').hide()
     });

     $(document).on('click','#open_login',function(){
        $('.email-container, .forgetbtn, #open_login, .register-container').hide()
        $('.licence-container, #submit_btn, #forgot_pass, #login-container').show()
           $('.back-btn').attr('data-next', "login")  
     });

    $('.subscription_plan').on('click', function () {
        window.open('https://selectorshub.com/how-to-get-page-load-timer-key/', '_blank'); 
    });

    $('#registration_help').on('click', function () {
        window.open('https://selectorshub.com/how-to-get-page-load-timer-key/', '_blank'); 
    });

    $('#registration_tutorial').on('click', function () {
        window.open('https://youtu.be/Yuu3CZ-Zd-U', '_blank');
    });


    let logoutModal = document.querySelector("#logoutModal");
    
    $(document).on('click','.open-logout', function () {
        $('#loginModal').hide()
        logoutModal.style.display = "flex";
    });

    $("#yes-logout").on("click", () => {
        logout();
    })

    $("#no-logout").on("click", () => {
        logoutModal.style.display = "none";
    })


    $('.home-profile-btn').click(function(){
        $(".main-body").slideUp(250); // Slide down the main body over 500ms
        $(".profile-tab").slideDown(250); // Slide up the register form over 500ms      
    });
    
     
 $("#email-f").on('keyup', function (e) {
     if (e.key === 'Enter' || e.keyCode === 13) {
         $('.forgetbtn').click();
     }
 });
 
 $("#password").on('keyup', function (e) {
     if (e.key === 'Enter' || e.keyCode === 13) {
         $('#submit_btn').click();
     }
 });
 
 
 
     $('.open-forgot-password').click(function(){
         $('.forgetbtn').show()
         $('#submit_btn').hide()
         $('.password-container').hide()
         $('.open-forgot-password').hide();
         $('.open-login').show();
     })
 
     $('.open-login').click(function(){
         $('.forgetbtn').hide()
         $('#submit_btn').show()
         $('.open-forgot-password').show();
         $('.open-login').hide()
          $('.password-container').show()
     })
 
     $('.open-home').click(function(){
        $('#loginModal').hide()
     })
     
 
    //   $('.forgetbtn').click(function(){
    //      let user_email = document.getElementById("email").value.trim();
    //     loading(true);
 
    //       $('.forgetbtn').prop('disabled', true); 
    //     $('.forgetbtn').val('Please wait') 
    //         $.ajax({
    //          method: "POST",
    //          url: endpoint + 'user/sendforgot',
    //           beforeSend: function(request) {
    //              request.setRequestHeader("Content-type", 'application/json');
    //            },
    //          data:  JSON.stringify({email:user_email}),
    //          success: function(serverResponse, txtStatus, request) {
    //             loading(false); 
    //                   $('.forgetbtn').prop('disabled', false); 
    //                      $('.forgetbtn').val('Submit') 
    //              if(request.status == 200 && serverResponse.status){
    //                     $('.user-status').text(serverResponse.message).css('color','green').slideDown();
    //                  setTimeout(()=>{$('.user-status').slideUp();},5000)
                    
    //                }else{
    //                 chrome.storage.local.remove('ttlt');
    //                  $('.user-status').text(serverResponse.message).css('color','red').slideDown();
    //                  setTimeout(()=>{$('.user-status').slideUp();},5000)
    //              }
    //          },
    //            error: function(event, jqxhr, exception) {
    //          },
    //          statusCode: {
    //          500: function(serverResponse) {
          
    //          },
    //           401: function(serverResponse) {
            
    //          }
    //        }
    //       });
       
 
    //      })
 
 
    //  $('#submit_btn').click(function(){
    //      let user_email = document.getElementById("licence").value.trim();

    //      if(user_email==''){return false}

    //     loading(true);
 
    //     $('#submit_btn').prop('disabled', true); 
    //     $('#submit_btn').val('Please wait') 
 
    //         $.ajax({
    //          method: "POST",
    //          url: endpoint + 'user/login',
    //           beforeSend: function(request) {
    //              request.setRequestHeader("Content-type", 'application/json');
    //            },
    //          data:  JSON.stringify({lk:user_email}),
    //          success: function(serverResponse, txtStatus, request) {
    //             loading(false); 
    //           $('#submit_btn').prop('disabled', false); 
    //              $('#submit_btn').val('Login') 
    //              if(request.status == 200 && serverResponse.status){
    //                    chrome.storage.local.set({ttlt:serverResponse.token});
    //                    ttlt = serverResponse.token; 
    //                    chrome.storage.local.set({data:serverResponse.data,messages:serverResponse.messages}, function(){
                        
    //                          chrome.runtime.sendMessage({message: "loggedin"}, function(response) {})
    //                    });
    //                    loginIssue() 
    //                }else{
    //                     $('#submit_btn').prop('disabled', false); 
    //                     $('#submit_btn').val('Login') 
    //                     chrome.storage.local.remove('ttlt');
    //                     $('.subscription-status').text(serverResponse.message).slideDown();
    //                     setTimeout(()=>{$('.subscription-status').slideUp();},5000)

    //                     if(serverResponse.message.indexOf('Already') > -1){
    //                         $('#three-modal').show();
    //                     }
    //              }
    //          },
    //            error: function(event, jqxhr, exception) {
    //                  loading(false)
    //                  $('#submit_btn').prop('disabled', false); 
    //                  $('#submit_btn').val('Login') 
    //                  $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
    //                 setTimeout(function(){ document.getElementsByClassName('invalid-credentails')[0].style.display = 'none'; },3000);
    //          },
    //          statusCode: {
    //          500: function(serverResponse) {
          
    //          },
    //           401: function(serverResponse) {
    //              loading(false)
    //                  $('#submit_btn').prop('disabled', false); 
    //                  $('#submit_btn').val('Login') 
    //              $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
    //              setTimeout(function(){ 
    //                  document.getElementsByClassName('invalid-credentails').style.display = 'none';
    //              },3000);
    //          }
    //        }
    //       });
       
 
    //      })
 
   $('.forgetbtn').click(function(){
         let user_email = document.getElementById("email").value.trim();

            if(user_email==''){ 
            $('#email').focus()
            return false
            }
        loading(true);
 
          $('.forgetbtn').prop('disabled', true); 
        $('.forgetbtn').val('Please wait') 
            $.ajax({
             method: "POST",
             url: endpoint + 'user/sendforgot',
              beforeSend: function(request) {
                 request.setRequestHeader("Content-type", 'application/json');
               },
             data:  JSON.stringify({email:user_email}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
                      $('.forgetbtn').prop('disabled', false); 
                         $('.forgetbtn').val('Submit') 
                 if(request.status == 200 && serverResponse.status){
                        $('.user-status').text(serverResponse.message).css('color','green').slideDown();
                     setTimeout(()=>{$('.user-status').slideUp();},5000)
                    
                   }else{
                    chrome.storage.local.remove('ttlt');
                     $('.user-status').text(serverResponse.message).css('color','red').slideDown();
                     setTimeout(()=>{$('.user-status').slideUp();},5000)
                 }
             },
               error: function(event, jqxhr, exception) {
             },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
            
             }
           }
          });
       
 
         })
 
 
     $('#submit_btn').click(function(){
         let user_email = document.getElementById("licence").value.trim();

         if(user_email==''){
            $('#licence').focus()
            return false
        }

        loading(true);
 
        $('#submit_btn').prop('disabled', true); 
        $('#submit_btn').val('Please wait') 
 
            $.ajax({
             method: "POST",
             url: endpoint + 'user/login',
              beforeSend: function(request) {
                 request.setRequestHeader("Content-type", 'application/json');
               },
             data:  JSON.stringify({lk:user_email}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
              $('#submit_btn').prop('disabled', false); 
                 $('#submit_btn').val('Login') 
                 if(request.status == 200 && serverResponse.status){
                       chrome.storage.local.set({ttlt:serverResponse.token});
                       ttlt = serverResponse.token; 
                       chrome.storage.local.set({data:serverResponse.data,messages:serverResponse.messages}, function(){
                             chrome.runtime.sendMessage({message: "loggedin"}, function(response) {})
                       });
                       loginIssue() 
                   }else{
                        $('#submit_btn').prop('disabled', false); 
                        $('#submit_btn').val('Login') 
                        chrome.storage.local.remove('ttlt');
                        $('.subscription-status').text(serverResponse.message).slideDown();
                        setTimeout(()=>{$('.subscription-status').slideUp();},5000)

                        if(serverResponse.message.indexOf('Already') > -1){
                            $('#three-modal').show();
                        }
                 }
             },
               error: function(event, jqxhr, exception) {
                     loading(false)
                     $('#submit_btn').prop('disabled', false); 
                     $('#submit_btn').val('Login') 
                     $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                    setTimeout(function(){ document.getElementsByClassName('invalid-credentails')[0].style.display = 'none'; },3000);
             },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
                 loading(false)
                     $('#submit_btn').prop('disabled', false); 
                     $('#submit_btn').val('Login') 
                 $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                 setTimeout(function(){ 
                     document.getElementsByClassName('invalid-credentails').style.display = 'none';
                 },3000);
             }
           }
          });
       
 
         })
 

    $('#re_submit_btn').click(function(){
         let user_email = document.getElementById("re_licence").value.trim();

         if(user_email==''){
            $('#re_licence').focus()
            return false
        }

        loading(true);
 
        $('#re_submit_btn').prop('disabled', true); 
        $('#re_submit_btn').val('Please wait') 
 
            $.ajax({
             method: "POST",
             url: endpoint + 'user/login',
              beforeSend: function(request) {
                 request.setRequestHeader("Content-type", 'application/json');
               },
             data:  JSON.stringify({lk:user_email}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
              $('#re_submit_btn').prop('disabled', false); 
                 $('#re_submit_btn').val('Login') 
                 if(request.status == 200 && serverResponse.status){
                       chrome.storage.local.set({ttlt:serverResponse.token});
                       ttlt = serverResponse.token; 
                       chrome.storage.local.set({data:serverResponse.data,messages:serverResponse.messages}, function(){
                             chrome.runtime.sendMessage({message: "loggedin"}, function(response) {})
                       });
                       loginIssue() 
                   }else{
                        $('#re_submit_btn').prop('disabled', false); 
                        $('#re_submit_btn').val('Login') 
                        chrome.storage.local.remove('ttlt');
                        $('.subscription-status').text(serverResponse.message).slideDown();
                        setTimeout(()=>{$('.subscription-status').slideUp();},5000)

                        if(serverResponse.message.indexOf('Already') > -1){
                            $('#three-modal').show();
                        }
                 }
             },
               error: function(event, jqxhr, exception) {
                     loading(false)
                     $('#re_submit_btn').prop('disabled', false); 
                     $('#re_submit_btn').val('Login') 
                     $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                    setTimeout(function(){ document.getElementsByClassName('invalid-credentails')[0].style.display = 'none'; },3000);
             },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
                 loading(false)
                     $('#submit_btn').prop('disabled', false); 
                     $('#submit_btn').val('Login') 
                 $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                 setTimeout(function(){ 
                     document.getElementsByClassName('invalid-credentails').style.display = 'none';
                 },3000);
             }
           }
          });
       
 
         })

     $('#resend_btn').click(function(){
         let userEmail = document.getElementById("re-email").value.trim();
         let reFullName = document.getElementById("re-full-name").value.trim();
        

        loading(true);
 
        $('.re-actions').prop('disabled', true); 
        $('#resend_btn').val('Please wait') 
 
        startCountdown()
            $.ajax({
             method: "POST",
             url: endpoint + 'user/resend-code',
            beforeSend: function(request) {
                request.setRequestHeader("Content-type", 'application/json');
                request.setRequestHeader("D", 'pageloadtime');
            },
             data:  JSON.stringify({email:userEmail, name:reFullName}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
                $('.re-actions').prop('disabled', false); 
                $('#resend_btn').val('Resend verification code') 
                 if(request.status == 200 && serverResponse.status){
                   showServerMessage(serverResponse.message, "success")
                 }else{
                    showServerMessage(serverResponse.message, "error")
                 }
             },
               error: function(event, jqxhr, exception) {
                     loading(false)
              },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
               
             }
           }
          });
       
 
         })



     $('#verify_btn').click(function(){
         let userEmail = document.getElementById("re-email").value.trim();
         let reFullName = document.getElementById("re-full-name").value.trim();
         let otpCode = document.getElementById("otp-code").value.trim();

         if(otpCode==''){ $("#otp-code").focus(); return false}

        loading(true);
 
        $('.re-actions').prop('disabled', true); 
        $('#verify_btn').val('Please wait') 
 
            $.ajax({
             method: "POST",
             url: endpoint + 'user/verify-code',
            beforeSend: function(request) {
                request.setRequestHeader("Content-type", 'application/json');
                request.setRequestHeader("D", 'pageloadtime');
            },
             data:  JSON.stringify({email:userEmail, name:reFullName, otp:otpCode}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
                $('.re-actions').prop('disabled', false); 
                $('#verify_btn').val('Submit') 
                 if(request.status == 200 && serverResponse.status){
                    //showServerMessage(serverResponse.message, "success")
                    // $('.subscription-status').text(serverResponse.message).slideDown();
                    // setTimeout(()=>{$('.subscription-status').slideUp();},5000)
                    // $(".back-btn").click();
                    showServerMessage(serverResponse.message, "success")
                  

                    $("#verify_btn, #resend_btn, .re-otp-container").hide()
                    $(".re-licence-input-container, #re_submit_btn").show()


                 }else{
                    showServerMessage(serverResponse.message, "error")
                 }
             },
               error: function(event, jqxhr, exception) {
                     loading(false)
              },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
               
             }
           }
          });
       
 
         })

    $('#register_btn').click(function(){
         let userEmail = document.getElementById("re-email").value.trim();
         let reFullName = document.getElementById("re-full-name").value.trim();

         if (reFullName === "") {
            $("#re-full-name").focus();
            return false;
        }

         if(userEmail==''){
             $("#re-email").focus();
            return false
        }

        loading(true);
 
        $('.re-actions').prop('disabled', true); 
       // $('#submit_btn').val('Please wait') 
 
            $.ajax({
             method: "POST",
             url: endpoint + 'user/register',
              beforeSend: function(request) {
                 request.setRequestHeader("Content-type", 'application/json');
                 request.setRequestHeader("D", 'pageloadtime');
               },
             data:  JSON.stringify({email:userEmail, name:reFullName}),
             success: function(serverResponse, txtStatus, request) {
                loading(false); 
              $('.re-actions').prop('disabled', false); 
                //  $('#submit_btn').val('Login') 
                 if(request.status == 200 && serverResponse.status){
                   showServerMessage(serverResponse.message, "success")
                   $("#verify_btn, #resend_btn, .re-otp-container").show()
                   $(".name-container, .re-email-container, #register_btn").hide()
                   startCountdown();
                 }else{
                    showServerMessage(serverResponse.message, "error")
                 }
             },
               error: function(event, jqxhr, exception) {
                     loading(false)
              },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
               
             }
           }
          });
       
 
         })

     checkSessionId();

     $(document).on('click','.close-modal',function(){
        $('#three-modal').hide()
     })

     $(document).on('click','.device-close',function(){
        let num = parseInt($(this).attr('data-num'))

        let user_email = document.getElementById("licence").value.trim();

        if(user_email==''){return false}
        $('#three-modal').hide()
        loading(true);

        $('#submit_btn').prop('disabled', true); 
        $('#submit_btn').val('Please wait') 

           $.ajax({
            method: "POST",
            url: endpoint + 'user/remove',
             beforeSend: function(request) {
                request.setRequestHeader("Content-type", 'application/json');
              },
            data:  JSON.stringify({lk:user_email, num:num}),
            success: function(serverResponse, txtStatus, request) {
               loading(false); 
             $('#submit_btn').prop('disabled', false); 
                $('#submit_btn').val('Login') 
                if(request.status == 200 && serverResponse.status){
                      chrome.storage.local.set({ttlt:serverResponse.token});
                      ttlt = serverResponse.token; 
                      chrome.storage.local.set({data:serverResponse.data,messages:serverResponse.messages}, function(){
                          
                            chrome.runtime.sendMessage({message: "loggedin"}, function(response) {})
                      });
                      loginIssue() 
                   
                  }else{
                       $('#submit_btn').prop('disabled', false); 
                       $('#submit_btn').val('Login') 
                       chrome.storage.local.remove('ttlt');
                       $('.subscription-status').text(serverResponse.message).slideDown();
                       setTimeout(()=>{$('.subscription-status').slideUp();},5000)

                       if(serverResponse.message.indexOf('Already') > -1){
                           $('#three-modal').show();
                       }
                }
            },
              error: function(event, jqxhr, exception) {
                    loading(false)
                    $('#submit_btn').prop('disabled', false); 
                    $('#submit_btn').val('Login') 
                    $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                   setTimeout(function(){ document.getElementsByClassName('invalid-credentails')[0].style.display = 'none'; },3000);
            },
            statusCode: {
            500: function(serverResponse) {
         
            },
             401: function(serverResponse) {
                loading(false)
                    $('#submit_btn').prop('disabled', false); 
                    $('#submit_btn').val('Login') 
                $('.invalid-error.invalid-credentails').text('Invalid credentials').slideDown()
                setTimeout(function(){ 
                    document.getElementsByClassName('invalid-credentails').style.display = 'none';
                },3000);
            }
          }
         });


     })

    
     $(document).on('click','#close_btn',function(){
       
        $("#loginModal").slideUp(250); // Slide down the main body over 500ms
        // $("#register_form").slideUp(250); // Slide up the register form over 500ms
        
     })

     $(document).on('click','#forgot_pass',function(){
        $('.email-container, .forgetbtn, #open_login').show()
        $('.licence-container, #submit_btn, #forgot_pass').hide()
     });

     $(document).on('click','#open_login',function(){
        $('.email-container, .forgetbtn, #open_login').hide()
        $('.licence-container, #submit_btn, #forgot_pass').show()
     });

 })
 
    function loading(show) {
        if (show) {
            $('.loading-view').show()
        }else{
            $('.loading-view').hide()
        }
    }
 
    function loginIssue() {
        // $(".main-body").slideDown(250); 
        $("#loginModal").slideUp(250);    
        $('.stat-can').css('height', '250px')
        $('.stat-can').css('overflow-y', 'scroll')
        checkSessionId()
    }

function logout() {
    $('#logoutModal').hide()
    $('.stat-can').css('height', 'unset')
    $('.stat-can').css('overflow-y', 'unset')
    const today = new Date();
    const expiry = new Date(today);
    expiry.setDate(today.getDate() - 365);
    
    chrome.storage.local.set({expiry_date: expiry.toISOString(), lastLoginOpenDate:new Date().toISOString().split('T')[0] },function(){ 
     

         chrome.storage.local.get(['ttlt'], (e) => {
            if (typeof e.ttlt == 'undefined' || e.ttlt == 'undefined' || e.ttlt ==  null || e.ttlt ==  '') {
            }else{
                logoutUser(e.ttlt)
                chrome.storage.local.remove('ttlt', function() {
                       checkSessionId()
                });
                }
            }
        )

    });

     

}

    function logoutUser(tlp){
        $.ajax({
            method: "get",
            url: endpoint + 'user/logout',
            beforeSend: function(request) {
                request.setRequestHeader("Content-type", 'application/json');
                request.setRequestHeader("Authorization", 'Bearer '+tlp);
            },
            success: function(serverResponse, txtStatus, request) {
            },
            error: function(event, jqxhr, exception) {
            
            },
            statusCode: {
            500: function(serverResponse) {
            
            },
            401: function(serverResponse) {
                
            }
        }
        });
    }

function checkUser(tlp){
    $.ajax({
        method: "get",
        url: endpoint + 'user/get-user-v2',
         beforeSend: function(request) {
            request.setRequestHeader("Content-type", 'application/json');
            request.setRequestHeader("Authorization", 'Bearer '+tlp);
          },
        success: function(serverResponse, txtStatus, request) {
            if(request.status == 200 && serverResponse.status){
                isExpired = serverResponse.licenseExpired
                if(isExpired){
                    $('.upgrate-lifetime').show()
                }

                $(".user-name").text("Hi, "+serverResponse.name || "User");
                $(".renewsub").text(serverResponse.message);

                allow = serverResponse.licenseExpired ? false : true 
                showPt(allow, true)

                if(serverResponse.showUpgrade) {
                $(".upgrate-lifetime")
                    .show()
                    .off("click")
                    .on("click", function () {
                        window.open(serverResponse.upgradeUrl, "_blank");
                    });
                } else {
                    $(".upgrate-lifetime").hide();
                }
            }else{
                logout()
            }
        },
          error: function(event, jqxhr, exception) {
            logout()
        },
        statusCode: {
        500: function(serverResponse) {
            logout()
        },
         401: function(serverResponse) {
            logout()
        }
      }
     });
 }

 function showRegForm(){
    $('#register_btn, #register_back_btn, #open_login').show()
    $('#forgot_pass').hide()
 }


 function openLoginForm() {
    const STORAGE_KEY = 'lastLoginOpenDate';
    const today = new Date().toISOString().split('T')[0];

    chrome.storage.local.get(STORAGE_KEY, function (result) {
        const savedDate = result[STORAGE_KEY];
        // First time OR date changed
        if (!savedDate || savedDate !== today) {
            $.ajax({
             method: "GET",
             url: endpoint + 'user/regshow',
            beforeSend: function(request) {
                request.setRequestHeader("Content-type", 'application/json');
                request.setRequestHeader("D", 'shub');
            },
             success: function(serverResponse, txtStatus, request) {
                 if(request.status == 200 && serverResponse.status && serverResponse.allowed){
                    $('.login-btn').click();
                    $('#show_reg_form').click()
             
                    chrome.storage.local.set({
                        [STORAGE_KEY]: today
                    });
                 }
             },
             error: function(event, jqxhr, exception) {
                  
              },
             statusCode: {
             500: function(serverResponse) {
          
             },
              401: function(serverResponse) {
               
             }
           }
          });
        }
    });
}

 hitCounterApiIfDateChanged();
function hitCounterApiIfDateChanged() {
    const STORAGE_KEY = 'user_counter_last_hit_date';
    const today = new Date().toISOString().split('T')[0];

    // chrome.storage.local.get is asynchronous
    chrome.storage.local.get([STORAGE_KEY], function(result) {
        const storedDate = result[STORAGE_KEY];

        if (storedDate !== today) {
            $.ajax({
                method: "GET",
                url: endpoint + 'user/counter',
                beforeSend: function (request) {
                    request.setRequestHeader("Content-type", 'application/json');
                    request.setRequestHeader("D", 'pageloadtime');
                },
                success: function (serverResponse) {
                    // Save today's date using the Chrome storage API
                    let data = {};
                    data[STORAGE_KEY] = today;
                    
                    chrome.storage.local.set(data, function() {
                    });
                },
                error: function (event, jqxhr, exception) {
                    // Error handling
                },
                statusCode: {
                    500: function () {},
                    401: function () {}
                }
            });
        }
    });
}

  function showServerMessage(message, type = "info") {
    const $msg = $(".server-message");
    let color;

    switch (type) {
        case "success":
            color = "#2ec52e";
            break;
        case "error":
            color = "#c55555";
            break;
        case "warning":
            color = "orange";
            break;
        case "info":
        default:
            color = "blue";
            break;
    }

     $msg.stop(true, true) // stop any ongoing animation
        .text(message)
        .css({
            "color": color,
            "font-weight": "bold"
        })
        .slideDown(300); // slide down smoothly

    // Slide up after 3 seconds
    setTimeout(() => {
        $msg.slideUp(300);
    }, 15000);
}