<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}PromptBin{% endblock %}</title>
    
    <!-- HTMX -->
    <script src="https://unpkg.com/htmx.org@1.9.10"></script>
    
    <!-- Highlight.js for syntax highlighting -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    
    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <div class="app-container">
        <!-- Header -->
        <header class="header">
            <div class="header-content">
                <h1 class="logo">
                    <a href="{{ url_for('index') }}">PromptBin</a>
                </h1>
                
                <div class="search-container">
                    <div class="search-input-group">
                        <input 
                            type="text" 
                            placeholder="Search prompts..." 
                            id="search-input"
                            name="q"
                            data-placeholder-default="Search prompts..."
                            data-placeholder-focus="Search by title, content, description, or tags..."
                            hx-get="{{ url_for('search_prompts') }}"
                            hx-trigger="keyup changed delay:300ms"
                            hx-target="#search-results"
                            hx-swap="innerHTML"
                            hx-indicator="#search-loading"
                        >
                        <button 
                            type="button" 
                            id="clear-filters-btn" 
                            class="clear-filters-btn"
                            title="Clear search and filters"
                            style="display: none;"
                            onclick="clearFilters()"
                        >
                            ✕
                        </button>
                    </div>
                    <div id="search-loading" class="search-loading htmx-indicator">
                        <span class="loading-spinner">⚡</span>
                        <span class="loading-text">Searching...</span>
                    </div>
                </div>
                
                <div class="tunnel-status">
                    <span id="tunnel-status-indicator">
                        <span class="status-dot" id="tunnel-status-dot"></span>
                        <span id="tunnel-status-text">Tunnel: Inactive</span>
                    </span>
                    <button id="tunnel-url-copy" style="display: none;" onclick="copyTunnelUrl()" title="Copy tunnel URL">
                        📋
                    </button>
                </div>
            </div>
        </header>

        <div class="main-container">
            <!-- Sidebar -->
            <aside class="sidebar" id="navigation-container">
                {% include 'partials/navigation.html' %}
            </aside>

            <!-- Main Content -->
            <main class="main-content">
                {% block content %}{% endblock %}
            </main>
        </div>

        <!-- Footer -->
        <footer class="footer">
            <div class="footer-content">
                <div class="tunnel-controls">
                    <button id="start-tunnel-btn" onclick="startTunnel()" class="tunnel-btn">
                        Start Tunnel
                    </button>
                    <button id="stop-tunnel-btn" onclick="stopTunnel()" class="tunnel-btn" style="display: none;">
                        Stop Tunnel
                    </button>
                    <div id="tunnel-url-display" style="display: none;">
                        <span>Tunnel: </span>
                        <a id="tunnel-url-link" href="#" target="_blank"></a>
                        <button onclick="copyTunnelUrl()" title="Copy URL">📋</button>
                    </div>
                    <div id="tunnel-loading" style="display: none;">
                        <span>⚡ Starting tunnel...</span>
                    </div>
                    <div id="tunnel-error" style="display: none; color: #dc2626;"></div>
                </div>
            </div>
        </footer>
    </div>

    <!-- HTMX Loading Indicator -->
    <div id="htmx-indicator" class="htmx-indicator">Loading...</div>

    <script>
        // Initialize highlight.js
        hljs.highlightAll();
        
        // Custom HTMX configuration
        document.addEventListener('htmx:afterRequest', function(event) {
            // Re-run highlight.js on new content
            hljs.highlightAll();
        });
        
        // Search functionality
        const searchInput = document.getElementById('search-input');
        const searchResults = document.getElementById('search-results');
        const promptGrid = document.getElementById('prompt-grid');
        const clearBtn = document.getElementById('clear-filters-btn');
        
        function updateClearButtonVisibility() {
            if (clearBtn && searchInput) {
                const hasQuery = searchInput.value.trim().length > 0;
                const hasCategory = window.location.search.includes('category=');
                clearBtn.style.display = (hasQuery || hasCategory) ? 'block' : 'none';
            }
        }
        
        function clearFilters() {
            // Clear search input
            if (searchInput) {
                searchInput.value = '';
            }
            
            // Hide search results and show main grid
            if (searchResults) {
                searchResults.style.display = 'none';
                searchResults.innerHTML = '';
            }
            if (promptGrid) {
                promptGrid.style.display = 'block';
            }
            
            // Navigate to main page without category filter
            htmx.ajax('GET', '{{ url_for("htmx_index") }}', {
                target: '.main-content',
                swap: 'innerHTML'
            });
            
            // Update navigation to show all prompts selected
            updateNavigation('');
            
            // Update URL without category
            history.pushState(null, '', '{{ url_for("index") }}');
            
            // Hide clear button
            updateClearButtonVisibility();
        }
        
        if (searchInput) {
            // Show search results when user starts typing with enhanced UX
            searchInput.addEventListener('input', function() {
                const query = this.value.trim();
                if (query.length > 0) {
                    // Add searching class for enhanced styling
                    searchInput.classList.add('searching');
                    if (searchResults) {
                        searchResults.style.display = 'block';
                        if (promptGrid) promptGrid.style.display = 'none';
                    }
                } else {
                    // Remove searching class
                    searchInput.classList.remove('searching');
                    if (searchResults) {
                        searchResults.style.display = 'none';
                        if (promptGrid) promptGrid.style.display = 'block';
                    }
                }
                updateClearButtonVisibility();
            });
            
            // Add focus/blur enhancements for better UX using data attributes
            searchInput.addEventListener('focus', function() {
                this.placeholder = this.dataset.placeholderFocus || this.placeholder;
            });
            
            searchInput.addEventListener('blur', function() {
                this.placeholder = this.dataset.placeholderDefault || "Search prompts...";
            });
            
            // Clear search on Escape
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    clearFilters();
                }
            });
        }
        
        // Update clear button visibility on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateClearButtonVisibility();
        });
        
        // Show/hide loading indicator
        document.addEventListener('htmx:beforeRequest', function() {
            document.getElementById('htmx-indicator').style.display = 'block';
        });
        
        document.addEventListener('htmx:afterRequest', function() {
            document.getElementById('htmx-indicator').style.display = 'none';
        });
        
        // Global notification function
        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = 'notification notification-' + type;
            notification.textContent = message;
            
            let backgroundColor = '#2563eb'; // default blue
            if (type === 'error') backgroundColor = '#dc2626'; // red
            if (type === 'info') backgroundColor = '#059669'; // green-ish
            if (type === 'success') backgroundColor = '#2563eb'; // blue
            
            notification.style.cssText = 
                'position: fixed;' +
                'top: 20px;' +
                'right: 20px;' +
                'background: ' + backgroundColor + ';' +
                'color: white;' +
                'padding: 1rem;' +
                'border-radius: 0.375rem;' +
                'z-index: 1000;' +
                'max-width: 300px;';
            document.body.appendChild(notification);
            
            setTimeout(function() {
                notification.remove();
            }, 3000);
        }
        
        // Update navigation sidebar when category changes with visual feedback
        function updateNavigation(category) {
            // Add loading state to navigation
            const navContainer = document.getElementById('navigation-container');
            if (navContainer) {
                navContainer.classList.add('loading');
            }
            
            const url = '/htmx/navigation' + (category ? '?category=' + category : '');
            htmx.ajax('GET', url, {
                target: '#navigation-container',
                swap: 'innerHTML'
            }).then(function() {
                // Remove loading state after update
                if (navContainer) {
                    navContainer.classList.remove('loading');
                }
                updateClearButtonVisibility();
            });
        }
        
        // Enhanced share prompt functionality
        function sharePrompt(promptId) {
            // Show loading state
            showNotification('Generating share link...', 'info');
            
            fetch('/api/share/' + promptId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({}) // Could include expiration options in future
            })
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    // Copy the shareable URL to clipboard
                    navigator.clipboard.writeText(result.share_url).then(function() {
                        const tunnelActive = document.getElementById('tunnel-status-dot').classList.contains('active');
                        const linkType = tunnelActive ? 'Public share link' : 'Share link';
                        showNotification(linkType + ' copied to clipboard!', 'success');
                    }).catch(function(err) {
                        // Fallback - show the URL in a prompt
                        console.error('Clipboard API failed:', err);
                        prompt('Share link generated! Copy this URL:', result.share_url);
                        showNotification('Share link generated (copied above)', 'success');
                    });
                } else {
                    showNotification('Error: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Share error:', error);
                showNotification('Failed to create share link. Please try again.', 'error');
            });
        }
        
        // Tunnel management functions
        let currentTunnelUrl = null;
        
        function startTunnel() {
            const startBtn = document.getElementById('start-tunnel-btn');
            const loading = document.getElementById('tunnel-loading');
            const errorDiv = document.getElementById('tunnel-error');
            
            // Show loading state
            startBtn.style.display = 'none';
            loading.style.display = 'block';
            errorDiv.style.display = 'none';
            
            fetch('/api/tunnel/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(result => {
                loading.style.display = 'none';
                
                if (result.status === 'success') {
                    showNotification('Tunnel started successfully!', 'success');
                    updateTunnelStatus();
                } else {
                    showNotification('Error: ' + result.message, 'error');
                    errorDiv.textContent = result.message;
                    errorDiv.style.display = 'block';
                    startBtn.style.display = 'block';
                }
            })
            .catch(error => {
                console.error('Tunnel start error:', error);
                showNotification('Failed to start tunnel. Please try again.', 'error');
                loading.style.display = 'none';
                startBtn.style.display = 'block';
            });
        }
        
        function stopTunnel() {
            if (confirm('Are you sure you want to stop the tunnel? This will make shared links inaccessible.')) {
                const stopBtn = document.getElementById('stop-tunnel-btn');
                stopBtn.disabled = true;
                stopBtn.textContent = 'Stopping...';
                
                fetch('/api/tunnel/stop', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.status === 'success') {
                        showNotification('Tunnel stopped successfully.', 'info');
                        updateTunnelStatus();
                    } else {
                        showNotification('Error: ' + result.message, 'error');
                    }
                    stopBtn.disabled = false;
                    stopBtn.textContent = 'Stop Tunnel';
                })
                .catch(error => {
                    console.error('Tunnel stop error:', error);
                    showNotification('Failed to stop tunnel.', 'error');
                    stopBtn.disabled = false;
                    stopBtn.textContent = 'Stop Tunnel';
                });
            }
        }
        
        function updateTunnelStatus() {
            fetch('/api/tunnel/status')
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    const data = result.data;
                    const statusDot = document.getElementById('tunnel-status-dot');
                    const statusText = document.getElementById('tunnel-status-text');
                    const startBtn = document.getElementById('start-tunnel-btn');
                    const stopBtn = document.getElementById('stop-tunnel-btn');
                    const urlDisplay = document.getElementById('tunnel-url-display');
                    const urlLink = document.getElementById('tunnel-url-link');
                    const urlCopyBtn = document.getElementById('tunnel-url-copy');
                    
                    if (data.active && data.tunnel_url) {
                        // Tunnel is active
                        statusDot.className = 'status-dot active';
                        statusText.textContent = 'Tunnel: Active';
                        startBtn.style.display = 'none';
                        stopBtn.style.display = 'block';
                        urlDisplay.style.display = 'block';
                        urlCopyBtn.style.display = 'inline';
                        urlLink.href = data.tunnel_url;
                        urlLink.textContent = data.tunnel_url;
                        currentTunnelUrl = data.tunnel_url;
                    } else {
                        // Tunnel is inactive
                        statusDot.className = 'status-dot';
                        statusText.textContent = 'Tunnel: Inactive';
                        startBtn.style.display = 'block';
                        stopBtn.style.display = 'none';
                        urlDisplay.style.display = 'none';
                        urlCopyBtn.style.display = 'none';
                        currentTunnelUrl = null;
                    }
                }
            })
            .catch(error => {
                console.error('Error fetching tunnel status:', error);
            });
        }
        
        function copyTunnelUrl() {
            if (currentTunnelUrl) {
                navigator.clipboard.writeText(currentTunnelUrl).then(function() {
                    showNotification('Tunnel URL copied to clipboard!', 'success');
                }).catch(function(err) {
                    console.error('Clipboard API failed:', err);
                    prompt('Copy this tunnel URL:', currentTunnelUrl);
                });
            }
        }
        
        // Update tunnel status on page load and periodically
        document.addEventListener('DOMContentLoaded', function() {
            updateTunnelStatus();
            // Check status every 30 seconds
            setInterval(updateTunnelStatus, 30000);
        });
    </script>

    {% block scripts %}{% endblock %}
</body>
</html>