const swiper = new Swiper(".mySwiper", {
  slidesPerView: 7,
  spaceBetween: 30,
  loop: false,
  speed: 550,
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
  },
  breakpoints: {
    // when window width is >= 320px
    320: {
      slidesPerView: 1,
      spaceBetween: 10,
    },
    // when window width is >= 480px
    480: {
      slidesPerView: 2,
      spaceBetween: 15,
    },
    // when window width is >= 640px
    640: {
      slidesPerView: 3,
      spaceBetween: 20,
    },
    768: {
      slidesPerView: 4,
      spaceBetween: 20,
    },
    1024: {
      slidesPerView: 5,
      spaceBetween: 20,
    },
    1200: {
      slidesPerView: 7,
      spaceBetween: 20,
    },
  },
  on: {
    slideChangeTransitionStart() {
      document.querySelector(".swiper_parent").classList.add("show_b");
    },
    // لما يخلص الحركة
    slideChangeTransitionEnd() {
      document.querySelector(".swiper_parent").classList.remove("show_b");
    },
  },
});
const swiper_organize = new Swiper(".organize_slider", {
  slidesPerView: 1,
  // spaceBetween: 30,
  loop: true,
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
  },
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
  },
});

// =========================
// Translation
let card_game_Ar = document.getElementById("card_game_Ar");
let card_game_en = document.getElementById("card_game_en");
let mobile_Ar = document.getElementById("mobile_Ar");
let mobile_en = document.getElementById("mobile_en");
let cosplay_Ar = document.getElementById("cosplay_Ar");
let cosplay_en = document.getElementById("cosplay_en");
let ticketing_btn_en = document.getElementById("ticketing_bnt_en");
let ticketing_ar = document.getElementById("ticketing_ar");
let ticketing_btn1 = document.getElementById("ticketing_btn1");
let ticketing_section_ar = document.getElementById("ticketing_section_ar");
let ticketing_section = document.getElementById("ticketing_section");
let vr_section = document.getElementById("vr_section_p");
let vr_section_en = document.getElementById("vr_section_en_p");
let casual_av_ar = document.getElementById("casual_av_ar");
let casual_en = document.getElementById("casual_en");
let hero_en = document.getElementById("hero_en");
let hero_ar = document.getElementById("hero_ar");
let Vr_zone_en = document.getElementById("Vr_zone_en");
let Vr_zone_AR = document.getElementById("Vr_zone_AR");
let playable_games_title = document.getElementById("playable_games_title");
let esports_title = document.getElementById("esports_title");
let e_sport_btn = document.getElementById("e_sport_btn");
let header = document.getElementById("header");
let Ar_flag = true;
let user_email = document.getElementById("email");
let user_phone = document.getElementById("phone");
let book_now1 = document.getElementById("book_now1");

function changeLanguage(lang) {
  // console.log("function")

  if (lang === "ar") {
    Ar_flag = true;
    card_game_en.classList.add("hidden1");
    card_game_Ar.classList.remove("hidden1");
    mobile_en.classList.add("hidden1");
    mobile_Ar.classList.remove("hidden1");
    cosplay_en.classList.add("hidden1");
    cosplay_Ar.classList.remove("hidden1");
    ticketing_btn_en.classList.add("hidden1");
    ticketing_ar.classList.remove("hidden1");
    ticketing_section_ar.classList.remove("hidden1");
    ticketing_section.classList.add("hidden1");
    vr_section_en.classList.add("hidden1");
    vr_section.classList.remove("hidden1");
    casual_av_ar.classList.remove("hidden1");
    casual_en.classList.add("hidden1");
    hero_ar.classList.remove("hidden1");
    hero_en.classList.add("hidden1");
    Vr_zone_AR.classList.remove("hidden1");
    Vr_zone_en.classList.add("hidden1");
    ticketing_btn1.innerHTML = " ticketing";
    esports_title.classList.remove("En_font");
    ticketing_btn1.classList.remove("En_font");
    e_sport_btn.classList.remove("En_font");
    playable_games_title.classList.remove("En_font");
    playable_games_title.innerHTML = "الألعاب المتاحه";
    esports_title.innerHTML = " بطولات الرياضات الالكترونية";
    e_sport_btn.innerHTML = "احجز الان";
    ticketing_btn1.innerHTML = " التذاكر";

    document.querySelector(".en_lang").classList.add("colored");
    document.querySelector(".en_lang1").classList.add("colored");
    document.querySelector(".ar_lang").classList.remove("colored");
    document.querySelector(".ar_lang1").classList.remove("colored");
  } else {
    Ar_flag = false;
    card_game_en.classList.remove("hidden1");
    card_game_Ar.classList.add("hidden1");
    mobile_en.classList.remove("hidden1");
    mobile_Ar.classList.add("hidden1");
    cosplay_en.classList.remove("hidden1");
    cosplay_Ar.classList.add("hidden1");
    ticketing_btn_en.classList.remove("hidden1");
    ticketing_ar.classList.add("hidden1");
    ticketing_section_ar.classList.add("hidden1");
    ticketing_section.classList.remove("hidden1");
    vr_section_en.classList.remove("hidden1");
    vr_section.classList.add("hidden1");
    casual_av_ar.classList.add("hidden1");
    casual_en.classList.remove("hidden1");
    hero_ar.classList.add("hidden1");
    hero_en.classList.remove("hidden1");
    Vr_zone_AR.classList.add("hidden1");
    Vr_zone_en.classList.remove("hidden1");
    playable_games_title.classList.add("En_font");
    esports_title.classList.add("En_font");
    e_sport_btn.classList.add("En_font");
    ticketing_btn1.classList.add("En_font");
    //  e_sport_btn.classList.remove("En_font")
    ticketing_btn1.innerHTML = "Ticketing";
    playable_games_title.innerHTML = " Playable games";
    esports_title.innerHTML = "E-Sports tournaments";
    e_sport_btn.innerHTML = "Book now";

    document.querySelector(".en_lang").classList.remove("colored");
    document.querySelector(".en_lang1").classList.remove("colored");
    document.querySelector(".ar_lang").classList.add("colored");
    document.querySelector(".ar_lang1").classList.add("colored");
  }
}

