/* ============================================
   JDGR CriptoTrade - Optimized Engine v4
   Performance-focused: GPU-friendly, throttled, lean
   ============================================ */

document.addEventListener('DOMContentLoaded', () => {
  initCursorSpotlight();
  initScrollProgress();
  initParticles();
  initNavbar();
  initScroll3D();
  initCounters();
  initCarousel();
  initScrollToTop();
  initMobileMenu();
  initParallaxDepth();
  initTiltCards();
  initMagneticButtons();
});

/* ============================================
   CURSOR SPOTLIGHT - Throttled with RAF
   ============================================ */
function initCursorSpotlight() {
  if (window.matchMedia('(hover: none)').matches) return;

  const spotlight = document.createElement('div');
  spotlight.className = 'cursor-spotlight';
  document.body.appendChild(spotlight);

  let mx = 0, my = 0, cx = 0, cy = 0, running = false;

  document.addEventListener('mousemove', e => {
    mx = e.clientX;
    my = e.clientY;
    if (!running) {
      running = true;
      requestAnimationFrame(updateSpotlight);
    }
  }, { passive: true });

  function lerp(a, b, t) { return a + (b - a) * t; }

  function updateSpotlight() {
    cx = lerp(cx, mx, 0.12);
    cy = lerp(cy, my, 0.12);
    spotlight.style.transform = `translate(${cx - 250}px, ${cy - 250}px)`;

    if (Math.abs(cx - mx) > 0.5 || Math.abs(cy - my) > 0.5) {
      requestAnimationFrame(updateSpotlight);
    } else {
      running = false;
    }
  }

  // Intensify near interactive elements
  document.querySelectorAll('.feature-card, .value-card, .stat-item, .btn').forEach(el => {
    el.addEventListener('mouseenter', () => spotlight.classList.add('intense'));
    el.addEventListener('mouseleave', () => spotlight.classList.remove('intense'));
  });
}

/* ============================================
   SCROLL PROGRESS BAR
   ============================================ */
function initScrollProgress() {
  const bar = document.querySelector('.scroll-progress');
  if (!bar) return;
  let ticking = false;
  window.addEventListener('scroll', () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      const h = document.documentElement.scrollHeight - window.innerHeight;
      bar.style.width = (window.scrollY / h) * 100 + '%';
      ticking = false;
    });
  }, { passive: true });
}

/* ============================================
   PARTICLE SYSTEM - Lightweight, no connections
   ============================================ */
function initParticles() {
  const canvas = document.getElementById('hero-canvas');
  if (!canvas) return;
  const ctx = canvas.getContext('2d');
  let w, h, particles = [];
  let animFrameId;
  let isVisible = true;

  function resize() {
    w = canvas.width = canvas.offsetWidth;
    h = canvas.height = canvas.offsetHeight;
  }
  resize();
  window.addEventListener('resize', () => {
    resize();
  });

  // Pause when hero is out of view
  const heroObs = new IntersectionObserver(entries => {
    isVisible = entries[0].isIntersecting;
    if (isVisible && !animFrameId) animate();
  }, { threshold: 0 });
  heroObs.observe(canvas.closest('.hero') || canvas);

  const COLORS = [
    { r: 245, g: 197, b: 24 },
    { r: 0, g: 240, b: 255 },
    { r: 255, g: 0, b: 170 },
    { r: 0, g: 255, b: 136 },
  ];

  class Particle {
    constructor() {
      this.x = Math.random() * w;
      this.y = Math.random() * h;
      this.z = Math.random() * 3 + 0.5;
      this.vx = (Math.random() - 0.5) * 0.3 / this.z;
      this.vy = (Math.random() - 0.5) * 0.3 / this.z;
      this.radius = (Math.random() * 1.8 + 0.4) * (1 / this.z);
      this.opacity = (Math.random() * 0.4 + 0.15) * (1 / this.z);
      this.color = COLORS[Math.floor(Math.random() * COLORS.length)];
    }

    update() {
      this.x += this.vx;
      this.y += this.vy;
      if (this.x < -5) this.x = w + 5;
      if (this.x > w + 5) this.x = -5;
      if (this.y < -5) this.y = h + 5;
      if (this.y > h + 5) this.y = -5;
    }

    draw() {
      const { r, g, b } = this.color;
      // Glow
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius * 3, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(${r},${g},${b},${this.opacity * 0.05})`;
      ctx.fill();
      // Core
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(${r},${g},${b},${this.opacity})`;
      ctx.fill();
    }
  }

  // Fewer particles - 40 max instead of 90
  const COUNT = Math.min(40, Math.floor(w * h / 25000));
  for (let i = 0; i < COUNT; i++) particles.push(new Particle());

  function animate() {
    if (!isVisible) { animFrameId = null; return; }
    ctx.clearRect(0, 0, w, h);
    particles.forEach(p => { p.update(); p.draw(); });
    // No connection lines - major perf gain
    animFrameId = requestAnimationFrame(animate);
  }
  animate();
}

