Files
rm-circle-team-router/public/chat.js
T
martbost 6ac1bcab55 Telegram companion bot, phase 1
New tgbot.js (raw Bot API, zero deps, private-chats only so the
group feeds are untouched): wallet-verified linking via dashboard
deep-link codes, personal payout + joined-on-your-link DMs, a
message bridge that delivers site messages natively in Telegram
with reply-to-answer routing (matrix-line permissions enforced by
the existing messages.js rules), and links/msg/help commands.
Webhook self-registers; secret derived from the token. Config key
companionBotToken overrides the feed bot token when Marty creates
a dedicated bot. Dashboard Messages panel gains Connect Telegram;
chatbot + AI prompt synced.
2026-08-22 19:39:55 -05:00

145 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function(){
let config=null,sponsorInfo=null;
async function loadData(){
try{const r=await fetch('/api/public/config');if(r.ok)config=await r.json()}catch(e){}
try{const r=await fetch('/api/public/current-sponsor');if(r.ok)sponsorInfo=await r.json()}catch(e){}
}
function esc(s){return String(s??'').replace(/[&<>'"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[c]))}
function tg(){return (config&&config.telegramUrl)||'https://t.me/cryptoteambuild'}
function pol(){return (config&&config.premiumEntryPol)||362}
function usd(){var u=config&&config.polUsd;return u>0?' (about $'+Math.round(pol()*u)+' at today’s POL price — it moves)':''}
function tgLink(label){return `<a href="${esc(tg())}" target="_blank" rel="noopener noreferrer">${esc(label||'Open the Telegram group ↗')}</a>`}
const KB=[
{k:['what is','rm circle','about','this site','this project','crypto team build','who are you','network'],
a:()=>`We enter the RM Circle dApp at the Premium tier (${pol()} POL on Polygon) and build as one team: each member gets exactly 2 directs, then helps those 2 get their 2 — building depth instead of width. Start with the <a href="/training">training videos</a>.`},
{k:['how does it work','strategy','how it works','plan','roadmap','system','duplicate','duplication'],
a:()=>`The core strategy: <strong>get your 2, retire your link, help your 2 get their 2, upgrade with profits, repeat.</strong> Once a position has 2 directs it's qualified — we stop using its link and move the team's effort down to the next positions. The full picture is in <a href="/training">Video 1 of the training</a>, and the roadmap poster is on the <a href="/">home page</a>.`},
{k:['cost','price','entry','how much','362','fee','pol needed','expensive'],
a:()=>`Premium entry is <strong>${pol()} POL</strong>${usd()} on Polygon Mainnet, plus a small extra POL balance for network gas. POL's dollar value changes with the market. Only ever use funds you can afford to lose.`},
{k:['pol','polygon','network','chain','gas','matic','mainnet'],
a:()=>`The build runs on <strong>Polygon Mainnet</strong> (chain ID 137). POL is the network's native token — it pays for your Premium entry AND for transaction "gas." Easiest way to think about gas: just like a car needs fuel to get from A to B, every blockchain transaction burns a tiny bit of POL to move. That's why you keep a little extra in the tank beyond your entry — a wallet that's bone-dry can't make the trip. In MetaMask, make sure Polygon is the selected network before doing anything.`},
{k:['metamask','wallet','create wallet','install','set up wallet','setup wallet'],
a:()=>`Install MetaMask only from the <a href="https://metamask.io/" target="_blank" rel="noopener noreferrer">official site</a> or your device's official app store, then create your wallet. <a href="/training">Video 2 in the training</a> walks through it step by step. Never share your Secret Recovery Phrase with anyone — not the team, not this site, not a "support agent".`},
{k:['fund','funding','buy pol','get pol','deposit','exchange','transfer','send pol'],
a:()=>`You'll need about ${pol()} POL plus a little extra for gas${usd()}, on Polygon Mainnet. <a href="/training">Video 3 in the training</a> shows how to fund your wallet. Brand new to crypto? You can buy POL directly with a debit/credit card, Apple Pay, or Google Pay via <a href="https://www.moonpay.com/buy/matic" target="_blank" rel="noopener noreferrer">MoonPay</a> — pick POL on the Polygon network (MoonPay may show POL's old name, MATIC — same token) and send it to your own wallet address. The join page also offers this automatically if your connected wallet is short. Double-check you're getting POL on Polygon — not another chain.`},
{k:['join','buy','purchase','premium position','enter','sign up','signup','register','get started','start'],
a:()=>`Ready to join? Go to the <a href="/start">Getting Started page</a> — it shows the current team sponsor and lets you connect your wallet and buy your position right on the site, with the sponsor ID filled in automatically. <a href="/training">Video 4 in the training</a> walks through the whole process (and Video 5 covers the dApp backup method).`},
{k:['sponsor','current sponsor','who do i join under','placement','whose link','referral'],
a:()=>{const s=sponsorInfo&&sponsorInfo.sponsor;return s?`The current team sponsor is <strong>ID ${esc(s.id)}${s.name?' ('+esc(s.name)+')':''}</strong> — always verify on the <a href="/start">Getting Started page</a> right before you join, because placements rotate as positions qualify. Don't use an old screenshot or saved link.`:`The current sponsor is always shown live on the <a href="/start">Getting Started page</a> — check there right before joining, because placements rotate as positions qualify.`}},
{k:['qualified','qualification','2 directs','two directs','directs','retire'],
a:()=>`A position is <strong>qualified</strong> once it has 2 directs. The team recommendation: retire your link at that point and help your 2 get <em>their</em> 2 using their own links — that's the only thing that qualifies them. And if someone happens to join through your link after 2/2, it's a bonus, not a problem: the entry reward still pays your position and they spill downward, adding depth to your leg. Just remember spillover never qualifies the people below — their own directs do.`},
{k:['safe','scam','rug','rug pull','security','audit','trust','legit','contract code','smart contract','can they change','steal'],
a:()=>`Fair question — don't take anyone's word for it. We reviewed the complete verified source of the RM Circle smart contract and published a plain-language breakdown at <a href="/contract">rmcircle.team/contract</a>: the code can never change (no upgrade mechanism exists), member money never sits in the contract (every payment distributes in the same transaction), prices and payout rules are locked forever, and the operator's powers are limited to a short, honest list. Every claim links to the blockchain so you can verify it yourself. Code security isn't an income guarantee though — results depend on real participation, and POL's value moves.`},
{k:['disappear','disappears','creator','creators','abandon','abandoned','walk away','goes away','shut down','shuts down','still work','keep running','keeps running','autonomous','dies','lost keys','without them','stop working','turned off','if they leave','what if they','forever','over time'],
a:()=>`Great question — and we checked it on-chain, not just in theory. The contract needs <strong>no one</strong> to keep it running: joins, upgrades, placement and every payout are fully automatic — no button anyone has to press, no expiry. If the creators walked away, lost their keys, or vanished, member payments keep flowing exactly as coded. We also verified that the founder, development and fee wallets are <strong>ordinary wallets, not programs</strong> — an ordinary wallet always accepts an incoming payment even if its key is lost forever, so a dead admin wallet can't jam a single member payment (at worst the project's <em>own</em> fee sits there uncollected). And the contract holds no stored balance — every payment is delivered in the same transaction. Full write-up in section 6 of <a href="/contract">rmcircle.team/contract</a>.`},
{k:['pyramid','ponzi','pyramid scheme','ponzi scheme','mlm','recruiting scheme','is this a scheme'],
a:()=>`A pyramid or Ponzi scheme funnels everyone's money to a central company and pays earlier joiners out of later joiners' deposits — and you can't verify any of it. This is the opposite: <strong>no company holds the money</strong>. A public smart contract on Polygon sends each payment person-to-person in the same transaction it arrives, and you can read the code and every payout yourself on-chain — nothing pooled, nothing hidden, rules that can't be changed. It <em>is</em> a team build, so it takes real effort and carries real crypto risk — not a passive investment. But you don't have to trust anyone; verify it at <a href="/contract">rmcircle.team/contract</a>. No income is guaranteed.`},
{k:['telegram bot','connect telegram','payout ping','telegram notification','message my downline','contact my downline','reach my downline'],
a:()=>`Link your position to our Telegram companion bot: open your <a href="/my">dashboard</a> → Messages → sign in with your wallet → tap "Connect Telegram". Once linked you get an instant DM whenever your position catches a payment, team messages reach you natively in Telegram (reply right there to answer), you're pinged when someone joins on your link, and "links" gives you all your invite links. Messaging still follows your matrix lines only — same rules as the site.`},
{k:['cash out','cashout','spend my crypto','withdraw','off ramp','off-ramp','gift card','giftcard','get my money out','turn into cash','convert to dollars'],
a:()=>`Three good paths, easiest first: (1) <strong>E-gift cards</strong> — send POL to CWallet (cwallet.com), swap to a US-dollar token there (their internal swaps are virtually free), and buy gift cards for brands you already use — groceries, gas, Amazon. eGifter (egifter.com) also takes crypto directly. (2) <strong>Straight cash-out</strong> via a regulated exchange in your country (Coinbase, Kraken…): send, sell, withdraw to your bank. (3) <strong>Keep it working</strong> — many members leave catches in the wallet to fund their next level. Full guide: <a href="/training#spending">Spending what you earn</a>. Honest notes: those are independent custodial services — only move what you're about to spend; taxes may apply where you live; not financial advice.`},
{k:['circle method','recruiting course','how do i recruit','recruiting training','get my two','get your two','how to invite','module 1','lessons'],
a:()=>`That's <a href="/training#circle-method">The Circle Method</a> — our free 10-lesson course, three modules, ~30 minutes total. Module 1 "Get Your Two": mindset, warm list, the exact words, objections. Module 2 "Help Your Two": your dashboard as a coaching desk, the first 48 hours, stalled people, timing upgrades. Module 3 "Teach the Teachers": run the same play + the 20-minute weekly rhythm. The Method's golden rule: the answer to every question is a lesson — when your people ask something, send the lesson that answers it.`},
{k:['no money','cant afford','can not afford',"can't afford",'broke','they dont have','waiting on payday','no funds to join'],
a:()=>`"No money" is usually one of three things — sort it first. (1) Most often it means "this sounds expensive/complicated": entry is ${pol()} POL${usd()||" — a small one-time amount"} — payable with a regular debit card right on the <a href="/join-now">join page</a>. (2) Sometimes it's a priority thing: send the "Pocket Change" video from <a href="/tools">Promo Tools</a> and let it do the talking. (3) If they're genuinely broke: tell them honestly "don't join yet" — never rent money, never money they can't afford to lose. Ask "when's payday?" and follow up then — their invite link doesn't expire and the team keeps building publicly while they wait. One hard rule: never pay someone's entry for them.`},
{k:['fast start','checklist','printable','print','48 hour','48-hour','getting started sheet'],
a:()=>`Grab the <a href="/fast-start">48-Hour Fast Start sheet</a> — a printable one-page checklist for your first two days. Open it from YOUR dashboard and it comes pre-filled with your invite link and a scannable QR code, then hit the print button (it prints clean black-on-white, in whatever language you've picked with the 🌐 button).`},
{k:['translate','translation','language','español','espanol','spanish','french','portuguese','not in english','other language'],
a:()=>`Tap the 🌐 Translate button in the bottom-left corner of any page — pick your language once and every page stays translated while you browse. Your phone's browser also usually offers its own "Translate page" option. And you can type to me here in ANY language — I'll answer in yours.`},
{k:['how many people','team size','organization size','org size','how big is my team','total team','people in my team','members below'],
a:()=>`Open your dashboard at <a href="/my">rmcircle.team/my</a> and look at the top of the "Your team" panel — the organization bar shows your total member count, how many generations deep your team runs, how many positions below you are qualified, the total POL earned below you, and its approximate US-dollar value at the latest POL price (refreshed about hourly). The matrix cards under it break the same numbers down leg by leg (the ⬇ rollup line on each card counts everyone underneath, all the way down).`},
{k:['wont upgrade',"won't upgrade",'not upgrading','refuses to upgrade','stalled','stuck member','not ready to upgrade','below me wont','waiting on someone','blocked by'],
a:()=>`Good news — a member who isn't upgrading never blocks your money. Each person below you pays you separately, once, at one level; nothing waits on pairs or chains. If someone pauses, payments they can't catch simply pass UP to the next ready position (often yours), and everyone below them keeps flowing normally. The only thing on hold is the single payment that person would send at your matching level. Never pressure anyone — upgrades are optional and self-paced, and paused members often return once their own entry rewards stack up and the upgrade funds itself. Your <a href="/my">pipeline panel</a> shows who's actually moving — coach them.`},
{k:['stops there','stop there','dead end','runs out','run out of people','get their two','get their 2','their own two','only two people','what if my two','cant get their'],
a:()=>`Honest answer: everyone needs their <strong>own</strong> 2 to qualify — no one else's activity qualifies them. But a leg doesn't just dead-end. It's a team: your job is to help your 2 get theirs, and your upline earns as your team grows, so helping you win is in their interest too. And when uplines bring in more than 2, the extras <strong>spill down</strong> and fill the matrix beneath you — adding depth even when someone's own recruiting is slow. It only truly stalls if everyone stops helping, which is the one thing a team is built to prevent. (Spillover fills your matrix but never <em>qualifies</em> anyone — their own directs do that.)`},
{k:['afford','cant afford','can t afford','no money to upgrade','forced to upgrade','have to upgrade','keep paying','cant keep up'],
a:()=>`Upgrades are <strong>optional and self-paced</strong> — you're never on a timer, and you should never use money you can't afford to lose. You upgrade to catch payments from deeper in your team, and the first payments at each level are designed to help fund the next upgrade, so many people let team activity pay their way up instead of out of pocket. Start where you're comfortable and move at your own pace. See how it lines up at <a href="/how-pay-works">how-pay-works</a>.`},
{k:['salesperson','not a seller','sales pitch','know anyone','no one to bring','nobody to','not good at sales','bad at recruiting','hate selling','who would i'],
a:()=>`Good news — there's nothing to sell. You share a short video and your invite link, and the site does the explaining for you. You don't need a big network or a sales pitch — just a couple of people who are curious. The team even gives you ready-made <a href="/tools">promo tools</a> (posts, swipes, videos) so you're not starting from a blank page. Get your 2, help them get their 2 — that's the whole ask.`},
{k:['quit','they quit','people quit','drop out','give up','go inactive','stop doing','flake','lose interest'],
a:()=>`Some people go quiet — that's normal anywhere. But a position lives on the blockchain and doesn't vanish when someone steps back, and the team keeps building around a quiet spot (spillover can still fill beneath it). You don't need everyone active — you need a couple of real builders. Focus on the people who show up, go deep with them, and the leg keeps growing. Build with people who genuinely want it — and remember, no income is guaranteed.`},
{k:['spillover','spill over','spill','under me but not qualified','people under me','not my direct','passed over','missed payment','skipped','why am i not qualified'],
a:()=>`<strong>Spillover</strong> happens when someone's sponsor already has both matrix slots full — the smart contract then places the new member in the next open slot further down, which can be under YOU. Spillover fills your matrix and sets up future upgrade payments to your position, but it does <strong>not</strong> count toward your qualification: only people who join using <em>your</em> ID are your directs. That's why you can see 2 under you and still show 1/2. And important: upgrade payments only stop at positions that are qualified (2 directs) AND at the required level — otherwise the payment passes you by to the next eligible upline. Check your position on your <a href="/my">Member Dashboard</a> — spillover placements are tagged there.`},
{k:['how do i get paid','how do i earn','commission','commissions','how payments work','how does the money','payout','payouts','pay flow','when do i get paid','how do i make money','income','two ways','how you get paid'],
a:()=>`Two ways money reaches your position — the full diagram is at <a href="/how-pay-works">rmcircle.team/how-pay-works</a>. <strong>(1) Entry rewards:</strong> when a direct joins under your link you get their entry reward (about 326 POL at Premium) and you keep it — on every direct you bring. <strong>(2) Upgrade payments:</strong> each person below you pays you once, at the ONE level that matches how far below you they sit — someone 1 layer below pays you when they hit Ascensus, 2 layers below pays you at Fabrica, 3 at Culmen, and so on. To catch each, you must be at that level yourself and qualified, so stay one level ahead of your team. No income is guaranteed.`},
{k:['tier','standard','premium tier','standard tier','premium vs standard','which tier','half','smaller payment','less than expected','why is my payment'],
a:()=>`There are two tiers. <strong>Premium</strong> is what our whole team builds at (${pol()} POL entry) — full payments. <strong>Standard</strong> costs about half and pays/earns half at every level. So if a payment ever comes in smaller than expected, it usually came from a Standard-tier position below you. Your tier is <strong>set when you join and can't be changed later</strong> (upgrading advances your level, not your tier), so always join <strong>Premium</strong> and make sure the people you bring on do too. Full breakdown: <a href="/how-pay-works">how-pay-works</a>.`},
{k:['dashboard','my dashboard','my page','my position','my team','check my','see my','pipeline','my stats','alerts','notify me','email me','get notified','message','messages','contact my sponsor','contact my upline','contact my downline','reach my team'],
a:()=>`Your <strong>Member Dashboard</strong> is at <a href="/my">rmcircle.team/my</a> — enter your ID to see your position, your team (with a depth summary showing members per generation), your payments, your pipeline (money forming below you), any spillover under you, and a <strong>Coach Your Team</strong> panel that tells you exactly who in your leg needs a nudge and what to say. When you're qualified, you can also <strong>upgrade your level right from your dashboard</strong> — connect the wallet that owns your position and confirm; the exact cost is read live from the contract. You can also turn on <strong>email alerts</strong> there, and use <strong>Messages</strong> — wallet-verified messaging with your upline and your team (sign in once with your wallet; no email needed; only people on your matrix lines can message you). To share, use your personal invite page: <strong>rmcircle.team/join/&lt;your ID&gt;</strong>.`},
{k:['level','levels','upgrade','scintilla','ascensus','fabrica','culmen','apex','fastigium','vertex','corona','8 levels'],
a:()=>`There are 8 Premium levels: <strong>Scintilla, Ascensus, Fabrica, Culmen, Apex, Fastigium, Vertex, Corona</strong>. Everyone starts at Scintilla. Upgrade as quickly as practical — ideally using earned POL — because the first two payments at each level are designed to help fund your next upgrade. Stay aware of your active downline's levels so you don't fall behind.`},
{k:['30 positions','goal','milestone','matrix','how many people','team size'],
a:()=>`The first major team goal is <strong>30 properly placed positions</strong>: 2 → 4 → 8 → 16 across the first four generations. Then we keep going — 32, 64, 128 and beyond.`},
{k:['moving link','why not my link','own link','my referral','use my link','extra legs'],
a:()=>`We use a <strong>moving-link strategy</strong>: the team focuses on one position's link until it qualifies with 2 directs, then that link is retired and the effort moves down to the next position. That's why you should always use the sponsor shown on the <a href="/start">Getting Started page</a> — not an old saved link. (If a late signup lands on a qualified link anyway, it's a harmless bonus — it pays that member and spills downward as depth — but spillover alone never qualifies anyone, so the focus stays on the next position.)`},
{k:['risk','safe','scam','lose money','guarantee','guaranteed','income','earnings','legit'],
a:()=>`Straight answer: participation involves cryptocurrency and smart-contract risk, and <strong>no income is guaranteed</strong>. Results depend on team effort, duplication, upgrades, smart-contract rules, and POL's market value. Only use funds you can afford to lose.`},
{k:['video','videos','training','watch','tutorial','learn','how to'],
a:()=>`All the training videos are on the <a href="/training">Training page</a>: (1) How the team build works, (2) Create your MetaMask wallet, (3) Funding your wallet, (4) Joining right on the site with wallet connect, (5) the dApp backup method, (6) how payments work, and (7) the full <strong>Member Dashboard walkthrough</strong> — pipeline, upgrading on-page, Messages, coaching, and your promo tools. Watch them in order.`},
{k:['seed phrase','secret recovery','recovery phrase','private key','12 words','passphrase'],
a:()=>`<strong>Never share your Secret Recovery Phrase or private keys with anyone</strong> — not this site, not a sponsor, not "support". Anyone asking for it is trying to steal your funds. MetaMask will never ask for it either, except when you restore a wallet yourself.`},
{k:['promote','promo','promo tools','tools','swipe','swipes','email swipe','banners','banner','graphics','marketing','share this','invite people','video clips','how do i share','social post','facebook post','twitter','my voice','branded voice'],
a:()=>`Grab share-ready promo tools at <a href="/tools">rmcircle.team/tools</a> — best way in is the gold <strong>Promo Tools</strong> button on <a href="/my">your dashboard</a>: arriving from there, every post and swipe is <strong>automatically personalized with YOUR invite link</strong>, so you copy and share as-is. You get promo <strong>videos</strong> (tap Copy link to share), copy-paste <strong>social posts</strong> for X &amp; Facebook, <strong>email &amp; message swipes</strong> (short and long), a downloadable <strong>banner kit</strong> in every standard size, a library of <strong>official RM Circle videos and graphics</strong> from the creators (vertical clips ready for Reels/TikTok/Shorts), and a builder for your <strong>personal invite link</strong>. Want it all in your own words? Learn to train an AI on your writing at <a href="https://mybrandedvoice.com" target="_blank" rel="noopener">mybrandedvoice.com</a>. Keep it honest — point people to the videos and the <a href="/contract">contract review</a>, never promise income.`},
{k:['telegram','group','chat','human','support','contact','talk','someone','admin','help me'],
a:()=>`For live help from the team, join the Telegram group: ${tgLink()}. Tell them where you're stuck and someone will walk you through it.`},
{k:['after join','next','what happens','confirmed','joined','i bought','i am in'],
a:()=>`Once your position is confirmed: tell the team your new RM Circle ID and your sponsor ID (in the Telegram group: ${tgLink('here')}) so your placement gets mapped. Then your job is simple — get your 2 directs, and when you're qualified, help your 2 get their 2.`},
{k:['waiting','queue','line','how long','when my turn'],
a:()=>{const w=sponsorInfo&&typeof sponsorInfo.waitingCount==='number'?sponsorInfo.waitingCount:null;return `${w!==null?`Right now there ${w===1?'is':'are'} <strong>${w}</strong> team placement${w===1?'':'s'} waiting behind the current sponsor. `:''}The queue moves every time a position qualifies with its 2 directs — the more the team helps each other, the faster it rotates.`}},
];
function answer(q){
const t=q.toLowerCase().replace(/[^a-z0-9 ]/g,' ');
let best=null,bestScore=0;
for(const e of KB){
let score=0;
for(const k of e.k){if(t.includes(k))score+=k.includes(' ')?2:1}
if(score>bestScore){bestScore=score;best=e}
}
if(best&&bestScore>0)return best.a();
return `I don't have a good answer for that one. The team can help you directly — ${tgLink('join our Telegram group ↗')} and ask there. You can also check the <a href="/training">training videos</a> or the <a href="/">strategy overview</a>.`;
}
const CHIPS=['How does it work?','What does it cost?','Who is the current sponsor?','How do I set up a wallet?','Is there risk?'];
const fab=document.createElement('button');
fab.className='chat-fab';fab.setAttribute('aria-label','Open team help chat');fab.innerHTML='💬';
const panel=document.createElement('div');
panel.className='chat-panel chat-hidden';
panel.innerHTML=`<div class="chat-head"><div><strong>Team Help</strong><div class="chat-sub">Ask about the RM Circle team build</div></div><button class="chat-close" aria-label="Close chat">×</button></div><div class="chat-msgs"></div><div class="chat-chips"></div><form class="chat-input"><input type="text" placeholder="Type a question…" aria-label="Your question" maxlength="300"><button type="submit" class="btn btn-primary btn-sm">Send</button></form><div class="chat-foot">Can't find it? ${tgLink('Get live help on Telegram ↗')}</div>`;
document.body.appendChild(fab);document.body.appendChild(panel);
const msgs=panel.querySelector('.chat-msgs'),chipsEl=panel.querySelector('.chat-chips'),form=panel.querySelector('.chat-input'),input=form.querySelector('input');
function addMsg(html,who){const d=document.createElement('div');d.className=`chat-msg ${who}`;if(who==='user'){d.textContent=html}else{d.innerHTML=html}msgs.appendChild(d);msgs.scrollTop=msgs.scrollHeight;return d}
function linkify(text){let h=esc(text);h=h.replace(/(https?:\/\/[^\s&<]+[^\s&<.,)])/g,u=>{const site=u.startsWith('https://rmcircle.team');const path=site?u.replace('https://rmcircle.team',''):u;return `<a href="${site?(path||'/'):u}"${site?'':' target="_blank" rel="noopener noreferrer"'}>${u}</a>`});return h.replace(/\n/g,'<br>')}
const history=[];let aiDown=false;
function stripHtml(h){const d=document.createElement('div');d.innerHTML=h;return d.textContent||''}
async function ask(q){
addMsg(q,'user');history.push({role:'user',content:q});
if(aiDown){const a=answer(q);addMsg(a,'bot');history.push({role:'assistant',content:stripHtml(a)});return}
const typing=addMsg('<span class="chat-typing">…</span>','bot');
try{
const r=await fetch('/api/public/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({messages:history.slice(-8)})});
const d=await r.json();
typing.remove();
if(d.reply){addMsg(linkify(d.reply),'bot');history.push({role:'assistant',content:d.reply})}
else{if(d.fallback)aiDown=true;const a=answer(q);addMsg(a,'bot');history.push({role:'assistant',content:stripHtml(a)})}
}catch(e){typing.remove();aiDown=true;const a=answer(q);addMsg(a,'bot');history.push({role:'assistant',content:stripHtml(a)})}
}
let started=false;
function open(){
panel.classList.remove('chat-hidden');fab.classList.add('chat-hidden');input.focus();
if(!started){started=true;loadData().then(()=>{
panel.querySelector('.chat-foot').innerHTML=`Can't find it? ${tgLink('Get live help on Telegram ↗')}`;
addMsg(`Hi! I can answer questions about the RM Circle team build — the strategy, wallet setup, funding, joining, levels, and more. What do you want to know?`,'bot');
for(const c of CHIPS){const b=document.createElement('button');b.type='button';b.className='chat-chip';b.textContent=c;b.addEventListener('click',()=>{chipsEl.classList.add('chat-hidden');ask(c)});chipsEl.appendChild(b)}
})}
}
function close(){panel.classList.add('chat-hidden');fab.classList.remove('chat-hidden')}
fab.addEventListener('click',open);
panel.querySelector('.chat-close').addEventListener('click',close);
form.addEventListener('submit',e=>{e.preventDefault();const q=input.value.trim();if(!q)return;input.value='';chipsEl.classList.add('chat-hidden');ask(q)});
})();