// ====== pre-loader ======
document.addEventListener("DOMContentLoaded", function () {
  var preloader = document.createElement("div");
  preloader.className = "preloader";

  var logo = document.createElement("div");
  logo.className = "preloader-logo";

  preloader.appendChild(logo);
  document.body.appendChild(preloader);

  var cursorEffect = document.createElement("div");
  cursorEffect.className = "cursor-effect";
  cursorEffect.style.position = "fixed";
  cursorEffect.style.zIndex = "9999";
  cursorEffect.style.transition =
    "transform 0.2s ease, left 0.1s ease, top 0.1s ease";
  document.body.appendChild(cursorEffect);

  document.addEventListener("mousemove", function (e) {
    var cursorSize = 30;
    var x = Math.max(0, Math.min(e.clientX, window.innerWidth - cursorSize));
    var y = Math.max(0, Math.min(e.clientY, window.innerHeight - cursorSize));

    cursorEffect.style.left = x + "px";
    cursorEffect.style.top = y + "px";
  });

  function removePreloader() {
    setTimeout(function () {
      preloader.style.opacity = "0";
      setTimeout(function () {
        preloader.style.display = "none";
        preloader.remove();
        document.body.classList.remove("preloader-active");
        var siteWrapper = document.querySelector(".site-wrapper");
        siteWrapper.style.visibility = "visible";
        siteWrapper.style.overflow = "auto";
        siteWrapper.style.display = "block";
        siteWrapper.style.opacity = "1";
        siteWrapper.style.transition = "opacity 0.5s ease";
        setTimeout(() => {
          siteWrapper.style.opacity = "1";
        }, 10);
        AOS.init({
          once: true,
          duration: 1500,
        });
        // ====== Back to top ======
        if (document.querySelector(".scrollToTop")) {
          var box = document.querySelector(".scrollToTop");
          var water = document.querySelector(".scrollToTop .water");

          function updateDimensions() {
            windowHeight = window.innerHeight;
            documentHeight =
              document.documentElement.scrollHeight - windowHeight;
          }

          updateDimensions();

          window.addEventListener("resize", updateDimensions);

          window.addEventListener("scroll", function () {
            var scrollPosition = window.scrollY;
            var percent = Math.min(
              Math.floor((scrollPosition / documentHeight) * 100),
              100
            );
            water.style.transform = "translate(0," + (100 - percent) + "%)";

            if (scrollPosition >= 200) {
              box.style.display = "block";
            } else {
              box.style.display = "none";
            }
          });

          if (box !== null) {
            box.addEventListener("click", function () {
              window.scrollTo({
                top: 0,
                behavior: "smooth",
              });
            });
          }
        }
      }, 500);
    }, 500);
  }

  document.body.classList.add("preloader-active");
  window.addEventListener("load", function () {
    removePreloader();
  });

  // ====== Custom_Cursor Effect  ======
  document.querySelectorAll("a, button").forEach(function (element) {
    element.addEventListener("mouseenter", function () {
      cursorEffect.style.transform = "scale(1.5) translate(-30px, -30px)";
    });
    element.addEventListener("mouseleave", function () {
      cursorEffect.style.transform = "scale(1) translate(-30px, -30px)";
    });
  });
});

// ====== 1.1 header (aside navigation bar) ======
if (document.getElementById("mySidenav")) {
  function open_aside() {
    "use strict";
    const sidepanel = document.getElementById("mySidenav");
    if (sidepanel) {
      sidepanel.style.left = "0";
    } else {
      console.error("Error: Side panel element not found!");
    }
  }
  function close_aside() {
    "use strict";
    const sidepanel = document.getElementById("mySidenav");
    if (sidepanel) {
      sidepanel.style.left = "-355px";
    } else {
      console.error("Error: Side panel element not found!");
    }
  }
  // aside page button
  let slid = document.getElementById("slid-btn");
  if (slid !== null) {
    slid.onclick = () => {
      let dropdwon = document.getElementById("slid-drop");
      dropdwon.classList.toggle("aside-dropdwon");
    };
  }
}

