{% if value.data %}
    <div id="grafl-{{ value.uuid }}" class="grafl-container"></div>

    {{ value.data|json_script:value.uuid }}

    <script>
        function resizeIframe(obj) {
            obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
        }

        function callGrafl() {
            const container = document.getElementById('grafl-{{ value.uuid }}');
            const data = JSON.stringify(JSON.parse(document.getElementById('{{ value.uuid }}').textContent));
            const xhr = new XMLHttpRequest();

            xhr.open('POST', 'https://grafl.io/api/');
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status === 200) {
                    container.innerHTML = `<iframe id="iframe-{{ value.uuid }}" title="Plot" src="about:blank" frameBorder="0" scrolling="no" width="100%" onload="resizeIframe(this)"></iframe>`;

                    const iframe = container.children[0];
                    iframe.contentWindow.document.open();
                    iframe.contentWindow.document.write(xhr.responseText);
                    iframe.contentWindow.document.close();
                }
            }

            // Check if we have IntersectionObserver available
            if ('IntersectionObserver' in window) {
                const intersectionCallback = function(entries, observer) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            observer.disconnect();
                            xhr.send(data);
                        }
                    });
                };

                const options = {threshold: 0};
                const observer = new IntersectionObserver(intersectionCallback, options);
                observer.observe(container);
            } else {
                xhr.send(data);
            }
        }
        callGrafl();
    </script>
{% endif %}
