I created a browser extension that uses huggingface models directly via APIs for chatting. I want it to have three models for each language, that is English, Spanish and German. Incorporate a mechanism to detect a language automatically and use a single API call to get response from all the three models for that particular language. Start by showing response from the first model and include a next button that will show response from the other models. Use PostgreSQL database.
Please include features below;
Chat Interface
* Floating Chat Window: A draggable and resizable chat window that only shows up when I click on the "Chat" button in the popup. Remember to include this button in the html, allowing seamless interaction with the AI assistant. The floating chat window should not interfere with existing page style. It should appear on top without altering settings of other web pages.
* User Interaction: You can send text messages to the AI, and receive responses using selected AI models for the input language.
AI Model Integration
* Model Selection: Inlcude 3 chat models for English, 3 chat models for German and 3 chat models for Spanish provided by the Huggingface platform via inference API (e.g., GPT-2, BART Large, T5 Base) to generate responses. Let user be able to add or delete models in settings.
* Language Support: The chat assistant supports multiple languages for input and translation (e.g., English, Spanish, French, German).
Customization & Persistence
* Theme Personalization: Users can switch between light and dark themes according to their preference.
* Custom Models: Users can add custom AI models if they have specific needs or preferred configurations.
* Language and Model Settings: Users' preferred language and chosen model persist across sessions via local storage.
Settings and Configuration
* Popup Settings Page: Create a button to open settings page accessible from the browser extension, allowing users to adjust their default language, theme, manage custom models, and input their Huggingface API key.
* Local Storage: Settings are stored locally, ensuring user preferences are maintained.
Chat Features
* Chat History: Previous chat interactions are saved on PostgreSQL and can be accessed later.
* Translate Messages: Users can translate messages into different languages through the extension.
Background Services
* API Communication: Background scripts handle the API requests to the server, which queries the Huggingface models for generating responses. Include mechanism to interchange between two APIs 
* Session Management: Manages unique user sessions to store chat history and settings tied to particular sessions.
Miscellaneous
* Cache Mechanism: Implements a caching system to store API responses temporarily, reducing redundant API calls.
* Retry Logic: Uses retry logic to handle temporary network failures when communicating with the Huggingface API.
* Logging: Logs important events and errors to a file and stream, aiding in troubleshooting and monitoring the extension's behavior.

I also want advanced features as below:
This code provides a complete implementation of the content.js and background.js files with the following enhanced features:
1. Visual Features:
* Draggable chat window
* Smooth animations for messages and panels
* Theme support (light/dark)
* Loading indicators
* Error messages with animations
* Tooltips for buttons
1. Enhanced Model Selection:
* Dropdown for model selection
* Custom model support
* Model information display
* Language selection dropdown
1. User Settings Interface:
* Settings panel with theme selection
* Language preferences
* Custom model management
* API key configuration
1. Chat History Visualization:
* Sliding history panel
* Timestamp display
* Model information for each message
* Clickable history items
* Search functionality (can be implemented)
1. Error Handling Improvements:
* Graceful error displays
* Retry mechanism for failed requests
* Network error handling
* API error handling
* Invalid response handling
1. Performance Optimizations:
* Message caching
* Debounced input handling
* Lazy loading of history
* Efficient DOM updates
* Memory management

I created below code, but when I load it, it only shows the settings page in popup.html and even after updating the settings the page doesn't go away, so please add a close utton on settings page to be able to exit after updating the settings. So I cannot access the chat interface. Can you change that code and add a button on settings page to open the chat interface and also let settings icon appear at the top on chat interface with option to exit it after changing the settings. Also, I signed up and subscribed to two accounts on hugghuggingface so I have two API keys, can you make the app use both APIs in case one fails or reaches the limit. Make it able to change if one API encounters an error and also include retry mechanism automatically. I want the floating window to appear on top of an existing page without changing the site's format. I realized my code was making sites to appear on half of the screen. I don't want that. Let all sites maintain their original style and format and my floating window should appear on top of it with the option to minimize it and drag it from one corner to the other. Also include resizing abilities. Ensure the database being used is PostgreSQL and use asyncio where possible. I want it to use one single API call to get responses from all the three models at once. Also, if possible, use the browsers language detection to check the input language and then use models for that language to generate responses.

#app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, JSON
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import URL
from datetime import datetime
import os
import json

app = Flask(__name__)
CORS(app)

# Database configuration
DATABASE_URL = URL('postgresql', username='Benrajj', password='Benrajj@6690', host='localhost', port=5432, database='Chatbot', query={})
engine = create_engine(DATABASE_URL)
Base = sqlalchemy.orm.declarative_base()
Session = sessionmaker(bind=engine)

