if (!document.getElementById("kform-inputsection-style")) {
  const style = document.createElement("style");
  style.id = "kform-inputsection-style";
  style.textContent = `
      .kform-input-row-container {
        margin-bottom: 20px;
        padding: 0 22px;
      }

      .kform-input-row-segment {
        display: flex;
        flex-wrap: nowrap;
        margin-top: 10px;
        width: 100%;
        gap: 10px;
        justify-content: flex-start;
      }

      .kform-input-container {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
      }

      .kform-input-label {
        margin-bottom: 15px;
        font-size: 16px;
        padding-left: 20px;
      }

      .kform-custom-input {
        padding: 5px !important;
        border: 1px solid #ccc !important;
        border-radius: 6px !important;
        outline: none !important;
        transition: all 0.2s ease !important;
        box-sizing: border-box !important;
        width: 100% !important;
      }

      .kform-custom-input:focus {
        border-color: #007bff;
        box-shadow: 0 0 3px rgba(0, 123, 255, 0.5);
      }

      input[type="number"].kform-hide-spinners::-webkit-inner-spin-button,
      input[type="number"].kform-hide-spinners::-webkit-outer-spin-button {
        -webkit-appearance: none;
        margin: 0;
      }
      input[type="number"].kform-hide-spinners {
        -moz-appearance: textfield;
      }

      .kform-radio-group {
        display: flex;
        gap: 12px;
        flex-direction: column;
        margin: 20px;
      }

      .kform-radio-option {
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        font-size: 14px;
      }

      .kform-combobox-select {
        padding: 5px;
        border-radius: 6px;
        outline: none;
        box-sizing: border-box;
        width: 100%;
      }

      .kform-userpicker-wrapper {
        position: relative;
      }

      .kform-userpicker-list {
        position: absolute;
        top: 100%;
        right: 0;
        left: 0;
        background: #fff;
        border: 1px solid #ccc;
        border-radius: 6px;
        max-height: 200px;
        overflow-y: auto;
        z-index: 993532543563464324599;
      }

      .kform-userpicker-item {
        padding: 6px 10px;
        cursor: pointer;
        font-size: 14px;
      }

      .kform-userpicker-item:hover {
        background: #f0f0f0;
      }
      #Form select option:nth-child(even), div[id*=k-modal] select option:nth-child(even) {
        background-color: #F5F5F5 !important;
        color: #222 !important;
        font-size: 16px !important;
      }
      #Form select option:nth-child(odd), div[id*=k-modal] select option:nth-child(odd) {
        background-color: #bae6ee !important;
        color: #222 !important;
        font-size: 16px !important;
      }

      #Form select:disabled, [id*=k-modal] select:disabled {
        color: black !important;
      }
  `;
  document.head.appendChild(style);
}

