<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EnLinea365 - Visor JSON Expandible y Formateado (MLR 2002)</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        textarea {
            width: 100%;
            height: 200px;
            box-sizing: border-box;
            font-family: monospace;
            margin: 10px 0;
        }
        .json-container {
            font-family: monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
        }
        .key {
            font-weight: bold;
            color: blue;
            background-color: yellow;
            padding: 2px 4px;
            border-radius: 4px;
        }
        .value {
            color: white;
            background-color: green;
            padding: 2px 4px;
            border-radius: 4px;
        }
        .expandable {
            cursor: pointer;
        }
        .collapsed > .content {
            display: none;
        }
        .collapsed::before {
            content: "▶ ";
        }
        .expanded::before {
            content: "▼ ";
        }
        .no-data {
            background-color: red;
            color: white;
            padding: 2px 5px;
            border-radius: 4px;
            font-size: 12px;
            margin-left: 10px;
        }
        .highlight {
            background-color: rgba(255, 255, 0, 0.3); /* Resalta en amarillo */
        }
    </style>
</head>
<body>
    <h1>EnLinea365 - Visor JSON Expandible y Formateado (MLR 2002)</h1>
    <p>Pega tu JSON en el cuadro de texto para verlo formateado y con nodos expandibles.</p>

    <textarea id="inputJson" placeholder="Pega tu JSON aquí..."></textarea>
    <div id="outputJson" class="json-container"></div>

    <h2>JSON Formateado:</h2>
    <textarea id="formattedJson" placeholder="JSON formateado se mostrará aquí..." readonly></textarea>

    <script>
        const inputJson = document.getElementById("inputJson");
        const outputJson = document.getElementById("outputJson");
        const formattedJson = document.getElementById("formattedJson");

        inputJson.addEventListener("input", () => {
            const rawJson = inputJson.value.trim();
            try {
                const parsedJson = JSON.parse(rawJson);
                outputJson.innerHTML = ""; // Limpia el contenido previo
                renderJson(parsedJson, outputJson, 0);
                formattedJson.value = JSON.stringify(parsedJson, null, 2); // Formato legible
            } catch (error) {
                outputJson.innerHTML = "<p style='color: red;'>⚠️ JSON no válido</p>";
                formattedJson.value = ""; // Limpiar el formato cuando hay error
            }
        });

        function renderJson(obj, container, indentLevel) {
            if (typeof obj !== "object" || obj === null) {
                const valueSpan = document.createElement("span");
                valueSpan.classList.add("value");
                valueSpan.textContent = JSON.stringify(obj);
                container.appendChild(valueSpan);
                return;
            }

            Object.keys(obj).forEach(key => {
                const value = obj[key];
                const keyElement = document.createElement("div");
                keyElement.style.marginLeft = `${indentLevel * 20}px`;

                if (typeof value === "object" && value !== null) {
                    keyElement.classList.add("expandable", "collapsed");
                    keyElement.innerHTML = `<span class="key">${key}</span>: `;
                    const content = document.createElement("div");
                    content.classList.add("content");
                    renderJson(value, content, indentLevel + 1);
                    keyElement.appendChild(content);

                    keyElement.addEventListener("click", (e) => {
                        if (e.target === keyElement || e.target.classList.contains("key")) {
                            keyElement.classList.toggle("collapsed");
                            keyElement.classList.toggle("expanded");
                        }
                        // Resaltar el campo correspondiente en el JSON de origen
                        highlightJsonInSource(key, value);
                    });
                } else {
                    keyElement.innerHTML = `<span class="key">${key}</span>: <span class="value">${JSON.stringify(value)}</span>`;

                    // Si el valor es vacío, agregar la etiqueta "sin datos"
                    if (value === "") {
                        const noDataTag = document.createElement("span");
                        noDataTag.classList.add("no-data");
                        noDataTag.textContent = "sin datos";
                        keyElement.appendChild(noDataTag);
                    }

                    keyElement.addEventListener("click", () => {
                        // Resaltar el campo correspondiente en el JSON de origen
                        highlightJsonInSource(key, value);
                    });
                }

                container.appendChild(keyElement);
            });
        }

        // Resalta el campo correspondiente en el JSON de origen
        function highlightJsonInSource(key, value) {
            const rawJson = inputJson.value;
            const regex = new RegExp(`"${key}":\\s*(${JSON.stringify(value)})`, 'g');
            const highlightedJson = rawJson.replace(regex, (match) => {
                return `<span class="highlight">${match}</span>`;
            });

            // Mostrar el JSON resaltado en el textarea original
            inputJson.innerHTML = highlightedJson;
        }
    </script>
</body>
</html>
