/* ============ TEXTWAY MAIN JS ============ */

// Mobile nav
function openMob(){document.getElementById('mobDrawer').classList.add('open');document.getElementById('mobOverlay').classList.add('open');document.body.style.overflow='hidden';}
function closeMob(){document.getElementById('mobDrawer').classList.remove('open');document.getElementById('mobOverlay').classList.remove('open');document.body.style.overflow='';}

// FAQ
document.addEventListener('click',function(e){
  const q = e.target.closest('.faq-q');
  if(q){
    const item = q.parentElement;
    const wasOpen = item.classList.contains('open');
    document.querySelectorAll('.faq-item').forEach(i=>i.classList.remove('open'));
    if(!wasOpen) item.classList.add('open');
  }
});

// Pricing toggle (visual only — same prices since textway.in shows yearly)
function setBilling(btn, key){
  document.querySelectorAll('.pt-btn').forEach(b=>b.classList.remove('active'));
  btn.classList.add('active');
  // Update period labels
  const labels = {yearly:'/year', halfyearly:'/6 months', quarterly:'/quarter'};
  document.querySelectorAll('.plan-period').forEach(el=>el.textContent = labels[key] || '/year');
}

// Chatbot
let chatOpen = false;
function toggleChat(){
  const w = document.getElementById('chatWin');
  chatOpen = !chatOpen;
  w.classList.toggle('open', chatOpen);
  if(chatOpen){
    const notif = document.getElementById('cbNotif');
    if(notif) notif.style.display = 'none';
  }
}
function sendChat(){
  const inp = document.getElementById('chatInput');
  const txt = inp.value.trim();
  if(!txt) return;
  addMsg(txt,'user');
  inp.value='';
  setTimeout(()=>botReply(txt),700);
}
function chatQ(q){
  addMsg(q,'user');
  setTimeout(()=>botReply(q),600);
}
function addMsg(text, who){
  const body = document.getElementById('cwBody');
  const m = document.createElement('div');
  m.className = 'cb-m '+who;
  const b = document.createElement('div');
  b.className='cb-bub';
  b.innerHTML = text;
  m.appendChild(b);
  body.appendChild(m);
  body.scrollTop = body.scrollHeight;
}
function botReply(q){
  const lower = q.toLowerCase();
  let reply = 'Thanks for reaching out! Our team will get back to you shortly. For instant help, call <strong>98437-20001</strong> or WhatsApp us.';
  if(lower.includes('sms') || lower.includes('bulk')){
    reply = '📱 Our Bulk SMS service starts at ₹9,999/year with DLT compliance, 99.8% delivery, and detailed analytics. <a href="sms.html" style="color:#FF6300;font-weight:600">View SMS plans →</a>';
  } else if(lower.includes('whatsapp') || lower.includes('wa')){
    reply = '💬 WhatsApp Business API plans include verified green tick, automated chatbots, and broadcasting. <a href="whatsapp.html" style="color:#FF6300;font-weight:600">Learn more →</a>';
  } else if(lower.includes('price') || lower.includes('cost') || lower.includes('plan')){
    reply = '💰 We have 3 plans: Growth (₹9,999), Advanced (₹16,999) & Ultimate (₹24,999) — yearly billing. <a href="pricing.html" style="color:#FF6300;font-weight:600">See all plans →</a>';
  } else if(lower.includes('voice') || lower.includes('ivr')){
    reply = '🎙️ Voice SMS & IVR services available. <a href="voice.html" style="color:#FF6300;font-weight:600">View Voice services →</a>';
  } else if(lower.includes('email')){
    reply = '📧 Bulk Email & Transactional SMTP available. <a href="email.html" style="color:#FF6300;font-weight:600">View Email services →</a>';
  } else if(lower.includes('contact') || lower.includes('support')){
    reply = '📞 Call us: <strong>98437-20001</strong><br>📧 hello@textway.in<br>📍 Coimbatore, Tamil Nadu';
  } else if(lower.includes('hi') || lower.includes('hello') || lower.includes('hey')){
    reply = '👋 Hi there! How can I help you today? Try asking about Bulk SMS, WhatsApp API, Voice, Email, or Pricing.';
  }
  addMsg(reply,'bot');
}

