(function() {
    const WEBSOCKET_URL = 'wss://aktascorp.com:8081';
    const API_URL = 'https://aktascorp.com/support-chatbox-intgr/server.php';
    const CHATBOX_ID = 'imators-chatbox';
    
    let ws = null;
    let conversationId = null;
    let visitorId = localStorage.getItem('imators_visitor_id') || generateId();
    localStorage.setItem('imators_visitor_id', visitorId);
    
    function generateId() {
        return 'visitor_' + Math.random().toString(36).substr(2, 9) + Date.now();
    }
    
    function injectStyles() {
        const style = document.createElement('style');
        style.innerHTML = `
            @import url('https://fonts.googleapis.com/css2?family=Raleway:wght@300;400;500;600;700&display=swap');
            
            #${CHATBOX_ID} {
                position: fixed;
                bottom: 20px;
                right: 20px;
                z-index: 999999;
                font-family: 'Raleway', sans-serif;
            }
            
            #${CHATBOX_ID} .chat-toggle {
                width: 60px;
                height: 60px;
                background: white;
                border-radius: 50%;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                transition: all 0.3s ease;
            }
            
            #${CHATBOX_ID} .chat-toggle:hover {
                transform: scale(1.05);
                box-shadow: 0 6px 20px rgba(0,0,0,0.2);
            }
            
            #${CHATBOX_ID} .chat-toggle img {
                width: 35px;
                height: 35px;
                transition: transform 0.3s ease;
            }
            
            #${CHATBOX_ID}.active .chat-toggle img {
                transform: rotate(90deg);
            }
            
            #${CHATBOX_ID} .chat-window {
                position: absolute;
                bottom: 80px;
                right: 0;
                width: 380px;
                height: 480px;
                background: #f9f0e6;
                border-radius: 12px;
                box-shadow: 0 10px 40px rgba(0,0,0,0.1);
                display: flex;
                flex-direction: column;
                opacity: 0;
                transform: translateY(20px) scale(0.95);
                pointer-events: none;
                transition: all 0.3s ease;
                overflow: hidden;
            }
            
            #${CHATBOX_ID}.active .chat-window {
                opacity: 1;
                transform: translateY(0) scale(1);
                pointer-events: all;
            }
            
            #${CHATBOX_ID} .chat-header {
                background: white;
                padding: 20px;
                border-bottom: 1px solid #e5d5c8;
                display: flex;
                align-items: center;
                gap: 15px;
            }
            
            #${CHATBOX_ID} .chat-header img {
                width: 40px;
                height: 40px;
            }
            
            #${CHATBOX_ID} .chat-header-text h3 {
                margin: 0;
                font-size: 18px;
                font-weight: 500;
                color: #333;
            }
            
            #${CHATBOX_ID} .chat-header-text p {
                margin: 2px 0 0 0;
                font-size: 13px;
                color: #666;
                font-weight: 300;
            }
            
            #${CHATBOX_ID} .chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 20px;
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            
            #${CHATBOX_ID} .chat-messages::-webkit-scrollbar {
                width: 6px;
            }
            
            #${CHATBOX_ID} .chat-messages::-webkit-scrollbar-track {
                background: transparent;
            }
            
            #${CHATBOX_ID} .chat-messages::-webkit-scrollbar-thumb {
                background: #d4c4b0;
                border-radius: 3px;
            }
            
            #${CHATBOX_ID} .message {
                display: flex;
                align-items: flex-end;
                gap: 8px;
                animation: messageIn 0.3s ease;
            }
            
            @keyframes messageIn {
                from {
                    opacity: 0;
                    transform: translateY(10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            
            #${CHATBOX_ID} .message.visitor {
                flex-direction: row-reverse;
            }
            
            #${CHATBOX_ID} .message-bubble {
                max-width: 70%;
                padding: 12px 16px;
                border-radius: 18px;
                font-size: 14px;
                line-height: 1.5;
                font-weight: 400;
            }
            
            #${CHATBOX_ID} .message.visitor .message-bubble {
                background: #333;
                color: white;
                border-bottom-right-radius: 4px;
            }
            
            #${CHATBOX_ID} .message.admin .message-bubble {
                background: white;
                color: #333;
                border-bottom-left-radius: 4px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            }
            
            #${CHATBOX_ID} .message-time {
                font-size: 11px;
                color: #999;
                margin-top: 4px;
                font-weight: 300;
            }
            
            #${CHATBOX_ID} .chat-input {
                padding: 20px;
                background: white;
                border-top: 1px solid #e5d5c8;
                display: flex;
                gap: 12px;
                align-items: center;
            }
            
            #${CHATBOX_ID} .chat-input input {
                flex: 1;
                padding: 10px 16px;
                border: 1px solid #e5d5c8;
                border-radius: 24px;
                font-size: 14px;
                font-family: 'Raleway', sans-serif;
                outline: none;
                transition: all 0.2s;
                background: #f9f0e6;
            }
            
            #${CHATBOX_ID} .chat-input input:focus {
                background: white;
                border-color: #333;
            }
            
            #${CHATBOX_ID} .chat-input button {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                border: none;
                background: #333;
                color: white;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s;
                flex-shrink: 0;
            }
            
            #${CHATBOX_ID} .chat-input button:hover {
                background: #555;
                transform: scale(1.05);
            }
            
            #${CHATBOX_ID} .chat-input button svg {
                width: 18px;
                height: 18px;
                fill: white;
            }
            
            #${CHATBOX_ID} .connection-status {
                position: absolute;
                top: 25px;
                right: 20px;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: #4ade80;
            }
            
            #${CHATBOX_ID} .connection-status.disconnected {
                background: #f87171;
            }
            
            #${CHATBOX_ID} .welcome-message {
                text-align: center;
                padding: 40px 20px;
                color: #666;
            }
            
            #${CHATBOX_ID} .welcome-message h4 {
                font-size: 16px;
                font-weight: 500;
                margin-bottom: 8px;
                color: #333;
            }
            
            #${CHATBOX_ID} .welcome-message p {
                font-size: 14px;
                font-weight: 300;
            }
            
            @media (max-width: 480px) {
                #${CHATBOX_ID} .chat-window {
                    width: calc(100vw - 40px);
                    height: calc(100vh - 100px);
                    right: 20px;
                    bottom: 80px;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    function createChatbox() {
        const chatbox = document.createElement('div');
        chatbox.id = CHATBOX_ID;
        chatbox.innerHTML = `
            <div class="chat-window">
                <div class="connection-status"></div>
                <div class="chat-header">
                    <img src="https://aktascorp.com/ac.png" alt="AktasCorp">
                    <div class="chat-header-text">
                        <h3>Help services</h3>
                        <p>Nous sommes là pour vous aider</p>
                    </div>
                </div>
                <div class="chat-messages">
                    <div class="welcome-message">
                        <h4>Bienvenue !</h4>
                        <p>Comment pouvons-nous vous aider aujourd'hui ?</p>
                    </div>
                </div>
                <div class="chat-input">
                    <input type="text" placeholder="Écrivez votre message..." />
                    <button type="button">
                        <svg viewBox="0 0 24 24">
                            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                        </svg>
                    </button>
                </div>
            </div>
            <div class="chat-toggle">
                <img src="https://aktascorp.com/ac.png" alt="Chat">
            </div>
        `;
        
        document.body.appendChild(chatbox);
        
        const toggle = chatbox.querySelector('.chat-toggle');
        const input = chatbox.querySelector('.chat-input input');
        const sendButton = chatbox.querySelector('.chat-input button');
        const messagesContainer = chatbox.querySelector('.chat-messages');
        
        toggle.addEventListener('click', () => {
            chatbox.classList.toggle('active');
            if (chatbox.classList.contains('active')) {
                input.focus();
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        });
        
        function sendMessage() {
            const message = input.value.trim();
            if (message && ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 'message',
                    message: message
                }));
                
                addMessage('visitor', message);
                input.value = '';
                input.focus();
                
                const welcome = messagesContainer.querySelector('.welcome-message');
                if (welcome) welcome.remove();
            }
        }
        
        sendButton.addEventListener('click', sendMessage);
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }
    
    function addMessage(sender, message, messageId) {
        const messagesContainer = document.querySelector(`#${CHATBOX_ID} .chat-messages`);
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}`;
        
        const time = new Date().toLocaleTimeString('fr-FR', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
        
        messageDiv.innerHTML = `
            <div class="message-bubble">
                ${message}
                <div class="message-time">${time}</div>
            </div>
        `;
        
        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    
    function connectWebSocket() {
        ws = new WebSocket(WEBSOCKET_URL);
        const statusIndicator = document.querySelector(`#${CHATBOX_ID} .connection-status`);
        
        ws.onopen = () => {
            if (statusIndicator) statusIndicator.classList.remove('disconnected');
            ws.send(JSON.stringify({
                type: 'init',
                domain: window.location.hostname,
                visitorId: visitorId
            }));
        };
        
        ws.onmessage = (event) => {
            const data = JSON.parse(event.data);
            
            switch(data.type) {
                case 'init_complete':
                    conversationId = data.conversationId;
                    const messagesContainer = document.querySelector(`#${CHATBOX_ID} .chat-messages`);
                    if (data.messages && data.messages.length > 0) {
                        const welcome = messagesContainer.querySelector('.welcome-message');
                        if (welcome) welcome.remove();
                        
                        messagesContainer.innerHTML = '';
                        data.messages.forEach(msg => {
                            addMessage(msg.sender, msg.message, msg.id);
                        });
                    }
                    break;
                    
                case 'admin_message':
                    addMessage('admin', data.message, data.messageId);
                    if ('Notification' in window && Notification.permission === 'granted') {
                        new Notification('Nouveau message', { 
                            body: data.message,
                            icon: 'https://aktascorp.com/ac.png'
                        });
                    }
                    break;
            }
        };
        
        ws.onclose = () => {
            if (statusIndicator) statusIndicator.classList.add('disconnected');
            setTimeout(connectWebSocket, 3000);
        };
        
        ws.onerror = () => {
            if (statusIndicator) statusIndicator.classList.add('disconnected');
        };
    }
    
    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', init);
            return;
        }
        
        injectStyles();
        createChatbox();
        connectWebSocket();
        
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
    
    init();
})();