<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QR Code for {{ key }}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        /* Center the QR code container */
        #qrcode {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 300px; /* Set width for the QR code container */
            height: 300px; /* Set height for the QR code container */
            margin: 0 auto; /* Horizontal centering */
        }
        /* Styling for the QR code image/canvas generated by QRCode.js */
        #qrcode img, #qrcode canvas {
            max-width: 100%;
            height: auto;
            border-radius: 0.5rem; /* Rounded corners */
            box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06); /* Inner shadow */
            border: 1px solid #e2e8f0; /* Border */
            padding: 0.5rem; /* Padding */
        }
    </style>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div class="bg-white p-8 rounded-lg shadow-md text-center max-w-sm w-full">
        <h1 class="text-2xl font-bold text-gray-800 mb-4">QR Code for: <span class="text-blue-600" id="current-name-display">{{ initial_name }}</span></h1>
        <!-- Display the link name, updated in real-time -->
        <p class="text-gray-600 mb-2">Link Name: <span class="font-medium text-gray-700">{{ key }}</span></p>
        <p class="text-gray-600 mb-6 break-words">Scan this QR code to go to: <br>
            <!-- Link to the current URL, updated in real-time -->
            <a id="current-url-link" href="{{ initial_url }}" target="_blank" class="text-blue-500 hover:underline">{{ initial_url }}</a>
        </p>
        <div class="flex justify-center mb-6">
            <!-- QR code will be rendered into this div by QRCode.js -->
            <div id="qrcode" class="w-64 h-64 rounded-lg shadow-inner border border-gray-200 p-2"></div>
        </div>
        <p class="text-sm text-gray-500">Powered by QRCode.js. Updates in real-time.</p>
        <!-- Status message for SSE connection -->
        <div id="status-message" class="text-sm text-gray-700 mt-4"></div>
    </div>

    <!-- Include QRCode.js library -->
    <script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js"></script>
    <script>
        const qrCodeContainer = document.getElementById('qrcode');
        const currentUrlLink = document.getElementById('current-url-link');
        const currentNameDisplay = document.getElementById('current-name-display'); // Get the new name display element
        const statusMessage = document.getElementById('status-message');
        const key = "{{ key }}"; // Key passed from Python template

        let qr = null; // To store QRCode.js instance

        /**
         * Function to create or update the QR code and display the URL and Name.
         * @param {string} url - The URL to encode in the QR code.
         * @param {string} name - The name associated with the URL.
         */
        function generateOrUpdateQrCode(url, name) {
            if (!url) {
                // If URL is empty, display a message and a placeholder image
                statusMessage.textContent = "URL not found for this key. Please set a URL.";
                qrCodeContainer.innerHTML = '<img src="https://placehold.co/300x300/e0e0e0/555555?text=No+URL+Set" alt="No URL set" class="w-full h-full rounded-lg shadow-inner border border-gray-200 p-2">';
                currentUrlLink.textContent = "No URL set";
                currentUrlLink.href = "#"; // Prevent navigation for empty URL
                currentNameDisplay.textContent = name || "Unnamed Link"; // Update name even if URL is empty
                return;
            }

            // Clear the container to ensure a fresh QR code on update
            qrCodeContainer.innerHTML = '';
            
            // Create or update QRCode.js instance
            qr = new QRCode(qrCodeContainer, {
                text: url,
                width: 256, // Width of the QR code
                height: 256, // Height of the QR code
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.H // Error correction level H (highest)
            });

            currentUrlLink.href = url; // Update the href attribute of the link
            currentUrlLink.textContent = url; // Update the displayed URL text
            currentNameDisplay.textContent = name || "Unnamed Link"; // Update the displayed name
            statusMessage.textContent = "QR code and details updated!";
        }

        // Generate initial QR code and display details on page load
        generateOrUpdateQrCode("{{ initial_url }}", "{{ initial_name }}");
        if ("{{ initial_url }}") {
            statusMessage.textContent = "Connected for real-time updates.";
        }

        // Set up Server-Sent Events (SSE) connection
        const eventSource = new EventSource(`/sse/${key}`);

        // Event listener for when the SSE connection is opened
        eventSource.onopen = function(event) {
            console.log("SSE connection opened.");
        };

        // Event listener for incoming messages from the SSE server
        eventSource.onmessage = function(event) {
            // Parse the JSON data received from the server
            const data = JSON.parse(event.data); 
            const newUrl = data.url;
            const newName = data.name;
            console.log("Received new URL:", newUrl, "and Name:", newName);
            // Call the function to update the QR code and display
            generateOrUpdateQrCode(newUrl, newName);
        };

        // Event listener for SSE errors
        eventSource.onerror = function(error) {
            console.error("SSE Error:", error);
            statusMessage.textContent = "Error connecting for updates. Retrying...";
            eventSource.close(); // Close existing connection on error
            // Optional: Implement a reconnect strategy here if needed
        };

        // Event listener for when the SSE connection is closed
        eventSource.onclose = function() {
            console.log("SSE connection closed.");
            statusMessage.textContent = "Connection closed. Refresh to reconnect.";
        };
    </script>
</body>
</html>