// ============ OPENING SPLASH SCREEN (first paint, all pages) ============
function showOpeningSplash(){
  // Only show once per session
  if(sessionStorage.getItem('opening_splash_shown')) return;

  const splash = document.createElement('div');
  splash.className = 'opening-splash';
  splash.innerHTML = `
    <div class="os-bg-grid"></div>
    <div class="os-orb os-orb-1"></div>
    <div class="os-orb os-orb-2"></div>
    <div class="os-orb os-orb-3"></div>
    <div class="os-content">
      <div class="os-logo-wrap">
        <img src="images/logo.png" alt="Textway" class="os-logo"/>
        <div class="os-ring os-ring-1"></div>
        <div class="os-ring os-ring-2"></div>
        <div class="os-ring os-ring-3"></div>
      </div>
      <div class="os-brand">Text<span>way</span></div>
      <div class="os-tagline">Send Smarter. Reach Millions.</div>
      <div class="os-progress"><div class="os-progress-bar"></div></div>
      <div class="os-loading">
        <span class="os-dot"></span><span class="os-dot"></span><span class="os-dot"></span>
        <span class="os-loading-text">Loading</span>
      </div>
    </div>
  `;
  document.body.appendChild(splash);
  document.body.classList.add('splash-locked');

  // Cycle loading text
  const loadingText = splash.querySelector('.os-loading-text');
  const messages = ['Loading', 'Connecting servers', 'Initializing API', 'Almost ready'];
  let idx = 0;
  const textTimer = setInterval(()=>{
    idx = (idx + 1) % messages.length;
    if(loadingText) loadingText.textContent = messages[idx];
  }, 550);

  // Dismiss
  function dismiss(){
    clearInterval(textTimer);
    splash.classList.add('os-out');
    setTimeout(()=>{
      if(splash.parentNode) splash.parentNode.removeChild(splash);
      document.body.classList.remove('splash-locked');
    }, 700);
  }

  // Total duration: 2.2s (long enough for the animation to feel complete, short enough not to annoy)
  setTimeout(dismiss, 2200);
  sessionStorage.setItem('opening_splash_shown','1');
}


function startSplash(){
  const wrap = document.createElement('div');
  wrap.className = 'top-splash';

  // Soft green flash overlay
  const flash = document.createElement('div');
  flash.className = 'splash-flash';
  wrap.appendChild(flash);

  document.body.appendChild(wrap);

  // 1) Vertical light streaks (like rain of light)
  for(let i=0; i<55; i++){
    const p = document.createElement('div');
    p.className = 'splash-light';
    p.style.left = Math.random()*100 + '%';
    const h = 30 + Math.random()*70;
    p.style.height = h + 'px';
    p.style.width = (1 + Math.random()*1.6).toFixed(1) + 'px';
    const dur = 1.4 + Math.random()*1.6;
    p.style.animationDuration = dur + 's';
    p.style.animationDelay = (Math.random()*3) + 's';
    p.style.opacity = (0.45 + Math.random()*0.5).toFixed(2);
    wrap.appendChild(p);
  }

  // 2) Glowing orbs drifting down
  for(let i=0; i<24; i++){
    const o = document.createElement('div');
    o.className = 'splash-orb';
    const sz = 6 + Math.random()*14;
    o.style.width = sz + 'px';
    o.style.height = sz + 'px';
    o.style.left = Math.random()*100 + '%';
    const drift = (Math.random()*80 - 40).toFixed(0) + 'px';
    o.style.setProperty('--drift', drift);
    const dur = 3.5 + Math.random()*3;
    o.style.animationDuration = dur + 's';
    o.style.animationDelay = (Math.random()*2.5) + 's';
    wrap.appendChild(o);
  }

  // 3) Floating leaf accents
  const leaves = ['🍃','🌿','✨','💚'];
  for(let i=0; i<14; i++){
    const l = document.createElement('div');
    l.className = 'splash-leaf';
    l.textContent = leaves[Math.floor(Math.random()*leaves.length)];
    l.style.left = Math.random()*100 + '%';
    l.style.fontSize = (14 + Math.random()*12) + 'px';
    const drift = (Math.random()*120 - 60).toFixed(0) + 'px';
    l.style.setProperty('--drift', drift);
    const dur = 4 + Math.random()*3;
    l.style.animationDuration = dur + 's';
    l.style.animationDelay = (Math.random()*2) + 's';
    wrap.appendChild(l);
  }

  setTimeout(()=>{ if(wrap.parentNode) wrap.parentNode.removeChild(wrap); }, 8500);
}

