(function () {

  console.log('✅ CART FIX LOADED');

  function getCart() {
    return document.querySelector('.t706__cartwin.t706__cartwin_showed');
  }

  /* =====================================================
     1) Перенос крестика внутрь карточки
  ===================================================== */
  function moveCartCloseIntoContent() {
    const cart = getCart();
    if (!cart) return;

    const close = cart.querySelector('.t706__cartwin-close');
    const content = cart.querySelector('.t706__cartwin-content');
    if (!close || !content) return;

    if (close.parentElement === content) return;
    content.appendChild(close);
  }

  /* =====================================================
     2) Чекбокс согласия
  ===================================================== */
  function addPrivacyCheckbox() {
    const cart = getCart();
    if (!cart) return;

    const form = cart.querySelector('form');
    if (!form || form.querySelector('.cart-privacy')) return;

    form.insertAdjacentHTML('beforeend', `
      
        
          
          
            Нажимая на кнопку, вы даете согласие на
            
              обработку своих персональных данных
            
          
        
      
    `);
  }

  /* =====================================================
     3) Блокировка оплаты без галочки
  ===================================================== */
  function setupConsentGate() {
    const cart = getCart();
    if (!cart) return;

    const form = cart.querySelector('form');
    if (!form) return;

    const checkbox = form.querySelector('.cart-privacy input[type="checkbox"]');
    if (!checkbox) return;

    const payBtn = form.querySelector(
      '.t706__submit, button[type="submit"], input[type="submit"], .t-submit'
    );
    if (!payBtn || payBtn.dataset.bound) return;
    payBtn.dataset.bound = '1';

    payBtn.addEventListener('click', function (e) {
      if (!checkbox.checked) {
        e.preventDefault();
        e.stopPropagation();
        alert('Необходимо дать согласие на обработку персональных данных');
        checkbox.focus();
        return false;
      }
    }, true);
  }

  /* =====================================================
     4) CSS-ФИКС: УБИВАЕМ ЛИШНЮЮ ЛИНИЮ (НЕ ЛОМАЯ "р.")
  ===================================================== */
  function injectCssFix() {
    if (document.getElementById('bm-cart-cssfix')) return;

    const style = document.createElement('style');
    style.id = 'bm-cart-cssfix';
    style.textContent = `
      /* Убираем ВСЕ декоративные линии в блоке итогов */
      .t706__cartwin .t706__cartwin-totalamount-wrap,
      .t706__cartwin .t706__cartwin-totalamount-wrap * {
        background-image: none !important;
        box-shadow: none !important;
        border-image: none !important;
      }

      /* Сам источник проблемы — currency */
      .t706__cartwin .t706__cartwin-prodamount-currency {
        background: none !important;
        border: none !important;
        box-shadow: none !important;
        outline: none !important;
      }

      /* ОСТАВЛЯЕМ "р.", но превращаем ::before в обычный текст */
      .t706__cartwin .t706__cartwin-prodamount-currency::before {
        display: inline !important;
        position: static !important;
        width: auto !important;
        height: auto !important;
        margin: 0 !important;
        padding: 0 !important;

        background: none !important;
        border: none !important;
        box-shadow: none !important;
        outline: none !important;
        transform: none !important;
        background-image: none !important;
      }

      /* На всякий случай гасим ::after */
      .t706__cartwin .t706__cartwin-prodamount-currency::after {
        content: none !important;
        display: none !important;
      }

      /* Убираем hr / divider если они есть */
      .t706__cartwin .t706__cartwin-totalamount-wrap hr,
      .t706__cartwin .t706__cartwin-totalamount-wrap [class*="line"],
      .t706__cartwin .t706__cartwin-totalamount-wrap [class*="divider"],
      .t706__cartwin .t706__cartwin-totalamount-wrap [class*="separator"] {
        display: none !important;
      }
    `;
    document.head.appendChild(style);
  }

  /* =====================================================
     5) Перенос итогов под товары + правильные линии
  ===================================================== */
  function moveTotalsUp() {
    const cart = getCart();
    if (!cart) return;

    const products =
      cart.querySelector('.t706__cartwin-products') ||
      cart.querySelector('.t706__cartwin-prodlist') ||
      cart.querySelector('.t706__products');

    const totals = cart.querySelector('.t706__cartwin-totalamount-wrap');
    if (!products || !totals) return;

    let holder = cart.querySelector('.cart-top-totals');
    if (!holder) {
      holder = document.createElement('div');
      holder.className = 'cart-top-totals';
      products.insertAdjacentElement('afterend', holder);

      /* Линия под товарами */
      holder.style.borderTop = '1px solid rgba(0,0,0,.12)';
      holder.style.marginTop = '14px';
      holder.style.paddingTop = '14px';

      /* Линия перед доставкой */
      holder.style.borderBottom = '1px solid rgba(0,0,0,.12)';
      holder.style.marginBottom = '18px';
      holder.style.paddingBottom = '16px';
    }

    if (!holder.contains(totals)) holder.appendChild(totals);

    totals.style.marginTop = '0';
    totals.style.textAlign = 'left';
    totals.style.fontFamily = 'Montserrat,Arial,sans-serif';

    const content = totals.querySelector('.t706__cartwin-totalamount-content');
    if (content) {
      content.style.fontSize = '20px';
      content.style.fontWeight = '700';
      content.style.marginTop = '6px';
    }
  }

  /* =====================================================
     6) Убираем дубликат строки "Сумма:"
  ===================================================== */
  function hideDuplicateSubtotal() {
    const cart = getCart();
    if (!cart) return;

    const totals = cart.querySelector('.t706__cartwin-totalamount-wrap');
    if (!totals) return;

    Array.from(cart.querySelectorAll('*')).forEach(el => {
      if (!el.textContent) return;
      if (totals.contains(el)) return;

      const t = el.textContent.trim();
      if (t.startsWith('Сумма:') && !t.includes('Итоговая')) {
        el.style.display = 'none';
      }
    });
  }

  /* =====================================================
     RUN
  ===================================================== */
  function run() {
    injectCssFix();
    moveCartCloseIntoContent();
    addPrivacyCheckbox();
    setupConsentGate();
    moveTotalsUp();
    hideDuplicateSubtotal();
  }

  new MutationObserver(() => setTimeout(run, 0))
    .observe(document.documentElement, { childList:true, subtree:true });

  document.addEventListener('DOMContentLoaded', () => setTimeout(run, 0));

})();


