(function () {
  'use strict';

  const ROUTE_OK =
    window.controllerId === 'control/userProduct' &&
    window.actionId === 'my';

  if (!ROUTE_OK) return;

  const qs = (sel, root = document) => root.querySelector(sel);
  const qsa = (sel, root = document) => Array.from(root.querySelectorAll(sel));

  function text(el) {
    return (el?.textContent || '').replace(/\s+/g, ' ').trim();
  }

  function escapeHtml(value) {
    return String(value ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function splitPurchaseTitle(raw) {
    const value = String(raw || '').trim();

    let m = value.match(/^#(\d+)\.\s*(.+)$/);
    if (m) {
      return { ref: '#' + m[1], title: m[2] };
    }

    m = value.match(/^Покупка\s+#(\d+)\.\s*(.+)$/i);
    if (m) {
      return { ref: 'Покупка #' + m[1], title: m[2] };
    }

    return { ref: '', title: value };
  }

  function normalizeCurrency(value) {
    return String(value || '')
      .replace(/\s*руб\.\s*$/i, ' ₽')
      .replace(/\s+/g, ' ')
      .trim();
  }

  function getRoot() {
    return qs('.main-page-container') || qs('.main-page-block') || qs('.gc-main-content');
  }

  function buildHero(root) {
    const pageHeader = qs('.page-header', root);
    if (!pageHeader || qs('.psych-purchases-hero', root)) return;

    const title = text(qs('h1', pageHeader)) || 'Мои покупки';

    const hero = document.createElement('section');
    hero.className = 'psych-purchases-hero';
    hero.innerHTML = `
      <div class="psych-purchases-hero__eyebrow">Личный кабинет</div>
      <h1 class="psych-purchases-hero__title">${escapeHtml(title)}</h1>
      <p class="psych-purchases-hero__subtitle">
        Здесь собраны ваши покупки, доступы, заказы и промокоды.
      </p>
    `;

    pageHeader.insertAdjacentElement('beforebegin', hero);
    pageHeader.style.display = 'none';
  }

  function parseBonusBlock(root) {
    const block = qs('.gc-bonus-alert', root);
    if (!block) return null;

    const info = qs('.gc-bonus-info', block) || block;
    const links = qsa('a', info);
    const bolds = qsa('b', info);

    const result = {
      normalLabel: links[0] ? text(links[0]) : 'На счету',
      normalHref: links[0]?.getAttribute('href') || '',
      normalValue: bolds[0] ? text(bolds[0]) : '',
      bonusLabel: links[1] ? text(links[1]) : 'Бонусный счет',
      bonusHref: links[1]?.getAttribute('href') || '',
      bonusValue: bolds[1] ? text(bolds[1]) : '',
      totalValue: bolds[2] ? text(bolds[2]) : '',
      source: block
    };

    return result;
  }

  function buildBalance(root) {
    if (qs('.psych-purchases-balance', root)) return;

    const data = parseBonusBlock(root);
    if (!data) return;

    const wrap = document.createElement('section');
    wrap.className = 'psych-purchases-balance';

    wrap.innerHTML = `
      <div class="psych-purchases-balance__item">
        <div class="psych-purchases-balance__label">
          ${data.normalHref
            ? `<a href="${escapeHtml(data.normalHref)}">${escapeHtml(data.normalLabel)}</a>`
            : escapeHtml(data.normalLabel)}
        </div>
        <div class="psych-purchases-balance__value">${escapeHtml(data.normalValue || '0 руб.')}</div>
      </div>

      <div class="psych-purchases-balance__item">
        <div class="psych-purchases-balance__label">
          ${data.bonusHref
            ? `<a href="${escapeHtml(data.bonusHref)}">${escapeHtml(data.bonusLabel)}</a>`
            : escapeHtml(data.bonusLabel)}
        </div>
        <div class="psych-purchases-balance__value">${escapeHtml(data.bonusValue || '0 руб.')}</div>
      </div>

      <div class="psych-purchases-balance__item psych-purchases-balance__item--total">
        <div class="psych-purchases-balance__label">Всего</div>
        <div class="psych-purchases-balance__value">${escapeHtml(data.totalValue || data.normalValue || '0 руб.')}</div>
      </div>
    `;

    data.source.insertAdjacentElement('beforebegin', wrap);
    data.source.style.display = 'none';
  }

  function buildPromoButton(root) {
    if (qs('.psych-purchases-promo-link', root)) return;

    const promo = qsa('a.big', root).find(a => /промокод/i.test(text(a)));
    if (!promo) return;

    const link = document.createElement('a');
    link.className = 'psych-purchases-promo-link';
    link.href = promo.getAttribute('href') || '#';
    link.innerHTML = `
      <span class="psych-purchases-promo-link__icon">%</span>
      <span>Мои промокоды</span>
    `;

    promo.insertAdjacentElement('beforebegin', link);
    promo.style.display = 'none';

    let next = promo.nextSibling;
    let removed = 0;
    while (next && removed < 4) {
      const current = next;
      next = current.nextSibling;

      if (current.nodeType === Node.ELEMENT_NODE && current.tagName === 'BR') {
        current.remove();
        removed += 1;
        continue;
      }

      if (current.nodeType === Node.TEXT_NODE && !current.textContent.trim()) {
        current.remove();
        continue;
      }

      break;
    }
  }

  function getSectionTitleForTable(table) {
    let el = table.previousElementSibling;

    while (el) {
      if (/^H[1-6]$/.test(el.tagName)) {
        return text(el);
      }
      if (el.tagName === 'TABLE') break;
      el = el.previousElementSibling;
    }

    return '';
  }

  function detectType(table, title) {
    const headers = qsa('thead th', table).map(text).join(' | ').toLowerCase();
    const t = String(title || '').toLowerCase();

    if (t.includes('купленные продукты') || headers.includes('подписка')) {
      return 'products';
    }

    if (t.includes('промокоды') || headers.includes('условия')) {
      return 'promocodes';
    }

    if (t.includes('незавершенные') || t.includes('незавершённые')) {
      return 'pending';
    }

    if (t.includes('завершенные') || t.includes('завершённые')) {
      return 'completed';
    }

    if (headers.includes('номер') && headers.includes('заказ') && headers.includes('стоимость')) {
      const hasPayButton = !!qs('button, .btn-success', table);
      return hasPayButton ? 'pending' : 'completed';
    }

    return 'generic';
  }

  function getRows(table) {
    const tbodyRows = qsa('tbody tr', table);
    if (tbodyRows.length) return tbodyRows;

    return qsa(':scope > tr', table).filter(tr => !tr.closest('thead'));
  }

  function buildSection(title, type) {
    const section = document.createElement('section');
    section.className = `psych-purchases-section psych-purchases-section--${type}`;

    const head = document.createElement('div');
    head.className = 'psych-purchases-section__head';
    head.innerHTML = `
      <div>
        <div class="psych-purchases-section__eyebrow">${type === 'pending' ? 'Требует внимания' : 'История и доступы'}</div>
        <h2>${escapeHtml(title || 'Покупки')}</h2>
      </div>
    `;

    const body = document.createElement('div');
    body.className = 'psych-purchases-section__body';

    section.appendChild(head);
    section.appendChild(body);

    return { section, body };
  }

  function cloneActionButton(row, card) {
    const button = qs('button', row);
    if (button) {
      const clone = button.cloneNode(true);
      clone.className = 'psych-purchases-btn psych-purchases-btn--primary';
      card.appendChild(clone);
      return true;
    }

    const linkBtn = qsa('a', row).find(a => /оплат/i.test(text(a)));
    if (linkBtn) {
      const clone = linkBtn.cloneNode(true);
      clone.className = 'psych-purchases-btn psych-purchases-btn--primary';
      card.appendChild(clone);
      return true;
    }

    return false;
  }

  function buildOrderCard(row, type) {
    const cells = qsa(':scope > td', row);
    if (cells.length < 2) return null;

    const number = text(cells[0]);
    const productLink = qs('a[href]', cells[1]);
    const product = text(productLink) || text(cells[1]);
    const productHref = productLink?.getAttribute('href') || '';
    const status = text(qs('.deal-status, .label', row)) || text(cells[2]);
    const cost = normalizeCurrency(text(cells[cells.length - 1]));

    const card = document.createElement('article');
    card.className = `psych-purchases-card psych-purchases-card--order psych-purchases-card--${type}`;

    card.innerHTML = `
      <div class="psych-purchases-card__top">
        <div class="psych-purchases-card__ref">${escapeHtml(number || 'Заказ')}</div>
        ${status ? `<span class="psych-purchases-status">${escapeHtml(status)}</span>` : ''}
      </div>

      <div class="psych-purchases-card__title">
        ${productHref
          ? `<a href="${escapeHtml(productHref)}">${escapeHtml(product)}</a>`
          : escapeHtml(product)}
      </div>

      <div class="psych-purchases-card__meta">
        <div class="psych-purchases-meta">
          <span class="psych-purchases-meta__label">Стоимость</span>
          <strong>${escapeHtml(cost || '—')}</strong>
        </div>
      </div>
    `;

    cloneActionButton(row, card);
    return card;
  }

  function buildProductCard(row) {
    const cells = qsa(':scope > td', row);
    if (cells.length < 3) return null;

    const link = qs('a[href]', cells[0]);
    const parsed = splitPurchaseTitle(text(link) || text(cells[0]));
    const href = link?.getAttribute('href') || '';
    const period = text(cells[1]);
    const status = text(qs('.label, .deal-status', cells[2])) || text(cells[2]);
    const ending = text(cells[3]);

    const card = document.createElement('article');
    card.className = 'psych-purchases-card psych-purchases-card--product';

    card.innerHTML = `
      <div class="psych-purchases-card__top">
        <div class="psych-purchases-card__ref">${escapeHtml(parsed.ref || 'Доступ')}</div>
        ${status ? `<span class="psych-purchases-status">${escapeHtml(status)}</span>` : ''}
      </div>

      <div class="psych-purchases-card__title">
        ${href
          ? `<a href="${escapeHtml(href)}">${escapeHtml(parsed.title)}</a>`
          : escapeHtml(parsed.title)}
      </div>

      <div class="psych-purchases-card__meta psych-purchases-card__meta--grid">
        <div class="psych-purchases-meta">
          <span class="psych-purchases-meta__label">Период</span>
          <strong>${escapeHtml(period || '—')}</strong>
        </div>
        <div class="psych-purchases-meta">
          <span class="psych-purchases-meta__label">Заканчивается</span>
          <strong>${escapeHtml(ending || '—')}</strong>
        </div>
      </div>
    `;

    return card;
  }

  function buildPromoCard(row) {
    const cells = qsa(':scope > td', row);
    if (!cells.length) return null;

    const title = text(cells[0]);
    const conditions = text(cells[1]);

    const card = document.createElement('article');
    card.className = 'psych-purchases-card psych-purchases-card--promo';

    card.innerHTML = `
      <div class="psych-purchases-card__title">${escapeHtml(title || 'Промокод')}</div>
      ${conditions
        ? `<div class="psych-purchases-card__description">${escapeHtml(conditions)}</div>`
        : `<div class="psych-purchases-card__description psych-purchases-card__description--muted">Без дополнительных условий</div>`
      }
    `;

    return card;
  }

  function transformTable(table) {
    if (table.dataset.psychPurchasesReady === '1') return;

    const title = getSectionTitleForTable(table);
    const type = detectType(table, title);
    const rows = getRows(table);

    if (!rows.length) return;

    const { section, body } = buildSection(title, type);
    let count = 0;

    rows.forEach(row => {
      let card = null;

      if (type === 'products') card = buildProductCard(row);
      else if (type === 'promocodes') card = buildPromoCard(row);
      else if (type === 'pending' || type === 'completed' || type === 'generic') {
        card = buildOrderCard(row, type);
      }

      if (card) {
        body.appendChild(card);
        count += 1;
      }
    });

    if (!count) return;

    const heading = (() => {
      let el = table.previousElementSibling;
      while (el) {
        if (/^H[1-6]$/.test(el.tagName)) return el;
        if (el.tagName === 'TABLE') return null;
        el = el.previousElementSibling;
      }
      return null;
    })();

    if (heading) heading.style.display = 'none';

    table.insertAdjacentElement('beforebegin', section);
    table.style.display = 'none';
    table.dataset.psychPurchasesReady = '1';
  }

  function enhance() {
    const root = getRoot();
    if (!root) return;

    document.body.classList.add('psych-purchases-ui');

    buildHero(root);
    buildBalance(root);
    buildPromoButton(root);

    qsa('table.table, table.table-notitle', root).forEach(transformTable);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', enhance, { once: true });
  } else {
    enhance();
  }
})();
