/* ============================================================
   CY CONSULTANCY — main.js v4 (PHP Edition)
   Fixed: Mobile menu, scroll speed, all animations
   ============================================================ */
(function(){
'use strict';

/* ─── 1. LENIS SMOOTH SCROLL ─── */
var lenis;
function initLenis(){
  if(typeof Lenis==='undefined') return;
  lenis = new Lenis({
    duration: 0.65,
    easing: function(t){ return 1-Math.pow(1-t,3); },
    orientation: 'vertical',
    smoothTouch: false,
    touchMultiplier: 1.2
  });
  function raf(t){ lenis.raf(t); requestAnimationFrame(raf); }
  requestAnimationFrame(raf);
}

/* ─── 2. SCROLL: PROGRESS + NAV SHADOW + SCROLL-TOP ─── */
function initScroll(){
  var prog = document.getElementById('prog');
  var nav  = document.getElementById('navbar');
  var stb  = document.getElementById('scroll-top');
  window.addEventListener('scroll', function(){
    var s=window.scrollY, h=document.body.scrollHeight-window.innerHeight;
    if(prog && h>0) prog.style.width=(s/h*100)+'%';
    if(nav)  nav.classList.toggle('scrolled', s>50);
    if(stb)  stb.classList.toggle('show', s>500);
  },{passive:true});
  if(stb) stb.addEventListener('click',function(){
    if(lenis) lenis.scrollTo(0,{duration:.7});
    else window.scrollTo({top:0,behavior:'smooth'});
  });
}

/* ─── 3. HERO BG SLIDESHOW ─── */
function initHeroBg(){
  var slides=document.querySelectorAll('.hero-bg-slide');
  if(!slides.length) return;
  var cur=0;
  function next(){
    slides[cur].classList.remove('active');
    cur=(cur+1)%slides.length;
    slides[cur].classList.add('active');
  }
  setInterval(next,7000);
}

/* ─── 4. PARALLAX MOUSE GLOW ─── */
function initParallax(){
  var g1=document.getElementById('glow1'),g2=document.getElementById('glow2');
  if(!g1) return;
  var mx=0,my=0,cx1=0,cy1=0,cx2=0,cy2=0;
  document.addEventListener('mousemove',function(e){
    mx=(e.clientX/window.innerWidth-.5)*70;
    my=(e.clientY/window.innerHeight-.5)*70;
  });
  (function tick(){
    cx1+=(mx-cx1)*.035; cy1+=(my-cy1)*.035;
    cx2+=(-mx*.6-cx2)*.035; cy2+=(-my*.6-cy2)*.035;
    g1.style.transform='translate('+cx1+'px,'+cy1+'px)';
    g2.style.transform='translate('+cx2+'px,'+cy2+'px)';
    requestAnimationFrame(tick);
  })();
}

/* ─── 5. AOS SCROLL REVEAL ─── */
var obs = new IntersectionObserver(function(entries){
  entries.forEach(function(e){
    if(!e.isIntersecting) return;
    var el=e.target, d=parseInt(el.getAttribute('data-aos-delay')||0);
    setTimeout(function(){ el.classList.add('aos-animate','show','in'); }, d);
    obs.unobserve(el);
  });
},{threshold:0.07, rootMargin:'0px 0px -36px 0px'});

function initReveal(){
  document.querySelectorAll('[data-aos],.anim,.anim-l,.anim-r,.anim-s,.sh,.blur-reveal,.section-line,.line-reveal-wrap').forEach(function(el){
    obs.observe(el);
  });
}

/* ─── 6. COUNTER ANIMATION ─── */
function animCount(el){
  var tgt=parseInt(el.dataset.target), s=performance.now(), dur=1800;
  (function tick(now){
    var p=Math.min((now-s)/dur,1), ease=1-Math.pow(1-p,3);
    el.textContent=Math.floor(ease*tgt).toLocaleString();
    if(p<1) requestAnimationFrame(tick);
  })(s);
}
var cObs=new IntersectionObserver(function(entries){
  entries.forEach(function(e){
    if(e.isIntersecting){ e.target.querySelectorAll('.counter').forEach(animCount); cObs.unobserve(e.target); }
  });
},{threshold:.3});
function initCounters(){
  document.querySelectorAll('.stats-row,.hero-card,.h-stats,.stats-in').forEach(function(s){ cObs.observe(s); });
}

/* ─── 7. CUSTOM CURSOR ─── */
function initCursor(){
  var cur=document.querySelector('.custom-cursor'),dot=document.querySelector('.cursor-dot');
  if(!cur) return;
  var mx=0,my=0,cx=0,cy=0;
  document.addEventListener('mousemove',function(e){
    mx=e.clientX; my=e.clientY;
    if(dot){ dot.style.left=mx+'px'; dot.style.top=my+'px'; }
  });
  (function ani(){ cx+=(mx-cx)*.12; cy+=(my-cy)*.12; cur.style.left=cx+'px'; cur.style.top=cy+'px'; requestAnimationFrame(ani); })();
  document.querySelectorAll('a,button,.svc,.why-card,.dest-item,.test-card,.doc-box,.uni-logo-card,.finder-card,.sfc').forEach(function(el){
    el.addEventListener('mouseenter',function(){ cur.classList.add('hov'); });
    el.addEventListener('mouseleave',function(){ cur.classList.remove('hov'); });
  });
}

/* ─── 8. NOISE ANIMATION ─── */
function initNoise(){
  var n=document.querySelector('.noise-overlay'); if(!n)return;
  var f=0; (function ani(){ f++; if(f%2===0) n.style.backgroundPosition=(Math.random()*100)+'% '+(Math.random()*100)+'%'; requestAnimationFrame(ani); })();
}

/* ─── 9. MOBILE MENU — COMPLETELY REWRITTEN & FIXED ─── */
function initMob(){
  var btn  = document.getElementById('mob-btn');
  var menu = document.getElementById('mob-menu');
  if(!btn || !menu) return;

  var isOpen = false;

  function open(){
    isOpen = true;
    menu.classList.add('open');
    btn.classList.add('open');
    btn.innerHTML = '<i class="fas fa-times"></i>';
    document.body.style.overflow = 'hidden';
  }

  function close(){
    isOpen = false;
    menu.classList.remove('open');
    btn.classList.remove('open');
    btn.innerHTML = '<i class="fas fa-bars"></i>';
    document.body.style.overflow = '';
  }

  // Button click — use touchstart for better mobile response
  ['click','touchstart'].forEach(function(ev){
    btn.addEventListener(ev, function(e){
      e.preventDefault();
      e.stopPropagation();
      isOpen ? close() : open();
    }, {passive:false});
  });

  // Close on outside click
  document.addEventListener('click', function(e){
    if(isOpen && !menu.contains(e.target) && !btn.contains(e.target)) close();
  });

  // Close on any link inside menu
  menu.querySelectorAll('a').forEach(function(a){
    a.addEventListener('click', close);
  });

  // Escape key
  document.addEventListener('keydown', function(e){
    if(e.key==='Escape' && isOpen) close();
  });
}

/* ─── 10. SMOOTH HASH LINKS ─── */
function initLinks(){
  document.querySelectorAll('a[href^="#"]').forEach(function(a){
    a.addEventListener('click',function(e){
      var t=document.querySelector(this.getAttribute('href')); if(!t)return;
      e.preventDefault();
      if(lenis) lenis.scrollTo(t,{offset:-90,duration:.7});
      else t.scrollIntoView({behavior:'smooth'});
    });
  });
}

/* ─── 11. FORM HANDLER ─── */
function initForms(){
  document.querySelectorAll('form.cy-form').forEach(function(f){
    f.addEventListener('submit',function(e){
      e.preventDefault();
      var btn=f.querySelector('.btn-submit');
      if(!btn) return;
      btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Sending...'; btn.disabled=true;
      setTimeout(function(){
        btn.innerHTML='<i class="fas fa-check-circle"></i> Submitted!';
        btn.style.background='linear-gradient(135deg,#2EC4B6,#1BA8A0)';
        setTimeout(function(){
          alert('ধন্যবাদ! ২৪ ঘন্টার মধ্যে যোগাযোগ করব। 🎓');
          btn.innerHTML='<i class="fas fa-paper-plane"></i> Submit Application';
          btn.style.background=''; btn.disabled=false; f.reset();
        },1600);
      },900);
    });
  });
}

/* ─── 12. WORK ITEMS HOVER ─── */
function initWorkItems(){
  var items=document.querySelectorAll('.work-item'); if(!items.length)return;
  var first=items[0] && items[0].querySelector('.wi-title');
  if(first){ first.style.opacity='1'; first.style.transform='none'; first.style.fontWeight='900'; first.style.textShadow='0 0 .3em rgba(120,136,222,.8)'; }
  items.forEach(function(item){
    item.addEventListener('mouseenter',function(){
      items.forEach(function(o){ var t=o.querySelector('.wi-title'); if(t){ t.style.opacity='.3'; t.style.transform='scale(.85)'; t.style.textShadow='none'; } });
      var mt=item.querySelector('.wi-title'); if(mt){ mt.style.opacity='1'; mt.style.transform='none'; mt.style.fontWeight='900'; mt.style.textShadow='0 0 .3em rgba(120,136,222,.8)'; }
    });
    item.addEventListener('mouseleave',function(){
      items.forEach(function(o){ var t=o.querySelector('.wi-title'); if(t){ t.style.opacity='.5'; t.style.transform='scale(.88)'; t.style.textShadow=''; } });
      if(first){ first.style.opacity='1'; first.style.transform='none'; first.style.fontWeight='900'; }
    });
  });
}

/* ─── 13. HERO SCROLL PARALLAX ─── */
function initHeroParallax(){
  var heroIn=document.querySelector('.hero-in'); if(!heroIn)return;
  window.addEventListener('scroll',function(){
    var s=window.scrollY;
    if(s<window.innerHeight){
      heroIn.style.transform='translateY('+(s*.15)+'px)';
      heroIn.style.opacity=String(Math.max(0, 1-s/600));
    }
  },{passive:true});
}

/* ─── 14. TITLE ANIMATIONS ─── */
function initTitles(){
  var shObs=new IntersectionObserver(function(entries){
    entries.forEach(function(e){
      if(!e.isIntersecting) return;
      e.target.classList.add('aos-animate','show');
      shObs.unobserve(e.target);
    });
  },{threshold:.08,rootMargin:'0px 0px -30px 0px'});
  document.querySelectorAll('.sh:not(.aos-animate)').forEach(function(sh){ shObs.observe(sh); });
}

/* ─── 15. ABOUT IMAGE HEIGHT SYNC ─── */
function initAboutImage(){
  var wrap=document.querySelector('.about-img-wrap');
  var left=wrap&&wrap.previousElementSibling;
  if(!wrap||!left) return;
  function sync(){
    var h=left.offsetHeight;
    if(h>300){ wrap.style.minHeight=h+'px'; }
  }
  sync();
  window.addEventListener('resize',sync,{passive:true});
  setTimeout(sync,500);
  setTimeout(sync,1500);
}

/* ─── 16. 3D CARD TILT ─── */
function initTilt(){
  if(window.innerWidth < 768) return; // skip on mobile
  document.querySelectorAll('.why-card,.svc,.finder-card,.uni-logo-card,.test-card').forEach(function(card){
    card.addEventListener('mousemove',function(e){
      var r=card.getBoundingClientRect();
      var x=((e.clientX-r.left)/r.width-.5)*16;
      var y=-((e.clientY-r.top)/r.height-.5)*16;
      card.style.transform='translateY(-8px) rotateX('+y+'deg) rotateY('+x+'deg)';
    });
    card.addEventListener('mouseleave',function(){
      card.style.transform='';
      card.style.transition='transform .4s cubic-bezier(.16,1,.3,1)';
    });
    card.addEventListener('mouseenter',function(){
      card.style.transition='transform .1s ease';
    });
  });
}

/* ─── INIT ALL ─── */
function init(){
  initLenis();
  initScroll();
  initHeroBg();
  initParallax();
  initReveal();
  initCounters();
  initCursor();
  initNoise();
  initMob();
  initLinks();
  initForms();
  initWorkItems();
  initHeroParallax();
  initTitles();
  initAboutImage();
  setTimeout(initTilt, 500);
}

if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',init);
else init();

})();

// ── Floating Particles ──
(function(){
  var wrap = document.getElementById('particles');
  if (!wrap) return;
  var colors = ['#e76f51','#f4a261','#1a56db','#ffffff','#fbbf24'];
  for (var i = 0; i < 25; i++) {
    (function(i){
      setTimeout(function(){
        var p = document.createElement('div');
        p.className = 'particle';
        var size = Math.random()*6+2;
        p.style.cssText = [
          'width:'+size+'px','height:'+size+'px',
          'left:'+Math.random()*100+'%',
          'background:'+colors[Math.floor(Math.random()*colors.length)],
          'animation-duration:'+(Math.random()*12+8)+'s',
          'animation-delay:'+(Math.random()*6)+'s'
        ].join(';');
        wrap.appendChild(p);
      }, i*200);
    })(i);
  }
})();
