

        // Helper Functions
        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 = window.lang || "en") {
            if (!field || !field.options) return [];
            if (Array.isArray(field.options)) return field.options;
            return field.options[lang] || field.options.en || Object.values(field.options)[0] || [];
        }

        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.score || 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() !== "") || // Removed val !== DEFAULT_OCCUPATION
        (typeof val === "number" && val !== 0 && !isNaN(val)) ||
        (inputType === "radio" && val !== null);

    if (["radio", "select"].includes(inputType) && field.weights) {
        if (inputType === "select" && val === "") { // Changed from val === DEFAULT_OCCUPATION
            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.score || field.weight || 1 : 0;
    }
}

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

        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);
        }

        function updateOutputJson(divId, schema) {
            const outputEl = document.getElementById(`${divId}-output`);
            if (outputEl) {
                outputEl.value = JSON.stringify(schema, null, 2);
            }
        }

        function updateScoreDisplay(divId, key, field) {
            const escapedKey = CSS.escape(key);
            const scoreDisplay = document.querySelector(`#${divId}-field-${escapedKey} .score-display`);
            if (scoreDisplay) {
                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                scoreDisplay.textContent = window.debug ? `(Score: ${currentScore}/${maxScore})` : "";
            }
        }
// Helper function to encode keys for IDs and hrefs to handle Unicode and spaces
function encodeFieldKey(key) {
    return encodeURIComponent(key).replace(/%20/g, '-').replace(/[^a-zA-Z0-9-_]/g, '');
}