// ============ HERO CANVAS — ORBITAL COIN ANIMATION ============
function startCoinCanvas(){
  const cv = document.getElementById('coinCanvas');
  if(!cv) return;
  const ctx = cv.getContext('2d');

  function fit(){
    const r = cv.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    cv.width = r.width * dpr;
    cv.height = r.height * dpr;
    ctx.setTransform(dpr,0,0,dpr,0,0);
  }
  fit();
  window.addEventListener('resize', fit);

  const W = ()=> cv.getBoundingClientRect().width;
  const H = ()=> cv.getBoundingClientRect().height;

  // Coin types — 4 WhatsApp Business API & messaging service icons
  const coinTypes = [
    {label:'💬', color:'#25D366', tint:'#DCFCE7', glow:'rgba(37,211,102,.7)', emoji:true},   // WhatsApp chat bubble
    {label:'✓✓', color:'#128C7E', tint:'#CCFBF1', glow:'rgba(18,140,126,.7)', emoji:false}, // Delivered/read double-tick
    {label:'🤖', color:'#25D366', tint:'#DCFCE7', glow:'rgba(37,211,102,.65)', emoji:true},  // Chatbot automation
    {label:'📢', color:'#128C7E', tint:'#CCFBF1', glow:'rgba(18,140,126,.65)', emoji:true},  // Broadcast messaging
  ];

  const coins = [];
  const numCoins = 4;
  for(let i=0; i<numCoins; i++){
    // Single orbit lane, evenly distributed (90° apart) for a clean professional look
    const orbit = 175;
    const angle = (i / numCoins) * Math.PI * 2;
    const speed = 0.0028;
    coins.push({
      angle,
      orbit,
      speed,
      size: 22,
      type: coinTypes[i],
      bobPhase: i * Math.PI / 2,
      tilt: 0,
      trail: []
    });
  }

  // Sparkles
  const sparkles = [];
  function addSparkle(x,y,color){
    sparkles.push({
      x, y, life: 1,
      vx: (Math.random()-0.5)*0.6,
      vy: (Math.random()-0.5)*0.6,
      size: 1 + Math.random()*2,
      color
    });
  }

  let t = 0;
  function loop(){
    const w = W(), h = H();
    ctx.clearRect(0,0,w,h);
    const cx = w/2, cy = h/2;
    t += 1;

    // Soft glow center
    const grad = ctx.createRadialGradient(cx,cy,0,cx,cy,Math.max(w,h)/2);
    grad.addColorStop(0,'rgba(255,99,0,.04)');
    grad.addColorStop(1,'rgba(255,99,0,0)');
    ctx.fillStyle = grad;
    ctx.fillRect(0,0,w,h);

    coins.forEach((c,i)=>{
      c.angle += c.speed;
      c.bobPhase += 0.04;
      const bob = Math.sin(c.bobPhase)*4;
      const x = cx + Math.cos(c.angle) * c.orbit;
      const y = cy + Math.sin(c.angle) * c.orbit * 0.78 + bob; // slight ellipse

      // Trail — subtle, short echo
      c.trail.push({x,y});
      if(c.trail.length > 4) c.trail.shift();

      c.trail.forEach((p,idx)=>{
        const alpha = (idx / c.trail.length) * 0.22;
        const hex = c.type.color;
        ctx.fillStyle = hex + Math.floor(alpha*255).toString(16).padStart(2,'0');
        ctx.beginPath();
        ctx.arc(p.x, p.y, c.size * (idx/c.trail.length) * 0.5, 0, Math.PI*2);
        ctx.fill();
      });

      // Glow halo
      ctx.beginPath();
      const glowR = c.size + 12;
      const gg = ctx.createRadialGradient(x,y,c.size*0.5,x,y,glowR);
      gg.addColorStop(0, c.type.glow);
      gg.addColorStop(1, 'rgba(255,255,255,0)');
      ctx.fillStyle = gg;
      ctx.arc(x, y, glowR, 0, Math.PI*2);
      ctx.fill();

      // Coin body — metallic gradient
      const cg = ctx.createRadialGradient(x-c.size*0.35, y-c.size*0.35, 1, x, y, c.size);
      cg.addColorStop(0, '#ffffff');
      cg.addColorStop(0.5, c.type.tint || '#FFE9D6');
      cg.addColorStop(1, c.type.color);
      ctx.fillStyle = cg;
      ctx.beginPath();
      ctx.arc(x, y, c.size, 0, Math.PI*2);
      ctx.fill();

      // Outer rim (slightly thicker for premium feel)
      ctx.lineWidth = 1.6;
      ctx.strokeStyle = c.type.color;
      ctx.stroke();

      // Inner ring (decorative)
      ctx.beginPath();
      ctx.arc(x, y, c.size*0.72, 0, Math.PI*2);
      ctx.strokeStyle = 'rgba(255,255,255,.65)';
      ctx.lineWidth = 0.9;
      ctx.stroke();

      // Specular highlight (top-left curve)
      ctx.beginPath();
      ctx.arc(x - c.size*0.25, y - c.size*0.25, c.size*0.35, Math.PI*0.9, Math.PI*1.7);
      ctx.strokeStyle = 'rgba(255,255,255,.55)';
      ctx.lineWidth = 1.4;
      ctx.stroke();

      // Symbol
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      if(c.type.emoji){
        ctx.font = `${c.size*1.05}px "Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif`;
        ctx.fillText(c.type.label, x, y + c.size*0.04);
      } else {
        ctx.fillStyle = c.type.color;
        ctx.font = `800 ${c.size*0.9}px Sora,Inter,sans-serif`;
        ctx.fillText(c.type.label, x, y + c.size*0.05);
      }

      // Subtle, occasional sparkle (less frequent now that we have fewer coins)
      if(Math.random() < 0.012) addSparkle(x + (Math.random()-0.5)*c.size*1.8, y + (Math.random()-0.5)*c.size*1.8, c.type.color);
    });

    // Sparkles update + draw
    for(let i=sparkles.length-1; i>=0; i--){
      const s = sparkles[i];
      s.x += s.vx; s.y += s.vy;
      s.life -= 0.025;
      if(s.life <= 0){ sparkles.splice(i,1); continue; }
      ctx.fillStyle = s.color + Math.floor(s.life*255).toString(16).padStart(2,'0');
      ctx.beginPath();
      ctx.arc(s.x, s.y, s.size, 0, Math.PI*2);
      ctx.fill();
      // 4-point star sparkle
      ctx.strokeStyle = ctx.fillStyle;
      ctx.lineWidth = 0.6;
      ctx.beginPath();
      ctx.moveTo(s.x - s.size*2, s.y); ctx.lineTo(s.x + s.size*2, s.y);
      ctx.moveTo(s.x, s.y - s.size*2); ctx.lineTo(s.x, s.y + s.size*2);
      ctx.stroke();
    }

    requestAnimationFrame(loop);
  }
  requestAnimationFrame(loop);
}