class ChatMessage(Base):
    __tablename__ = 'chat_messages'

    id = Column(Integer, primary_key=True)
    user_id = Column(String(100))
    message = Column(Text)
    responses = Column(JSON)
    language = Column(String(10))
    timestamp = Column(DateTime, default=datetime.utcnow)
    session_id = Column(String(100))

# Create tables
Base.metadata.create_all(engine)

@app.route('/api/messages', methods=['POST'])
def save_message():
    try:
        data = request.json
        session = Session()
        
        message = ChatMessage(
            user_id=data.get('user_id'),
            message=data.get('message'),
            responses=data.get('responses'),
            language=data.get('language'),
            session_id=data.get('session_id')
        )
        
        session.add(message)
        session.commit()
        
        return jsonify({'status': 'success', 'message_id': message.id}), 200
    except Exception as e:
        session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500
    finally:
        session.close()

@app.route('/api/messages/<user_id>', methods=['GET'])
def get_messages(user_id):
    try:
        session = Session()
        messages = session.query(ChatMessage)\
            .filter(ChatMessage.user_id == user_id)\
            .order_by(ChatMessage.timestamp.desc())\
            .limit(100)\
            .all()
        
        return jsonify({
            'status': 'success',
            'messages': [{
                'id': msg.id,
                'message': msg.message,
                'responses': msg.responses,
                'language': msg.language,
                'timestamp': msg.timestamp.isoformat(),
                'session_id': msg.session_id
            } for msg in messages]
        }), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500
    finally:
        session.close()

@app.route('/api/messages/session/<session_id>', methods=['GET'])
def get_session_messages(session_id):
    try:
        session = Session()
        messages = session.query(ChatMessage)\
            .filter(ChatMessage.session_id == session_id)\
            .order_by(ChatMessage.timestamp)\
            .all()
        
        return jsonify({
            'status': 'success',
            'messages': [{
                'id': msg.id,
                'message': msg.message,
                'responses': msg.responses,
                'language': msg.language,
                'timestamp': msg.timestamp.isoformat()
            } for msg in messages]
        }), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500
    finally:
        session.close()

if __name__ == '__main__':
    app.run(debug=True)

//background.js
// Constants for API and caching
const CACHE_DURATION = 1000 * 60 * 5; // 5 minutes
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000; // 1 second

class BackgroundService {
    constructor() {
        this.cache = new Map();
        this.modelConfigs = {
            en: ['gpt2', 'bart-large', 't5-base'],
            es: ['spanish-gpt2', 'spanish-bart', 'spanish-t5'],
            de: ['german-gpt2', 'german-bart', 'german-t5']
        };
        this.setupMessageListeners();
    }

    setupMessageListeners() {
        chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
            if (request.type === 'getResponses') {
                this.handleGetResponses(request.data)
                    .then(sendResponse)
                    .catch(error => sendResponse({ error: error.message }));
                return true; // Indicates async response
            }
        });
    }

    async handleGetResponses(data) {
        const { message, language } = data;
        const cacheKey = `${language}-${message}`;

        // Check cache
        if (this.cache.has(cacheKey)) {
            const cached = this.cache.get(cacheKey);
            if (Date.now() - cached.timestamp < CACHE_DURATION) {
                return cached.responses;
            }
            this.cache.delete(cacheKey);
        }

        try {
            const responses = await this.fetchAllModelResponses(message, language);
            this.cache.set(cacheKey, {
                responses,
                timestamp: Date.now()
            });
            return responses;
        } catch (error) {
            console.error('Error fetching responses:', error);
            throw error;
        }
    }

    async fetchAllModelResponses(message, language) {
        const models = this.modelConfigs[language];
        const responses = await Promise.all(
            models.map(model => this.fetchWithRetry(message, model))
        );
        return responses;
    }

    async fetchWithRetry(message, model, retryCount = 0) {
        try {
            const apiKey = await this.getApiKey();
            const response = await fetch('https://api-inference.huggingface.co/models/' + model, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ inputs: message })
            });

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

            const data = await response.json();
            return data[0].generated_text;
        } catch (error) {
            if (retryCount < MAX_RETRIES) {
                await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
                return this.fetchWithRetry(message, model, retryCount + 1);
            }
            throw error;
        }
    }

    async getApiKey() {
        const result = await chrome.storage.local.get(['huggingFaceApiKey']);
        if (!result.huggingFaceApiKey) {
            throw new Error('API key not found. Please set it in the extension settings.');
        }
        return result.huggingFaceApiKey;
    }
}

// Initialize background service
const backgroundService = new BackgroundService();