// Search icone js in next pages
if (document.querySelector(".searchModal")) {
  function openSearchModal() {
    const modal = document.querySelector(".searchModal");
    modal.style.display = "flex";
    document.body.classList.add("modal-open");
    setTimeout(() => {
      modal.classList.add("show");
    }, 10);
  }
  function closeSearchModal() {
    const modal = document.querySelector(".searchModal");
    modal.classList.remove("show");
    setTimeout(() => {
      modal.style.display = "none";
      document.body.classList.remove("modal-open");
    }, 500);
  }
  document
    .querySelector(".SearchModal a")
    .addEventListener("click", openSearchModal);
}

// ====== 1.1 header (dropdown bar) ======
const dropdowns = document.querySelectorAll(".navbar .dropdown");
dropdowns.forEach((dropdown) => {
  const dropdownMenu = dropdown.querySelector(".dropdown-menu");
  dropdownMenu.style.maxHeight = "0";
  dropdown.addEventListener("mouseenter", () => {
    dropdownMenu.style.visibility = "visible";
    dropdownMenu.style.maxHeight = `${dropdownMenu.scrollHeight}px`;
  });
  dropdown.addEventListener("mouseleave", () => {
    dropdownMenu.style.visibility = "hidden";
    dropdownMenu.style.maxHeight = "0";
  });
});

// ======== 1.3. Partners section =======
if (document.querySelector(".PartnersSlider")) {
  $(".PartnersSlider").slick({
    arrows: false,
    dots: false,
    infinite: true,
    autoplay: true,
    autoplaySpeed: 2000,
    speed: 3000,
    slidesToShow: 6,
    cssEase: "linear",
    responsive: [
      {
        breakpoint: 1200,
        settings: {
          slidesToShow: 5,
          slidesToScroll: 1,
        },
      },
      {
        breakpoint: 900,
        settings: {
          slidesToShow: 4,
          slidesToScroll: 1,
        },
      },
      {
        breakpoint: 700,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 1,
        },
      },
      {
        breakpoint: 400,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1,
        },
      },
    ],
  });
}

//  1.14. footer section === Submit message
const contactForm = document.querySelector("footer form");
if (contactForm !== null)
  contactForm.addEventListener("submit", function (event) {
    const path = document
      .querySelector("footer .modal img")
      .getAttribute("src");
    document.querySelector("footer .modal img").setAttribute("src", "");
    event.preventDefault();
    var modal = new bootstrap.Modal(document.querySelector("footer .modal"));
    modal.show();
    document.querySelector("footer form").reset();
    document.querySelector("footer .modal img").setAttribute("src", path);
    setTimeout(() => {
      modal.hide();
    }, 5000);
  });

// ======= 1.15. Footer Date ========
if (document.getElementById("year")) {
  document.addEventListener("DOMContentLoaded", function () {
    let currentYear = new Date().getFullYear();

    let yearElement = document.getElementById("year");
    yearElement.innerText = currentYear;
  });
}

//  8.3. Comment section === Submit message
const contactForm3 = document.querySelector(".Comment form");
if (contactForm3 !== null)
  contactForm3.addEventListener("submit", function (event) {
    const path = document
      .querySelector(".Comment .modal img")
      .getAttribute("src");
    document.querySelector(".Comment .modal img").setAttribute("src", "");
    event.preventDefault();
    var modal = new bootstrap.Modal(document.querySelector(".Comment .modal"));
    modal.show();
    document.querySelector(".Comment form").reset();
    document.querySelector(".Comment .modal img").setAttribute("src", path);
    setTimeout(() => {
      modal.hide();
    }, 5000);
  });

//  9.2. Contact section === Submit message
const contactForm1 = document.querySelector(".Contact form");
if (contactForm1 !== null)
  contactForm1.addEventListener("submit", function (event) {
    const path = document
      .querySelector(".Contact .modal img")
      .getAttribute("src");
    document.querySelector(".Contact .modal img").setAttribute("src", "");
    event.preventDefault();
    var modal = new bootstrap.Modal(document.querySelector(".Contact .modal"));
    modal.show();
    document.querySelector(".Contact form").reset();
    document.querySelector(".Contact .modal img").setAttribute("src", path);
    setTimeout(() => {
      modal.hide();
    }, 5000);
  });

