<?php
// Note: This file assumes 'config.php' and 'layouts.php' are correctly defined elsewhere.

require_once 'config.php';
// require_login(); 

// --- Layout Rendering (Assumed from layouts.php) ---
require_once 'layouts.php';
render_header('Class Keeper AI Chat'); // Title updated
render_sidebar($_SESSION['user_role'] ?? 'student', basename(__FILE__));

$topbar_nav = [
    ['label' => 'Dashboard', 'url' => 'dashboard.php'],
    ['label' => 'My Classes', 'url' => 'classes.php'],
    ['label' => 'AI Chat', 'url' => 'ai.php'], // Highlight AI Chat
    ['label' => 'Buy Classes', 'url' => 'buy.php'],
    ['label' => 'Profile', 'url' => 'profile.php'],
];
render_topbar($topbar_nav); 
?>

<style>
/* Base Styling */
body, .main-content-wrapper {
    background-color: #f7f9fc !important;
}
.chat-container {
    background-color: white;
    /* Stronger, more modern shadow */
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    border-radius: 16px;
    /* --- MODIFIED: Fixed height requested by user (800px) --- */
    height: 700px; 
    /* -------------------------------------------------------- */
    display: flex;
    flex-direction: column;
}
.chat-history {
    flex-grow: 1;
    overflow-y: auto;
    padding: 1.5rem;
}
.input-area {
    border-top: 1px solid #e5e7eb;
    padding: 1rem 1.5rem;
    background-color: #ffffff;
    border-radius: 0 0 16px 16px;
}
/* Ensure Sinhala text displays correctly */
.chat-container p, .chat-container h2, .chat-container button, .chat-container input {
    font-family: 'Noto Sans', sans-serif;
}
/* User message bubble */
.user-message {
    background-color: #6366f1; /* Indigo-500 */
    color: white;
    align-self: flex-end;
    max-width: 80%;
    margin-left: auto;
    border-radius: 14px 14px 0 14px; /* More rounded, distinct shape */
}
/* AI message bubble */
.ai-message {
    background-color: #eef2ff; /* Indigo-50 */
    color: #1f2937; /* Gray-800 */
    align-self: flex-start;
    max-width: 80%;
    margin-right: auto;
    border-radius: 14px 14px 14px 0; /* More rounded, distinct shape */
    white-space: pre-wrap; /* Preserve formatting for code/ASCII art */
}

/* ADVANCEMENT: Custom styling for code blocks (pre tags inside ai-message) */
.ai-message pre {
    background-color: #1f2937; /* Dark background */
    color: #e5e7eb; /* Light text (off-white) */
    padding: 1rem;
    border-radius: 8px;
    font-family: monospace;
    overflow-x: auto;
    border-left: 4px solid #6366f1; /* Indigo border for a modern look */
    line-height: 1.4;
    font-size: 0.9rem;
    margin-top: 1rem;
    margin-bottom: 1rem;
}

/* Style for the prompt input */
#promptInput {
    transition: all 0.2s;
}
#promptInput:focus {
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3); /* Custom ring color */
}
</style>

<!-- Wrapper for centering and limiting width on large screens. Removed max-w-5xl for full width. -->
<div class="px-4 sm:px-6 lg:px-8 py-4 bg-gray-50 h-full"> 
    
    <div class="w-full"> <!-- Full width applied here -->
        <div class="chat-container">
            <!-- Chat Header -->
            <div class="p-4 border-b border-gray-100 flex items-center">
                <h1 class="text-xl font-bold text-gray-900 flex items-center">
                    <div class="w-8 h-8 rounded-full bg-purple-600 text-white flex items-center justify-center text-sm font-black mr-3">AI</div>
                    <!-- Updated AI Name -->
                    <span class="text-purple-600">Class Keeper</span> AI
                </h1>
                <!-- Removed 'ADVANCED LEVEL PHYSICS' subtitle -->
            </div>

                <!-- Dynamic chat messages will be added here -->
            </div>

            <!-- Input Area -->
            <div class="input-area flex items-center space-x-3">
                <input type="text" id="promptInput" placeholder="ප්‍රශ්න/උපදෙස් සපයන්න: (Start Typing...)" class="flex-grow p-3 border border-gray-300 rounded-xl focus:ring-purple-500 focus:border-purple-500 transition duration-150">
                <button id="sendButton" class="bg-purple-600 hover:bg-purple-700 text-white p-3 rounded-xl shadow-lg transition duration-300 flex items-center justify-center disabled:opacity-50" disabled>
                    <!-- Send Icon -->
                    <svg class="w-6 h-6 transform rotate-90" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M1.946 9.315c-.522-.174-.527-.455.01-.634l19.087-6.362c.529-.176.832.12.684.638l-5.454 19.086c-.15.529-.466.529-.684.032L8.5 14.5l-6.096-3.804z"></path></svg>
                </button>
            </div>

        </div>
    </div>
