!function(){const t=".cst-header-navigation__cart-button",e=".cst-cart",o=".cst-cart__close-btn",n=".cst-cart__checkout-btn--buy",s=".cst-cart__checkout-btn--close",c=".cst-cart__overlay",r=".cst-cart__content",a=".cst-cart__footer",i=".cst-cart__continue-btn",l=".cst-cart__checkout-btn--order",u=".cst-popup_block",d=".gc-modal .close-btn, .cst-popup__close",p=".gc-modal, .modal-backdrop.in",m="[data-buy-now]",f=".cst-product-item__button--cart",h=".basket-counter, .cart-count, [data-basket-count]",b=".cst-catalog__product",k=".cst-catalog__products",y=".cst-product-popup__button--cart",_="body--oh",g="hidden",v="cst-product-popup__button--cart-success",C="cst-product-item__button--cart-success",w="cst-popup-item--hidden",E="button--disabled",B={isCartOpen:!1,basketData:null,productsInCart:[],isAddingToCart:!1,isCleaningExpired:!1};const P={STORAGE_KEY:"cart_expiry_timers",cleaningInProgress:!1,pendingRemovals:new Set,init:function(){this.setupExpiryCheck()},addExpiryTimer:function(t){const e=this.getTimers(),o=Date.now()+864e5;e[t]=o,this.saveTimers(e),console.log(`Таймер установлен для товара ${t}, истекает:`,new Date(o).toLocaleString())},removeExpiryTimer:function(t){const e=this.getTimers();delete e[t],this.saveTimers(e)},cleanExpiredItems:function(){if(this.cleaningInProgress)return void console.log("Очистка уже в процессе...");this.cleaningInProgress=!0;const t=this.getTimers(),e=Date.now(),o=[];Object.entries(t).forEach((([t,n])=>{n<=e&&!this.pendingRemovals.has(t)&&(o.push(t),this.pendingRemovals.add(t))})),0!==o.length?(console.log(`Найдено просроченных товаров: ${o.length}`,o),this.removeExpiredItemsSequentially(o)):this.cleaningInProgress=!1},removeExpiredItemsSequentially:function(t){if(0===t.length)return this.cleaningInProgress=!1,console.log("Фоновая очистка завершена"),void(B.isCartOpen&&setTimeout((()=>L.refreshBasket()),1e3));const e=t[0],o=t.slice(1);console.log(`Фоновая очистка: товар ${e} просрочен, удаляем`),this.removeExpiryTimer(e),L.removeItemWithCallback(e,(n=>{this.pendingRemovals.delete(e),n?setTimeout((()=>{this.removeExpiredItemsSequentially(o)}),300):(console.warn(`Ошибка удаления товара ${e}, повтор через 2 секунды`),setTimeout((()=>{this.removeExpiredItemsSequentially(t)}),2e3))}))},quickCheckExpiredItems:function(){const t=this.getTimers(),e=Date.now();let o=0;return Object.entries(t).forEach((([t,n])=>{n<=e&&!this.pendingRemovals.has(t)&&o++})),o},forceRemoveExpiredItems:function(){const t=this.getTimers(),e=Date.now(),o=[];Object.entries(t).forEach((([t,n])=>{n<=e&&o.push(t)})),o.length>0&&(console.log("Принудительное удаление просроченных товаров:",o),o.forEach((t=>{this.removeExpiryTimer(t),L.removeItem(t)})),setTimeout((()=>{L.refreshBasket()}),1e3))},getTimers:function(){try{const t=localStorage.getItem(this.STORAGE_KEY);return t?JSON.parse(t):{}}catch(t){return console.error("Ошибка чтения таймеров:",t),{}}},saveTimers:function(t){try{localStorage.setItem(this.STORAGE_KEY,JSON.stringify(t))}catch(t){console.error("Ошибка сохранения таймеров:",t)}},setupExpiryCheck:function(){document.addEventListener("visibilitychange",(()=>{!document.hidden&&B.isCartOpen&&this.cleanExpiredItems()}))}},I=()=>{const t=P.getTimers(),e=Date.now()-864e5;Object.entries(t).forEach((([t,o])=>{o<e&&(console.log("Удаляем старый таймер для товара:",t),P.removeExpiryTimer(t))}))},S={debounce:function(t,e){let o;return function(...n){clearTimeout(o),o=setTimeout((()=>{clearTimeout(o),t(...n)}),e)}},getOfferImage:t=>{if(!window.customDataCart)return"//fs.getcourse.ru/fileservice/file/download/a/298472/sc/156/h/4f84b5e9131419e5b9aeee1538ae4248.png";const e=window.customDataCart.find((e=>e.idOffer===parseInt(t)));return e?.img||"//fs.getcourse.ru/fileservice/file/download/a/298472/sc/156/h/4f84b5e9131419e5b9aeee1538ae4248.png"},getOfferDescription:t=>{if(!window.customDataCart)return"Неизвестный товар";const e=window.customDataCart.find((e=>e.idOffer===parseInt(t)));return e?.description||"Неизвестный товар"},formatPositions:t=>t?.positions?Object.values(t.positions).map((t=>({offerId:t.offerId||t.offer?.id,img:S.getOfferImage(t.offerId||t.offer?.id),description:S.getOfferDescription(t.offerId||t.offer?.id),price:t.price_str||t.price}))):[],findObjectByModal:t=>window.customDataCart&&Array.isArray(window.customDataCart)?window.customDataCart.find((e=>e.modal===t))||null:(console.error("customDataCart не найден или не является массивом"),null),findObjectByRecommendedModal:t=>window.customDataCart&&Array.isArray(window.customDataCart)?window.customDataCart.find((e=>e.recommendedModal===t))||null:(console.error("customDataCart не найден или не является массивом"),null),findObjectByOffer:t=>window.customDataCart&&Array.isArray(window.customDataCart)?window.customDataCart.find((e=>e.idOffer===parseInt(t)))||null:(console.error("customDataCart не найден или не является массивом"),null),findObjectByAnyModal:function(t){return window.customDataCart&&Array.isArray(window.customDataCart)?window.customDataCart.find((e=>e.modal===t||e.recommendedModal===t||e.idOffer===parseInt(t)))||null:(console.error("customDataCart не найден или не является массивом"),null)}},T={createCartItem:t=>`\n            <article class="cst-cart-item" data-offer="${t.offerId}">\n                <div class="cst-cart-item__image">\n                    <img class="cst-cart-item__img" src="${t.img}" \n                         alt="${t.description}" width="80" height="80" loading="lazy">\n                </div>\n                <div class="cst-cart-item__info">\n                    <h3 class="cst-cart-item__title">${t.description}</h3>\n                    <p class="cst-cart-item__price">${t.price}</p>\n                </div>\n                <div class="cst-cart-item__actions">\n                    <button class="cst-cart-item__remove-btn cst-reset-btn" type="button" \n                            aria-label="Удалить товар" data-remove-from-basket="${t.offerId}">\n                        &times;\n                    </button>\n                </div>\n            </article>\n        `,createCartItems:t=>`\n            <div class="cst-cart__items">\n                ${t.map((t=>T.createCartItem(t))).join("")}\n            </div>\n        `,createCartButtons:()=>'\n            <div class="cst-cart__footer-container">\n                <button class="cst-cart__continue-btn cst-cart__checkout-btn--close cst-reset-btn" type="button">\n                    Продолжить покупки\n                </button>\n                <button class="cst-cart__checkout-btn cst-cart__checkout-btn--order reset-btn-link" type="button">\n                    <span>Оформить заказ</span>\n                </button>\n            </div>\n        ',createDefaultCartButton:()=>'\n            <button class="cst-cart__continue-btn cst-cart__checkout-btn--buy cst-reset-btn" type="button">\n                За покупками\n            </button>\n        ',createEmptyContainer:()=>'\n            <div class="cst-cart__content-empty-wrapper">\n                <p class="cst-cart__content-empty">В корзине пока ничего нет</p>\n            </div>\n        ',createCart:(t=null)=>{const e=!t||t.is_empty,o=S.formatPositions(t);return`\n                <section class="cst-cart" aria-label="Корзина покупок">\n                    <div class="cst-cart__overlay"></div>\n                    <div class="cst-cart__container">\n                        <header class="cst-cart__header">\n                            <h2 class="cst-cart__title">Корзина</h2>\n                            <button class="cst-cart__close-btn cst-reset-btn" type="button" \n                                    aria-label="Закрыть корзину">\n                                &times;\n                            </button>\n                        </header>\n                        <div class="cst-cart__content">\n                            ${e?T.createEmptyContainer():T.createCartItems(o)}\n                        </div>\n                        ${T.createCartFooter(t)}\n                    </div>\n                </section>`},createCartFooter:t=>{const e=!t||t.is_empty;return`\n                <footer class="cst-cart__footer">\n                    ${e?"":`\n                        <div class="cst-cart__total">\n                            <span class="cst-cart__total-label">Итого:</span>\n                            <span class="cst-cart__total-amount">${t?.total_cost_str||"0 ₽"}</span>\n                        </div>\n                    `}\n                    ${e?T.createDefaultCartButton():T.createCartButtons()}\n                </footer>`}},L={removeItem:function(t){return window.ltBasketEl?(window.ltBasketEl.liteBasket("deleteOffer",t),!0):(console.error("Корзина не инициализирована"),!1)},changeQuantity:function(t,e){return window.ltBasketEl?(window.ltBasketEl.liteBasket("changeOfferQuantity",t,e),!0):(console.error("Корзина не инициализирована"),!1)},getBasketData:function(){return new Promise(((t,e)=>{window.ltBasketEl?(window.ltBasketEl.liteBasket("getBasketData"),setTimeout((()=>{B.basketData?t(B.basketData):e(new Error("Не удалось получить данные корзины"))}),300)):e(new Error("Корзина не инициализирована"))}))},refreshBasket:function(){window.ltBasketEl&&window.ltBasketEl.liteBasket("getBasketData")},checkout:function(){const t=document.querySelector(".lt-basket .btn-deal.btn-success");t?(t.click(),O.close()):console.warn("Кнопка оформления заказа не найдена")},safeAddToCart:function(t,e){if(B.isAddingToCart)return console.log("Добавление товара уже в процессе..."),!1;B.isAddingToCart=!0;try{return ltAddToBasket(t),P.addExpiryTimer(t),setTimeout((()=>{B.isAddingToCart=!1,L.refreshBasket(),"function"==typeof e&&setTimeout(e,100)}),500),!0}catch(t){return console.error("Ошибка при добавлении в корзину:",t),B.isAddingToCart=!1,!1}},removeItem:function(t){if(!window.ltBasketEl)return console.error("Корзина не инициализирована"),!1;try{return P.removeExpiryTimer(t),window.ltBasketEl.liteBasket("deleteOffer",t),!0}catch(t){return console.error("Ошибка при удалении товара:",t),!1}},removeMultipleItems:function(t){if(!window.ltBasketEl)return console.error("Корзина не инициализирована"),!1;try{return t.forEach((t=>{P.removeExpiryTimer(t),window.ltBasketEl.liteBasket("deleteOffer",t)})),!0}catch(t){return console.error("Ошибка при массовом удалении товаров:",t),!1}},removeItemWithCallback:function(t,e){if(!window.ltBasketEl)return console.error("Корзина не инициализирована"),e(!1),!1;let o=!1;const n=setTimeout((()=>{o||(o=!0,console.warn(`Таймаут удаления товара ${t}`),e(!1))}),5e3);try{const s=$.gc.liteBasket.prototype.updateBasketData;$.gc.liteBasket.prototype.updateBasketData=function(c){s.call(this,c),o||!c||c.positions?.[t]||(o=!0,clearTimeout(n),e(!0))},window.ltBasketEl.liteBasket("deleteOffer",t),setTimeout((()=>{$.gc.liteBasket.prototype.updateBasketData=s,o||(o=!0,e(!1))}),5e3)}catch(t){return console.error("Ошибка при удалении товара:",t),clearTimeout(n),o||(o=!0,e(!1)),!1}return!0},removeItemWithEvent:function(t){return new Promise((e=>{if(!window.ltBasketEl)return void e(!1);const o=setTimeout((()=>e(!1)),5e3);let n=!1;const s=(c,r)=>{r&&!r.positions?.[t]&&(n||(n=!0,clearTimeout(o),$(document).off("basketUpdated",s),e(!0)))};$(document).on("basketUpdated",s);try{window.ltBasketEl.liteBasket("deleteOffer",t),setTimeout((()=>{n||(n=!0,clearTimeout(o),$(document).off("basketUpdated",s),e(!1))}),3e3)}catch(t){console.error("Ошибка при удалении товара:",t),n||(n=!0,clearTimeout(o),$(document).off("basketUpdated",s),e(!1))}}))}},x={init:function(){this.cleanOldTimers(),this.setupForceCleanup()},cleanOldTimers:function(){const t=P.getTimers(),e=Date.now();Object.keys(t).forEach((o=>{t[o]<e-1728e5&&(console.log("Удаляем старый таймер:",o),P.removeExpiryTimer(o))}))},setupForceCleanup:function(){setInterval((()=>{P.forceRemoveExpiredItems(),this.cleanOldTimers()}),6e5)}},D=function(){if(!$.gc||!$.gc.liteBasket)return console.error("Виджет liteBasket не найден"),!1;const t=$.gc.liteBasket.prototype.updateBasketData;return $.extend($.gc.liteBasket.prototype,{updateBasketData:function(e){t.call(this,e),B.basketData=e,B.isCartOpen&&O.updateCartContent(e),this._updateBasketCounter(),$(document).trigger("basketUpdated",[e])},deleteOffer:function(t){const e=this;ajaxCall("/sales/shop/basketDeleteOffer",{offerId:t},{},(o=>{o.success?(e._trackRemoval(t),"function"==typeof window.onBasketItemRemoved&&window.onBasketItemRemoved(t),e.updateBasketData(o.data.basket)):console.error("Ошибка удаления:",o.error)}))},changeOfferQuantity:function(t,e){const o=this;ajaxCall("/sales/shop/basketChangeOfferQuantity",{offerId:t,quantity:e},{},(t=>o.updateBasketData(t.data.basket)))},_trackRemoval:function(t){"function"==typeof gtag&&gtag("event","remove_from_cart",{items:[{id:t}]})},_updateBasketCounter:function(){if(this.basketData){const t=this.basketData.total_quantity||0;this._updateUICounter(t)}},_updateUICounter:function(t){const e=$(h);e.length&&(e.text(t),e.toggle(t>0))}}),!0},O={open:async function(){if(!B.isCartOpen)try{const t=P.quickCheckExpiredItems();t>0&&(console.log(`Обнаружено ${t} просроченных товаров, запускаем фоновую очистку`),setTimeout((()=>P.cleanExpiredItems()),1e3)),await L.getBasketData(),this.renderCart()}catch(t){console.error("Ошибка открытия корзины:",t),this.openFallback()}},openFallback:function(){this.renderCart()},renderCart:function(){const t=document.body;t.insertAdjacentHTML("beforeend",T.createCart(B.basketData)),t.classList.add(_),B.isCartOpen=!0,this.setupEventListeners()},close:function(){if(!B.isCartOpen)return;const t=document.body,o=document.querySelector(e);t.classList.remove(_),o?.remove(),B.isCartOpen=!1,this.removeEventListeners()},updateCartContent:function(t){if(!B.isCartOpen)return;const e=document.querySelector(r),o=document.querySelector(a);if(e&&o){const n=S.formatPositions(t),s=!t||t.is_empty;e.innerHTML=s?T.createEmptyContainer():`\n                <div class="cst-cart__items">\n                    ${n.map((t=>M.createCartItem(t))).join("")}\n                </div>\n            `,o.innerHTML=T.createCartFooter(t),this.setupEventListeners()}},setupEventListeners:function(){const t=document.querySelector(e);if(!t)return;[o,n,s,c,i].forEach((e=>{const o=t.querySelector(e);o?.addEventListener("click",(()=>this.close()))}));const r=t.querySelector(l);r?.addEventListener("click",(()=>L.checkout())),document.addEventListener("keydown",this.handleEscapeKey)},removeEventListeners:function(){document.removeEventListener("keydown",this.handleEscapeKey)},handleEscapeKey:t=>{"Escape"===t.key&&O.close()}},q={initializedPopups:new Set,eventHandlers:new Map,checkProductInCart:function(t,e){if(!t)return;this.isProductInBasket(e)?(t.innerHTML="Добавлено в корзину &#10004;",t.classList.add(v),t.disabled=!1,t.classList.remove(E)):(t.textContent="Добавить в корзину",t.classList.remove(v),t.disabled=!1,t.classList.remove(E))},getModalType:function(t){const e=t.closest(k);t.closest(b);return e?"recommendedModal":"modal"},isProductInBasket:function(t){if(!B.basketData?.positions)return!1;return Object.values(B.basketData.positions).some((e=>parseInt(e.offerId||e.offer?.id)===parseInt(t)))},getPopupElements:t=>({popupHeader:t.querySelector(".cst-product-popup"),popupImg:t.querySelector(".cst-product-popup-logo__img"),popupTag:t.querySelector(".cst-product-popup__tag"),popupTitle:t.querySelector(".cst-product-popup__title"),popupPrice:t.querySelector(".cst-product-popup__price"),popupButtonCart:t.querySelector(".cst-product-popup__button--cart"),popupButtonPay:t.querySelector(".cst-product-popup__button--pay"),popupDescription:t.querySelector(".cst-product-popup__description"),popupLink:t.querySelector(".cst-product-popup__link"),popupInputs:t.querySelectorAll(".cst-popup-item"),checkbox:t.querySelector(".global-confirm-checkbox-block"),actionButtons:t.querySelector(".cst-product-popup__actions"),warning:t.querySelector(".cst-product-popup__warning")}),updatePopupContent:function(t,e){const{popupImg:o,popupTag:n,popupTitle:s,popupPrice:c,popupDescription:r,popupLink:a,warning:i}=t;o&&(o.src=e.img,o.alt=e.description),n&&(n.textContent=e.popupTag||""),s&&(s.textContent=e.description),c&&(c.textContent=e.price),r&&(r.textContent=e.popupDescription||""),a&&(a.href=e.link||"#"),a&&(a.href=e.link||"#"),i&&(i.textContent=e.warningAccess,e.warningAccess.length>0&&i.classList.add("cst-product-popup__warning--active"))},updateAllPopupsCartState:function(){document.querySelectorAll(u).forEach((t=>{const e=t.dataset.code;if(e){const o=t.querySelector(y);if(o){const t=S.findObjectByAnyModal(e);t&&this.checkProductInCart(o,t.idOffer)}}}))},handleProceedToPayment:function(t,e,o){t&&t.classList.add(g),e.forEach((t=>t.classList.remove(w))),o&&o.classList.remove(w)},setupPopupCloseHandler:function(t){this.removePopupCloseHandler(t);const e={closeButtons:[],overlays:[],escape:null};document.querySelectorAll(d).forEach((t=>{const o=()=>this.resetPopupState();t.addEventListener("click",o),e.closeButtons.push({element:t,handler:o})}));document.querySelectorAll(p).forEach((t=>{const o=e=>{e.target===t&&this.resetPopupState()};t.addEventListener("click",o),e.overlays.push({element:t,handler:o})}));const o=t=>{"Escape"===t.key&&this.resetPopupState()};document.addEventListener("keydown",o),e.escape=o,this.eventHandlers.set(t,e)},removePopupCloseHandler:function(t){if(this.eventHandlers.has(t)){const e=this.eventHandlers.get(t);e.closeButtons.forEach((({element:t,handler:e})=>t.removeEventListener("click",e))),e.overlays.forEach((({element:t,handler:e})=>t.removeEventListener("click",e))),e.escape&&document.removeEventListener("keydown",e.escape),this.eventHandlers.delete(t)}},initAddDataPopup:function(t,e=null){if(this.initializedPopups.has(t))return;const o=document.querySelector(`${u}[data-code="${t}"]`);if(!o)return void console.error(`Попап с data-code="${t}" не найден`);let n;if("recommendedModal"===(e?this.getModalType(e):"modal")?(n=S.findObjectByRecommendedModal(t),n||(n=S.findObjectByModal(t))):(n=S.findObjectByModal(t),n||(n=S.findObjectByRecommendedModal(t))),n||(n=S.findObjectByAnyModal(t)),!n)return void console.error(`Данные для модального окна "${t}" не найдены`);const s=this.getPopupElements(o);this.updatePopupContent(s,n),this.setupPopupEventListeners(s,n,t),this.setupPopupCloseHandler(t),this.checkProductInCart(s.popupButtonCart,n.idOffer),this.initializedPopups.add(t)},showErrorMessage:function(t,e){const o=document.createElement("div");o.className="cst-popup-error",o.innerHTML=`\n        <div style="padding: 20px; text-align: center; color: #dc3545;">\n            <h3>Ошибка загрузки данных</h3>\n            <p>${e}</p>\n            <button class="cst-reset-btn" onclick="this.closest('.cst-popup_block').querySelector('.close-btn').click()" \n                    style="margin-top: 15px; padding: 10px 20px; background: #dc3545; color: white; border: none; border-radius: 5px;">\n                Закрыть\n            </button>\n        </div>\n    `;const n=t.querySelector(".cst-product-popup")||t.querySelector(".gc-modal__body");n&&(n.innerHTML="",n.appendChild(o))},setupPopupEventListeners:function(t,e,o){const{popupButtonCart:n,popupButtonPay:s,popupHeader:c,popupInputs:r,checkbox:a}=t;if(n){const t=n.cloneNode(!0);n.parentNode.replaceChild(t,n),t.addEventListener("click",S.debounce((()=>{this.handleAddToCart(t,e.idOffer,o)}),500))}if(s&&c&&r){const t=s.cloneNode(!0);s.parentNode.replaceChild(t,s),t.addEventListener("click",(()=>{this.handleProceedToPayment(c,r,a)}))}},handleAddToCart:function(t,e,o){if(this.isProductInBasket(e))return t.innerHTML="Добавлено в корзину &#10004;",void t.classList.add(v);t.disabled=!0,t.classList.add(E),t.textContent="Добавляем...",L.safeAddToCart(e,(()=>{setTimeout((()=>{this.checkProductInCart(t,e),this.updateAllPopupsCartState()}),300)}))},cleanupAllHandlers:function(){for(const t of this.eventHandlers.keys())this.removePopupCloseHandler(t);this.eventHandlers.clear(),this.initializedPopups.clear()},resetPopupState:function(){document.querySelectorAll(u).forEach((t=>{const e=this.getPopupElements(t);e.popupHeader&&e.popupHeader.classList.remove(g),e.popupInputs.forEach((t=>t.classList.add(w))),e.checkbox&&e.checkbox.classList.add(w)}));document.querySelectorAll(".cst-product-popup__button--cart").forEach((t=>{const e=t.closest(".cst-popup_block"),o=e?.dataset.code;if(o){const e=S.findObjectByModal(o);e&&this.checkProductInCart(t,e.idOffer)}}))},handleBuyNow:function(t){const e=document.querySelector(`${u}[data-code="${t}"]`);if(!e)return;const o=this.getPopupElements(e);!B.basketData||B.basketData.is_empty?this.showCheckoutForm(o):this.showProductPopup(o)},showCheckoutForm:function(t){t.popupHeader&&t.popupHeader.classList.add(g),t.popupInputs.forEach((t=>t.classList.remove(w))),t.checkbox&&t.checkbox.classList.remove(w)},showProductPopup:function(t){[...t.popupInputs].filter((t=>t&&t.classList&&t.classList.contains("part-position")))[0].querySelector(".text-muted.strike")?t.actionButtons.classList.remove("cst-product-popup__actions--show"):t.actionButtons.classList.add("cst-product-popup__actions--show"),t.popupHeader&&t.popupHeader.classList.remove(g),t.popupInputs.forEach((t=>t.classList.add(w))),t.checkbox&&t.checkbox.classList.add(w)},findProductDataByOfferId:function(t){if(!window.customDataCart||!Array.isArray(window.customDataCart))return null;const e=window.customDataCart.find((e=>e.idOffer===parseInt(t)));return e?{...e,allModalIds:[e.modal,e.recommendedModal].filter(Boolean)}:null},updatePopupsForProduct:function(t){const e=this.findProductDataByOfferId(t);e&&e.allModalIds.length&&e.allModalIds.forEach((e=>{const o=document.querySelector(`${u}[data-code="${e}"]`);if(o){const e=o.querySelector(y);e&&this.checkProductInCart(e,t)}}))}},A={isProcessingClick:!1,updatePopupButtonsAfterCartChange:function(t){document.querySelectorAll(".cst-product-popup__button--cart").forEach((e=>{const o=e.closest(".cst-popup_block"),n=o?.dataset.code;if(n){const o=S.findObjectByModal(n);o&&o.idOffer==t&&q.checkProductInCart(e,t)}}))},updateAllCartButtons:function(){document.querySelectorAll(".cst-product-popup__button--cart").forEach((t=>{const e=t.closest(".cst-popup_block"),o=e?.dataset.code;if(o){const e=S.findObjectByAnyModal(o);e&&q.checkProductInCart(t,e.idOffer)}})),this.updateProductPageButtons()},updateProductPageButtons:function(){document.querySelectorAll(f).forEach((t=>{const e=t.closest(".cst-product-block");if(e){const o=Number(e.querySelector("label.form-position")?.dataset.offerId);if(o){q.isProductInBasket(o)?(t.innerHTML="Добавлено в корзину &#10004;",t.classList.add(C),t.disabled=!1,t.classList.remove(E)):(t.textContent="Добавить в корзину",t.classList.remove(C),t.disabled=!1,t.classList.remove(E))}}}))},init:function(){P.init(),$(document).on("click","[data-remove-from-basket]",(t=>{t.preventDefault();const e=$(t.target).data("remove-from-basket");L.removeItem(e),setTimeout((()=>{this.updateAllCartButtons()}),100)})).on("basketUpdated",((t,e)=>{B.basketData=e,this.cleanupExpiredTimers(),setTimeout((()=>{this.updateAllCartButtons()}),50)})),L.refreshBasket()},cleanupExpiredTimers:function(){const t=P.getTimers(),e=B.basketData?.positions?Object.values(B.basketData.positions).map((t=>t.offerId||t.offer?.id)):[];Object.keys(t).forEach((t=>{e.includes(parseInt(t))||(console.log("Удаляем таймер для отсутствующего товара:",t),P.removeExpiryTimer(t))}))},handleDocumentClick:function(t){const e=t.target.closest("[data-modal]"),o=t.target.closest(m);if(!o||this.isProcessingClick){if(e&&!this.isProcessingClick){this.isProcessingClick=!0,t.preventDefault();const o=e.dataset.modal;if(o)try{ltShowModalBlock(o),setTimeout((()=>{q.initAddDataPopup(o,e);const t=document.querySelector(`${u}[data-code="${o}"]`);if(t){const e=q.getPopupElements(t);q.showProductPopup(e)}this.isProcessingClick=!1}),50)}catch(t){console.error("Ошибка при открытии попапа:",t),this.isProcessingClick=!1}else this.isProcessingClick=!1}}else{this.isProcessingClick=!0,t.preventDefault();const e=o.dataset.modal||o.dataset.buyNow;if(e)try{ltShowModalBlock(e),setTimeout((()=>{q.initAddDataPopup(e,o),q.handleBuyNow(e),this.isProcessingClick=!1}),50)}catch(t){console.error('Ошибка при обработке кнопки "Купить сейчас":',t),this.isProcessingClick=!1}else this.isProcessingClick=!1}}},M={createCartItem:t=>{const e=P.getTimers()[t.offerId],o=e?M.getTimeLeftString(e):"";return`\n            <article class="cst-cart-item" data-offer="${t.offerId}">\n                <div class="cst-cart-item__image">\n                    <img class="cst-cart-item__img" src="${t.img}" \n                         alt="${t.description}" width="80" height="80" loading="lazy">\n                </div>\n                <div class="cst-cart-item__info">\n                    <h3 class="cst-cart-item__title">${t.description}</h3>\n                    <p class="cst-cart-item__price">${t.price}</p>\n                    ${o?`\n                        <div class="cst-cart-item__expiry">\n                            <span class="cst-cart-item__expiry-text">Удалится из корзины через: ${o}</span>\n                        </div>\n                    `:""}\n                </div>\n                <div class="cst-cart-item__actions">\n                    <button class="cst-cart-item__remove-btn cst-reset-btn" type="button" \n                            aria-label="Удалить товар" data-remove-from-basket="${t.offerId}">\n                        &times;\n                    </button>\n                </div>\n            </article>\n        `},getTimeLeftString:function(t){const e=t-Date.now();if(e<=0)return"0 минут";const o=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return o>0?`${o}ч ${n}м`:`${n} минут`}};T.createCartItem=M.createCartItem;const j={init:function(){x.init(),P.init(),D(),A.init(),this.initCartButton(),this.initDocumentEventListeners(),this.initProductPage()},initCartButton:function(){const e=document.querySelectorAll(t);for(const t of e)t?.addEventListener("click",(()=>O.open()))},initDocumentEventListeners:function(){document.addEventListener("click",(t=>{A.handleDocumentClick(t)}))},initProductPage:function(){const t=document.querySelector(".cst-product-block");if(!t)return;const e=Number(t.querySelector("label.form-position")?.dataset.offerId);if(!e)return;const o=S.findObjectByOffer(e);if(!o)return void console.error(`Предложение "${e}" не найдено`);this.updateProductItemContent(t,o),this.setupProductItemEvents(t,o);const n=t.querySelector(f);if(n){const t=q.isProductInBasket(o.idOffer);this.updateCartButtonState(n,t)}this.setupProductPayButton(t,o)},setupProductPayButton:function(t,e){const o=t.querySelector(".cst-product-item__button--pay"),n=t.querySelectorAll(".cst-popup-item"),s=t.querySelector(".cst-product-item__actions"),c=t.querySelector(".global-confirm-checkbox-block");o&&n.length&&s&&o.addEventListener("click",(()=>{n.forEach((t=>{t.classList.remove("cst-popup-item--hidden")})),c&&c.classList.add("global-confirm-checkbox-block--show"),s.style.display="none",this.createBackButton(t,n,s)}))},createBackButton:function(t,e,o){if(t.querySelector(".cst-product-item__back-button"))return;const n=document.createElement("button");n.className="cst-product-item__back-button cst-reset-btn",n.textContent="Назад",n.type="button",n.addEventListener("click",(()=>{e.forEach((t=>{t.classList.add("cst-popup-item--hidden")})),o.style.display="",n.remove();const s=t.querySelector(".global-confirm-checkbox-block");s&&s.classList.remove("global-confirm-checkbox-block--show")}));const s=e[0];e[e.length-1];s.insertAdjacentElement("beforebegin",n)},updateProductItemContent:function(t,e){const o=t.querySelector(".cst-product-item-logo__img"),n=t.querySelector(".cst-product-item__title"),s=t.querySelector(".cst-product-item__tag"),c=t.querySelector(".cst-product-item__description"),r=t.querySelector(".cst-product-item__duration"),a=t.querySelector(".cst-product-item__price"),i=t.querySelector(".cst-product-item__button--cart"),l=t.querySelector(".cst-product-item__warning"),u=t.querySelector(".cst-product-item__actions");o&&(o.src=e.img,o.alt=e.description),n&&(n.textContent=e.description),s&&(s.textContent=e.popupTag||""),c&&(c.textContent=e.popupDescription||""),r&&(r.textContent=e.duration||""),a&&(a.textContent=e.price||""),e.warningAccess.length>0?l&&(l.textContent=e.warningAccess,l.classList.add("cst-product-item__warning--active")):u.classList.add("cst-product-item__actions--show"),i&&setTimeout((()=>{const t=q.isProductInBasket(e.idOffer);this.updateCartButtonState(i,t)}),300)},updateCartButtonState:function(t,e){e?(t.innerHTML="Добавлено в корзину &#10004;",t.classList.add(C),t.disabled=!1,t.classList.remove(E)):(t.textContent="Добавить в корзину",t.classList.remove(C),t.disabled=!1,t.classList.remove(E))},setupProductItemEvents:function(t,e){const o=t.querySelector(".cst-product-item__button--cart");if(!o)return;const n=S.debounce((()=>{this.handleProductCartButtonClick(o,e.idOffer)}),500);o.addEventListener("click",n)},handleProductCartButtonClick:function(t,e){q.isProductInBasket(e)?this.updateCartButtonState(t,!0):(t.disabled=!0,t.classList.add(E),t.textContent="Добавляем...",L.safeAddToCart(e,(()=>{setTimeout((()=>{const o=q.isProductInBasket(e);this.updateCartButtonState(t,o),q.updatePopupsForProduct(e)}),300)})))}},H=document.querySelector(".cst-product-block");if(H){const t=H.querySelector("#root-offer-form");if(t){const e=H.querySelectorAll(".cst-popup-item");if(e.length>0)for(const o of e)t.insertAdjacentElement("beforeend",o);(R=H,new Promise((t=>{const e=R.querySelector(".global-confirm-checkbox-block");if(e)return void t(e);const o=new MutationObserver((e=>{const n=R.querySelector(".global-confirm-checkbox-block");n&&(o.disconnect(),t(n))}));o.observe(R,{childList:!0,subtree:!0,attributes:!1,characterData:!1}),setTimeout((()=>{o.disconnect(),t(null)}),1e4)}))).then((e=>{e&&t.insertAdjacentElement("beforeend",e)}))}}var R;"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{I(),j.init(),setTimeout((()=>{A.updateAllCartButtons()}),1e3)})):(I(),j.init(),setTimeout((()=>{A.updateAllCartButtons()}),1e3));const N=document.createElement("style");N.textContent="\n    .cst-cart-item__expiry {\n        margin-top: 10rem;\n        font-size: 12rem;\n        color: #666;\n    }\n    \n    .cst-cart-item__expiry-text {\n        background: #fff3cd;\n        padding: 3rem 8rem;\n        border-radius: 12rem;\n        border: 1rem solid #ffeaa7;\n    }\n\n    @media screen and (max-width: 768px) {\n        .cst-cart-item__expiry {\n            font-size: 9rem;\n            max-width: 108rem;\n        }\n\n        .cst-cart-item__expiry-text {\n            display: inline-block;\n        }\n    }\n",document.head.appendChild(N)}();