// ===================================
// Flutter AI Assistant - Main Script
// ===================================

// Configuration
const API_ENDPOINT = 'api/chat.php';

// DOM Elements
const chatForm = document.getElementById('chatForm');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const messagesContainer = document.getElementById('messagesContainer');

// Conversation History
let conversationHistory = [];

// Initialize
document.addEventListener('DOMContentLoaded', () => {
    chatForm.addEventListener('submit', handleSubmit);
    userInput.addEventListener('keydown', handleKeyPress);

    // Focus input on load
    userInput.focus();
});

// Handle form submission
async function handleSubmit(e) {
    e.preventDefault();

    const message = userInput.value.trim();
    if (!message) return;

    // Clear input
    userInput.value = '';

    // Remove welcome message if exists
    const welcomeMsg = document.querySelector('.welcome-message');
    if (welcomeMsg) {
        welcomeMsg.remove();
    }

    // Add user message to UI
    addMessage(message, 'user');

    // Disable input while processing
    setLoading(true);

    // Add typing indicator
    const typingIndicator = addTypingIndicator();

    try {
        // Send to API
        const response = await sendMessageToAPI(message);

        // Remove typing indicator
        typingIndicator.remove();

        // Add AI response
        addMessage(response, 'ai');

        // Update conversation history
        conversationHistory.push(
            { role: 'user', content: message },
            { role: 'assistant', content: response }
        );

    } catch (error) {
        // Remove typing indicator
        typingIndicator.remove();

        // Show error message
        addErrorMessage(error.message);
    } finally {
        // Re-enable input
        setLoading(false);
        userInput.focus();
    }
}

// Send message to API
async function sendMessageToAPI(message) {
    try {
        const response = await fetch(API_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                message: message,
                history: conversationHistory.slice(-10) // Last 5 exchanges
            })
        });

        if (!response.ok) {
            throw new Error(`Server error: ${response.status}`);
        }

        const data = await response.json();

        if (data.error) {
            throw new Error(data.error);
        }

        return data.response;

    } catch (error) {
        console.error('API Error:', error);
        throw new Error('Failed to get response. Please check your connection and try again.');
    }
}

// Add message to chat
function addMessage(text, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;

    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.textContent = type === 'user' ? '👤' : '🤖';

    const content = document.createElement('div');
    content.className = 'message-content';

    // Format message with basic markdown support
    content.innerHTML = formatMessage(text);

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(content);

    messagesContainer.appendChild(messageDiv);

    // Smooth scroll to bottom
    scrollToBottom();

    return messageDiv;
}

// Format message with markdown-like syntax
function formatMessage(text) {
    // Escape HTML
    let formatted = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

    // Code blocks with language detection (```language\ncode```)
    formatted = formatted.replace(/```(\w+)?\n?([\s\S]*?)```/g, function (match, language, code) {
        const lang = language || 'code';
        const codeId = 'code-' + Math.random().toString(36).substr(2, 9);
        return `<pre><div class="code-header"><span class="code-language">${lang}</span><button class="copy-btn" onclick="copyCode('${codeId}')">Copy</button></div><code id="${codeId}">${applySyntaxHighlight(code.trim(), lang)}</code></pre>`;
    });

    // Inline code (`code`)
    formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>');

    // Bold (**text**)
    formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');

    // Italic (*text*)
    formatted = formatted.replace(/\*([^*]+)\*/g, '<em>$1</em>');

    // Auto-link URLs
    formatted = formatted.replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');

    // Line breaks
    formatted = formatted.replace(/\n/g, '<br>');

    return formatted;
}

