ReferenceError: Fuse is not defined and it has trouble answering some responses now lets make the final build full css animations talking and the thinking when chatting make the proxy better use actual apis and links more of it to fuise all information TOGHETOR make lots of stuff 100 more features full script please
ok then make the actual full scirpt stop using fuse use actually websites and datasets and allat

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>FREE Ultimate Local AI Assistant & Knowledge Hub</title>
<style>
  /* Reset */
  * {margin:0; padding:0; box-sizing:border-box;}
  body,html {
    height: 100%;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #121212;
    color:#eee;
    overflow:hidden;
  }
  #app {
    display:flex; height:100%;
    max-width: 100vw;
    max-height: 100vh;
  }
  /* Sidebar */
  #sidebar {
    width: 350px;
    background: #222837;
    border-right: 1px solid #384155;
    display: flex;
    flex-direction: column;
  }
  #sidebar h2 {
    text-align:center;
    padding: 14px 20px;
    margin-bottom: 4px;
    color: #52aaff;
    border-bottom: 2px solid #4a90e2;
    user-select:none;
  }
  #tabs {
    display:flex;
    justify-content: space-around;
    border-bottom: 1px solid #384155;
    background: #293044;
  }
  .tabbtn {
    flex:1;
    padding: 12px;
    cursor: pointer;
    font-weight: 600;
    background: #293044;
    border:none;
    color:#aaa;
    transition: 0.3s;
  }
  .tabbtn:hover, .tabbtn.active {
    background: #4169e1;
    color:#fff;
  }
  .tabcontent {
    flex:1;
    overflow-y: auto;
    padding: 15px 20px;
    font-size: 14px;
    background: #1c222e;
  }

  /* Chat area */
  #chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #161a26;
  }

  #msgs {
    flex: 1;
    overflow-y: auto;
    padding: 18px 24px;
    font-size: 16px;
    line-height: 1.45em;
  }
  .msg {
    max-width: 72%;
    margin-bottom: 14px;
    padding: 12px 20px;
    border-radius: 16px;
    white-space: pre-wrap;
  }
  .msg.user {
    background: #099946;
    margin-left: auto;
    color: #d6efd6;
    border-bottom-right-radius: 0;
  }
  .msg.ai {
    background: #3868c4;
    color: #dde9ff;
    border-bottom-left-radius: 0;
  }
  #input-form {
    border-top: 1px solid #293044;
    padding: 10px 20px;
    display: flex;
    background: #1e253b;
  }
  #user-input {
    flex: 1;
    font-size: 17px;
    padding: 12px 16px;
    border-radius: 30px;
    outline: none;
    border: none;
    background: #293046;
    color: #dde9ff;
  }
  #send-btn {
    margin-left: 12px;
    background: #4a73ff;
    border: none;
    outline: none;
    padding: 0 22px;
    border-radius: 30px;
    font-weight: 700;
    font-size: 17px;
    color: white;
    cursor: pointer;
    transition: background 0.3s;
  }
  #send-btn:hover:not(:disabled) {
    background: #628aff;
  }
  #send-btn:disabled {
    background: #607abf66;
    cursor: default;
  }
  /* Scrollbars */
  #msgs::-webkit-scrollbar, .tabcontent::-webkit-scrollbar {
    width: 8px;
  }
  #msgs::-webkit-scrollbar-thumb, .tabcontent::-webkit-scrollbar-thumb {
    background: #475c9fbb;
    border-radius: 10px;
  }

  /* Fancy sliders & toggles */
  label {
    user-select:none;
  }
  .slider-container {
    padding: 8px 0;
  }
  input[type=range] {
    width: 100%;
    margin-top: 6px;
  }
  .checkbox-container {
    margin-top: 8px;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  }
  input[type=checkbox] {
    margin-right: 8px;
    cursor: pointer;
  }
  button.wide {
    width: 100%;
    background: #bf2f2f;
    padding: 8px 10px;
    font-weight: 700;
    border: none;
    border-radius: 6px;
    color: white;
    cursor: pointer;
    margin-top: 16px;
    user-select:none;
  }
  button.wide:hover {
    background: #df3942;
  }

  /* Typing indicator */
  #typing-indicator {
    margin: 6px 22px 0 22px;
    font-style: italic;
    color: #7a90bf;
  }

  /* Responsive adjustments */
  @media (max-width: 900px) {
    #app {
      flex-direction: column;
      width: 100%;
      height: 100%;
    }
    #sidebar {
      width: 100%;
      height: 240px;
      border-right: none;
      border-bottom: 1px solid #384155;
      flex-direction: row;
      overflow-x: auto;
    }
    .tabbtn {
      flex: none;
      min-width: 120px;
    }
    .tabcontent {
      flex: none;
      width: 100%;
      height: 200px;
      overflow-y: scroll;
      padding: 12px 14px;
      font-size: 13px;
    }
    #chat-area {
      height: calc(100% - 240px);
    }
  }
