<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChaiClone - Private AI Roleplay</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        darkBg: '#0f172a',
                        cardBg: '#1e293b',
                        accent: '#ec4899',
                        accentHover: '#db2777'
                    }
                }
            }
        }
    </script>
    <!-- FontAwesome for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Marked.js for Markdown parsing -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body class="bg-darkBg text-slate-100 font-sans h-screen flex flex-col overflow-hidden">

    <!-- Top Navigation Bar -->
    <header class="bg-cardBg border-b border-slate-700 p-4 flex justify-between items-center z-10">
        <div class="flex items-center space-x-3">
            <button id="back-btn" class="hidden text-slate-300 hover:text-white text-xl mr-2">
                <i class="fa-solid fa-arrow-left"></i>
            </button>
            <div id="header-avatar" class="w-10 h-10 rounded-full bg-accent flex items-center justify-center font-bold text-lg overflow-hidden">
                <i class="fa-solid fa-robot"></i>
            </div>
            <div>
                <h1 id="header-title" class="font-bold text-lg leading-tight">My Characters</h1>
                <p id="header-subtitle" class="text-xs text-slate-400">Choose a bot to chat</p>
            </div>
        </div>
        <div class="flex items-center space-x-3">
            <button id="settings-btn" class="w-10 h-10 rounded-full bg-slate-700 hover:bg-slate-600 flex items-center justify-center text-slate-200 transition">
                <i class="fa-solid fa-gear"></i>
            </button>
        </div>
    </header>

    <!-- Main Container Area -->
    <main class="flex-1 relative overflow-hidden flex flex-col">

        <!-- VIEW 1: Character List / Home -->
        <div id="view-home" class="flex-1 overflow-y-auto p-4 space-y-4">
            <div class="flex justify-between items-center mb-2">
                <h2 class="text-xl font-bold tracking-wide">Your Bots</h2>
                <button id="new-char-btn" class="bg-accent hover:bg-accentHover text-white px-4 py-2 rounded-full text-sm font-medium flex items-center space-x-2 shadow-lg transition">
                    <i class="fa-solid fa-plus"></i>
                    <span>Create Bot</span>
                </button>
            </div>
            <div id="character-grid" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 pb-20">
                <!-- Dynamically injected bot cards -->
            </div>
        </div>

        <!-- VIEW 2: Chat Room -->
        <div id="view-chat" class="hidden flex-1 flex flex-col overflow-hidden">
            <!-- Messages Scroll Area -->
            <div id="chat-messages" class="flex-1 overflow-y-auto p-4 space-y-4">
                <!-- Dynamically injected messages -->
            </div>
            <!-- Chat Input Area -->
            <div class="bg-cardBg border-t border-slate-700 p-3 flex items-center space-x-2">
                <textarea id="chat-input" rows="1" placeholder="Type your message..." class="flex-1 bg-slate-900 border border-slate-700 rounded-xl px-4 py-3 text-sm focus:outline-none focus:border-accent resize-none max-h-32"></textarea>
                <button id="send-btn" class="bg-accent hover:bg-accentHover text-white w-12 h-12 rounded-xl flex items-center justify-center transition shadow-lg shrink-0">
                    <i class="fa-solid fa-paper-plane"></i>
                </button>
            </div>
        </div>

    </main>

    <!-- MODAL: Settings (API Key & Provider) -->
    <div id="modal-settings" class="fixed inset-0 bg-black/70 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-cardBg border border-slate-700 rounded-2xl w-full max-w-md p-6 space-y-4 shadow-2xl">
            <div class="flex justify-between items-center">
                <h3 class="text-lg font-bold">API Settings</h3>
                <button class="close-modal text-slate-400 hover:text-white text-lg"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <p class="text-xs text-slate-400">Plug in your free API key to power your chats. (Get a Gemini key free at Google AI Studio).</p>
            <div class="space-y-3">
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">AI Provider</label>
                    <select id="api-provider" class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent">
                        <option value="gemini">Google Gemini (Free API Key)</option>
                        <option value="openrouter">OpenRouter (Supports Free/Paid Models)</option>
                    </select>
                </div>
                <div id="model-name-wrapper">
                    <label class="block text-xs font-medium text-slate-300 mb-1">Model Name</label>
                    <input type="text" id="api-model" value="gemini-2.5-flash" class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent" placeholder="e.g. gemini-2.5-flash or google/gemini-2.5-flash">
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">API Key</label>
                    <input type="password" id="api-key-input" placeholder="Paste your API key here..." class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent">
                </div>
            </div>
            <button id="save-settings-btn" class="w-full bg-accent hover:bg-accentHover text-white py-3 rounded-xl font-medium transition shadow-lg">Save Settings</button>
        </div>
    </div>

    <!-- MODAL: Create / Edit Character -->
    <div id="modal-char" class="fixed inset-0 bg-black/70 z-50 hidden flex items-center justify-center p-4 overflow-y-auto">
        <div class="bg-cardBg border border-slate-700 rounded-2xl w-full max-w-lg p-6 space-y-4 shadow-2xl my-auto">
            <div class="flex justify-between items-center">
                <h3 id="char-modal-title" class="text-lg font-bold">Create Bot</h3>
                <button class="close-modal text-slate-400 hover:text-white text-lg"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <input type="hidden" id="edit-char-id">
            <div class="space-y-3 max-h-[70vh] overflow-y-auto pr-2">
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">Character Name</label>
                    <input type="text" id="char-name" placeholder="e.g., Kylie" class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent">
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">Avatar Image URL (Optional)</label>
                    <input type="text" id="char-avatar" placeholder="https://example.com/image.jpg" class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent">
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">Personality / System Prompt</label>
                    <textarea id="char-personality" rows="3" placeholder="Describe the bot's background, personality, tone, and traits..." class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent"></textarea>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-300 mb-1">First Message (Greeting)</label>
                    <textarea id="char-greeting" rows="2" placeholder="The very first message the character sends..." class="w-full bg-slate-900 border border-slate-700 rounded-xl p-3 text-sm focus:outline-none focus:border-accent"></textarea>
                </div>
            </div>
            <div class="flex space-x-3 pt-2">
                <button id="delete-char-btn" class="hidden bg-red-600/20 hover:bg-red-600 text-red-400 hover:text-white px-4 py-3 rounded-xl font-medium transition">Delete</button>
                <button id="save-char-btn" class="flex-1 bg-accent hover:bg-accentHover text-white py-3 rounded-xl font-medium transition shadow-lg">Save Character</button>
            </div>
        </div>
    </div>

    <!-- App Logic Script -->
    <script>
        // State Management
        let state = {
            apiKey: localStorage.getItem('chai_api_key') || '',
            provider: localStorage.getItem('chai_provider') || 'gemini',
            model: localStorage.getItem('chai_model') || 'gemini-2.5-flash',
            characters: JSON.parse(localStorage.getItem('chai_characters') || '[]'),
            chats: JSON.parse(localStorage.getItem('chai_chats') || '{}'), // { charId: [ {role, content} ] }
            activeCharId: null
        };

        // Default Sample Bot if none exist
        if (state.characters.length === 0) {
            const defaultBot = {
                id: 'bot_' + Date.now(),
                name: 'Kylie',
                avatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=150',
                personality: 'You are Kylie. You are affectionate, playful, and responsive. You enjoy deep roleplay scenarios.',
                greeting: 'Hey baby.'
            };
            state.characters.push(defaultBot);
            state.chats[defaultBot.id] = [{ role: 'assistant', content: defaultBot.greeting }];
            saveState();
        }

        function saveState() {
            localStorage.setItem('chai_api_key', state.apiKey);
            localStorage.setItem('chai_provider', state.provider);
            localStorage.setItem('chai_model', state.model);
            localStorage.setItem('chai_characters', JSON.stringify(state.characters));
            localStorage.setItem('chai_chats', JSON.stringify(state.chats));
        }

        // DOM Elements
        const viewHome = document.getElementById('view-home');
        const viewChat = document.getElementById('view-chat');
        const backBtn = document.getElementById('back-btn');
        const headerTitle = document.getElementById('header-title');
        const headerSubtitle = document.getElementById('header-subtitle');
        const headerAvatar = document.getElementById('header-avatar');
        const characterGrid = document.getElementById('character-grid');
        const chatMessages = document.getElementById('chat-messages');
        const chatInput = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');

        // Modals
        const modalSettings = document.getElementById('modal-settings');
        const modalChar = document.getElementById('modal-char');
        const apiKeyInput = document.getElementById('api-key-input');
        const apiProvider = document.getElementById('api-provider');
        const apiModel = document.getElementById('api-model');

        // Initialize UI
        renderCharacterList();

        // Navigation & Views
        function showHome() {
            state.activeCharId = null;
            viewChat.classList.add('hidden');
            viewHome.classList.remove('hidden');
            backBtn.classList.add('hidden');
            headerTitle.textContent = "My Characters";
            headerSubtitle.textContent = "Choose a bot to chat";
            headerAvatar.innerHTML = '<i class="fa-solid fa-robot"></i>';
            renderCharacterList();
        }

        function showChat(charId) {
            state.activeCharId = charId;
            const char = state.characters.find(c => c.id === charId);
            if (!char) return;

            viewHome.classList.add('hidden');
            viewChat.classList.remove('hidden');
            backBtn.classList.remove('hidden');
            headerTitle.textContent = char.name;
            headerSubtitle.textContent = "Active Roleplay";
            if (char.avatar) {
                headerAvatar.innerHTML = `<img src="${char.avatar}" class="w-full h-full object-cover">`;
            } else {
                headerAvatar.innerHTML = '<i class="fa-solid fa-user"></i>';
            }

            // Ensure chat history exists
            if (!state.chats[charId]) {
                state.chats[charId] = [{ role: 'assistant', content: char.greeting }];
                saveState();
            }
            renderMessages();
        }

        backBtn.addEventListener('click', showHome);

        // Render Character Cards
        function renderCharacterList() {
            characterGrid.innerHTML = '';
            state.characters.forEach(char => {
                const card = document.createElement('div');
                card.className = "bg-cardBorder bg-cardBg border border-slate-700 rounded-2xl p-4 flex flex-col justify-between hover:border-accent transition cursor-pointer group shadow-md";
                
                const avatarHtml = char.avatar 
                    ? `<img src="${char.avatar}" class="w-16 h-16 rounded-full object-cover border-2 border-accent">`
                    : `<div class="w-16 h-16 rounded-full bg-slate-700 flex items-center justify-center text-2xl text-slate-300 border-2 border-accent"><i class="fa-solid fa-user"></i></div>`;

                card.innerHTML = `
                    <div class="flex items-center space-x-4 mb-3">
                        ${avatarHtml}
                        <div class="flex-1 min-w-0">
                            <h3 class="font-bold text-lg truncate group-hover:text-accent transition">${char.name}</h3>
                            <p class="text-xs text-slate-400 line-clamp-2">${char.personality || 'No personality description provided.'}</p>
                        </div>
                    </div>
                    <div class="flex justify-between items-center pt-3 border-t border-slate-700/50">
                        <span class="text-xs text-slate-500">Tap to chat</span>
                        <button class="edit-char-trigger text-slate-400 hover:text-white p-2" data-id="${char.id}">
                            <i class="fa-solid fa-pen-to-square"></i>
                        </button>
                    </div>
                `;

                card.addEventListener('click', (e) => {
                    if (e.target.closest('.edit-char-trigger')) {
                        openEditCharacterModal(char.id);
                    } else {
                        showChat(char.id);
                    }
                });

                characterGrid.appendChild(card);
            });
        }

        // Render Messages
        function renderMessages() {
            chatMessages.innerHTML = '';
            const messages = state.chats[state.activeCharId] || [];
            const char = state.characters.find(c => c.id === state.activeCharId);

            messages.forEach((msg, index) => {
                const isUser = msg.role === 'user';
                const msgDiv = document.createElement('div');
                msgDiv.className = `flex ${isUser ? 'justify-end' : 'justify-start'} mb-4 items-end space-x-2`;

                const avatarHtml = !isUser ? (
                    char.avatar ? `<img src="${char.avatar}" class="w-8 h-8 rounded-full object-cover shrink-0 mb-1">` : `<div class="w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center text-xs shrink-0 mb-1"><i class="fa-solid fa-robot"></i></div>`
                ) : '';

                const bubbleBg = isUser ? 'bg-accent text-white rounded-br-none' : 'bg-cardBg border border-slate-700 text-slate-100 rounded-bl-none';
                
                // Parse markdown for assistant, plain text or markdown for user
                const formattedContent = isUser ? escapeHtml(msg.content) : marked.parse(msg.content);

                msgDiv.innerHTML = `
                    ${avatarHtml}
                    <div class="max-w-[80%] sm:max-w-[70%] rounded-2xl px-4 py-3 text-sm ${bubbleBg} shadow-sm leading-relaxed prose prose-invert">
                        ${formattedContent}
                    </div>
                `;
                chatMessages.appendChild(msgDiv);
            });
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function escapeHtml(text) {
            return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }

        // Send Message & AI Call
        async.chat = async function() {
            const text = chatInput.value.trim();
            if (!text || !state.activeCharId) return;

            if (!state.apiKey) {
                alert("Please set your API key in the settings gear at the top right first!");
                modalSettings.classList.remove('hidden');
                return;
            }

            // Append user message
            state.chats[state.activeCharId].push({ role: 'user', content: text });
            chatInput.value = '';
            chatInput.style.height = 'auto';
            renderMessages();

            // Add typing indicator
            const typingDiv = document.createElement('div');
            typingDiv.id = 'typing-indicator';
            typingDiv.className = 'flex justify-start mb-4 items-center space-x-2';
            typingDiv.innerHTML = `<div class="bg-cardBg border border-slate-700 rounded-2xl px-4 py-3 text-sm text-slate-400 animate-pulse">Typing...</div>`;
            chatMessages.appendChild(typingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;

            try {
                const reply = await callAIAPI();
                state.chats[state.activeCharId].push({ role: 'assistant', content: reply });
            } catch (err) {
                state.chats[state.activeCharId].push({ role: 'assistant', content: `*[Error connecting to AI: ${err.message}]*` });
            }

            document.getElementById('typing-indicator')?.remove();
            saveState();
            renderMessages();
        };

        sendBtn.addEventListener('click', window.chat);
        chatInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                window.chat();
            }
        });

        // AI API Connector (Gemini & OpenRouter)
        async function callAIAPI() {
            const char = state.characters.find(c => c.id === state.activeCharId);
            const history = state.chats[state.activeCharId];

            if (state.provider === 'gemini') {
                // Google Gemini API integration
                const model = state.model || 'gemini-2.5-flash';
                const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${state.apiKey}`;

                const contents = history.map(m => ({
                    role: m.role === 'assistant' ? 'model' : 'user',
                    parts: [{ text: m.content }]
                }));

                const body = {
                    system_instruction: {
                        parts: [{ text: `You are participating in an immersive roleplay. Character Profile & Personality: ${char.personality}` }]
                    },
                    contents: contents,
                    g