/** ==========================================================
Slider
===========================================================**/

document.addEventListener("DOMContentLoaded", function () {
  const animatedElements = document.querySelectorAll(
    ".side-image-layout, .qualifications-section"
  );
  function checkScroll() {
    animatedElements.forEach((element) => {
      if (element) {
        const elementPosition = element.getBoundingClientRect().top;
        const screenPosition = window.innerHeight / 1.3;
        if (elementPosition < screenPosition) {
          element.classList.add("show");
        }
      }
    });
  }
  window.addEventListener("scroll", checkScroll);
  checkScroll();
});

/** ==========================================================
Sroll Animation
===========================================================**/
document.addEventListener("DOMContentLoaded", () => {
  const reveals = document.querySelectorAll(".reveal");
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("show");
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.2 }
  );
  reveals.forEach((el) => observer.observe(el));
});

document.addEventListener("DOMContentLoaded", () => {
  const cards = document.querySelectorAll(".currency-card");
  const revealOnScroll = () => {
    cards.forEach((card) => {
      const cardTop = card.getBoundingClientRect().top;
      if (cardTop < window.innerHeight - 50) {
        card.classList.add("show");
      }
    });
  };
  window.addEventListener("scroll", revealOnScroll);
  revealOnScroll();
});

/** ==========================================================
Forex and Calculator 
===========================================================**/

// Currency Calculator Functionality
document.addEventListener("DOMContentLoaded", function () {
  // Exchange rates (simplified for demo)
  const exchangeRates = {
    UGX: {
      USD: 1 / 3500,
      EUR: 1 / 4100,
      GBP: 1 / 4800,
      KES: 1 / 28,
      TZS: 1 / 1.5,
      ZAR: 1 / 220,
      INR: 1 / 40,
    },
    USD: {
      UGX: 3500,
      EUR: 0.85,
      GBP: 0.75,
      KES: 110,
      TZS: 2300,
      ZAR: 15,
      INR: 75,
    },
    EUR: {
      UGX: 4100,
      USD: 1.18,
      GBP: 0.88,
      KES: 130,
      TZS: 2700,
      ZAR: 18,
      INR: 88,
    },
    GBP: {
      UGX: 4800,
      USD: 1.33,
      EUR: 1.14,
      KES: 150,
      TZS: 3100,
      ZAR: 20,
      INR: 100,
    },
    KES: {
      UGX: 28,
      USD: 0.0091,
      EUR: 0.0077,
      GBP: 0.0067,
      TZS: 20,
      ZAR: 0.13,
      INR: 0.67,
    },
    TZS: {
      UGX: 1.5,
      USD: 0.00043,
      EUR: 0.00037,
      GBP: 0.00032,
      KES: 0.05,
      ZAR: 0.0067,
      INR: 0.033,
    },
    ZAR: {
      UGX: 220,
      USD: 0.067,
      EUR: 0.056,
      GBP: 0.05,
      KES: 7.5,
      TZS: 150,
      INR: 5,
    },
    INR: {
      UGX: 40,
      USD: 0.013,
      EUR: 0.011,
      GBP: 0.01,
      KES: 1.5,
      TZS: 30,
      ZAR: 0.2,
    },
  };

  const amountInput = document.getElementById("amount");
  const fromCurrency = document.getElementById("from-currency");
  const toCurrency = document.getElementById("to-currency");
  const convertedAmount = document.getElementById("converted-amount");

  // Only initialize calculator if elements exist
  if (amountInput && fromCurrency && toCurrency && convertedAmount) {
    function calculateExchange() {
      const amount = parseFloat(amountInput.value);
      const from = fromCurrency.value;
      const to = toCurrency.value;

      if (isNaN(amount) || amount <= 0) {
        convertedAmount.textContent = "0.00";
        return;
      }

      let result;
      if (from === to) {
        result = amount;
      } else {
        // For demo purposes - in a real application, you would use current rates from an API
        result = amount * exchangeRates[from][to];
      }

      convertedAmount.textContent = result.toFixed(2);
    }

    amountInput.addEventListener("input", calculateExchange);
    fromCurrency.addEventListener("change", calculateExchange);
    toCurrency.addEventListener("change", calculateExchange);

    // Initialize calculation only when calculator exists
    try {
      calculateExchange();
    } catch (err) {
      // Defensive: if something goes wrong, avoid breaking other scripts
      console &&
        console.warn &&
        console.warn("calculateExchange init failed:", err);
    }
  }

  // FAQ Toggle Functionality
  const faqItems = document.querySelectorAll(".faq-item");

  if (faqItems.length > 0) {
    faqItems.forEach((item) => {
      const question = item.querySelector(".faq-question");

      if (question) {
        question.addEventListener("click", () => {
          // Close all items first
          faqItems.forEach((i) => {
            if (i !== item) {
              i.classList.remove("active");
            }
          });

          // Toggle the clicked one
          item.classList.toggle("active");
        });
      }
    });
  }
});

