(() => {
  const debug = (() => {
    try {
      return new URL(window.location.href).searchParams.get("tb_debug") === "1";
    } catch {
      return false;
    }
  })();

  function log(...args) {
    if (!debug) return;
    // eslint-disable-next-line no-console
    console.log("[tb-ticket]", ...args);
  }

  function formatCopIntPart(value) {
    const n = Number(value);
    if (!Number.isFinite(n)) return "0";
    return Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
  }

  function formatCop(value) {
    return "$" + formatCopIntPart(value);
  }

  function getSelection() {
    const url = new URL(window.location.href);
    const fromUrl = {
      event: url.searchParams.get("tb_event") || "",
      date: url.searchParams.get("tb_date") || "",
      ticket: url.searchParams.get("tb_ticket") || "",
      price: url.searchParams.get("tb_price") || "",
    };

    const urlHas = fromUrl.ticket && fromUrl.price;
    if (urlHas) return fromUrl;

    try {
      const ticket = sessionStorage.getItem("tb_selected_ticket") || "";
      const price = sessionStorage.getItem("tb_selected_price") || "";
      const event = sessionStorage.getItem("tb_selected_event") || "";
      const date = sessionStorage.getItem("tb_selected_date") || "";
      if (ticket && price) return { event, date, ticket, price };
    } catch {
      // ignore
    }

    return null;
  }

  function updateAmountEl(amountEl, price) {
    if (!amountEl) return;
    const intPart = amountEl.querySelector(".int_part");
    if (intPart) intPart.textContent = formatCopIntPart(price);
    amountEl.setAttribute("data-amount", String(Math.round(price) * 1000));
  }

  function updateSeatCategoryText(ticketName) {
    const seatCategoryEl = document.getElementById("seat_category_10230352475856");
    if (!seatCategoryEl) return;
    const prev = (seatCategoryEl.textContent || "").trim();
    const m = prev.match(/^(\d+)\s+Ticket\b/i);
    const qty = m ? m[1] : "1";
    seatCategoryEl.textContent = `${qty} Ticket ${ticketName}`;
  }

  function applySelectionSimplePage(sel) {
    const price = Number(sel.price);
    if (!Number.isFinite(price) || price <= 0) return false;

    const ticketEl = document.getElementById("tbSummaryTicket");
    const priceEl = document.getElementById("tbSummaryPrice");
    const totalEl = document.getElementById("tbSummaryTotal");
    const eventEl = document.getElementById("tbSummaryEvent");
    const dateEl = document.getElementById("tbSummaryDate");
    const hintEl = document.getElementById("tbSummaryHint");
    const eventLineEl = document.getElementById("tbSummaryEventLine");

    if (!ticketEl || !priceEl || !totalEl) return false;

    document.documentElement.setAttribute("data-tb-ticket-selection", "1");

    if (eventEl) eventEl.textContent = sel.event || "—";
    if (dateEl) dateEl.textContent = sel.date || "—";
    ticketEl.textContent = sel.ticket || "—";
    priceEl.textContent = formatCop(price);
    totalEl.textContent = formatCop(price);
    if (hintEl) hintEl.hidden = true;
    if (eventLineEl) {
      const parts = [];
      if (sel.event) parts.push(sel.event);
      if (sel.date) parts.push(sel.date);
      eventLineEl.textContent = parts.length ? parts.join(" · ") : "Confirma la localidad y continúa al pago.";
    }

    return true;
  }

  function applySelection(sel) {
    const price = Number(sel.price);
    if (!Number.isFinite(price) || price <= 0) return;

    if (applySelectionSimplePage(sel)) return;

    document.documentElement.setAttribute("data-tb-ticket-selection", "1");

    updateSeatCategoryText(sel.ticket);

    const seatInfo = document.getElementById("seat_info_10230352478348");
    if (seatInfo) seatInfo.textContent = sel.ticket;

    // Line item unit price (specific row)
    const rowHeader = document.getElementById("mov_10230352478348");
    const row = rowHeader ? rowHeader.closest("tr") : null;
    if (row) {
      const unitAmount = row.querySelector("td.unit_price .amount.amount_COP");
      updateAmountEl(unitAmount, price);
    }

    // Subtotal / reservation amount
    const reservationCell = document.querySelector("td.reservation_amount");
    if (reservationCell) {
      reservationCell.setAttribute("data-amount", String(Math.round(price) * 1000));
      const subtotalAmount = reservationCell.querySelector(".amount.amount_COP");
      updateAmountEl(subtotalAmount, price);
    }

    // Cart summary total (hidden summary section)
    const cartTotalAmount = document.querySelector("p.total .amount.amount_COP");
    updateAmountEl(cartTotalAmount, price);

    // Any other duplicated subtotal display in page (keep narrow)
    const reservationAmount = document.querySelector("td.reservation_amount .amount.amount_COP");
    updateAmountEl(reservationAmount, price);
  }

  function init() {
    const sel = getSelection();
    if (!sel) {
      const hintEl = document.getElementById("tbSummaryHint");
      if (hintEl) hintEl.hidden = false;
      return;
    }

    log("selection", sel);

    // Apply now and then retry with backoff in case checkout scripts repaint the DOM.
    const delays = [0, 200, 600, 1200, 2500, 5000, 9000, 15000, 25000];
    for (const d of delays) setTimeout(() => applySelection(sel), d);

    // Lightweight observer: only watch key containers when they exist.
    if (typeof MutationObserver === "function") {
      const targets = [
        document.getElementById("seat_category_10230352475856")?.parentElement,
        document.getElementById("seat_info_10230352478348")?.parentElement,
        document.querySelector("p.total")?.parentElement,
        document.querySelector("td.reservation_amount")?.parentElement,
      ].filter(Boolean);

      if (targets.length) {
        const obs = new MutationObserver(() => applySelection(sel));
        for (const t of targets) obs.observe(t, { subtree: true, childList: true, characterData: true });
        setTimeout(() => obs.disconnect(), 12000);
      }
    }
  }

  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
  else init();
})();
