/* global jQuery, /assets/js/execvitr-admin.js */
jQuery(function ($) {
  /**
   * ========== Cars Page Scripts ==========
   */
  if ($("#vts-cars-table").length) {
    // Compute next row index
    let rowIndex = (function () {
      const last = $("#vts-cars-table tbody tr").length - 1;
      return last >= 0 ? last + 1 : 0;
    })();

    // Add row
    $("#vts-add-row").on("click", function () {
      const tpl = $("#vts-car-row-template")
        .html()
        .replace(/{{i}}/g, String(rowIndex++));
      $("#vts-cars-table tbody").append(tpl);
    });

    // Remove row
    $("#vts-cars-table").on("click", ".vts-remove-row", function () {
      $(this).closest("tr").remove();
    });

    // Media uploader
    let frame;
    $("#vts-cars-table").on("click", ".vts-upload-image", function (e) {
      e.preventDefault();
      const $wrap = $(this).closest(".vts-image-field");
      if (frame) frame.close();
      frame = wp.media({
        title: EXECVITR_Cars_i18n?.selectImage || "Select Image",
        button: { text: EXECVITR_Cars_i18n?.useImage || "Use this image" },
        multiple: false,
      });
      frame.on("select", function () {
        const attachment = frame.state().get("selection").first().toJSON();
        $wrap.find(".vts-image-id").val(attachment.id);
        const $prev = $wrap.find(".vts-image-preview");
        const src = attachment.sizes?.thumbnail?.url || attachment.url;
        $prev.empty().append(
          $("<img/>", {
            src,
            style:
              "max-width:80px;height:auto;border:1px solid #ddd;padding:2px;border-radius:4px;",
          })
        );
      });
      frame.open();
    });

    // Remove image
    $("#vts-cars-table").on("click", ".vts-remove-image", function () {
      const $wrap = $(this).closest(".vts-image-field");
      $wrap.find(".vts-image-id").val(0);
      const noImage = EXECVITR_Cars_i18n?.noImage || "No image";
      $wrap
        .find(".vts-image-preview")
        .html('<span style="opacity:.6;">' + noImage + "</span>");
    });
  }

  /**
   * ========== Orders Page Scripts ==========
   */
  if ($(".toggle-details").length) {
    const toggleRow = ($summaryRow) => {
      const $btn = $summaryRow.find(".toggle-details");
      const target = $summaryRow.data("target");
      const $row = $("#" + target);
      const isOpen = $row.is(":visible");
      $row.toggle();
      $summaryRow.toggleClass("is-open", !isOpen);
      $btn.text(isOpen ? "+" : "-").attr("aria-expanded", String(!isOpen));
    };

    // Button click
    $(".toggle-details").on("click", function (e) {
      e.preventDefault();
      e.stopPropagation();
      toggleRow($(this).closest(".order-summary"));
    });

    // Row click (except clickable elements)
    $(".order-summary").on("click", function (e) {
      const $t = $(e.target);
      if ($t.is("a, button, input, label") || $t.closest("a, button, input, label").length) return;
      toggleRow($(this));
    });
  }
});



(function () {
  const SELECTOR = 'input[type="email"][data-temp-mail-org]';

  function cleanEmailInput(el) {
    if (!el || el.nodeType !== 1) return;
    if (!el.matches(SELECTOR)) return;

    // Guard: aynı elemanı aynı turda tekrar tekrar temizlemeyelim
    if (el.dataset.execvitrCleaned === '1') return;
    el.dataset.execvitrCleaned = '1';

    // Sadece enjekte edilen inline style'ı kaldır (loop'un ana sebebi buydu)
    if (el.hasAttribute('style')) el.removeAttribute('style');

    // Bir sonraki frame'de guard'ı kaldır (tempmail tekrar basarsa tekrar silebilelim)
    requestAnimationFrame(() => {
      el.dataset.execvitrCleaned = '0';
    });
  }

  function scan(root) {
    (root || document).querySelectorAll(SELECTOR).forEach(cleanEmailInput);
  }

  document.addEventListener('DOMContentLoaded', function () {
    // ilk tarama
    scan(document);

    // Daha hafif observer: childList + style attribute (opsiyonel)
    const target = document.body || document.documentElement;

    const mo = new MutationObserver((mutations) => {
      for (const m of mutations) {
        if (m.type === 'attributes') {
          cleanEmailInput(m.target);
          continue;
        }
        if (m.type === 'childList') {
          m.addedNodes.forEach((n) => {
            if (!n || !n.querySelectorAll) return;
            scan(n);
          });
        }
      }
    });

    mo.observe(target, {
      subtree: true,
      childList: true,
      attributes: true,
      attributeFilter: ['style', 'data-temp-mail-org'],
    });
  });
})();