/* ============================================
   NAVBAR
   ============================================ */
function initNavbar() {
  const nav = document.querySelector('.navbar');
  if (!nav) return;
  let ticking = false;
  window.addEventListener('scroll', () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      nav.classList.toggle('scrolled', window.scrollY > 60);
      ticking = false;
    });
  }, { passive: true });

  document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function(e) {
      e.preventDefault();
      const t = document.querySelector(this.getAttribute('href'));
      if (t) window.scrollTo({ top: t.offsetTop - 70, behavior: 'smooth' });
      document.querySelector('.navbar-actions')?.classList.remove('open');
      document.querySelector('.navbar-toggle')?.classList.remove('active');
      document.body.style.overflow = '';
    });
  });
}

/* ============================================
   SCROLL-DRIVEN REVEAL ANIMATIONS
   Using IntersectionObserver only (no rAF loop)
   ============================================ */
function initScroll3D() {
  const reveals = document.querySelectorAll('.reveal, .reveal-left, .reveal-right, .reveal-scale, .reveal-3d, .reveal-zoom, .reveal-push');

  const revealObs = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('active');
        revealObs.unobserve(entry.target);
      }
    });
  }, { threshold: 0.05, rootMargin: '0px 0px -30px 0px' });

  reveals.forEach(el => revealObs.observe(el));
}

/* ============================================
   ANIMATED COUNTERS
   ============================================ */
function initCounters() {
  const counters = document.querySelectorAll('[data-count]');
  let done = false;
  const obs = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting && !done) {
        done = true;
        counters.forEach(el => {
          const target = parseInt(el.dataset.count);
          const suffix = el.dataset.suffix || '';
          const start = performance.now();
          (function tick(now) {
            const p = Math.min((now - start) / 2800, 1);
            const ease = 1 - Math.pow(1 - p, 4);
            el.textContent = Math.floor(ease * target).toLocaleString() + suffix;
            if (p < 1) requestAnimationFrame(tick);
            else { el.textContent = target.toLocaleString() + suffix; el.style.animation = 'counterBounce 0.4s ease'; }
          })(performance.now());
        });
      }
    });
  }, { threshold: 0.3 });
  counters.forEach(c => obs.observe(c));
}

/* ============================================
   CAROUSEL
   ============================================ */
function initCarousel() {
  const track = document.querySelector('.carousel-track');
  const slides = document.querySelectorAll('.carousel-slide');
  const dotsContainer = document.querySelector('.carousel-dots');
  const prevBtn = document.querySelector('.carousel-prev');
  const nextBtn = document.querySelector('.carousel-next');
  if (!track || slides.length === 0) return;

  let idx = 0, total = slides.length, autoplay;

  function go(i) {
    idx = ((i % total) + total) % total;
    track.style.transform = `translateX(-${idx * 100}%)`;
    document.querySelectorAll('.carousel-dot').forEach((d, j) => d.classList.toggle('active', j === idx));
  }

  if (dotsContainer) {
    slides.forEach((_, i) => {
      const dot = document.createElement('button');
      dot.className = 'carousel-dot' + (i === 0 ? ' active' : '');
      dot.addEventListener('click', () => { go(i); resetAuto(); });
      dotsContainer.appendChild(dot);
    });
  }

  prevBtn?.addEventListener('click', () => { go(idx - 1); resetAuto(); });
  nextBtn?.addEventListener('click', () => { go(idx + 1); resetAuto(); });

  function startAuto() { autoplay = setInterval(() => go(idx + 1), 6000); }
  function resetAuto() { clearInterval(autoplay); startAuto(); }
  startAuto();

  let sx = 0;
  track.addEventListener('touchstart', e => { sx = e.changedTouches[0].screenX; }, { passive: true });
  track.addEventListener('touchend', e => {
    const d = sx - e.changedTouches[0].screenX;
    if (Math.abs(d) > 50) { go(d > 0 ? idx + 1 : idx - 1); resetAuto(); }
  }, { passive: true });
}