// ============ SCROLL REVEAL (IntersectionObserver) ============
function initScrollReveal(){
  if(!('IntersectionObserver' in window)){
    document.querySelectorAll('.reveal,.reveal-left,.reveal-right,.reveal-scale,.stagger').forEach(el=>el.classList.add('in'));
    return;
  }
  const io = new IntersectionObserver((entries)=>{
    entries.forEach(e=>{
      if(e.isIntersecting){
        e.target.classList.add('in');
        io.unobserve(e.target);
      }
    });
  }, {threshold:0.12, rootMargin:'0px 0px -60px 0px'});

  document.querySelectorAll('.reveal,.reveal-left,.reveal-right,.reveal-scale,.stagger').forEach(el=>io.observe(el));
}

// ============ AUTO-TAG SECTIONS WITH REVEAL CLASSES ============
function autoReveal(){
  // Add .reveal to section-head, and .stagger to common grids
  document.querySelectorAll('.section-head').forEach(el=>{ if(!el.classList.contains('reveal')) el.classList.add('reveal'); });
  const gridSelectors = [
    '.services-grid','.features-grid','.test-grid','.steps-grid',
    '.pricing-grid','.values-grid','.why-stats','.stats-grid',
    '.team-grid','.use-grid','.faq-list','.foot-grid'
  ];
  gridSelectors.forEach(sel=>{
    document.querySelectorAll(sel).forEach(el=>{ if(!el.classList.contains('stagger')) el.classList.add('stagger'); });
  });
  // Hero content slides in from left, visual from right (on first paint these animate in via .in being set on load)
  const hc = document.querySelector('.hero-content');
  const hv = document.querySelector('.hero-visual');
  if(hc) hc.classList.add('reveal-left','in'); // already visible
  if(hv) hv.classList.add('reveal-right','in');
  // Split sections
  document.querySelectorAll('.split-content').forEach(el=>el.classList.add('reveal-left'));
  document.querySelectorAll('.split-media').forEach(el=>el.classList.add('reveal-right'));
  // CTA / why blocks
  document.querySelectorAll('.cta-band, .why').forEach(el=>el.classList.add('reveal-scale'));
}

