function scrollToField(key, divId = "genform") {
  // Try field first
  let encodedKey = encodeFieldKey(key);
  let element = document.getElementById(`${divId}-field-${encodedKey}`);

  // If not found, try section
  if (!element)
    element = document.getElementById(`${divId}-section-${encodedKey}`);

  // If still not found, try segment
  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 calculateAchievedScore(field) {
  if (field.weights) {
    if (field.data_type === "checkbox" && Array.isArray(field.value)) {
      return field.value.reduce(
        (sum, idx) => sum + (field.weights[idx] || 0),
        0,
      );
    } else if (["radio", "select"].includes(field.data_type)) {
      const idx =
        typeof field.value === "number"
          ? field.value
          : field.options.en.indexOf(field.value);
      return idx >= 0 ? field.weights[idx] || 0 : 0;
    }
  }
  return field.value ? field.score || field.weight || 1 : 0;
}

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 updateDebugInfo(fieldKey, field) {
  const debugDiv = document.getElementById(
    `debugscorediv-${encodeFieldKey(fieldKey)}`,
  );
  if (!debugDiv) return;

  const safeVal = Array.isArray(field.value)
    ? "[" + field.value.join(", ") + "]"
    : (field.value ?? "");

  const achievedScore = calculateAchievedScore(field);
  const maxScore = calculateMaxScore(field);

  let debugText = `[Score: ${field.score || 0}, `;
  debugText += `Weight: ${field.weight || "-"}, `;
  debugText += `Achieved: ${achievedScore}, `;
  debugText += `Max: ${maxScore}, `;
  debugText += `Required: ${field.required ? "yes" : "no"}, `;
  debugText += `Value: ${safeVal}]`;

  debugDiv.textContent = debugText;
}
function updateSummary(panel) {
  const summary = {
    segments: {},
    totals: {
      allFields: 0,
      requiredFields: 0,
      answeredFields: 0,
      answeredRequiredFields: 0,
      totalScore: 0,
      totalScoreWeighted: 0,
      maxPossibleScore: 0,
      maxPossibleScoreWeighted: 0,
      totalFiles: 0,
    },
  };

  // Group data by segment and section
  Object.entries(panel).forEach(([key, item]) => {
    if (item.type === "field") {
      const segment = item.segment?.[0];
      const section = item.section;

      if (!segment || !section) return;

      if (!summary.segments[segment]) {
        summary.segments[segment] = {
          label: panel.grouping.label.en[panel.grouping.name.indexOf(segment)],
          sections: {},
          totals: {
            allFields: 0,
            requiredFields: 0,
            answeredFields: 0,
            answeredRequiredFields: 0,
            totalScore: 0,
            totalScoreWeighted: 0,
            maxPossibleScore: 0,
            maxPossibleScoreWeighted: 0,
            totalFiles: 0,
          },
        };
      }

      if (!summary.segments[segment].sections[section]) {
        summary.segments[segment].sections[section] = {
          label: panel[section]?.label?.en || section,
          totals: {
            allFields: 0,
            requiredFields: 0,
            answeredFields: 0,
            answeredRequiredFields: 0,
            totalScore: 0,
            totalScoreWeighted: 0,
            maxPossibleScore: 0,
            maxPossibleScoreWeighted: 0,
            totalFiles: 0,
          },
        };
      }

      const currentScore = calculateCurrentScore(item);
      const maxScore = calculateMaxScore(item);
      const isAnswered = currentScore > 0;
      const isFile = item.data_type === "attachment";
      const fileCount = isFile ? countFiles(item) : 0;

      const baseScore = isAnswered ? item.score || 1 : 0;
      const baseMaxScore = item.score || 1;

      summary.segments[segment].sections[section].totals.allFields++;
      if (item.required)
        summary.segments[segment].sections[section].totals.requiredFields++;
      if (isAnswered)
        summary.segments[segment].sections[section].totals.answeredFields++;
      if (item.required && isAnswered)
        summary.segments[segment].sections[section].totals
          .answeredRequiredFields++;
      summary.segments[segment].sections[section].totals.totalScore +=
        baseScore;
      summary.segments[segment].sections[section].totals.totalScoreWeighted +=
        currentScore;
      summary.segments[segment].sections[section].totals.maxPossibleScore +=
        baseMaxScore;
      summary.segments[segment].sections[
        section
      ].totals.maxPossibleScoreWeighted += maxScore;
      summary.segments[segment].sections[section].totals.totalFiles +=
        fileCount;

      summary.segments[segment].totals.allFields++;
      if (item.required) summary.segments[segment].totals.requiredFields++;
      if (isAnswered) summary.segments[segment].totals.answeredFields++;
      if (item.required && isAnswered)
        summary.segments[segment].totals.answeredRequiredFields++;
      summary.segments[segment].totals.totalScore += baseScore;
      summary.segments[segment].totals.totalScoreWeighted += currentScore;
      summary.segments[segment].totals.maxPossibleScore += baseMaxScore;
      summary.segments[segment].totals.maxPossibleScoreWeighted += maxScore;
      summary.segments[segment].totals.totalFiles += fileCount;

      summary.totals.allFields++;
      if (item.required) summary.totals.requiredFields++;
      if (isAnswered) summary.totals.answeredFields++;
      if (item.required && isAnswered) summary.totals.answeredRequiredFields++;
      summary.totals.totalScore += baseScore;
      summary.totals.totalScoreWeighted += currentScore;
      summary.totals.maxPossibleScore += baseMaxScore;
      summary.totals.maxPossibleScoreWeighted += maxScore;
      summary.totals.totalFiles += fileCount;
    }
  });
  let element = document.getElementById(`summary`);
  if (!element) return;
  // If not found, try section

  document.getElementById("summary").innerHTML =
    `<pre>${JSON.stringify(summary, null, 2)}</pre>`;

  // Use the modified jumper helper
  updateJumperHelperWithUnanswered(summary);
}
function updateJumperHelperWithUnanswered(summary) {
  const lang = window.lang || "en";
  const unansweredFields = getUnansweredRequiredFields();
  let html =
    "<h3>Quick Navigation</h3><div style='display: flex; flex-wrap: wrap; gap: 10px;'>";

  Object.entries(summary.segments).forEach(([segmentKey, segment]) => {
    const segmentEncoded = encodeFieldKey(segmentKey);
    const segmentTotals = segment.totals;

    html += `<div style='border: 1px solid #ccc; padding: 10px; border-radius: 5px; min-width: 200px;'>
            <h4 style='margin: 0 0 5px 0;'>
                <a href="javascript:scrollToField('${segmentKey}')" style='text-decoration: none; color: #333;'>
                    ${segment.label}
                </a>
            </h4>
            <div>Fields: ${segmentTotals.answeredFields}/${segmentTotals.allFields}</div>
            <div>Required: ${segmentTotals.answeredRequiredFields}/${segmentTotals.requiredFields}</div>
            <div>Score: ${segmentTotals.totalScoreWeighted}/${segmentTotals.maxPossibleScoreWeighted}</div>
            <div style='margin-top: 5px; font-size: 0.9em;'>`;

    Object.entries(segment.sections).forEach(([sectionKey, section]) => {
      const sectionEncoded = encodeFieldKey(sectionKey);
      const sectionTotals = section.totals;

      html += `<div style='margin-bottom: 3px;'>
                <a href="javascript:scrollToField('${sectionKey}')" style='text-decoration: none; color: #666;'>
                    ${section.label} (${sectionTotals.answeredFields}/${sectionTotals.allFields})
                </a>
            </div>`;
    });

    // Add unanswered required fields for this segment with ellipsis
    const segmentUnanswered = unansweredFields.filter(
      (field) => field.segment === segmentKey,
    );
    if (segmentUnanswered.length > 0) {
      html += `<div style='margin-top: 10px; color: red;'>
                <strong>Unanswered Required Fields:</strong><ul style='margin: 5px 0; padding-left: 20px;'>`;
      segmentUnanswered.forEach((field) => {
        const sectionLabel = panel[field.section]?.label[lang] || field.section;
        html += `<li style='max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>
                    <a href="javascript:scrollToField('${field.key}')"
                       style='text-decoration: none; color: red;'
                       title='${field.label} (Section: ${sectionLabel})'>
                        ${field.label} (Section: ${sectionLabel})
                    </a>
                </li>`;
      });
      html += `</ul></div>`;
    }

    html += `</div></div>`;
  });

  html += `</div>`;
  document.getElementById("jumperhelper").innerHTML = html;
}
function getUnansweredRequiredFields() {
  const lang = window.lang || "en";
  const unansweredFields = [];

  // Iterate through panel to find fields
  Object.entries(panel).forEach(([key, item]) => {
    if (item.type === "field" && item.required) {
      const isAnswered = calculateCurrentScore(item) > 0;
      if (!isAnswered) {
        unansweredFields.push({
          key,
          label: getLabel(item, lang),
          segment: item.segment[0],
          section: item.section,
        });
      }
    }
  });

  return unansweredFields;
}
function updateJumperHelper(summary) {
  let html =
    "<h3>Quick Navigation</h3><div style='display: flex; flex-wrap: wrap; gap: 10px;'>";

  Object.entries(summary.segments).forEach(([segmentKey, segment]) => {
    const segmentEncoded = encodeFieldKey(segmentKey);
    const segmentTotals = segment.totals;

    html += `<div style='border: 1px solid #ccc; padding: 10px; border-radius: 5px; min-width: 200px;'>
            <h4 style='margin: 0 0 5px 0;'>
                <a href="javascript:scrollToField('${segmentKey}')" style='text-decoration: none; color: #333;'>
                    ${segment.label}
                </a>
            </h4>
            <div>Fields: ${segmentTotals.answeredFields}/${segmentTotals.allFields}</div>
            <div>Required: ${segmentTotals.answeredRequiredFields}/${segmentTotals.requiredFields}</div>
            <div>Score: ${segmentTotals.totalScoreWeighted}/${segmentTotals.maxPossibleScoreWeighted}</div>
            <div style='margin-top: 5px; font-size: 0.9em;'>`;

    Object.entries(segment.sections).forEach(([sectionKey, section]) => {
      const sectionEncoded = encodeFieldKey(sectionKey);
      const sectionTotals = section.totals;

      html += `<div style='margin-bottom: 3px;'>
                <a href="javascript:scrollToField('${sectionKey}')" style='text-decoration: none; color: #666;'>
                    ${section.label} (${sectionTotals.answeredFields}/${sectionTotals.allFields})
                </a>
            </div>`;
    });

    html += `</div></div>`;
  });

  html += `</div>`;
  document.getElementById("jumperhelper").innerHTML = html;
}

function renderGF(data, divId) {
  const container = document.getElementById(divId);
  container.innerHTML = "";
  const lang = window.lang || "en";
  const grouping = data.grouping;

  if (!grouping || !grouping.name) return;

  const segments = grouping.name.filter(
    (_, i) => grouping.type[i] === "segment",
  );

  segments.forEach((segmentKey, segmentIndex) => {
    const segmentLabel = grouping.label[lang][segmentIndex];
    const segmentEncodedKey = encodeFieldKey(segmentKey);

    const segmentDiv = document.createElement("div");
    segmentDiv.className = "segment";
    segmentDiv.id = `${divId}-segment-${segmentEncodedKey}`;
    segmentDiv.style.border = "2px solid #888";
    segmentDiv.style.padding = "12px";
    segmentDiv.style.marginBottom = "20px";
    segmentDiv.style.borderRadius = "10px";
    segmentDiv.style.background = "#f3f3f3";

    const segmentHeader = document.createElement("h2");
    segmentHeader.textContent = segmentLabel;
    segmentDiv.appendChild(segmentHeader);

    const sections = grouping.name.filter(
      (k, i) =>
        grouping.type[i] === "section" &&
        Object.values(data).some(
          (field) =>
            field.type === "field" &&
            field.segment?.includes(segmentKey) &&
            field.section === k,
        ),
    );

    sections.forEach((sectionKey) => {
      const section = data[sectionKey];
      const sectionLabel = getLabel(section, lang);
      const sectionEncodedKey = encodeFieldKey(sectionKey);

      const sectionDiv = document.createElement("div");
      sectionDiv.className = "section";
      sectionDiv.id = `${divId}-section-${sectionEncodedKey}`;
      sectionDiv.style.border = "1px solid #ccc";
      sectionDiv.style.padding = "10px";
      sectionDiv.style.margin = "10px 0";
      sectionDiv.style.borderRadius = "8px";
      sectionDiv.style.background = "#fff";

      const sectionHeader = document.createElement("h3");
      sectionHeader.textContent = sectionLabel;
      sectionDiv.appendChild(sectionHeader);

      Object.entries(data).forEach(([fieldKey, field]) => {
        if (!field || field.type !== "field") return;
        if (
          !field.segment?.includes(segmentKey) ||
          field.section !== sectionKey
        )
          return;

        const fieldEncodedKey = encodeFieldKey(fieldKey);
        // Create question container
        const questionContainer = document.createElement("div");
        questionContainer.className = "question-container";
        questionContainer.style.marginBottom = "15px";
        questionContainer.style.padding = "10px";
        questionContainer.style.border = "1px solid #eee";
        questionContainer.style.borderRadius = "5px";
        questionContainer.id = `${divId}-question-${fieldEncodedKey}`;
        const fieldDiv = document.createElement("div");
        fieldDiv.className = "field";
        fieldDiv.id = `${divId}-field-${fieldEncodedKey}`;
        fieldDiv.style.marginBottom = "10px";
        fieldDiv.style.padding = "8px";
        fieldDiv.style.border = "1px solid #ddd";
        fieldDiv.style.borderRadius = "4px";

        // Set red border if required field is empty
        if (field.required && calculateCurrentScore(field) === 0) {
          fieldDiv.style.borderColor = "red";
        }

        const fieldLabel = document.createElement("label");
        fieldLabel.innerHTML =
          getLabel(field, lang) +
          (field.required ? " <span style='color:red'>*</span>" : "");
        fieldLabel.style.display = "block";
        fieldLabel.style.fontWeight = "bold";
        fieldLabel.style.marginBottom = "3px";
        fieldDiv.appendChild(fieldLabel);

        // Create answer container for all field types
        const answerContainer = document.createElement("div");
        answerContainer.className = "answer-container";
        answerContainer.style.marginLeft = "15px";
        answerContainer.style.marginTop = "5px";

        let input;
        const inputType = field.data_type;

        if (inputType === "textarea") {
          input = document.createElement("textarea");
          input.id = `${divId}-${fieldKey}`;
          input.value = field.value || "";
          input.style.width = "100%";
          input.style.minHeight = "60px";
          answerContainer.appendChild(input);
          bindInputEvents(input, fieldKey, field, inputType);
        } else if (inputType === "radio") {
          input = document.createElement("div");
          input.style.display = "flex";
          input.style.flexDirection = "column";
          input.style.gap = "8px";

          getOptions(field, lang).forEach((opt, idx) => {
            const optionContainer = document.createElement("div");
            optionContainer.style.display = "flex";
            optionContainer.style.alignItems = "flex-start";

            const radioInput = document.createElement("input");
            radioInput.type = "radio";
            radioInput.name = `${divId}-${fieldKey}`;
            radioInput.value = idx;
            radioInput.id = `${divId}-${fieldKey}-${idx}`;
            if (field.value === idx) radioInput.checked = true;

            const radioLabel = document.createElement("label");
            radioLabel.htmlFor = `${divId}-${fieldKey}-${idx}`;
            radioLabel.style.marginLeft = "8px";
            radioLabel.style.wordBreak = "break-word";
            radioLabel.style.flex = "1";

            const weight = field.weights?.[idx] || 1;
            radioLabel.textContent = `${opt} (weight:${weight})`;

            optionContainer.appendChild(radioInput);
            optionContainer.appendChild(radioLabel);
            input.appendChild(optionContainer);
          });
          answerContainer.appendChild(input);
          bindInputEvents(input, fieldKey, field, inputType);
        } else if (inputType === "checkbox") {
          input = document.createElement("div");
          input.style.display = "flex";
          input.style.flexDirection = "column";
          input.style.gap = "8px";

          getOptions(field, lang).forEach((opt, idx) => {
            const optionContainer = document.createElement("div");
            optionContainer.style.display = "flex";
            optionContainer.style.alignItems = "flex-start";

            const checkInput = document.createElement("input");
            checkInput.type = "checkbox";
            checkInput.name = `${divId}-${fieldKey}[]`;
            checkInput.value = idx;
            checkInput.id = `${divId}-${fieldKey}-${idx}`;
            checkInput.checked =
              Array.isArray(field.value) && field.value.includes(idx);

            const checkLabel = document.createElement("label");
            checkLabel.htmlFor = `${divId}-${fieldKey}-${idx}`;
            checkLabel.style.marginLeft = "8px";
            checkLabel.style.wordBreak = "break-word";
            checkLabel.style.flex = "1";

            const weight = field.weights?.[idx] || 1;
            checkLabel.textContent = `${opt} (weight:${weight})`;

            optionContainer.appendChild(checkInput);
            optionContainer.appendChild(checkLabel);
            input.appendChild(optionContainer);
          });
          answerContainer.appendChild(input);
          bindInputEvents(input, fieldKey, field, inputType);
        } else if (inputType === "select") {
          input = document.createElement("select");
          input.id = `${divId}-${fieldKey}`;
          getOptions(field, lang).forEach((opt, idx) => {
            const option = document.createElement("option");
            const value = idx === 0 ? "" : opt;
            const weight = field.weights?.[idx] || 1;
            option.value = value;
            option.textContent = `${opt} (weight:${weight})`;
            option.selected = field.value === value;
            input.appendChild(option);
          });
          answerContainer.appendChild(input);
          bindInputEvents(input, fieldKey, field, inputType);
        } else if (inputType === "attachment") {
          input = document.createElement("div");

          const textInput = document.createElement("input");
          textInput.type = "text";
          textInput.id = `${divId}-${fieldKey}`;
          textInput.value = field.value || "";
          textInput.placeholder = getLabel(
            {
              label: {
                en: "Enter file names (comma-separated)",
                th: "ป้อนชื่อไฟล์ (คั่นด้วยเครื่องหมายจุลภาค)",
              },
            },
            lang,
          );
          textInput.style.width = "260px";
          answerContainer.appendChild(textInput);
          bindInputEvents(textInput, fieldKey, field, inputType);

          const fileCount = document.createElement("div");
          fileCount.id = `${divId}-filecount-${fieldKey}`;
          fileCount.style.marginTop = "5px";
          fileCount.textContent = `Files: ${countFiles(field)}`;
          answerContainer.appendChild(fileCount);

          const buttonDiv = document.createElement("div");
          buttonDiv.style.marginTop = "5px";

          const addFileBtn = document.createElement("button");
          addFileBtn.textContent = getLabel(
            { label: { en: "Add file", th: "เพิ่มไฟล์" } },
            lang,
          );
          addFileBtn.style.marginLeft = "10px";
          addFileBtn.style.padding = "4px 8px";
          addFileBtn.style.cursor = "pointer";
          addFileBtn.onclick = () => {
            toggleUploadPanel();
            updateFileListFromInput(`${divId}-${fieldKey}`);
            field.value = textInput.value;
            fileCount.textContent = `Files: ${countFiles(field)}`;
            updateSummary();
          };
          buttonDiv.appendChild(addFileBtn);

          const countFilesBtn = document.createElement("button");
          countFilesBtn.textContent = getLabel(
            { label: { en: "Count Files", th: "นับไฟล์" } },
            lang,
          );
          countFilesBtn.style.marginLeft = "10px";
          countFilesBtn.style.padding = "4px 8px";
          countFilesBtn.style.cursor = "pointer";
          countFilesBtn.onclick = () => {
            field.value = textInput.value;
            fileCount.textContent = `Files: ${countFiles(field)}`;
            updateSummary();
          };
          buttonDiv.appendChild(countFilesBtn);

          answerContainer.appendChild(buttonDiv);
        } else {
          input = document.createElement("input");
          input.id = `${divId}-${fieldKey}`;
          input.type = inputType === "number" ? "number" : "text";
          input.value = field.value || (inputType === "number" ? 0 : "");
          input.style.width = "260px";
          answerContainer.appendChild(input);
          bindInputEvents(input, fieldKey, field, inputType);
        }

        fieldDiv.appendChild(answerContainer);

        // Reset button
        const resetBtn = document.createElement("button");
        resetBtn.textContent = "Reset";
        resetBtn.style.marginLeft = "10px";
        resetBtn.style.padding = "2px 6px";
        resetBtn.style.cursor = "pointer";
        resetBtn.onclick = () => {
          if (inputType === "radio" || inputType === "checkbox") {
            const inputs = input.querySelectorAll("input");
            inputs.forEach((el) => (el.checked = false));
            field.value = inputType === "checkbox" ? [] : null;
          } else if (inputType === "select") {
            input.selectedIndex = 0;
            field.value = "";
          } else if (inputType === "attachment") {
            const el = answerContainer.querySelector("input[type='text']");
            if (el) el.value = "";
            field.value = "";
          } else {
            input.value = field.data_type === "number" ? 0 : "";
            field.value = input.value;
          }
          updateFieldUI(fieldDiv, field);
          updateDebugInfo(fieldKey, field);
          updateSummary(data);
        };
        fieldDiv.appendChild(resetBtn);

        // Debug info
        if (window.debug) {
          const debugDiv = document.createElement("div");
          debugDiv.id = `debugscorediv-${encodeFieldKey(fieldKey)}`;
          debugDiv.style.fontSize = "12px";
          debugDiv.style.color = "#666";
          debugDiv.style.marginTop = "4px";

          const safeVal = Array.isArray(field.value)
            ? "[" + field.value.join(", ") + "]"
            : (field.value ?? "");

          const currentScore = calculateCurrentScore(field);
          const maxScore = calculateMaxScore(field);

          let debugText = `[score:${currentScore}, weight:${field.weight || "-"}, `;
          debugText += `maxscore:${maxScore}, required:${field.required ? "yes" : "no"}, value:${safeVal}]`;

          debugDiv.textContent = debugText;
          fieldDiv.appendChild(debugDiv);
        }
        // Add field to question container
        questionContainer.appendChild(fieldDiv);
        sectionDiv.appendChild(fieldDiv);
      });

      segmentDiv.appendChild(sectionDiv);
    });

    container.appendChild(segmentDiv);
  });

  // Update summary after rendering
  updateSummary(data);
}

function updateFieldUI(fieldDiv, field) {
  if (field.required && calculateCurrentScore(field) === 0) {
    fieldDiv.style.borderColor = "red";
  } else {
    fieldDiv.style.borderColor = "#ddd";
  }
}

function bindInputEvents(input, fieldKey, field, fieldType) {
  const updateValue = () => {
    if (fieldType === "checkbox") {
      const checkboxes = input.querySelectorAll(`input[type="checkbox"]`);
      field.value = [];
      checkboxes.forEach((cb) => {
        if (cb.checked) {
          const idx = parseInt(cb.value);
          field.value.push(idx);
        }
      });
    } else if (fieldType === "radio") {
      const selected = input.querySelector(`input[type="radio"]:checked`);
      field.value = selected ? parseInt(selected.value) : null;
    } else if (fieldType === "select") {
      const el = document.getElementById(input.id || `${divId}-${fieldKey}`);
      if (el) {
        field.value = el.value;
      }
    } else {
      const el = document.getElementById(input.id || `${divId}-${fieldKey}`);
      if (!el) return;
      if (field.data_type === "number") {
        field.value = parseFloat(el.value) || 0;
      } else {
        field.value = el.value;
      }
    }

    // Update field UI
    const fieldDiv = input.closest(".field");
    if (fieldDiv) {
      updateFieldUI(fieldDiv, field);
    }

    // Update debug info
    updateDebugInfo(fieldKey, field);

    // Update summary
    updateSummary();
  };

  if (fieldType === "radio" || fieldType === "checkbox") {
    const inputs = input.querySelectorAll("input");
    inputs.forEach((i) => {
      i.addEventListener("change", updateValue);
    });
  } else {
    input.addEventListener?.("input", updateValue);
    input.addEventListener?.("change", updateValue);
    input.addEventListener?.("blur", updateValue);
  }
}

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 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 exportToJson() {
  const dataStr = JSON.stringify(panel, null, 2);
  const blob = new Blob([dataStr], { type: "application/json" });
  const url = URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = url;
  a.download = "panel-data.json";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function savePanelToLocal() {
  try {
    localStorage.setItem("panel_data", JSON.stringify(panel));
    alert("Saved to localStorage.");
  } catch (e) {
    console.error("Failed to save:", e);
    alert("Save failed.");
  }
}

function loadPanelFromLocal() {
  try {
    const dataStr = localStorage.getItem("panel_data");
    if (!dataStr) return alert("No saved data found.");
    panel = JSON.parse(dataStr);
    renderGF(panel, "genform");
    alert("Loaded from localStorage.");
  } catch (e) {
    console.error("Failed to load:", e);
    alert("Load failed.");
  }
}

function dataToGF(div) {
  renderGF(panel, div);
}
function QSummary(panel) {
  const result = { segments: [] };
  const summary = {
    segments: {},
    totals: {
      allFields: 0,
      requiredFields: 0,
      answeredFields: 0,
      answeredRequiredFields: 0,
      totalScore: 0,
      totalScoreWeighted: 0,
      maxPossibleScore: 0,
      maxPossibleScoreWeighted: 0,
      totalFiles: 0,
    },
  };

  const segmentMap = {}; // for result.segments lookup

  // Group data by segment and section
  Object.entries(panel).forEach(([key, item]) => {
    if (item.type === "field") {
      const segment = item.segment?.[0];
      const section = item.section;
      if (!segment || !section) return;

      // ---- summary.segment and section (totals) ----
      if (!summary.segments[segment]) {
        summary.segments[segment] = {
          label: panel.grouping.label.en[panel.grouping.name.indexOf(segment)],
          sections: {},
          totals: {
            allFields: 0,
            requiredFields: 0,
            answeredFields: 0,
            answeredRequiredFields: 0,
            totalScore: 0,
            totalScoreWeighted: 0,
            maxPossibleScore: 0,
            maxPossibleScoreWeighted: 0,
            totalFiles: 0,
          },
        };
      }
      if (!summary.segments[segment].sections[section]) {
        summary.segments[segment].sections[section] = {
          label: panel[section]?.label?.en || section,
          totals: {
            allFields: 0,
            requiredFields: 0,
            answeredFields: 0,
            answeredRequiredFields: 0,
            totalScore: 0,
            totalScoreWeighted: 0,
            maxPossibleScore: 0,
            maxPossibleScoreWeighted: 0,
            totalFiles: 0,
          },
        };
      }

      const currentScore = calculateCurrentScore(item);
      const maxScore = calculateMaxScore(item);
      const isAnswered = currentScore > 0;
      const isFile = item.data_type === "attachment";
      const fileCount = isFile ? countFiles(item) : 0;

      const baseScore = isAnswered ? item.score || 1 : 0;
      const baseMaxScore = item.score || 1;

      const sectionTotals = summary.segments[segment].sections[section].totals;
      const segmentTotals = summary.segments[segment].totals;
      const globalTotals = summary.totals;

      sectionTotals.allFields++;
      if (item.required) sectionTotals.requiredFields++;
      if (isAnswered) sectionTotals.answeredFields++;
      if (item.required && isAnswered) sectionTotals.answeredRequiredFields++;
      sectionTotals.totalScore += baseScore;
      sectionTotals.totalScoreWeighted += currentScore;
      sectionTotals.maxPossibleScore += baseMaxScore;
      sectionTotals.maxPossibleScoreWeighted += maxScore;
      sectionTotals.totalFiles += fileCount;

      segmentTotals.allFields++;
      if (item.required) segmentTotals.requiredFields++;
      if (isAnswered) segmentTotals.answeredFields++;
      if (item.required && isAnswered) segmentTotals.answeredRequiredFields++;
      segmentTotals.totalScore += baseScore;
      segmentTotals.totalScoreWeighted += currentScore;
      segmentTotals.maxPossibleScore += baseMaxScore;
      segmentTotals.maxPossibleScoreWeighted += maxScore;
      segmentTotals.totalFiles += fileCount;

      globalTotals.allFields++;
      if (item.required) globalTotals.requiredFields++;
      if (isAnswered) globalTotals.answeredFields++;
      if (item.required && isAnswered) globalTotals.answeredRequiredFields++;
      globalTotals.totalScore += baseScore;
      globalTotals.totalScoreWeighted += currentScore;
      globalTotals.maxPossibleScore += baseMaxScore;
      globalTotals.maxPossibleScoreWeighted += maxScore;
      globalTotals.totalFiles += fileCount;

      // ---- result.segments → sections → fields ----
      if (!segmentMap[segment]) {
        const segmentLabel =
          panel.grouping.label?.en?.[panel.grouping.name.indexOf(segment)] ||
          segment;
        const segmentObj = {
          id: segment,
          label: segmentLabel,
          sections: [],
        };
        result.segments.push(segmentObj);
        segmentMap[segment] = segmentObj;
      }

      const segmentObj = segmentMap[segment];

      let sectionObj = segmentObj.sections.find((sec) => sec.id === section);
      if (!sectionObj) {
        sectionObj = {
          id: section,
          label: panel[section]?.label?.en || section,
          fields: [],
        };
        segmentObj.sections.push(sectionObj);
      }

      sectionObj.fields.push({ key, ...item });
    }
  });

  // Display full summaries
  //document.getElementById("summary").innerHTML = `<pre>${JSON.stringify(summary, null, 2)}</pre>`;
  console.log(`${JSON.stringify(result, null, 2)}`);
  return result;
  //updateJumperHelper(summary); // assumed helper
}
function renderQ(result, div, html) {
  const lang = window.lang || "en"; // fallback to 'en' if not defined

  if (!result || !Array.isArray(result.segments)) {
    console.warn("Invalid result format");
    return;
  }

  if (html) {
    const container =
      typeof div === "string" ? document.getElementById(div) : div;
    if (!container) {
      console.warn("Target div not found");
      return;
    }

    const htmlOutput = [];

    result.segments.forEach((segment) => {
      htmlOutput.push(
        `<div class="segment"><b>Segment:</b> ${segment.label} (${segment.id})</div>`,
      );

      segment.sections?.forEach((section) => {
        htmlOutput.push(
          `<div class="section" style="margin-left:1em;"><b>Section:</b> ${section.label} (${section.id})</div>`,
        );

        section.fields?.forEach((field) => {
          const label = field.label?.[lang] || field.label?.en || field.key;
          htmlOutput.push(
            `<div class="field" style="margin-left:2em;">• <b>${field.key}</b>: ${label}</div>`,
          );
        });
      });
    });

    container.innerHTML = htmlOutput.join("\n");
  } else {
    // Console log fallback
    result.segments.forEach((segment) => {
      console.log(`Segment: ${segment.label} (${segment.id})`);

      segment.sections?.forEach((section) => {
        console.log(`  Section: ${section.label} (${section.id})`);

        section.fields?.forEach((field) => {
          console.log(`    Key: ${field.key}`);
          console.log(`    Label:`, field.label);
        });
      });
    });
  }
}

function renderQ2(result, targetDiv, html = false) {
  const lang = window.lang || "en";

  if (!result || !Array.isArray(result.segments)) {
    console.warn("Invalid result format");
    return;
  }

  if (html) {
    const container =
      typeof targetDiv === "string"
        ? document.getElementById(targetDiv)
        : targetDiv;
    if (!container) {
      console.warn("Target container not found");
      return;
    }

    const htmlOutput = [];

    result.segments.forEach((segment) => {
      htmlOutput.push(`<div class="segment"><b>Segment:</b>
                <a href="javascript:scrollToField('${segment.id}')"
                   style="text-decoration: none; color: #333;">
                   ${segment.label}</a> (${segment.id})
            </div>`);

      segment.sections?.forEach((section) => {
        htmlOutput.push(`<div class="section" style="margin-left:1em;"><b>Section:</b>
                    <a href="javascript:scrollToField('${section.id}')"
                       style="text-decoration: none; color: #444;">
                       ${section.label}</a> (${section.id})
                </div>`);

        section.fields?.forEach((field) => {
          const labelText = getLabel(field, lang);
          htmlOutput.push(
            `<div class="field" style="margin-left:2em; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                                • <a href="javascript:scrollToField('${field.key}')"
                                     style="text-decoration: none; "
                                     title="${labelText}">
                                     ${labelText}
                        </div>`,
          );
        });
      });
    });

    container.innerHTML = htmlOutput.join("\n");
  } else {
    result.segments.forEach((segment) => {
      console.log(`Segment: ${segment.label} (${segment.id})`);
      segment.sections?.forEach((section) => {
        console.log(`  Section: ${section.label} (${section.id})`);
        section.fields?.forEach((field) => {
          console.log(`    Key: ${field.key}`);
          console.log(`    Label: ${getLabel(field, lang)}`);
        });
      });
    });
  }
}
function encodeFieldKey(key) {
  return encodeURIComponent(key)
    .replace(/%20/g, "-")
    .replace(/[^a-zA-Z0-9-_]/g, "");
}

function scrollToField(key, divId = "genform") {
  // Try field first
  let encodedKey = encodeFieldKey(key);
  let element = document.getElementById(`${divId}-field-${encodedKey}`);

  // If not found, try section
  if (!element)
    element = document.getElementById(`${divId}-section-${encodedKey}`);

  // If still not found, try segment
  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`);
  }
}
