<!DOCTYPE html>
<!--
  Familiar - Self-hosted AI Agent
  Copyright (c) 2026 George Scott Foley
  
  Licensed under the MIT License
  For commercial licensing, contact: licensing@familiar.ai
-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#6B21A8">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Familiar">
    
    <title>Familiar</title>
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="{{ url_for('pwa.manifest') }}">
    
    <!-- Icons -->
    <link rel="icon" type="image/png" sizes="192x192" href="{{ url_for('pwa.static', filename='icons/icon-192.png') }}">
    <link rel="apple-touch-icon" href="{{ url_for('pwa.static', filename='icons/icon-192.png') }}">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <style>
        /* iOS safe areas */
        body {
            padding-top: env(safe-area-inset-top);
            padding-bottom: env(safe-area-inset-bottom);
            padding-left: env(safe-area-inset-left);
            padding-right: env(safe-area-inset-right);
        }
        
        /* Custom scrollbar */
        .messages::-webkit-scrollbar {
            width: 6px;
        }
        .messages::-webkit-scrollbar-track {
            background: transparent;
        }
        .messages::-webkit-scrollbar-thumb {
            background: #d1d5db;
            border-radius: 3px;
        }
        
        /* Message animation */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .message-enter {
            animation: fadeIn 0.2s ease-out;
        }
        
        /* Typing indicator */
        .typing-dot {
            animation: typingBounce 1.4s infinite ease-in-out both;
        }
        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }
        @keyframes typingBounce {
            0%, 80%, 100% { transform: scale(0.6); }
            40% { transform: scale(1); }
        }
        
        /* Offline indicator */
        .offline-banner {
            display: none;
        }
        .offline .offline-banner {
            display: flex;
        }
    </style>