function createInputRow(
  root,
  rowName,
  inputsConfig,
  totalSlots = 5,
  gapPx = 10
) {
  root = document.getElementById(root);
  if (!root) throw new Error("No root found.");

  const container = document.createElement("div");
  container.className = "kform-input-row-container";
  container.dataset.name = rowName;

  let segmentInputs = [];
  let segmentSlots = 0;

  function flushSegment() {
    if (!segmentInputs.length) return;
    const rowSegment = document.createElement("div");
    rowSegment.className = "kform-input-row-segment";

    segmentInputs.forEach(async (cfg) => {
      const size = cfg.size || 1;
      const inputContainer = document.createElement("div");
      inputContainer.className = "kform-input-container";

      if (cfg.inline == null || cfg.inline == undefined) cfg.inline = false;
      if (cfg.inline == true) inputContainer.style.flexDirection = "row";

      const totalGap = (segmentInputs.length - 1) * gapPx;
      const widthPercent = (size / totalSlots) * 100;
      inputContainer.style.flex = `0 0 calc(${widthPercent}% - ${
        (size / totalSlots) * totalGap
      }px)`;

      if (cfg.labelVisible == null || cfg.labelVisible == undefined)
        cfg.labelVisible = true;

      const label = document.createElement("label");
      label.className = "kform-input-label";
      label.textContent = cfg.label || "Label";
      label.setAttribute("for", cfg.id);
      if (cfg.inline == true) label.style.margin = "auto";
      inputContainer.appendChild(label);

      if (!cfg.labelVisible) {
        label.style.color = "transparent";
      }
      let element;

      // LABEL
      if (cfg.type === "label") {
        element = document.createElement("label");
        element.className = "kform-input-label";
        element.style.margin = cfg.margin || "auto";
        element.style.height = "35px";
        element.style.borderRadius = "6px";
        element.style.textAlign = cfg.textAlign || "right";
        element.id = cfg.id;
        element.style.padding = "5px 0";
        element.textContent = cfg.labelText || cfg.label || "";
        element.style.backgroundColor = cfg.backgroundColor || "#FFF";
        if (cfg.nullElement) {
          element.style.color = "transparent";
          element.style.backgroundColor = "transparent";
        }
        inputContainer.appendChild(element);
        rowSegment.appendChild(inputContainer);
        return;
      }

      // Title
      else if (cfg.type === "title") {
        label.parentElement.style.borderBottom = cfg.borderBottom;
        label.style.fontWeight = "bold";
        label.style.color = cfg.color;
        inputContainer.appendChild(label);
        rowSegment.appendChild(inputContainer);
        return;
      }

      // SELECT
      else if (cfg.type === "combobox") {
        element = document.createElement("select");
        element.className = "kform-combobox-select";
        element.id = cfg.id;

        const placeHolderOptionEl = document.createElement("option");
        placeHolderOptionEl.value = "";
        placeHolderOptionEl.textContent = "یک مورد را انتخاب نمایید.";
        placeHolderOptionEl.selected = true;

        element.appendChild(placeHolderOptionEl);

        cfg.options.forEach((opt) => {
          const optionEl = document.createElement("option");
          optionEl.value = opt.value;
          optionEl.textContent = opt.label;
          if (
            cfg.defaultValue !== undefined &&
            opt.value === cfg.defaultValue
          ) {
            optionEl.selected = true;
          }
          element.appendChild(optionEl);
        });
      }

      // LOOKUP
      else if (cfg.type === "lookup") {
        element = document.createElement("select");
        element.classList.add("kform-lookup-select", "kform-combobox-select");
        element.id = cfg.id + "Id";

        const valueField = cfg.valueField || "Id";
        const textField = cfg.textField || "Title";
        const saveId = cfg.saveId !== false;

        element.setAttribute("valuefield", valueField);
        element.setAttribute("textfield", textField);
        element.setAttribute("saveid", saveId);
        element.setAttribute("defaultvalue", cfg.defaultValue);
        element.setAttribute("siteurl", cfg.siteUrl);
        element.setAttribute("listname", cfg.listName);

        filter = cfg.filter;

        // placeholder
        const placeholder = document.createElement("option");
        element.appendChild(placeholder);

        var apiUrl = `${cfg.siteUrl}/_api/web/lists/getbytitle('${cfg.listName}')/items?$select=${valueField},${textField}`;
        if (filter) {
          apiUrl += `&$filter=${filter}`;
        }

        fetch(apiUrl, {
          headers: {
            Accept: "application/json;odata=nometadata",
          },
        })
          .then((res) => res.json())
          .then((data) => {
            data.value.forEach((item) => {
              const option = document.createElement("option");
              option.value = saveId ? item[valueField] : item[textField];
              option.textContent = item[textField];

              if (
                cfg.defaultValue !== undefined &&
                option.value == cfg.defaultValue
              ) {
                option.selected = true;
              }

              element.appendChild(option);
            });
          })
          .catch((err) => {
            console.error("Lookup load failed:", err);
          });
      }

      // Multi Lookup
      else if (cfg.type === "multilookup") {
        element = document.createElement("div");
        element.classList.add("kform-multilookup");
        element.id = cfg.id + "Id";

        element.setAttribute("siteurl", cfg.siteUrl);
        element.setAttribute("listname", cfg.listName);
        element.setAttribute("valuefield", cfg.valueField || "Id");
        element.setAttribute("textfield", cfg.textField || "Title");

        const gridData = setGridDataFromArray(cfg.defaultValue || "");

        element.onchange = () => {
          if (cfg.onchangefunction != undefined) cfg.onchangefunction();
          element.classList.add("K_Dirty_Input");
        };

        inputContainer.appendChild(element);
        rowSegment.appendChild(inputContainer);

        await createSPComboboxGrid(element, {
          gridName: cfg.id + "_Grid",
          displayName: cfg.label || "",
          siteUrl: cfg.siteUrl,
          listName: cfg.listName,
          displayColumn: cfg.textField || "Title",
          data: gridData,
          filter: cfg.filter,
        });

        // Attach API to element (important)
        element.getValue = () => getGridSelectedValues(gridData);
        element.setValue = (val) => {
          gridData.length = 0;
          gridData.push(...setGridDataFromArray(val));
          createSPComboboxGrid(element, {
            gridName: cfg.id + "_Grid",
            displayName: cfg.label || "",
            siteUrl: cfg.siteUrl,
            listName: cfg.listName,
            displayColumn: cfg.textField || "Title",
            data: gridData,
            filter: cfg.filter,
          });
        };
        return;
      }

      else if (cfg.type === "multiuserpicker") {
        element = document.createElement("div");
        element.classList.add("kform-multiuserpicker");
        element.id = cfg.id + "Id";

        element.setAttribute("siteurl", cfg.siteUrl);

        const gridData = setGridDataFromArray(cfg.defaultValue || "");

        element.onchange = () => {
          if (cfg.onchangefunction != undefined) cfg.onchangefunction();
          element.classList.add("K_Dirty_Input");
        };

        inputContainer.appendChild(element);
        rowSegment.appendChild(inputContainer);

        await createSPUserpickerGrid(element, {
          gridName: cfg.id + "_Multiuserpicker_Grid",
          displayName: cfg.label || "",
          siteUrl: cfg.siteUrl,
          data: gridData,
          filter: cfg.filter,
        });

        // Attach API to element (important)
        element.getValue = () => getGridSelectedValues(gridData);
        element.setValue = (val) => {
          gridData.length = 0;
          gridData.push(...setGridDataFromArray(val));
          createSPUserpickerGrid(element, {
            gridName: cfg.id + "_Multiuserpicker_Grid",
            displayName: cfg.label || "",
            siteUrl: cfg.siteUrl,
            data: gridData,
            filter: cfg.filter,
          });
        };
        return;
      }

      // RADIO
      else if (cfg.type === "radio") {
        element = document.createElement("div");
        element.className = "kform-radio-group";

        cfg.options.forEach((opt, i) => {
          const radioId = `${cfg.id}_${i}`;
          const radioWrapper = document.createElement("label");
          radioWrapper.className = "kform-radio-option";

          const radio = document.createElement("input");
          radio.type = "radio";
          radio.name = cfg.id;
          radio.value = opt.value;
          radio.id = radioId;

          if (cfg.defaultValue && cfg.defaultValue === opt.value) {
            radio.checked = true;
          }

          radio.addEventListener("click", function () {
            element.classList.add("K_Dirty_Input");
            if (this.checked && this.dataset.wasChecked === "true") {
              this.checked = false;
              this.dataset.wasChecked = "false";
              document
                .querySelectorAll(`input[name="${cfg.id}"]`)
                .forEach((r) => (r.dataset.wasChecked = "false"));
            } else {
              document
                .querySelectorAll(`input[name="${cfg.id}"]`)
                .forEach((r) => (r.dataset.wasChecked = "false"));
              this.dataset.wasChecked = "true";
            }
          });

          const span = document.createElement("span");
          span.textContent = opt.label;

          radioWrapper.appendChild(radio);
          radioWrapper.appendChild(span);

          element.appendChild(radioWrapper);
        });
      }

      // DATE
      else if (cfg.type === "date") {
        element = document.createElement("input");
        element.type = "text"; // keep text if you use Persian date picker
        element.placeholder = cfg.placeholder || "تاریخ را وارد کنید";

        // same class your grid uses
        element.classList.add("kform-custom-input", "p-date-picker");
        element.setAttribute("data-jdp", "true");

        if (cfg.defaultValue) {
          element.value = cfg.defaultValue;
        }
      }

      // USER PICKER
      else if (cfg.type === "userpicker") {
        const wrapper = document.createElement("div");
        wrapper.classList.add("kform-userpicker-wrapper", "kform-custom-input");

        element = document.createElement("input");
        element.type = "text";
        element.classList.add("kform-custom-input");
        element.placeholder = cfg.placeholder || "نام کاربر را وارد کنید";
        element.autocomplete = "off";
        element.setAttribute("input-type", "userpicker");
        element.id = cfg.id + "Id";
        element.addEventListener("keydown", (e)=>{
          if(e.key === "Backspace") {
            
            element.value = "";
          }
        })

        const list = document.createElement("div");
        list.classList.add("kform-userpicker-list");
        list.style.display = "none";

        let timeout = null;

        element.addEventListener("input", () => {
          const query = element.value.trim();

          if (query.length < 3) {
            list.style.display = "none";
            list.innerHTML = "";
            return;
          }

          clearTimeout(timeout);

          timeout = setTimeout(() => {
            fetch(
              `${cfg.siteUrl}/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser`,
              {
                method: "POST",
                headers: {
                  Accept: "application/json;odata=verbose",
                  "Content-Type": "application/json;odata=verbose",
                  "X-RequestDigest":
                    document.getElementById("__REQUESTDIGEST").value,
                },
                body: JSON.stringify({
                  queryParams: {
                    AllowEmailAddresses: true,
                    AllowMultipleEntities: false,
                    AllUrlZones: false,
                    MaximumEntitySuggestions: 10,
                    PrincipalSource: 15,
                    PrincipalType: 1,
                    QueryString: query,
                  },
                }),
              }
            )
              .then((res) => res.json())
              .then((data) => {
                const results = JSON.parse(data.d.ClientPeoplePickerSearchUser);

                list.innerHTML = "";
                list.style.display = "block";

                results.forEach((user) => {
                  const item = document.createElement("div");
                  item.className = "kform-userpicker-item";
                  item.textContent = user.DisplayText;

                  item.onclick = () => {
                    element.value = user.DisplayText;
                    element.dataset.login = user.Key;
                    list.style.display = "none";
                    element.classList.add("K_Dirty_Input");
                  };

                  list.appendChild(item);
                });
              })
              .catch((err) => {
                console.error("User picker failed:", err);
              });
          }, 300);
        });

        document.addEventListener("click", (e) => {
          if (!wrapper.contains(e.target)) {
            list.style.display = "none";
          }
        });

        if (cfg.save == false) {
          element.setAttribute("save", false);
        } else {
          element.setAttribute("save", true);
        }

        wrapper.appendChild(element);
        wrapper.appendChild(list);
        inputContainer.appendChild(wrapper);
        rowSegment.appendChild(inputContainer);
        return;
      }

      // TEXTAREA
      else if (cfg.type === "multiline") {
        element = document.createElement("textarea");
      }

      // INPUT
      else {
        element = document.createElement("input");

        if (cfg.type === "number" && cfg.formatThousands) {
          element.type = "text";
          element.dataset.originalType = "number";

          element.addEventListener("input", (e) => {
            const el = e.target;

            // Save cursor position BEFORE formatting
            const start = el.selectionStart;

            // Remove all non-digits
            let raw = el.value.replace(/[^\d]/g, "");

            // Count digits to the left of cursor BEFORE formatting
            const digitsBefore = el.value
              .slice(0, start)
              .replace(/[^\d]/g, "").length;

            // Reformat with commas
            let formatted = raw.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            el.value = formatted;

            // Restore caret position by moving to the same number of digits
            let newPos = 0;
            let digitsSeen = 0;

            while (newPos < formatted.length && digitsSeen < digitsBefore) {
              if (/\d/.test(formatted[newPos])) digitsSeen++;
              newPos++;
            }

            el.setSelectionRange(newPos, newPos);
          });
        } else {
          element.type = cfg.type || "text";
        }
      }

      // APPLY INPUT-ONLY STYLES
      if (cfg.type !== "label") {
        element.id = cfg.id;

        if (element.tagName === "INPUT" || element.tagName === "TEXTAREA") {
          element.classList.add("kform-custom-input");
        }
        if (element.tagName === "SELECT") {
          element.classList.add("kform-combobox-select");
        }
        if (element.className.includes("kform-lookup-select")) {
          element.id = cfg.id + "Id";
        }

        if (
          cfg.type === "number" &&
          !cfg.formatThousands &&
          cfg.showSpinners === false
        ) {
          element.classList.add("kform-hide-spinners");
        }

        element.style.fontSize = cfg.fontSize || "14px";
        if (cfg.type == "radio") {
          element.style.backgroundColor = cfg.backgroundColor || "transparent";
          element.style.height = cfg.height || "";
        } else {
          element.style.backgroundColor = cfg.backgroundColor || "#fff";
          element.style.height = cfg.height || "35px";
        }

        element.style.textAlign = cfg.textAlign || "right";
        element.style.color = cfg.color || "#000";
        element.style.borderColor = cfg.borderColor || "rgb(100, 100, 100)";
        if (cfg.margin) element.style.margin = cfg.margin;
        if (cfg.disabled) element.disabled = true;

        element.onchange = () => {
          if (cfg.onchangefunction != undefined) cfg.onchangefunction();
          element.classList.add("K_Dirty_Input");
        };
      }

      if (cfg.defaultValue) {
        SetElement(element.id, cfg.defaultValue);
      }
      if (cfg.save == false) {
        element.setAttribute("save", false);
      } else {
        element.setAttribute("save", true);
      }

      inputContainer.appendChild(element);
      rowSegment.appendChild(inputContainer);
    });

    container.appendChild(rowSegment);
    segmentInputs = [];
    segmentSlots = 0;
  }

  inputsConfig.forEach((cfg) => {
    const size = cfg.size || 1;

    if (segmentSlots + size > totalSlots) flushSegment();

    segmentInputs.push(cfg);
    segmentSlots += size;

    if (segmentSlots === totalSlots) flushSegment();
  });

  if (segmentInputs.length) flushSegment();

  root.appendChild(container);
}

