<!DOCTYPE html>
<html lang="en" data-theme="dark">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Flock UI{% endblock %}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css" />
    <!-- Split modular CSS files -->
    <link rel="stylesheet"
      href="{{ url_for('static', path='css/layout.css') }}">
    <link rel="stylesheet"
        href="{{ url_for('static', path='css/header.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', path='css/sidebar.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', path='css/components.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', path='css/chat.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', path='css/two-pane.css') }}">
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <!-- Prism.js CSS for syntax highlighting (okaidia theme) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-okaidia.min.css" referrerpolicy="no-referrer" />
    {# Inject Theme CSS Variables #}
    {% if theme_css and theme_css.strip() %}
    <style>
        /* Start Theme CSS */
        {{ theme_css | safe }}
        /* End Theme CSS */
    </style>
    {% endif %}
    {# End Theme CSS Injection #}
    <script src="https://unpkg.com/htmx.org@1.9.10"
        integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC"
        crossorigin="anonymous"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <!-- Prism.js JS (core and autoloader) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js" referrerpolicy="no-referrer"></script>
    <!-- Removed inline styles as they're in custom.css -->
</head>

<body>
    <div id="global-toast-container" style="position: fixed; top: 1rem; right: 1rem; z-index: 9999; display: flex; flex-direction: column; gap: 0.5rem;">
        <!-- Toasts will be appended here -->
    </div>

    <header class="top-header">
        <span><strong>🐧 Flock Playground 🐤</strong></span>        <span id="header-flock-status-container" hx-get="{{ url_for('htmx_get_header_flock_status') }}?ui_mode={{ ui_mode }}"
            hx-trigger="load, flockLoaded from:body, flockCleared from:body" hx-swap="innerHTML">
            <small>Loading status...</small> {# Placeholder while loading #}
        </span>
    </header>    <aside class="sidebar" hx-get="{{ url_for('htmx_get_sidebar') }}?ui_mode={{ ui_mode }}"
        hx-trigger="load, flockLoaded from:body, flockListChanged from:body" hx-swap="innerHTML">
        <p>Loading navigation...</p><progress></progress>
    </aside>

    <main class="main-content" id="main-content-area">
        {# Initial content is now loaded via HTMX based on the route #}
        <div hx-get="{{ initial_content_url }}" hx-trigger="load" hx-swap="innerHTML">
            <p>Loading content...</p><progress></progress>
        </div>
        {# Render block content if navigating directly and template extends base #}
        {% block content %}{% endblock %}
    </main>

    <div class="message-container" x-data="messageHandler(
            {{ success_message | tojson | safe if success_message else 'null' }},
            {{ error_message | tojson | safe if error_message else 'null' }}
         )">
        <template x-if="showSuccess && successMsg">
            <div class="success" role="alert" @click="showSuccess = false" style="cursor: pointer;">
                <span x-text="successMsg"></span>
                <button type="button" class="close" aria-label="Dismiss">×</button>
            </div>
        </template>
        <template x-if="showError && errorMsg">
            <div class="error" role="alert" @click="showError = false" style="cursor: pointer;">
                <span x-text="errorMsg"></span>
                <button type="button" class="close" aria-label="Dismiss">×</button>
            </div>
        </template>
    </div>

    <footer class="main-footer" data-expanded="false" data-maximized="false">
        <div class="footer-bar">
            <small class="footer-meta">Built with FastAPI, HTMX, Pico.CSS by 🤍 white duck 🦆 - Theme: {{ active_theme_name | default('default') }}</small>
            <button id="live-log-toggle" class="live-log-toggle-link" type="button" aria-expanded="false" aria-controls="live-log-panel">
                Show logs
            </button>
        </div>
        <div class="live-log-wrapper" hidden>
            <div class="live-log-header">
                <div class="live-log-title-group">
                    <span class="live-log-title">Live CLI Logs</span>
                    <span class="live-log-hint">Mirrors recent stdout/stderr output</span>
                </div>
                <div class="live-log-actions">
                    <form id="live-log-filter-form" class="live-log-filter" onsubmit="return false;">
                        <label class="live-log-option">
                            <input type="checkbox" name="hide_polling" value="1" checked>
                            Hide poll requests
                        </label>
                    </form>
                    <label class="live-log-option" for="live-log-autoscroll">
                        <input type="checkbox" id="live-log-autoscroll" checked>
                        Auto-scroll
                    </label>
                    <div class="live-log-buttons">
                        <button id="live-log-copy" type="button" class="live-log-action-button" title="Copy visible logs" aria-label="Copy logs to clipboard">
                            Copy
                        </button>
                        <button id="live-log-maximize" type="button" class="live-log-action-button" aria-pressed="false">
                            Maximize
                        </button>
                    </div>
                </div>
            </div>
            <div
                id="live-log-panel"
                class="live-log-panel"
                hx-get="{{ url_for('htmx_live_cli_logs') }}"
                hx-trigger="refresh"
                hx-swap="innerHTML"
                hx-target="this"
                hx-include="#live-log-filter-form"
            >
                <div class="live-log-empty">Collecting CLI output...</div>
            </div>
        </div>
    </footer>

    <script>
        function messageHandler(initialSuccessMsg, initialErrorMsg) {
            return {
                showSuccess: !!initialSuccessMsg,
                showError: !!initialErrorMsg,
                successMsg: initialSuccessMsg,
                errorMsg: initialErrorMsg,
                init() {
                    if (this.successMsg) { setTimeout(() => this.showSuccess = false, 5000); }
                    if (this.errorMsg) { setTimeout(() => this.showError = false, 7000); }

                    window.addEventListener('notify', event => {
                        if (event.detail.type === 'success') {
                            this.successMsg = event.detail.message;
                            this.showSuccess = true; this.showError = false;
                            setTimeout(() => this.showSuccess = false, 5000);
                        }
                        if (event.detail.type === 'error') {
                            this.errorMsg = event.detail.message;
                            this.showError = true; this.showSuccess = false;
                            setTimeout(() => this.showError = false, 7000);
                        }
                    });
                }
            };
        }
        function triggerEvent(eventName, detail = {}) {
            htmx.trigger(document.body, eventName, detail);
        }

        // Add HTMX event listener for Prism highlighting
        document.addEventListener('htmx:afterSwap', function(event) {
            // Check if the swapped element or its parent is the main content area or results display
            const mainContentArea = document.getElementById('main-content-area');
            const resultsDisplay = document.getElementById('results-display-content');
            let targetElement = event.detail.target;

            if (targetElement === mainContentArea || (resultsDisplay && resultsDisplay.contains(targetElement)) || (mainContentArea && mainContentArea.contains(targetElement))) {
                if (typeof Prism !== 'undefined') {
                    // console.log('Prism highlighting triggered for swapped content in main area.');
                    Prism.highlightAllUnder(mainContentArea || document.documentElement); 
                }
            }
        });

        // Initial highlight on page load
        document.addEventListener('DOMContentLoaded', () => {
            if (typeof Prism !== 'undefined') {
                // console.log('Prism initial highlighting.');
                Prism.highlightAll();
            }
        });
    </script>
    {# Global Toast Handler - identical to the one in chat.html #}
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var footer = document.querySelector('.main-footer');
            var toggleBtn = document.getElementById('live-log-toggle');
            var wrapper = footer ? footer.querySelector('.live-log-wrapper') : null;
            var panel = document.getElementById('live-log-panel');
            var filterForm = document.getElementById('live-log-filter-form');
            var autoScrollCheckbox = document.getElementById('live-log-autoscroll');
            var maximizeBtn = document.getElementById('live-log-maximize');
            var copyBtn = document.getElementById('live-log-copy');
            var AUTO_SCROLL_STORAGE_KEY = 'flock.liveLogs.autoScroll';
            var storageAvailable = false;

            try {
                if (window.localStorage) {
                    var probeKey = '__flock_live_log_probe__';
                    localStorage.setItem(probeKey, '1');
                    localStorage.removeItem(probeKey);
                    storageAvailable = true;
                }
            } catch (err) {
                storageAvailable = false;
            }

            if (!footer || !toggleBtn || !wrapper || !panel) {
                return;
            }

            var collapsedTrigger = 'refresh';
            var expandedTrigger = 'refresh, every 2s, change from:#live-log-filter-form';

            if (autoScrollCheckbox && storageAvailable) {
                var stored = localStorage.getItem(AUTO_SCROLL_STORAGE_KEY);
                if (stored === 'true' || stored === 'false') {
                    autoScrollCheckbox.checked = stored === 'true';
                }
            }

            function updateLayout(expanded) {
                if (!expanded) {
                    updateMaximize(false);
                }

                footer.classList.toggle('expanded', expanded);
                document.body.classList.toggle('logs-expanded', expanded);
                footer.dataset.expanded = expanded ? 'true' : 'false';
                toggleBtn.setAttribute('aria-expanded', String(expanded));
                toggleBtn.textContent = expanded ? 'Hide logs' : 'Show logs';
                wrapper.hidden = !expanded;
                panel.setAttribute('hx-trigger', expanded ? expandedTrigger : collapsedTrigger);

                if (window.htmx) {
                    if (typeof window.htmx.stopPolling === 'function') {
                        window.htmx.stopPolling(panel);
                    }
                    if (expanded) {
                        window.htmx.process(panel);
                        window.htmx.trigger(panel, 'refresh');
                    }
                }
            }

            function updateMaximize(maximized) {
                footer.classList.toggle('maximized', maximized);
                document.body.classList.toggle('logs-maximized', maximized);
                footer.dataset.maximized = maximized ? 'true' : 'false';
                if (maximizeBtn) {
                    maximizeBtn.setAttribute('aria-pressed', String(maximized));
                    maximizeBtn.textContent = maximized ? 'Minimize' : 'Maximize';
                }

                if (maximized) {
                    if (!footer.classList.contains('expanded')) {
                        updateLayout(true);
                    }

                    requestAnimationFrame(function () {
                        if (!autoScrollCheckbox || autoScrollCheckbox.checked) {
                            panel.scrollTop = panel.scrollHeight;
                        }
                    });
                }
            }

            updateLayout(false);

            toggleBtn.addEventListener('click', function () {
                var expanded = !footer.classList.contains('expanded');
                updateLayout(expanded);
            });

            if (maximizeBtn) {
                maximizeBtn.addEventListener('click', function () {
                    var maximized = footer.classList.contains('maximized');
                    updateMaximize(!maximized);
                });
            }

            if (copyBtn && navigator.clipboard && navigator.clipboard.writeText) {
                copyBtn.addEventListener('click', function () {
                    var text = panel.innerText.trim();
                    if (!text) {
                        return;
                    }

                    navigator.clipboard.writeText(text).then(function () {
                        if (typeof triggerEvent === 'function') {
                            triggerEvent('showGlobalToast', { type: 'success', message: 'Logs copied to clipboard.' });
                        } else {
                            document.body.dispatchEvent(new CustomEvent('showGlobalToast', { detail: { type: 'success', message: 'Logs copied to clipboard.' } }));
                        }
                    }).catch(function () {
                        document.body.dispatchEvent(new CustomEvent('showGlobalToast', { detail: { type: 'error', message: 'Unable to copy logs.' } }));
                    });
                });
            } else if (copyBtn) {
                copyBtn.disabled = true;
                copyBtn.title = 'Clipboard API unavailable in this browser.';
            }

            if (autoScrollCheckbox && storageAvailable) {
                autoScrollCheckbox.addEventListener('change', function () {
                    localStorage.setItem(AUTO_SCROLL_STORAGE_KEY, String(autoScrollCheckbox.checked));
                });
            }

            if (window.htmx) {
                document.body.addEventListener('htmx:afterSwap', function (event) {
                    if (event.target === panel) {
                        if (!autoScrollCheckbox || autoScrollCheckbox.checked) {
                            panel.scrollTop = panel.scrollHeight;
                        }
                    }
                });
            }

            if (filterForm) {
                filterForm.addEventListener('change', function () {
                    if (window.htmx && footer.classList.contains('expanded')) {
                        window.htmx.trigger(panel, 'refresh');
                    }
                });
            }
        });
    </script>
    <script>
        document.body.addEventListener('showGlobalToast', function (event) {
            const detail = event.detail;
            const message = detail.message || 'Done!';
            const type = detail.type || 'info'; // success, error, warning, info

            const toastContainer = document.getElementById('global-toast-container');
            if (!toastContainer) return;

            const toast = document.createElement('article');
            toast.className = `toast-message ${type}`;
            toast.innerHTML = `<button class="close-toast" style="float: right; background: none; border: none; font-size: 1.2rem; line-height: 1; padding: 0.25rem 0.5rem; cursor: pointer;">&times;</button>${message}`;
            
            toast.style.padding = '0.75rem';
            toast.style.border = '1px solid';
            toast.style.borderRadius = 'var(--pico-border-radius, 4px)';
            toast.style.minWidth = '250px';
            toast.style.maxWidth = '400px';
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.3s ease-in-out, transform 0.3s ease-in-out';
            toast.style.transform = 'translateX(100%)';

            if (type === 'success') {
                toast.style.borderColor = 'var(--pico-color-green-500, green)';
                toast.style.backgroundColor = 'var(--pico-color-green-150, #e6fffa)';
                toast.style.color = 'var(--pico-color-green-700, darkgreen)';
            } else if (type === 'error') {
                toast.style.borderColor = 'var(--pico-color-red-500, red)';
                toast.style.backgroundColor = 'var(--pico-color-red-150, #ffe6e6)';
                toast.style.color = 'var(--pico-color-red-700, darkred)';
            } else { // Default/info/warning
                toast.style.borderColor = 'var(--pico-color-blue-500, blue)';
                toast.style.backgroundColor = 'var(--pico-color-blue-150, #e6f7ff)';
                toast.style.color = 'var(--pico-color-blue-700, darkblue)';
            }

            toastContainer.appendChild(toast);

            setTimeout(() => {
                toast.style.opacity = '1';
                toast.style.transform = 'translateX(0)';
            }, 10);

            const closeButton = toast.querySelector('.close-toast');
            closeButton.onclick = () => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(-20px)';
                setTimeout(() => toast.remove(), 300);
            };

            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(-20px)';
                setTimeout(() => toast.remove(), 300);
            }, 5000);
        });
    </script>
</body>

</html>