// /** ==========================================================
// TEAM MODAL
// ===========================================================**/

// document.addEventListener("DOMContentLoaded", function () {
//   // Get all modal buttons
//   const modalButtons = document.querySelectorAll(".card-button");
//   const modals = document.querySelectorAll(".modal");
//   const closeButtons = document.querySelectorAll(".close-modal");

//   // Only initialize modal functionality if elements exist
//   if (modalButtons.length > 0 && modals.length > 0 && closeButtons.length > 0) {
//     // Open modal when button is clicked
//     modalButtons.forEach((button) => {
//       button.addEventListener("click", () => {
//         const modalId = button.getAttribute("data-modal");
//         const modal = document.getElementById(modalId);
//         if (modal) {
//           modal.classList.add("show");
//           document.body.style.overflow = "hidden"; // Prevent scrolling
//         }
//       });
//     });

//     // Close modal when close button is clicked
//     closeButtons.forEach((button) => {
//       button.addEventListener("click", () => {
//         const modal = button.closest(".modal");
//         if (modal) {
//           modal.classList.remove("show");
//           document.body.style.overflow = ""; // Enable scrolling
//         }
//       });
//     });

//     // Close modal when clicking outside the modal content
//     modals.forEach((modal) => {
//       modal.addEventListener("click", (e) => {
//         if (e.target === modal) {
//           modal.classList.remove("show");
//           document.body.style.overflow = ""; // Enable scrolling
//         }
//       });
//     });

//     // Close modal with Escape key
//     document.addEventListener("keydown", (e) => {
//       if (e.key === "Escape") {
//         modals.forEach((modal) => {
//           if (modal.classList.contains("show")) {
//             modal.classList.remove("show");
//             document.body.style.overflow = ""; // Enable scrolling
//           }
//         });
//       }
//     });
//   }
// });

/** ==========================================================
MOBILE MENU
===========================================================**/

document.addEventListener("DOMContentLoaded", function () {
  const mobileToggle = document.getElementById("mobileToggle");
  const mobileMenuContainer = document.getElementById("mobileMenuContainer");
  const closeMenu = document.getElementById("closeMenu");
  const mobileMenuItems = document.querySelectorAll(".mobile-menu-item");

  // Only initialize mobile menu if elements exist
  if (
    mobileToggle &&
    mobileMenuContainer &&
    closeMenu &&
    mobileMenuItems.length > 0
  ) {
    // Toggle mobile menu
    mobileToggle.addEventListener("click", function () {
      mobileMenuContainer.style.display = "block";
      setTimeout(() => {
        mobileMenuContainer.style.opacity = "1";
        document.querySelector(".mobile-menu").style.right = "0";
      }, 10);
      document.body.style.overflow = "hidden";
    });

    // Close mobile menu
    closeMenu.addEventListener("click", closeMobileMenu);
    mobileMenuContainer.addEventListener("click", function (e) {
      if (e.target === mobileMenuContainer) {
        closeMobileMenu();
      }
    });

    function closeMobileMenu() {
      mobileMenuContainer.style.opacity = "0";
      document.querySelector(".mobile-menu").style.right = "-300px";
      setTimeout(() => {
        mobileMenuContainer.style.display = "none";
      }, 300);
      document.body.style.overflow = "auto";
    }

    // Toggle dropdowns in mobile menu
    mobileMenuItems.forEach((item) => {
      item.addEventListener("click", function (e) {
        const targetId = this.getAttribute("data-target");

        if (targetId) {
          // ✅ only block clicks for dropdown parents
          e.preventDefault();

          const dropdownContent = document.getElementById(targetId);
          const arrow = this.querySelector(".dropdown-arrow");

          // Close all other dropdowns
          document
            .querySelectorAll(".mobile-dropdown-content")
            .forEach((content) => {
              if (content !== dropdownContent) content.classList.remove("show");
            });

          document.querySelectorAll(".dropdown-arrow").forEach((otherArrow) => {
            if (otherArrow !== arrow) otherArrow.classList.remove("rotated");
          });

          // Toggle current dropdown
          if (dropdownContent) {
            dropdownContent.classList.toggle("show");
          }
          if (arrow) {
            arrow.classList.toggle("rotated");
          }
        }
      });
    });

    // Handle window resize
    window.addEventListener("resize", function () {
      if (window.innerWidth > 900) {
        closeMobileMenu();
      }
    });
  }
});