function getInputRowValues(rowName) {
  const container = document.querySelector(
    `.kform-input-row-container[data-name="${rowName}"]`
  );
  if (!container) return {};

  const inputs = container.querySelectorAll("input, select");
  const values = {};

  inputs.forEach((input) => {
    let val = input.value;
    if (input.dataset.originalType === "number") {
      val = val.replace(/,/g, "");
    }
    values[input.id] = val;
  });

  return values;
}

function setInputRowValues(rowName, valuesObj) {
  const container = document.querySelector(
    `.kform-input-row-container[data-name="${rowName}"]`
  );
  if (!container) return;

  const inputs = container.querySelectorAll("input, select");

  inputs.forEach((input) => {
    if (valuesObj.hasOwnProperty(input.id)) {
      let val = valuesObj[input.id];
      if (input.dataset.originalType === "number") {
        input.value = val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      } else {
        input.value = val;
      }
    }
  });
}

function setLookupOptions(id, filter) {
  const element = document.getElementById(id);
  element.innerHTML = "";

  const valueField = element.getAttribute("valuefield");
  const textField = element.getAttribute("textfield");
  const saveId = element.getAttribute("saveid");
  const defaultValue = element.getAttribute("defaultvalue");
  const siteUrl = element.getAttribute("siteurl");
  const listName = element.getAttribute("listname");

  // placeholder
  const placeholder = document.createElement("option");
  element.appendChild(placeholder);

  var apiUrl = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=${valueField},${textField}`;
  if (filter) {
    apiUrl += `&$filter=${filter}`;
  }

  fetch(apiUrl, {
    headers: {
      Accept: "application/json;odata=nometadata",
    },
  })
    .then((res) => res.json())
    .then((data) => {
      const items = data.value;
      for (var it = 0; it < items.length; it++) {
        const option = document.createElement("option");
        option.value =
          saveId == "true" ? items[it][valueField] : items[it][textField];
        option.textContent = items[it][textField];

        if (defaultValue !== undefined && option.value == defaultValue) {
          option.selected = true;
        }

        element.appendChild(option);
      }
      if (element.value == "") {
        loadSharePointItemForOneField(
          document.getElementById("Form").getAttribute("SiteUrl"),
          document.getElementById("Form").getAttribute("ListName"),
          id,
        );
      }
    })
    .catch((err) => {
      console.error("Lookup load failed:", err);
    });
}

function setGridDataFromArray(array) {
  if (!array) return [];

  const data = [];

  for (let i = 0; i < array.length; i++) {
    data.push({
      id: array[i],
    });
  }
  return data;
}
function getGridSelectedValues(data) {
  return data.filter((d) => d.id).map((d) => parseInt(d.id));
}

async function createSPComboboxGrid(container, config) {
  if (!container) return;

  container.style.marginTop = "-4.5em";

  const {
    gridName = "SPComboGrid",
    displayName = "Grid",
    siteUrl,
    listName,
    displayColumn = "Title",
    data = [],
    filter,
  } = config;

  // Load options from SharePoint
  const options = await getSharePointListOptions(
    siteUrl,
    listName,
    displayColumn,
    filter
  );

  // Clear previous grid
  const old = container.querySelector(`#K_Grid_${gridName}`);
  if (old) old.remove();

  const wrapper = document.createElement("div");
  wrapper.id = `K_Grid_${gridName}`;
  wrapper.style.padding = "12px";

  const table = document.createElement("table");
  table.style.width = "100%";
  table.style.marginRight = "-1em";

  // ===== HEADER =====
  const thead = document.createElement("thead");
  const trh = document.createElement("tr");

  const th1 = document.createElement("th");
  th1.textContent = displayColumn;
  th1.style.background = "transparent";
  th1.style.borderRadius = "10px";
  th1.style.color = "transparent";
  th1.style.textAlign = "center";
  th1.style.padding = "8px";
  th1.style.width = "100%";

  trh.appendChild(th1);

  const thAdd = document.createElement("th");
  thAdd.style.width = "50px";
  thAdd.style.height = "42px";
  thAdd.style.padding = "0px";

  const btnAdd = document.createElement("button");
  btnAdd.textContent = "+";
  btnAdd.style.fontSize = "20px";
  btnAdd.style.border = "none";
  btnAdd.style.background = "transparent";
  btnAdd.style.cursor = "pointer";
  btnAdd.style.minWidth = "0px";
  btnAdd.style.margin = "0px";
  btnAdd.style.width = "50px";
  btnAdd.style.padding = "0px";

  btnAdd.onclick = (event) => {
    event.preventDefault();
    data.push({ id: "", text: "" });
    createSPComboboxGrid(container, config);
  };

  thAdd.appendChild(btnAdd);
  trh.appendChild(thAdd);
  thead.appendChild(trh);
  table.appendChild(thead);

  // ===== BODY =====
  const tbody = document.createElement("tbody");

  data.forEach((row, index) => {
    const tr = document.createElement("tr");

    // Select
    const tdSel = document.createElement("td");
    const select = document.createElement("select");
    select.classList.add("kform-lookup-select", "kform-combobox-select");
    select.style.width = "100%";
    select.style.padding = "8px";

    const empty = document.createElement("option");
    empty.value = "";
    empty.textContent = "انتخاب کنید";
    select.appendChild(empty);

    options.forEach((opt) => {
      const o = document.createElement("option");
      o.value = opt.id;
      o.textContent = opt.text;
      select.appendChild(o);
    });

    select.value = row.id || "";

    select.onchange = () => {
      const selected = options.find((o) => o.id == select.value);
      row.id = selected ? selected.id : "";
      row.text = selected ? selected.text : "";
    };

    tdSel.appendChild(select);
    tr.appendChild(tdSel);

    // Delete
    const tdDel = document.createElement("td");

    tdDel.style.width = "50px";
    tdDel.style.height = "50px";
    tdDel.style.padding = "0px";

    const btnDel = document.createElement("button");
    btnDel.innerHTML = "✕";
    btnDel.style.border = "none";
    btnDel.style.backgroundColor = "transparent";
    btnDel.style.backgroundSize = "20px 20px";
    btnDel.style.backgroundRepeat = "no-repeat";
    btnDel.style.backgroundPosition = "67% 50%";
    btnDel.style.cursor = "pointer";
    btnDel.style.margin = "0px";
    btnDel.style.width = "50px";
    btnDel.style.height = "50px";
    btnDel.style.padding = "0px";

    btnDel.onclick = (event) => {
      event.preventDefault();
      data.splice(index, 1);
      createSPComboboxGrid(container, config);
    };

    tdDel.appendChild(btnDel);
    tr.appendChild(tdDel);

    tbody.appendChild(tr);
  });

  table.appendChild(tbody);
  wrapper.appendChild(table);
  container.appendChild(wrapper);
}