//content.js
class AIChatUI {
    constructor() {
        this.container = null;
        this.isDragging = false;
        this.currentX = 0;
        this.currentY = 0;
        this.initialX = 0;
        this.initialY = 0;
        this.xOffset = 0;
        this.yOffset = 0;
        this.currentModelIndex = 0;
        this.currentResponses = [];
        this.messageCache = new Map();
        this.settings = {
            theme: 'light',
            language: 'en'
        };
        this.databaseService = new DatabaseService();
        this.translationService = new TranslationService();
        this.init();
    }

    async init() {
        await this.loadSettings();
        this.createChatWindow();
        this.initializeDragAndResize();
        this.setupEventListeners();
        this.initializeSessionId();
    }

    async loadSettings() {
        const settings = await chrome.storage.local.get(['theme', 'language']);
        this.settings = {
            theme: settings.theme || 'light',
            language: settings.language || 'en'
        };
    }

    createChatWindow() {
        this.container = document.createElement('div');
        this.container.className = 'ai-chat-container';
        this.container.setAttribute('data-theme', this.settings.theme);

        this.container.innerHTML = `
            <div class="ai-chat-header">
                <span>AI Chat Assistant</span>
                <div class="header-controls">
                    <button class="ai-chat-button" id="toggleTheme" title="Toggle Theme">🌓</button>
                    <button class="ai-chat-button" id="showHistory" title="Chat History">📜</button>
                    <button class="ai-chat-button" id="settings" title="Settings">⚙️</button>
                    <button class="ai-chat-button" id="minimize" title="Minimize">_</button>
                    <button class="ai-chat-button" id="close" title="Close">×</button>
                </div>
            </div>
            <div class="ai-chat-messages"></div>
            <div class="ai-chat-controls">
                <button class="ai-chat-button" id="prevResponse" disabled>Previous</button>
                <button class="ai-chat-button" id="nextResponse" disabled>Next</button>
                <select id="languageSelect">
                    <option value="en">English</option>
                    <option value="es">Spanish</option>
                    <option value="de">German</option>
                </select>
            </div>
            <div class="ai-chat-input">
                <input type="text" placeholder="Type your message...">
                <button class="ai-chat-button" id="sendMessage">Send</button>
            </div>
            <div class="history-panel" style="display: none;">
                <div class="history-header">
                    <h3>Chat History</h3>
                    <button class="ai-chat-button" id="closeHistory">×</button>
                </div>
                <div class="history-content"></div>
            </div>
        `;

        document.body.appendChild(this.container);
    }

    initializeDragAndResize() {
        const header = this.container.querySelector('.ai-chat-header');
        
        header.addEventListener('mousedown', (e) => {
            if (e.target === header) {
                this.isDragging = true;
                this.initialX = e.clientX - this.xOffset;
                this.initialY = e.clientY - this.yOffset;
            }
        });

        document.addEventListener('mousemove', (e) => {
            if (this.isDragging) {
                e.preventDefault();
                this.currentX = e.clientX - this.initialX;
                this.currentY = e.clientY - this.initialY;
                this.xOffset = this.currentX;
                this.yOffset = this.currentY;
                this.container.style.transform = 
                    `translate(${this.currentX}px, ${this.currentY}px)`;
            }
        });

        document.addEventListener('mouseup', () => {
            this.isDragging = false;
        });
    }

    initializeSessionId() {
        this.sessionId = Date.now().toString() + '-' + 
            Math.random().toString(36).substring(2, 15);
    }

    setupEventListeners() {
        const sendButton = this.container.querySelector('#sendMessage');
        const input = this.container.querySelector('input');
        const closeButton = this.container.querySelector('#close');
        const minimizeButton = this.container.querySelector('#minimize');
        const themeButton = this.container.querySelector('#toggleTheme');
        const nextButton = this.container.querySelector('#nextResponse');
        const prevButton = this.container.querySelector('#prevResponse');
        const languageSelect = this.container.querySelector('#languageSelect');
        const historyButton = this.container.querySelector('#showHistory');
        const closeHistoryButton = this.container.querySelector('#closeHistory');
        const settingsButton = this.container.querySelector('#settings');
        settingsButton.addEventListener('click', () => this.showSettings());

        // Debounce input handler
        let typingTimer;
        input.addEventListener('input', () => {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => {
                this.saveInputToCache(input.value);
            }, 500);
        });

