{% extends 'admin/base.html' %}

{% load static %}
{% load unfold %}
{% load django_cfg %}
{% load streamlit_admin %}

{% block extrahead %}
    {{ block.super }}
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="{% static 'admin/css/dashboard.css' %}">

    {# JWT Token Injection for localStorage (backup) #}
    {% if user.is_authenticated %}
    <script>
    (function() {
        try {
            {% generate_jwt_tokens as jwt_tokens %}
            localStorage.setItem('auth_token', '{{ jwt_tokens.access }}');
            localStorage.setItem('refresh_token', '{{ jwt_tokens.refresh }}');
        } catch (e) {
            console.error('[Django Admin] Failed to inject JWT tokens:', e);
        }
    })();
    </script>
    {% endif %}

    <style>
        /* Make content container full height and full width */
        #content {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        /* Remove container centering and width limits */
        #content.container,
        #content.mx-auto,
        #content .mx-auto {
            margin-left: 0 !important;
            margin-right: 0 !important;
            max-width: none !important;
        }

        /* Also remove from unfold container component and make it full height */
        #content > .mx-auto {
            margin-left: 0 !important;
            margin-right: 0 !important;
            max-width: none !important;
            height: 100%;
        }

        /* Remove horizontal padding on mobile for @container */
        @media (max-width: 768px) {
            div[class*="@container"].px-4 {
                padding-left: 0 !important;
                padding-right: 0 !important;
            }
        }

        /* Make Alpine tabs wrapper full height */
        #content [x-data] {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        /* Make tab content blocks full height */
        #content [x-data] > div[x-show] {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .dashboard-iframe {
            width: 100%;
            height: 100%;
            border: none;
            display: block;
            visibility: visible;
            opacity: 1;
        }

        .dashboard-iframe.loaded {
            /* No additional changes needed - iframe is already visible */
        }

        .iframe-container {
            position: relative;
            background: transparent;
            flex: 1;
            display: flex;
            flex-direction: column;
            border: 1px solid rgba(209, 213, 219, 0.2);
            border-radius: 0.375rem; /* rounded-md */
            overflow: hidden;
            min-height: 400px;
        }

        /* On mobile, use more screen space */
        @media (max-width: 768px) {
            .iframe-container {
                min-height: calc(100vh - 200px);
            }
        }

        .dark .iframe-container {
            border-color: rgba(75, 85, 99, 0.2);
        }

        .iframe-loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            z-index: 1;
            /* Hide Django loading indicator - Next.js preloader handles loading state */
            display: none !important;
        }

        .iframe-loading.hidden {
            display: none;
        }

        .spinner {
            width: 48px;
            height: 48px;
            border: 4px solid #e5e7eb;
            border-top-color: #3b82f6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* Hide elements when Alpine x-cloak is active */
        [x-cloak] { display: none !important; }
    </style>
{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block coltype %}{% endblock %}

{% block title %}
    {% if subtitle %}{{ subtitle }} | {% endif %}
    {{ title }} | {{ site_title|default:'Django site admin' }}
{% endblock %}

{% block branding %}
    {% include "unfold/helpers/site_branding.html" %}
{% endblock %}

{% block content %}
    <!-- Main Container -->
    {% component "unfold/components/container.html" %}
        {% has_streamlit_admin as streamlit_enabled %}

        <div x-data="{
            openInNewWindow() {
                const iframe = document.getElementById('streamlit-dashboard-iframe');
                if (!iframe) return;
                let url = iframe.src || iframe.getAttribute('data-original-src');
                if (url) {
                    window.open(url, '_blank', 'noopener,noreferrer');
                }
            }
        }">
            {% version_update_info as version %}
            {% if version.update_available %}
            <!-- Package Update Available Banner -->
            <a href="{{ version.update_url }}"
               target="_blank"
               rel="noopener noreferrer"
               class="block bg-white dark:bg-base-900 border border-base-200 dark:border-base-700 hover:border-primary-300 dark:hover:border-primary-700 rounded-md p-3 mb-3 transition-colors cursor-pointer">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <span class="material-icons text-amber-500" style="font-size: 20px;">system_update</span>
                        <div>
                            <div class="text-font-default-light dark:text-font-default-dark text-sm font-medium">
                                New django-cfg version available
                            </div>
                            <div class="text-font-subtle-light dark:text-font-subtle-dark text-xs mt-0.5">
                                {{ version.current_version }} → <span class="text-green-600 dark:text-green-500 font-medium">{{ version.latest_version }}</span>
                                <span class="mx-1.5">•</span>
                                <code class="bg-base-100 dark:bg-base-800 px-1 py-0.5 rounded font-mono">poetry add django-cfg@latest</code>
                            </div>
                        </div>
                    </div>
                    <span class="material-icons text-font-subtle-light dark:text-font-subtle-dark" style="font-size: 18px;">open_in_new</span>
                </div>
            </a>
            {% endif %}

            <!-- Header Bar -->
            <div class="border-b border-gray-300 dark:border-gray-600" style="border-bottom-color: rgba(209, 213, 219, 0.2);">
                <style>
                    .dark [style*="border-bottom-color"] {
                        border-bottom-color: rgba(75, 85, 99, 0.2) !important;
                    }
                </style>
                <div class="flex items-center justify-between px-4">
                    <div class="flex items-center gap-2 py-4">
                        <span class="material-icons text-base text-primary-600 dark:text-primary-500">dashboard</span>
                        <span class="font-medium text-sm text-gray-700 dark:text-gray-300">{% streamlit_admin_tab_title %}</span>
                    </div>

                    <!-- Actions & Version -->
                    <div class="flex items-center gap-2 md:gap-4 py-4">
                        <!-- Open in new window button -->
                        <button @click="openInNewWindow()"
                                title="Open in new window"
                                class="flex items-center gap-1.5 px-2 md:px-3 py-1.5 text-xs font-medium rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-700 transition-all duration-150 whitespace-nowrap">
                            <span class="material-icons" style="font-size: 16px;">open_in_new</span>
                            <span class="hidden sm:inline">Open in New Window</span>
                        </button>

                        <!-- Version info -->
                        <a href="https://pypi.org/project/django-cfg/"
                           target="_blank"
                           rel="noopener noreferrer"
                           class="text-xs font-medium text-gray-600 hover:text-primary-600 dark:text-gray-400 dark:hover:text-primary-500 transition-colors duration-150 whitespace-nowrap">
                            {% lib_name %}
                        </a>
                    </div>
                </div>
            </div>

            <!-- Streamlit Dashboard Content -->
            {% if streamlit_enabled %}
            {% streamlit_admin_iframe_url_with_token as streamlit_url %}
            <div class="iframe-container">
                <div class="iframe-loading" id="iframe-loading-streamlit">
                    <div class="spinner"></div>
                    <p>Loading Streamlit...</p>
                </div>

                <iframe
                    id="streamlit-dashboard-iframe"
                    class="dashboard-iframe"
                    src="{{ streamlit_url }}"
                    data-original-src="{{ streamlit_url }}"
                    title="{% streamlit_admin_tab_title %}"
                    sandbox="{% streamlit_admin_iframe_sandbox %}"
                    onload="this.classList.add('loaded'); document.getElementById('iframe-loading-streamlit').classList.add('hidden');"
                ></iframe>
            </div>
            {% else %}
            <!-- Streamlit Not Configured -->
            <div class="flex items-center justify-center h-96 bg-gray-50 dark:bg-base-900 rounded-md border border-gray-200 dark:border-gray-700">
                <div class="text-center">
                    <span class="material-icons text-4xl text-gray-400 dark:text-gray-600 mb-4">dashboard_customize</span>
                    <h3 class="text-lg font-medium text-gray-700 dark:text-gray-300 mb-2">Streamlit Admin Not Configured</h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400 max-w-md">
                        Configure Streamlit admin in your DjangoConfig to enable the dashboard.
                    </p>
                    <pre class="mt-4 text-left bg-gray-100 dark:bg-base-800 p-4 rounded-md text-xs text-gray-600 dark:text-gray-400 overflow-x-auto"><code>from django_cfg import DjangoConfig
from django_cfg.modules.streamlit_admin import StreamlitAdminConfig

config = DjangoConfig(
    streamlit_admin=StreamlitAdminConfig(
        app_path="admin_app",
    ),
)</code></pre>
                </div>
            </div>
            {% endif %}
        </div>
    {% endcomponent %}
{% endblock %}

{% block footer %}
    {{ block.super }}
    {# Streamlit uses query param token injection - no postMessage needed #}
{% endblock %}