// Trigger on load
// Trigger opening splash as early as possible (before window load)
// Use DOMContentLoaded so it appears right when the HTML parses
if(document.readyState === 'loading'){
  document.addEventListener('DOMContentLoaded', showOpeningSplash);
} else {
  showOpeningSplash();
}

window.addEventListener('load', function(){
  // Auto-tag DOM with reveal classes, then init observer
  autoReveal();
  initScrollReveal();

  // Start the orbital coin canvas if on a page with one
  startCoinCanvas();

  // Green light-rain splash on home only — once per session, after opening splash dismisses
  const path = window.location.pathname;
  const isHome = path.endsWith('index.html') || path === '/' || path.split('/').pop() === '';
  if(isHome && !sessionStorage.getItem('splash_shown')){
    setTimeout(startSplash, 2400); // wait for opening splash to finish
    sessionStorage.setItem('splash_shown','1');
  }

  // Live SMS counter animation
  const lc = document.getElementById('liveCount');
  if(lc){
    let n = 1240;
    setInterval(()=>{
      n += Math.floor(Math.random()*4) + 1;
      lc.textContent = n.toLocaleString('en-IN');
    }, 1800);
  }

  // Init flip-box keyboard accessibility
  initFlipBoxes();
  initAccordion();
});

// ============ ACCORDION (single-open behavior) ============
function initAccordion(){
  document.querySelectorAll('.accordion').forEach(acc => {
    const items = acc.querySelectorAll('.acc-item');
    items.forEach((item, idx) => {
      const head = item.querySelector('.acc-head');
      if(!head) return;
      // Open first item by default
      if(idx === 0) item.classList.add('open');
      head.setAttribute('aria-expanded', idx === 0 ? 'true' : 'false');
      head.addEventListener('click', () => {
        const isOpen = item.classList.contains('open');
        // Close all others
        items.forEach(other => {
          other.classList.remove('open');
          const h = other.querySelector('.acc-head');
          if(h) h.setAttribute('aria-expanded','false');
        });
        // Toggle this one
        if(!isOpen){
          item.classList.add('open');
          head.setAttribute('aria-expanded','true');
        }
      });
    });
  });
}

// ============ FLIP BOXES (keyboard accessible) ============
function initFlipBoxes(){
  document.querySelectorAll('.flip-box').forEach(box => {
    box.setAttribute('tabindex', '0');
    box.setAttribute('role', 'button');
    box.addEventListener('keydown', e => {
      if(e.key === 'Enter' || e.key === ' '){
        e.preventDefault();
        box.classList.toggle('flipped');
      }
    });
    box.addEventListener('click', () => {
      // On touch devices the hover doesn't work; clicking toggles
      if(window.matchMedia('(hover: none)').matches){
        box.classList.toggle('flipped');
      }
    });
  });
}

// Video unmute toggle
function toggleMute(btn){
  const wrap = btn.closest('.video-wrap');
  const vid = wrap.querySelector('video');
  vid.muted = !vid.muted;
  btn.innerHTML = vid.muted ? '🔇' : '🔊';
  if(!vid.muted){
    vid.volume = 0.6;
    vid.play();
  }
}

// Auto-pause videos when out of view (perf)
if('IntersectionObserver' in window){
  document.addEventListener('DOMContentLoaded', function(){
    const vids = document.querySelectorAll('video');
    const io = new IntersectionObserver((entries)=>{
      entries.forEach(e=>{
        const v = e.target;
        if(e.isIntersecting) v.play().catch(()=>{});
        else v.pause();
      });
    },{threshold:0.25});
    vids.forEach(v=>io.observe(v));
  });
}

// Contact form (demo)
function submitContact(e){
  e.preventDefault();
  const btn = e.target.querySelector('.form-submit');
  const orig = btn.innerHTML;
  btn.innerHTML = '✓ Sent! We\'ll reply within 24h';
  btn.style.background = '#22C55E';
  e.target.reset();
  setTimeout(()=>{
    btn.innerHTML = orig;
    btn.style.background = '';
  }, 3500);
  return false;
}