        sendButton.addEventListener('click', () => this.handleSendMessage());
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.handleSendMessage();
        });

        closeButton.addEventListener('click', () => this.closeChat());
        minimizeButton.addEventListener('click', () => this.toggleMinimize());
        themeButton.addEventListener('click', () => this.toggleTheme());
        
        nextButton.addEventListener('click', () => this.showNextResponse());
        prevButton.addEventListener('click', () => this.showPreviousResponse());
        
        historyButton.addEventListener('click', () => this.toggleHistory());
        closeHistoryButton.addEventListener('click', () => this.toggleHistory());
        
        languageSelect.value = this.settings.language;
        languageSelect.addEventListener('change', (e) => {
            this.settings.language = e.target.value;
            chrome.storage.local.set({ language: e.target.value });
        });

        // Handle window resize
        window.addEventListener('resize', () => {
            this.adjustContainerPosition();
        });
    }

    async handleSendMessage() {
        const input = this.container.querySelector('input');
        const message = input.value.trim();
        if (!message) return;

        try {
            // Detect language and translate if needed
            const detectedLang = await this.translationService.detectLanguage(message);
            let translatedMessage = message;
            
            if (detectedLang !== this.settings.language) {
                translatedMessage = await this.translationService.translate(
                    message, 
                    this.settings.language, 
                    detectedLang
                );
            }

            this.addMessage(message, 'user');
            input.value = '';
            this.saveInputToCache('');

            this.showLoadingIndicator();
            const responses = await this.getAIResponses(translatedMessage);
            this.hideLoadingIndicator();
            
            // Translate responses back to original language if needed
            let finalResponses = responses;
            if (detectedLang !== this.settings.language) {
                finalResponses = await Promise.all(
                    responses.map(response => 
                        this.translationService.translate(response, detectedLang, this.settings.language)
                    )
                );
            }
            
            this.currentResponses = finalResponses;
            this.currentModelIndex = 0;
            this.addMessage(finalResponses[0], 'ai');
            this.updateResponseControls();

            // Save to database using DatabaseService
            await this.databaseService.saveMessage(
                this.getUserId(),
                message,
                finalResponses,
                detectedLang,
                this.sessionId
            );
        } catch (error) {
            this.hideLoadingIndicator();
            this.addMessage('Error: ' + error.message, 'error');
        }
    }

    async getAIResponses(message) {
        const response = await chrome.runtime.sendMessage({
            type: 'getResponses',
            data: {
                message,
                language: this.settings.language
            }
        });

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

        return response;
    }

    async loadChatHistory() {
        const historyContent = this.container.querySelector('.history-content');
        historyContent.innerHTML = '<div class="loading-indicator">Loading...</div>';

        try {
            const data = await this.databaseService.getUserMessages(this.getUserId());
            if (data.status === 'success') {
                this.renderChatHistory(data.messages);
            } else {
                throw new Error('Failed to load chat history');
            }
        } catch (error) {
            historyContent.innerHTML = 
                '<div class="error-message">Failed to load chat history</div>';
        }
    }

    async loadHistorySession(sessionId) {
        try {
            const data = await this.databaseService.getSessionMessages(sessionId);
            if (data.status === 'success') {
                const messagesContainer = this.container.querySelector('.ai-chat-messages');
                messagesContainer.innerHTML = '';
                
                for (const msg of data.messages) {
                    // Translate messages if needed
                    let displayMessage = msg.message;
                    let displayResponse = msg.responses[0];
                    
                    if (msg.language !== this.settings.language) {
                        displayMessage = await this.translationService.translate(
                            msg.message,
                            this.settings.language,
                            msg.language
                        );
                        displayResponse = await this.translationService.translate(
                            msg.responses[0],
                            this.settings.language,
                            msg.language
                        );
                    }
                    
                    this.addMessage(displayMessage, 'user');
                    this.addMessage(displayResponse, 'ai');
                }

                this.toggleHistory();
            }
        } catch (error) {
            console.error('Error loading session:', error);
        }
    }


    async saveMessageToDatabase(message, responses) {
        try {
            const response = await fetch('http://localhost:5000/api/messages', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: this.getUserId(),
                    message: message,
                    responses: responses,
                    language: this.settings.language,
                    session_id: this.sessionId
                })
            });

            if (!response.ok) {
                throw new Error('Failed to save message');
            }
        } catch (error) {
            console.error('Error saving message:', error);
        }
    }

    getUserId() {
        let userId = localStorage.getItem('chat_user_id');
        if (!userId) {
            userId = 'user_' + Date.now() + Math.random().toString(36).substring(2);
            localStorage.setItem('chat_user_id', userId);
        }
        return userId;
    }

    addMessage(message, type) {
        const messagesContainer = this.container.querySelector('.ai-chat-messages');
        const messageElement = document.createElement('div');
        messageElement.className = `message ${type}-message`;
        
        if (type === 'ai') {
            messageElement.innerHTML = `
                <div class="message-content">${this.formatMessage(message)}</div>
                <div class="message-meta">
                    <span class="model-info">Model ${this.currentModelIndex + 1}</span>
                    <span class="timestamp">${new Date().toLocaleTimeString()}</span>
                </div>
            `;
        } else {
            messageElement.textContent = message;
        }

        messagesContainer.appendChild(messageElement);
        this.scrollToBottom();
    }

    formatMessage(message) {
        // Convert URLs to links
        return message.replace(
            /(https?:\/\/[^\s]+)/g,
            '<a href="$1" target="_blank">$1</a>'
        );
    }

    scrollToBottom() {
        const messagesContainer = this.container.querySelector('.ai-chat-messages');
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    showNextResponse() {
        if (this.currentModelIndex < this.currentResponses.length - 1) {
            this.currentModelIndex++;
            const messagesContainer = this.container.querySelector('.ai-chat-messages');
            const lastMessage = messagesContainer.lastElementChild;
            lastMessage.querySelector('.message-content').innerHTML = 
                this.formatMessage(this.currentResponses[this.currentModelIndex]);
            lastMessage.querySelector('.model-info').textContent = 
                `Model ${this.currentModelIndex + 1}`;
            this.updateResponseControls();
        }
    }

    showPreviousResponse() {
        if (this.currentModelIndex > 0) {
            this.currentModelIndex--;
            const messagesContainer = this.container.querySelector('.ai-chat-messages');
            const lastMessage = messagesContainer.lastElementChild;
            lastMessage.querySelector('.message-content').innerHTML = 
                this.formatMessage(this.currentResponses[this.currentModelIndex]);
            lastMessage.querySelector('.model-info').textContent = 
                `Model ${this.currentModelIndex + 1}`;
            this.updateResponseControls();
        }
    }

    updateResponseControls() {
        const prevButton = this.container.querySelector('#prevResponse');
        const nextButton = this.container.querySelector('#nextResponse');
        
        prevButton.disabled = this.currentModelIndex === 0;
        nextButton.disabled = this.currentModelIndex === this.currentResponses.length - 1;
    }

    toggleMinimize() {
        const messagesContainer = this.container.querySelector('.ai-chat-messages');
        const inputContainer = this.container.querySelector('.ai-chat-input');
        const controlsContainer = this.container.querySelector('.ai-chat-controls');
        const historyPanel = this.container.querySelector('.history-panel');
        
        if (messagesContainer.style.display === 'none') {
            messagesContainer.style.display = 'block';
            inputContainer.style.display = 'flex';
            controlsContainer.style.display = 'flex';
            if (historyPanel.classList.contains('active')) {
                historyPanel.style.display = 'block';
            }
            this.container.style.height = '500px';
        } else {
            messagesContainer.style.display = 'none';
            inputContainer.style.display = 'none';
            controlsContainer.style.display = 'none';
            historyPanel.style.display = 'none';
            this.container.style.height = 'auto';
        }
    }

    toggleTheme() {
        this.settings.theme = this.settings.theme === 'light' ? 'dark' : 'light';
        this.container.setAttribute('data-theme', this.settings.theme);
        chrome.storage.local.set({ theme: this.settings.theme });
    }

    async toggleHistory() {
        const historyPanel = this.container.querySelector('.history-panel');
        if (historyPanel.style.display === 'none') {
            await this.loadChatHistory();
            historyPanel.style.display = 'block';
            historyPanel.classList.add('active');
        } else {
            historyPanel.style.display = 'none';
            historyPanel.classList.remove('active');
        }
    }

    renderChatHistory(messages) {
        const historyContent = this.container.querySelector('.history-content');
        historyContent.innerHTML = '';

        messages.forEach(msg => {
            const messageElement = document.createElement('div');
            messageElement.className = 'history-item';
            messageElement.innerHTML = `
                <div class="history-message">${msg.message}</div>
                <div class="history-meta">
                    <span class="history-language">${msg.language}</span>
                    <span class="history-time">
                        ${new Date(msg.timestamp).toLocaleString()}
                    </span>
                </div>
            `;

            messageElement.addEventListener('click', () => {
                this.loadHistorySession(msg.session_id);
            });

            historyContent.appendChild(messageElement);
        });
    }

    showLoadingIndicator() {
        const loadingIndicator = document.createElement('div');
        loadingIndicator.className = 'loading-indicator';
        this.container.querySelector('.ai-chat-messages').appendChild(loadingIndicator);
    }

    hideLoadingIndicator() {
        const loadingIndicator = this.container.querySelector('.loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.remove();
        }
    }

    saveInputToCache(text) {
        localStorage.setItem('chat_input_cache', text);
    }

    loadInputFromCache() {
        const cachedInput = localStorage.getItem('chat_input_cache', text);
    }
    showSettings() {
        const settingsContainer = document.createElement('div');
        settingsContainer.className = 'settings-overlay';
        // Add API key configuration to settings
        const apiKeySection = `
            <section class="setting-section">
                <h4>API Configuration</h4>
                <input type="password" id="apiKey" placeholder="Enter Hugging Face API Key">
                <button id="saveApiKey">Save API Key</button>
                <div id="apiKeyStatus"></div>
            </section>
        `;
        settingsContainer.innerHTML = `
            <div class="settings-panel">
                <div class="settings-header">
                    <h3>Settings</h3>
                    <button class="ai-chat-button" id="closeSettings">×</button>
                </div>
                <div class="settings-content">
                    <section class="setting-section">
                        <h4>Theme</h4>
                        <div class="theme-toggle">
                            <input type="radio" id="light" name="theme" value="light">
                            <label for="light">Light</label>
                            <input type="radio" id="dark" name="theme" value="dark">
                            <label for="dark">Dark</label>
                        </div>
                    </section>
    
                    <section class="setting-section">
                        <h4>Language</h4>
                        <select id="defaultLanguage">
                            <option value="en">English</option>
                            <option value="es">Spanish</option>
                            <option value="de">German</option>
                        </select>
                    </section>
    
                    <section class="setting-section">
                        <h4>API Configuration</h4>
                        <input type="password" id="apiKey" placeholder="Enter Hugging Face API Key">
                        <button id="saveApiKey">Save API Key</button>
                    </section>
    
                    <section class="setting-section">
                        <h4>Custom Models</h4>
                        <div id="customModels"></div>
                        <button id="addCustomModel">Add Custom Model</button>
                    </section>
                </div>
            </div>
        `;
    
        this.container.appendChild(settingsContainer);
        this.initializeSettingsPanel(settingsContainer);
        // Add API key save functionality
        const saveApiKeyButton = settingsContainer.querySelector('#saveApiKey');
        const apiKeyInput = settingsContainer.querySelector('#apiKey');
        const apiKeyStatus = settingsContainer.querySelector('#apiKeyStatus');
        
        saveApiKeyButton.addEventListener('click', async () => {
            const apiKey = apiKeyInput.value.trim();
            if (apiKey) {
                await chrome.storage.local.set({ huggingFaceApiKey: apiKey });
                apiKeyStatus.textContent = 'API key saved successfully!';
                apiKeyStatus.style.color = 'green';
                setTimeout(() => {
                    apiKeyStatus.textContent = '';
                }, 3000);
            }
        });
    }
    }
    
