/**
 * ENT Hospital Chatbot Widget
 * Embeddable chatbot for external websites
 */
(function() {
    'use strict';
    // Configuration
    const CONFIG = {
        apiUrl: window.location.origin + '/api/chatbot_public.php',
        position: 'bottom-right', // bottom-right, bottom-left
        primaryColor: '#059669',
        botName: 'Prodigy ENT AI Assistant',
        welcomeMessage: 'Hi! How can I help you today?'
    };
    // Generate unique session ID
    function generateSessionId() {
        return 'guest_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    // Get or create session ID
    function getSessionId() {
        let sessionId = sessionStorage.getItem('ent_chatbot_session');
        if (!sessionId) {
            sessionId = generateSessionId();
            sessionStorage.setItem('ent_chatbot_session', sessionId);
        }
        return sessionId;
    }
    // Create widget HTML
    function createWidget() {
        const widgetHTML = `
            <div id="ent-chatbot-widget" style="display: none;">
                <!-- Chat Button -->
                <button id="ent-chat-button" aria-label="Open chat">
                    <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <!-- Robot head -->
                        <rect x="7" y="4" width="10" height="8" rx="2" />
                        <!-- Eyes -->
                        <circle class="robot-eye" cx="10" cy="8" r="1.5" />
                        <circle class="robot-eye" cx="14" cy="8" r="1.5" />
                        <!-- Mouth -->
                        <path class="robot-mouth" d="M10 12h4" />
                        <!-- Antennae -->
                        <path class="robot-antenna" d="M12 2v2" />
                    </svg>
                    <span id="ent-chat-badge" style="display: none;">1</span>
                </button>
                <!-- Chat Window -->
                <div id="ent-chat-window" style="display: none;">
                    <!-- Header -->
                    <div id="ent-chat-header">
                        <div class="ent-chat-header-content">
                            <div class="ent-chat-avatar">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/>
                                </svg>
                            </div>
                            <div class="ent-chat-title">
                                <div class="ent-chat-name">${CONFIG.botName}</div>
                                <div class="ent-chat-status">
                                    <span class="ent-status-dot"></span>
                                    Online
                                </div>
                            </div>
                        </div>
                        <button id="ent-chat-close" aria-label="Close chat">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </button>
                    </div>
                    <!-- Messages Container -->
                    <div id="ent-chat-messages">
                        <div class="ent-welcome-message">
                            <div class="ent-message ent-bot-message">
                                <div class="ent-message-avatar">🤖</div>
                                <div class="ent-message-content">
                                    <div class="ent-message-text">${CONFIG.welcomeMessage}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- Quick Actions -->
                    <div id="ent-quick-actions">
                        <button class="ent-quick-btn" data-message="I want to book an appointment">
                            📅 Book Appointment
                        </button>
                        <button class="ent-quick-btn" data-message="What are your visiting hours?">
                            🕐 Visiting Hours
                        </button>
                        <button class="ent-quick-btn" data-message="I have ear pain">
                            👂 ENT Symptoms
                        </button>
                    </div>
                    <!-- Typing Indicator -->
                    <div id="ent-typing-indicator" style="display: none;">
                        <div class="ent-message ent-bot-message">
                            <div class="ent-message-avatar">🤖</div>
                            <div class="ent-typing-dots">
                                <span></span><span></span><span></span>
                            </div>
                        </div>
                    </div>
                    <!-- Input Area -->
                    <div id="ent-chat-input-area">
                        <textarea
                            id="ent-chat-input"
                            placeholder="Type your message..."
                            rows="1"
                        ></textarea>
                        <button id="ent-chat-send" aria-label="Send message">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                            </svg>
                        </button>
                    </div>
                    <!-- Footer -->
                    <div id="ent-chat-footer">
                        <span>Powered by Prodigy ENT AI</span>
                    </div>
                </div>
            </div>
        `;
        // Inject HTML
        const container = document.createElement('div');
        container.innerHTML = widgetHTML;
        document.body.appendChild(container.firstElementChild);
    }
    // Create and inject CSS
    function injectStyles() {
        const styles = `
            #ent-chatbot-widget * {
                box-sizing: border-box;
                margin: 0;
                padding: 0;
            }
            #ent-chatbot-widget {
                position: fixed;
                ${CONFIG.position.includes('right') ? 'right: 20px;' : 'left: 20px;'}
                bottom: 20px;
                z-index: 999999;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            }
            #ent-chat-button {
                width: 60px;
                height: 60px;
                border-radius: 50%;
                background: ${CONFIG.primaryColor};
                color: white;
                border: none;
                cursor: pointer;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
                position: relative;
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0%, 100% { transform: scale(1); }
                50% { transform: scale(1.05); }
            }
            #ent-chat-button:hover {
                transform: scale(1.1);
                box-shadow: 0 6px 20px rgba(0,0,0,0.2);
            }
            /* Robot eye animation */
            .robot-eye {
                animation: blink 4s infinite;
            }
            @keyframes blink {
                0%, 45%, 55%, 100% { transform: scaleY(1); }
                50% { transform: scaleY(0.1); }
            }
            /* Robot mouth animation */
            .robot-mouth {
                animation: talk 3s infinite;
            }
            @keyframes talk {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(1px); }
            }
            /* Robot antenna animation */
            .robot-antenna {
                animation: wiggle 2s infinite;
            }
            @keyframes wiggle {
                0%, 100% { transform: rotate(0deg); }
                25% { transform: rotate(10deg); }
                75% { transform: rotate(-10deg); }
            }
            #ent-chat-badge {
                position: absolute;
                top: -5px;
                right: -5px;
                background: #dc2626;
                color: white;
                border-radius: 50%;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                font-weight: bold;
            }
            #ent-chat-window {
                position: absolute;
                bottom: 80px;
                ${CONFIG.position.includes('right') ? 'right: 0;' : 'left: 0;'}
                width: 380px;
                height: 600px;
                max-height: calc(100vh - 120px);
                background: white;
                border-radius: 12px;
                box-shadow: 0 8px 30px rgba(0,0,0,0.12);
                display: flex;
                flex-direction: column;
                overflow: hidden;
                animation: slideUp 0.3s ease;
            }
            @keyframes slideUp {
                from {
                    opacity: 0;
                    transform: translateY(20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            #ent-chat-header {
                background: ${CONFIG.primaryColor};
                color: white;
                padding: 16px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .ent-chat-header-content {
                display: flex;
                align-items: center;
                gap: 12px;
            }
            .ent-chat-avatar {
                width: 40px;
                height: 40px;
                background: rgba(255,255,255,0.2);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .ent-chat-name {
                font-weight: 600;
                font-size: 16px;
            }
            .ent-chat-status {
                font-size: 12px;
                opacity: 0.9;
                display: flex;
                align-items: center;
                gap: 6px;
            }
            .ent-status-dot {
                width: 8px;
                height: 8px;
                background: #10b981;
                border-radius: 50%;
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.5; }
            }
            #ent-chat-close {
                background: none;
                border: none;
                color: white;
                cursor: pointer;
                padding: 4px;
                opacity: 0.8;
                transition: opacity 0.2s;
            }
            #ent-chat-close:hover {
                opacity: 1;
            }
            #ent-chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 16px;
                background: #f8fafc;
            }
            #ent-chat-messages::-webkit-scrollbar {
                width: 6px;
            }
            #ent-chat-messages::-webkit-scrollbar-thumb {
                background: #cbd5e1;
                border-radius: 3px;
            }
            .ent-message {
                margin-bottom: 16px;
                display: flex;
                gap: 8px;
            }
            .ent-user-message {
                flex-direction: row-reverse;
            }
            .ent-message-avatar {
                width: 32px;
                height: 32px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 18px;
                flex-shrink: 0;
            }
            .ent-message-content {
                max-width: 70%;
            }
            .ent-message-text {
                padding: 10px 14px;
                word-wrap: break-word;
                line-height: 1.5;
                font-size: 14px;
            }
            .ent-bot-message .ent-message-text {
                color: #1e293b;
            }
            .ent-user-message .ent-message-text {
                color: #059669;
            }
            .ent-message-time {
                font-size: 11px;
                color: #64748b;
                margin-top: 4px;
                padding: 0 4px;
            }
            #ent-quick-actions {
                padding: 12px 16px;
                display: flex;
                gap: 8px;
                flex-wrap: wrap;
                background: white;
                border-top: 1px solid #e2e8f0;
            }
            .ent-quick-btn {
                padding: 8px 12px;
                background: white;
                border: 1px solid #e2e8f0;
                border-radius: 8px;
                font-size: 13px;
                cursor: pointer;
                transition: all 0.2s;
                color: #475569;
            }
            .ent-quick-btn:hover {
                background: #f0fdf4;
                border-color: ${CONFIG.primaryColor};
                color: ${CONFIG.primaryColor};
            }
            .ent-typing-dots {
                display: flex;
                gap: 4px;
                padding: 12px 16px;
                border-radius: 12px;
            }
            .ent-typing-dots span {
                width: 8px;
                height: 8px;
                background: #94a3b8;
                border-radius: 50%;
                animation: typing 1.4s infinite;
            }
            .ent-typing-dots span:nth-child(2) {
                animation-delay: 0.2s;
            }
            .ent-typing-dots span:nth-child(3) {
                animation-delay: 0.4s;
            }
            @keyframes typing {
                0%, 60%, 100% { transform: translateY(0); }
                30% { transform: translateY(-6px); }
            }
            #ent-chat-input-area {
                padding: 16px;
                background: white;
                border-top: 1px solid #e2e8f0;
                display: flex;
                gap: 8px;
                align-items: flex-end;
            }
            #ent-chat-input {
                flex: 1;
                border: 1px solid #e2e8f0;
                border-radius: 8px;
                padding: 10px 12px;
                font-size: 14px;
                font-family: inherit;
                resize: none;
                max-height: 100px;
                line-height: 1.5;
            }
            #ent-chat-input:focus {
                outline: none;
                border-color: ${CONFIG.primaryColor};
            }
            #ent-chat-send {
                width: 40px;
                height: 40px;
                background: ${CONFIG.primaryColor};
                color: white;
                border: none;
                border-radius: 8px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s;
                flex-shrink: 0;
            }
            #ent-chat-send:hover {
                background: #047857;
            }
            #ent-chat-send:disabled {
                opacity: 0.5;
                cursor: not-allowed;
            }
            #ent-chat-footer {
                padding: 8px 16px;
                text-align: center;
                font-size: 11px;
                color: #94a3b8;
                background: #f8fafc;
                border-top: 1px solid #e2e8f0;
            }
            @media (max-width: 480px) {
                #ent-chat-window {
                    width: calc(100vw - 40px);
                    height: calc(100vh - 120px);
                    max-width: 380px;
                }
            }
        `;
        const styleSheet = document.createElement('style');
        styleSheet.textContent = styles;
        document.head.appendChild(styleSheet);
    }
    // Initialize chat functionality
    function initializeChat() {
        const widget = document.getElementById('ent-chatbot-widget');
        const button = document.getElementById('ent-chat-button');
        const window_elem = document.getElementById('ent-chat-window');
        const closeBtn = document.getElementById('ent-chat-close');
        const input = document.getElementById('ent-chat-input');
        const sendBtn = document.getElementById('ent-chat-send');
        const messagesContainer = document.getElementById('ent-chat-messages');
        let isOpen = false;
        const sessionId = getSessionId();
        let conversationId = null;
        // Toggle chat window
        button.addEventListener('click', () => {
            isOpen = !isOpen;
            window_elem.style.display = isOpen ? 'flex' : 'none';
            button.style.display = isOpen ? 'none' : 'flex';
            if (isOpen) {
                input.focus();
                document.getElementById('ent-chat-badge').style.display = 'none';
            }
        });
        closeBtn.addEventListener('click', () => {
            isOpen = false;
            window_elem.style.display = 'none';
            button.style.display = 'flex';
        });
        // Handle quick action buttons
        document.querySelectorAll('.ent-quick-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const message = btn.getAttribute('data-message');
                sendMessage(message);
            });
        });
        // Handle input
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        input.addEventListener('input', () => {
            input.style.height = 'auto';
            input.style.height = input.scrollHeight + 'px';
        });
        sendBtn.addEventListener('click', () => sendMessage());
        // Send message function
        function sendMessage(messageText = null) {
            const text = messageText || input.value.trim();
            if (!text) return;
            // Clear input
            if (!messageText) {
                input.value = '';
                input.style.height = 'auto';
            }
            // Add user message
            addMessage(text, 'user');
            // Show typing indicator
            showTypingIndicator();
            // Send to API
            fetch(CONFIG.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: text,
                    session_id: sessionId,
                    conversation_id: conversationId,
                    user_agent: navigator.userAgent,
                    referrer: document.referrer
                })
            })
            .then(response => response.json())
            .then(data => {
                hideTypingIndicator();
                if (data.success) {
                    if (data.conversation_id) {
                        conversationId = data.conversation_id;
                    }
                    addMessage(data.response, 'bot');
                    // Handle special actions
                    if (data.action_required) {
                        handleAction(data.action_required, data.action_data);
                    }
                } else {
                    addMessage('Sorry, I encountered an error. Please try again.', 'bot');
                }
            })
            .catch(error => {
                hideTypingIndicator();
                addMessage('Connection error. Please check your internet and try again.', 'bot');
                console.error('Chat error:', error);
            });
        }
        // Add message to chat
        function addMessage(text, type) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `ent-message ${type === 'user' ? 'ent-user-message' : 'ent-bot-message'}`;
            const avatar = document.createElement('div');
            avatar.className = 'ent-message-avatar';
            avatar.textContent = type === 'user' ? '👤' : '🤖';
            const contentDiv = document.createElement('div');
            contentDiv.className = 'ent-message-content';
            const textDiv = document.createElement('div');
            textDiv.className = 'ent-message-text';
            textDiv.textContent = text;
            const timeDiv = document.createElement('div');
            timeDiv.className = 'ent-message-time';
            timeDiv.textContent = new Date().toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit'
            });
            contentDiv.appendChild(textDiv);
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(contentDiv);
            // Remove welcome message if present
            const welcome = messagesContainer.querySelector('.ent-welcome-message');
            if (welcome && type === 'user') {
                welcome.remove();
            }
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        // Show/hide typing indicator
        function showTypingIndicator() {
            document.getElementById('ent-typing-indicator').style.display = 'block';
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
        function hideTypingIndicator() {
            document.getElementById('ent-typing-indicator').style.display = 'none';
        }
        // Handle special actions
        function handleAction(action, data) {
            switch(action) {
                case 'show_emergency':
                    addMessage('🚨 Emergency Contact: +254-700-000-111', 'bot');
                    break;
                case 'redirect_booking':
                    setTimeout(() => {
                        if (confirm('Would you like to visit our appointment booking page?')) {
                            window.open(data.url, '_blank');
                        }
                    }, 1000);
                    break;
            }
        }
    }
    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    function init() {
        injectStyles();
        createWidget();
        initializeChat();
        // Show widget after short delay
        setTimeout(() => {
            document.getElementById('ent-chatbot-widget').style.display = 'block';
        }, 1000);
    }
})();