// Basic syntax highlighting
function applySyntaxHighlight(code, language) {
    // Keywords for different languages
    const keywords = {
        dart: ['class', 'void', 'return', 'if', 'else', 'for', 'while', 'import', 'extends', 'implements', 'final', 'const', 'var', 'String', 'int', 'double', 'bool', 'List', 'Map', 'Widget', 'StatelessWidget', 'StatefulWidget', 'State', 'BuildContext', 'async', 'await', 'Future'],
        javascript: ['function', 'const', 'let', 'var', 'return', 'if', 'else', 'for', 'while', 'class', 'extends', 'import', 'export', 'async', 'await', 'Promise'],
        python: ['def', 'class', 'return', 'if', 'else', 'elif', 'for', 'while', 'import', 'from', 'as', 'try', 'except', 'with', 'async', 'await'],
        php: ['function', 'class', 'return', 'if', 'else', 'foreach', 'while', 'public', 'private', 'protected', 'static', 'namespace', 'use']
    };

    let highlighted = code;
    const langKeywords = keywords[language.toLowerCase()] || keywords.dart;

    // Highlight strings
    highlighted = highlighted.replace(/(['"`])(.*?)\1/g, '<span class="string">$1$2$1</span>');

    // Highlight comments
    highlighted = highlighted.replace(/\/\/(.*?)$/gm, '<span class="comment">//$1</span>');
    highlighted = highlighted.replace(/\/\*([\s\S]*?)\*\//g, '<span class="comment">/*$1*/</span>');

    // Highlight keywords
    langKeywords.forEach(keyword => {
        const regex = new RegExp(`\\b(${keyword})\\b`, 'g');
        highlighted = highlighted.replace(regex, '<span class="keyword">$1</span>');
    });

    // Highlight numbers
    highlighted = highlighted.replace(/\b(\d+)\b/g, '<span class="number">$1</span>');

    return highlighted;
}

// Copy code to clipboard
function copyCode(codeId) {
    const codeElement = document.getElementById(codeId);
    if (!codeElement) return;

    // Get text content without HTML tags
    const code = codeElement.innerText || codeElement.textContent;

    // Copy to clipboard
    navigator.clipboard.writeText(code).then(() => {
        // Find the copy button
        const btn = codeElement.parentElement.querySelector('.copy-btn');
        if (btn) {
            const originalText = btn.textContent;
            btn.textContent = 'Copied!';
            btn.classList.add('copied');

            setTimeout(() => {
                btn.textContent = originalText;
                btn.classList.remove('copied');
            }, 2000);
        }
    }).catch(err => {
        console.error('Failed to copy:', err);
        alert('Failed to copy code');
    });
}

// Add typing indicator
function addTypingIndicator() {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message ai';

    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.textContent = '🤖';

    const content = document.createElement('div');
    content.className = 'message-content';

    const typingDiv = document.createElement('div');
    typingDiv.className = 'typing-indicator active';
    typingDiv.innerHTML = '<span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span>';

    content.appendChild(typingDiv);
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(content);

    messagesContainer.appendChild(messageDiv);
    scrollToBottom();

    return messageDiv;
}

// Add error message
function addErrorMessage(errorText) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.innerHTML = `<strong>⚠️ Error:</strong> ${errorText}`;

    messagesContainer.appendChild(errorDiv);
    scrollToBottom();

    // Auto-remove after 5 seconds
    setTimeout(() => {
        errorDiv.style.animation = 'fadeOut 0.3s ease';
        setTimeout(() => errorDiv.remove(), 300);
    }, 5000);
}

// Set loading state
function setLoading(isLoading) {
    sendBtn.disabled = isLoading;
    userInput.disabled = isLoading;

    if (isLoading) {
        sendBtn.textContent = 'Thinking... 🧠';
        chatForm.classList.add('loading');
    } else {
        sendBtn.textContent = 'Send 🚀';
        chatForm.classList.remove('loading');
    }
}

// Smooth scroll to bottom
function scrollToBottom() {
    messagesContainer.scrollTo({
        top: messagesContainer.scrollHeight,
        behavior: 'smooth'
    });
}

// Handle Enter key (Shift+Enter for new line)
function handleKeyPress(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        chatForm.dispatchEvent(new Event('submit'));
    }
}

// Send suggestion chip message
function sendSuggestion(text) {
    userInput.value = text;
    chatForm.dispatchEvent(new Event('submit'));
}

// Add fade out animation to CSS dynamically
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
`;
document.head.appendChild(style);
