function getFlagBase(){const el=document.getElementById("dpBlock");return(el&&el.dataset.flagBase||"/wp-content/uploads/flags/4x3/").replace(/\/+$/,"")+"/"}function toggleAllCountries(btn){const extra=document.getElementById("countriesExtra");extra.classList.toggle("open"),btn.classList.toggle("open"),btn.querySelector("span.btn-show-all-count").textContent=extra.classList.contains("open")?"скрыть":"190+"}function toggleFaq(btn){const answer=btn.nextElementSibling,isOpen=btn.classList.contains("open");document.querySelectorAll(".faq-question.open").forEach((b=>{b.classList.remove("open");const a=b.nextElementSibling;a.classList.remove("open"),a.style.maxHeight=null})),isOpen||(btn.classList.add("open"),answer.classList.add("open"),answer.style.maxHeight=answer.scrollHeight+"px")}document.addEventListener("DOMContentLoaded",(function(){const menuBtn=document.getElementById("menuBtn"),mobileNav=document.getElementById("mobileNav");menuBtn&&mobileNav&&menuBtn.addEventListener("click",(()=>mobileNav.classList.toggle("open"))),document.addEventListener("click",(function(e){var link=e.target.closest(".mobile-nav .menu-item-has-children > a");if(link){var href=link.getAttribute("href");href&&"#"!==href||(e.preventDefault(),link.parentElement.classList.toggle("sub-open"))}}));const reveals=document.querySelectorAll(".reveal");if(reveals.length){const observer=new IntersectionObserver((entries=>{entries.forEach((e=>{e.isIntersecting&&e.target.classList.add("visible")}))}),{threshold:.12});reveals.forEach((el=>observer.observe(el)))}}));let mCurrentPrice="",mCurrentPackageCode="",mAppliedPromo="",mDiscountedPrice="",mCurrentDays=0;function getCookie(name){const match=document.cookie.match(new RegExp("(?:^|;)"+name+"=([^;]*)"));return match?decodeURIComponent(match[1]):""}function setCookie(name,value,days){const d=new Date;d.setTime(d.getTime()+864e5*days),document.cookie=name+"="+encodeURIComponent(value)+";path=/;expires="+d.toUTCString()}function deleteCookie(name){document.cookie=name+"=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT"}function getModalEls(){return{flag:document.getElementById("mFlag"),name:document.getElementById("mName"),spec:document.getElementById("mSpec"),price:document.getElementById("mPriceEl"),total:document.getElementById("mTotal"),totalOld:document.getElementById("mTotalOld"),promo:document.getElementById("mPromo"),promoInputRow:document.getElementById("promoInputRow"),promoApplied:document.getElementById("promoApplied"),promoAppliedCode:document.getElementById("promoAppliedCode"),promoRemove:document.getElementById("promoRemove"),promoError:document.getElementById("promoError"),email:document.getElementById("mEmail"),form:document.getElementById("mForm"),success:document.getElementById("mSuccess"),successIcon:document.getElementById("mSuccessIcon"),successTitle:document.getElementById("mSuccessTitle"),successText:document.getElementById("mSuccessText"),successBtn:document.getElementById("mSuccessBtn"),successClose:document.getElementById("mSuccessClose"),modal:document.getElementById("modal"),chkError:document.getElementById("chkError"),packageCode:document.getElementById("mPackageCode")}}const modalEls=new Proxy({},{get:(_,key)=>getModalEls()[key]}),REQUIRED_CHECKBOXES=["chkOferta","chkPd","chkEsim"];function renderFlag(flagHtml,countryCode){const el=modalEls.flag;if(el)if(flagHtml)el.innerHTML=flagHtml;else if(countryCode){const base=getFlagBase();el.innerHTML='<img class="modal-flag-img" src="'+base+countryCode.toLowerCase()+'.svg" alt="">'}else el.innerHTML=""}function openModal(t){mCurrentPrice=t.price||"",mCurrentPackageCode=t.packageCode||t.pack_code||"",mAppliedPromo="",mDiscountedPrice="",mCurrentDays=t.days||0,renderFlag(t.flag||"",t.countryCode||""),modalEls.name&&(modalEls.name.textContent=t.name||""),modalEls.spec&&(modalEls.spec.textContent=t.spec||t.data||""),modalEls.price&&(modalEls.price.textContent=t.price||""),modalEls.packageCode&&(modalEls.packageCode.value=mCurrentPackageCode);const savedPromo=getCookie("redesim_promo_code");savedPromo?(modalEls.promo&&(modalEls.promo.value=savedPromo),applyPromo()):(resetPromoUI(),setTotalPrice(mCurrentPrice,"")),modalEls.email&&(modalEls.email.value=""),modalEls.form&&(modalEls.form.style.display=""),modalEls.success&&(modalEls.success.style.display="none"),"function"==typeof resetChecks&&resetChecks(),modalEls.modal.classList.add("open"),document.body.style.overflow="hidden",window.RedesimTariffHash&&mCurrentPackageCode&&window.RedesimTariffHash.set(mCurrentPackageCode)}function closeModal(){modalEls.modal.classList.remove("open"),document.body.style.overflow="",window.RedesimTariffHash&&window.RedesimTariffHash.clear()}function setTotalPrice(newPrice,oldPrice){modalEls.total&&(modalEls.total.textContent=newPrice||""),modalEls.totalOld&&(oldPrice?(modalEls.totalOld.textContent=oldPrice,modalEls.totalOld.classList.add("visible")):(modalEls.totalOld.textContent="",modalEls.totalOld.classList.remove("visible")))}function resetPromoUI(){modalEls.promoInputRow&&(modalEls.promoInputRow.style.display=""),modalEls.promoApplied&&(modalEls.promoApplied.style.display="none"),modalEls.promoError&&(modalEls.promoError.style.display="none"),modalEls.promoError&&(modalEls.promoError.textContent=""),modalEls.promo&&(modalEls.promo.value=""),mAppliedPromo="",mDiscountedPrice=""}function applyPromo(){const code=(modalEls.promo?.value||"").trim(),packCode=mCurrentPackageCode||modalEls.packageCode?.value||"";if(!code)return;const btn=document.querySelector(".btn-promo");btn&&(btn.disabled=!0,btn.textContent="..."),modalEls.promoError&&(modalEls.promoError.style.display="none",modalEls.promoError.textContent=""),fetch("/api/v2/promo/get",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:code,pack_code:packCode,...mCurrentDays?{days:mCurrentDays}:{}})}).then((r=>r.json())).then((data=>{if(btn&&(btn.disabled=!1,btn.textContent="Применить"),data.success){const priceNew=Number(data.data.price_promo).toLocaleString("ru-RU")+"₽",priceOld=Number(data.data.price).toLocaleString("ru-RU")+"₽";mAppliedPromo=code,mDiscountedPrice=priceNew,mCurrentPrice=priceOld,setTotalPrice(priceNew,priceOld),setCookie("redesim_promo_code",code,7),modalEls.promoInputRow&&(modalEls.promoInputRow.style.display="none"),modalEls.promoApplied&&(modalEls.promoApplied.style.display="flex"),modalEls.promoAppliedCode&&(modalEls.promoAppliedCode.textContent=code.toUpperCase())}else modalEls.promoError&&(modalEls.promoError.textContent=data.message||"Промокод не найден",modalEls.promoError.style.display="block")})).catch((()=>{btn&&(btn.disabled=!1,btn.textContent="Применить"),modalEls.promoError&&(modalEls.promoError.textContent="Ошибка соединения",modalEls.promoError.style.display="block")}))}function removePromo(){deleteCookie("redesim_promo_code"),resetPromoUI(),setTotalPrice(mCurrentPrice,"")}!function(){function encodeBase64Url(value){value=String(value||"");try{return btoa(unescape(encodeURIComponent(value))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}catch(e){return""}}function decodeBase64Url(value){if(!(value=String(value||"").trim()))return"";try{let normalized=value.replace(/-/g,"+").replace(/_/g,"/");for(;normalized.length%4;)normalized+="=";const decoded=atob(normalized);try{return decodeURIComponent(Array.prototype.map.call(decoded,(function(ch){return"%"+("00"+ch.charCodeAt(0).toString(16)).slice(-2)})).join(""))}catch(e){return decoded}}catch(e){return""}}window.RedesimTariffHash={encode:encodeBase64Url,decode:decodeBase64Url,getCode:function(){const hash=String(window.location.hash||"").replace(/^#/,"");return hash&&0===hash.indexOf("tf=")?decodeBase64Url(hash.slice(3)):""},set:function(packageCode){if(!(packageCode=String(packageCode||"").trim()))return;const encoded=encodeBase64Url(packageCode);if(!encoded)return;const url=window.location.pathname+window.location.search+"#tf="+encoded;window.history.replaceState(null,"",url)},clear:function(){if(0!==String(window.location.hash||"").replace(/^#/,"").indexOf("tf="))return;const url=window.location.pathname+window.location.search;window.history.replaceState(null,"",url)},findRow:function(packageCode){if(!(packageCode=String(packageCode||"").trim()))return null;if(window.CSS&&"function"==typeof window.CSS.escape){const row=document.querySelector('.t-row[data-id="'+window.CSS.escape(packageCode)+'"]');if(row)return row}return Array.prototype.find.call(document.querySelectorAll(".t-row[data-id]"),(function(row){return row.dataset.id===packageCode}))||null}}}(),function(){let homeTfOpening="";function pluralDaysLocal(days){const n=Math.abs(Number(days))%100,n1=n%10;return n>10&&n<20?"дней":n1>1&&n1<5?"дня":1===n1?"день":"дней"}function getFlagHtmlLocal(countryName,countryCode){const code=String(countryCode||"").toLowerCase();if(!code)return"";return'<img class="countries-flag-mini" alt="'+String(countryName||"").replace(/&/g,"&amp;").replace(/"/g,"&quot;")+'" src="'+getFlagBase()+code+'.svg">'}function buildModalDataFromPackage(item,chip){const countryCode=String(item.country_code||chip?.dataset?.cCode||"").toLowerCase(),countryName=item.country_name?.name||chip?.dataset?.name||chip?.dataset?.nameEn||"",gb=function(megabyte){const mb=Number(megabyte||0);if(!mb)return"";if(mb>=1024){const gb=mb/1024;return Number.isInteger(gb)?`${gb} ГБ`:`${gb.toFixed(1)} ГБ`}return`${mb} МБ`}(item.megabyte||item.format_megabyte||item.volume||0),days=item.duration||item.period||"",speed=item.speed||"",price=(value=item.price_rub_format||item.price_rub||item.priceRUB||item.price||"",(value=String(value||"").trim())?-1!==value.indexOf("₽")?value:value+" ₽":"");var value;return{name:countryName,flag:getFlagHtmlLocal(countryName,countryCode),data:[gb,days?`${days} ${pluralDaysLocal(days)}`:"",speed].filter(Boolean).join(" · "),price:price,packageCode:item.package_code||item.packageCode||"",countryCode:countryCode,provider:item.provider||chip?.dataset?.p||"",megabyte:String(item.megabyte||item.format_megabyte||item.volume||""),duration:String(days||"")}}async function fetchPackagesForChip(chip){const countryCode=String(chip?.dataset?.cCode||"").toLowerCase(),pc=String(chip?.dataset?.packages||"").trim(),pr=String(chip?.dataset?.p||"").trim();if(!countryCode||!pc||!pr)return[];const url=`/api/v2/countries/popular/packages?pc=${encodeURIComponent(pc)}&cc=${encodeURIComponent(countryCode)}&pr=${encodeURIComponent(pr)}`,response=await fetch(url,{method:"GET",headers:{Accept:"application/json"}});if(!response.ok)return[];const json=await response.json();return json&&json.success&&Array.isArray(json.data)?json.data:[]}async function openHomeTariffFromHash(){if(!document.getElementById("dpBlock")&&!document.querySelector(".dest-picker")||!window.RedesimTariffHash||"function"!=typeof openModal)return!1;const packageCode=window.RedesimTariffHash.getCode();if(!packageCode)return!1;if(homeTfOpening===packageCode)return!1;if(modalEls.modal?.classList.contains("open")&&String(modalEls.packageCode?.value||"")===packageCode)return!0;homeTfOpening=packageCode;try{if(function(packageCode){const option=Array.prototype.slice.call(document.querySelectorAll(".dp-opt[data-package-code]")).find((function(opt){return String(opt.dataset.packageCode||"")===packageCode}));return!!option&&(openModal({name:option.dataset.countryName||"",flag:option.dataset.countryFlag||"",data:option.dataset.data||"",price:option.dataset.price||"",packageCode:option.dataset.packageCode||"",countryCode:option.dataset.countryCode||"",provider:option.dataset.provider||"",megabyte:option.dataset.megabyte||"",duration:option.dataset.duration||""}),!0)}(packageCode))return!0;const chips=Array.prototype.slice.call(document.querySelectorAll(".dp-chip[data-packages][data-c-code][data-p]"));for(const chip of chips){const found=(await fetchPackagesForChip(chip)).find((function(item){return String(item.package_code||item.packageCode||"")===packageCode}));if(found)return openModal(buildModalDataFromPackage(found,chip)),!0}}catch(e){console.warn("Не удалось открыть тариф по #tf на главной странице",e)}finally{setTimeout((function(){homeTfOpening=""}),0)}return!1}document.addEventListener("DOMContentLoaded",(function(){setTimeout(openHomeTariffFromHash,300)})),window.addEventListener("hashchange",(function(){openHomeTariffFromHash()}))}();const ALL_CHECKBOXES=["chkOferta","chkPd","chkEsim","chkAds"];function toggleAllChecks(chkAll){const checked=chkAll.checked;if(ALL_CHECKBOXES.forEach((function(id){const el=document.getElementById(id);if(el&&(el.checked=checked,checked)){const row=el.closest(".check-row");row&&row.classList.remove("check-row--error")}})),checked){const chkError=document.getElementById("chkError");chkError&&(chkError.style.display="none")}}function syncAllCheck(){const chkAll=document.getElementById("chkAll");chkAll&&(chkAll.checked=ALL_CHECKBOXES.every((function(id){const el=document.getElementById(id);return el&&el.checked})))}function resetChecks(){const chkAll=document.getElementById("chkAll");chkAll&&(chkAll.checked=!1),ALL_CHECKBOXES.forEach((function(id){const el=document.getElementById(id);if(el){el.checked=!1;const row=el.closest(".check-row");row&&row.classList.remove("check-row--error")}}));const chkError=document.getElementById("chkError");chkError&&(chkError.style.display="none")}function submitPurchase(){const email=modalEls.email?.value.trim();if(!email||!email.includes("@"))return void modalEls.email?.focus();if(!REQUIRED_CHECKBOXES.every((id=>{const el=document.getElementById(id);return el&&el.checked})))return REQUIRED_CHECKBOXES.forEach((function(id){const el=document.getElementById(id);if(!el)return;const row=el.closest(".check-row");row&&(el.checked||(row.classList.add("check-row--error"),el.addEventListener("change",(function onFix(){row.classList.remove("check-row--error"),el.removeEventListener("change",onFix);REQUIRED_CHECKBOXES.every((function(rid){const rel=document.getElementById(rid);return rel&&rel.checked}))&&modalEls.chkError&&(modalEls.chkError.style.display="none")}))))})),void(modalEls.chkError&&(modalEls.chkError.style.display="flex",modalEls.chkError.scrollIntoView({behavior:"smooth",block:"nearest"})));REQUIRED_CHECKBOXES.forEach((function(id){const el=document.getElementById(id);el&&el.closest(".check-row")?.classList.remove("check-row--error")})),modalEls.chkError&&(modalEls.chkError.style.display="none"),modalEls.form&&(modalEls.form.style.display="none"),modalEls.success&&(modalEls.success.style.display="block"),modalEls.successIcon&&(modalEls.successIcon.textContent="⏳"),modalEls.successTitle&&(modalEls.successTitle.textContent="Создаём заказ..."),modalEls.successText&&(modalEls.successText.textContent="Подождите несколько секунд."),modalEls.successBtn&&(modalEls.successBtn.style.display="none"),modalEls.successClose&&(modalEls.successClose.style.display="none");const payload={email:email,package_code:mCurrentPackageCode||modalEls.packageCode?.value||"",promo_code:mAppliedPromo||"",days:mCurrentDays||void 0};fetch("/api/v2/order/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload)}).then((r=>r.json())).then((data=>{data.success&&data.data?.url?window.location.href=data.data.url:(modalEls.successIcon&&(modalEls.successIcon.innerHTML='<img class="modal_icon" src="/wp-content/uploads/img/warning.png">'),modalEls.successTitle&&(modalEls.successTitle.textContent="Что-то пошло не так"),modalEls.successText&&(modalEls.successText.textContent=data.message||"Не удалось создать заказ. Попробуйте ещё раз."),modalEls.successClose&&(modalEls.successClose.style.display=""))})).catch((()=>{modalEls.successIcon&&(modalEls.successIcon.innerHTML='<img class="modal_icon" src="/wp-content/uploads/img/warning.png">'),modalEls.successTitle&&(modalEls.successTitle.textContent="Что-то пошло не так"),modalEls.successText&&(modalEls.successText.textContent="Сервис банка временно недоступен. Попробуйте повторить позднее."),modalEls.successClose&&(modalEls.successClose.style.display="")}))}function dpSearch(val){const query=val.trim(),FLAG_BASE=getFlagBase();query?fetch(`/search/?q=${encodeURIComponent(query)}*`,{method:"GET",headers:{"Content-Type":"application/json"}}).then((resp=>resp.json())).then((comp=>{const hits=comp?.hits?.hits||[];if(!(comp?.hits?.total?.value||0)||!hits.length)return void showDpNoResults();let html="";const used=new Set;hits.forEach((element=>{const source=element?._source||{},countryCodeRaw=source.country_code||"",cCode=String(countryCodeRaw).toLowerCase();if(!cCode||"ua"===cCode||"ru"===cCode)return;const cName=source.country_name||"";let cNameE=source.country_name_en||"";if(!cName||!cNameE)return;const uniqKey=cNameE.toLowerCase();if(used.has(uniqKey))return;used.add(uniqKey);let hrefName=cNameE,flagHtml=`<img loading="lazy" class="countries-flag-mini" alt="${escapeHtml(cName)}" src="${FLAG_BASE}${escapeHtml(cCode)}.svg">`;"Europe"!==cNameE&&"Asia"!==cNameE&&"Africa"!==cNameE&&"Global"!==cNameE||(hrefName=`region-${cNameE}`,flagHtml='<span class="countries-flag-mini countries-flag-mini--none"></span>');const href=`/esim/${slugifyCountryName(hrefName)}`;html+=`\n                    <a class="dp-search-item" href="${escapeHtml(href)}/">\n                        <span class="dp-search-item-flag">${flagHtml}</span>\n                        <span class="dp-search-item-name">${escapeHtml(cName)}</span>\n                    </a>\n                `})),html?showDpSearchResults(html):showDpNoResults()})).catch((e=>{console.log(e),showDpNoResults()})):resetDpSearchState()}function resetDpSearchState(){const dpSearchResults=document.getElementById("dpSearchResults"),dpResult=document.getElementById("dpResult"),dpNoResult=document.getElementById("dpNoResult"),dpChips=document.getElementById("dpChips"),dpChipsLabel=document.getElementById("dpChipsLabel");dpSearchResults&&(dpSearchResults.style.display="none",dpSearchResults.innerHTML=""),dpResult&&dpResult.classList.add("show"),dpNoResult&&dpNoResult.classList.remove("show"),dpChips&&(dpChips.style.display=""),dpChipsLabel&&(dpChipsLabel.textContent="Популярные направления")}function showDpSearchResults(html){const dpSearchResults=document.getElementById("dpSearchResults"),dpResult=document.getElementById("dpResult"),dpNoResult=document.getElementById("dpNoResult"),dpChips=document.getElementById("dpChips"),dpChipsLabel=document.getElementById("dpChipsLabel");dpResult&&dpResult.classList.remove("show"),dpNoResult&&dpNoResult.classList.remove("show"),dpChips&&(dpChips.style.display="none"),dpChipsLabel&&(dpChipsLabel.textContent="Результаты поиска"),dpSearchResults&&(dpSearchResults.innerHTML=html,dpSearchResults.style.display="block")}function showDpNoResults(){const dpSearchResults=document.getElementById("dpSearchResults"),dpResult=document.getElementById("dpResult"),dpNoResult=document.getElementById("dpNoResult"),dpChips=document.getElementById("dpChips"),dpChipsLabel=document.getElementById("dpChipsLabel");dpSearchResults&&(dpSearchResults.style.display="none",dpSearchResults.innerHTML=""),dpResult&&dpResult.classList.remove("show"),dpChips&&(dpChips.style.display="none"),dpChipsLabel&&(dpChipsLabel.textContent="Результаты поиска"),dpNoResult&&dpNoResult.classList.add("show")}function slugifyCountryName(name){return String(name||"").trim().toLowerCase().replace(/\s|,|'|`/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function escapeHtml(str){return String(str||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function initCookieNotice(){if(document.cookie.split("; ").some((row=>row.startsWith("redesim_cookie_notice_closed="))))return;if(document.getElementById("cookieNotice"))return;const notice=document.createElement("div");notice.id="cookieNotice",notice.className="cookie-notice",notice.innerHTML='\n    <p class="cookie-notice__text">\n      Мы используем файлы cookie. Оставаясь на сайте, вы соглашаетесь с<br>\n      <a href="/privacy-policy/" target="_blank" rel="noopener noreferrer">Политика конфиденциальности</a>, <a href="/soglasie-na-obrabotku-personalnyh-dannyh/" target="_blank" rel="noopener noreferrer">Согласие на обработку персональных данных</a>\n    </p>\n    <button type="button" class="cookie-notice__close" aria-label="Закрыть уведомление">\n      Закрыть\n    </button>\n  ',document.body.appendChild(notice);notice.querySelector(".cookie-notice__close").addEventListener("click",(function(){const expires=new Date;expires.setTime(expires.getTime()+31536e6),document.cookie="redesim_cookie_notice_closed=1; expires="+expires.toUTCString()+"; path=/; SameSite=Lax",notice.remove()}))}document.addEventListener("keydown",(e=>{"Escape"===e.key&&modalEls.modal?.classList.contains("open")&&closeModal()})),document.addEventListener("DOMContentLoaded",(()=>{const dpInput=document.getElementById("dpInput"),dpClearBtn=document.getElementById("dpClearBtn"),cSearch=document.getElementById("cSearch"),dpResult=document.getElementById("dpResult"),dpNoResult=document.getElementById("dpNoResult"),dpOptions=document.getElementById("dpOptions"),dpResultName=document.getElementById("dpResultName");let dpSearchTimeout,dpAbortController=null,dpRequestId=0;if(!dpInput)return;function toggleDpClearBtn(){dpClearBtn&&dpClearBtn.classList.toggle("show",dpInput.value.trim().length>0)}dpClearBtn&&dpClearBtn.addEventListener("click",(function(){dpInput.value="",resetDpSearchState(),toggleDpClearBtn(),dpInput.focus()})),cSearch&&cSearch.addEventListener("click",(()=>{const value=dpInput.value.trim();value.length>=4?dpSearch(value):0===value.length&&resetDpSearchState(),toggleDpClearBtn()})),dpInput.addEventListener("input",(event=>{const search=event.target.value.trim();clearTimeout(dpSearchTimeout),toggleDpClearBtn(),search?search.length>=4&&(dpSearchTimeout=setTimeout((()=>{dpSearch(search)}),500)):resetDpSearchState()})),dpInput.addEventListener("keydown",(event=>{if("Enter"===event.key){const value=event.target.value.trim();if(!value)return resetDpSearchState(),void toggleDpClearBtn();value.length>=4&&dpSearch(value)}})),toggleDpClearBtn(),document.querySelectorAll(".dp-chip").forEach((chip=>{chip.addEventListener("click",(()=>{dpSelect(chip,chip.dataset.nameEn,chip.dataset.packages,chip.dataset.p,chip.dataset.cCode)}))}));const activeChip=document.querySelector(".dp-chip.active");function setResultVisibility(hasResult){dpResult&&dpNoResult&&(dpResult.classList.toggle("show",hasResult),dpNoResult.classList.toggle("show",!hasResult))}function clearOptions(){dpOptions&&(dpOptions.innerHTML="")}async function dpRenderResult(key,pack,provider,cCode){if(!(dpResultName&&dpOptions&&dpResult&&dpNoResult))return;const countryCode=String(cCode||"").toLowerCase(),pc=String(pack||"").trim(),pr=String(provider||"").trim();if(!countryCode||!pc||!pr)return clearOptions(),void setResultVisibility(!1);const currentRequestId=++dpRequestId;dpAbortController&&dpAbortController.abort(),dpAbortController=new AbortController,dpResult.classList.add("is-loading"),setResultVisibility(!0);try{const url=`/api/v2/countries/popular/packages?pc=${encodeURIComponent(pc)}&cc=${encodeURIComponent(countryCode)}&pr=${encodeURIComponent(pr)}`,response=await fetch(url,{method:"GET",headers:{Accept:"application/json"},signal:dpAbortController.signal});if(!response.ok)throw new Error(`HTTP ${response.status}`);const json=await response.json();if(currentRequestId!==dpRequestId)return;if(!json.success||!Array.isArray(json.data)||0===json.data.length)return clearOptions(),void setResultVisibility(!1);const packages=json.data.slice().sort(((a,b)=>(a.megabyte||0)!==(b.megabyte||0)?(a.megabyte||0)-(b.megabyte||0):(a.duration||0)-(b.duration||0))),countryName=packages[0].country_name?.name||key||"",resultCountryCode=String(packages[0].country_code||cCode||"").toLowerCase(),countryFlagHtml=function(countryName,countryCode){const code=String(countryCode||"").toLowerCase();if(!code)return"";const flagUrl=`${getFlagBase()}${code}.svg`;return`<img class="countries-flag-mini" alt="${escapeHtml(countryName)}" src="${flagUrl}">`}(countryName,resultCountryCode),bestIndex=function(packages){if(!Array.isArray(packages)||!packages.length)return-1;const selectedPackageId=packages.find((item=>item.package_selected))?.package_selected??null;if(null!=selectedPackageId&&""!==selectedPackageId){const selectedIndex=packages.findIndex((item=>String(item.package_code)===String(selectedPackageId)));if(-1!==selectedIndex)return selectedIndex}return packages.length>1?1:0}(packages),newOptionsHtml=packages.map(((item,index)=>{const gb=function(megabyte){const mb=Number(megabyte||0);if(!mb)return"";if(mb>=1024){const gb=mb/1024;return Number.isInteger(gb)?`${gb} ГБ`:`${gb.toFixed(1)} ГБ`}return`${mb} МБ`}(item.megabyte),days=item.duration||"",speed=item.speed||"",price=item.price_rub_format||item.price_rub||"",label=item.description||"",isBest=index===bestIndex;return`\n                <div class="dp-opt${isBest?" best":""}" \n                     data-country-name="${escapeHtml(countryName)}"\n                     data-country-flag="${escapeHtml(countryFlagHtml)}"\n                     data-data="${escapeHtml(`${gb} · ${days} ${pluralDays(days)} · ${speed}`)}"\n                     data-price="${escapeHtml(`${price} ₽`)}"\n                     data-package-code="${escapeHtml(item.package_code||"")}"\n                     data-country-code="${escapeHtml(item.country_code||"")}"\n                     data-provider="${escapeHtml(item.provider||"")}"\n                     data-megabyte="${escapeHtml(String(item.megabyte||""))}"\n                     data-duration="${escapeHtml(String(item.duration||""))}">\n                    <div class="dp-opt-left">\n                        <div class="dp-opt-name">\n                            ${escapeHtml(gb)} · ${escapeHtml(String(days))} ${pluralDays(days)}${isBest?" ⭐":""}\n                        </div>\n                        <div class="dp-opt-meta">\n                            ${escapeHtml(speed)}${label?" · "+escapeHtml(label):""}\n                        </div>\n                    </div>\n                    <div class="dp-opt-right">\n                        <span class="dp-opt-price">${escapeHtml(String(price))} ₽</span>\n                        <button class="dp-opt-buy" type="button">Купить</button>\n                    </div>\n                </div>\n            `})).join("");dpResultName.innerHTML=`${countryFlagHtml?`<span class="dp-chip-flag">${countryFlagHtml}</span> `:""}${escapeHtml(countryName)}`,dpOptions.innerHTML=newOptionsHtml,dpOptions.querySelectorAll(".dp-opt").forEach((opt=>{opt.addEventListener("click",(()=>{openModal({name:opt.dataset.countryName||"",flag:opt.dataset.countryFlag||"",data:opt.dataset.data||"",price:opt.dataset.price||"",packageCode:opt.dataset.packageCode||"",countryCode:opt.dataset.countryCode||"",provider:opt.dataset.provider||"",megabyte:opt.dataset.megabyte||"",duration:opt.dataset.duration||""})}))})),setResultVisibility(!0)}catch(error){if("AbortError"===error.name)return;console.error("Ошибка загрузки пакетов:",error),clearOptions(),setResultVisibility(!1)}finally{currentRequestId===dpRequestId&&dpResult.classList.remove("is-loading")}}function dpSelect(el,key,pack,provider,cCode){document.querySelectorAll(".dp-chip").forEach((chip=>{chip.classList.remove("active")})),el.classList.add("active"),dpInput.value="",toggleDpClearBtn(),resetDpSearchState(),dpRenderResult(key,pack,provider,cCode)}function pluralDays(days){const n=Math.abs(Number(days))%100,n1=n%10;return n>10&&n<20?"дней":n1>1&&n1<5?"дня":1===n1?"день":"дней"}function escapeHtml(str){return String(str).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}activeChip&&dpSelect(activeChip,activeChip.dataset.nameEn,activeChip.dataset.packages,activeChip.dataset.p,activeChip.dataset.cCode)})),document.addEventListener("DOMContentLoaded",(function(){document.addEventListener("click",(function(e){var btn=e.target.closest("[data-scroll-to]");if(btn){var el=document.getElementById(btn.getAttribute("data-scroll-to"));if(el)el.scrollIntoView({behavior:"smooth"});else{var fb=btn.getAttribute("data-fallback");fb&&(window.location.href=fb)}}})),document.addEventListener("click",(function(e){var btn=e.target.closest("[data-href]");btn&&(window.location.href=btn.getAttribute("data-href"))}));var modalOverlay=document.getElementById("modal");modalOverlay&&modalOverlay.addEventListener("click",(function(e){e.target===modalOverlay&&closeModal()})),document.addEventListener("click",(function(e){(e.target.closest(".modal-close")||e.target.closest('[data-action="close-modal"]'))&&closeModal()})),document.addEventListener("click",(function(e){e.target.closest(".btn-promo")&&applyPromo()})),document.addEventListener("click",(function(e){e.target.closest("#promoRemove")&&removePromo()})),document.addEventListener("click",(function(e){e.target.closest('[data-action="submit-purchase"]')&&submitPurchase()})),document.addEventListener("click",(function(e){var btn=e.target.closest(".day-adj[data-delta]");btn&&adjustDays(parseInt(btn.getAttribute("data-delta"),10))}));var btnShowAll=document.getElementById("btnShowAll");btnShowAll&&btnShowAll.addEventListener("click",(function(){toggleAllCountries(btnShowAll)})),document.addEventListener("click",(function(e){var btn=e.target.closest(".faq-question");btn&&toggleFaq(btn)})),document.addEventListener("click",(function(e){var btn=e.target.closest(".filter-btn[data-filter]");btn&&filterTariffs(btn,btn.getAttribute("data-filter"))}));var cPrev=document.getElementById("cPrev"),cNext=document.getElementById("cNext");cPrev&&cPrev.addEventListener("click",(function(){carouselMove(-1)})),cNext&&cNext.addEventListener("click",(function(){carouselMove(1)})),document.addEventListener("click",(function(e){var btn=e.target.closest(".resort-buy[data-resort]");btn&&goToResort(btn.getAttribute("data-resort"))})),document.addEventListener("click",(function(e){var btn=e.target.closest("[data-modal]");if(btn)try{var md=JSON.parse(btn.getAttribute("data-modal"));if(!md.countryCode){var provCols=btn.closest("[data-country-code]");provCols&&(md.countryCode=provCols.dataset.countryCode)}if(!md.packageCode){var tRow=btn.closest("[data-id]");tRow&&(md.packageCode=tRow.dataset.id)}openModal(md)}catch(_){}})),document.addEventListener("click",(function(e){var btn=e.target.closest(".t-det-toggle[data-pkg]");btn&&(toggleDet(btn.getAttribute("data-pkg"),btn),e.stopPropagation())}));var chkAll=document.getElementById("chkAll");chkAll&&chkAll.addEventListener("change",(function(){"function"==typeof toggleAllChecks&&toggleAllChecks(chkAll)})),["chkOferta","chkPd","chkEsim","chkAds"].forEach((function(id){var el=document.getElementById(id);el&&el.addEventListener("change",(function(){"function"==typeof syncAllCheck&&syncAllCheck()}))}))})),document.addEventListener("DOMContentLoaded",(function(){document.querySelectorAll(".js-email").forEach((function(el){const user=el.dataset.user||"",domain=el.dataset.domain||"";if(!user||!domain)return;const email=user+"@"+domain;el.textContent=email}))})),document.addEventListener("DOMContentLoaded",initCookieNotice),function(){function applyLocationFilter(){var checked,val=(checked=document.querySelector('input[name="locFilter"]:checked'))?checked.value:"cn";document.querySelectorAll(".t-row[data-location]").forEach((function(row){var codes=(row.dataset.location||"").toUpperCase().split(","),show=!1;"cn"===val?show=1===codes.length&&"CN"===codes[0]:"hk"===val?show=-1!==codes.indexOf("HK")||-1!==codes.indexOf("MO"):"jp"===val&&(show=-1!==codes.indexOf("JP")||-1!==codes.indexOf("KR")),row.classList.toggle("lf-hidden",!show)})),document.querySelectorAll(".lf-check").forEach((function(lbl){var inp=lbl.querySelector('input[name="locFilter"]');inp&&lbl.classList.toggle("act",inp.value===val)})),"function"==typeof window.filterTariffs&&window.filterTariffs()}document.querySelector('.lf-check input[name="locFilter"]')&&(document.addEventListener("change",(function(e){e.target.matches('input[name="locFilter"]')&&applyLocationFilter()})),document.addEventListener("DOMContentLoaded",(function(){applyLocationFilter()})))}(),document.addEventListener("DOMContentLoaded",(function(){document.querySelectorAll(".email-obf").forEach((function(el){const email=el.dataset.u+"@"+el.dataset.d+"."+el.dataset.t;el.textContent=email,el.href="mailto:"+email}))})),document.addEventListener("DOMContentLoaded",(function(){document.querySelectorAll(".phone-obf").forEach((function(el){const rawPhone=el.dataset.one+el.dataset.two,cleanPhone=rawPhone.replace(/[^\d+]/g,"");let visiblePhone=rawPhone;12===cleanPhone.length&&cleanPhone.startsWith("+7")&&(visiblePhone=cleanPhone.replace(/^(\+7)(\d{3})(\d{3})(\d{2})(\d{2})$/,"$1 $2 $3-$4-$5")),el.textContent=visiblePhone,el.href="tel:"+cleanPhone}))}));