//popup.js
class PopupManager {
    constructor() {
        this.customModels = [];
        this.init();
    }

    async init() {
        this.loadSettings();
        this.setupEventListeners();
        this.setupCustomModelsUI();
    }

    async loadSettings() {
        const settings = await chrome.storage.local.get([
            'theme',
            'language',
            'huggingFaceApiKey',
            'customModels'
        ]);

        // Set theme
        const themeInputs = document.querySelectorAll('input[name="theme"]');
        themeInputs.forEach(input => {
            if (input.value === settings.theme) {
                input.checked = true;
            }
        });

        // Set language
        const languageSelect = document.getElementById('defaultLanguage');
        if (settings.language) {
            languageSelect.value = settings.language;
        }

        // Set API key
        const apiKeyInput = document.getElementById('apiKey');
        if (settings.huggingFaceApiKey) {
            apiKeyInput.value = settings.huggingFaceApiKey;
        }

        // Load custom models
        this.customModels = settings.customModels || [];
    }

    setupEventListeners() {
        // Theme selection
        document.querySelectorAll('input[name="theme"]').forEach(input => {
            input.addEventListener('change', (e) => {
                chrome.storage.local.set({ theme: e.target.value });
                this.showStatus('Theme updated');
            });
        });

        // Language selection
        document.getElementById('defaultLanguage').addEventListener('change', (e) => {
            chrome.storage.local.set({ language: e.target.value });
            this.showStatus('Default language updated');
        });

        // API key
        document.getElementById('saveApiKey').addEventListener('click', () => {
            const apiKey = document.getElementById('apiKey').value.trim();
            if (apiKey) {
                chrome.storage.local.set({ huggingFaceApiKey: apiKey });
                this.showStatus('API key saved');
            } else {
                this.showStatus('Please enter a valid API key', true);
            }
        });

        // Add custom model
        document.getElementById('addCustomModel').addEventListener('click', () => {
            this.showCustomModelDialog();
        });
    }

