{% extends "base.html" %}

{% block title %}Devices Submitted{% endblock %}

{% block content %}
<h1>Devices Submitted Successfully!</h1>

<!-- Toggle button for raw JSON -->
<button id="toggle-raw-btn" class="secondary-btn">Show Raw JSON</button>

<!-- Collapsible devices container -->
<div id="devices-container" class="submitted-devices"></div>

<!-- Raw JSON -->
<pre id="raw-json" class="raw-json" style="display:none;"></pre>

<p id="raw-json-msg" class="raw-json-msg" style="display:none;">
    You are viewing the raw JSON. You can copy it for backup or import.
</p>

<!-- Buttons -->
<div class="json-buttons">
    <button id="copy-json-btn" class="secondary-btn danger">
        Copy JSON
    </button>

    <button id="download-json-btn" class="secondary-btn">
        Download JSON
    </button>
</div>

<a href="{{ url_for('setup.setup_log') }}" class="back-link">← Back to setup</a>
{% endblock %}

{% block scripts %}
{{ super() }}

<script>
const data = {{ data | safe }};

/* =====================================================
   COLLAPSIBLE DEVICES
===================================================== */
function createDeviceSection(device, index) {
    const container = document.createElement("div");
    container.className = "submitted-device";

    const header = document.createElement("button");
    header.className = "device-header";
    header.textContent = `Device ${index + 1}: ${device.device_name}`;

    const details = document.createElement("div");
    details.className = "submitted-device-details";
    details.style.display = "block";

    const infoList = document.createElement("ul");
    [
        "device_guid",
        "num_sensors",
        "device_info",
        "device_type",
        "device_location",
        "device_active",
        "connection"
    ].forEach(key => {
        const li = document.createElement("li");
        li.textContent = `${key}: ${device[key]}`;
        infoList.appendChild(li);
    });
    details.appendChild(infoList);

    /* ---------- Sensors ---------- */
    if (device.sensors && device.sensors.length > 0) {
        device.sensors.forEach((sensor, idx) => {
            const sensorWrapper = document.createElement("div");
            sensorWrapper.className = "submitted-sensor";

            const sensorHeader = document.createElement("button");
            sensorHeader.className = "sensor-header";
            sensorHeader.textContent = `Sensor ${idx + 1}: ${sensor.sens_name}`;

            const sensorDetails = document.createElement("div");
            sensorDetails.className = "submitted-sensor-details";
            sensorDetails.style.display = "none";

            const sensorList = document.createElement("ul");
            ["measures","returns","calib","range","info","comments"].forEach(key => {
                const li = document.createElement("li");
                li.textContent = `${key}: ${sensor[key]}`;
                sensorList.appendChild(li);
            });

            sensorDetails.appendChild(sensorList);

            sensorHeader.addEventListener("click", () => {
                sensorDetails.style.display =
                    sensorDetails.style.display === "none" ? "block" : "none";
            });

            sensorWrapper.appendChild(sensorHeader);
            sensorWrapper.appendChild(sensorDetails);
            details.appendChild(sensorWrapper);
        });
    }

    header.addEventListener("click", () => {
        details.style.display = details.style.display === "none" ? "block" : "none";
    });

    container.appendChild(header);
    container.appendChild(details);
    return container;
}

/* Render devices */
const devicesContainer = document.getElementById("devices-container");
data.devices.forEach((device, idx) => {
    devicesContainer.appendChild(createDeviceSection(device, idx));
});

/* =====================================================
   RAW JSON VIEW
===================================================== */
const toggleBtn = document.getElementById("toggle-raw-btn");
const rawJsonPre = document.getElementById("raw-json");
const rawJsonMsg = document.getElementById("raw-json-msg");
const copyBtn = document.getElementById("copy-json-btn");
const downloadBtn = document.getElementById("download-json-btn");

/* Syntax highlighting */
function syntaxHighlight(json) {
    if (typeof json !== "string") json = JSON.stringify(json, null, 2);
    json = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    return json.replace(
        /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|\b(true|false|null)\b|\b\d+\.?\d*\b)/g,
        match => {
            let cls = "number";
            if (/^"/.test(match)) cls = /:$/.test(match) ? "key" : "string";
            else if (/true|false/.test(match)) cls = "boolean";
            else if (/null/.test(match)) cls = "null";
            return `<span style="${getStyle(cls)}">${match}</span>`;
        }
    );
}

function getStyle(cls) {
    switch (cls) {
        case "key": return "color:#fca5a5;font-weight:bold;";
        case "string": return "color:#86efac;";
        case "number": return "color:#93c5fd;";
        case "boolean": return "color:#c4b5fd;font-weight:bold;";
        case "null": return "color:#f87171;font-style:italic;";
        default: return "";
    }
}

rawJsonPre.innerHTML = syntaxHighlight(data);

/* Toggle raw JSON view */
toggleBtn.addEventListener("click", () => {
    const showingRaw = rawJsonPre.style.display === "block";

    rawJsonPre.style.display = showingRaw ? "none" : "block";
    rawJsonMsg.style.display = showingRaw ? "none" : "block";
    devicesContainer.style.display = showingRaw ? "block" : "none";

    toggleBtn.textContent = showingRaw
        ? "Show Raw JSON"
        : "Show Collapsible View";
});

/* =====================================================
   COPY JSON
===================================================== */
copyBtn.addEventListener("click", () => {
    const jsonStr = JSON.stringify(data, null, 2);

    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(jsonStr)
            .then(() => copyBtn.textContent = "Copied ✓")
            .catch(() => fallbackCopy(jsonStr));
    } else {
        fallbackCopy(jsonStr);
    }

    setTimeout(() => copyBtn.textContent = "Copy JSON", 1500);
});

function fallbackCopy(text) {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
}

/* =====================================================
   DOWNLOAD JSON
===================================================== */
downloadBtn.addEventListener("click", () => {
    const jsonStr = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonStr], { type: "application/json" });
    const url = URL.createObjectURL(blob);

    const a = document.createElement("a");
    a.href = url;
    a.download = "device_info.json";
    document.body.appendChild(a);
    a.click();

    document.body.removeChild(a);
    URL.revokeObjectURL(url);
});
</script>

<style>
.submitted-device, .submitted-sensor {
    border: 1px solid #ddd;
    padding: 0.75rem;
    margin-bottom: 0.5rem;
    border-radius: 6px;
}

.device-header, .sensor-header {
    display: block;
    width: 100%;
    text-align: left;
    background: #f3f3f3;
    border: none;
    padding: 0.5rem;
    cursor: pointer;
    font-weight: bold;
    border-radius: 4px;
    margin-bottom: 0.25rem;
}

.submitted-device-details, .submitted-sensor-details {
    padding-left: 1rem;
}
</style>
{% endblock %}