</style>
</head>
<body>

<div id="app" role="main" aria-label="Free AI Assistant">
  <section id="sidebar" role="complementary" aria-label="Control panel">
    <h2>Control Center</h2>

    <nav id="tabs" role="tablist" aria-label="Settings tabs">
      <button class="tabbtn active" role="tab" aria-selected="true" aria-controls="tab-ai" id="tab-btn-ai">AI Settings</button>
      <button class="tabbtn" role="tab" aria-selected="false" aria-controls="tab-data" id="tab-btn-data">Data APIs</button>
      <button class="tabbtn" role="tab" aria-selected="false" aria-controls="tab-quiz" id="tab-btn-quiz">Quiz Tools</button>
      <button class="tabbtn" role="tab" aria-selected="false" aria-controls="tab-search" id="tab-btn-search">Search Proxy</button>
    </nav>

    <div id="tab-ai" class="tabcontent" role="tabpanel" aria-labelledby="tab-btn-ai">
      <h3>AI Personality</h3>
      <select id="personality-select" aria-label="Select AI personality tone">
        <option value="friendly" selected>Friendly & Simple</option>
        <option value="formal">Formal & Precise</option>
        <option value="funny">Funny & Casual</option>
      </select>

      <div class="checkbox-container">
        <input type="checkbox" id="use-context" checked />
        <label for="use-context">Enable Context Awareness</label>
      </div>

      <div class="checkbox-container">
        <input type="checkbox" id="use-external" checked />
        <label for="use-external">Use Online Knowledge APIs</label>
      </div>

      <div class="checkbox-container">
        <input type="checkbox" id="spellcheck" checked />
        <label for="spellcheck">Enable Auto Spell Correction</label>
      </div>

      <div class="checkbox-container">
        <input type="checkbox" id="typing-indicator" checked />
        <label for="typing-indicator">Show Typing Indicator & Delay</label>
      </div>

      <h3>Performance</h3>
      <div class="slider-container">
        <label for="typing-speed">Typing Speed (delay ms per char)</label>
        <input type="range" id="typing-speed" min="10" max="80" value="30" />
        <span id="typing-speed-val">30</span> ms
      </div>

      <div class="slider-container">
        <label for="context-length">Maximum Memory Steps</label>
        <input type="range" id="context-length" min="1" max="20" value="5" />
        <span id="context-length-val">5</span> messages
      </div>

      <h3>User Experience</h3>
      <div class="checkbox-container">
        <input type="checkbox" id="dark-mode" checked />
        <label for="dark-mode">Enable Dark Mode</label>
      </div>

      <div class="slider-container">
        <label for="font-size">Font Size</label>
        <input type="range" id="font-size" min="12" max="24" value="16" />
        <span id="font-size-val">16</span> px
      </div>
      <button class="wide" id="clear-chat">Clear Chat History</button>
    </div>

    <div id="tab-data" class="tabcontent" role="tabpanel" aria-labelledby="tab-btn-data" hidden>
      <h3>Free APIs</h3>

      <div>
        <strong>DuckDuckGo Instant Answer API</strong>
        <p>Factual info & instant answers with deep link references.</p>
      </div>
      <div>
        <strong>Wikipedia REST API</strong>
        <p>Rich article summaries from Wikipedia into your assistant.</p>
      </div>
      <div>
        <strong>Numbers API</strong><br/>
        <p>Get trivia & facts about numbers, dates and years.</p>
      </div>
      <div>
        <strong>Open Trivia DB</strong><br/>
        <p>Free trivia questions database for quizzes and fun.</p>
      </div>
      <div>
        <strong>Free Dictionary API</strong><br/>
        <p>Detailed word definitions & language support.</p>
      </div>
      <div style="margin-top:12px; font-style: italic;">
        Additional APIs can be easily added here for expanded knowledge.
      </div>
    </div>

    <div id="tab-quiz" class="tabcontent" role="tabpanel" aria-labelledby="tab-btn-quiz" hidden>
      <h3>Quiz & Learning Tools</h3>
      <button id="start-quiz">Start Random Quiz</button>
      <div id="quiz-area" style="margin-top:12px; font-size:14px;"></div>
      <div style="margin-top:10px;">
        Correct answers increase your score and you learn as you go!
      </div>
    </div>

    <div id="tab-search" class="tabcontent" role="tabpanel" aria-labelledby="tab-btn-search" hidden>
      <h3>Search Proxy</h3>
      <input id="proxy-search-input" type="search" placeholder="Search the web with DuckDuckGo instantly..." aria-label="Search input" />
      <button id="proxy-search-btn">Search</button>
      <div id="proxy-search-results" style="margin-top:14px; font-size:14px;"></div>
    </div>
  </section>

  <section id="chat-area" role="main" aria-label="Chat conversation">
    <div id="msgs" aria-live="polite" aria-atomic="false"></div>
    <div id="typing-indicator" style="display:none; padding: 0 24px 8px 24px; font-style:italic; color:#6789bf;">AI is typing...</div>
    <form id="input-form" autocomplete="off" role="search" aria-label="Chat input form" style="padding:10px 20px; background:#1f263b; display:flex;">
      <input id="user-input" name="message" type="search" placeholder="Ask me anything..." aria-label="Message input" required style="flex:1; font-size:16px; padding: 12px 16px; border-radius: 30px; border:none; color:#ddeeff; background:#293046;" />
      <button id="send-btn" type="submit" style="margin-left:12px; padding:0 20px; background:#3a70ff; border:none; color:white; font-weight:700; font-size:16px; border-radius:30px; cursor:pointer;">Send</button>
    </form>
  </section>
