function countFiles(field) {
  if (!field || !field.value || typeof field.value !== "string") {
    console.log(`countFiles: No valid value for field, returning 0`);
    return 0;
  }
  const files = field.value.split(",").filter((f) => f.trim()).length;
  console.log(`countFiles: field.value="${field.value}", count=${files}`);
  return files;
}

function isFieldAnswered(field) {
  const inputType = field.data_type || field.type;
  if (inputType === "checkbox") {
    return Array.isArray(field.value) && field.value.length > 0;
  } else if (inputType === "radio" || inputType === "select") {
    return field.value !== null && field.value !== "";
  } else if (inputType === "attachment") {
    return field.value && countFiles(field) > 0;
  } else {
    return field.value !== null && field.value !== "";
  }
}

function encodeFieldKey(key) {
  return key; // Assume simple pass-through; replace with actual implementation if needed
}

function getLabel(field, lang) {
  return field.label?.[lang] || field.label?.en || key;
}

function calculateCurrentScore(field) {
  if (!isFieldAnswered(field)) return 0;
  if (field.weights && field.value !== null) {
    if (Array.isArray(field.value)) {
      return field.value.reduce(
        (sum, val) => sum + (field.weights[val] || 0),
        0,
      );
    }
    return field.weights[field.value] || 0;
  }
  return field.score || 1;
}

function calculateMaxScore(field) {
  if (field.weights) {
    return Math.max(...field.weights) || 1;
  }
  return field.score || 1;
}

function getOptions(field, lang) {
  return field.options?.[lang] || field.options?.en || [];
}
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`);
  }
}