// Scroll to field function for jump links
function scrollToField(key, divId = 'form-container') {
    const encodedKey = encodeFieldKey(key);
    const element = document.getElementById(`${divId}-field-${encodedKey}`);
    if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        element.style.backgroundColor = '#e0f7fa';
        setTimeout(() => { element.style.backgroundColor = ''; }, 2000);
    } else {
        console.warn(`Field with key ${key} not found for scrolling`);
    }
}
        function AAAupdateSectionSummaries(divId, schema) {
    const lang = window.lang || "en";
    const segments = new Map();
    if (schema.grouping) {
        schema.grouping.name.forEach((name, i) => {
            if (schema.grouping.type[i] === "segment") {
                segments.set(name, {
                    label: getLabel({ label: schema.grouping.label }, lang)[i] || name,
                    sections: new Map(),
                });
            }
        });
    }

    for (const key in schema) {
        if (key === "grouping" || schema[key].type === "section") continue;
        const field = schema[key];
        const section = field.section || "default";
        const segment = field.segment?.[0] || "default";
        if (!segments.has(segment)) {
            segments.set(segment, { label: segment, sections: new Map() });
        }
        if (!segments.get(segment).sections.has(section)) {
            segments.get(segment).sections.set(section, getLabel({ label: schema[section]?.label }, lang) || section);
        }
    }

    segments.forEach((segmentData, segmentId) => {
        segmentData.sections.forEach((sectionLabel, sectionId) => {
            const summaryDiv = document.getElementById(`${divId}-summary-${segmentId}-${sectionId}`);
            if (!summaryDiv) return;

            let totalFields = 0, answeredFields = 0, totalScore = 0, achievedScore = 0;
            let totalRequiredFields = 0, answeredRequiredFields = 0, totalFiles = 0;
            const unansweredFields = [], unansweredRequiredFields = [], weightDetails = [];

            for (const key in schema) {
                if (key === "grouping" || schema[key].type === "section") continue;
                const field = schema[key];
                if (field.section !== sectionId || !field.segment?.includes(segmentId)) continue;

                totalFields += 1;
                if (field.required) totalRequiredFields += 1;
                if (field.type === "attachment") totalFiles += countFiles(field);

                const val = field.value;
                const hasAnswer =
                    (Array.isArray(val) && val.length > 0) ||
                    (typeof val === "string" && val.trim() !== "") ||
                    (typeof val === "number" && val !== 0 && !isNaN(val)) ||
                    (field.data_type === "radio" && val !== null);

                if (hasAnswer) {
                    answeredFields += 1;
                    if (field.required) answeredRequiredFields += 1;
                } else {
                    unansweredFields.push({ label: getLabel(field, lang) || key, key });
                    if (field.required) unansweredRequiredFields.push({ label: getLabel(field, lang) || key, key });
                }

                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                totalScore += maxScore;
                achievedScore += currentScore;

                if (window.debug && (field.weights || field.score || field.weight)) {
                    const weights = field.weights ? field.weights.join(", ") : field.score || field.weight || 1;
                    weightDetails.push(`${getLabel(field, lang)}: ${currentScore}/${maxScore} (Weights: ${weights})`);
                }
            }

            const percent = totalFields > 0 ? Math.round((answeredFields / totalFields) * 100) : 0;
            const requiredPercent = totalRequiredFields > 0 ? Math.round((answeredRequiredFields / totalRequiredFields) * 100) : 100;

            const headerProgress = document.getElementById(`${divId}-section-header-${sectionId}-progress`);
            if (headerProgress) {
                headerProgress.innerHTML = ` 
                    <progress value="${requiredPercent}" max="100"></progress> ${requiredPercent}%
                `;
            }

            summaryDiv.innerHTML = `
                <strong>${getLabel({ label: { en: "Section Summary", th: "สรุปหมวด" } }, lang)}:</strong><br>
                ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: 
                <progress value="${percent}" max="100"></progress>
                <span class="progress-text">${percent}%</span><br>
                ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${answeredFields}/${totalFields}<br>
                ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${totalRequiredFields}<br>
                ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}:
                <progress value="${answeredRequiredFields}" max="${totalRequiredFields}"></progress> ${requiredPercent}%<br>
                ${getLabel({ label: { en: "Unanswered", th: "ยังไม่ได้ตอบ" } }, lang)}: ${
                    unansweredFields.length > 0
                        ? unansweredFields.map(({ label, key }) => 
                              `<a href="#${divId}-field-${CSS.escape(key)}" style="color:blue;text-decoration:underline">${label}</a>`
                          ).join(", ")
                        : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                }<br>
                ${getLabel({ label: { en: "Required Missing", th: "จำเป็นต้องตอบ" } }, lang)}: ${
                    unansweredRequiredFields.length > 0
                        ? unansweredRequiredFields.map(({ label, key }) => 
                              `<a href="#${divId}-field-${CSS.escape(key)}" style="color:blue;text-decoration:underline">${label}</a>`
                          ).join(", ")
                        : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                }<br>
                ${window.debug ? `
                    ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${achievedScore}/${totalScore}<br>
                    ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${achievedScore}<br>
                    <details>${weightDetails.length > 0 ? `<summary>${getLabel({ label: { en: "Weight Details", th: "รายละเอียดน้ำหนัก" } }, lang)}</summary> ${weightDetails.join(", ")}<br>` : ""}
                </details>` : ""}
                ${totalFiles > 0 ? `${getLabel({ label: { en: "Files Attached", th: "ไฟล์ที่แนบ" } }, lang)}: ${totalFiles}` : ""}
            `;
            summaryDiv.style.display = window.debug ? "block" : "none";
        });
    });

    ssum("ssum-report", schema);
}
// Modified updateSectionSummaries to fix jump links
function updateSectionSummaries(divId, schema) {
    const lang = window.lang || "en";
    const segments = new Map();
    if (schema.grouping) {
        schema.grouping.name.forEach((name, i) => {
            if (schema.grouping.type[i] === "segment") {
                segments.set(name, {
                    label: getLabel({ label: schema.grouping.label }, lang)[i] || name,
                    sections: new Map(),
                });
            }
        });
    }

    for (const key in schema) {
        if (key === "grouping" || schema[key].type === "section") continue;
        const field = schema[key];
        const section = field.section || "default";
        const segment = field.segment?.[0] || "default";
        if (!segments.has(segment)) {
            segments.set(segment, { label: segment, sections: new Map() });
        }
        if (!segments.get(segment).sections.has(section)) {
            segments.get(segment).sections.set(section, getLabel({ label: schema[section]?.label }, lang) || section);
        }
    }

    segments.forEach((segmentData, segmentId) => {
        segmentData.sections.forEach((sectionLabel, sectionId) => {
            const summaryDiv = document.getElementById(`${divId}-summary-${segmentId}-${sectionId}`);
            if (!summaryDiv) return;

            let totalFields = 0, answeredFields = 0, totalScore = 0, achievedScore = 0;
            let totalRequiredFields = 0, answeredRequiredFields = 0, totalFiles = 0;
            const unansweredFields = [], unansweredRequiredFields = [], weightDetails = [];

            for (const key in schema) {
                if (key === "grouping" || schema[key].type === "section") continue;
                const field = schema[key];
                if (field.section !== sectionId || !field.segment?.includes(segmentId)) continue;

                totalFields += 1;
                if (field.required) totalRequiredFields += 1;
                if (field.type === "attachment") totalFiles += countFiles(field);

                const val = field.value;
                const hasAnswer =
                    (Array.isArray(val) && val.length > 0) ||
                    (typeof val === "string" && val.trim() !== "") ||
                    (typeof val === "number" && val !== 0 && !isNaN(val)) ||
                    (field.data_type === "radio" && val !== null);

                if (hasAnswer) {
                    answeredFields += 1;
                    if (field.required) answeredRequiredFields += 1;
                } else {
                    unansweredFields.push({ label: getLabel(field, lang) || key, key });
                    if (field.required) unansweredRequiredFields.push({ label: getLabel(field, lang) || key, key });
                }

                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                totalScore += maxScore;
                achievedScore += currentScore;

                if (window.debug && (field.weights || field.score || field.weight)) {
                    const weights = field.weights ? field.weights.join(", ") : field.score || field.weight || 1;
                    weightDetails.push(`${getLabel(field, lang)}: ${currentScore}/${maxScore} (Weights: ${weights})`);
                }
            }

            const percent = totalFields > 0 ? Math.round((answeredFields / totalFields) * 100) : 0;
            const requiredPercent = totalRequiredFields > 0 ? Math.round((answeredRequiredFields / totalRequiredFields) * 100) : 100;

            const headerProgress = document.getElementById(`${divId}-section-header-${sectionId}-progress`);
            if (headerProgress) {
                headerProgress.innerHTML = ` 
                    <progress value="${requiredPercent}" max="100"></progress> ${requiredPercent}%
                `;
            }

            summaryDiv.innerHTML = `
                <strong>${getLabel({ label: { en: "Section Summary", th: "สรุปหมวด" } }, lang)}:</strong><br>
                ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: 
                <progress value="${percent}" max="100"></progress>
                <span class="progress-text">${percent}%</span><br>
                ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${answeredFields}/${totalFields}<br>
                ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${totalRequiredFields}<br>
                ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}:
                <progress value="${answeredRequiredFields}" max="${totalRequiredFields}"></progress> ${requiredPercent}%<br>
                ${getLabel({ label: { en: "Unanswered", th: "ยังไม่ได้ตอบ" } }, lang)}: ${
                    unansweredFields.length > 0
                        ? unansweredFields.map(({ label, key }) => 
                              `<a href="#" onclick="scrollToField('${encodeFieldKey(key)}', '${divId}');return false;" style="color:blue;text-decoration:underline">${label}</a>`
                          ).join(", ")
                        : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                }<br>
                ${getLabel({ label: { en: "Required Missing", th: "จำเป็นต้องตอบ" } }, lang)}: ${
                    unansweredRequiredFields.length > 0
                        ? unansweredRequiredFields.map(({ label, key }) => 
                              `<a href="#" onclick="scrollToField('${encodeFieldKey(key)}', '${divId}');return false;" style="color:blue;text-decoration:underline">${label}</a>`
                          ).join(", ")
                        : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                }<br>
                ${window.debug ? `
                    ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${achievedScore}/${totalScore}<br>
                    ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${achievedScore}<br>
                    <details>${weightDetails.length > 0 ? `<summary>${getLabel({ label: { en: "Weight Details", th: "รายละเอียดน้ำหนัก" } }, lang)}</summary> ${weightDetails.join(", ")}<br>` : ""}
                </details>` : ""}
                ${totalFiles > 0 ? `${getLabel({ label: { en: "Files Attached", th: "ไฟล์ที่แนบ" } }, lang)}: ${totalFiles}` : ""}
            `;
            summaryDiv.style.display = window.debug ? "block" : "none";
        });
    });

    ssum("ssum-report", schema);
}
        function updateGrandSummary(divId = "form-container") {

            const grandSummary = document.getElementById("grand-summary");
            if (!grandSummary) return;

            const lang = window.lang || "en";
    const el = document.getElementById(divId);
const schema = el && el._formData ? el._formData : null;
if (!schema) {
        displayMessage(`Form "${divId}" not available or schema not loaded`, true);
        return;
    }

            let totalFields = 0, answeredFields = 0, totalScore = 0, achievedScore = 0;
            let totalRequiredFields = 0, answeredRequiredFields = 0, totalFiles = 0;
            const unansweredRequiredFields = [], weightDetails = [];

            for (const key in schema) {
                if (key === "grouping" || schema[key].type === "section") continue;
                const field = schema[key];
                totalFields += 1;
                if (field.required) totalRequiredFields += 1;
                if (field.type === "attachment") totalFiles += countFiles(field);

                const val = field.value;
                const hasAnswer =
                    (Array.isArray(val) && val.length > 0) ||
                    (typeof val === "string" && val.trim() !== "" && !(field.data_type === "select" && val === getOptions(field)[0])) ||
                    (typeof val === "number" && val !== 0 && !isNaN(val)) ||
                    (field.data_type === "radio" && val !== null);

                if (hasAnswer) {
                    answeredFields += 1;
                    if (field.required) answeredRequiredFields += 1;
                } else if (field.required) {
                    unansweredRequiredFields.push(getLabel(field, lang) || key);
                }

                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                totalScore += maxScore;
                achievedScore += currentScore;

                if (window.debug && (field.weights || field.score || field.weight)) {
                    const weights = field.weights ? field.weights.join(", ") : field.score || field.weight || 1;
                    weightDetails.push(`${getLabel(field, lang)}: ${currentScore}/${maxScore} (Weights: ${weights})`);
                }
            }

            const fieldPercent = totalFields > 0 ? Math.round((answeredFields / totalFields) * 100) : 0;
            const requiredPercent = totalRequiredFields > 0 ? Math.round((answeredRequiredFields / totalRequiredFields) * 100) : 100;
            const scorePercent = totalScore > 0 && window.debug ? Math.round((achievedScore / totalScore) * 100) : 0;

            grandSummary.innerHTML = `
                <h3>${getLabel({ label: { en: "Grand Summary", th: "สรุปรวม" } }, lang)}</h3>
                <strong>${getLabel({ label: { en: "Overall", th: "ภาพรวม" } }, lang)}:</strong><br>
                ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: 
                <progress value="${fieldPercent}" max="100"></progress>
                <span class="progress-text">${fieldPercent}%</span><br>
                ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${answeredFields}/${totalFields}<br>
                ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}:
                <progress value="${answeredRequiredFields}" max="${totalRequiredFields}"></progress> ${requiredPercent}%<br>
                ${getLabel({ label: { en: "Required Missing", th: "จำเป็นต้องตอบ" } }, lang)}: ${
                    unansweredRequiredFields.length > 0 
                        ? unansweredRequiredFields.join(", ") 
                        : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                }<br>
                ${window.debug ? `
                    ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${achievedScore}/${totalScore} (${scorePercent}%)<br>
                    ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${achievedScore}<br>
                    <details>${weightDetails.length > 0 ? `<summary>${getLabel({ label: { en: "Weight Details", th: "รายละเอียดน้ำหนัก" } }, lang)}</summary> ${weightDetails.join(", ")}<br>` : ""}
                </details>` : ""}
                ${totalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${totalFiles}` : ""}
            `;
        }

        function checkpoint(divId, data) {
            const reportDiv = document.getElementById(divId);
            if (!reportDiv) {
                console.error(`Div with ID ${divId} not found`);
                return;
            }

            const lang = window.lang || "en";
            const segments = new Map();
            let reportHtml = "";

            if (data.grouping) {
                data.grouping.name.forEach((name, i) => {
                    if (data.grouping.type[i] === "segment") {
                        segments.set(name, {
                            label: getLabel({ label: data.grouping.label }, lang)[i] || name,
                            sections: new Map(),
                        });
                    }
                });
            }

            for (const key in data) {
                if (key === "grouping" || data[key].type !== "section") continue;
                const section = data[key];
                const segment = section.segment?.[0] || "default";
                if (!segments.has(segment)) {
                    segments.set(segment, { label: segment, sections: new Map() });
                }
                segments.get(segment).sections.set(key, getLabel(section, lang) || key);
            }

            segments.forEach((segmentData, segmentId) => {
                reportHtml += `<h3>Segment: ${segmentData.label}</h3>`;
                segmentData.sections.forEach((sectionLabel, sectionId) => {
                    let totalFields = 0, answeredFields = 0, totalScore = 0, achievedScore = 0;
                    let totalRequiredFields = 0, answeredRequiredFields = 0, totalFiles = 0;
                    const unansweredFields = [], unansweredRequiredFields = [], weightDetails = [];

                    for (const key in data) {
                        if (key === "grouping" || data[key].type === "section") continue;
                        const field = data[key];
                        if (field.section !== sectionId || !field.segment?.includes(segmentId)) continue;

                        totalFields += 1;
                        if (field.required) totalRequiredFields += 1;
                        if (field.type === "attachment") totalFiles += countFiles(field);

                        const val = field.value;
                        const hasAnswer =
                            (Array.isArray(val) && val.length > 0) ||
                            (typeof val === "string" && val.trim() !== "" && val !== DEFAULT_OCCUPATION) ||
                            (typeof val === "number" && val !== 0 && !isNaN(val)) ||
                            (field.data_type === "radio" && val !== null);

                        if (hasAnswer) {
                            answeredFields += 1;
                            if (field.required) answeredRequiredFields += 1;
                        } else {
                            unansweredFields.push(getLabel(field, lang) || key);
                            if (field.required) unansweredRequiredFields.push(getLabel(field, lang) || key);
                        }

                        const maxScore = calculateMaxScore(field);
                        const currentScore = calculateCurrentScore(field);
                        totalScore += maxScore;
                        achievedScore += currentScore;

                        if (window.debug && (field.weights || field.score || field.weight)) {
                            const weights = field.weights ? field.weights.join(", ") : field.score || field.weight || 1;
                            weightDetails.push(`${getLabel(field, lang)}: ${currentScore}/${maxScore} (Weights: ${weights})`);
                        }
                    }

                    const percent = totalFields > 0 ? Math.round((answeredFields / totalFields) * 100) : 0;
                    const requiredPercent = totalRequiredFields > 0 ? Math.round((answeredRequiredFields / totalRequiredFields) * 100) : 100;

                    reportHtml += `
                        <div style="margin-left: 20px;">
                            <strong>Section: ${sectionLabel}</strong><br>
                            Percent Progress: <progress value="${percent}" max="100"></progress> ${percent}%<br>
                            Total Fields: ${answeredFields}/${totalFields}<br>
                            Required Fields Completed: ${answeredRequiredFields}/${totalRequiredFields} (${requiredPercent}%)<br>
                            Unanswered: ${unansweredFields.length > 0 ? unansweredFields.join(", ") : "None"}<br>
                            Required Missing: ${unansweredRequiredFields.length > 0 ? unansweredRequiredFields.join(", ") : "None"}<br>
                            ${window.debug ? `
                                Total Score: ${achievedScore}/${totalScore}<br>
                                Achieved Score: ${achievedScore}<br>
                                ${weightDetails.length > 0 ? `Weight Details: ${weightDetails.join(", ")}<br>` : ""}
                            ` : ""}
                            ${totalFiles > 0 ? `Files Attached: ${totalFiles}` : ""}
                        </div>
                    `;
                });
            });

            reportDiv.innerHTML = reportHtml || "<div>No sections found in the schema.</div>";
        }

        function listenform(divId) {
            const schema = document.getElementById(divId)._formData;
            const lang = window.lang || "en";

            for (const key in schema) {
                if (key === "grouping" || schema[key].type === "section") continue;
                const field = schema[key];
                const inputType = field.data_type || field.type;
                const inputEl = document.getElementById(`${divId}-${key}`);

                if (["string", "textarea", "text", "number"].includes(inputType)) {
                    if (inputEl) {
                        inputEl.addEventListener("input", () => {
                            schema[key].value = inputType === "number" ? parseFloat(inputEl.value) || 0 : inputEl.value.trim();
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                            //checkpoint("checkpoint-report", schema);
                        });
                    }
                } else if (inputType === "radio") {
                    document.querySelectorAll(`input[name="${divId}-${key}"]`).forEach((radio) => {
                        radio.addEventListener("change", () => {
                            schema[key].value = parseInt(radio.value);
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                            //checkpoint("checkpoint-report", schema);
                        });
                    });
                } else if (inputType === "checkbox") {
                    document.querySelectorAll(`input[name="${divId}-${key}[]"]`).forEach((checkbox) => {
                        checkbox.addEventListener("change", () => {
                            const checked = Array.from(document.querySelectorAll(`input[name="${divId}-${key}[]"]:checked`)).map(el => parseInt(el.value));
                            schema[key].value = checked;
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                            //checkpoint("checkpoint-report", schema);
                        });
                    });
                } else if (inputType === "select") {
                    if (inputEl) {
                        inputEl.addEventListener("change", () => {
                            schema[key].value = inputEl.value;
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                            //checkpoint("checkpoint-report", schema);
                        });
                    }
                } else if (inputType === "attachment") {
                    if (inputEl) {
                        inputEl.addEventListener("input", () => {
                            schema[key].value = inputEl.value;
                            const fileCount = document.getElementById(`${divId}-filecount-${key}`);
                            fileCount.textContent = `Files: ${countFiles(schema[key])}`;
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                            //checkpoint("checkpoint-report", schema);
                        });
                    }
                }
            }
        }

        function refreshForm(divId, schema) {
            genform(divId, JSON.parse(JSON.stringify(schema)));
            updateGrandSummary(divId);

            //checkpoint("checkpoint-report", schema);
        }

        function AAgenform(divId, data) {
            const container = document.getElementById(divId);
            if (!container) {
              //  console.error(`Div with ID ${divId} not found`);
                return;
            }

            window._globalSchemas = window._globalSchemas || {};
            window._globalSchemas[divId] = JSON.parse(JSON.stringify(data));
            container._formData = window._globalSchemas[divId];
            container._initialData = JSON.parse(JSON.stringify(data));

            const lang = window.lang || "en";

            container.innerHTML = `
                <div style="font-family: Arial, sans-serif;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="font-size: 1.5em;">${getLabel({ label: { en: "Form in", th: "ฟอร์มใน" } }, lang)} ${divId}</h3>
                       
                        
                    </div>
                    <div id="${divId}-fields"></div>
                    <div style="display:none;"><textarea id="${divId}-input" placeholder="Enter JSON schema"></textarea>
                        <button id="${divId}-copy-btn">Copy to Schema</button>
                    <textarea id="${divId}-output" readonly></textarea></div>
                </div>
            `;
//<button id="${divId}-refresh-btn">Reset!</button>
            //document.getElementById(`${divId}-refresh-btn`).addEventListener("click", () => {                refreshForm(divId, container._initialData);            });

            

            
            const fieldsDiv = document.getElementById(`${divId}-fields`);
            const schema = container._formData;

            const segments = new Map();
            if (schema.grouping) {
                schema.grouping.name.forEach((name, i) => {
                    if (schema.grouping.type[i] === "segment") {
                        segments.set(name, {
                            label: getLabel({ label: schema.grouping.label }, lang)[i] || name,
                            sections: new Map(),
                        });
                    }
                });
            }

            for (const key in schema) {
                if (key === "grouping") continue;
                const field = schema[key];
                if (field.type === "section") {
                    const segment = field.segment?.[0] || schema.grouping?.name[0] || "default";
                    if (!segments.has(segment)) {
                        segments.set(segment, { label: segment, sections: new Map() });
                    }
                    segments.get(segment).sections.set(key, getLabel(field, lang) || key);
                } else if (field.section) {
                    const segment = field.segment?.[0] || schema.grouping?.name[0] || "default";
                    if (!segments.has(segment)) {
                        segments.set(segment, { label: segment, sections: new Map() });
                    }
                    if (!segments.get(segment).sections.has(field.section)) {
                        segments.get(segment).sections.set(field.section, getLabel({ label: schema[field.section]?.label }, lang) || field.section);
                    }
                }
            }

            segments.forEach((segmentData, segmentId) => {
                const segDetails = document.createElement("details");
                segDetails.className = "segment";
                segDetails.open = true;
                segDetails.innerHTML = `<summary>${getLabel({ label: { en: "Segment", th: "ส่วน" } }, lang)}: ${segmentData.label}</summary>`;

                const segDiv = document.createElement("div");
                segDiv.style.padding = "10px";

                segmentData.sections.forEach((sectionLabel, sectionId) => {
                    const secDetails = document.createElement("details");
                    secDetails.className = "section";
                    secDetails.id = `${divId}-section-${sectionId}`;
                    secDetails.open = true;
                    secDetails.innerHTML = `<summary>${getLabel({ label: { en: "Section", th: "หมวด" } }, lang)}: ${sectionLabel}<span id="${divId}-section-header-${sectionId}-progress"></span></summary>`;

                    const secDiv = document.createElement("div");
                    secDiv.style.padding = "8px";

                    let hasField = false;
                    for (const key in schema) {
                        if (key === "grouping" || schema[key].type === "section") continue;
                        const field = schema[key];
                        if (field.section !== sectionId || !field.segment?.includes(segmentId)) continue;

                        hasField = true;
                        const fieldDiv = document.createElement("div");
                        fieldDiv.className = "form-field";
                        fieldDiv.id = `${divId}-field-${key}`;

                        const label = document.createElement("label");
                        label.style.fontWeight = "300";
                        label.style.marginRight = "6px";
                        label.style.display = "block";
                        if (field.required) label.classList.add("required-field");
                        label.textContent = getLabel(field, lang) || key;
                        label.htmlFor = `${divId}-${key}`;
                        if (field.score !== undefined || field.weights) {
                            const scoreDisplay = document.createElement("span");
                            scoreDisplay.className = "score-display";
                            const maxScore = calculateMaxScore(field);
                            const currentScore = calculateCurrentScore(field);
                            if (typeof window.score !== "undefined" && window.score) {
                                scoreDisplay.textContent = `(Score: ${currentScore}/${maxScore})`;
                            }
                            label.appendChild(scoreDisplay);
                        }
                        fieldDiv.appendChild(label);

                        let input;
                        const inputType = field.data_type || field.type;
                        if (inputType === "textarea") {
                            input = document.createElement("textarea");
                            input.id = `${divId}-${key}`;
                            input.value = field.value || "";
                        } else if (inputType === "radio") {
                            input = document.createElement("div");
                            getOptions(field, lang).forEach((opt, idx) => {
                                const radioLabel = document.createElement("label");
                                radioLabel.style.marginRight = "8px";
                                const val = idx;
                                radioLabel.innerHTML = `<input type="radio" name="${divId}-${key}" value="${val}" ${field.value === val ? "checked" : ""}> ${opt}`;
                                input.appendChild(radioLabel);
                            });
                        } else if (inputType === "checkbox") {
                            input = document.createElement("div");
                            getOptions(field, lang).forEach((opt, idx) => {
                                const checkLabel = document.createElement("label");
                                checkLabel.style.marginRight = "8px";
                                const val = idx;
                                checkLabel.innerHTML = `<input type="checkbox" name="${divId}-${key}[]" value="${val}" ${field.value.includes(val) ? "checked" : ""}> ${opt}`;
                                input.appendChild(checkLabel);
                            });
                        } else if (inputType === "select") {
    input = document.createElement("select");
    input.id = `${divId}-${key}`;
    getOptions(field, lang).forEach((opt, idx) => {
        const option = document.createElement("option");
        const value = idx === 0 ? "" : opt; // Use empty string for first option
        option.value = value;
        option.textContent = opt;
        option.selected = field.value === value;
        input.appendChild(option);
    });
} else if (inputType === "attachment") {
                            input = document.createElement("div");
                                const textInput =
                                    document.createElement("input");
                                textInput.type = "text";
                                textInput.id = `${divId}-${key}`;
                                textInput.value = field.value || "";
                                textInput.placeholder = getLabel(
                                    {
                                        label: {
                                            en: "Enter file names (comma-separated)",
                                            th: "ป้อนชื่อไฟล์ (คั่นด้วยเครื่องหมายจุลภาค)",
                                        },
                                    },
                                    lang,
                                );
                                textInput.style.width = "260px";
                                input.appendChild(textInput);
                                const fileCount = document.createElement("div");
                                fileCount.id = `${divId}-filecount-${key}`;
                                fileCount.style.marginTop = "5px";
                                const initialFileCount = countFiles(field);
                                fileCount.textContent = `Files: ${initialFileCount}`;
                                input.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 = () => {
                                    const files = toggleUploadPanel();
                                    updateFileListFromInput(`${divId}-${key}`);
                                    //schema[key].value = files.join(", ");
                                    const count = countFiles(schema[key]);
                                    fileCount.textContent = `Files: ${count}`;
                                    updateOutputJson(divId, schema);
                                    updateScoreDisplay(divId, key, schema[key]);
                                    updateSectionSummaries(divId, schema);
                                    updateGrandSummary(divId);
                                    if (
                                        document.getElementById(
                                            "checkpoint-report",
                                        )
                                    ) {
                                        checkpoint("checkpoint-report", schema);
                                    }
                                };
                                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 = () => {
                                    schema[key].value = textInput.value;
                                    const count = countFiles(schema[key]);
                                    fileCount.textContent = `Files: ${count}`;
                                    updateOutputJson(divId, schema);
                                    updateScoreDisplay(divId, key, schema[key]);
                                    updateSectionSummaries(divId, schema);
                                    updateGrandSummary(divId);
                                    
                                };
                                buttonDiv.appendChild(countFilesBtn);
                                input.appendChild(buttonDiv);
                            } else {
                                input = document.createElement("input");
                                input.id = `${divId}-${key}`;
                                input.type =
                                    inputType === "string"
                                        ? "text"
                                        : inputType || "text";
                                input.value =
                                    field.value ||
                                    (inputType === "number" ? 0 : "");
                                input.style.width = "260px";
                            }

                            fieldDiv.appendChild(input);

                            const resetBtn = document.createElement("button");
                            resetBtn.textContent = getLabel(
                                { label: { en: "Reset", th: "รีเซ็ต" } },
                                lang,
                            );
                            resetBtn.style.marginLeft = "10px";
                            resetBtn.style.padding = "4px 8px";
                            resetBtn.style.cursor = "pointer";
                            resetBtn.onclick = () => {
                            if (inputType === "radio") {
                                schema[key].value = null;
                                document.querySelectorAll(`input[name="${divId}-${key}"]`).forEach((el) => {
                                    el.checked = false;
                                });
                            } else if (inputType === "checkbox") {
                                schema[key].value = [];
                                document.querySelectorAll(`input[name="${divId}-${key}[]"]`).forEach((el) => {
                                    el.checked = false;
                                });
                            } else if (inputType === "select") {
    schema[key].value = ""; // Changed from DEFAULT_OCCUPATION to empty string
    const selectEl = document.getElementById(`${divId}-${key}`);
    selectEl.value = ""; // Changed from DEFAULT_OCCUPATION to empty string
} else if (inputType === "attachment") {
                                schema[key].value = "";
                                const textInput = document.getElementById(`${divId}-${key}`);
                                textInput.value = "";
                                const fileCount = document.getElementById(`${divId}-filecount-${key}`);
                                fileCount.textContent = `Files: 0`;
                            } else {
                                schema[key].value = inputType === "number" ? 0 : "";
                                const textInput = document.getElementById(`${divId}-${key}`);
                                textInput.value = inputType === "number" ? 0 : "";
                            }
                            updateOutputJson(divId, schema);
                            updateScoreDisplay(divId, key, schema[key]);
                            updateSectionSummaries(divId, schema);
                            updateGrandSummary(divId);

                           // checkpoint("checkpoint-report", schema);
                        };
                        fieldDiv.appendChild(resetBtn);

                        secDiv.appendChild(fieldDiv);
                    }

                    if (hasField) {
                        const sectionSummary = document.createElement("div");
                        sectionSummary.className = "section-summary";
                        sectionSummary.id = `${divId}-summary-${segmentId}-${sectionId}`;
                        secDiv.appendChild(sectionSummary);
                        segDiv.appendChild(secDetails);
                        secDetails.appendChild(secDiv);
                    }
                });

                segDetails.appendChild(segDiv);
                fieldsDiv.appendChild(segDetails);
            });

            updateOutputJson(divId, schema);
            updateSectionSummaries(divId, schema);
            ssum("ssum-report", schema); // Initial call to ssum
            updateGrandSummary(divId);

            //checkpoint("checkpoint-report", schema);

            const copyBtn = document.getElementById(`${divId}-copy-btn`);
            copyBtn.addEventListener("click", () => {
                const inputEl = document.getElementById(`${divId}-input`);
                try {
                    const newSchema = JSON.parse(inputEl.value);
                    genform(divId, newSchema);
                    updateGrandSummary(divId);

                    //checkpoint("checkpoint-report", newSchema);
                } catch (e) {
                    console.error(`Invalid JSON in ${divId}-input: ${e.message}`);
                    alert(getLabel({ label: { en: `Invalid JSON: ${e.message}`, th: `JSON ไม่ถูกต้อง: ${e.message}` } }, lang));
                }
            });

            listenform(divId);
            if (divId === "form-container") autosaveOnChange(divId, "schema");
if (divId === "schema2") autosaveOnChange(divId, "schema2");
if (divId === "schema3") autosaveOnChange(divId, "schema3");

}
// Modified genform to ensure field IDs match jump links
function genform(divId, data) {
    const container = document.getElementById(divId);
    if (!container) {
        console.error(`Div with ID ${divId} not found`);
        return;
    }

    window._globalSchemas = window._globalSchemas || {};
    window._globalSchemas[divId] = JSON.parse(JSON.stringify(data));
    container._formData = window._globalSchemas[divId];
    container._initialData = JSON.parse(JSON.stringify(data));

    const lang = window.lang || "en";

    container.innerHTML = `
        <div style="font-family: Arial, sans-serif;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h3 style="font-size: 1.5em;">${getLabel({ label: { en: "Form in", th: "ฟอร์มใน" } }, lang)} ${divId}</h3>
            </div>
            <div id="${divId}-fields"></div>
            <div style="display:none;">
                <textarea id="${divId}-input" placeholder="Enter JSON schema"></textarea>
                <button id="${divId}-copy-btn">Copy to Schema</button>
                <textarea id="${divId}-output" readonly></textarea>
            </div>
        </div>
    `;

    const fieldsDiv = document.getElementById(`${divId}-fields`);
    const schema = container._formData;

    const segments = new Map();
    if (schema.grouping) {
        schema.grouping.name.forEach((name, i) => {
            if (schema.grouping.type[i] === "segment") {
                segments.set(name, {
                    label: getLabel({ label: schema.grouping.label }, lang)[i] || name,
                    sections: new Map(),
                });
            }
        });
    }

    for (const key in schema) {
        if (key === "grouping") continue;
        const field = schema[key];
        if (field.type === "section") {
            const segment = field.segment?.[0] || schema.grouping?.name[0] || "default";
            if (!segments.has(segment)) {
                segments.set(segment, { label: segment, sections: new Map() });
            }
            segments.get(segment).sections.set(key, getLabel(field, lang) || key);
        } else if (field.section) {
            const segment = field.segment?.[0] || schema.grouping?.name[0] || "default";
            if (!segments.has(segment)) {
                segments.set(segment, { label: segment, sections: new Map() });
            }
            if (!segments.get(segment).sections.has(field.section)) {
                segments.get(segment).sections.set(field.section, getLabel({ label: schema[field.section]?.label }, lang) || field.section);
            }
        }
    }

    segments.forEach((segmentData, segmentId) => {
        const segDetails = document.createElement("details");
        segDetails.className = "segment";
        segDetails.open = true;
        segDetails.innerHTML = `<summary>${getLabel({ label: { en: "Segment", th: "ส่วน" } }, lang)}: ${segmentData.label}</summary>`;

        const segDiv = document.createElement("div");
        segDiv.style.padding = "10px";

        segmentData.sections.forEach((sectionLabel, sectionId) => {
            const secDetails = document.createElement("details");
            secDetails.className = "section";
            secDetails.id = `${divId}-section-${sectionId}`;
            secDetails.open = true;
            secDetails.innerHTML = `<summary>${getLabel({ label: { en: "Section", th: "หมวด" } }, lang)}: ${sectionLabel}<span id="${divId}-section-header-${sectionId}-progress"></span></summary>`;

            const secDiv = document.createElement("div");
            secDiv.style.padding = "8px";

            let hasField = false;
            for (const key in schema) {
                if (key === "grouping" || schema[key].type === "section") continue;
                const field = schema[key];
                if (field.section !== sectionId || !field.segment?.includes(segmentId)) continue;

                hasField = true;
                const fieldDiv = document.createElement("div");
                fieldDiv.className = "form-field";
                fieldDiv.id = `${divId}-field-${encodeFieldKey(key)}`; // Use encoded key for ID

                const label = document.createElement("label");
                label.style.fontWeight = "300";
                label.style.marginRight = "6px";
                label.style.display = "block";
                if (field.required) label.classList.add("required-field");
                label.textContent = getLabel(field, lang) || key;
                label.htmlFor = `${divId}-${encodeFieldKey(key)}`;
                if (field.score !== undefined || field.weights) {
                    const scoreDisplay = document.createElement("span");
                    scoreDisplay.className = "score-display";
                    const maxScore = calculateMaxScore(field);
                    const currentScore = calculateCurrentScore(field);
                    if (typeof window.score !== "undefined" && window.score) {
                        scoreDisplay.textContent = `(Score: ${currentScore}/${maxScore})`;
                    }
                    label.appendChild(scoreDisplay);
                }
                fieldDiv.appendChild(label);

                let input;
                const inputType = field.data_type || field.type;
                if (inputType === "textarea") {
                    input = document.createElement("textarea");
                    input.id = `${divId}-${encodeFieldKey(key)}`;
                    input.value = field.value || "";
                } else if (inputType === "radio") {
                    input = document.createElement("div");
                    getOptions(field, lang).forEach((opt, idx) => {
                        const radioLabel = document.createElement("label");
                        radioLabel.style.marginRight = "8px";
                        const val = idx;
                        radioLabel.innerHTML = `<input type="radio" name="${divId}-${encodeFieldKey(key)}" value="${val}" ${field.value === val ? "checked" : ""}> ${opt}`;
                        input.appendChild(radioLabel);
                    });
                } else if (inputType === "checkbox") {
                    input = document.createElement("div");
                    getOptions(field, lang).forEach((opt, idx) => {
                        const checkLabel = document.createElement("label");
                        checkLabel.style.marginRight = "8px";
                        const val = idx;
                        checkLabel.innerHTML = `<input type="checkbox" name="${divId}-${encodeFieldKey(key)}[]" value="${val}" ${field.value.includes(val) ? "checked" : ""}> ${opt}`;
                        input.appendChild(checkLabel);
                    });
                } else if (inputType === "select") {
                    input = document.createElement("select");
                    input.id = `${divId}-${encodeFieldKey(key)}`;
                    getOptions(field, lang).forEach((opt, idx) => {
                        const option = document.createElement("option");
                        const value = idx === 0 ? "" : opt;
                        option.value = value;
                        option.textContent = opt;
                        option.selected = field.value === value;
                        input.appendChild(option);
                    });
                } else if (inputType === "attachment") {
                    input = document.createElement("div");
                    const textInput = document.createElement("input");
                    textInput.type = "text";
                    textInput.id = `${divId}-${encodeFieldKey(key)}`;
                    textInput.value = field.value || "";
                    textInput.placeholder = getLabel(
                        { label: { en: "Enter file names (comma-separated)", th: "ป้อนชื่อไฟล์ (คั่นด้วยเครื่องหมายจุลภาค)" } }, lang
                    );
                    textInput.style.width = "260px";
                    input.appendChild(textInput);
                    const fileCount = document.createElement("div");
                    fileCount.id = `${divId}-filecount-${encodeFieldKey(key)}`;
                    fileCount.style.marginTop = "5px";
                    const initialFileCount = countFiles(field);
                    fileCount.textContent = `Files: ${initialFileCount}`;
                    input.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 = () => {
                        const files = toggleUploadPanel();
                        updateFileListFromInput(`${divId}-${encodeFieldKey(key)}`);
                        const count = countFiles(schema[key]);
                        fileCount.textContent = `Files: ${count}`;
                        updateOutputJson(divId, schema);
                        updateScoreDisplay(divId, key, schema[key]);
                        updateSectionSummaries(divId, schema);
                        updateGrandSummary(divId);
                    };
                    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 = () => {
                        schema[key].value = textInput.value;
                        const count = countFiles(schema[key]);
                        fileCount.textContent = `Files: ${count}`;
                        updateOutputJson(divId, schema);
                        updateScoreDisplay(divId, key, schema[key]);
                        updateSectionSummaries(divId, schema);
                        updateGrandSummary(divId);
                    };
                    buttonDiv.appendChild(countFilesBtn);
                    input.appendChild(buttonDiv);
                } else {
                    input = document.createElement("input");
                    input.id = `${divId}-${encodeFieldKey(key)}`;
                    input.type = inputType === "string" ? "text" : inputType || "text";
                    input.value = field.value || (inputType === "number" ? 0 : "");
                    input.style.width = "260px";
                }

                fieldDiv.appendChild(input);

                const resetBtn = document.createElement("button");
                resetBtn.textContent = getLabel({ label: { en: "Reset", th: "รีเซ็ต" } }, lang);
                resetBtn.style.marginLeft = "10px";
                resetBtn.style.padding = "4px 8px";
                resetBtn.style.cursor = "pointer";
                resetBtn.onclick = () => {
                    if (inputType === "radio") {
                        schema[key].value = null;
                        document.querySelectorAll(`input[name="${divId}-${encodeFieldKey(key)}"]`).forEach((el) => {
                            el.checked = false;
                        });
                    } else if (inputType === "checkbox") {
                        schema[key].value = [];
                        document.querySelectorAll(`input[name="${divId}-${encodeFieldKey(key)}[]"]`).forEach((el) => {
                            el.checked = false;
                        });
                    } else if (inputType === "select") {
                        schema[key].value = "";
                        const selectEl = document.getElementById(`${divId}-${encodeFieldKey(key)}`);
                        selectEl.value = "";
                    } else if (inputType === "attachment") {
                        schema[key].value = "";
                        const textInput = document.getElementById(`${divId}-${encodeFieldKey(key)}`);
                        textInput.value = "";
                        const fileCount = document.getElementById(`${divId}-filecount-${encodeFieldKey(key)}`);
                        fileCount.textContent = `Files: 0`;
                    } else {
                        schema[key].value = inputType === "number" ? 0 : "";
                        const textInput = document.getElementById(`${divId}-${encodeFieldKey(key)}`);
                        textInput.value = inputType === "number" ? 0 : "";
                    }
                    updateOutputJson(divId, schema);
                    updateScoreDisplay(divId, key, schema[key]);
                    updateSectionSummaries(divId, schema);
                    updateGrandSummary(divId);
                };
                fieldDiv.appendChild(resetBtn);

                secDiv.appendChild(fieldDiv);
            }

            if (hasField) {
                const sectionSummary = document.createElement("div");
                sectionSummary.className = "section-summary";
                sectionSummary.id = `${divId}-summary-${segmentId}-${sectionId}`;
                secDiv.appendChild(sectionSummary);
                segDiv.appendChild(secDetails);
                secDetails.appendChild(secDiv);
            }
        });

        segDetails.appendChild(segDiv);
        fieldsDiv.appendChild(segDetails);
    });

    updateOutputJson(divId, schema);
    updateSectionSummaries(divId, schema);
    ssum("ssum-report", schema);
    updateGrandSummary(divId);

    const copyBtn = document.getElementById(`${divId}-copy-btn`);
    copyBtn.addEventListener("click", () => {
        const inputEl = document.getElementById(`${divId}-input`);
        try {
            const newSchema = JSON.parse(inputEl.value);
            genform(divId, newSchema);
            updateGrandSummary(divId);
        } catch (e) {
            console.error(`Invalid JSON in ${divId}-input: ${e.message}`);
            alert(getLabel({ label: { en: `Invalid JSON: ${e.message}`, th: `JSON ไม่ถูกต้อง: ${e.message}` } }, lang));
        }
    });

    listenform(divId);
    if (divId === "form-container") autosaveOnChange(divId, "schema");
    if (divId === "schema2") autosaveOnChange(divId, "schema2");
    if (divId === "schema3") autosaveOnChange(divId, "schema3");
}

       function enableFloatingSave(schemaType) {
    let btn = document.getElementById("floating-save-btn");

    // Create button if it doesn't exist
    if (!btn) {
        btn = document.createElement("button");
        btn.id = "floating-save-btn";
        btn.textContent = "Save";
        Object.assign(btn.style, {
            display: "none",
            position: "fixed",
            bottom: "20px",
            right: "20px",
            zIndex: "9999",
            padding: "10px 20px",
            background: "#007bff",
            color: "white",
            border: "none",
            borderRadius: "6px",
            boxShadow: "0 2px 5px rgba(0,0,0,0.2)",
            fontSize: "16px",
            cursor: "pointer"
        });
        document.body.appendChild(btn);
    }

    // Show button
    btn.style.display = "block";

    // Clear previous listener
    btn.onclick = null;

    // New click behavior
    btn.onclick = () => {
        saveToLocal(schemaType);
        btn.textContent = "Saved!";
        setTimeout(() => {
            hideFloatingSave();
        }, 1000);
    };
}


function hideFloatingSave() {
    const btn = document.getElementById("floating-save-btn");
    if (btn) {
        btn.style.display = "none";
        btn.textContent = "Save";
    }
}


        function SautosaveOnChange(divId, schemaType) {
    const container = document.getElementById(divId);
    if (!container) return;

    const handler = () => {
        saveToLocal(schemaType);
        console.log(`Auto-saved ${schemaType} (change/blur)`);
    };

    container.querySelectorAll("input, select, textarea").forEach(el => {
        el.addEventListener("change", handler);
        el.addEventListener("blur", handler);
    });
}
function autosaveOnChange(divId, schemaType) {
    const container = document.getElementById(divId);
    if (!container) return;

    const handler = () => {
        enableFloatingSave(schemaType);
    };

    container.querySelectorAll("input, select, textarea").forEach(el => {
        el.addEventListener("change", handler);
        el.addEventListener("blur", handler);
    });
}

function AAssum(divId, data) {
    const container = document.getElementById(divId);
    if (!container) {
        console.log(`Container not found for ssum(): ${divId}`);
        return;
    }
    const results = [];
    const lang = window.lang || "en";
    let grandTotalFields = 0, grandTotalRequired = 0, grandAnsweredRequired = 0, grandAnswered = 0;
    let grandTotalScore = 0, grandAchievedScore = 0, grandTotalFiles = 0;

    if (!data.grouping) {
        container.innerHTML = "<div>No grouping found in schema.</div>";
        return;
    }

    const segments = {};
    for (const key in data) {
        if (key === "grouping" || data[key].type === "section") continue;
        const field = data[key];
        if (!field.section) continue;
        const segment = field.segment?.[0] || data.grouping.name[0] || "default";
        if (!segments[segment]) segments[segment] = {};
        if (!segments[segment][field.section]) segments[segment][field.section] = [];
        segments[segment][field.section].push({ key, field });
    }

    for (const segment in segments) {
        const segmentLabel = data.grouping?.label?.[lang][data.grouping.name.indexOf(segment)] || segment;
        results.push(`<h3>${getLabel({ label: { en: "Segment", th: "ส่วน" } }, lang)}: ${segmentLabel}</h3>`);
        let segmentTotals = { fields: 0, required: 0, answeredRequired: 0, answered: 0, totalScore: 0, achievedScore: 0, totalFiles: 0 };

        const sections = Object.keys(segments[segment]);
        for (const section of sections) {
            const sectionLabel = getLabel(data[section], lang) || section;
            const fields = segments[segment][section];
            const totalField = fields.length;
            const totalRequired = fields.filter(({ field }) => field.required).length;
            let answeredRequired = 0, answered = 0, totalScore = 0, achievedScore = 0, totalFiles = 0;
            const unansweredFields = [], unansweredRequiredFields = [];

            fields.forEach(({ key, field }) => {
                const hasAnswer =
                    (Array.isArray(field.value) && field.value.length > 0) ||
                    (typeof field.value === "string" && field.value.trim() !== "") ||
                    (typeof field.value === "number" && field.value !== 0 && !isNaN(field.value)) ||
                    (field.data_type === "radio" && field.value !== null);

                if (hasAnswer) {
                    answered += 1;
                    if (field.required) answeredRequired += 1;
                } else {
                    unansweredFields.push({ label: getLabel(field, lang) || key, key });
                    if (field.required) unansweredRequiredFields.push({ label: getLabel(field, lang) || key, key });
                }

                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                totalScore += maxScore;
                achievedScore += currentScore;

                if (field.type === "attachment") totalFiles += countFiles(field);
            });

            const percent = totalField > 0 ? Math.round((answered / totalField) * 100) : 0;
            const requiredPercent = totalRequired > 0 ? Math.round((answeredRequired / totalRequired) * 100) : 100;

            results.push(`
                <div style="margin-left:20px;">
                    <strong>${getLabel({ label: { en: "Section", th: "หมวด" } }, lang)}: ${sectionLabel}</strong><br>
                    ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: <progress value="${percent}" max="100"></progress> ${percent}%<br>
                    ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${answered}/${totalField}<br>
                    ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${totalRequired}<br>
                    ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: <progress value="${answeredRequired}" max="${totalRequired}"></progress> ${requiredPercent}%<br>
                    ${getLabel({ label: { en: "Unanswered", th: "ยังไม่ได้ตอบ" } }, lang)}: ${
                        unansweredFields.length > 0
                            ? unansweredFields.map(({ label, key }) => 
                                  `<a href="#" onclick="scrollToField('${CSS.escape(key)}');return false;" style="color:blue;text-decoration:underline">${label}</a>`
                  ).join(", ")
                            : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                    }<br>
                    ${getLabel({ label: { en: "Required Missing", th: "จำเป็นต้องตอบ" } }, lang)}: ${
                        unansweredRequiredFields.length > 0
                            ? unansweredRequiredFields.map(({ label, key }) => 
                                  `<a href="#form-container-field-${CSS.escape(key)}" style="color:blue;text-decoration:underline">${label}</a>`
                              ).join(", ")
                            : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                    }<br>
                    ${window.debug ? `
                        ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${achievedScore}/${totalScore}<br>
                        ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${achievedScore}<br>
                    ` : ""}
                    ${totalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${totalFiles}<br>` : ""}
                </div>
            `);

            segmentTotals.fields += totalField;
            segmentTotals.required += totalRequired;
            segmentTotals.answeredRequired += answeredRequired;
            segmentTotals.answered += answered;
            segmentTotals.totalScore += totalScore;
            segmentTotals.achievedScore += achievedScore;
            segmentTotals.totalFiles += totalFiles;
        }

        // Only show "Sum Section" if the segment has multiple sections
        if (sections.length > 1) {
            const segmentPercent = segmentTotals.fields > 0 ? Math.round((segmentTotals.answered / segmentTotals.fields) * 100) : 0;
            const segmentRequiredPercent = segmentTotals.required > 0 ? Math.round((segmentTotals.answeredRequired / segmentTotals.required) * 100) : 100;

            results.push(`
                <div style="margin-left:20px;font-weight:bold;">
                    ${getLabel({ label: { en: "Sum Section", th: "สรุปหมวด" } }, lang)} — 
                    ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: ${segmentPercent}%<br>
                    ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${segmentTotals.answered}/${segmentTotals.fields}<br>
                    ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${segmentTotals.required}<br>
                    ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: ${segmentTotals.answeredRequired}/${segmentTotals.required} (${segmentRequiredPercent}%)<br>
                    ${window.debug ? `
                        ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${segmentTotals.achievedScore}/${segmentTotals.totalScore}<br>
                        ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${segmentTotals.achievedScore}<br>
                    ` : ""}
                    ${segmentTotals.totalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${segmentTotals.totalFiles}<br>` : ""}
                </div>
            `);
        }

        grandTotalFields += segmentTotals.fields;
        grandTotalRequired += segmentTotals.required;
        grandAnsweredRequired += segmentTotals.answeredRequired;
        grandAnswered += segmentTotals.answered;
        grandTotalScore += segmentTotals.totalScore;
        grandAchievedScore += segmentTotals.achievedScore;
        grandTotalFiles += segmentTotals.totalFiles;
    }

    const grandPercent = grandTotalFields > 0 ? Math.round((grandAnswered / grandTotalFields) * 100) : 0;
    const grandRequiredPercent = grandTotalRequired > 0 ? Math.round((grandAnsweredRequired / grandTotalRequired) * 100) : 100;

    results.push(`
        <h3>${getLabel({ label: { en: "Sum Segment", th: "สรุปส่วน" } }, lang)}</h3>
        ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: <progress value="${grandPercent}" max="100"></progress> ${grandPercent}%<br>
        ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${grandAnswered}/${grandTotalFields}<br>
        ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${grandTotalRequired}<br>
        ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: <progress value="${grandAnsweredRequired}" max="${grandTotalRequired}"></progress> ${grandRequiredPercent}%<br>
        ${window.debug ? `
            ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${grandAchievedScore}/${grandTotalScore}<br>
            ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${grandAchievedScore}<br>
        ` : ""}
        ${grandTotalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${grandTotalFiles}<br>` : ""}
    `);

    container.innerHTML = results.join("\n");
}
// Modified ssum to fix jump links
function ssum(divId, data) {
    const container = document.getElementById(divId);
    if (!container) {
        console.log(`Container not found for ssum(): ${divId}`);
        return;
    }
    const results = [];
    const lang = window.lang || "en";
    let grandTotalFields = 0, grandTotalRequired = 0, grandAnsweredRequired = 0, grandAnswered = 0;
    let grandTotalScore = 0, grandAchievedScore = 0, grandTotalFiles = 0;

    if (!data.grouping) {
        container.innerHTML = "<div>No grouping found in schema.</div>";
        return;
    }

    const segments = {};
    for (const key in data) {
        if (key === "grouping" || data[key].type === "section") continue;
        const field = data[key];
        if (!field.section) continue;
        const segment = field.segment?.[0] || data.grouping.name[0] || "default";
        if (!segments[segment]) segments[segment] = {};
        if (!segments[segment][field.section]) segments[segment][field.section] = [];
        segments[segment][field.section].push({ key, field });
    }

    for (const segment in segments) {
        const segmentLabel = data.grouping?.label?.[lang][data.grouping.name.indexOf(segment)] || segment;
        results.push(`<h3>${getLabel({ label: { en: "Segment", th: "ส่วน" } }, lang)}: ${segmentLabel}</h3>`);
        let segmentTotals = { fields: 0, required: 0, answeredRequired: 0, answered: 0, totalScore: 0, achievedScore: 0, totalFiles: 0 };

        const sections = Object.keys(segments[segment]);
        for (const section of sections) {
            const sectionLabel = getLabel(data[section], lang) || section;
            const fields = segments[segment][section];
            const totalField = fields.length;
            const totalRequired = fields.filter(({ field }) => field.required).length;
            let answeredRequired = 0, answered = 0, totalScore = 0, achievedScore = 0, totalFiles = 0;
            const unansweredFields = [], unansweredRequiredFields = [];

            fields.forEach(({ key, field }) => {
                const hasAnswer =
                    (Array.isArray(field.value) && field.value.length > 0) ||
                    (typeof field.value === "string" && field.value.trim() !== "") ||
                    (typeof field.value === "number" && field.value !== 0 && !isNaN(field.value)) ||
                    (field.data_type === "radio" && field.value !== null);

                if (hasAnswer) {
                    answered += 1;
                    if (field.required) answeredRequired += 1;
                } else {
                    unansweredFields.push({ label: getLabel(field, lang) || key, key });
                    if (field.required) unansweredRequiredFields.push({ label: getLabel(field, lang) || key, key });
                }

                const maxScore = calculateMaxScore(field);
                const currentScore = calculateCurrentScore(field);
                totalScore += maxScore;
                achievedScore += currentScore;

                if (field.type === "attachment") totalFiles += countFiles(field);
            });

            const percent = totalField > 0 ? Math.round((answered / totalField) * 100) : 0;
            const requiredPercent = totalRequired > 0 ? Math.round((answeredRequired / totalRequired) * 100) : 100;

            results.push(`
                <div style="margin-left:20px;">
                    <strong>${getLabel({ label: { en: "Section", th: "หมวด" } }, lang)}: ${sectionLabel}</strong><br>
                    ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: <progress value="${percent}" max="100"></progress> ${percent}%<br>
                    ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${answered}/${totalField}<br>
                    ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${totalRequired}<br>
                    ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: <progress value="${answeredRequired}" max="${totalRequired}"></progress> ${requiredPercent}%<br>
                    ${getLabel({ label: { en: "Unanswered", th: "ยังไม่ได้ตอบ" } }, lang)}: ${
                        unansweredFields.length > 0
                            ? unansweredFields.map(({ label, key }) => 
                                  `<a href="#" onclick="scrollToField('${encodeFieldKey(key)}', 'form-container');return false;" style="color:blue;text-decoration:underline">${label}</a>`
                              ).join(", ")
                            : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                    }<br>
                    ${getLabel({ label: { en: "Required Missing", th: "จำเป็นต้องตอบ" } }, lang)}: ${
                        unansweredRequiredFields.length > 0
                            ? unansweredRequiredFields.map(({ label, key }) => 
                                  `<a href="#" onclick="scrollToField('${encodeFieldKey(key)}', 'form-container');return false;" style="color:blue;text-decoration:underline">${label}</a>`
                              ).join(", ")
                            : getLabel({ label: { en: "None", th: "ไม่มี" } }, lang)
                    }<br>
                    ${window.debug ? `
                        ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${achievedScore}/${totalScore}<br>
                        ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${achievedScore}<br>
                    ` : ""}
                    ${totalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${totalFiles}<br>` : ""}
                </div>
            `);

            segmentTotals.fields += totalField;
            segmentTotals.required += totalRequired;
            segmentTotals.answeredRequired += answeredRequired;
            segmentTotals.answered += answered;
            segmentTotals.totalScore += totalScore;
            segmentTotals.achievedScore += achievedScore;
            segmentTotals.totalFiles += totalFiles;
        }

        if (sections.length > 1) {
            const segmentPercent = segmentTotals.fields > 0 ? Math.round((segmentTotals.answered / segmentTotals.fields) * 100) : 0;
            const segmentRequiredPercent = segmentTotals.required > 0 ? Math.round((segmentTotals.answeredRequired / segmentTotals.required) * 100) : 100;

            results.push(`
                <div style="margin-left:20px;font-weight:bold;">
                    ${getLabel({ label: { en: "Sum Section", th: "สรุปหมวด" } }, lang)} — 
                    ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: ${segmentPercent}%<br>
                    ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${segmentTotals.answered}/${segmentTotals.fields}<br>
                    ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${segmentTotals.required}<br>
                    ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: ${segmentTotals.answeredRequired}/${segmentTotals.required} (${segmentRequiredPercent}%)<br>
                    ${window.debug ? `
                        ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${segmentTotals.achievedScore}/${segmentTotals.totalScore}<br>
                        ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${segmentTotals.achievedScore}<br>
                    ` : ""}
                    ${segmentTotals.totalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${segmentTotals.totalFiles}<br>` : ""}
                </div>
            `);
        }

        grandTotalFields += segmentTotals.fields;
        grandTotalRequired += segmentTotals.required;
        grandAnsweredRequired += segmentTotals.answeredRequired;
        grandAnswered += segmentTotals.answered;
        grandTotalScore += segmentTotals.totalScore;
        grandAchievedScore += segmentTotals.achievedScore;
        grandTotalFiles += segmentTotals.totalFiles;
    }

    const grandPercent = grandTotalFields > 0 ? Math.round((grandAnswered / grandTotalFields) * 100) : 0;
    const grandRequiredPercent = grandTotalRequired > 0 ? Math.round((grandAnsweredRequired / grandTotalRequired) * 100) : 100;

    results.push(`
        <h3>${getLabel({ label: { en: "Sum Segment", th: "สรุปส่วน" } }, lang)}</h3>
        ${getLabel({ label: { en: "Percent Answered", th: "ตอบ %" } }, lang)}: <progress value="${grandPercent}" max="100"></progress> ${grandPercent}%<br>
        ${getLabel({ label: { en: "Total Fields", th: "จำนวนฟิลด์ทั้งหมด" } }, lang)}: ${grandAnswered}/${grandTotalFields}<br>
        ${getLabel({ label: { en: "Total Required Fields", th: "จำนวนฟิลด์ที่จำเป็นทั้งหมด" } }, lang)}: ${grandTotalRequired}<br>
        ${getLabel({ label: { en: "Required Fields Completed", th: "ฟิลด์ที่จำเป็นตอบแล้ว" } }, lang)}: <progress value="${grandAnsweredRequired}" max="${grandTotalRequired}"></progress> ${grandRequiredPercent}%<br>
        ${window.debug ? `
            ${getLabel({ label: { en: "Total Score", th: "คะแนนรวม" } }, lang)}: ${grandAchievedScore}/${grandTotalScore}<br>
            ${getLabel({ label: { en: "Achieved Score", th: "คะแนนที่ได้" } }, lang)}: ${grandAchievedScore}<br>
        ` : ""}
        ${grandTotalFiles > 0 ? `${getLabel({ label: { en: "Total Files Attached", th: "ไฟล์ที่แนบทั้งหมด" } }, lang)}: ${grandTotalFiles}<br>` : ""}
    `);

    container.innerHTML = results.join("\n");
}
        // Initialize
        window.lang = "en";
        window.debug = false;
        window.score = false;

        genform("form-container", schema);