    setupCustomModelsUI() {
        const container = document.getElementById('customModels');
        container.innerHTML = '';

        this.customModels.forEach((model, index) => {
            const modelElement = this.createCustomModelElement(model, index);
            container.appendChild(modelElement);
        });
    }

    createCustomModelElement(model, index) {
        const div = document.createElement('div');
        div.className = 'custom-model-item';
        div.innerHTML = `
            <span>${model.name} (${model.language})</span>
            <button class="remove-model" data-index="${index}">Remove</button>
        `;

        div.querySelector('.remove-model').addEventListener('click', () => {
            this.removeCustomModel(index);
        });

        return div;
    }

    showCustomModelDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'custom-model-dialog';
        dialog.innerHTML = `
            <h4>Add Custom Model</h4>
            <input type="text" id="modelName" placeholder="Model Name">
            <input type="text" id="modelId" placeholder="Model ID">
            <select id="modelLanguage">
                <option value="en">English</option>
                <option value="es">Spanish</option>
                <option value="de">German</option>
            </select>
            <div class="dialog-buttons">
                <button id="saveModel">Save</button>
                <button id="cancelModel">Cancel</button>
            </div>
        `;

        document.body.appendChild(dialog);

        dialog.querySelector('#saveModel').addEventListener('click', () => {
            const name = dialog.querySelector('#modelName').value.trim();
            const id = dialog.querySelector('#modelId').value.trim();
            const language = dialog.querySelector('#modelLanguage').value;

            if (name && id) {
                this.addCustomModel({ name, id, language });
                dialog.remove();
            } else {
                this.showStatus('Please fill all fields', true);
            }
        });

