/**
 * Rig N Dig AI Core Helper
 * Handles Chatbot and Admin AI generation
 */

document.addEventListener('DOMContentLoaded', function() {
    // --- Chatbot Functionality ---
    const chatbotToggle = document.getElementById('chatbot-toggle');
    const chatbotWindow = document.getElementById('chatbot-window');
    const chatbotMessages = document.getElementById('chatbot-messages');
    const chatbotForm = document.getElementById('chatbot-form');
    const chatbotInput = document.getElementById('chatbot-input');
    const providerBadge = document.getElementById('ai-provider-badge');

    if (chatbotToggle && chatbotWindow) {
        chatbotToggle.addEventListener('click', () => {
            const isOpen = chatbotWindow.classList.toggle('open');
            chatbotToggle.setAttribute('data-open', isOpen);
            if (isOpen) chatbotInput.focus();
        });

        document.getElementById('chatbot-close')?.addEventListener('click', () => {
            chatbotWindow.classList.remove('open');
            chatbotToggle.setAttribute('data-open', 'false');
        });

        chatbotForm?.addEventListener('submit', async (e) => {
            e.preventDefault();
            const message = chatbotInput.value.trim();
            if (!message) return;

            // User message
            appendMessage('user', message);
            chatbotInput.value = '';

            // Typing indicator
            const typingId = appendTypingIndicator();

            try {
                const response = await callAI(message, 'chat');
                removeTypingIndicator(typingId);
                appendMessage('bot', response.response);
                if (providerBadge) providerBadge.textContent = 'Powered by ' + response.provider;
            } catch (error) {
                removeTypingIndicator(typingId);
                appendMessage('bot', 'System Error: ' + error.message, true);
            }
        });
    }

    // --- Admin Product AI Functionality ---
    const aiGenButtons = document.querySelectorAll('.btn-ai-generate');
    aiGenButtons.forEach(btn => {
        btn.addEventListener('click', async function() {
            const targetId = this.getAttribute('data-target');
            const type = this.getAttribute('data-type'); // 'description' or 'short'
            const productName = document.querySelector('input[name="name"]').value;
            
            if (!productName) {
                alert('Please enter a product name first.');
                return;
            }

            const originalBtnText = this.innerHTML;
            this.disabled = true;
            this.innerHTML = '<span class="animate-spin inline-block">⏳</span> Processing...';

            let prompt = "";
            if (type === 'short') {
                prompt = `Write a professional 1-sentence technical abstract for an industrial product named "${productName}". Use punchy, sales-oriented language. No placeholders.`;
            } else if (type === 'full') {
                prompt = `Write a deep technical paragraph (about 60-80 words) for an industrial asset named "${productName}". Mention precision, durability, and compliance with industry standards like API or ASME. Do not use generic filler words.`;
            } else if (type === 'sku') {
                prompt = `Generate a single short professional SKU for an industrial product named "${productName}". Format should be uppercase alphanumeric (e.g. RND-VL-192). ONLY RETURN THE SKU STRING.`;
            } else {
                prompt = `Generate a valid JSON object of key-value technical specifications for the product "${productName}". Only return the JSON. Example: {"Material": "Cast Steel", "Connection": "Flanged", "Standard": "API 600"}. No markdown code blocks, JUST the JSON string.`;
            }

            try {
                const response = await callAI(prompt, 'generate');
                const targetArea = document.querySelector(`textarea[name="${targetId}"]`);
                if (targetArea) {
                    targetArea.value = response.response;
                    targetArea.dispatchEvent(new Event('input')); // Trigger any auto-resize or sync
                }
            } catch (error) {
                alert('AI Generation Error: ' + error.message);
            } finally {
                this.disabled = false;
                this.innerHTML = originalBtnText;
            }
        });
    });

    // Helper functions
    async function callAI(prompt, mode) {
        const basePrefix = (window.SITE_URL || '').replace(/\/$/, '');
        // If site_url is empty, we check if we are in admin to prepend ..
        let resolver = basePrefix ? basePrefix + '/api/ai_handler.php' : 'api/ai_handler.php';
        if (!basePrefix && window.location.pathname.includes('/admin/')) {
            resolver = '../api/ai_handler.php';
        }

        const response = await fetch(resolver, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt, mode })
        });
        const data = await response.json();
        if (!response.ok || data.error) throw new Error(data.error || 'Failed to communicate with AI');
        return data;
    }

    function appendMessage(role, text, isError = false) {
        const div = document.createElement('div');
        div.className = `flex gap-3 message-animate ${role === 'user' ? 'flex-row-reverse' : ''}`;
        
        const icon = role === 'user' ? '👤' : '⚙️';
        const bg = role === 'user' ? 'bg-orange-600/20 border-orange-500/20' : 'bg-navy-800/50 border-white/5';
        const textColor = isError ? 'text-red-400' : 'text-gray-300';
        const align = role === 'user' ? 'rounded-tr-none' : 'rounded-tl-none';

        div.innerHTML = `
            <div class="w-8 h-8 rounded-lg bg-navy-800 border border-white/5 flex flex-shrink-0 items-center justify-center text-sm">${icon}</div>
            <div class="${bg} border p-3.5 rounded-2xl ${align} text-xs leading-relaxed ${textColor} max-w-[85%] whitespace-pre-wrap">${text}</div>
        `;
        
        chatbotMessages.appendChild(div);
        chatbotMessages.scrollTop = chatbotMessages.scrollHeight;
    }

    function appendTypingIndicator() {
        const id = 'typing-' + Date.now();
        const div = document.createElement('div');
        div.id = id;
        div.className = 'flex gap-3 message-animate';
        div.innerHTML = `
            <div class="w-8 h-8 rounded-lg bg-navy-800 border border-white/5 flex flex-shrink-0 items-center justify-center text-sm">⚙️</div>
            <div class="bg-navy-800/50 border border-white/5 p-3.5 rounded-2xl rounded-tl-none text-xs text-gray-400 flex items-center gap-1 typing-dots">
                <span></span><span></span><span></span>
            </div>
        `;
        chatbotMessages.appendChild(div);
        chatbotMessages.scrollTop = chatbotMessages.scrollHeight;
        return id;
    }

    function removeTypingIndicator(id) {
        document.getElementById(id)?.remove();
    }
});