</head>
<body class="bg-gray-100 h-screen flex flex-col">
    <!-- Offline Banner -->
    <div class="offline-banner bg-yellow-500 text-white text-center py-1 text-sm">
        📶 You're offline. Messages will be sent when connected.
    </div>
    
    <!-- Header -->
    <header class="bg-purple-800 text-white px-4 py-3 flex items-center justify-between shadow-lg flex-shrink-0">
        <div class="flex items-center space-x-3">
            <span class="text-2xl">🐍</span>
            <div>
                <h1 class="font-bold text-lg">Familiar</h1>
                <p class="text-xs text-purple-200" id="status">Ready</p>
            </div>
        </div>
        <div class="flex items-center space-x-2">
            <button id="newChatBtn" class="p-2 hover:bg-purple-700 rounded-lg" title="New Chat">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                </svg>
            </button>
            <button id="menuBtn" class="p-2 hover:bg-purple-700 rounded-lg" title="Menu">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"/>
                </svg>
            </button>
        </div>
    </header>
    
    <!-- Menu Dropdown -->
    <div id="menuDropdown" class="hidden absolute right-2 top-14 bg-white rounded-lg shadow-xl z-50 py-2 min-w-48">
        <div class="px-4 py-2 border-b">
            <p class="font-medium text-gray-800">{{ user.name }}</p>
            <p class="text-sm text-gray-500">{{ user.email }}</p>
        </div>
        <button id="enablePushBtn" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center space-x-2">
            <span>🔔</span>
            <span>Enable Notifications</span>
        </button>
        <button id="installBtn" class="w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center space-x-2 hidden">
            <span>📲</span>
            <span>Install App</span>
        </button>
        <a href="{{ url_for('pwa.logout') }}" class="block px-4 py-2 hover:bg-gray-100 text-red-600">
            Sign Out
        </a>
    </div>
    
    <!-- Messages -->
    <div id="messages" class="messages flex-1 overflow-y-auto px-4 py-4 space-y-4">
        <!-- Welcome message -->
        <div class="flex justify-start message-enter">
            <div class="bg-white rounded-2xl rounded-tl-sm px-4 py-3 max-w-[85%] shadow-sm">
                <p class="text-gray-800">👋 Hi {{ user.name.split()[0] }}! How can I help you today?</p>
            </div>
        </div>
    </div>
    
    <!-- Typing Indicator (hidden by default) -->
    <div id="typingIndicator" class="hidden px-4 pb-2">
        <div class="flex items-center space-x-2 text-gray-500">
            <div class="flex space-x-1">
                <div class="typing-dot w-2 h-2 bg-gray-400 rounded-full"></div>
                <div class="typing-dot w-2 h-2 bg-gray-400 rounded-full"></div>
                <div class="typing-dot w-2 h-2 bg-gray-400 rounded-full"></div>
            </div>
            <span class="text-sm">Familiar is thinking...</span>
        </div>
    </div>
    
    <!-- Input -->
    <div class="bg-white border-t px-4 py-3 flex-shrink-0">
        <form id="chatForm" class="flex items-end space-x-2">
            <div class="flex-1 relative">
                <textarea 
                    id="messageInput"
                    rows="1"
                    placeholder="Message Familiar..."
                    class="w-full px-4 py-3 border border-gray-300 rounded-2xl resize-none focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                    style="max-height: 120px;"
                ></textarea>
            </div>
            <button 
                type="submit"
                id="sendBtn"
                class="bg-purple-600 text-white p-3 rounded-full hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                disabled
            >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
                </svg>
            </button>
        </form>
    </div>
    
    <!-- Service Worker Registration -->
    <script>
        // Register service worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('{{ url_for("pwa.service_worker") }}')
                .then(reg => console.log('SW registered'))
                .catch(err => console.error('SW registration failed:', err));
        }
        
        // PWA install prompt
        let deferredPrompt;
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            deferredPrompt = e;
            document.getElementById('installBtn').classList.remove('hidden');
        });
        
        document.getElementById('installBtn')?.addEventListener('click', async () => {
            if (deferredPrompt) {
                deferredPrompt.prompt();
                const { outcome } = await deferredPrompt.userChoice;
                console.log('Install outcome:', outcome);
                deferredPrompt = null;
                document.getElementById('installBtn').classList.add('hidden');
            }
        });
    </script>
    
    <!-- Chat Logic -->
    <script>
        const messagesEl = document.getElementById('messages');
        const chatForm = document.getElementById('chatForm');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const typingIndicator = document.getElementById('typingIndicator');
        const statusEl = document.getElementById('status');
        const menuBtn = document.getElementById('menuBtn');
        const menuDropdown = document.getElementById('menuDropdown');
        const newChatBtn = document.getElementById('newChatBtn');
        
        // Offline message queue
        let messageQueue = [];
        let isOnline = navigator.onLine;
        
        // Update online status
        function updateOnlineStatus() {
            isOnline = navigator.onLine;
            document.body.classList.toggle('offline', !isOnline);
            statusEl.textContent = isOnline ? 'Ready' : 'Offline';
            
            // Process queue when back online
            if (isOnline && messageQueue.length > 0) {
                processMessageQueue();
            }
        }
        
        window.addEventListener('online', updateOnlineStatus);
        window.addEventListener('offline', updateOnlineStatus);
        updateOnlineStatus();
        
        // Menu toggle
        menuBtn.addEventListener('click', () => {
            menuDropdown.classList.toggle('hidden');
        });
        
        document.addEventListener('click', (e) => {
            if (!menuBtn.contains(e.target) && !menuDropdown.contains(e.target)) {
                menuDropdown.classList.add('hidden');
            }
        });
        
        // New chat
        newChatBtn.addEventListener('click', () => {
            messagesEl.innerHTML = `
                <div class="flex justify-start message-enter">
                    <div class="bg-white rounded-2xl rounded-tl-sm px-4 py-3 max-w-[85%] shadow-sm">
                        <p class="text-gray-800">👋 Hi! Starting a new conversation. How can I help?</p>
                    </div>
                </div>
            `;
        });
        
        // Auto-resize textarea
        messageInput.addEventListener('input', () => {
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
            sendBtn.disabled = !messageInput.value.trim();
        });
        
        // Enter to send (Shift+Enter for newline)
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (messageInput.value.trim()) {
                    chatForm.dispatchEvent(new Event('submit'));
                }
            }
        });
        
        // Add message to UI
        function addMessage(text, isUser = false) {
            const div = document.createElement('div');
            div.className = `flex ${isUser ? 'justify-end' : 'justify-start'} message-enter`;
            
            const bubble = document.createElement('div');
            bubble.className = isUser 
                ? 'bg-purple-600 text-white rounded-2xl rounded-tr-sm px-4 py-3 max-w-[85%] shadow-sm'
                : 'bg-white rounded-2xl rounded-tl-sm px-4 py-3 max-w-[85%] shadow-sm';
            
            // HTML-escape first to prevent XSS, then apply markdown formatting
            let escaped = text
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;');
            let formattedText = escaped
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 rounded">$1</code>')
                .replace(/\n/g, '<br>');

            bubble.innerHTML = `<p class="${isUser ? '' : 'text-gray-800'}">${formattedText}</p>`;
            div.appendChild(bubble);
            messagesEl.appendChild(div);
            
            // Scroll to bottom
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
        
        // Process message queue
        async function processMessageQueue() {
            while (messageQueue.length > 0) {
                const message = messageQueue.shift();
                await sendMessage(message, false);
            }
        }
        
        // Send message
        async function sendMessage(text, addToQueue = true) {
            if (!isOnline && addToQueue) {
                messageQueue.push(text);
                addMessage(text, true);
                addMessage('📶 Message queued. Will send when online.', false);
                return;
            }
            
            statusEl.textContent = 'Sending...';
            typingIndicator.classList.remove('hidden');
            
            try {
                const response = await fetch('{{ url_for("pwa.api_chat") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message: text })
                });
                
                const data = await response.json();
                
                typingIndicator.classList.add('hidden');
                
                if (data.error) {
                    addMessage('❌ ' + data.error, false);
                } else {
                    addMessage(data.response, false);
                }
                
                statusEl.textContent = 'Ready';
                
            } catch (error) {
                typingIndicator.classList.add('hidden');
                statusEl.textContent = 'Error';
                
                if (addToQueue) {
                    messageQueue.push(text);
                    addMessage('❌ Failed to send. Queued for retry.', false);
                } else {
                    addMessage('❌ ' + error.message, false);
                }
            }
        }
        
        // Form submit
        chatForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const text = messageInput.value.trim();
            if (!text) return;
            
            addMessage(text, true);
            messageInput.value = '';
            messageInput.style.height = 'auto';
            sendBtn.disabled = true;
            
            await sendMessage(text);
        });
        
        // Push notifications
        const enablePushBtn = document.getElementById('enablePushBtn');
        const vapidPublicKey = '{{ vapid_public_key }}';
        
        enablePushBtn?.addEventListener('click', async () => {
            if (!('Notification' in window)) {
                alert('Notifications not supported');
                return;
            }
            
            const permission = await Notification.requestPermission();
            if (permission !== 'granted') {
                alert('Notification permission denied');
                return;
            }
            
            if (!vapidPublicKey) {
                alert('Push notifications not configured on server');
                return;
            }
            
            try {
                const registration = await navigator.serviceWorker.ready;
                const subscription = await registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: vapidPublicKey
                });
                
                // Send to server
                await fetch('{{ url_for("pwa.push_subscribe") }}', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ subscription })
                });
                
                alert('Notifications enabled!');
                enablePushBtn.innerHTML = '<span>✅</span><span>Notifications Enabled</span>';
                
            } catch (error) {
                console.error('Push subscription error:', error);
                alert('Failed to enable notifications');
            }
        });
        
        // Focus input on load
        messageInput.focus();
    </script>
</body>
</html>