        dialog.querySelector('#cancelModel').addEventListener('click', () => {
            dialog.remove();
        });
    }

    async addCustomModel(model) {
        this.customModels.push(model);
        await chrome.storage.local.set({ customModels: this.customModels });
        this.setupCustomModelsUI();
        this.showStatus('Custom model added');
    }

    async removeCustomModel(index) {
        this.customModels.splice(index, 1);
        await chrome.storage.local.set({ customModels: this.customModels });
        this.setupCustomModelsUI();
        this.showStatus('Custom model removed');
    }

    showStatus(message, isError = false) {
        const statusElement = document.getElementById('statusMessage');
        statusElement.textContent = message;
        statusElement.className = `status-message ${isError ? 'error' : 'success'}`;
        setTimeout(() => {
            statusElement.textContent = '';
            statusElement.className = 'status-message';
        }, 3000);
    }
}

// Initialize popup
document.addEventListener('DOMContentLoaded', () => {
    new PopupManager();
});

{
  "manifest_version": 3,
  "name": "AI Chat Bot",
  "version": "1.0.0",
  "description": "A browser extension for multilingual AI chat using Hugging Face models",
  "permissions": [
    "storage",
    "activeTab",
    "scripting",
    "webRequest"
  ],
  "host_permissions": [
    "https://api-inference.huggingface.co/*"
  ],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "css": ["styles/content.css"],
    "js": ["content.js"]
  }],
  "web_accessible_resources": [{
    "resources": [
      "icons/*",
      "styles/*"
    ],
    "matches": ["<all_urls>"]
  }]
}

content.css
.ai-chat-container {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: var(--bg-primary);
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    z-index: 10000;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    resize: both;
    min-width: 300px;
    min-height: 400px;
}

.ai-chat-header {
    padding: 10px;
    background: var(--header-bg);
    color: var(--text-primary);
    cursor: move;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.settings-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10001;
}

.settings-panel {
    background: var(--bg-primary);
    border-radius: 8px;
    width: 80%;
    max-height: 80%;
    overflow-y: auto;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.settings-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.settings-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.setting-section {
    padding: 10px;
    border-bottom: 1px solid var(--border-color);
}

.setting-section:last-child {
    border-bottom: none;
}

.ai-chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background: var(--bg-secondary);
}

.message {
    margin: 10px 0;
    padding: 10px;
    border-radius: 8px;
    max-width: 80%;
    animation: messageSlide 0.3s ease-out;
}

.user-message {
    background: var(--user-message-bg);
    color: var(--text-primary);
    margin-left: auto;
}

.ai-message {
    background: var(--ai-message-bg);
    color: var(--text-primary);
    margin-right: auto;
}

.ai-chat-input {
    padding: 10px;
    display: flex;
    gap: 10px;
    background: var(--bg-primary);
}

.ai-chat-input input {
    flex: 1;
    padding: 8px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    background: var(--input-bg);
    color: var(--text-primary);
}

