$(function(){
  
  $('.order_btn_link').click(orderLinkFn);
  $('.package_list>p').click(packageSelectFn);
  $('.static_buy').click(orderNowFn);

  $('#package_num').on('input', inputNumChangeFn );
  $('#package_num').on('blur', inputNumBlurFn );
  $('.c_close').on('click', function(){
    $('.coupon-model').hide();
  })
  couponCuttime();
  $('#package_num').focus();
  checkUserTypeFn();
  if(localStorage.getItem("userType") && localStorage.getItem("userType") == 0){
    document.addEventListener('visibilitychange', function () {
      if (document.visibilityState === 'visible' && localStorage.getItem('session')) {
        checkUserTypeFn();
      }
    });
  }

  $('.already-pay,.checkpay-close').on('click', function(){
    $('.checkpay').hide();
  })

  $('.proxy_tab_btn>p').on('click', function(){
    const index = $(this).index();
    $(this).addClass('active').siblings().removeClass('active');
    $('.proxy_container>div').eq(index).show().siblings().hide();
    $('.ublimit_proxy_container>div').eq(index).show().siblings().hide();
    $('.unlimit-proxy-list').eq(index).show().siblings('.unlimit-proxy-list').hide();
  })
 

})
let submitFlag1 = false;
let countdown_check = 300;
let check_time = null;
const checkUserTypeFn = async () => {
  const res = await $POST("/v1/memberSimple");
  if(res.code!=0)return;
  localStorage.setItem("userType", res.data.repay);
  if(res.data.repay != 0){
    $('.neworder').fadeOut();
  }
}
const session = localStorage.getItem("session");
const user = localStorage.getItem("user");
let lang = $('#language').val();
const orderLinkFn = async (e) => {
  const DOM = $(e.currentTarget);
  const sn = DOM.data("sn");
  countdown_check = 30;
  var currentUrl = window.location.href;
  var match = currentUrl.match(/\.com(.*)/);
  

  if (!session || !user || user == undefined || user == "undefined") {
    let url = "/sign-up/" ;
    if (lang == "zh"){
      url = `/${lang}/sign-up/`
    }
    let r = "";
    if (match && match.length > 1) {
      var contentAfterCom = match[1];
      r = contentAfterCom;
    }
    window.location.href = url +"?r=" + r
  } else {
    settime();
    check_time = setInterval(function () {
      checkpay()
    }, 3000);
    if(submitFlag1) return;
    submitFlag1 = true;
    const res = await $POST("/v1/orderPackage", { sn, lang });
    submitFlag1 = false;
    if(res.code!=0)return messageFn(res.msg);
    window.open(res.data.url);

  }
}

const checkpay = async () => {
  const res = await $POST("/v1/paymentCheck", { session, lang });
  if(res.code!=0)return;
  if(res.data.show == 1){
    $(".checkpay").show();
    clearInterval(check_time);
  }
}



function settime() {
  clearInterval(check_time);
  check_time = setInterval(function () {
      if (countdown_check == 0) {
          clearInterval(check_time);
      } else {
          countdown_check--;
      }
  }, 1000);
}

let price = $('.package_list>p.active').data("price");
let costprice = $('.package_list>p.active').data("costprice");
let number = 1;
let total = Math.floor(price * number * 100) / 100;;
const packageSelectFn = (e) => {
  $('#package_num').focus();

  const DOM = $(e.currentTarget);
  $(DOM).addClass('active').siblings().removeClass('active');
  price = DOM.data("price");
  costprice = DOM.data("costprice");
  number = $("#package_num").val();
  randerFn();
}
const inputNumChangeFn = (e) => {
  const dom = $(e.currentTarget);
  number = $(e.currentTarget).val();
  if (isNaN(number) || number < 1) {
    dom.addClass('error');
  } else {
    dom.removeClass('error');
    
  }
  randerFn();
  
}
const inputNumBlurFn = (e) => {
  number = $(e.currentTarget).val();
  if(number < 1){
    number = 1;
    $(e.currentTarget).removeClass('error');
    $(e.currentTarget).val(1);
  }
  randerFn();
}
const randerFn = () => {
  total = Math.floor(price * number * 100) / 100;
  $('.total_price_num').html('$'+total);
  $('.unit_price').html(price);
  $('.cost_price_hx').html(`$${costprice}/IP`);
}

const orderNowFn = async (e) => {
  var currentUrl = window.location.href;
  var match = currentUrl.match(/\.com(.*)/);
  
  if(total<1) return messageFn('Quantity must be greater than 0');;
  if (!session || !user || user == undefined || user == "undefined") {
    let url = "/sign-up/" ;
    if (lang == "zh"){
      url = `/${lang}/sign-up/`
    }
    let r = "";
    if (match && match.length > 1) {
      var contentAfterCom = match[1];
      r = contentAfterCom;
    }
    
    window.location.href = url +"?r=" + r
  } else {
    window.open(requestApi+`/recharge/${lang}/${session}/${total}`) ;

  }
}

const couponCuttime = async () => {

  const res = await $POST("/v1/coupons");
  if(res.code!=0)return;
  const coupons = res.data.coupons;
  let HTML = ''
  if(coupons.length > 0){
    coupons.forEach(coupon => {
      HTML += `
        <div>
          <p>
            <span>${coupon.value}</span>
            <span>${coupon.value_tip}</span>
          </p>
          <div>
            <p>${coupon.title}</p>
            <p>${expiredTxt}: <span>${coupon.expired}</span></p>
          </div>
        </div>
      `;
    });

    $('.counpin-list').html(HTML)


    $('.coupon-pop').show();
    const countdown = createCountdown(res.data.surplus_time, '.coupon_countdown');
    countdown.start();

    $('.coupon-pop').on('click', function(e){
      $(".coupon-model").show();
    })

  }
};



function createCountdown(totalSeconds, targetSelector) {
  const $target = $(targetSelector);
  let timer;

  const formatTime = (time) => String(time).padStart(2, '0');
  const update = () => {
      const h = formatTime(Math.floor(totalSeconds / 3600));
      const m = formatTime(Math.floor((totalSeconds % 3600) / 60));
      const s = formatTime(totalSeconds % 60);
      $target.text(`${h}:${m}:${s}`);
  };

  const start = () => {
      update();
      timer = setInterval(() => {
          totalSeconds > 0 ? (totalSeconds--, update()) : (clearInterval(timer), $target.hide());
      }, 1000);
  }; 

  const stop = () => clearInterval(timer);

  return { start, stop };
}




// couponCuttime();