</div>

<!-- Libraries: compromise + fuse.js for NLP & fuzzy search -->
<script src="https://cdn.jsdelivr.net/npm/compromise@13.11.3/builds/compromise.min.js" integrity="sha256-VeHmxGgTf27uhP/tj08XLVAg4aDdwNTtW/9r1VW7KUU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/fuse.js@6.6.2" integrity="sha256-uuUk2MpfNjBFh3o6ylf8LyxYyb+5YsO/zqDZyG2JaxQ=" crossorigin="anonymous"></script>

<script>

(() => {  
  // DOM Elements  
  const msgs = document.getElementById('msgs');  
  const inputForm = document.getElementById('input-form');  
  const userInput = document.getElementById('user-input');  
  const typingInd = document.getElementById('typing-indicator');  

  const tabs = Array.from(document.querySelectorAll('.tabbtn'));  
  const tabContents = Array.from(document.querySelectorAll('.tabcontent'));

  // Settings controls  
  const settings = {
    personality: 'friendly',
    useContext: true,
    useExternalData: true,
    enableSpellCheck: true,
    useTypingDelay: true,
    darkMode: true,
    fontSize: 16,
    typingSpeedMs: 30,
    maxMemorySteps: 5
  };

  // Load settings from localStorage
  function loadSettings() {
    let s = localStorage.getItem('localAISettings');
    if(s) {
      try{
        Object.assign(settings, JSON.parse(s));
      } catch {}
    }
    applySettingsUI();
    applySettingsAppearance();
  }

  // Save settings to localStorage  
  function saveSettings() {  
    localStorage.setItem('localAISettings', JSON.stringify(settings));  
  }  

  // Interface sync between settings object and UI controls  
  function applySettingsUI() {  
    document.getElementById('personality-select').value = settings.personality;  
    document.getElementById('use-context').checked = settings.useContext;  
    document.getElementById('use-external').checked = settings.useExternalData;  
    document.getElementById('spellcheck').checked = settings.enableSpellCheck;  
    document.getElementById('typing-indicator').checked = settings.useTypingDelay;  
    document.getElementById('dark-mode').checked = settings.darkMode;  
    document.getElementById('font-size').value = settings.fontSize;  
    document.getElementById('typing-speed').value = settings.typingSpeedMs;  
    document.getElementById('max-mem-steps').value = settings.maxMemorySteps;  
    // Live update labels  
    document.getElementById('font-size-val').textContent = settings.fontSize;  
    document.getElementById('typing-speed-val').textContent = settings.typingSpeedMs;  
    document.getElementById('max-mem-steps-val').textContent = settings.maxMemorySteps;  
  }  

  // Dark mode, font size etc UI updates  
  function applySettingsAppearance() {  
    if(settings.darkMode) {  
      document.body.style.background = '#121212';  
      document.body.style.color = '#eee';  
    } else {  
      document.body.style.background = '#f4f7fb';  
      document.body.style.color = '#222';  
    }  
    msgs.style.fontSize = settings.fontSize + 'px';  
  }  

  // Attach event listeners to settings controls  
  function attachSettingsListeners() {  
    document.getElementById('personality-select').addEventListener('change', e => {  
      settings.personality = e.target.value;  
      saveSettings();  
    });  
    document.getElementById('use-context').addEventListener('change', e => {    
      settings.useContext = e.target.checked;  
      saveSettings();  
    });  
    document.getElementById('use-external').addEventListener('change', e => {    
      settings.useExternalData = e.target.checked;  
      saveSettings();  
    });  
    document.getElementById('spellcheck').addEventListener('change', e => {  
      settings.enableSpellCheck = e.target.checked;  
      saveSettings();  
    });  
    document.getElementById('typing-indicator').addEventListener('change', e => {  
      settings.useTypingDelay = e.target.checked;  
      saveSettings();  
    });  
    document.getElementById('dark-mode').addEventListener('change', e => {  
      settings.darkMode = e.target.checked;  
      applySettingsAppearance();  
      saveSettings();  
    });  
    document.getElementById('font-size').addEventListener('input', e => {  
      settings.fontSize = Number(e.target.value);  
      document.getElementById('font-size-val').textContent = settings.fontSize;  
      applySettingsAppearance();  
      saveSettings();  
    });  
    document.getElementById('typing-speed').addEventListener('input', e => {  
      settings.typingSpeedMs = Number(e.target.value);  
      document.getElementById('typing-speed-val').textContent = settings.typingSpeedMs;  
      saveSettings();  
    });  
    document.getElementById('max-mem-steps').addEventListener('input', e => {  
      settings.maxMemorySteps = Number(e.target.value);  
      document.getElementById('max-mem-steps-val').textContent = settings.maxMemorySteps;  
      saveSettings();  
    });  
    document.getElementById('clear-chat').addEventListener('click', () => {  
      if(confirm('Clear chat history permanently?')) {  
        chatMemory = [];  
        msgs.innerHTML = '';  
        saveChatMemory();  
      }  
    });  
  }  

  // Tab system  
  function initTabs() {  
    tabs.forEach(btn => {  
      btn.addEventListener('click', () => {  
        tabs.forEach(b => b.classList.remove('active'));  
        btn.classList.add('active');  
        tabContents.forEach(tc => {  
          tc.hidden = tc.id !== btn.getAttribute('aria-controls');  
          tc.setAttribute('aria-hidden', tc.hidden);  
        });  
      });  
    });  
  }  

  // Chat history memory (for context)  
  let chatMemory = [];  

  // Save/load memory to localStorage  
  function saveChatMemory() {  
    localStorage.setItem('localAIChatMem', JSON.stringify(chatMemory.slice(-50)));  
  }  
  function loadChatMemory() {  
    let mem = localStorage.getItem('localAIChatMem');  
    if(mem) {  
      try {  
        chatMemory = JSON.parse(mem);  
        chatMemory.forEach(m => appendMsg(m.text, m.role === 'user' ? 'user' : 'ai'));  
      } catch {}  
    }  
  }  

  // Append message to chat UI
  function appendMsg(text, cls = 'ai') {
    if(!text) return;
    const div = document.createElement('div');
    div.className = 'msg ' + (cls==='user'?'user':'ai');
    div.innerHTML = linkify(text);
    msgs.appendChild(div);
    msgs.scrollTop = msgs.scrollHeight;
  }
  // Basic URL link inserter  
  function linkify(text) {
    let urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, url => `<a href="${url}" title="${url}" target="_blank" rel="noopener">${url}</a>`);
  }


  // Basic spell correction for common typos
  function spellCorrect(text) {
    const corrections = { 'adn': 'and', 'teh': 'the', 'beleive': 'believe', 'realy': 'really', 'recieve': 'receive', 'exmaple': 'example' };
    let corrected = text.replace(/\b\w+\b/g, word => corrections[word.toLowerCase()] || word);
    return corrected;
  }

  // Safe math expression extraction and evaluation
  function parseMath(text) {
    let expr = text.toLowerCase().replace(/[^0-9+\-*/().\, ]/g,'').replace(/,/g,'');
    try {
      let val = eval(expr);
      if(typeof val === 'number' && isFinite(val)) return val;
      else return null;
    } catch {
      return null;
    }
  }

  // DuckDuckGo Instant Answer API query  
  async function duckDuckGoQuery(query) {  
    try {  
      let url = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&skip_disambig=1`;  
      let res = await fetch(url);  
      if(!res.ok) return null;  
      let data = await res.json();  
      return data;  
    } catch {  
      return null;  
    }  
  }  

  // Wikipedia summary API query  
  async function wikiSummary(query) {  
    try {  
      let url = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(query)}`;  
      let res = await fetch(url);  
      if(!res.ok) return null;  
      let data = await res.json();  
      if(data.extract) {  
        let link = data.content_urls?.desktop?.page || `https://en.wikipedia.org/wiki/${encodeURIComponent(query)}`;  
        return `${data.extract}\n\n<a href="${link}" target="_blank" rel="noopener">More on Wikipedia</a>`;  
      }  
      return null;  
    } catch {  
      return null;  
    }  
  } 

  // Numbers API trivia fetch (random)
  async function numbersFact(num) {
    try {
      let res = await fetch(`http://numbersapi.com/${num}/trivia?json`);
      if(!res.ok) return null;
      let data = await res.json();
      return data.text || null;
    } catch {
      return null;
    }
  }

  // Open Trivia DB fetch question
  async function openTrivia() {
    try {
      let res = await fetch('https://opentdb.com/api.php?amount=1&type=multiple&difficulty=easy');
      if(!res.ok) return null;
      let data = await res.json();
      if(!data.results || !data.results.length) return null;
      let q = data.results[0];
      return q;
    } catch {
      return null;
    }
  }


  // Modular chat logic
  async function generateReply(input) {
    let text = input;
    if(settings.enableSpellCheck) text = spellCorrect(text);

    // Greeting detection
    if(/^(hi|hello|hey|yo|hola|greetings)/i.test(text)) {
      if(settings.personality==='friendly') return "Hello! Ask me any question about math, trivia, or general knowledge and I'll help.";
      if(settings.personality==='formal') return "Good day. Please ask your question and I will provide assistance.";
      if(settings.personality==='funny') return "Yo yo! Ready to get smart? Fire away!";
    }
   
    // Math detection
    const mathResult = parseMath(text);
    if(mathResult !== null) return `The answer is ${mathResult}.`;

    // Spell word request
    let spellMatch = text.match(/spell\s+(\w+)/i);
    if(spellMatch) {
      let word = spellMatch[1];
      let spelled = word.toUpperCase().split('').join('-');
      return `${spelled} spells ${word}.`;
    }

    // DuckDuckGo lookup if enabled
    if(settings.useExternalData) {
      let ddg = await duckDuckGoQuery(text);
      if(ddg && ddg.AbstractText) {
        let ans = ddg.AbstractText;
        if(ddg.AbstractURL) ans += `\n\n<a href="${ddg.AbstractURL}" target="_blank" rel="noopener">Read more on DuckDuckGo</a>`;
        return ans;
      }
      // Try Wikipedia fallback
      let wikiAns = await wikiSummary(text);
      if(wikiAns) return wikiAns;
    }

    // Use fallback knowledge base fuzzy search
    let fuseResult = fuse.search(text);
    if(fuseResult.length > 0 && fuseResult[0].score < 0.4) {
      return fuseResult[0].item.answer;
    }

    // If user asks for trivia  
    if(/quiz|trivia|question/i.test(text)) {
      let trivia = await openTrivia();
      if(trivia) {
        let allAnswers = [...trivia.incorrect_answers, trivia.correct_answer];
        shuffle(allAnswers);
        let quiz = `Trivia question:\n${decodeHtml(trivia.question)}\nOptions:\n${allAnswers.map((a,i)=>`${i+1}: ${decodeHtml(a)}`).join('\n')}\n(Type the option number to answer.)`;
        lastQuiz = {correct: trivia.correct_answer, options: allAnswers};
        return quiz;
      }
    }

    // Numbers fact example
    if(/number fact for (\d+)/i.test(text)) {
      let num = text.match(/number fact for (\d+)/i)[1];
      let fact = await numbersFact(num);
      if(fact) return `Did you know? ${fact}`;
    }

    // Fallback personality-based fallback:
    let fallbackMsgs = {
      friendly: "Hmm... I don't know that one. Try asking me a math question or trivia!",
      formal: "Apologies, the information is unavailable. Please ask something else.",
      funny: "I can't help you with that... maybe take a snack break and try again!"
    };
    return fallbackMsgs[settings.personality] || fallbackMsgs['friendly'];
  }

  // Simple shuffle helper for quiz options
  function shuffle(array) {
    for(let i=array.length-1; i>0; i--) {
      let j = Math.floor(Math.random()*(i+1));
      [array[i],array[j]]=[array[j],array[i]];
    }
  }

  // Decode basic HTML entities for trivia questions/answers
  function decodeHtml(html) {
    let txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
  }

  // --- Handle quiz answers ---
  let lastQuiz = null;
  function handleQuizAnswer(input) {
    if(!lastQuiz) return null;
    let choice = Number(input.trim());
    if(isNaN(choice) || choice <1 || choice > lastQuiz.options.length) return "Please reply with the option number!";
    let answer = lastQuiz.options[choice-1];
    if(answer === lastQuiz.correct) {
      lastQuiz = null;
      return "Correct! Nice job. Ask for another quiz or question.";
    } else {
      return "Oops, that's not right. Try again or type 'skip' to move on.";
    }
  }

  // Chat memory management
  function addToMemory(role, text) {
    chatMemory.push({role, text});
    if(chatMemory.length > settings.maxMemorySteps * 2) {
      chatMemory.splice(0, chatMemory.length - settings.maxMemorySteps * 2);
    }
    saveChatMemory();
  }

  // Show typing indicator with delay simulating typing speed
  async function botReplyWithTyping(text) {
    if(!settings.useTypingDelay) {
      appendMsg(text, 'ai');
      return;
    }
    typingInd.style.display = 'block';
    let delay = Math.max(200, text.length * settings.typingSpeedMs);
    await new Promise(r=>setTimeout(r, delay));
    typingInd.style.display = 'none';
    appendMsg(text, 'ai');
  }

  // Main chat submit handler
  inputForm.addEventListener('submit', async e => {
    e.preventDefault();
    let inputVal = userInput.value.trim();
    if(!inputVal) return;
    appendMsg(inputVal, 'user');
    addToMemory('user', inputVal);
    userInput.value = '';

    // Check quiz mode first
    if(lastQuiz) {
      let result = handleQuizAnswer(inputVal);
      if(result) {
        await botReplyWithTyping(result);
        if(result.includes('Correct')) addToMemory('ai', result);
        return;
      }
    }

    let reply = await generateReply(inputVal);
    await botReplyWithTyping(reply);
    addToMemory('ai', reply);
  });

  // Tab switch logic
  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      tabs.forEach(t => {
        t.classList.remove('active');
        tabContents.find(tc => tc.id === t.getAttribute('aria-controls')).hidden = true;
      });
      tab.classList.add('active');
      document.getElementById(tab.getAttribute('aria-controls')).hidden = false;
    });
  });

  // Proxy Search Interface
  const proxySearchInput = document.getElementById('proxy-search-input');
  const proxySearchBtn = document.getElementById('proxy-search-btn');
  const proxySearchResults = document.getElementById('proxy-search-results');

  proxySearchBtn.addEventListener('click', async () => {
    let query = proxySearchInput.value.trim();
    if(!query) return;
    proxySearchResults.innerHTML = 'Searching...';
    try {
      let ddgData = await duckDuckGoQuery(query);
      if(ddgData && ddgData.RelatedTopics && ddgData.RelatedTopics.length) {
        let html = '';
        ddgData.RelatedTopics.slice(0,8).forEach(item => {
          let text = item.Text || (item.Topics && item.Topics[0].Text) || 'Result';
          let url = item.FirstURL || (item.Topics && item.Topics[0].FirstURL) || 'https://duckduckgo.com';
          html += `<p><a href="${url}" target="_blank" rel="noopener">${text}</a></p>`;
        });
        proxySearchResults.innerHTML = html || 'No results found.';
      } else {
        proxySearchResults.textContent = 'No results found.';
      }
    } catch (e) {
      proxySearchResults.textContent = 'Error during search.';
    }
  });

  // Initialize fuse fuzzy search on fallbackQA  
  const fuse = new Fuse([
    { question: 'How many continents are there?', answer: 'There are 7 continents on Earth.' },
    { question: 'What color do you get when you mix red and blue?', answer: 'You get purple.' },
    { question: 'Who was Abraham Lincoln?', answer: 'He was the 16th President of the United States.' },
    { question: 'What is the largest planet?', answer: 'Jupiter is the largest planet.' },
    { question: 'How many legs does a spider have?', answer: 'A spider has 8 legs.' },
    { question: 'Spell apple', answer: 'A-P-P-L-E spells apple.' },
    { question: 'Chemical formula of water', answer: 'H2O.' },
    { question: 'What is photosynthesis?', answer: 'It is the process plants use to turn sunlight into energy.' },
    { question: 'Who is the president of the United States?', answer: 'Joe Biden.' }
  ], {
    keys: ['question'],
    threshold: 0.45,
  });

  // Load settings and chat memory  
  loadSettings();  
  applySettingsUI();  
  attachSettingsListeners();  
  loadChatMemory();

})();

</script>
</body>
</html>