/* VESTIS Москва — /moskva/ v1 */
(function(){
'use strict';
var root=null;
/* ---------- шапка: фон при скролле ---------- */
function initHead(){
var head=document.getElementById('vxm-head');
if(!head)return;
var upd=function(){head.classList.toggle('sc',window.scrollY>24);};
window.addEventListener('scroll',upd,{passive:true});
upd();
}
/* ---------- мобильное меню ---------- */
function initBurger(){
var b=document.getElementById('vxm-burger'),m=document.getElementById('vxm-mnav');
if(!b||!m)return;
var io=b.querySelector('.i-open'),ic=b.querySelector('.i-close');
function set(on){
m.classList.toggle('on',on);
b.setAttribute('aria-expanded',on?'true':'false');
b.setAttribute('aria-label',on?'Закрыть меню':'Открыть меню');
if(io)io.style.display=on?'none':'';
if(ic)ic.style.display=on?'':'none';
document.body.style.overflow=on?'hidden':'';
}
b.addEventListener('click',function(){set(!m.classList.contains('on'));});
m.addEventListener('click',function(e){if(e.target.tagName==='A')set(false);});
document.addEventListener('keydown',function(e){if(e.key==='Escape'&&m.classList.contains('on'))set(false);});
}
/* ---------- появление при скролле ---------- */
function initReveal(){
var els=root.querySelectorAll('.rv');
if(!('IntersectionObserver' in window)){els.forEach?els.forEach(function(e){e.classList.add('in');}):null;return;}
var ob=new IntersectionObserver(function(entries){
entries.forEach(function(en){
if(en.isIntersecting){en.target.classList.add('in');ob.unobserve(en.target);}
});
},{rootMargin:'0px 0px -8% 0px',threshold:0.06});
Array.prototype.forEach.call(els,function(e){ob.observe(e);});
}
/* ---------- лайтбокс ---------- */
var lb,lbImg,lbCnt,lbList=[],lbIdx=0;
function collectGroups(){
var map={};
Array.prototype.forEach.call(root.querySelectorAll('[data-gal]'),function(el){
var g=el.getAttribute('data-gal');
if(!map[g])map[g]=[];
var full=el.getAttribute('data-full')||el.getAttribute('href');
var alt=(el.tagName==='IMG'?el.alt:(el.querySelector('img')?el.querySelector('img').alt:''))||'';
map[g].push({src:full,alt:alt});
el.setAttribute('data-gi',map[g].length-1);
el.setAttribute('data-elementor-open-lightbox','no');
el.addEventListener('click',function(e){
e.preventDefault();
e.stopPropagation();
openLb(map[g],parseInt(el.getAttribute('data-gi'),10)||0);
});
});
}
function buildLb(){
lb=document.createElement('div');
lb.id='vxm-lb';
lb.setAttribute('role','dialog');
lb.setAttribute('aria-label','Просмотр фото');
lb.innerHTML='
'+
''+
''+
''+
'';
document.body.appendChild(lb);
lbImg=lb.querySelector('img');lbCnt=lb.querySelector('.lb-c');
lb.querySelector('.lb-x').addEventListener('click',closeLb);
lb.querySelector('.lb-p').addEventListener('click',function(){stepLb(-1);});
lb.querySelector('.lb-n').addEventListener('click',function(){stepLb(1);});
lb.addEventListener('click',function(e){if(e.target===lb)closeLb();});
document.addEventListener('keydown',function(e){
if(!lb.classList.contains('on'))return;
if(e.key==='Escape')closeLb();
else if(e.key==='ArrowLeft')stepLb(-1);
else if(e.key==='ArrowRight')stepLb(1);
});
}
function openLb(list,idx){
if(!lb)buildLb();
lbList=list;lbIdx=idx;
showLb();
lb.classList.add('on');
document.body.style.overflow='hidden';
lb.querySelector('.lb-x').focus();
}
function showLb(){
var it=lbList[lbIdx];
lbImg.src=it.src;lbImg.alt=it.alt;
lbCnt.textContent=(lbIdx+1)+' / '+lbList.length;
var one=lbList.length<2;
lb.querySelector('.lb-p').style.display=one?'none':'';
lb.querySelector('.lb-n').style.display=one?'none':'';
}
function stepLb(d){lbIdx=(lbIdx+d+lbList.length)%lbList.length;showLb();}
function closeLb(){lb.classList.remove('on');document.body.style.overflow='';}
/* ---------- FAQ: открыт один ---------- */
function initFaq(){
var items=root.querySelectorAll('.faq-item');
Array.prototype.forEach.call(items,function(it){
var q=it.querySelector('.faq-q'),a=it.querySelector('.faq-a');
q.addEventListener('click',function(){
var on=it.classList.contains('on');
Array.prototype.forEach.call(items,function(o){
o.classList.remove('on');
o.querySelector('.faq-q').setAttribute('aria-expanded','false');
o.querySelector('.faq-a').style.maxHeight='';
});
if(!on){
it.classList.add('on');
q.setAttribute('aria-expanded','true');
a.style.maxHeight=a.scrollHeight+'px';
}
});
});
}
/* ---------- маска телефона ---------- */
function fmtPhone(v){
var d=v.replace(/\D/g,'');
if(d.length&&(d[0]==='7'||d[0]==='8'))d=d.slice(1);
d=d.slice(0,10);
var out='+7';
if(d.length)out+=' ('+d.slice(0,3);
if(d.length>=4)out+=') '+d.slice(3,6);
if(d.length>=7)out+='-'+d.slice(6,8);
if(d.length>=9)out+='-'+d.slice(8,10);
return out;
}
function initPhone(){
var p=document.getElementById('f-phone');
if(!p)return;
p.addEventListener('input',function(){
var v=p.value.replace(/\D/g,'');
p.value=v?fmtPhone(p.value):'';
});
p.addEventListener('focus',function(){if(!p.value)p.value='+7 (';});
p.addEventListener('blur',function(){if(p.value==='+7 ('||p.value==='+7')p.value='';});
}
/* ---------- кнопки с предвыбором интереса ---------- */
function initInterest(){
Array.prototype.forEach.call(root.querySelectorAll('[data-interest]'),function(a){
a.addEventListener('click',function(){
var s=document.getElementById('f-int');
if(s)s.value=a.getAttribute('data-interest');
});
});
}
/* ---------- отправка формы (vst_lead) ---------- */
function initForm(){
var f=document.getElementById('vxm-form');
if(!f)return;
f.addEventListener('submit',function(e){
e.preventDefault();
var msg=f.querySelector('.fmsg'),btn=f.querySelector('button[type="submit"]');
var name=f.name.value.trim(),phone=f.phone.value.trim();
var digits=phone.replace(/\D/g,'');
if(!name){msg.textContent='Укажите имя';msg.className='fmsg err';f.name.focus();return;}
if(digits.length<11){msg.textContent='Укажите телефон полностью';msg.className='fmsg err';f.phone.focus();return;}
if(f.dataset.busy==='1')return; /* v4: защита от двойной отправки */
f.dataset.busy='1';btn.disabled=true;msg.textContent='Отправляем…';msg.className='fmsg';
/* v4: поля уходят по отдельности — сервер собирает структурированную заявку (CRM + Telegram дилера) */
var body='action=vst_lead&form=moskva&service='+encodeURIComponent('Москва — аксессуары (филиал)')+'&name='+encodeURIComponent(name)+'&phone='+encodeURIComponent(phone)+'&interest='+encodeURIComponent(f.interest.value)+'&car='+encodeURIComponent(f.car.value.trim())+'&msg='+encodeURIComponent(f.msg.value.trim())+'&page='+encodeURIComponent(location.href.split('#')[0]);
fetch('https://vestis.pro/wp-admin/admin-ajax.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:body})
.then(function(r){return r.json();})
.then(function(j){
if(j&&j.success){
msg.textContent='Спасибо! Ваша заявка отправлена. Мы свяжемся с вами в ближайшее время.';
msg.className='fmsg ok';
f.reset();
}else{
msg.textContent=(j&&j.data&&j.data.msg)||'Не удалось отправить заявку. Позвоните нам: +7 (903) 799-66-46 или напишите в Telegram.';
msg.className='fmsg err';
}
btn.disabled=false;f.dataset.busy='';
})
.catch(function(){
msg.textContent='Не удалось отправить заявку: ошибка сети. Попробуйте ещё раз или напишите в Telegram.';
msg.className='fmsg err';
btn.disabled=false;f.dataset.busy='';
});
});
}
/* ---------- год в подвале ---------- */
function initYear(){
var y=document.getElementById('vxm-year');
if(y)y.textContent=String(new Date().getFullYear());
}
/* ---------- boot (WPFC-safe: ретраи до появления контейнера) ---------- */
function boot(){
root=document.getElementById('vxm');
if(!root){boot._n=(boot._n||0)+1;if(boot._n<200)setTimeout(boot,50);return;}
if(root.getAttribute('data-vxm'))return;
root.setAttribute('data-vxm','1');
root.classList.add('js');
initHead();initBurger();initReveal();collectGroups();initFaq();initPhone();initInterest();initForm();initYear();
}
window.__vxmLoaded=true;
boot();
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',boot);
window.addEventListener('load',boot);
})();