// window.onload=function()
// {
//   changeLanguage("en")
// }

document
  .querySelector(".en_lang")
  .addEventListener("click", () => changeLanguage("en"));
document
  .querySelector(".en_lang1")
  .addEventListener("click", () => changeLanguage("en"));
document
  .querySelector(".ar_lang")
  .addEventListener("click", () => changeLanguage("ar"));
document
  .querySelector(".ar_lang1")
  .addEventListener("click", () => changeLanguage("ar"));
// =========================
// ==========List Logic===============
let list_btn = document.getElementById("open_list");
let list = document.querySelector(".right_side_h");
let buttons = document.querySelectorAll(".right_side_h a");
let opened = false;
buttons.forEach((button) => {
  button.addEventListener("click", () => {
    list.classList.add("hidden");
    header.classList.remove("PB");
    opened = false;
  });
});
list_btn.onclick = function () {
  list.classList.toggle("hidden");
  if (!list.classList.contains("hidden")) {
    header.classList.add("PB");
    opened = true;
  } else {
    header.classList.remove("PB");
    opened = false;
  }
};
let lastScrollTop = 0;

window.addEventListener("scroll", function () {
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

  if (scrollTop > lastScrollTop) {
    list.classList.add("hidden");
    header.classList.remove("PB");
    opened = false;
  }

  lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
});

window.addEventListener("resize", function () {
  list.classList.add("hidden");
  opened = false;
  header.classList.remove("PB");
});
document.addEventListener("click", (e) => {
  if (!list.contains(e.target) && e.target != list_btn) {
    // console.log(opened)
    list.classList.add("hidden");
    header.classList.remove("PB");
  }
});
// ======================= Organize Logic
function openNewWindow(url, target) {
  if (target == "self") {
    window.open(url, "_self");
    history.pushState(
      "",
      document.title,
      window.location.pathname + window.location.search
    );
  } else window.open(url, "_blank");
}
e_sport_btn.onclick = function () {
  const targetId = Ar_flag ? "ticketing_section_ar" : "ticketing_section";
  const target = document.getElementById(targetId);

  if (target) {
    target.scrollIntoView({ behavior: "smooth" });

    history.pushState(
      "",
      document.title,
      window.location.pathname + window.location.search
    );
  }
};
function gotoTic(targetId) {
  const target = document.getElementById(targetId);

  if (target) {
    target.scrollIntoView({ behavior: "smooth" });

    history.pushState(
      "",
      document.title,
      window.location.pathname + window.location.search
    );
  }
}

