function getLabel(field, lang = window.lang || "en") {
  if (!field || !field.label) return "Unknown Field";
  if (typeof field.label === "string") return field.label;
  return (
    field.label[lang] ||
    field.label.en ||
    Object.values(field.label)[0] ||
    "Unknown Label"
  );
}
function encodeFieldKey(key) {
  return encodeURIComponent(key)
    .replace(/%20/g, "-")
    .replace(/[^a-zA-Z0-9-_]/g, "");
}
function scrollToField(key, divId = "genform") {
  let encodedKey = encodeFieldKey(key);
  let element = document.getElementById(`${divId}-field-${encodedKey}`);

  if (!element)
    element = document.getElementById(`${divId}-section-${encodedKey}`);
  if (!element)
    element = document.getElementById(`${divId}-segment-${encodedKey}`);

  if (element) {
    element.scrollIntoView({ behavior: "smooth", block: "center" });
    element.style.backgroundColor = "#e0f7fa";
    setTimeout(() => {
      element.style.backgroundColor = "";
    }, 2000);
  } else {
    console.warn(`Element with key ${key} not found for scrolling`);
  }
}
function calculateMaxScore(field) {
  if (field.weights) {
    return field.data_type === "checkbox"
      ? field.weights.reduce((sum, w) => sum + w, 0)
      : Math.max(...field.weights);
  }
  return field.weight || 1;
}
function calculateCurrentScore(field) {
  const inputType = field.data_type || field.type;
  const val = field.value;
  const hasAnswer =
    (Array.isArray(val) && val.length > 0) ||
    (typeof val === "string" && val.trim() !== "") ||
    (typeof val === "number" && val !== 0 && !isNaN(val)) ||
    (inputType === "radio" && val !== null);

  if (["radio", "select"].includes(inputType) && field.weights) {
    if (inputType === "select" && val === "") {
      return 0;
    }
    const idx = typeof val === "number" ? val : getOptions(field).indexOf(val);
    return idx >= 0 ? field.weights[idx] || 0 : 0;
  } else if (inputType === "checkbox" && Array.isArray(val)) {
    return val.reduce((sum, v) => {
      const idx = isNaN(v) ? getOptions(field).indexOf(v) : parseInt(v);
      return sum + (idx >= 0 ? field.weights?.[idx] || 0 : 0);
    }, 0);
  } else {
    return hasAnswer ? field.weight || 1 : 0;
  }
}
function getOptions(field, lang = "en") {
  if (!field.options) return [];
  const opts =
    field.options[lang] ||
    field.options.en ||
    Object.values(field.options)[0] ||
    [];
  return Array.isArray(opts) ? opts : [];
}

function countFiles(field) {
  if (!field || !field.value) return 0;
  return field.value.split(",").filter((f) => f.trim()).length;
}

function uploadPanel(key, inputId, textInput, existingFiles) {
  const fileName = prompt(
    getLabel({ label: { en: "Enter file name", th: "ป้อนชื่อไฟล์" } }),
  );
  if (fileName) {
    existingFiles.push(fileName);
    textInput.value = existingFiles.join(", ");
    return existingFiles;
  }
  return existingFiles;
}

function toggleUploadPanelX(divId, key) {
  const inputId = `${divId}-${key}`;
  const textInput = document.getElementById(inputId);
  const existingFiles = textInput.value
    ? textInput.value.split(",").map((f) => f.trim())
    : [];
  return uploadPanel(key, inputId, textInput, existingFiles);
}
