{% extends "base_playground.html" %}

{% block content %}
<!-- ── Playground Layout ── -->
<div class="pg-layout">
    <!-- Left Panel: Controls -->
    <aside class="pg-panel">
        <div class="pg-panel-header">
            <span class="pg-icon">{{ meta.icon }}</span>
            <div>
                <h1 class="pg-title">{{ meta.title }}</h1>
                <span class="pg-badge">Playground</span>
            </div>
        </div>

        <p class="pg-description">{{ meta.description }}</p>

        <div class="pg-controls" id="controls">
            {% for p in params %}
            <div class="pg-control-group">
                <label class="pg-label" for="param-{{ p.name }}">
                    {{ p.label }}
                    {% if p.type == "slider" %}
                    <span class="pg-value" id="val-{{ p.name }}">{{ p.default }}</span>
                    {% endif %}
                </label>

                {% if p.type == "slider" %}
                <input type="range" id="param-{{ p.name }}" class="pg-slider" data-param="{{ p.name }}"
                    min="{{ p.min }}" max="{{ p.max }}" step="{{ p.step }}" value="{{ p.default }}">
                <div class="pg-range-labels">
                    <span>{{ p.min }}</span>
                    <span>{{ p.max }}</span>
                </div>

                {% elif p.type == "select" %}
                <select id="param-{{ p.name }}" class="pg-select" data-param="{{ p.name }}">
                    {% for opt in p.options %}
                    <option value="{{ opt }}" {% if opt==p.default %}selected{% endif %}>
                        {{ opt }}
                    </option>
                    {% endfor %}
                </select>
                {% endif %}
            </div>
            {% endfor %}
        </div>

        <button class="pg-reset-btn" id="resetBtn" onclick="resetParams()">
            ↺ Reset to Defaults
        </button>

        <div class="pg-panel-footer">
            <div class="theme-toggle" id="themeToggle" onclick="toggleTheme()">
                <span class="theme-toggle-icon" id="themeIcon">🌙</span>
                <span class="theme-toggle-label" id="themeLabel">Dark Mode</span>
            </div>
            <span class="version-badge">⚡ VexRay v0.1.0</span>
        </div>
    </aside>

    <!-- Right Area: Graph -->
    <main class="pg-main">
        <div class="pg-graph-wrapper">
            <div id="playground-graph" class="pg-graph"></div>
            <div class="pg-loading" id="loadingIndicator">
                <div class="pg-spinner"></div>
                Computing...
            </div>
        </div>
    </main>
</div>

<script>
    // ── Defaults & State ──
    const DEFAULTS = {{ defaults_json | safe }};
    let currentParams = { ...DEFAULTS };
    let debounceTimer = null;

    // ── Initialize Graph ──
    const initialSpec = {{ initial_graph_json | safe }};
    Plotly.newPlot('playground-graph', initialSpec.data, initialSpec.layout, { responsive: true });

    // ── Slider & Select Events ──
    document.querySelectorAll('.pg-slider, .pg-select').forEach(el => {
        const eventType = el.classList.contains('pg-slider') ? 'input' : 'change';
        el.addEventListener(eventType, function () {
            const paramName = this.dataset.param;
            let value = this.value;

            // Update displayed value for sliders
            if (this.classList.contains('pg-slider')) {
                document.getElementById('val-' + paramName).textContent = value;
                value = parseFloat(value);
            }

            currentParams[paramName] = value;

            // Debounce to avoid flooding the server
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(fetchUpdate, 150);
        });
    });

    // ── Fetch updated graph from server ──
    function fetchUpdate() {
        const loader = document.getElementById('loadingIndicator');
        loader.classList.add('visible');

        fetch('/api/compute', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(currentParams),
        })
            .then(res => res.json())
            .then(spec => {
                // Inherit theme-appropriate colors
                const theme = getTheme();
                const tpl = theme === 'dark' ? 'plotly_dark' : 'plotly_white';
                spec.layout.template = tpl;
                spec.layout.paper_bgcolor = 'rgba(0,0,0,0)';
                spec.layout.plot_bgcolor = 'rgba(0,0,0,0)';
                spec.layout.font = { color: theme === 'dark' ? '#e0e0e0' : '#333' };

                Plotly.react('playground-graph', spec.data, spec.layout, { responsive: true });
            })
            .catch(err => console.error('Compute error:', err))
            .finally(() => loader.classList.remove('visible'));
    }

    // ── Reset ──
    function resetParams() {
        currentParams = { ...DEFAULTS };
        for (const [name, val] of Object.entries(DEFAULTS)) {
            const el = document.getElementById('param-' + name);
            if (el) {
                el.value = val;
                const valSpan = document.getElementById('val-' + name);
                if (valSpan) valSpan.textContent = val;
            }
        }
        fetchUpdate();
    }

    // ── Theme ──
    function getTheme() {
        return localStorage.getItem('vexray-theme') || 'dark';
    }

    function applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        const icon = document.getElementById('themeIcon');
        const label = document.getElementById('themeLabel');
        if (icon) icon.textContent = theme === 'dark' ? '🌙' : '☀️';
        if (label) label.textContent = theme === 'dark' ? 'Dark Mode' : 'Light Mode';

        // Re-render graph with matching template
        const container = document.getElementById('playground-graph');
        if (container && container.data) {
            Plotly.relayout(container, {
                'template': theme === 'dark' ? 'plotly_dark' : 'plotly_white',
                'paper_bgcolor': 'rgba(0,0,0,0)',
                'plot_bgcolor': 'rgba(0,0,0,0)',
                'font.color': theme === 'dark' ? '#e0e0e0' : '#333',
                'xaxis.gridcolor': theme === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',
                'yaxis.gridcolor': theme === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',
            });
        }
    }

    function toggleTheme() {
        const next = getTheme() === 'dark' ? 'light' : 'dark';
        localStorage.setItem('vexray-theme', next);
        applyTheme(next);
    }

    applyTheme(getTheme());
</script>
{% endblock %}