<!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,{"name":"Rich Man Thinker Ai","short_name":"RichThinker","start_url":".","display":"standalone","background_color":"#0f0f1a","theme_color":"#eea236","icons":[{"src":"https://via.placeholder.com/192/eea236/111?text=Money","sizes":"192x192"}]}'>

  <style>
    /* Your existing CSS remains the same */
    @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;display:flex;justify-content:center;align-items:center}
    .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{left:12px}
    #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}
    .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-list{flex:1;overflow-y:auto;padding:10px 0}
    .history-item{padding:12px 16px;margin-bottom:10px;background:var(--input-bg);border-radius:12px;cursor:pointer;border:1px solid var(--border);transition:all 0.2s ease}
    .history-item:hover{background:rgba(238,162,54,0.1)}
    .history-item.active{background:rgba(238,162,54,0.2);border-color:var(--accent)}
    .history-preview{font-size:14px;color:var(--text);opacity:0.8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .history-date{font-size:12px;color:var(--accent);margin-top:4px}
    #clear-history{width:100%;padding:12px;margin-top:20px;border-radius:12px;background:rgba(238,54,54,0.2);color:#ff6b6b;border:1px solid rgba(238,54,54,0.3);cursor:pointer;font-weight:600}
    #clear-history:hover{background:rgba(238,54,54,0.3)}
  </style>
</head>
<body data-theme="dark">

<div class="container">
  <div id="chat-view" style="display:flex;flex-direction:column;height:100dvh">
    <header>
      <button class="icon-btn history-btn" id="openHistory">
        <svg viewBox="0 0 24 24" width="24" height="24" fill="white"><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/></svg>
      </button>
      Rich Man Thinker Ai 
      <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>
  
  <!-- New 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>Previous Conversations</h2>
    <div id="history-list">
      <!-- History items will be populated here -->
    </div>
    <button id="clear-history">Clear All History</button>
  </div>
</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 কী এবং মডেল সেট করা হয়েছে**
  const API_KEY = "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"; 
  const GROQ_MODEL = "llama-3.3-70b-versatile"; 
  
  // Use CORS proxy to fix the CORS error
  const GROQ_ENDPOINT = "https://corsproxy.io/?https://api.groq.com/openai/v1/chat/completions";

  const translations = JSON.parse(document.getElementById("translations").textContent);
  let currentLang = "en", userName = "Friend"; 
  
  // Chat History Variables
  let chatHistory = JSON.parse(localStorage.getItem("richThinkerChatHistory") || "[]");
  let currentChatId = null;

  // Load saved settings (Existing logic remains)
  const saved = JSON.parse(localStorage.getItem("richThinkerSettings") || "{}");
  userName = saved.name || "Friend";
  currentLang = saved.lang || "en"; 
  document.body.dataset.theme = saved.theme || "dark";

  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("openHistory").onclick = () => {
    document.getElementById("chat-view").style.display = "none";
    document.getElementById("history-panel").style.display = "flex";
    renderHistoryList();
  };
  
  document.getElementById("backToChat").onclick = () => {
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("settings-panel").style.display = "none";
  };
  
  document.getElementById("backToChatFromHistory").onclick = () => {
    document.getElementById("chat-view").style.display = "flex";
    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 History Functions
  function renderHistoryList() {
    const historyList = document.getElementById("history-list");
    historyList.innerHTML = "";
    
    if (chatHistory.length === 0) {
      historyList.innerHTML = '<div style="text-align:center;padding:20px;opacity:0.7">No chat history yet</div>';
      return;
    }
    
    chatHistory.forEach((chat, index) => {
      const historyItem = document.createElement("div");
      historyItem.className = "history-item";
      if (chat.id === currentChatId) {
        historyItem.classList.add("active");
      }
      
      const preview = chat.messages.length > 1 ? 
        (chat.messages[1].content.length > 50 ? 
          chat.messages[1].content.substring(0, 50) + "..." : 
          chat.messages[1].content) : 
        "New conversation";
      
      historyItem.innerHTML = `
        <div class="history-preview">${preview}</div>
        <div class="history-date">${new Date(chat.timestamp).toLocaleDateString()}</div>
      `;
      
      historyItem.onclick = () => loadChatHistory(chat.id);
      historyList.appendChild(historyItem);
    });
  }
  
  function loadChatHistory(chatId) {
    const chat = chatHistory.find(c => c.id === chatId);
    if (!chat) return;
    
    currentChatId = chatId;
    const chatbox = document.getElementById("chatbox");
    chatbox.innerHTML = "";
    
    chat.messages.forEach(msg => {
      const div = document.createElement("div");
      div.className = `message ${msg.role === "user" ? "user" : "bot"}`;
      div.innerHTML = msg.content.replace(/\n/g, "<br>");
      chatbox.appendChild(div);
    });
    
    chatbox.scrollTop = chatbox.scrollHeight;
    
    // Return to chat view
    document.getElementById("chat-view").style.display = "flex";
    document.getElementById("history-panel").style.display = "none";
  }
  
  function saveMessageToHistory(message, role) {
    // If no current chat, create a new one
    if (!currentChatId) {
      currentChatId = Date.now().toString();
      chatHistory.unshift({
        id: currentChatId,
        timestamp: Date.now(),
        messages: []
      });
    }
    
    // Find current chat
    const currentChat = chatHistory.find(c => c.id === currentChatId);
    if (currentChat) {
      currentChat.messages.push({
        role: role,
        content: message,
        timestamp: Date.now()
      });
      
      // Keep only the latest 20 chats
      if (chatHistory.length > 20) {
        chatHistory = chatHistory.slice(0, 20);
      }
      
      localStorage.setItem("richThinkerChatHistory", JSON.stringify(chatHistory));
    }
  }
  
  document.getElementById("clear-history").onclick = () => {
    if (confirm("Are you sure you want to clear all chat history?")) {
      chatHistory = [];
      localStorage.removeItem("richThinkerChatHistory");
      renderHistoryList();
    }
  };

  // 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 to history
    saveMessageToHistory(msg, type);
    
    return div;
  }

  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 = ""; 
      } 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 {
          chatbox.removeChild(typing);
          const finalErrorMsg = e.message.includes("429") 
            ? `API Limit reached. Please wait a minute before trying again. `
            : `API failed after ${max} attempts (${e.message}). Please check your API Key and internet connection.`;
          add(finalErrorMsg, "bot");
          document.getElementById("status").textContent = "";
        }
      }
    };
    trySend();
  }

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