<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Guru - Pembuat Soal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 50%, #1e1b4b 100%);
            min-height: 100vh;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .chat-bubble-user {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        }

        .chat-bubble-ai {
            background: rgba(30, 41, 59, 0.8);
            border: 1px solid rgba(99, 102, 241, 0.3);
        }

        .level-section {
            background: linear-gradient(145deg, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.8));
            border: 1px solid rgba(99, 102, 241, 0.2);
        }

        .input-field {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(99, 102, 241, 0.3);
            transition: all 0.3s ease;
        }

        .input-field:focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
            outline: none;
        }

        .save-btn {
            background: linear-gradient(135deg, #10b981, #059669);
            transition: all 0.3s ease;
        }

        .save-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);
        }

        .send-btn {
            background: linear-gradient(135deg, #6366f1, #4f46e5);
        }

        .send-btn:hover {
            background: linear-gradient(135deg, #818cf8, #6366f1);
        }

        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(15, 23, 42, 0.5);
        }

        ::-webkit-scrollbar-thumb {
            background: rgba(99, 102, 241, 0.5);
            border-radius: 3px;
        }

        .typing-indicator span {
            animation: bounce 1.4s infinite ease-in-out both;
        }

        .typing-indicator span:nth-child(1) {
            animation-delay: -0.32s;
        }

        .typing-indicator span:nth-child(2) {
            animation-delay: -0.16s;
        }

        @keyframes bounce {

            0%,
            80%,
            100% {
                transform: scale(0);
            }

            40% {
                transform: scale(1);
            }
        }

        .auto-filled {
            animation: highlight 1s ease-out;
        }

        @keyframes highlight {
            0% {
                background-color: rgba(16, 185, 129, 0.3);
            }

            100% {
                background-color: transparent;
            }
        }
    </style>
</head>

<body class="text-white">
    <header class="glass-card py-4 px-6 mb-6">
        <div class="container mx-auto flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div
                    class="w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg flex items-center justify-center">
                    <span class="text-xl">🎓</span>
                </div>
                <div>
                    <h1
                        class="text-xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
                        Dashboard Guru</h1>
                    <p class="text-xs text-gray-400">Pembuat Soal Game Pico Park</p>
                </div>
            </div>
            <a href="index.php"
                class="px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg text-sm font-medium transition-all border border-red-500/30">←
                Kembali</a>
        </div>
    </header>

    <main class="container mx-auto px-4 pb-8">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-140px)]">

            <!-- Left Column: AI Assistant -->
            <div class="glass-card rounded-2xl overflow-hidden flex flex-col">
                <div class="p-4 border-b border-white/10">
                    <h2 class="text-lg font-semibold flex items-center gap-2">
                        <span class="text-2xl">🤖</span>
                        Asisten Pembuat Soal (AI)
                    </h2>
                    <p class="text-xs text-gray-400 mt-1">Minta bantuan AI, soal akan otomatis terisi ke form →</p>
                </div>

                <div id="chat-history" class="flex-1 overflow-y-auto p-4 space-y-4">
                    <div class="flex items-start gap-3">
                        <div
                            class="w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex-shrink-0 flex items-center justify-center text-sm">
                            🤖</div>
                        <div class="chat-bubble-ai p-3 rounded-2xl rounded-tl-none max-w-[85%]">
                            <p class="text-sm">Halo Pak/Bu Guru! 👋</p>
                            <p class="text-sm mt-2">Saya bisa membantu membuat soal pilihan ganda. Ketik topiknya, dan
                                soal akan <strong class="text-green-400">otomatis terisi</strong> ke form sebelah kanan!
                            </p>
                            <p class="text-xs text-gray-400 mt-2">Contoh: "Buatkan soal matematika tentang penjumlahan"
                            </p>
                        </div>
                    </div>
                </div>

                <div class="p-4 border-t border-white/10">
                    <div class="flex gap-2">
                        <input type="text" id="chat-input" placeholder="Ketik permintaan Anda..."
                            class="flex-1 input-field rounded-xl px-4 py-3 text-sm text-white placeholder-gray-500">
                        <button id="send-btn"
                            class="send-btn px-6 py-3 rounded-xl font-medium text-sm hover:opacity-90 transition-all">Kirim</button>
                    </div>
                </div>
            </div>

            <!-- Right Column: Question Input Forms -->
            <div class="glass-card rounded-2xl overflow-hidden flex flex-col">
                <div class="p-4 border-b border-white/10">
                    <h2 class="text-lg font-semibold flex items-center gap-2">
                        <span class="text-2xl">📝</span>
                        Input Soal Game
                    </h2>
                    <p class="text-xs text-gray-400 mt-1">Soal dari AI akan otomatis terisi di sini</p>
                </div>

                <div class="flex-1 overflow-y-auto p-4 space-y-4">
                    <!-- Level 1 -->
                    <div class="level-section rounded-xl p-4">
                        <h3 class="font-semibold text-indigo-400 mb-3 flex items-center gap-2">
                            <span
                                class="w-6 h-6 bg-indigo-500/20 rounded-full flex items-center justify-center text-xs">1</span>
                            Level 1
                        </h3>
                        <div class="space-y-3">
                            <input type="text" id="q1-question" placeholder="Pertanyaan Level 1"
                                class="w-full input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            <div class="grid grid-cols-3 gap-2">
                                <input type="text" id="q1-optA" placeholder="Pilihan A"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q1-optB" placeholder="Pilihan B"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q1-optC" placeholder="Pilihan C"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            </div>
                            <select id="q1-correct" class="input-field rounded-lg px-3 py-2 text-sm text-white w-full">
                                <option value="0">Jawaban Benar: A</option>
                                <option value="1">Jawaban Benar: B</option>
                                <option value="2">Jawaban Benar: C</option>
                            </select>
                        </div>
                    </div>

                    <!-- Level 2 -->
                    <div class="level-section rounded-xl p-4">
                        <h3 class="font-semibold text-emerald-400 mb-3 flex items-center gap-2">
                            <span
                                class="w-6 h-6 bg-emerald-500/20 rounded-full flex items-center justify-center text-xs">2</span>
                            Level 2
                        </h3>
                        <div class="space-y-3">
                            <input type="text" id="q2-question" placeholder="Pertanyaan Level 2"
                                class="w-full input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            <div class="grid grid-cols-3 gap-2">
                                <input type="text" id="q2-optA" placeholder="Pilihan A"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q2-optB" placeholder="Pilihan B"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q2-optC" placeholder="Pilihan C"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            </div>
                            <select id="q2-correct" class="input-field rounded-lg px-3 py-2 text-sm text-white w-full">
                                <option value="0">Jawaban Benar: A</option>
                                <option value="1">Jawaban Benar: B</option>
                                <option value="2">Jawaban Benar: C</option>
                            </select>
                        </div>
                    </div>

                    <!-- Level 3 -->
                    <div class="level-section rounded-xl p-4">
                        <h3 class="font-semibold text-amber-400 mb-3 flex items-center gap-2">
                            <span
                                class="w-6 h-6 bg-amber-500/20 rounded-full flex items-center justify-center text-xs">3</span>
                            Level 3
                        </h3>
                        <div class="space-y-3">
                            <input type="text" id="q3-question" placeholder="Pertanyaan Level 3"
                                class="w-full input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            <div class="grid grid-cols-3 gap-2">
                                <input type="text" id="q3-optA" placeholder="Pilihan A"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q3-optB" placeholder="Pilihan B"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                                <input type="text" id="q3-optC" placeholder="Pilihan C"
                                    class="input-field rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500">
                            </div>
                            <select id="q3-correct" class="input-field rounded-lg px-3 py-2 text-sm text-white w-full">
                                <option value="0">Jawaban Benar: A</option>
                                <option value="1">Jawaban Benar: B</option>
                                <option value="2">Jawaban Benar: C</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="p-4 border-t border-white/10">
                    <button id="save-btn"
                        class="w-full save-btn py-4 rounded-xl font-semibold text-lg flex items-center justify-center gap-2">
                        <span>💾</span>
                        SIMPAN KE GAME
                    </button>
                </div>
            </div>
        </div>
    </main>

    <script>
        // ===== API CONFIG (menggunakan PHP backend proxy) =====
        const API_URL = 'api.php';

        const SYSTEM_PROMPT = `Kamu adalah asisten guru. Tugasmu membuatkan 3 Soal Pilihan Ganda (Level 1, 2, 3) yang singkat, jelas, dan formatnya mudah dicopy.

Format yang HARUS kamu gunakan:

**Level 1:**
Pertanyaan: [pertanyaan sederhana]
A. [jawaban 1]
B. [jawaban 2]
C. [jawaban 3]
Jawaban Benar: [A/B/C]

**Level 2:**
Pertanyaan: [pertanyaan menengah]
A. [jawaban 1]
B. [jawaban 2]
C. [jawaban 3]
Jawaban Benar: [A/B/C]

**Level 3:**
Pertanyaan: [pertanyaan lebih sulit]
A. [jawaban 1]
B. [jawaban 2]
C. [jawaban 3]
Jawaban Benar: [A/B/C]

Buat soal yang singkat (max 15 kata per pertanyaan), jelas, dan sesuai topik.`;

        const chatHistory = document.getElementById('chat-history');
        const chatInput = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');
        const saveBtn = document.getElementById('save-btn');

        function addMessage(sender, text) {
            const div = document.createElement('div');
            div.className = 'flex items-start gap-3' + (sender === 'user' ? ' flex-row-reverse' : '');
            const icon = sender === 'user' ? '👤' : '🤖';
            const bubbleClass = sender === 'user' ? 'chat-bubble-user rounded-tr-none' : 'chat-bubble-ai rounded-tl-none';
            const bgClass = sender === 'user' ? 'bg-gradient-to-br from-blue-500 to-blue-600' : 'bg-gradient-to-br from-indigo-500 to-purple-600';
            let formattedText = text.replace(/\*\*(.*?)\*\*/g, '<strong class="text-indigo-300">$1</strong>').replace(/\n/g, '<br>');
            div.innerHTML = `<div class="w-8 h-8 rounded-full ${bgClass} flex-shrink-0 flex items-center justify-center text-sm">${icon}</div>
                <div class="${bubbleClass} p-3 rounded-2xl max-w-[85%]"><p class="text-sm leading-relaxed">${formattedText}</p></div>`;
            chatHistory.appendChild(div);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function showTypingIndicator() {
            const div = document.createElement('div');
            div.id = 'typing-indicator';
            div.className = 'flex items-start gap-3';
            div.innerHTML = `<div class="w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex-shrink-0 flex items-center justify-center text-sm">🤖</div>
                <div class="chat-bubble-ai p-3 rounded-2xl rounded-tl-none">
                    <div class="typing-indicator flex gap-1"><span class="w-2 h-2 bg-indigo-400 rounded-full"></span><span class="w-2 h-2 bg-indigo-400 rounded-full"></span><span class="w-2 h-2 bg-indigo-400 rounded-full"></span></div>
                </div>`;
            chatHistory.appendChild(div);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function removeTypingIndicator() {
            const indicator = document.getElementById('typing-indicator');
            if (indicator) indicator.remove();
        }

        // ===== PARSE AI RESPONSE & AUTO-FILL =====
        function parseAIResponse(text) {
            try {
                const levels = text.split(/\*\*Level\s*(\d+):\*\*/i);
                let parsed = {};

                for (let i = 1; i < levels.length; i += 2) {
                    const levelNum = parseInt(levels[i]);
                    const content = levels[i + 1] || '';

                    const qMatch = content.match(/Pertanyaan:\s*(.+?)(?=\n|A\.|$)/i);
                    const question = qMatch ? qMatch[1].trim() : '';

                    const optAMatch = content.match(/A\.\s*(.+?)(?=\n|B\.|$)/i);
                    const optBMatch = content.match(/B\.\s*(.+?)(?=\n|C\.|$)/i);
                    const optCMatch = content.match(/C\.\s*(.+?)(?=\n|Jawaban|$)/i);

                    const optA = optAMatch ? optAMatch[1].trim() : '';
                    const optB = optBMatch ? optBMatch[1].trim() : '';
                    const optC = optCMatch ? optCMatch[1].trim() : '';

                    const correctMatch = content.match(/Jawaban\s*Benar:\s*([ABC])/i);
                    let correct = 0;
                    if (correctMatch) {
                        const letter = correctMatch[1].toUpperCase();
                        correct = letter === 'A' ? 0 : letter === 'B' ? 1 : 2;
                    }

                    if (levelNum >= 1 && levelNum <= 3 && question) {
                        parsed[levelNum] = { q: question, options: [optA, optB, optC], correct: correct };
                    }
                }
                return parsed;
            } catch (e) {
                console.error('Parse error:', e);
                return null;
            }
        }

        function autoFillForms(parsedData) {
            if (!parsedData) return false;
            let filled = false;
            for (let lvl = 1; lvl <= 3; lvl++) {
                if (parsedData[lvl]) {
                    const d = parsedData[lvl];
                    const fields = [
                        document.getElementById('q' + lvl + '-question'),
                        document.getElementById('q' + lvl + '-optA'),
                        document.getElementById('q' + lvl + '-optB'),
                        document.getElementById('q' + lvl + '-optC'),
                        document.getElementById('q' + lvl + '-correct')
                    ];
                    fields[0].value = d.q || '';
                    fields[1].value = d.options[0] || '';
                    fields[2].value = d.options[1] || '';
                    fields[3].value = d.options[2] || '';
                    fields[4].value = d.correct.toString();
                    // Add highlight animation
                    fields.forEach(f => { f.classList.add('auto-filled'); setTimeout(() => f.classList.remove('auto-filled'), 1000); });
                    filled = true;
                }
            }
            return filled;
        }

        async function sendMessage() {
            const text = chatInput.value.trim();
            if (!text) return;
            addMessage('user', text);
            chatInput.value = '';
            showTypingIndicator();

            try {
                // Using PHP proxy (API key aman di server)
                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        message: text,
                        system_prompt: SYSTEM_PROMPT,
                        max_tokens: 1024,
                        temperature: 0.7
                    })
                });
                const data = await response.json();
                removeTypingIndicator();

                if (data.choices && data.choices[0] && data.choices[0].message) {
                    const aiResponse = data.choices[0].message.content;
                    addMessage('ai', aiResponse);
                    // Auto-fill forms
                    const parsed = parseAIResponse(aiResponse);
                    if (autoFillForms(parsed)) {
                        addMessage('ai', '✅ Soal berhasil diisi otomatis ke form! Cek dan edit jika perlu, lalu klik SIMPAN.');
                    }
                } else if (data.error) {
                    addMessage('ai', '❌ Error: ' + (data.error.message || data.error));
                } else {
                    addMessage('ai', '❌ Terjadi kesalahan. Coba lagi nanti.');
                }
            } catch (error) {
                removeTypingIndicator();
                addMessage('ai', '❌ Gagal menghubungi AI: ' + error.message);
            }
        }

        function saveToGame() {
            const questionsData = {
                1: { q: document.getElementById('q1-question').value.trim(), options: [document.getElementById('q1-optA').value.trim(), document.getElementById('q1-optB').value.trim(), document.getElementById('q1-optC').value.trim()], correct: parseInt(document.getElementById('q1-correct').value) },
                2: { q: document.getElementById('q2-question').value.trim(), options: [document.getElementById('q2-optA').value.trim(), document.getElementById('q2-optB').value.trim(), document.getElementById('q2-optC').value.trim()], correct: parseInt(document.getElementById('q2-correct').value) },
                3: { q: document.getElementById('q3-question').value.trim(), options: [document.getElementById('q3-optA').value.trim(), document.getElementById('q3-optB').value.trim(), document.getElementById('q3-optC').value.trim()], correct: parseInt(document.getElementById('q3-correct').value) }
            };
            for (let lvl = 1; lvl <= 3; lvl++) {
                if (!questionsData[lvl].q) { alert('⚠️ Pertanyaan Level ' + lvl + ' belum diisi!'); return; }
                for (let i = 0; i < 3; i++) { if (!questionsData[lvl].options[i]) { alert('⚠️ Pilihan ' + String.fromCharCode(65 + i) + ' Level ' + lvl + ' belum diisi!'); return; } }
            }
            localStorage.setItem('customQuestions', JSON.stringify(questionsData));
            alert('✅ Soal berhasil disimpan! Silakan mainkan game.');
        }

        sendBtn.addEventListener('click', sendMessage);
        chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); });
        saveBtn.addEventListener('click', saveToGame);

        window.addEventListener('DOMContentLoaded', () => {
            const existingData = localStorage.getItem('customQuestions');
            if (existingData) {
                try {
                    const data = JSON.parse(existingData);
                    for (let lvl = 1; lvl <= 3; lvl++) {
                        if (data[lvl]) {
                            document.getElementById('q' + lvl + '-question').value = data[lvl].q || '';
                            document.getElementById('q' + lvl + '-optA').value = data[lvl].options[0] || '';
                            document.getElementById('q' + lvl + '-optB').value = data[lvl].options[1] || '';
                            document.getElementById('q' + lvl + '-optC').value = data[lvl].options[2] || '';
                            document.getElementById('q' + lvl + '-correct').value = data[lvl].correct.toString();
                        }
                    }
                } catch (e) { console.error('Load error:', e); }
            }
        });
        // Bridge: accept questions from other origins (e.g., React app). Save to localStorage and ACK.
        window.addEventListener('message', (e) => {
            try {
                const msg = e.data || {};
                if (msg && msg.type === 'kk_sync_questions' && msg.payload) {
                    localStorage.setItem('customQuestions', JSON.stringify(msg.payload));
                    try { e.source && e.source.postMessage({ type: 'kk_sync_ack' }, '*'); } catch {}
                }
            } catch {}
        });
    </script>
</body>

</html>
