{% comment %}
    Dashboard content partial — rendered by HtmxResponseMixin.
    For htmx sidebar navigation this is returned bare.
    For full-page loads it is injected into htmx_wrapper.html.
{% endcomment %}

{% partialdef project-experiment-card %}
{% include 'lara_django_projects/components/project_experiment_card.html' %}
{% endpartialdef project-experiment-card %}

{% partialdef projects-overview-table %}
{% include 'lara_django_projects/components/projects_overview_table.html' %}
{% endpartialdef projects-overview-table %}

{% partialdef webrtc-client %}
{% include 'lara_django_base/partials/webrtc_client.html' %}
{% endpartialdef webrtc-client %}

{# Tailwind browser-CDN theme extension for WebRTC status colours #}
<script>
    tailwind.config = {
        theme: {
            extend: {
                colors: {
                    'stream-blue': '#3b82f6',
                    'stream-green': '#10b981',
                    'stream-red': '#ef4444',
                    'stream-yellow': '#f59e0b',
                }
            }
        }
    }
</script>

<div class="mx-auto py-4 px-3 sm:px-6 lg:px-8 bg-gray-100 min-h-screen w-full">

    <details id="data-monitor" class="collapse collapse-arrow border-base-300 bg-base-200 border z-0">
        <summary class="collapse-title text-xl font-medium">data monitor</summary>
        <div class="collapse-content">
            <div class="flex justify-end mb-4">
                <a href="{% url 'lara_django_base:data_monitor_create' %}" class="btn bg-green-500 text-white mt-3">Add</a>
            </div>
            <p>here new data can be monitored</p>
        </div>
    </details>

    <!-- replace with web-rtc client -->

    <details id="device-action-monitor" class="collapse collapse-arrow border-base-300 bg-base-200 border z-0">
        <summary class="collapse-title text-xl font-medium">device action monitor</summary>
        <div class="collapse-content">
            <div class="flex">
                <iframe src="http://localhost:8085/" class="w-full lg:w-2/3 h-48 lg:h-200" title="dev mon"></iframe>
            </div>
        </div>
    </details>

    <!-- Project Carousel -->
    {% include 'lara_django_base/partials/project_carousel.html' %}

    <!-- LARA AI chat-->
    <div class="flex justify-center mt-4 text-white">
        <a href="{% url 'lara_django_base:chat' %}">
            <button class="btn bg-gray-400 rounded-full h-16 w-48">LARA AI Chat</button>
        </a>
    </div>

    <details id="projects-planning" class="collapse collapse-arrow border-base-300 bg-base-200 border m-3 z-0">
        <summary class="collapse-title text-xl font-medium flex items-center">
            <span>projects planning</span>
            <a href="{% url 'lara_django_projects:project-create' %}"
               class="inline-flex items-center btn btn-sm bg-green-500 hover:bg-green-600 text-white border-0 ml-auto mr-6"
               onclick="event.stopPropagation()">
                <span>+</span><span class="hidden md:inline">&nbsp;Add new project</span>
            </a>
        </summary>
        <div class="collapse-content">
            <div class="overflow-x-auto">
                {% with projects=projects %}
                {% with project_progress=33 %}
                {% partial projects-overview-table %}
                {% endwith %}
                {% endwith %}
            </div>
        </div>
    </details>

    <div class="mt-3">
    </div>

</div>

{# WebRTC client script — htmx executes inline scripts in swapped content #}
<script>
    const video = document.getElementById('video');
    const startButton = document.getElementById('startButton');
    const stopButton = document.getElementById('stopButton');
    const statusDiv = document.getElementById('status');

    let pc = null;

    function updateStatus(message, className) {
        statusDiv.innerHTML = '';

        // Create status indicator with appropriate styling
        const statusContent = document.createElement('div');
        statusContent.className = 'flex items-center';

        let dotColor, bgColor, textColor, borderColor;

        switch(className) {
            case 'connected':
                dotColor = 'bg-green-500';
                bgColor = 'bg-green-50';
                textColor = 'text-green-800';
                borderColor = 'border-green-200';
                break;
            case 'connecting':
                dotColor = 'bg-yellow-500 animate-pulse';
                bgColor = 'bg-yellow-50';
                textColor = 'text-yellow-800';
                borderColor = 'border-yellow-200';
                break;
            case 'disconnected':
            default:
                dotColor = 'bg-red-500 animate-pulse';
                bgColor = 'bg-red-50';
                textColor = 'text-red-800';
                borderColor = 'border-red-200';
                break;
        }

        statusDiv.className = `flex items-center justify-center py-3 px-4 rounded-lg font-medium transition-all duration-300 ${bgColor} ${textColor} border ${borderColor}`;

        statusContent.innerHTML = `
            <div class="w-2 h-2 ${dotColor} rounded-full mr-2"></div>
            ${message}
        `;

        statusDiv.appendChild(statusContent);
    }

    async function startStream() {
        try {
            updateStatus('Connecting...', 'connecting');
            startButton.disabled = true;
            startButton.classList.add('opacity-50', 'cursor-not-allowed');

            // Create RTCPeerConnection
            pc = new RTCPeerConnection({
                iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
            });

            // Handle incoming stream
            pc.ontrack = (event) => {
                console.log('Received track:', event.track.kind);
                if (event.track.kind === 'video') {
                    video.srcObject = event.streams[0];
                    updateStatus('Connected - Receiving video stream', 'connected');
                    stopButton.disabled = false;
                    stopButton.classList.remove('opacity-50', 'cursor-not-allowed');
                }
            };

            // Handle connection state changes
            pc.onconnectionstatechange = () => {
                console.log('Connection state:', pc.connectionState);
                if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
                    updateStatus('Connection failed', 'disconnected');
                    stopStream();
                }
            };

            // Handle ICE connection state changes
            pc.oniceconnectionstatechange = () => {
                console.log('ICE connection state:', pc.iceConnectionState);
                if (pc.iceConnectionState === 'connected') {
                    updateStatus('WebRTC connection established', 'connected');
                }
            };

            // Add a transceiver to receive video
            pc.addTransceiver('video', { direction: 'recvonly' });

            // Create offer
            const offer = await pc.createOffer();
            await pc.setLocalDescription(offer);

            // Send offer to server
            const response = await fetch('/offer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sdp: offer.sdp,
                    type: offer.type,
                }),
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const answer = await response.json();
            await pc.setRemoteDescription(new RTCSessionDescription(answer));

        } catch (error) {
            console.error('Error starting stream:', error);
            updateStatus('Error starting stream: ' + error.message, 'disconnected');
            startButton.disabled = false;
            startButton.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    }

    function stopStream() {
        if (pc) {
            pc.close();
            pc = null;
        }

        video.srcObject = null;
        updateStatus('Disconnected', 'disconnected');
        startButton.disabled = false;
        startButton.classList.remove('opacity-50', 'cursor-not-allowed');
        stopButton.disabled = true;
        stopButton.classList.add('opacity-50', 'cursor-not-allowed');
    }

    startButton.addEventListener('click', startStream);
    stopButton.addEventListener('click', stopStream);

    // Cleanup on page unload
    window.addEventListener('beforeunload', stopStream);

    // Auto-reconnect functionality (optional)
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 3;

    function attemptReconnect() {
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;
            updateStatus(`Reconnecting... (attempt ${reconnectAttempts}/${maxReconnectAttempts})`, 'connecting');
            setTimeout(startStream, 2000);
        } else {
            updateStatus('Maximum reconnection attempts reached', 'disconnected');
            reconnectAttempts = 0;
        }
    }

    // Initialize status
    updateStatus('Ready to connect', 'disconnected');
</script>
