
// let NAV_MENU_STATUS = false;
const requestApi = `${window.location.protocol}//${window.location.host}`;
let kwdValue = new URLSearchParams(window.location.search).get('kwd');
let invitCode = new URLSearchParams(window.location.search).get('code');


if (kwdValue) {
  localStorage.setItem("keyword", kwdValue);
  kwd(kwdValue)
}
if(invitCode){
  localStorage.setItem("invitCode", invitCode);
}
const $POST = async (u, d) => $.post(requestApi + u, { ...d,lang:$('#language').val(),token: localStorage.getItem("session") || "" });

const nav_en_init = async () => {

  if ($(document).scrollTop() > 44) {
    $(".nav_header").addClass("active");
  }
  $(document).on("scroll", function () {
    if ($(document).scrollTop() > 44) {
      $(".nav_header").addClass("active");
    } else {
      $(".nav_header").removeClass("active");
    }
  });

  $('.m-menu-list-main>.m-menu-list-item').on('click', function () {
    
  });
  $(".m-menu-list-main>.m-menu-list-item").click((e) => {
    const DOM = $(e.currentTarget).parent()[0];
    if ($(DOM).hasClass("active")) return $(DOM).removeClass("active");
    $(DOM).addClass("active").siblings(".m-menu-list-main").removeClass("active");
  });

  $('.mobile_menu').on('click',function(){
    $('.header_container>.m-menu-list').show();
  })

  $('.m-menu-list-hesder>img').on('click',function(){
    $('.header_container>.m-menu-list').hide();
  })


  $('.m-menu-list-hesder img, .nav-small-screen .bg').on('click',function(){
      $('.nav-small-screen').removeClass('active');
      $('.nav-small-screen>.bg').fadeOut();
    
  })

  $('.faq-list>div:nth-of-type(1)').on('click',function(e){
    e.stopPropagation();
    $(this).siblings().slideToggle(200);
    $(this).parents(".faq-list").toggleClass("on");
    $(this).parents(".faq-list").siblings().find("div:nth-of-type(2)").slideUp(200);
    $(this).parents(".faq-list").siblings().removeClass("on");
  })

  await checkLoginFn();
  // logout login
  $(".infobtn.user>.user-panel>em").click(sinOutFn);
  $(".vh-middle-logout").click(sinOutFn);
  $(".m-logout").click(sinOutFn);

  $('.change_price_case>li').click(changeProxyFn)

 

  // vh.getUrlParams("invite") && sessionStorage.setItem("invite", vh.getUrlParams("invite"));

  $(".proxy_nav_banner>img").on("click", function () {
    $(".proxy_nav_banner").hide();
  })
};

function getLanguageFromUrl(url = window.location.href, defaultLang = 'en') {
  const match = url.match(/\/([a-z]{2}|zh-tw)\/(?!\d)/); 
  return match? match[1] : defaultLang;
}
let shareLang = 'en'
window.addEventListener('load', function() {
  shareLang = getLanguageFromUrl();
  if(shareLang == 'zh'){
    shareLang = 'zh-tw';
  }
  
  const expiresDate = new Date();
  expiresDate.setDate(expiresDate.getDate() + 3000);
  const domain = window.location.host.split(".").slice(-2).join(".");
  Cookies.set("cli_lang", shareLang, { expires: expiresDate, domain });
});



const checkLoginFn = async () => {
  const session = localStorage.getItem("session");
  const user = localStorage.getItem("user");
  if (!session || !user || user == undefined || user == "undefined") {
    
    $(".infobtn.haveinfo").hide().siblings(".infobtn").css('display', 'flex');
    $('.m-l-item-btn>.m-no-login').show().siblings('.m-have-login').hide();
    localStorage.removeItem("session");
    localStorage.removeItem("user");
  } else {
    let center_url = $("#centerUrl").val()+'/cli/isp-user';
    $('.banner_free_link').attr('href', center_url);
    const userDOM = $(".infobtn.haveinfo");
    userDOM.find(">a").html(JSON.parse(user).email);
    userDOM.find(".user-panel>span>i").text(JSON.parse(user).email);
    $('.m-have-login>a').html(JSON.parse(user).email);
    userDOM.css({ display: "flex" }).siblings(".infobtn").hide();
    $('.m-l-item-btn>.m-no-login').hide().siblings('.m-have-login').show();

  }
};

// logout login
const sinOutFn = async (e) => {

  const res = await $POST("/v1/signout");

  messageFn(res.msg);
  $(e.currentTarget).parent().css("pointer-events", "none").parent().css("pointer-events", "none");
  localStorage.removeItem("session");
  localStorage.removeItem("user");
  const domain = window.location.host.split(".").slice(-2).join(".");
  Cookies.set("common_session", "null", { domain });
  location.reload();
};
const updateLink = () => {

  const link = $('.tlinks');
  if (!link) return;
  const utcHour = new Date().getUTCHours();
  const { href } = utcHour >= 14 && utcHour <= 23 ? LINKS.evening : LINKS.daytime;
  link.attr('href', href);
  $('.tlinks-email').html(href);
};