// ========== Numbers Animations for spans =======
function animateNumbers(num, finalValue, duration, isDecimal) {
  let start = null;
  const finalValueStr = num.getAttribute("data-final-value");
  const charCount = finalValueStr.length;
  num.style.display = "inline-block";
  num.style.width = `${charCount}ch`;
  const numberFormatter = new Intl.NumberFormat(
    "en-US",
    isDecimal ? { minimumFractionDigits: 1, maximumFractionDigits: 1 } : {}
  );
  function step(timestamp) {
    if (!start) start = timestamp;
    const progress = Math.min((timestamp - start) / duration, 1);
    const currentValue = progress * finalValue;
    num.textContent = numberFormatter.format(
      isDecimal ? currentValue.toFixed(1) : Math.floor(currentValue)
    );
    if (progress < 1) {
      window.requestAnimationFrame(step);
    } else {
      num.style.display = "inline";
    }
  }
  window.requestAnimationFrame(step);
}
function startNumberAnimation() {
  const numbers = document.querySelectorAll(".number");
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const finalValueStr = entry.target.getAttribute("data-final-value");
          const isDecimal = finalValueStr.includes(".");
          const finalValue = isDecimal
            ? parseFloat(finalValueStr)
            : parseInt(finalValueStr, 10);
          animateNumbers(entry.target, finalValue, 2000, isDecimal);
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.1 }
  );
  numbers.forEach((num) => observer.observe(num));
}
startNumberAnimation();
window.addEventListener("load", startNumberAnimation);

// Modern Payment API Landing Page JavaScript
// Updated for Tailwind CSS implementation

