$(function(){
  
  
  if(location.href.includes('pricing/unlimit-proxies/')){
    const partnersDOM = document.querySelector(".partner_list_main");
    vhInfiniteLoop.init(partnersDOM, true, 0.4);
  }
 
  $('.static_buy').click(orderNowFn);

  $('.dropdown_ports>.dropdown-toggle,.dropdown_bandwidth>.dropdown-toggle,.dropdown_area>.dropdown-toggle').on('click', function(){
    $(this).next('.dropdown-menu').toggle();
    $(this).toggleClass("active");
    $(this).parents('.unlimt-detail').siblings().find('.dropdown-toggle').removeClass('active');
    $(this).parents('.unlimt-detail').siblings().find('.dropdown-menu').hide();

    $(this).parents('.dropdown').siblings('.dropdown').find('.dropdown-toggle').removeClass('active');
    $(this).parents('.dropdown').siblings('.dropdown').find('.dropdown-menu').hide();
  })

  $('.dropdown_ports>.dropdown-menu>li').click(portDropdownFn);
  $('.dropdown_bandwidth>.dropdown-menu>li').click(portBandDropdownFn);
  $('.dropdown_area>.dropdown-menu>li').click(areaDropdownFn);
  
  $(document).on('click', '.order_btn_link', orderLinkFn);

  $(document).on('click', function (e) {
    if (!$(e.target).closest('.dropdown').length) {
      $('.dropdown>.dropdown-menu').hide();
      $('.dropdown>.dropdown-toggle').removeClass('active');
    }
  });

  $('.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');
    $('.ublimit_proxy_container>div').eq(index).show().siblings().hide();
    $('.unlimit-proxy-list').eq(index).show().siblings('.unlimit-proxy-list').hide();
  })
})
const portDropdownFn = (e) => {
  const PORTDOM = $(e.currentTarget);
  const costMoney = PORTDOM.data('costmoney');
  const money = PORTDOM.data('money');
  const parentDiv = PORTDOM.closest('div[data-sn]');
  const portCostMoney = parentDiv.find('.port_cost_money');
  const portMoney = parentDiv.find('.port_money');
  portCostMoney.text(costMoney);
  portMoney.text(money);
  parentDiv.find('.unit_money').text(PORTDOM.data('price'))
  const dropdown = PORTDOM.closest('.dropdown');
  const toggleSpan = dropdown.find('.dropdown-toggle span');
  toggleSpan.text(PORTDOM.text());
  PORTDOM.parent('.dropdown-menu').hide();
  dropdown.find('.dropdown-toggle').removeClass('active');
  parentDiv.data('sn', PORTDOM.data('sn'));
}

const portBandDropdownFn = (e) => {
  const PORTDOM = $(e.currentTarget);
  const parentDiv = PORTDOM.closest('div[data-sn]');
  const dropdown = PORTDOM.closest('.dropdown');
  const toggleSpan = dropdown.find('.dropdown-toggle span');
  toggleSpan.text(PORTDOM.text());
  PORTDOM.parent('.dropdown-menu').hide();
  dropdown.find('.dropdown-toggle').removeClass('active');
  parentDiv.data('day', PORTDOM.data('value'));
  queryBaindWidthInfo(parentDiv.data('regions'), PORTDOM.data('value'),parentDiv.data('name'),PORTDOM);
}

const areaDropdownFn = (e) => {
  const PORTDOM = $(e.currentTarget);
  const parentDiv = PORTDOM.closest('div[data-sn]');
  const dropdown = PORTDOM.closest('.dropdown');
  const toggleSpan = dropdown.find('.dropdown-toggle span');
  toggleSpan.text(PORTDOM.text());
  PORTDOM.parent('.dropdown-menu').hide();
  dropdown.find('.dropdown-toggle').removeClass('active');
  parentDiv.data('regions', PORTDOM.data('value'));
  queryBaindWidthInfo(PORTDOM.data('value'), parentDiv.data('day'),parentDiv.data('name'),PORTDOM);
}

const queryBaindWidthInfo = async(region,hours,value,PORTDOM) => {
  const res = await $POST("/v1/orderPriceSwitch",{region, value, hour: hours});
  if(res.code!=0) return messageFn(res.msg);
  const parentDiv = PORTDOM.closest('div[data-sn]');
  parentDiv.find('.unit_money').text(res.data.price);
  parentDiv.find('.port_cost_money').text(res.data.cost_money);
  parentDiv.find('.port_money').text(res.data.money);
  parentDiv.find('.ubind_hour').text(res.data.unit);
  
  parentDiv.data('sn', res.data.sn);

}


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.closest('div[data-sn]').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 {
    
    
    if(submitFlag1) return;
    submitFlag1 = true;
    const res = await $POST("/v1/orderUnlimit ", { sn, lang });
    submitFlag1 = false;
    if(res.code!=0)return messageFn(res.msg);
    settime();
    check_time = setInterval(function () {
      checkpay()
    }, 3000);
    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);
}

const orderNowFn = async (e) => {
  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 {
    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();
