import {ENDPOINT,buildPayload,accepted} from './form-contract.mjs'; import {submitMock} from './local-mock.mjs'; async function submitTransport(endpoint,payload,form){ if(location.hostname==='ostrovnayageometriya.ru'){ const response=await globalThis['fetch'](endpoint,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),credentials:'omit'}); let body={};try{body=await response.json();}catch{} return {ok:response.ok,body}; } return submitMock(endpoint,payload,form); } for(const menu of document.querySelectorAll('.mobile-menu')){ const toggle=menu.querySelector('.mobile-menu__toggle'),panel=menu.querySelector('.mobile-menu__panel'); const setOpen=open=>{menu.classList.toggle('mobile-menu--open',open);toggle.setAttribute('aria-expanded',String(open));toggle.querySelector('strong').textContent=open?'Закрыть':'Меню';panel.hidden=!open;}; toggle.addEventListener('click',()=>setOpen(toggle.getAttribute('aria-expanded')!=='true')); for(const link of menu.querySelectorAll('a'))link.addEventListener('click',()=>setOpen(false)); } for(const form of document.querySelectorAll('.lead-form')){ const capture=document.body.dataset.formCapture==='true',consentVariant=document.body.dataset.formVariant==='ConsentLeadForm'; const message=form.elements.namedItem('message');const defaultMessage=message.value; const button=form.querySelector('[type=submit]'),note=form.querySelector('.form-note'); const noteState=(value,state)=>{note.textContent=value;note.setAttribute('role','status');if(capture)note.style.color=state==='success'?'#256b38':'#b3322d';else note.className='form-note form-note--'+state;}; form.addEventListener('submit',async event=>{ event.preventDefault();event.stopImmediatePropagation();if(!form.reportValidity())return; const fields=Object.fromEntries(new FormData(form)); const payload=buildPayload({fields,context:{url:location.href,search:location.search,referrer:document.referrer,title:document.title,formId:form.id||form.getAttribute('name'),h1:document.querySelector('h1')?.textContent||'',eyebrow:document.querySelector('.eyebrow')?.textContent||''},capture,consentVariant,requestId:crypto.randomUUID(),timestamp:new Date().toISOString()}); const old=button.textContent;button.disabled=true;button.textContent='Отправляем...';if(!capture)noteState('Отправляем заявку...','sending'); try{ const result=await submitTransport(ENDPOINT,payload,form); if(!accepted(result,capture))throw Error(result.body.error||'FORM_NOT_ACCEPTED'); form.reset();message.value=defaultMessage; noteState(capture?'Спасибо! Заявка принята. Мы свяжемся с вами в ближайшее время.':'Спасибо! Заявка отправлена. Мы свяжемся с вами после обработки обращения.','success'); if(!capture)button.disabled=false; }catch(error){ const config=String(error.message).includes('MAX_NOT_CONFIGURED'); noteState(capture?(config?'Канал MAX еще требует настройки получателя. Почтовая программа не открывается; заявка не ушла.':'Не удалось отправить заявку в MAX. Почтовая программа не открывается; повторите отправку позже.'):(config?'Канал MAX еще требует настройки получателя. Почтовая программа не открывается; до включения MAX можно написать на ostrovnayageometriya@mail.ru.':'Заявка не отправилась. Почтовая программа не открывается; повторите отправку или напишите на ostrovnayageometriya@mail.ru.'),'error'); button.disabled=false; }finally{if(!button.disabled)button.textContent=old;} }); if(capture)for(const link of document.querySelectorAll('a[href^="mailto:"]'))link.addEventListener('click',event=>{event.preventDefault();form.scrollIntoView({behavior:'smooth',block:'center'});form.querySelector('[name=name],[name=phone]')?.focus({preventScroll:true});}); }