$(function () {
  // updateLink();
  nav_en_init();
  currntPageShow();
  $('.copy_tmemail').click(function () {
    const email = $('.tlinks-email').text();
    copyText(email);
  });

});

const currntPageShow = async () => {
  const domain = window.location.host.split(".").slice(-2).join(".");
  const c_token = Cookies.get("common_session");
  const local_session = localStorage.getItem("session");
  if (c_token == "null" || c_token == undefined || c_token == '') {
    if (!local_session) return;
    window.stop();
    
    Cookies.set("common_session", "", { domain });
    localStorage.removeItem("session");
    localStorage.removeItem("user");
    setTimeout(() => {
      location.reload();
    }, 100);
  } else if (c_token && c_token.length > 6) {
    if (local_session) return;
    localStorage.setItem("session", c_token);
    const res = await $POST("/v1/webauto", { session: c_token });
    if (res.code != 0) {
      localStorage.removeItem("session");
      localStorage.removeItem("user");
      const domain = window.location.host.split(".").slice(-2).join(".");
      Cookies.set("common_session", "null", { domain });
      return;
    }
    localStorage.setItem('session',res.data.token);
    localStorage.setItem("user", JSON.stringify(res.data));
    setTimeout(() => {
      location.reload();
    }, 666);
  }
};

const LINKS = {
  evening: { href: 'https://t.me/cliproxybd'},
  daytime: { href: 'https://t.me/webipme'}
};


window.addEventListener("visibilitychange", () => document.visibilityState === "visible" && currntPageShow());



const messageData = {
   handle: null,
   delayTime: 3000,
   obj: []
}
const messageFn= async (v) => {
  clearTimeout(messageData.handle);
  // Clean box
  var removeObj = setTimeout(function () {
  $(".lo_message").removeClass("on");
  }, 0);

  var newTime = "lo_" + new Date().getTime();
  var message = $('<div class="lo_message ' + newTime + '"><span>' + v + "</span></div>");
  $(document.body).append(message);

  var addObj = setTimeout(function () {
  $("." + newTime).addClass("on");
  }, 2);

  messageData.handle = setTimeout(function () {
  $(".lo_message").remove();
  }, messageData.delayTime);
}

const changeProxyFn = async (e) => {
  const DOM = $(e.currentTarget);
  DOM.addClass("active").siblings().removeClass("active");
  const index = DOM.index();
  $('.price_case_content').eq(index).css('display','flex').siblings('.price_case_content').hide();
}


const setStorage = (key, value, ttl_ms) => {
  var data = { value: value, exprice: new Date(ttl_ms).getTime() };
  sessionStorage.setItem(key, JSON.stringify(data));
}

const getStorage = (key) => {
  var data = JSON.parse(sessionStorage.getItem(key));
  if (data !== null) {
    if (data.exprice != null && data.exprice - new Date().getTime() < 0) {
      sessionStorage.removeItem(key);
      return [];
    } else {
      return data.value;
    }
  }
}

const countDownTime =() =>{
  const now = Date.now();
    const endOfDay = new Date().setHours(23, 59, 59, 999);
    const diff = endOfDay - now;
    const [hour, min, sec] = [
        Math.floor(diff / 1000 / 3600).toString().padStart(2, '0'),
        Math.floor((diff % (1000 * 3600)) / 1000 / 60).toString().padStart(2, '0'),
        Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0')
    ];
    $(".countdown").html(`${hour}:${min}:${sec}`);
    
    setTimeout(countDownTime, 1000);
}

function countdown(endTimes) {
  const update = () => {
    const now = Date.now();
    endTimes.forEach((endTime, index) => {
      const diff = endTime - now;
      if (diff <= 0) {
        return;
      }
      const days = Math.floor(diff / (1000 * 3600 * 24));
      const hours = Math.floor((diff % (1000 * 3600 * 24)) / (1000 * 3600)).toString().padStart(2, '0');
      const minutes = Math.floor((diff % (1000 * 3600)) / (1000 * 60)).toString().padStart(2, '0');
      const seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');
      
      $(`.coming_soon_days_${index}`).html(days);
      $(`.itime`).html(hours);
      $(`.imin`).html(minutes);
      $(`.isec`).html(seconds);
      $(`.iday`).html(days);
    });
  };
  const timer = setInterval(update, 1000);
  update();
}

// crontab
const endTimes = [
  new Date('2025-07-15T00:00:00').getTime(),
  new Date('2025-07-15T00:00:00').getTime(),
  new Date('2025-07-15T00:00:00').getTime()
];
countdown(endTimes);
// countdown(endTine);
// countdown(endActiveTime);
const copyText = (str) =>{
  var save = function (e) {
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  };
  document.addEventListener("copy", save);
  document.execCommand("copy");
  document.removeEventListener("copy", save);
  messageFn("Copied to clipboard");
}


function kwd(kword){
  var xhr = new XMLHttpRequest();

  xhr.open('POST', requestApi + '/v1/kwd', true);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        console.log(xhr.responseText);
      } else {

      }
    }
  };
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('kwd='+kword);
}