ticketing_btn1.onclick = function () {
  const targetId = Ar_flag ? "ticketing_section_ar" : "ticketing_section";
  const target = document.getElementById(targetId);

  if (target) {
    target.scrollIntoView({ behavior: "smooth" });

    history.pushState(
      "",
      document.title,
      window.location.pathname + window.location.search
    );
  }
};
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function sendEmail(event) {
  event.preventDefault();
  if (!user_email.value || !user_phone.value) notify();
  else if (!emailPattern.test(user_email.value)) notify1();
  else {
    var Params = {
      email: user_email.value,
      phone: user_phone.value,
    };
    const servieceID = "service_n1e464q";
    const templateID = "template_3dejf6d";
    emailjs
      .send(servieceID, templateID, Params)
      .then((res) => {
        document.getElementById("email").value = "";
        document.getElementById("phone").value = "";
        notifyS();
      })
      .catch((error) => console.log("Error : ", error));
  }
}
function openWhatsApp() {
  const phone = "96595504919"; // full number, no '+'
  const appUrl = `whatsapp://send?phone=${phone}`;
  const webUrl = `https://wa.me/${phone}`;

  const ua = navigator.userAgent.toLowerCase();
  const isAndroid = ua.includes("android");
  const isIOS = /iphone|ipad|ipod/.test(ua);

  window.location.href = appUrl;

  setTimeout(() => {
    if (isAndroid) {
      window.location.href = webUrl;
    } else if (isIOS) {
      window.location.href = webUrl;
    } else {
      window.open(webUrl, "_blank");
    }
  }, 800);
}

function notify() {
  Toastify({
    text: "Email and Phone required",
    duration: 3000,
    gravity: "top",
    position: "right",
    backgroundColor: "red",
  }).showToast();
}
function notify1() {
  Toastify({
    text: " invalid Email",
    duration: 3000,
    gravity: "top",
    position: "right",
    backgroundColor: "red",
  }).showToast();
}
function notifyS() {
  Toastify({
    text: "Form submitted successfully!",
    duration: 3000,
    gravity: "top",
    position: "right",
    backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
  }).showToast();
}
function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
// 1. دالة مساعدة لجلب الكوكيز (عشان الـ Server-Side Tracking)
function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(";").shift();
  return null;
}

function tracking(price) {
  const uniqueEventID = generateUUID();

  const fbp = getCookie("_fbp");
  const fbc = getCookie("_fbc");
  const ttp = getCookie("_ttp");

  console.log("Event Fired with ID:", uniqueEventID);

  if (typeof fbq !== "undefined") {
    fbq("track", "InitiateCheckout", {}, { eventID: uniqueEventID });
  }

  if (typeof ttq !== "undefined") {
    ttq.track("InitiateCheckout", { event_id: uniqueEventID });
  }

  if (typeof snaptr !== "undefined") {
    snaptr("track", "START_CHECKOUT", { event_id: uniqueEventID });
  }

  fetch("http://localhost:3000/api/track", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      event_name: "InitiateCheckout",
      event_id: uniqueEventID,
      value: price,
      currency: "KD",
      fbp: fbp,
      fbc: fbc,
      ttp: ttp,
    }),
  })
    .then((response) => {
      console.log("response", response);
    })
    .catch((err) => {
      console.error("Server-Side Error:", err);
    });
}
function trackingContact() {
  const uniqueEventID = generateUUID();

  const fbp = getCookie("_fbp");
  const fbc = getCookie("_fbc");
  const ttp = getCookie("_ttp");

  console.log("Contact Event Fired with ID:", uniqueEventID);

  if (typeof fbq !== "undefined") {
    fbq("track", "Contact", {}, { eventID: uniqueEventID });
  }

  // TikTok
  if (typeof ttq !== "undefined") {
    ttq.track("Contact", { event_id: uniqueEventID });
  }

  // Snapchat
  if (typeof snaptr !== "undefined") {
    snaptr("track", "VIEW_CONTENT", { event_id: uniqueEventID });
  }

  // --- B. Server-Side API (CAPI) ---
  fetch("http://localhost:3000/api/track", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      event_name: "Contact",
      event_id: uniqueEventID,
      value: 0,
      currency: "KD",
      fbp: fbp,
      fbc: fbc,
      ttp: ttp,
    }),
  })
    .then((response) => {
      if (response.ok) {
        console.log("✅ Contact Event sent to Server");
      }
    })
    .catch((err) => {
      console.error("Server-Side Error:", err);
    });
}
function trackPageView() {
  const uniqueEventID = generateUUID();

  const fbp = getCookie("_fbp");
  const fbc = getCookie("_fbc");
  const ttp = getCookie("_ttp");

  console.log("📄 PageView Fired with ID:", uniqueEventID);

  if (typeof fbq !== "undefined") {
    fbq("track", "PageView", {}, { eventID: uniqueEventID });
  }

  if (typeof snaptr !== "undefined") {
    snaptr("track", "PAGE_VIEW", { event_id: uniqueEventID });
  }

  fetch("http://localhost:3000/api/track", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      event_name: "PageView",
      event_id: uniqueEventID,
      value: 0,
      currency: "KD",
      fbp: fbp,
      fbc: fbc,
      ttp: ttp,
    }),
  })
    .then((res) => {
      if (res.ok) console.log("✅ Server PageView Sent");
    })
    .catch((err) => console.error("Server PageView Error:", err));
}

trackPageView();