</div>

<?php render_main_content_end(); ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const chatHistory = document.getElementById('chatHistory');
    const promptInput = document.getElementById('promptInput');
    const sendButton = document.getElementById('sendButton');

    const modelName = 'gemini-2.5-flash-preview-09-2025';
    const apiKey = "AIzaSyDTtu48EYGTEuSCjbVBp39fHwm_BYdHnQw"; // API Key is provided by the canvas environment

    // System instruction updated for a general academic tutor (Class Keeper AI)
    const systemPrompt = "You are Class Keeper AI, a highly knowledgeable and encouraging general academic tutor for all students. Your responses must be accurate, clear, and supportive across various subjects. You should use Sinhala when responding to a Sinhala query. For numerical answers, show steps. If asked to draw a curve or diagram, generate it using clean, simple ASCII art in a monospace font block.";
    
    // Simple state to track conversation history for subsequent requests
    let conversationHistory = [];

    // --- Utility Functions ---

    /**
     * Renders a message bubble to the chat history.
     * @param {string} text - The message content.
     * @param {string} role - 'user' or 'ai'.
     * @param {string} [sourcesHtml=''] - HTML for citations/sources (only for 'ai').
     */
    function renderMessage(text, role, sourcesHtml = '') {
        const messageDiv = document.createElement('div');
        messageDiv.className = `flex mb-4 ${role === 'user' ? 'justify-end' : 'justify-start'}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = `p-3 shadow-md text-sm ${role}-message`; 
        contentDiv.innerHTML = text;
        
        // Add sources below AI response
        if (role === 'ai' && sourcesHtml) {
            const sourcesDiv = document.createElement('div');
            sourcesDiv.className = 'mt-2 pt-2 border-t border-gray-200 text-xs text-gray-500';
            sourcesDiv.innerHTML = sourcesHtml;
            contentDiv.appendChild(sourcesDiv);
        }

        messageDiv.appendChild(contentDiv);
        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight; // Scroll to bottom
    }

    /**
     * Displays a temporary loading indicator.
     */
    function showLoading() {
        const loadingDiv = document.createElement('div');
        loadingDiv.id = 'loadingIndicator';
        loadingDiv.className = 'flex mb-4 justify-start';
        loadingDiv.innerHTML = `
            <div class="p-3 shadow-md text-sm ai-message">
                <div class="flex items-center space-x-2">
                    <svg class="animate-spin h-5 w-5 text-purple-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                    </svg>
                    <span>පිළිතුරු සකසමින්... (Generating response...)</span>
                </div>
            </div>
        `;
        chatHistory.appendChild(loadingDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    /**
     * Removes the loading indicator.
     */
    function hideLoading() {
        const loadingDiv = document.getElementById('loadingIndicator');
        if (loadingDiv) {
            loadingDiv.remove();
        }
    }

    /**
     * Formats citations into an HTML string.
     * @param {Array<Object>} sources - Array of source objects.
     * @returns {string} HTML string of citations.
     */
    function formatSources(sources) {
        if (!sources || sources.length === 0) return '';
        
        const listItems = sources.map((source, index) => `
            <li>
                [${index + 1}] <a href="${source.uri}" target="_blank" class="text-blue-500 hover:underline">${source.title || source.uri}</a>
            </li>
        `).join('');

        return `
            <p class="font-semibold mb-1">මූලාශ්‍ර (Sources):</p>
            <ul class="list-none space-y-0.5">${listItems}</ul>
        `;
    }

    /**
     * Handles the AI API call with exponential backoff.
     */
    async function fetchAiResponse(userQuery, history, retries = 0) {
        if (apiKey === "") {
             return { text: "සමාවෙන්න! API යතුර සකසා නැත. කෙසේ වෙතත්, මෙය Gemini AI API හරහා ක්‍රියාත්මක වේ.", sources: [] };
        }
        
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:generateContent?key=${apiKey}`;
        const maxRetries = 5;
        const delay = Math.pow(2, retries) * 1000; // 1s, 2s, 4s, 8s, 16s

        const chatParts = history.map(msg => ({ 
            role: msg.role === 'user' ? 'user' : 'model', 
            parts: [{ text: msg.text }] 
        }));

        chatParts.push({ role: 'user', parts: [{ text: userQuery }] });

        const payload = {
            contents: chatParts,
            tools: [{ "google_search": {} }], // Enable search grounding
            systemInstruction: {
                parts: [{ text: systemPrompt }]
            },
        };

        try {
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                if (response.status === 429 && retries < maxRetries) {
                    await new Promise(resolve => setTimeout(resolve, delay));
                    return fetchAiResponse(userQuery, history, retries + 1); // Retry
                }
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            const candidate = result.candidates?.[0];

            if (candidate && candidate.content?.parts?.[0]?.text) {
                const text = candidate.content.parts[0].text;
                let sources = [];
                const groundingMetadata = candidate.groundingMetadata;
                
                if (groundingMetadata && groundingMetadata.groundingAttributions) {
                    sources = groundingMetadata.groundingAttributions
                        .map(attribution => ({
                            uri: attribution.web?.uri,
                            title: attribution.web?.title,
                        }))
                        .filter(source => source.uri && source.title); 
                }
                
                return { text, sources };

            } else {
                return { text: "සමාවෙන්න! පිළිතුරක් ලබා ගැනීමට නොහැකි විය. කරුණාකර නැවත උත්සාහ කරන්න.", sources: [] };
            }

        } catch (error) {
            console.error('API Call Error:', error);
            if (retries < maxRetries) {
                await new Promise(resolve => setTimeout(resolve, delay));
                return fetchAiResponse(userQuery, history, retries + 1); // Retry
            }
            return { text: "තාක්ෂණික දෝෂයක්. කරුණාකර නැවත උත්සාහ කරන්න.", sources: [] };
        }
    }

    /**
     * Main function to handle sending a message.
     */
    async function sendMessage() {
        const prompt = promptInput.value.trim();
        if (prompt === '') return;

        // 1. Clear input and disable button
        promptInput.value = '';
        sendButton.disabled = true;

        // 2. Render user message
        renderMessage(prompt, 'user');

        // 3. Add user message to history
        conversationHistory.push({ role: 'user', text: prompt });

        // 4. Show loading indicator
        showLoading();

        // 5. Call AI API
        const { text: aiResponseText, sources: aiSources } = await fetchAiResponse(prompt, conversationHistory);

        // 6. Hide loading indicator
        hideLoading();

        // 7. Format the response and sources
        const sourcesHtml = formatSources(aiSources);
        
        // ADVANCEMENT: Use the new CSS style for pre tags
        let formattedText = aiResponseText
            .replace(/```(.*?)```/gs, (match, code) => `<pre>${code.trim()}</pre>`)
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // Bold text
            .replace(/\*(.*?)\*/g, '<em>$1</em>') // Italic text
            .replace(/\n/g, '<br>'); // Simple newline replacement for Sinhala text

        // 8. Render AI response
        renderMessage(formattedText, 'ai', sourcesHtml);

        // 9. Add AI response to history
        conversationHistory.push({ role: 'ai', text: aiResponseText });

        // 10. Re-enable button
        sendButton.disabled = false;
        promptInput.focus();
    }

    // --- Event Listeners ---
    sendButton.addEventListener('click', sendMessage);
    
    promptInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !sendButton.disabled) {
            sendMessage();
        }
    });

    // Enable button only when input is not empty
    promptInput.addEventListener('input', () => {
        sendButton.disabled = promptInput.value.trim() === '';
    });
    
    // Initial state: ensure button is disabled if input is empty on load
    sendButton.disabled = true;
});
</script>