.ai-chat-controls {
    display: flex;
    gap: 5px;
    padding: 5px 10px;
    background: var(--bg-primary);
}

.ai-chat-button {
    padding: 8px 12px;
    border: none;
    border-radius: 4px;
    background: var(--button-bg);
    color: var(--button-text);
    cursor: pointer;
    transition: background 0.2s;
}

.ai-chat-button:hover {
    background: var(--button-hover-bg);
}

.loading-indicator {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 2px solid var(--loader-color);
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 1s linear infinite;
}

@keyframes messageSlide {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* Theme Variables */
:root {
    /* Light Theme */
    --bg-primary-light: #ffffff;
    --bg-secondary-light: #f5f5f5;
    --text-primary-light: #333333;
    --header-bg-light: #4a90e2;
    --user-message-bg-light: #e3f2fd;
    --ai-message-bg-light: #f0f4f8;
    --button-bg-light: #4a90e2;
    --button-text-light: #ffffff;
    --button-hover-bg-light: #357abd;
    --input-bg-light: #ffffff;
    --border-color-light: #dddddd;
    --loader-color-light: #4a90e2;

    /* Dark Theme */
    --bg-primary-dark: #1a1a1a;
    --bg-secondary-dark: #2d2d2d;
    --text-primary-dark: #ffffff;
    --header-bg-dark: #333333;
    --user-message-bg-dark: #404040;
    --ai-message-bg-dark: #333333;
    --button-bg-dark: #4a90e2;
    --button-text-dark: #ffffff;
    --button-hover-bg-dark: #357abd;
    --input-bg-dark: #404040;
    --border-color-dark: #404040;
    --loader-color-dark: #4a90e2;
}

/* Apply theme */
[data-theme="light"] {
    --bg-primary: var(--bg-primary-light);
    --bg-secondary: var(--bg-secondary-light);
    --text-primary: var(--text-primary-light);
    --header-bg: var(--header-bg-light);
    --user-message-bg: var(--user-message-bg-light);
    --ai-message-bg: var(--ai-message-bg-light);
    --button-bg: var(--button-bg-light);
    --button-text: var(--button-text-light);
    --button-hover-bg: var(--button-hover-bg-light);
    --input-bg: var(--input-bg-light);
    --border-color: var(--border-color-light);
    --loader-color: var(--loader-color-light);
}

[data-theme="dark"] {
    --bg-primary: var(--bg-primary-dark);
    --bg-secondary: var(--bg-secondary-dark);
    --text-primary: var(--text-primary-dark);
    --header-bg: var(--header-bg-dark);
    --user-message-bg: var(--user-message-bg-dark);
    --ai-message-bg: var(--ai-message-bg-dark);
    --button-bg: var(--button-bg-dark);
    --button-text: var(--button-text-dark);
    --button-hover-bg: var(--button-hover-bg-dark);
    --input-bg: var(--input-bg-dark);
    --border-color: var(--border-color-dark);
    --loader-color: var(--loader-color-dark);
}


popup.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Assistant Settings</title>
    <script src="popup.js" defer></script>
    <link rel="stylesheet" href="styles/content.css">
</head>
<body>
    <div class="settings-container">
        <h2>Settings</h2>
        
        <section class="setting-section">
            <h3>Theme</h3>
            <div class="theme-toggle">
                <input type="radio" id="light" name="theme" value="light">
                <label for="light">Light</label>
                <input type="radio" id="dark" name="theme" value="dark">
                <label for="dark">Dark</label>
            </div>
        </section>

        <section class="setting-section">
            <h3>Language</h3>
            <select id="defaultLanguage">
                <option value="en">English</option>
                <option value="es">Spanish</option>
                <option value="de">German</option>
            </select>
        </section>

        <section class="setting-section">
            <h3>API Configuration</h3>
            <input type="password" id="apiKey" placeholder="Enter Hugging Face API Key">
            <button id="saveApiKey">Save API Key</button>
        </section>

        <section class="setting-section">
            <h3>Custom Models</h3>
            <div id="customModels">
                <!-- Custom models will be dynamically added here -->
            </div>
            <button id="addCustomModel">Add Custom Model</button>
        </section>

        <div class="status-message" id="statusMessage"></div>
    </div>
    <script src="popup.js"></script>
</body>
</html>

NOTE: PLEASE START WRITING CONTENT.JS FOLLOWED BY POPUP.HTML AND THEN POPUP.JS.  Make any other advancements to make the extension user friendly, amazing to use and boost user experience. Ensure you include a button for "Chat" to open the floating window, and should only open when the button is clicked. Write complete code for all the scripts so that I can copy and paste.