/*
  FOUNDATION DUPLICATION ENGINE – FINAL CLEAN VERSION
  Works with: imported bars, equipment, column types, column bases, after-excavation.
  Compatible with your posted HTML. Safe for modal-loaded forms.
*/

(function () {
  "use strict";

  /** Utility: clear inputs/selects when keeping template but not removing */
  function clearFields(row) {
    row.querySelectorAll("input").forEach((i) => {
      if (i.type === "checkbox" || i.type === "radio") i.checked = false;
      else i.value = "";
    });
    row.querySelectorAll("textarea").forEach((t) => (t.value = ""));
    row.querySelectorAll("select").forEach((s) => {
      // If empty option exists, select it; otherwise select first item
      if ([...s.options].some((o) => o.value === "")) {
        s.value = "";
      } else {
        s.selectedIndex = 0;
      }
    });
  }

  /** Utility: Attach remove button to clone */
  function addRemoveButton(row, className = "remove-btn") {
    // Remove any existing remove button inside clone
    row.querySelectorAll("." + className).forEach((btn) => btn.remove());

    const btn = document.createElement("button");
    btn.type = "button";
    btn.className = className;
    btn.textContent = "X";
    btn.style.cssText =
      "margin-left:6px;padding:4px 10px;background:#c0392b;color:white;" +
      "border:none;border-radius:4px;cursor:pointer;height:32px;";

    btn.onclick = function () {
      removeRow(btn);
    };

    row.appendChild(btn);
  }

  /** Utility: check if removing is allowed (don't remove last template row) */
  function canRemoveRow(row) {
    const parent = row.parentElement;
    if (!parent) return true;

    const rows = [...parent.children].filter((child) =>
      child.matches(
        ".row, .column-base-row, .column-type-row, .imported-bar-row, .equipment-row, .after-exc-row"
      )
    );

    return rows.length > 1; // only allow removal if >1 rows remain
  }

  /** GLOBAL removeRow function (used by all sections) */
  window.removeRow = function (btn) {
    const row = btn.closest(
      ".row, .column-base-row, .column-type-row, .imported-bar-row, .equipment-row, .after-exc-row"
    );

    if (!row) return;

    if (!canRemoveRow(row)) {
      clearFields(row);
      return;
    }

    row.remove();
  };

  /**
   * MASTER DUPLICATOR
   * containerId = ID of container
   * selector = CSS selector for rows inside container
   * keepValues = keep values from previous row (you want this = true)
   */
  function cloneRow(containerId, selector, keepValues = true, removeClass = "remove-btn") {
    const container = document.getElementById(containerId);
    if (!container) return;

    const template =
      container.querySelector(selector + ":last-of-type") ||
      container.querySelector(selector);

    if (!template) return;

    // clone row deeply
    const clone = template.cloneNode(true);

    // Remove inline labels from clone (you requested duplicates without labels)
    clone.querySelectorAll("label").forEach((l) => l.remove());

    // Remove any previous remove buttons inside clone
    clone.querySelectorAll("." + removeClass).forEach((b) => b.remove());

    // If not keeping values, clear clone fields
    if (!keepValues) clearFields(clone);

    // Attach remove button
    addRemoveButton(clone, removeClass);

    container.appendChild(clone);
    return clone;
  }

  // ===============================================================
  //  YOUR SECTIONS (ALL LINKED TO YOUR BUTTONS IN HTML)
  // ===============================================================

  /** Imported Bars */
  window.addImportedBarRow = function () {
    cloneRow("importedBarsContainer", ".imported-bar-row", true, "removeBtn");
  };

  /** Equipment */
  window.addEquipmentRow = function () {
    cloneRow("equipmentContainer", ".equipment-row", true, "removeBtn");
  };

  /** Column Types */
  window.addColumnTypeRow = function () {
    const row = cloneRow("columnTypeContainer", ".column-type-row", true, "removeBtn");
    if (!row) return;

    // Align remove button same way your HTML positions it
    const btn = row.querySelector(".removeBtn");
    if (btn) {
      const wrap = document.createElement("div");
      wrap.style.display = "flex";
      wrap.style.flexDirection = "column";
      wrap.style.justifyContent = "flex-end";
      wrap.style.marginLeft = "6px";
      wrap.appendChild(btn);
      row.appendChild(wrap);
    }
  };

  /** Column Base */
  window.addColumnBaseRow = function () {
    cloneRow("columnBaseContainer", ".column-base-row", true, "remove-btn");
  };

  /** After Excavation */
  window.addAfterExcavationRow = function () {
    const row = cloneRow("afterExcavationContainer", ".after-exc-row", true, "remove-btn");
    if (!row) return;

    // Auto-expand field (if template contains autoSpan & autoInput)
    const input = row.querySelector(".autoInput");
    const span = row.querySelector(".autoSpan");

    if (input && span) {
      input.addEventListener("input", function () {
        span.textContent = input.value;
        input.style.width = Math.max(246, span.offsetWidth) + "px";
      });
    }
  };

  // ===============================================================
  // MODAL-SAFE INITIALIZATION
  // ===============================================================

  /** Initialize script after modal loads its content */
  function initDuplicateEngine() {
    // This function stays available for manual calls if needed
  }

  window.initStageScripts = initDuplicateEngine;

  // If Bootstrap modal is used, auto-init after modal opens
  if (window.jQuery) {
    jQuery(document).on("shown.bs.modal", function () {
      initDuplicateEngine();
    });
  }

  // In case modal content already exists in DOM
  document.addEventListener("DOMContentLoaded", initDuplicateEngine);
})();