document.addEventListener('DOMContentLoaded', function() {
  // Preloader functionality
  const preloader = document.getElementById('preloader');
  
  window.addEventListener('load', function() {
    if (preloader) {
      preloader.classList.add('fade-out');
      setTimeout(() => {
        preloader.style.display = 'none';
      }, 500);
    }
  });

  // Mobile menu functionality
  const mobileMenuButton = document.getElementById('mobile-menu-button');
  const mobileMenu = document.getElementById('mobile-menu');
  const mobileMenuClose = document.getElementById('mobile-menu-close');

  if (mobileMenuButton) {
    mobileMenuButton.addEventListener('click', () => {
      mobileMenu.classList.add('open');
      document.body.style.overflow = 'hidden';
    });
  }

  if (mobileMenuClose) {
    mobileMenuClose.addEventListener('click', () => {
      mobileMenu.classList.remove('open');
      document.body.style.overflow = '';
    });
  }

  // Close mobile menu when clicking on menu items
  document.querySelectorAll('.mobile-menu-item').forEach(item => {
    item.addEventListener('click', () => {
      mobileMenu.classList.remove('open');
      document.body.style.overflow = '';
    });
  });

  // Navbar scroll effect
  const navbar = document.querySelector('.navbar');
  function handleNavbarScroll() {
    if (window.scrollY > 50) {
      navbar.classList.add('scrolled');
    } else {
      navbar.classList.remove('scrolled');
    }
  }

  window.addEventListener('scroll', handleNavbarScroll);

  // Scroll to top button
  const scrollToTopButton = document.getElementById('scroll-to-top');
  
  if (scrollToTopButton) {
    function handleScrollToTop() {
      if (window.scrollY > 300) {
        scrollToTopButton.classList.remove('hidden');
      } else {
        scrollToTopButton.classList.add('hidden');
      }
    }

    window.addEventListener('scroll', handleScrollToTop);

    scrollToTopButton.addEventListener('click', () => {
      window.scrollTo({ 
        top: 0, 
        behavior: 'smooth' 
      });
    });
  }

  // Smooth scrolling for anchor links
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
      e.preventDefault();
      const target = document.querySelector(this.getAttribute('href'));
      if (target) {
        const offsetTop = target.offsetTop - 80; // Account for fixed navbar
        window.scrollTo({
          top: offsetTop,
          behavior: 'smooth'
        });
      }
    });
  });

  // Intersection Observer for fade-in animations
  const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('visible');
      }
    });
  }, observerOptions);

  // Observe all elements with fade-in classes
  document.querySelectorAll('.fade-in, .fade-in-left, .fade-in-right').forEach(el => {
    observer.observe(el);
  });

  // Counter animation function
  function animateCounter(element, target, duration = 2000) {
    const start = 0;
    const increment = target / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
      current += increment;
      if (current >= target) {
        // Format large numbers
        if (target >= 1000) {
          element.textContent = (target / 1000).toFixed(0) + 'k';
        } else {
          element.textContent = target.toString();
        }
        clearInterval(timer);
      } else {
        element.textContent = Math.floor(current).toString();
      }
    }, 16);
  }

  // Trigger counter animations when visible
  const counterElements = document.querySelectorAll('.stat-counter');
  const counterObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const element = entry.target;
        const targetText = element.textContent;
        const target = parseInt(targetText.replace(/[^\d]/g, ''));
        
        if (target > 0) {
          animateCounter(element, target);
          counterObserver.unobserve(element);
        }
      }
    });
  }, { threshold: 0.5 });

  counterElements.forEach(el => counterObserver.observe(el));

  // Testimonial card hover effects
  document.querySelectorAll('.testimonial-card').forEach(card => {
    card.addEventListener('mouseenter', () => {
      card.style.transform = 'translateY(-5px)';
    });
    
    card.addEventListener('mouseleave', () => {
      card.style.transform = 'translateY(0)';
    });
  });

  // Feature card hover effects
  document.querySelectorAll('.card-hover').forEach(card => {
    card.addEventListener('mouseenter', () => {
      card.style.transform = 'translateY(-5px)';
    });
    
    card.addEventListener('mouseleave', () => {
      card.style.transform = 'translateY(0)';
    });
  });

  // Partner logo hover effects
  document.querySelectorAll('.partner-logo').forEach(logo => {
    logo.addEventListener('mouseenter', () => {
      logo.style.transform = 'scale(1.1)';
      logo.style.filter = 'grayscale(0%)';
    });
    
    logo.addEventListener('mouseleave', () => {
      logo.style.transform = 'scale(1)';
      logo.style.filter = 'grayscale(100%)';
    });
  });

  // Form validation and enhancement
  document.querySelectorAll('.form-input').forEach(input => {
    input.addEventListener('focus', () => {
      input.style.borderColor = '#3b82f6';
      input.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.3)';
    });
    
    input.addEventListener('blur', () => {
      input.style.borderColor = 'rgba(255, 255, 255, 0.3)';
      input.style.boxShadow = 'none';
    });
  });

  // Button hover effects
  document.querySelectorAll('.btn-primary, .btn-secondary').forEach(btn => {
    btn.addEventListener('mouseenter', () => {
      btn.style.transform = 'translateY(-2px)';
    });
    
    btn.addEventListener('mouseleave', () => {
      btn.style.transform = 'translateY(0)';
    });
  });

  // Add loading state to buttons
  document.querySelectorAll('a[href="register"], a[href="auth/index"]').forEach(link => {
    link.addEventListener('click', function(e) {
      // Add loading state
      const originalText = this.textContent;
      this.innerHTML = '<div class="spinner mr-2"></div>' + originalText;
      this.style.pointerEvents = 'none';
      
      // Remove loading state after a short delay (in case of navigation)
      setTimeout(() => {
        this.innerHTML = originalText;
        this.style.pointerEvents = 'auto';
      }, 2000);
    });
  });

  // Parallax effect for hero section
  window.addEventListener('scroll', () => {
    const scrolled = window.pageYOffset;
    const parallaxElements = document.querySelectorAll('.float-animation');
    
    parallaxElements.forEach(element => {
      const speed = 0.5;
      const yPos = -(scrolled * speed);
      element.style.transform = `translateY(${yPos}px)`;
    });
  });

  // Dark mode toggle (if needed)
  const darkModeToggle = document.getElementById('dark-mode-toggle');
  if (darkModeToggle) {
    darkModeToggle.addEventListener('click', () => {
      document.body.classList.toggle('dark-mode');
      localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
    });

    // Check for saved dark mode preference
    if (localStorage.getItem('darkMode') === 'true') {
      document.body.classList.add('dark-mode');
    }
  }

  // Copy to clipboard functionality
  document.querySelectorAll('[data-copy]').forEach(button => {
    button.addEventListener('click', async () => {
      const textToCopy = button.getAttribute('data-copy');
      try {
        await navigator.clipboard.writeText(textToCopy);
        
        // Show success feedback
        const originalText = button.textContent;
        button.textContent = 'Copied!';
        button.style.backgroundColor = '#10b981';
        
        setTimeout(() => {
          button.textContent = originalText;
          button.style.backgroundColor = '';
        }, 2000);
      } catch (err) {
        console.error('Failed to copy: ', err);
      }
    });
  });

  // Lazy loading for images
  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.classList.remove('lazy');
        imageObserver.unobserve(img);
      }
    });
  });

  document.querySelectorAll('img[data-src]').forEach(img => {
    imageObserver.observe(img);
  });

  // Performance optimization: Debounce scroll events
  function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  // Apply debouncing to scroll events
  window.addEventListener('scroll', debounce(() => {
    handleNavbarScroll();
    if (scrollToTopButton) {
      if (window.scrollY > 300) {
        scrollToTopButton.classList.remove('hidden');
      } else {
        scrollToTopButton.classList.add('hidden');
      }
    }
  }, 10));

  // Security: Disable right-click and dev tools
  document.addEventListener('contextmenu', e => e.preventDefault());
  
  document.addEventListener('keydown', e => {
    if (e.key === 'F12' || 
        (e.ctrlKey && e.shiftKey && e.key === 'I') ||
        (e.ctrlKey && e.shiftKey && e.key === 'C') ||
        (e.ctrlKey && e.key === 'U')) {
      e.preventDefault();
    }
  });

  // Error handling for images
  document.querySelectorAll('img').forEach(img => {
    img.addEventListener('error', function() {
      this.style.display = 'none';
      console.warn('Failed to load image:', this.src);
    });
  });

  // Add smooth reveal animation to sections
  const sections = document.querySelectorAll('section');
  const sectionObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.style.opacity = '1';
        entry.target.style.transform = 'translateY(0)';
      }
    });
  }, { threshold: 0.1 });

  sections.forEach(section => {
    section.style.opacity = '0';
    section.style.transform = 'translateY(30px)';
    section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    sectionObserver.observe(section);
  });

  // Initialize tooltips (if using a tooltip library)
  if (typeof tippy !== 'undefined') {
    tippy('[data-tippy-content]');
  }

  console.log('PaglaUPI modern UI initialized successfully!');
});

// FAQ Toggle Function (Global scope for onclick handlers)
function toggleFAQ(button) {
  const faqItem = button.parentElement;
  const answer = faqItem.querySelector('.faq-answer');
  const icon = button.querySelector('svg');
  
  if (answer && icon) {
    if (answer.classList.contains('hidden')) {
      answer.classList.remove('hidden');
      icon.style.transform = 'rotate(180deg)';
    } else {
      answer.classList.add('hidden');
      icon.style.transform = 'rotate(0deg)';
    }
  }
}

// Utility function for smooth animations
function animateElement(element, animation, duration = 1000) {
  element.style.animation = `${animation} ${duration}ms ease-in-out`;
  
  setTimeout(() => {
    element.style.animation = '';
  }, duration);
}

// Analytics and tracking (if needed)
function trackEvent(eventName, eventData = {}) {
  if (typeof gtag !== 'undefined') {
    gtag('event', eventName, eventData);
  }
  
  if (typeof fbq !== 'undefined') {
    fbq('track', eventName, eventData);
  }
  
  console.log('Event tracked:', eventName, eventData);
}