async function createSPUserpickerGrid(container, config) {
  if (!container) return;

  container.style.marginTop = "-4.5em";

  const {
    gridName = "SPComboGrid",
    displayName = "Grid",
    siteUrl,
    listName,
    displayColumn = "Title",
    data = [],
    filter,
  } = config;

  // Clear previous grid
  const old = container.querySelector(`#K_Grid_${gridName}`);
  if (old) old.remove();

  const wrappergrid = document.createElement("div");
  wrappergrid.id = `K_Grid_${gridName}`;
  wrappergrid.style.padding = "12px";

  const table = document.createElement("table");
  table.style.width = "100%";
  table.style.marginRight = "-1em";

  // ===== HEADER =====
  const thead = document.createElement("thead");
  const trh = document.createElement("tr");

  const th1 = document.createElement("th");
  th1.textContent = displayColumn;
  th1.style.background = "transparent";
  th1.style.borderRadius = "10px";
  th1.style.color = "transparent";
  th1.style.textAlign = "center";
  th1.style.padding = "8px";
  th1.style.width = "100%";

  trh.appendChild(th1);

  const thAdd = document.createElement("th");
  thAdd.style.width = "50px";
  thAdd.style.height = "42px";
  thAdd.style.padding = "0px";

  const btnAdd = document.createElement("button");
  btnAdd.textContent = "+";
  btnAdd.style.fontSize = "20px";
  btnAdd.style.border = "none";
  btnAdd.style.background = "transparent";
  btnAdd.style.cursor = "pointer";
  btnAdd.style.minWidth = "0px";
  btnAdd.style.margin = "0px";
  btnAdd.style.width = "50px";
  btnAdd.style.padding = "0px";

  btnAdd.onclick = (event) => {
    event.preventDefault();
    data.push({ id: "", text: "" });
    createSPUserpickerGrid(container, config);
  };

  thAdd.appendChild(btnAdd);
  trh.appendChild(thAdd);
  thead.appendChild(trh);
  table.appendChild(thead);

  // ===== BODY =====
  const tbody = document.createElement("tbody");

  data.forEach((row, index) => {
    const tr = document.createElement("tr");
    const tdSel = document.createElement("td");
    const wrapper = document.createElement("div");
        wrapper.classList.add("kform-userpicker-wrapper", "kform-custom-input");

        element = document.createElement("input");
        element.type = "text";
        element.classList.add("kform-custom-input");
        element.placeholder = "نام کاربر را وارد کنید";
        element.autocomplete = "off";
        element.setAttribute("input-type", "userpicker");
        element.addEventListener("keydown", (e)=>{
          if(e.key === "Backspace") {
            
            element.value = "";
          }
        })

        const list = document.createElement("div");
        list.classList.add("kform-userpicker-list");
        list.style.display = "none";

        let timeout = null;

        element.addEventListener("input", () => {
          const query = element.value.trim();

          if (query.length < 3) {
            list.style.display = "none";
            list.innerHTML = "";
            return;
          }

          clearTimeout(timeout);

          timeout = setTimeout(() => {
            fetch(
              `${siteUrl}/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser`,
              {
                method: "POST",
                headers: {
                  Accept: "application/json;odata=verbose",
                  "Content-Type": "application/json;odata=verbose",
                  "X-RequestDigest":
                    document.getElementById("__REQUESTDIGEST").value,
                },
                body: JSON.stringify({
                  queryParams: {
                    AllowEmailAddresses: true,
                    AllowMultipleEntities: false,
                    AllUrlZones: false,
                    MaximumEntitySuggestions: 10,
                    PrincipalSource: 15,
                    PrincipalType: 1,
                    QueryString: query,
                  },
                }),
              }
            )
              .then((res) => res.json())
              .then((data) => {
                const results = JSON.parse(data.d.ClientPeoplePickerSearchUser);

                list.innerHTML = "";
                list.style.display = "block";

                results.forEach((user) => {
                  const item = document.createElement("div");
                  item.className = "kform-userpicker-item";
                  item.textContent = user.DisplayText;

                  item.onclick = () => {
                    element.value = user.DisplayText;
                    element.dataset.login = user.Key;
                    list.style.display = "none";
                  };

                  list.appendChild(item);
                });
              })
              .catch((err) => {
                console.error("User picker failed:", err);
              });
          }, 300);
        });

        if(row.id != "") {
          debugger;
          fetch(
              `${siteUrl}/_api/web/getuserbyid(${row.id})`,
              {
                method: "POST",
                headers: {
                  Accept: "application/json;odata=verbose",
                  "Content-Type": "application/json;odata=verbose",
                  "X-RequestDigest":
                    document.getElementById("__REQUESTDIGEST").value,
                }
              }
            )
              .then((res) => res.json())
              .then((data) => {
                debugger;
                var user = data.d;
                element.value = user.Title;
                element.dataset.login = user.LoginName;
                list.style.display = "none";
              })
              .catch((err) => {
                console.error("User picker failed:", err);
              });
        }
        document.addEventListener("click", (e) => {
          if (!wrapper.contains(e.target)) {
            list.style.display = "none";
          }
        });

        wrapper.appendChild(element);
        wrapper.appendChild(list);

    tdSel.appendChild(wrapper);
    tr.appendChild(tdSel);

    // Delete
    const tdDel = document.createElement("td");

    tdDel.style.width = "50px";
    tdDel.style.height = "50px";
    tdDel.style.padding = "0px";

    const btnDel = document.createElement("button");
    btnDel.innerHTML = "✕";
    btnDel.style.border = "none";
    btnDel.style.backgroundColor = "transparent";
    btnDel.style.backgroundSize = "20px 20px";
    btnDel.style.backgroundRepeat = "no-repeat";
    btnDel.style.backgroundPosition = "67% 50%";
    btnDel.style.cursor = "pointer";
    btnDel.style.margin = "0px";
    btnDel.style.width = "50px";
    btnDel.style.height = "50px";
    btnDel.style.padding = "0px";

    btnDel.onclick = (event) => {
      event.preventDefault();
      data.splice(index, 1);
      createSPUserpickerGrid(container, config);
    };

    tdDel.appendChild(btnDel);
    tr.appendChild(tdDel);

    tbody.appendChild(tr);
  });

  table.appendChild(tbody);
  wrappergrid.appendChild(table);
  container.appendChild(wrappergrid);
}

async function getSharePointListOptions(
  siteUrl,
  listName,
  displayColumn,
  filter
) {
  var url =
    `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items` +
    `?$select=Id,${displayColumn}&$top=5000`;

  if (filter != undefined) {
    url += "&$filter=" + filter;
  }
  const res = await fetch(url, {
    headers: { Accept: "application/json;odata=verbose" },
  });

  const data = await res.json();

  return data.d.results.map((item) => ({
    id: item.Id,
    text: item[displayColumn],
  }));
}
