/* ═══════════════════════════════════════════════════════════
   TEXTWAY v7 — COMPLETE JS ENGINE
   • Splash → Nav → Scroll Reveal → 3D Tilt → Sound Engine
   • Chatbot → Form → FAQ → Pricing Toggle → Clients Track
   ═══════════════════════════════════════════════════════════ */
'use strict';

/* ─── WEB AUDIO SFX ENGINE ──────────────────────────────── */
const SFX = (() => {
  let ctx = null, enabled = false;
  const init = () => { if (!ctx) { try { ctx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e){} } };
  const tone = (freq, type, vol, dur, attack=0.01, decay=0.05, sustain=0.4, release=0.18) => {
    if (!ctx || !enabled) return;
    try {
      const osc = ctx.createOscillator(), gain = ctx.createGain();
      osc.connect(gain); gain.connect(ctx.destination);
      osc.type = type; osc.frequency.setValueAtTime(freq, ctx.currentTime);
      gain.gain.setValueAtTime(0, ctx.currentTime);
      gain.gain.linearRampToValueAtTime(vol, ctx.currentTime + attack);
      gain.gain.linearRampToValueAtTime(vol * sustain, ctx.currentTime + attack + decay);
      gain.gain.setValueAtTime(vol * sustain, ctx.currentTime + dur - release);
      gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
      osc.start(ctx.currentTime); osc.stop(ctx.currentTime + dur);
    } catch(e){}
  };
  const noise = (vol, dur) => {
    if (!ctx || !enabled) return;
    try {
      const bufSize = ctx.sampleRate * dur;
      const buf = ctx.createBuffer(1, bufSize, ctx.sampleRate);
      const d = buf.getChannelData(0);
      for (let i = 0; i < bufSize; i++) d[i] = Math.random() * 2 - 1;
      const src = ctx.createBufferSource(), gain = ctx.createGain(), filt = ctx.createBiquadFilter();
      src.buffer = buf; filt.type = 'bandpass'; filt.frequency.setValueAtTime(800, ctx.currentTime);
      src.connect(filt); filt.connect(gain); gain.connect(ctx.destination);
      gain.gain.setValueAtTime(vol, ctx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
      src.start(ctx.currentTime); src.stop(ctx.currentTime + dur);
    } catch(e){}
  };
  return {
    enable() { enabled = true; init(); if (ctx && ctx.state === 'suspended') ctx.resume(); },
    disable() { enabled = false; },
    isEnabled() { return enabled; },
    click() { tone(440, 'sine', 0.1, 0.08); },
    hover() { tone(660, 'sine', 0.04, 0.06); },
    ping() { tone(880, 'sine', 0.12, 0.22, 0.005, 0.02, 0.3, 0.2); },
    smsSend() {
      tone(523, 'sine', 0.15, 0.12);
      setTimeout(() => tone(659, 'sine', 0.12, 0.12), 80);
      setTimeout(() => tone(784, 'sine', 0.1, 0.22), 160);
    },
    waNotify() {
      tone(783, 'sine', 0.18, 0.14);
      setTimeout(() => tone(987, 'sine', 0.15, 0.14), 90);
      setTimeout(() => tone(1174, 'sine', 0.12, 0.24), 180);
    },
    tick() { tone(880, 'square', 0.04, 0.04, 0.003); },
    reveal() { tone(440, 'sine', 0.04, 0.14, 0.01, 0.03, 0.2, 0.1); },
    faqOpen() { tone(330, 'sine', 0.09, 0.16, 0.01, 0.03, 0.3, 0.12); },
    success() {
      [523,659,784,1046].forEach((f,i) => setTimeout(() => tone(f,'sine',0.14,0.22),i*88));
    },
    error() { tone(220, 'sawtooth', 0.1, 0.28); setTimeout(() => tone(180, 'sawtooth', 0.08, 0.22), 120); },
    ambientPing() { if (!enabled) return; tone(1200, 'sine', 0.03, 0.4, 0.02, 0.08, 0.15, 0.3); },
  };
})();

/* ─── SPLASH ─────────────────────────────────────────────── */
const splash = document.getElementById('splash');
const spPct  = document.getElementById('spPct');
const pctTexts = ['Connecting servers...','Loading DLT routes...','Initializing API...','Ready!'];
let pctVal = 0;
const spTimer = setInterval(() => {
  pctVal = Math.min(pctVal + (Math.random() * 4.5 + 1.5), 100);
  if (spPct) spPct.textContent = pctTexts[Math.floor(pctVal / 26)] || `${Math.round(pctVal)}%`;
  if (pctVal >= 100) { clearInterval(spTimer); dismissSplash(); }
}, 45);
const confColors = ['#ff8c00','#ffb347','#00c853','#4ade80','#fff','#ffdd57'];
function spawnConf() {
  if (!document.getElementById('confWrap')) return;
  const w = document.getElementById('confWrap');
  for (let i = 0; i < 9; i++) {
    const el = document.createElement('div');
    el.className = 'sp-conf';
    el.style.cssText = `left:${Math.random()*100}%;width:${Math.random()*8+4}px;height:${Math.random()*8+4}px;background:${confColors[Math.floor(Math.random()*confColors.length)]};border-radius:${Math.random()>0.5?'50%':'2px'};animation-duration:${Math.random()*2+2}s;animation-delay:${Math.random()*1.5}s`;
    w.appendChild(el);
    setTimeout(() => el.remove(), 5000);
  }
}
for (let i = 0; i < 3; i++) setTimeout(spawnConf, i * 600);
function dismissSplash() {
  if (splash) { splash.classList.add('out'); setTimeout(() => { splash.style.display='none'; }, 900); }
}
window.addEventListener('load', () => { clearInterval(spTimer); pctVal=100; setTimeout(dismissSplash, 300); });

/* ─── CURSOR GLOW ────────────────────────────────────────── */
const cg = document.getElementById('cg');
document.addEventListener('mousemove', e => {
  if (cg) { cg.style.left = e.clientX + 'px'; cg.style.top = e.clientY + 'px'; }
});

/* ─── NAV ────────────────────────────────────────────────── */
const nav = document.getElementById('nav');
const vidHero = document.getElementById('vidHeroSec');
function updateNav() {
  if (!nav) return;
  const scrolled = window.scrollY > 40;
  const hasVH = !!vidHero;
  const pastVH = hasVH ? window.scrollY > (vidHero.offsetHeight - 80) : true;
  if (!hasVH || pastVH) {
    nav.className = 'solid';
  } else {
    nav.className = scrolled ? 'dark-mode solid' : 'dark-mode';
  }
}
window.addEventListener('scroll', updateNav, { passive: true });
updateNav();

/* ─── MOBILE MENU ────────────────────────────────────────── */
let mobOpen = false;
function toggleMob() {
  mobOpen = !mobOpen;
  const mob = document.getElementById('mob');
  const b1 = document.getElementById('b1');
  const b2 = document.getElementById('b2');
  const b3 = document.getElementById('b3');
  if (mob) mob.classList.toggle('open', mobOpen);
  if (b1 && b2 && b3) {
    if (mobOpen) { b1.style.transform='rotate(45deg) translate(5px,5px)'; b2.style.opacity='0'; b3.style.transform='rotate(-45deg) translate(5px,-5px)'; }
    else { b1.style.transform=''; b2.style.opacity=''; b3.style.transform=''; }
  }
}

/* ─── SCROLL REVEAL ──────────────────────────────────────── */
const revObs = new IntersectionObserver(entries => {
  entries.forEach(e => {
    if (e.isIntersecting) { e.target.classList.add('vis'); SFX.reveal(); revObs.unobserve(e.target); }
  });
}, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
document.querySelectorAll('.rev').forEach(el => revObs.observe(el));

/* ─── 3D CARD TILT ───────────────────────────────────────── */
function initTilt(selector, maxTilt = 10, glare = true) {
  document.querySelectorAll(selector).forEach(card => {
    card.addEventListener('mousemove', e => {
      const rect = card.getBoundingClientRect();
      const cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2;
      const rx = (e.clientY - cy) / (rect.height / 2) * -maxTilt;
      const ry = (e.clientX - cx) / (rect.width / 2) * maxTilt;
      card.style.transform = `perspective(900px) rotateX(${rx}deg) rotateY(${ry}deg) scale(1.03)`;
      if (glare) {
        const px = (e.clientX - rect.left) / rect.width * 100;
        const py = (e.clientY - rect.top) / rect.height * 100;
        card.style.background = `radial-gradient(circle at ${px}% ${py}%, rgba(255,255,255,.08) 0%, transparent 60%), var(--wh)`;
      }
    });
    card.addEventListener('mouseleave', () => {
      card.style.transform = ''; card.style.background = '';
    });
  });
}
initTilt('.svc-card', 12, true);
initTilt('.pf-card', 10, true);
initTilt('.price-card', 8, false);
initTilt('.test-card', 7, false);

/* ─── PHONE 3D MOUSE PARALLAX ────────────────────────────── */
const ph3d = document.getElementById('ph3d');
if (ph3d) {
  let tx = 0, ty = 0, cx2 = 0, cy2 = 0;
  document.addEventListener('mousemove', e => { cx2 = e.clientX; cy2 = e.clientY; });
  setInterval(() => {
    const w = window.innerWidth, h = window.innerHeight;
    const rx = (cy2 / h - 0.5) * -18;
    const ry = (cx2 / w - 0.5) * 24;
    tx += (rx - tx) * 0.07;
    ty += (ry - ty) * 0.07;
    ph3d.style.transform = `perspective(700px) rotateX(${tx}deg) rotateY(${ty}deg)`;
  }, 16);
}

/* ─── VIDEO HERO MOUSE TILT ──────────────────────────────── */
const vidHeroVideo = document.getElementById('vidHeroVideo');
if (vidHeroVideo) {
  document.addEventListener('mousemove', e => {
    const rx = (e.clientY / window.innerHeight - 0.5) * -4;
    const ry = (e.clientX / window.innerWidth - 0.5) * 4;
    vidHeroVideo.style.transform = `scale(1.06) rotateX(${rx}deg) rotateY(${ry}deg)`;
  });
}

/* ─── SOUND TOGGLE ───────────────────────────────────────── */
let soundOn = false;
function toggleSound() {
  soundOn = !soundOn;
  const btn = document.getElementById('soundBtn');
  const vid = document.getElementById('vidHeroVideo');
  if (soundOn) {
    SFX.enable();
    if (vid) { vid.muted = false; vid.volume = 0.55; vid.play().catch(() => {}); }
    if (btn) btn.textContent = '🔊';
    SFX.ping();
  } else {
    SFX.disable();
    if (vid) { vid.muted = true; }
    if (btn) btn.textContent = '🔇';
  }
}

/* ─── SECTION SOUND TRIGGERS ─────────────────────────────── */
const secSounds = new IntersectionObserver(entries => {
  entries.forEach(e => {
    if (e.isIntersecting) {
      const id = e.target.id;
      if (id === 'apiVidSec') SFX.smsSend();
      else if (id === 'pricing-sec') SFX.waNotify();
      else SFX.ambientPing();
      secSounds.unobserve(e.target);
    }
  });
}, { threshold: 0.3 });
['apiVidSec','pricing-sec','clients-sec'].forEach(id => {
  const el = document.getElementById(id); if (el) secSounds.observe(el);
});

/* ─── COUNTER ANIMATION ──────────────────────────────────── */
const ctrObs = new IntersectionObserver(entries => {
  entries.forEach(e => {
    if (!e.isIntersecting) return;
    const el = e.target;
    const target = parseFloat(el.dataset.t);
    const suffix = el.dataset.s || '';
    const isFloat = target % 1 !== 0;
    let start = null, dur = 1800;
    const step = ts => {
      if (!start) start = ts;
      const p = Math.min((ts - start) / dur, 1);
      const ease = 1 - Math.pow(1 - p, 3);
      const val = target * ease;
      el.textContent = (isFloat ? val.toFixed(1) : Math.floor(val).toLocaleString()) + suffix;
      if (p < 1) { SFX.tick(); requestAnimationFrame(step); }
      else el.textContent = (isFloat ? target.toFixed(1) : target.toLocaleString()) + suffix;
    };
    requestAnimationFrame(step);
    ctrObs.unobserve(el);
  });
}, { threshold: 0.5 });
document.querySelectorAll('.ctr').forEach(el => ctrObs.observe(el));

/* ─── FAQ ────────────────────────────────────────────────── */
function toggleFaq(q) {
  const item = q.parentElement;
  const isOpen = item.classList.contains('open');
  document.querySelectorAll('.faq-item.open').forEach(i => { i.classList.remove('open'); i.querySelector('.faq-a').style.maxHeight = null; });
  if (!isOpen) { item.classList.add('open'); item.querySelector('.faq-a').style.maxHeight = item.querySelector('.faq-a').scrollHeight + 'px'; SFX.faqOpen(); }
  SFX.click();
}

/* ─── PRICING TOGGLE ─────────────────────────────────────── */
function setPlan(id, btn, price) {
  document.getElementById(id).textContent = price;
  btn.closest('.price-toggle').querySelectorAll('.ptb').forEach(b => b.classList.remove('on'));
  btn.classList.add('on');
  SFX.click();
}

/* ─── CLIENTS TRACK ──────────────────────────────────────── */
const CLIENTS = [
  {name:'Kovai Medicals',c1:'#ff8c00',c2:'#d96b00',t:'KM'},
  {name:'Sri Ram Textiles',c1:'#00c853',c2:'#009a40',t:'SR'},
  {name:'Tirupur Exports',c1:'#0070e0',c2:'#0050a0',t:'TE'},
  {name:'Salem Steel',c1:'#7c3aed',c2:'#5b21b6',t:'SS'},
  {name:'Erode Silks',c1:'#e11d48',c2:'#be123c',t:'ES'},
  {name:'Pollachi Farms',c1:'#0891b2',c2:'#0e7490',t:'PF'},
  {name:'CBE Motors',c1:'#d97706',c2:'#b45309',t:'CM'},
  {name:'Karur Textiles',c1:'#16a34a',c2:'#15803d',t:'KT'},
  {name:'TN Pharma',c1:'#dc2626',c2:'#b91c1c',t:'TP'},
  {name:'Netzy Solutions',c1:'#7c3aed',c2:'#6d28d9',t:'NS'},
];
function buildClients() {
  const track = document.getElementById('cliTrack');
  if (!track) return;
  const double = [...CLIENTS, ...CLIENTS];
  track.innerHTML = double.map(c => `
    <div class="client-logo" title="${c.name}">
      <div style="width:88%;height:54px;border-radius:10px;background:linear-gradient(135deg,${c.c1},${c.c2});display:flex;align-items:center;justify-content:center;font-family:'Space Grotesk',sans-serif;font-weight:800;color:#fff;font-size:1rem;letter-spacing:.04em">${c.t}</div>
    </div>`).join('');
}
buildClients();

/* ─── TOAST ──────────────────────────────────────────────── */
function showToast(msg, type='info') {
  const toast = document.getElementById('toast');
  if (!toast) return;
  const icons = {success:'✅', error:'❌', info:'💬'};
  toast.textContent = (icons[type]||'') + ' ' + msg;
  toast.style.background = type==='success'?'#00c853':type==='error'?'#ef4444':'#0a0f1e';
  toast.classList.add('show');
  setTimeout(() => toast.classList.remove('show'), 3200);
}

/* ─── LIVE NOTIFICATION TOASTS ───────────────────────────── */
const liveNotifs = [
  '📱 New: 1,450 SMS delivered — 99.9% success',
  '💬 WhatsApp campaign: 380 leads captured',
  '⚡ API: 8,200 messages sent in 2.4s',
  '✅ Coimbatore business started free trial',
  '📊 SMS delivery rate: 99.82% today',
  '🤖 WhatsApp chatbot: 52 auto-responses sent',
];
let liveNI = 0;
setTimeout(() => {
  setInterval(() => { showToast(liveNotifs[liveNI++ % liveNotifs.length]); SFX.waNotify(); }, 12000);
}, 8000);

/* ─── CHATBOT ────────────────────────────────────────────── */
const chatBtn = document.getElementById('cbot');
const chatWin = document.getElementById('cwin');
const chatBody = document.getElementById('cwbody');
const cinp = document.getElementById('cinp');
const cwcl = document.getElementById('cwcl');
const qrs = document.getElementById('qrs');

if (chatBtn) chatBtn.addEventListener('click', () => {
  SFX.enable(); SFX.click();
  const open = chatWin && !chatWin.classList.contains('open');
  if (chatWin) chatWin.classList.toggle('open');
  if (chatBtn.querySelector('.cbot-notif')) chatBtn.querySelector('.cbot-notif').style.display = 'none';
  if (open) setTimeout(() => showTyping(), 800);
});
if (cwcl) cwcl.addEventListener('click', () => { if (chatWin) chatWin.classList.remove('open'); SFX.click(); });
if (cinp) cinp.addEventListener('keydown', e => { if (e.key === 'Enter') sendChat(); });

function addMsg(text, isBot) {
  if (!chatBody) return;
  const d = document.createElement('div');
  d.className = `msg ${isBot ? 'msg-bot' : 'msg-usr'}`;
  d.innerHTML = `<div class="msg-bubble">${text}</div><div class="msg-time">Just now</div>`;
  chatBody.appendChild(d);
  chatBody.scrollTop = chatBody.scrollHeight;
  if (isBot) SFX.waNotify(); else SFX.click();
}

function showTyping() {
  if (!chatBody) return;
  const d = document.createElement('div');
  d.className = 'msg msg-bot'; d.id = 'typingInd';
  d.innerHTML = '<div class="typing-ind"><span></span><span></span><span></span></div>';
  chatBody.appendChild(d);
  chatBody.scrollTop = chatBody.scrollHeight;
}

function removeTyping() {
  const t = document.getElementById('typingInd'); if (t) t.remove();
}

const replies = {
  'bulk sms': '📱 <strong>Bulk SMS</strong><br>We offer Transactional &amp; Promotional SMS with 99.8% delivery.<br>Pricing from <strong>₹0.10/SMS</strong> for volumes above 1L/month.<br><br>Want a custom quote? Call <strong>98437-20001</strong>!',
  'whatsapp': '💬 <strong>WhatsApp Business API</strong><br>Official Meta partner. Plans:<br>• Growth: ₹9,999/year<br>• Advanced: ₹16,999/year<br>• Ultimate: ₹24,999/year<br><br>Includes chatbot, broadcasts &amp; webhooks!',
  'voice': '🎙️ <strong>Voice SMS &amp; IVR</strong><br>Outbound voice SMS, IVR menus, call latching &amp; missed call services.<br><br>Call us for custom Voice SMS pricing: <strong>98437-20001</strong>',
  'pricing': '💰 Our pricing is <strong>fully transparent</strong>:<br>• SMS: from ₹0.10/msg<br>• WhatsApp API: from ₹9,999/yr<br><br><a href="pricing.html" style="color:var(--or)">View all plans →</a>',
  'support': '📞 <strong>Contact Support</strong><br>Phone: <a href="tel:+919843720001" style="color:var(--or)">+91 98437-20001</a><br>WhatsApp: <a href="https://api.whatsapp.com/send?phone=919843720001" target="_blank" style="color:var(--or)">Chat Now</a><br>Email: support@textway.in<br><br>Mon–Sat 9am–7pm IST',
  'default': '👋 Great question! Our team is ready to help. Call <strong>98437-20001</strong> or <a href="contact.html" style="color:var(--or)">send us a message</a> for instant support!',
};

function chatReply(key) {
  if (qrs) qrs.style.display = 'none';
  SFX.enable();
  const labels = {'bulk sms pricing':'📱 Bulk SMS','whatsapp api plans':'💬 WhatsApp API','voice sms info':'🎙️ Voice SMS','contact support':'📞 Support'};
  addMsg(labels[key] || key, false);
  showTyping();
  const rkey = key.toLowerCase();
  let resp = replies.default;
  for (const k in replies) { if (rkey.includes(k)) { resp = replies[k]; break; } }
  setTimeout(() => { removeTyping(); addMsg(resp, true); }, 1200);
}

function sendChat() {
  if (!cinp) return;
  const val = cinp.value.trim();
  if (!val) return;
  SFX.enable();
  if (qrs) qrs.style.display = 'none';
  addMsg(val, false);
  cinp.value = '';
  showTyping();
  const low = val.toLowerCase();
  let resp = replies.default;
  for (const k in replies) { if (low.includes(k)) { resp = replies[k]; break; } }
  setTimeout(() => { removeTyping(); addMsg(resp, true); }, 1100 + Math.random() * 600);
}

/* ─── CONTACT FORM ───────────────────────────────────────── */
function submitForm(e) {
  e.preventDefault();
  SFX.enable(); SFX.click();
  const fn = document.getElementById('fn');
  const fp = document.getElementById('fp');
  const fe = document.getElementById('fe');
  const fm = document.getElementById('fm');
  let valid = true;
  [fn,fp,fe,fm].forEach(el => { if (el) { el.classList.remove('err'); } });
  ['en','ep','ee','em'].forEach(id => { const el=document.getElementById(id); if(el) el.style.display='none'; });
  if (!fn?.value.trim()) { fn.classList.add('err'); document.getElementById('en').style.display='block'; valid=false; }
  if (!fp?.value.trim() || !/^[6-9]\d{9}$/.test(fp.value.replace(/\s/g,''))) { fp.classList.add('err'); document.getElementById('ep').style.display='block'; valid=false; }
  if (!fe?.value.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fe.value)) { fe.classList.add('err'); document.getElementById('ee').style.display='block'; valid=false; }
  if (!fm?.value.trim()) { fm.classList.add('err'); document.getElementById('em').style.display='block'; valid=false; }
  if (!valid) { SFX.error(); return; }
  SFX.success();
  showToast('Message sent! We\'ll call you within 4 hours. 🙏','success');
  [fn,fp,fe,fm].forEach(el => { if(el) el.value=''; });
}

/* ─── BTN SFX ────────────────────────────────────────────── */
document.querySelectorAll('.btnp,.btns,.btns-wh,.btn-price-primary,.btn-price-outline,.nst,.nlog,.nph').forEach(btn => {
  btn.addEventListener('click', () => SFX.click());
  btn.addEventListener('mouseenter', () => SFX.hover());
});

/* ─── INIT ───────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', () => {
  buildClients();
  // Ambient periodic ping when sound is on
  setInterval(() => { if (Math.random() < 0.3) SFX.ambientPing(); }, 18000);
});