/* ============================================
   SCROLL TO TOP
   ============================================ */
function initScrollToTop() {
  const btn = document.querySelector('.scroll-top');
  if (!btn) return;
  let ticking = false;
  window.addEventListener('scroll', () => {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      btn.classList.toggle('visible', window.scrollY > 400);
      ticking = false;
    });
  }, { passive: true });
  btn.addEventListener('click', () => window.scrollTo({ top: 0, behavior: 'smooth' }));
}

/* ============================================
   MOBILE MENU
   ============================================ */
function initMobileMenu() {
  const toggle = document.querySelector('.navbar-toggle');
  const actions = document.querySelector('.navbar-actions');
  if (!toggle || !actions) return;
  toggle.addEventListener('click', () => {
    toggle.classList.toggle('active');
    actions.classList.toggle('open');
    document.body.style.overflow = actions.classList.contains('open') ? 'hidden' : '';
  });
  document.addEventListener('click', e => {
    if (actions.classList.contains('open') && !actions.contains(e.target) && !toggle.contains(e.target)) {
      toggle.classList.remove('active');
      actions.classList.remove('open');
      document.body.style.overflow = '';
    }
  });
}

/* ============================================
   PARALLAX DEPTH - CSS-only with scroll events throttled
   Simplified: only hero elements, no per-section 3D
   ============================================ */
function initParallaxDepth() {
  const hero = document.querySelector('.hero-bg-image');
  const blobs = document.querySelectorAll('.hero-blob');
  const grid = document.querySelector('.hero-grid-floor');
  const heroSection = document.querySelector('.hero');

  if (!heroSection) return;

  let ticking = false;
  let isHeroVisible = true;

  // Only animate when hero is visible
  const obs = new IntersectionObserver(entries => {
    isHeroVisible = entries[0].isIntersecting;
  }, { threshold: 0 });
  obs.observe(heroSection);

  window.addEventListener('scroll', () => {
    if (ticking || !isHeroVisible) return;
    ticking = true;
    requestAnimationFrame(() => {
      const y = window.scrollY;
      if (hero) hero.style.transform = `translateY(${y * 0.3}px)`;
      if (grid) grid.style.transform = `perspective(400px) rotateX(55deg) translateY(${y * 0.1}px)`;
      blobs.forEach((b, i) => {
        const speed = [0.1, 0.06, 0.04][i] || 0.08;
        b.style.transform = `translateY(${y * speed}px)`;
      });
      ticking = false;
    });
  }, { passive: true });
}

/* ============================================
   3D TILT CARDS - Lighter, no GPU thrashing
   ============================================ */
function initTiltCards() {
  if (window.matchMedia('(hover: none)').matches) return;

  const cards = document.querySelectorAll('.feature-card, .value-card');

  cards.forEach(card => {
    let ticking = false;

    card.addEventListener('mousemove', e => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const rect = card.getBoundingClientRect();
        const x = (e.clientX - rect.left) / rect.width;
        const y = (e.clientY - rect.top) / rect.height;
        const rotY = (x - 0.5) * 10;
        const rotX = (0.5 - y) * 10;
        card.style.transform = `perspective(800px) rotateX(${rotX}deg) rotateY(${rotY}deg) scale(1.02)`;
        ticking = false;
      });
    });

    card.addEventListener('mouseleave', () => {
      card.style.transform = '';
      card.style.transition = 'transform 0.5s ease';
      setTimeout(() => { card.style.transition = ''; }, 500);
    });
  });
}

/* ============================================
   MAGNETIC BUTTONS
   ============================================ */
function initMagneticButtons() {
  if (window.matchMedia('(hover: none)').matches) return;

  document.querySelectorAll('.btn').forEach(btn => {
    btn.addEventListener('mousemove', e => {
      const rect = btn.getBoundingClientRect();
      const x = e.clientX - rect.left - rect.width / 2;
      const y = e.clientY - rect.top - rect.height / 2;
      btn.style.transform = `translate(${x * 0.15}px, ${y * 0.15}px) scale(1.03)`;
    });
    btn.addEventListener('mouseleave', () => { btn.style.transform = ''; });
  });
}
