import {config} from './config.mjs';
import {validateLead,sendLead} from './form.mjs';
const $=s=>document.querySelector(s);
const menu=$('#mobile-menu'),toggle=$('.menu-toggle');
function closeMenu(){menu.close();toggle.setAttribute('aria-expanded','false');document.body.style.overflow='';}
toggle.addEventListener('click',()=>{menu.showModal();toggle.setAttribute('aria-expanded','true');document.body.style.overflow='hidden';});
$('.menu-close').addEventListener('click',closeMenu);
menu.addEventListener('cancel',e=>{e.preventDefault();closeMenu();});
menu.addEventListener('click',e=>{if(e.target===menu && e.clientX
a.addEventListener('click',closeMenu));
matchMedia('(min-width: 1101px)').addEventListener('change',e=>{if(e.matches&&menu.open)closeMenu();});
// Keep approved icons intact; bind only destinations actually supplied by the owner.
document.querySelectorAll('.unconfigured-social').forEach(button=>{
const telegram=button.getAttribute('aria-label').startsWith('Telegram');
const url=telegram?config.telegramUrl:config.instagramUrl;
if(url){const a=document.createElement('a');a.href=url;a.target='_blank';a.rel='noopener';a.setAttribute('aria-label',telegram?'Telegram':'Instagram');a.append(...button.childNodes);button.replaceWith(a);}
else button.addEventListener('click',()=>showToast('Ссылка Instagram пока не указана. Свяжитесь с нами в WhatsApp.'));
});
let toastTimer;
function showToast(message){const toast=$('.toast');toast.textContent=message;toast.hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>toast.hidden=true,5000);}
const select=$('#objectType'),options=$('#object-options'),value=$('#objectType-value'),hidden=$('input[name="objectType"]');
const choices=[...options.querySelectorAll('[role=option]')];
function setObject(text){hidden.value=text;value.textContent=text||'Выберите тип';choices.forEach(o=>o.setAttribute('aria-selected',String(o.dataset.value===text)));select.removeAttribute('aria-invalid');$('#objectType-error').textContent='';}
function closeOptions(focus=false){options.hidden=true;select.setAttribute('aria-expanded','false');if(focus)select.focus();}
function openOptions(){options.hidden=false;select.setAttribute('aria-expanded','true');(choices.find(o=>o.dataset.value===hidden.value)||choices[0]).focus();}
select.addEventListener('click',()=>options.hidden?openOptions():closeOptions(true));
select.addEventListener('keydown',e=>{if(['ArrowDown','ArrowUp'].includes(e.key)){e.preventDefault();openOptions();}});
choices.forEach((option,index)=>{
option.addEventListener('click',()=>{setObject(option.dataset.value);closeOptions(true);});
option.addEventListener('keydown',e=>{
if(['ArrowDown','ArrowUp','Home','End'].includes(e.key)){e.preventDefault();choices[e.key==='Home'?0:e.key==='End'?choices.length-1:(index+(e.key==='ArrowDown'?1:-1)+choices.length)%choices.length].focus();}
if(e.key==='Enter'||e.key===' '){e.preventDefault();option.click();}
if(e.key==='Escape'){e.preventDefault();closeOptions(true);}
if(e.key==='Tab')closeOptions();
});
});
document.addEventListener('click',e=>{if(!e.target.closest('.select-field'))closeOptions();});
document.querySelectorAll('a[href^="#"]').forEach(a=>a.addEventListener('click',()=>{
const target=document.querySelector(a.getAttribute('href'));if(!target)return;
if(a.dataset.object)setObject(a.dataset.object);
if(target.id==='request'){const heading=target.querySelector('h2');heading.tabIndex=-1;heading.focus({preventScroll:true});}
else {target.tabIndex=-1;target.focus({preventScroll:true});}
}));
const form=$('#lead-form'),status=form.querySelector('.form-status'),submit=form.querySelector('[type=submit]');
form.addEventListener('input',e=>{if(e.target.id){e.target.removeAttribute('aria-invalid');const error=document.getElementById(e.target.id+'-error');if(error)error.textContent='';}});
let submitting=false;
form.addEventListener('submit',async e=>{
e.preventDefault();if(submitting)return;
const data=Object.fromEntries(new FormData(form));
const errors=validateLead(data);
form.querySelectorAll('[aria-invalid]').forEach(el=>el.removeAttribute('aria-invalid'));
form.querySelectorAll('.field-error').forEach(el=>el.textContent='');
status.hidden=true;
if(Object.keys(errors).length){
for(const [name,message] of Object.entries(errors)){const field=document.getElementById(name);field?.setAttribute('aria-invalid','true');const error=document.getElementById(name+'-error');if(error)error.textContent=message;}
document.getElementById(Object.keys(errors)[0])?.focus();return;
}
submitting=true;submit.disabled=true;submit.textContent='Отправляем…';form.setAttribute('aria-busy','true');
try {
await sendLead(data,{endpoint:config.leadEndpoint});
status.textContent='Заявка отправлена. Мы свяжемся с вами по телефону.';status.classList.add('success');form.reset();setObject('');
} catch(error){status.textContent=error.message;status.classList.remove('success');}
finally {submitting=false;submit.disabled=false;submit.textContent='Отправить запрос';form.removeAttribute('aria-busy');status.hidden=false;status.focus({preventScroll:true});}
});
submit.disabled=false;
// Reveal only offscreen content; the first screen is never delayed.
if(!matchMedia('(prefers-reduced-motion: reduce)').matches && 'IntersectionObserver' in window){
const observer=new IntersectionObserver(entries=>entries.forEach(entry=>{if(entry.isIntersecting){entry.target.classList.remove('is-waiting');observer.unobserve(entry.target);}}),{threshold:.08});
document.querySelectorAll('.reveal').forEach(el=>{if(el.getBoundingClientRect().top>innerHeight){el.classList.add('is-waiting');observer.observe(el);}});
}