<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <title>Rich Man Thinker Ai</title>
  <meta name="theme-color" content="#eea236">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  
  <!-- Fixed Manifest -->
  <link rel="manifest" href="data:application/manifest+json,{%22name%22:%22Rich%20Man%20Thinker%20Ai%22,%22short_name%22:%22RichThinker%22,%22start_url%22:%22.%22,%22display%22:%22standalone%22,%22background_color%22:%22%230f0f1a%22,%22theme_color%22:%22%23eea236%22,%22icons%22:[{%22src%22:%22https://via.placeholder.com/192/eea236/111?text=Money%22,%22sizes%22:%22192x192%22}]}">

  <style>
    /* Font styles (unchanged) */
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@500;700&family=Inter:wght@400;600;700&family=Baloo+Da+2:wght@400;600;700&display=swap');
    :root{--bg:#0f0f1a;--surface:rgba(15,15,26,0.95);--text:#eee;--accent:#eea236;--accent-light:#ffca6f;--input-bg:rgba(30,30,50,0.9);--border:rgba(238,162,54,0.3)}
    [data-theme="light"]{--bg:#f8f9fa;--surface:rgba(255,255,255,0.95);--text:#1a1a2e;--accent:#d48f1e;--accent-light:#f5a623;--input-bg:rgba(240,240,245,0.9);--border:rgba(212,143,30,0.4)}
    *{margin:0;padding:0;box-sizing:border-box}
    body{font-family:'Inter', 'Baloo Da 2', sans-serif;background:var(--bg);color:var(--text);min-height:100dvh;display:flex;justify-content:center;align-items:center;overflow:hidden}
    body::before{content:'';position:absolute;inset:0;background:radial-gradient(circle at 30% 30%,rgba(238,162,54,0.15),transparent 60%);pointer-events:none}
    .container{width:100vw;height:100dvh;max-width:100%;background:var(--surface);border-radius:0;box-shadow:none;display:flex;flex-direction:column;position:relative}
    header{background:linear-gradient(135deg,var(--accent),var(--accent-light));color:#0f0f1a;padding:20px;text-align:center;font-family:'Orbitron',sans-serif;font-size:26px;letter-spacing:2px;position:relative}
    .icon-btn{position:absolute;top:14px;background:rgba(0,0,0,0.3);color:white;border:none;border-radius:50%;width:48px;height:48px;cursor:pointer;display:flex;align-items:center;justify-content:center}
    .settings-btn{right:12px}
    .back-btn{left:12px}
    .history-btn{right:68px}
    #chatbox{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:16px}
    .message{max-width:85%;padding:14px 18px;border-radius:20px;line-height:1.6;font-size:16px;word-wrap:break-word;position:relative}
    .message.bot{align-self:flex-start;background:rgba(30,30,50,0.9);border:1px solid var(--border);border-bottom-left-radius:4px}
    .message.user{align-self:flex-end;background:linear-gradient(135deg,var(--accent),var(--accent-light));color:#0f0f1a;border-bottom-right-radius:4px}
    [data-theme=light] .message.bot{background:#fff;color:#1a1a2e}
    #input-area{display:flex;padding:12px 16px;background:rgba(10,10,20,0.98);border-top:1px solid var(--border);gap:10px;align-items:center}
    [data-theme=light] #input-area{background:#fff}
    #userInput{flex:1;padding:16px 20px;border:none;border-radius:30px;background:var(--input-bg);color:var(--text);font-size:16px;outline:none;border:1.5px solid var(--border)}
    #sendBtn{width:56px;height:56px;background:linear-gradient(135deg,var(--accent),var(--accent-light));color:#0f0f1a;border:none;border-radius:50%;font-size:26px;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0}
    #settings-panel{display:none;flex-direction:column;height:100dvh;background:var(--surface);padding:20px}
    #settings-panel h2{margin:20px 0 30px;font-size:24px;text-align:center}
    input,select,button.save-btn{width:100%;padding:16px;margin:12px 0;border-radius:16px;font-size:16px;border:1.5px solid var(--border);background:var(--input-bg);color:var(--text)}
    button.save-btn{background:linear-gradient(135deg,var(--accent),var(--accent-light));color:#0f0f1a;font-weight:bold}
    .status{text-align:center;padding:10px;font-size:14px;color:#ff9800}
    
    /* Chat History Panel Styles */
    #history-panel{display:none;flex-direction:column;height:100dvh;background:var(--surface);padding:20px}
    #history-panel h2{margin:20px 0 30px;font-size:24px;text-align:center}
    .history-controls{display:flex;gap:10px;margin-bottom:20px}
    .history-controls button{flex:1;padding:12px;border-radius:12px;border:1.5px solid var(--border);background:var(--input-bg);color:var(--text);cursor:pointer}
    .history-controls button.clear-btn{background:linear-gradient(135deg,#ff4d4d,#ff9999);color:#0f0f1a}
    .history-list{flex:1;overflow-y:auto;display:flex;flex-direction:column;gap:12px}
    .history-item{padding:14px;border-radius:12px;background:var(--input-bg);border:1px solid var(--border);cursor:pointer;transition:all 0.2s}
    .history-item:hover{transform:translateY(-2px);box-shadow:0 4px 8px rgba(0,0,0,0.1)}
    .history-item-header{display:flex;justify-content:space-between;margin-bottom:8px;font-size:14px;color:var(--accent)}
    .history-item-content{font-size:14px;line-height:1.4;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
    .history-item-actions{display:flex;justify-content:flex-end;margin-top:8px;gap:8px}
    .history-item-actions button{padding:6px 12px;border-radius:8px;border:none;font-size:12px;cursor:pointer}
    .history-item-actions .delete-btn{background:rgba(255,77,77,0.2);color:#ff4d4d}
    .history-item-actions .delete-btn:hover{background:rgba(255,77,77,0.3)}
    
    /* Delete confirmation modal */
    .modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:1000;justify-content:center;align-items:center}
    .modal-content{background:var(--surface);padding:24px;border-radius:16px;max-width:90%;width:400px;text-align:center;box-shadow:0 10px 25px rgba(0,0,0,0.2)}
    .modal-buttons{display:flex;gap:12px;margin-top:20px}
    .modal-buttons button{flex:1;padding:12px;border-radius:12px;border:none;cursor:pointer;font-weight:bold}
    .modal-buttons .confirm-btn{background:linear-gradient(135deg,#ff4d4d,#ff9999);color:#0f0f1a}
    .modal-buttons .cancel-btn{background:var(--input-bg);color:var(--text)}

    /* Demo mode indicator */
    .demo-indicator {
      position: fixed;
      top: 10px;
      right: 10px;
      background: #ff9800;
      color: #000;
      padding: 5px 10px;
      border-radius: 10px;
      font-size: 12px;
      z-index: 1000;
    }
  </style>
</head>
<body data-theme="dark">

<div class="container">
  <div id="chat-view" style="display:flex;flex-direction:column;height:100dvh">
    <header>
      Rich Man Thinker Ai 
      <button class="icon-btn history-btn" id="openHistory">
        <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/></svg>
      </button>
      <button class="icon-btn settings-btn" id="openSettings">
        <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.49.49 0 0 0-.49-.42h-3.84a.49.49 0 0 0-.49.42l-.36 2.54c-.59.24-1.13.56-1.62.94l-2.39-.96a.49.49 0 0 0-.59.22l-1.92 3.32c-.15.25-.08.54.12.61l2.03 1.58c-.05.3-.07.62-.07.94 0 .33.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.15.25.42.33.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.25.42.49.42h3.84c.24 0 .44-.18.49-.42l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.17.11.44.03.59-.22l1.92-3.32c.15-.25.08-.54-.12-.61l-2.03-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>
      </button>
    </header>

    <div id="chatbox">
      <div class="message bot" data-i18n="welcome"></div>
    </div>

    <div class="status" id="status"></div>

    <div id="input-area">
      <input type="text" id="userInput" placeholder="Ask about wealth..." autocomplete="off"/>
      <button id="sendBtn">
        <svg viewBox="0 0 24 24" width="28" height="28" fill="#0f0f1a"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
      </button>
    </div>
  </div>

  <div id="settings-panel">
    <header>
      <button class="icon-btn back-btn" id="backToChat">
        <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M20 11H7.83l5.31-5.31-1.42-1.42L4 12l7.72 7.72 1.42-1.42L7.83 13H20z"/></svg>
      </button>
      Settings
    </header>
    <h2>Personalize Your Experience</h2>
    <input type="text" id="userName" placeholder="Your Name"/>
    <select id="languageSelect">
      <option value="en">English (Default)</option>
      <option value="bn">বাংলা</option>
      <option value="es">Español</option>
    </select>
    <select id="themeSelect">
      <option value="dark">Dark Mode</option>
      <option value="light">Light Mode</option>
    </select>
    <button class="save-btn">Save Settings</button>
  </div>

  <!-- Chat History Panel -->
  <div id="history-panel">
    <header>
      <button class="icon-btn back-btn" id="backToChatFromHistory">
        <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M20 11H7.83l5.31-5.31-1.42-1.42L4 12l7.72 7.72 1.42-1.42L7.83 13H20z"/></svg>
      </button>
      Chat History
    </header>
    <h2>Your Conversation History</h2>
    <div class="history-controls">
      <button id="loadHistory">Load History</button>
      <button class="clear-btn" id="clearAllHistory">Clear All</button>
    </div>
    <div class="history-list" id="historyList">
      <!-- History items will be populated here -->
    </div>
  </div>

  <!-- Delete Confirmation Modal -->
  <div class="modal" id="deleteModal">
    <div class="modal-content">
      <h3>Delete Message</h3>
      <p>Are you sure you want to delete this message? This action cannot be undone.</p>
      <div class="modal-buttons">
        <button class="confirm-btn" id="confirmDelete">Delete</button>
        <button class="cancel-btn" id="cancelDelete">Cancel</button>
      </div>
    </div>
  </div>
</div>

<!-- Demo Mode Indicator -->
<div class="demo-indicator" id="demoIndicator" style="display: none;">Demo Mode</div>

<script type="text/json" id="translations">
{
  "en": {"welcome":"Hello <strong>[NAME]</strong>! I am your Rich Man Thinker AI. I provide advice on building true wealth.<br><br>Ask me anything about assets, cashflow, or financial mindset.<br><em>Money works for YOU.</em>","placeholder":"Ask about wealth...","thinking":"Analyzing financial principles...","error":"API is currently busy — I'll keep trying..."},
  "bn": {"welcome":"স্বাগতম <strong>[NAME]</strong>! আমি আপনার 'ধনী চিন্তাবিদ' (Rich Man Thinker) এআই। আমি সত্যিকারের সম্পদ তৈরির বিষয়ে পরামর্শ দিই।<br><br>সম্পদ, অ্যাসেট, ক্যাশফ্লো বা আর্থিক মানসিকতা নিয়ে যেকোনো প্রশ্ন করুন।<br><em>টাকা আপনার জন্য কাজ করবে।</em>","placeholder":"সম্পদ নিয়ে জিজ্ঞাসা করুন...","thinking":"আর্থিক নীতি বিশ্লেষণ করছি...","error":"API এই মুহূর্তে ব্যস্ত আছে—আমি চেষ্টা করে যাব..."},
  "es": {"welcome":"¡Hola <strong>[NAME]</strong>! Soy tu Rich Man Thinker AI. Ofrezco consejos para construir riqueza real.<br><br>Pregúntame sobre activos, flujo de caja o mentalidad financiera.<br><em>El dinero trabaja para TI.</em>","placeholder":"Pregunta sobre riqueza...","thinking":"Analizando principios financieros...","error":"API está ocupado — seguiré intentando..."}
}
</script>

<script>
  // **Groq API key and model settings**
  const API_KEY = "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"; 
  const GROQ_MODEL = "llama-3.3-70b-versatile"; 
  const GROQ_ENDPOINT = "https://api.groq.com/openai/v1/chat/completions";

  const translations = JSON.parse(document.getElementById("translations").textContent);
  let currentLang = "en", userName = "Friend"; 
  let chatHistory = [];
  let currentChatId = null;
  let messageToDelete = null;
  let demoMode = false;

  // Load saved settings and chat history
  const saved = JSON.parse(localStorage.getItem("richThinkerSettings") || "{}");
  userName = saved.name || "Friend";
  currentLang = saved.lang || "en"; 
  document.body.dataset.theme = saved.theme || "dark";
  
  // Load chat history from localStorage
  const savedHistory = JSON.parse(localStorage.getItem("richThinkerChatHistory") || "[]");
  chatHistory = savedHistory;

  // Generate a unique ID for the current chat session
  function generateChatId() {
    return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  // Initialize current chat ID if not exists
  if (!currentChatId) {
    currentChatId = generateChatId();
  }

  document.querySelector("[data-i18n=welcome]").innerHTML = translations[currentLang].welcome.replace("[NAME]", userName);
  document.getElementById("userInput").placeholder = translations[currentLang].placeholder;

  document.getElementById("userName").value = userName;
  document.getElementById("languageSelect").value = currentLang;
  document.getElementById("themeSelect").value = document.body.dataset.theme;

  // Panel navigation
  document.getElementById("openSettings").onclick = () => {
    document.getElementById("chat-view").style.display = "none";
    document.getElementById("settings-panel").style.display = "flex";
    document.getElementById("history-panel").style.display = "none";
  };
  
  document.getElementById("openHistory").onclick = () => {
    document.getElementById("chat-view").style.display = "none";
    document.getElementById("settings-panel").style.display = "none";
    document.getElementById("history-panel").style.display = "flex";
    loadHistoryList();
  };
  
  document.getElementById("backToChat").onclick = () => {
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("settings-panel").style.display = "none";
    document.getElementById("history-panel").style.display = "none";
  };
  
  document.getElementById("backToChatFromHistory").onclick = () => {
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("settings-panel").style.display = "none";
    document.getElementById("history-panel").style.display = "none";
  };
  
  document.querySelector(".save-btn").onclick = () => {
    userName = document.getElementById("userName").value.trim() || "Friend";
    currentLang = document.getElementById("languageSelect").value;
    const theme = document.getElementById("themeSelect").value;
    document.body.dataset.theme = theme;
    localStorage.setItem("richThinkerSettings", JSON.stringify({name:userName,lang:currentLang,theme}));
    document.querySelector("[data-i18n=welcome]").innerHTML = translations[currentLang].welcome.replace("[NAME]", userName);
    document.getElementById("userInput").placeholder = translations[currentLang].placeholder;
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("settings-panel").style.display = "none";
  };

  // Chat Logic
  const chatbox = document.getElementById("chatbox");
  
  function add(msg, type) {
    const div = document.createElement("div");
    div.className = `message ${type}`;
    div.innerHTML = msg.replace(/\n/g,"<br>");
    chatbox.appendChild(div);
    chatbox.scrollTop = chatbox.scrollHeight;
    
    // Save message to history
    saveMessageToHistory(msg, type);
    
    return div;
  }

  // Save message to chat history
  function saveMessageToHistory(content, type) {
    const message = {
      id: Date.now().toString(),
      content: content,
      type: type,
      timestamp: new Date().toISOString(),
      chatId: currentChatId
    };
    
    // Add to current session
    const currentChat = chatHistory.find(chat => chat.id === currentChatId);
    if (currentChat) {
      currentChat.messages.push(message);
    } else {
      // Create new chat session
      chatHistory.push({
        id: currentChatId,
        title: content.substring(0, 50) + (content.length > 50 ? '...' : ''),
        timestamp: new Date().toISOString(),
        messages: [message]
      });
    }
    
    // Save to localStorage
    localStorage.setItem("richThinkerChatHistory", JSON.stringify(chatHistory));
  }

  // Load history list in the history panel
  function loadHistoryList() {
    const historyList = document.getElementById("historyList");
    historyList.innerHTML = '';
    
    if (chatHistory.length === 0) {
      historyList.innerHTML = '<div class="history-item">No chat history available</div>';
      return;
    }
    
    // Sort by timestamp (newest first)
    const sortedHistory = [...chatHistory].sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    
    sortedHistory.forEach(chat => {
      const historyItem = document.createElement("div");
      historyItem.className = "history-item";
      
      const date = new Date(chat.timestamp);
      const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
      
      historyItem.innerHTML = `
        <div class="history-item-header">
          <span>${formattedDate}</span>
          <span>${chat.messages.length} messages</span>
        </div>
        <div class="history-item-content">${chat.title}</div>
        <div class="history-item-actions">
          <button class="delete-btn" data-chat-id="${chat.id}">Delete Chat</button>
        </div>
      `;
      
      // Add click event to load chat
      historyItem.addEventListener('click', (e) => {
        if (!e.target.classList.contains('delete-btn')) {
          loadChat(chat.id);
        }
      });
      
      // Add delete event
      const deleteBtn = historyItem.querySelector('.delete-btn');
      deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        showDeleteConfirmation(chat.id);
      });
      
      historyList.appendChild(historyItem);
    });
  }

  // Load a specific chat
  function loadChat(chatId) {
    const chat = chatHistory.find(c => c.id === chatId);
    if (!chat) return;
    
    // Clear current chat
    chatbox.innerHTML = '';
    
    // Load messages
    chat.messages.forEach(msg => {
      const div = document.createElement("div");
      div.className = `message ${msg.type}`;
      div.innerHTML = msg.content.replace(/\n/g,"<br>");
      chatbox.appendChild(div);
    });
    
    // Set current chat ID
    currentChatId = chatId;
    
    // Return to chat view
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("history-panel").style.display = "none";
    
    // Scroll to bottom
    chatbox.scrollTop = chatbox.scrollHeight;
  }

  // Show delete confirmation modal
  function showDeleteConfirmation(chatId) {
    messageToDelete = chatId;
    document.getElementById("deleteModal").style.display = "flex";
  }

  // Delete a chat
  function deleteChat(chatId) {
    chatHistory = chatHistory.filter(chat => chat.id !== chatId);
    localStorage.setItem("richThinkerChatHistory", JSON.stringify(chatHistory));
    
    // If we deleted the current chat, create a new one
    if (currentChatId === chatId) {
      currentChatId = generateChatId();
      chatbox.innerHTML = '<div class="message bot" data-i18n="welcome"></div>';
      document.querySelector("[data-i18n=welcome]").innerHTML = translations[currentLang].welcome.replace("[NAME]", userName);
    }
    
    // Reload history list
    loadHistoryList();
  }

  // Clear all chat history
  function clearAllHistory() {
    chatHistory = [];
    localStorage.setItem("richThinkerChatHistory", JSON.stringify(chatHistory));
    
    // Reset current chat
    currentChatId = generateChatId();
    chatbox.innerHTML = '<div class="message bot" data-i18n="welcome"></div>';
    document.querySelector("[data-i18n=welcome]").innerHTML = translations[currentLang].welcome.replace("[NAME]", userName);
    
    // Reload history list
    loadHistoryList();
  }

  // Event listeners for history controls
  document.getElementById("loadHistory").addEventListener("click", loadHistoryList);
  document.getElementById("clearAllHistory").addEventListener("click", clearAllHistory);
  
  // Modal event listeners
  document.getElementById("confirmDelete").addEventListener("click", () => {
    if (messageToDelete) {
      deleteChat(messageToDelete);
      messageToDelete = null;
    }
    document.getElementById("deleteModal").style.display = "none";
  });
  
  document.getElementById("cancelDelete").addEventListener("click", () => {
    messageToDelete = null;
    document.getElementById("deleteModal").style.display = "none";
  });

  // Demo responses for when API fails
  const demoResponses = {
    "en": [
      "Focus on acquiring income-generating assets rather than liabilities. True wealth comes from assets that work for you while you sleep.",
      "Build multiple streams of income. Don't rely solely on your job - create systems that generate money automatically.",
      "Financial freedom isn't about how much you earn, but how much you keep and how effectively that money works for you.",
      "Invest in your financial education first. The best asset you can develop is your own financial intelligence.",
      "Start small but start now. Consistent investment in assets, no matter how small, compounds into significant wealth over time."
    ],
    "bn": [
      "দায়বদ্ধতার পরিবর্তে আয়-উৎপাদনকারী সম্পদ অর্জনের দিকে মনোনিবেশ করুন। সত্যিকারের সম্পদ আসে এমন সম্পদ থেকে যা আপনার ঘুমানোর সময়ও আপনার জন্য কাজ করে।",
      "একাধিক আয়ের উৎস তৈরি করুন। শুধুমাত্র আপনার চাকরির উপর নির্ভর করবেন না - এমন সিস্টেম তৈরি করুন যা স্বয়ংক্রিয়ভাবে অর্থ উপার্জন করে।",
      "আর্থিক স্বাধীনতা আপনি কতটা আয় করেন তার উপর নয়, বরং আপনি কতটা সংরক্ষণ করেন এবং সেই অর্থ আপনার জন্য কতটা কার্যকরভাবে কাজ করে তার উপর নির্ভর করে।",
      "প্রথমে আপনার আর্থিক শিক্ষায় বিনিয়োগ করুন। আপনি যে সেরা সম্পদ বিকাশ করতে পারেন তা হল আপনার নিজের আর্থিক বুদ্ধিমত্তা।",
      "ছোট করে শুরু করুন কিন্তু এখনই শুরু করুন। সম্পদে সামঞ্জস্যপূর্ণ বিনিয়োগ, যত ছোটই হোক না কেন, সময়ের সাথে সাথে তা উল্লেখযোগ্য সম্পদে পরিণত হয়।"
    ],
    "es": [
      "Concéntrate en adquirir activos que generen ingresos en lugar de pasivos. La verdadera riqueza proviene de activos que trabajan para ti mientras duermes.",
      "Construye múltiples flujos de ingresos. No dependas únicamente de tu trabajo: crea sistemas que generen dinero automáticamente.",
      "La libertad financiera no se trata de cuánto ganas, sino de cuánto conservas y qué tan efectivamente ese dinero trabaja para ti.",
      "Invierte primero en tu educación financiera. El mejor activo que puedes desarrollar es tu propia inteligencia financiera.",
      "Comienza pequeño pero comienza ahora. La inversión constante en activos, sin importar cuán pequeña sea, se convierte en una riqueza significativa con el tiempo."
    ]
  };

  function getDemoResponse() {
    const responses = demoResponses[currentLang] || demoResponses["en"];
    return responses[Math.floor(Math.random() * responses.length)];
  }

  async function sendMessage() {
    const q = document.getElementById("userInput").value.trim();
    if (!q) return;
    add(q, "user");
    document.getElementById("userInput").value = "";
    const typing = add(translations[currentLang].thinking, "bot");

    let attempts = 0;
    const max = 4;
    const trySend = async () => {
      attempts++;
      
      const langName = { "en": "English", "bn": "Bengali (Bangla)", "es": "Spanish" }[currentLang];
      
      // ***সংশোধিত সিস্টেম প্রম্পট: নিষিদ্ধ শব্দগুলি কঠোরভাবে নিষেধ করা হয়েছে***
      const systemPrompt = `You are a highly sought-after Financial Advisor AI, acting as a coach who imparts a single, powerful financial philosophy. Your advice is strictly based on the philosophy that **true wealth is built by generating income from assets, not from a paycheck.** Your core mission is to aggressively guide the user to shift their focus from relying on a job (Employee/Self-Employed mentality) to building or investing in systems/businesses (Investor/Business Owner mentality). You MUST prioritize the accumulation of **income-generating assets** (Assets) over non-income-generating purchases (Liabilities) at all times. All advice must be paired with **patient, long-term, and value-focused investment principles.**

        STRICT RULE 1: Respond ONLY in ${langName}.
        STRICT RULE 2: Your entire response must be a maximum of 6 sentences long.
        STRICT RULE 3: You MUST end the response with a powerful, motivational quote emphasizing financial independence or asset building.
        STRICT RULE 4: **DO NOT use the terms "Kiyosaki," "Cashflow Quadrant," "Buffett," or "Groq."** Use only the philosophical terms (e.g., Asset, Liability, Financial Freedom) in your advice.
        STRICT RULE 5: When the user asks about buying a liability (like an expensive car), immediately categorize it as a **Liability** and redirect the focus to building an Asset.`;

      try {
        // Groq API এর জন্য fetch রিকোয়েস্ট
        const res = await fetch(GROQ_ENDPOINT, {
          method:"POST", 
          headers:{
            "Content-Type":"application/json",
            "Authorization": `Bearer ${API_KEY}` 
          },
          body:JSON.stringify({
            model: GROQ_MODEL,
            messages: [
              { role: "system", content: systemPrompt },
              { role: "user", content: q }
            ],
            temperature: 1,
            max_tokens: 1000,
          })
        });
        
        if (res.status === 429) {
           throw new Error("Rate Limit Exceeded (429)");
        }
        if (res.status === 503) {
           throw new Error("Service Unavailable (503)");
        }
        if (!res.ok) {
           throw new Error(`HTTP Error: ${res.status}`);
        }

        const data = await res.json();
        const reply = data.choices?.[0]?.message?.content || translations[currentLang].error;
        
        chatbox.removeChild(typing);
        add(reply, "bot");
        document.getElementById("status").textContent = "";
        demoMode = false;
        document.getElementById("demoIndicator").style.display = "none";
      } catch(e) {
        if (attempts < max) {
          document.getElementById("status").textContent = e.message.includes("429") 
            ? `⚠️ ${translations[currentLang].error} (Too Many Requests). Retrying... (${attempts}/${max})`
            : `⚠️ ${translations[currentLang].error} (${e.message.split('(')[0].trim()}). Retrying... (${attempts}/${max})`;
          
          setTimeout(trySend, 3000*attempts); 
        } else {
          // Switch to demo mode after all attempts fail
          chatbox.removeChild(typing);
          const demoResponse = getDemoResponse();
          add(demoResponse, "bot");
          document.getElementById("status").textContent = "Using demo mode - API unavailable";
          demoMode = true;
          document.getElementById("demoIndicator").style.display = "block";
        }
      }
    };
    trySend();
  }

  document.getElementById("userInput").addEventListener("keypress", e=>e.key==="Enter"&&sendMessage());
  document.getElementById("sendBtn").addEventListener("click", sendMessage);
</script>
</body>
</html>