/** ==========================================================
LOAN CALCULATOR
===========================================================**/
document.addEventListener("DOMContentLoaded", function () {
  // Get DOM elements
  const loanAmount = document.getElementById("loan-amount");
  const loanAmountRange = document.getElementById("loan-amount-range");
  const loanTerm = document.getElementById("loan-term");
  const loanTermRange = document.getElementById("loan-term-range");
  const interestRate = document.getElementById("interest-rate");
  const interestRateRange = document.getElementById("interest-rate-range");
  const calculateBtn = document.getElementById("calculate-btn");
  const resetBtn = document.getElementById("reset-btn");

  const monthlyPaymentEl = document.getElementById("monthly-payment");
  const totalPaymentEl = document.getElementById("total-payment");
  const totalInterestEl = document.getElementById("total-interest");

  // Only initialize loan calculator if elements exist
  if (
    loanAmount &&
    loanAmountRange &&
    loanTerm &&
    loanTermRange &&
    interestRate &&
    interestRateRange &&
    calculateBtn &&
    resetBtn &&
    monthlyPaymentEl &&
    totalPaymentEl &&
    totalInterestEl
  ) {
    // Sync range and number inputs
    loanAmount.addEventListener("input", () => {
      loanAmountRange.value = loanAmount.value;
      calculateLoan();
    });

    loanAmountRange.addEventListener("input", () => {
      loanAmount.value = loanAmountRange.value;
      calculateLoan();
    });

    loanTerm.addEventListener("input", () => {
      loanTermRange.value = loanTerm.value;
      calculateLoan();
    });

    loanTermRange.addEventListener("input", () => {
      loanTerm.value = loanTermRange.value;
      calculateLoan();
    });

    interestRate.addEventListener("input", () => {
      interestRateRange.value = interestRate.value;
      calculateLoan();
    });

    interestRateRange.addEventListener("input", () => {
      interestRate.value = interestRateRange.value;
      calculateLoan();
    });

    // Calculate loan function
    function calculateLoan() {
      const principal = parseFloat(loanAmount.value);
      const months = parseFloat(loanTerm.value);
      const yearlyRate = parseFloat(interestRate.value);

      if (
        isNaN(principal) ||
        isNaN(months) ||
        isNaN(yearlyRate) ||
        principal <= 0 ||
        months <= 0 ||
        yearlyRate <= 0
      ) {
        return;
      }

      // Convert yearly rate to monthly and percentage to decimal
      const monthlyRate = yearlyRate / 100 / 12;

      // Calculate monthly payment
      const x = Math.pow(1 + monthlyRate, months);
      const monthlyPayment = (principal * x * monthlyRate) / (x - 1);

      // Calculate total payment and total interest
      const totalPayment = monthlyPayment * months;
      const totalInterest = totalPayment - principal;

      // Update UI
      monthlyPaymentEl.textContent = `UGX ${monthlyPayment
        .toFixed(0)
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
      totalPaymentEl.textContent = `UGX ${totalPayment
        .toFixed(0)
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
      totalInterestEl.textContent = `UGX ${totalInterest
        .toFixed(0)
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
    }

    // Reset form function
    function resetForm() {
      loanAmount.value = 5000000;
      loanAmountRange.value = 5000000;
      loanTerm.value = 36;
      loanTermRange.value = 36;
      interestRate.value = 15;
      interestRateRange.value = 15;

      monthlyPaymentEl.textContent = "UGX 0";
      totalPaymentEl.textContent = "UGX 0";
      totalInterestEl.textContent = "UGX 0";
    }

    // Event listeners
    calculateBtn.addEventListener("click", calculateLoan);
    resetBtn.addEventListener("click", resetForm);

    // Initialize calculation
    calculateLoan();
  }
});

/** ==========================================================
REQUIREMENT TABS
===========================================================**/
document.addEventListener("DOMContentLoaded", function () {
  // Tab functionality for requirements section
  const tabHeaders = document.querySelectorAll(".tab-header");
  const tabContents = document.querySelectorAll(".tab-content");

  tabHeaders.forEach((header) => {
    header.addEventListener("click", () => {
      const tabId = header.getAttribute("data-tab");

      // Remove active class from all headers and contents
      tabHeaders.forEach((h) => h.classList.remove("active"));
      tabContents.forEach((c) => c.classList.remove("active"));

      // Add active class to clicked header and corresponding content
      header.classList.add("active");
      document.getElementById(tabId).classList.add("active");
    });
  });

  // FAQ toggle functionality
  const faqItems = document.querySelectorAll(".faq-item");

  faqItems.forEach((item) => {
    const question = item.querySelector(".faq-question");

    question.addEventListener("click", () => {
      item.classList.toggle("active");
    });
  });
});

document.addEventListener("DOMContentLoaded", function () {
  // Channel tabs functionality
  const channelTabs = document.querySelectorAll(".channel-tab");
  const channelContents = document.querySelectorAll(".channel-content");

  channelTabs.forEach((tab) => {
    tab.addEventListener("click", () => {
      const channelId = tab.getAttribute("data-channel");

      // Remove active class from all tabs and contents
      channelTabs.forEach((t) => t.classList.remove("active"));
      channelContents.forEach((c) => c.classList.remove("active"));

      // Add active class to clicked tab and corresponding content
      tab.classList.add("active");
      document.getElementById(`${channelId}-content`).classList.add("active");
    });
  });

  // Branch item hover effect
  const branchItems = document.querySelectorAll(".branch-item");

  branchItems.forEach((item) => {
    item.addEventListener("mouseenter", () => {
      item.style.transform = "translateY(-5px)";
      item.style.boxShadow = "0 10px 25px rgba(0, 0, 0, 0.1)";
    });

    item.addEventListener("mouseleave", () => {
      item.style.transform = "translateY(0)";
      item.style.boxShadow = "0 5px 15px rgba(0, 0, 0, 0.05)";
    });
  });
});

/** ==========================================================
MENU SCROLL STICKY
===========================================================**/
window.addEventListener("scroll", function () {
  const nav = document.querySelector(".main-nav");
  if (window.scrollY > 50) {
    nav.classList.add("scrolled");
  } else {
    nav.classList.remove("scrolled");
  }
});

document.addEventListener("DOMContentLoaded", function () {
  const tabButtons = document.querySelectorAll(".tab-button");
  const categoryContainers = document.querySelectorAll(".category-cards");

  // Function to switch tabs
  function switchTab(category) {
    // Update tab buttons
    tabButtons.forEach((button) => {
      if (button.getAttribute("data-category") === category) {
        button.classList.add("active");
      } else {
        button.classList.remove("active");
      }
    });

    // Show selected category, hide others
    categoryContainers.forEach((container) => {
      if (container.id === `${category}-cards`) {
        container.classList.add("active");
      } else {
        container.classList.remove("active");
      }
    });
  }

  // Add event listeners to tab buttons
  tabButtons.forEach((button) => {
    button.addEventListener("click", function () {
      const category = this.getAttribute("data-category");
      switchTab(category);
    });
  });
});
