const{useState,useEffect,useRef}=React;
const M_DATA=[["m01","Mexico","South Africa","A","Jun 11","22:00",1.49,4.10,6.45],["m02","Rep. of Korea","Czech Republic","B","Jun 12","05:00",2.65,3.10,2.75],["m03","Canada","Bosnia & Herz.","C","Jun 12","22:00",1.74,3.85,4.30],["m04","USA","Paraguay","D","Jun 12","23:00",1.97,3.55,3.66],["m05","Qatar","Switzerland","E","Jun 13","22:00",8.75,5.80,1.28],["m06","Brazil","Morocco","F","Jun 14","01:00",1.59,3.80,5.60],["m07","Haiti","Scotland","F","Jun 14","01:00",6.35,4.88,1.41],["m08","Australia","Turkey","G","Jun 14","07:00",4.40,3.70,1.76],["m09","Germany","Curacao","H","Jun 14","20:00",1.02,12.0,28.0],["m10","Netherlands","Japan","E","Jun 14","23:00",1.97,3.60,3.40],["m11","Ivory Coast","Ecuador","H","Jun 15","02:00",3.45,2.75,2.35],["m12","Sweden","Tunisia","G","Jun 15","05:00",1.89,3.35,4.00],["m13","Spain","Cape Verde","A","Jun 15","19:00",1.12,8.00,17.0],["m14","Belgium","Egypt","C","Jun 15","22:00",1.65,3.80,4.75],["m15","Iran","New Zealand","D","Jun 16","04:00",1.82,3.50,4.05],["m16","Saudi Arabia","Uruguay","B","Jun 16","01:00",5.85,4.15,1.49],["m17","France","Senegal","A","Jun 16","22:00",1.41,4.35,6.80],["m18","Argentina","Algeria","F","Jun 17","01:00",1.38,4.28,8.00],["m19","Iraq","Norway","D","Jun 17","01:00",8.65,6.00,1.25],["m20","Austria","Jordan","C","Jun 17","07:00",1.32,5.05,7.75],["m21","Portugal","DR Congo","E","Jun 17","20:00",1.25,5.55,9.35],["m22","England","Croatia","G","Jun 17","23:00",1.64,3.80,4.80],["m23","Uzbekistan","Colombia","H","Jun 18","01:00",7.49,4.40,1.39],["m24","Ghana","Panama","G","Jun 18","02:00",1.85,3.85,3.60],["m25","Czech Republic","South Africa","B","Jun 18","19:00",1.95,3.20,3.95],["m26","Switzerland","Bosnia & Herz.","E","Jun 18","22:00",1.52,4.05,5.60],["m27","Canada","Qatar","C","Jun 19","01:00",1.47,4.20,6.15],["m28","Mexico","Rep. of Korea","A","Jun 19","04:00",1.73,3.55,4.50],["m29","USA","Australia","D","Jun 19","07:00",1.68,3.95,4.30],["m30","Scotland","Morocco","F","Jun 20","01:00",3.60,3.10,2.08],["m31","Brazil","Haiti","F","Jun 20","03:30",1.08,10.0,25.0],["m32","Turkey","Paraguay","G","Jun 20","06:00",2.20,3.05,3.35],["m33","Netherlands","Sweden","E","Jun 20","20:00",1.60,3.95,4.85],["m34","Germany","Ivory Coast","H","Jun 20","23:00",1.54,4.15,5.25],["m35","Ecuador","Curacao","H","Jun 21","03:00",1.22,5.70,11.0],["m36","Tunisia","Japan","G","Jun 21","07:00",4.65,3.25,1.80],["m37","Spain","Saudi Arabia","A","Jun 21","19:00",1.10,8.50,19.0],["m38","Belgium","Iran","C","Jun 21","22:00",1.38,4.45,7.35],["m39","Uruguay","Cape Verde","B","Jun 22","01:00",1.39,4.40,7.20],["m40","New Zealand","Egypt","D","Jun 22","04:00",4.40,3.75,1.71],["m41","Argentina","Austria","F","Jun 22","20:00",1.67,3.55,5.00],["m42","France","Iraq","A","Jun 23","00:00",1.11,7.60,19.0],["m43","Norway","Senegal","D","Jun 23","03:00",1.96,3.55,3.50],["m44","Jordan","Algeria","C","Jun 23","06:00",4.70,3.65,1.69],["m45","Portugal","Uzbekistan","E","Jun 23","20:00",1.19,6.20,11.0],["m46","England","Ghana","G","Jun 23","23:00",1.30,5.15,8.20],["m47","Panama","Croatia","H","Jun 24","02:00",6.45,3.65,1.53],["m48","Colombia","DR Congo","H","Jun 24","05:00",1.44,4.10,6.85]].map(d=>({id:d[0],home:d[1],away:d[2],group:d[3],date:d[4],time:d[5],hO:d[6],dO:d[7],aO:d[8],st:"upcoming"}));
const FL={"Mexico":"\u{1F1F2}\u{1F1FD}","South Africa":"\u{1F1FF}\u{1F1E6}","Rep. of Korea":"\u{1F1F0}\u{1F1F7}","Czech Republic":"\u{1F1E8}\u{1F1FF}","Canada":"\u{1F1E8}\u{1F1E6}","Bosnia & Herz.":"\u{1F1E7}\u{1F1E6}","USA":"\u{1F1FA}\u{1F1F8}","Paraguay":"\u{1F1F5}\u{1F1FE}","Qatar":"\u{1F1F6}\u{1F1E6}","Switzerland":"\u{1F1E8}\u{1F1ED}","Brazil":"\u{1F1E7}\u{1F1F7}","Morocco":"\u{1F1F2}\u{1F1E6}","Haiti":"\u{1F1ED}\u{1F1F9}","Scotland":"\u{1F3F4}\u{E0067}\u{E0062}\u{E0073}\u{E0063}\u{E0074}\u{E007F}","Australia":"\u{1F1E6}\u{1F1FA}","Turkey":"\u{1F1F9}\u{1F1F7}","Germany":"\u{1F1E9}\u{1F1EA}","Curacao":"\u{1F1E8}\u{1F1FC}","Netherlands":"\u{1F1F3}\u{1F1F1}","Japan":"\u{1F1EF}\u{1F1F5}","Ivory Coast":"\u{1F1E8}\u{1F1EE}","Ecuador":"\u{1F1EA}\u{1F1E8}","Sweden":"\u{1F1F8}\u{1F1EA}","Tunisia":"\u{1F1F9}\u{1F1F3}","Spain":"\u{1F1EA}\u{1F1F8}","Cape Verde":"\u{1F1E8}\u{1F1FB}","Belgium":"\u{1F1E7}\u{1F1EA}","Egypt":"\u{1F1EA}\u{1F1EC}","Iran":"\u{1F1EE}\u{1F1F7}","New Zealand":"\u{1F1F3}\u{1F1FF}","Saudi Arabia":"\u{1F1F8}\u{1F1E6}","Uruguay":"\u{1F1FA}\u{1F1FE}","France":"\u{1F1EB}\u{1F1F7}","Senegal":"\u{1F1F8}\u{1F1F3}","Argentina":"\u{1F1E6}\u{1F1F7}","Algeria":"\u{1F1E9}\u{1F1FF}","Iraq":"\u{1F1EE}\u{1F1F6}","Norway":"\u{1F1F3}\u{1F1F4}","Austria":"\u{1F1E6}\u{1F1F9}","Jordan":"\u{1F1EF}\u{1F1F4}","Portugal":"\u{1F1F5}\u{1F1F9}","DR Congo":"\u{1F1E8}\u{1F1E9}","England":"\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}","Uzbekistan":"\u{1F1FA}\u{1F1FF}","Colombia":"\u{1F1E8}\u{1F1F4}","Ghana":"\u{1F1EC}\u{1F1ED}","Panama":"\u{1F1F5}\u{1F1E6}","Croatia":"\u{1F1ED}\u{1F1F7}"};
const rr=v=>+Math.max(1.05,v).toFixed(2);
const mkMarkets=m=>{const h=m.hO<m.aO?0.85:m.hO>m.aO?1.15:1;return[{cat:"Full Time Result",id:"1x2",opts:[{label:m.home,odds:m.hO,key:"1"},{label:"Draw",odds:m.dO,key:"X"},{label:m.away,odds:m.aO,key:"2"}]},{cat:"Double Chance",id:"dc",opts:[{label:m.home+" or Draw",odds:rr(1/(1/m.hO+1/m.dO)*1.05),key:"1X"},{label:m.home+" or "+m.away,odds:rr(1/(1/m.hO+1/m.aO)*1.05),key:"12"},{label:m.away+" or Draw",odds:rr(1/(1/m.aO+1/m.dO)*1.05),key:"X2"}]},{cat:"Over/Under 2.5",id:"ou25",opts:[{label:"Over 2.5",odds:rr(1.85*h),key:"o25"},{label:"Under 2.5",odds:rr(1.95/h),key:"u25"}]},{cat:"Over/Under 1.5",id:"ou15",opts:[{label:"Over 1.5",odds:rr(1.3*h),key:"o15"},{label:"Under 1.5",odds:rr(3.2/h),key:"u15"}]},{cat:"Both Teams Score",id:"btts",opts:[{label:"Yes",odds:rr(1.72+(m.dO-3)*.05),key:"btY"},{label:"No",odds:rr(2.05-(m.dO-3)*.05),key:"btN"}]},{cat:"First to Score",id:"fts",opts:[{label:m.home,odds:rr(m.hO*.6+.3),key:"fH"},{label:m.away,odds:rr(m.aO*.6+.3),key:"fA"},{label:"No Goal",odds:rr(9),key:"fN"}]},{cat:"Half-Time",id:"ht",opts:[{label:m.home,odds:rr(m.hO*1.6),key:"ht1"},{label:"Draw",odds:rr(m.dO*.65),key:"htX"},{label:m.away,odds:rr(m.aO*1.6),key:"ht2"}]},{cat:"Correct Score",id:"cs",opts:[{label:"1-0",odds:rr(5.5*h),key:"cs10"},{label:"0-0",odds:rr(7+m.dO*.3),key:"cs00"},{label:"0-1",odds:rr(5.5/h),key:"cs01"},{label:"2-1",odds:rr(8*h),key:"cs21"},{label:"1-1",odds:rr(5.5+m.dO*.2),key:"cs11"},{label:"1-2",odds:rr(8/h),key:"cs12"},{label:"2-0",odds:rr(9*h),key:"cs20"},{label:"0-2",odds:rr(9/h),key:"cs02"},{label:"2-2",odds:rr(14),key:"cs22"},{label:"3-0",odds:rr(18*h),key:"cs30"},{label:"3-1",odds:rr(16*h),key:"cs31"},{label:"0-3",odds:rr(18/h),key:"cs03"},{label:"Other",odds:rr(12),key:"csOt"}]},{cat:"Handicap",id:"ah",opts:[{label:m.home+" -0.5",odds:rr(m.hO*.62+.5),key:"ah1"},{label:m.away+" +0.5",odds:rr(m.aO*.45+.6),key:"ah2"}]},{cat:m.home+" Goals",id:"htg",opts:[{label:"Over 1.5",odds:rr(1.85+(m.hO-2)*.15),key:"htO"},{label:"Under 1.5",odds:rr(1.9-(m.hO-2)*.1),key:"htU"}]},{cat:m.away+" Goals",id:"atg",opts:[{label:"Over 1.5",odds:rr(1.85+(m.aO-2)*.15),key:"atO"},{label:"Under 1.5",odds:rr(1.9-(m.aO-2)*.1),key:"atU"}]}]};
const STYLE=`@import url('https://fonts.googleapis.com/css2?family=Sora:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600;700&display=swap');*{box-sizing:border-box;margin:0;padding:0;-webkit-font-smoothing:antialiased}:root{--b1:#0a0e1a;--b2:#0e1326;--c1:#141c30;--c2:#182440;--cb:rgba(255,255,255,.06);--t:#2dd4a0;--td:rgba(45,212,160,.1);--tg:rgba(45,212,160,.15);--r:#ff5c5c;--rd:rgba(255,92,92,.1);--a:#e8b830;--ad:rgba(232,184,48,.08);--bl:#5b9cf6;--bld:rgba(91,156,246,.08);--w:#edf2f7;--w2:#8696b0;--w3:#4a5a76;--w4:#2d3a52}html,body{font-family:'Sora',sans-serif;background:var(--b1);color:var(--w);overflow-x:hidden}.jm{font-family:'JetBrains Mono',monospace}@keyframes up{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}@keyframes cfall{0%{transform:translateY(-100vh) rotate(0);opacity:1}100%{transform:translateY(100vh) rotate(720deg);opacity:0}}@keyframes slideR{from{opacity:0;transform:translateX(16px)}to{opacity:1;transform:translateX(0)}}@keyframes slideUp{from{opacity:0;transform:translateY(100%)}to{opacity:1;transform:translateY(0)}}.au{animation:up .3s ease-out both}.d1{animation-delay:.02s}.d2{animation-delay:.04s}.d3{animation-delay:.06s}.d4{animation-delay:.08s}.d5{animation-delay:.1s}.d6{animation-delay:.12s}.log-wrap{min-height:100vh;display:flex;align-items:center;justify-content:center;background:var(--b1);position:relative}.log-wrap::after{content:'';position:absolute;inset:0;background-image:linear-gradient(rgba(45,212,160,.012) 1px,transparent 1px),linear-gradient(90deg,rgba(45,212,160,.012) 1px,transparent 1px);background-size:40px 40px;pointer-events:none}.log-card{width:380px;max-width:92vw;background:var(--c1);border:1px solid var(--cb);border-radius:16px;padding:36px 28px;position:relative;z-index:2;box-shadow:0 24px 64px rgba(0,0,0,.4)}.inp{width:100%;padding:11px 14px;background:rgba(10,14,26,.7);border:1px solid var(--cb);border-radius:8px;color:var(--w);font-family:'Sora',sans-serif;font-size:13px;font-weight:500;outline:none;transition:.15s}.inp:focus{border-color:var(--t);box-shadow:0 0 0 2px var(--td)}.inp::placeholder{color:var(--w3)}.bt{width:100%;padding:12px;background:linear-gradient(135deg,#1a9e78,var(--t));border:none;border-radius:8px;color:#fff;font-family:'Sora',sans-serif;font-weight:700;font-size:13px;cursor:pointer;transition:.15s}.bt:hover{filter:brightness(1.1);box-shadow:0 6px 20px var(--tg)}.bt:active{transform:scale(.99)}.bt-ghost{background:transparent;border:1px solid var(--cb);color:var(--w2)}.bt-ghost:hover{border-color:var(--t);color:var(--t);background:var(--td);box-shadow:none;filter:none}.side{width:220px;height:100vh;background:var(--b2);border-right:1px solid var(--cb);padding:16px 8px;display:flex;flex-direction:column;position:fixed;left:0;top:0;z-index:50}.nl{display:flex;align-items:center;gap:8px;padding:9px 12px;border-radius:8px;color:var(--w2);font-weight:600;font-size:12px;cursor:pointer;transition:.12s;border:1px solid transparent}.nl:hover{background:rgba(255,255,255,.02);color:var(--w)}.nl.on{background:var(--td);color:var(--t);border-color:rgba(45,212,160,.08)}.mn{margin-left:220px;min-height:100vh;padding:24px 32px;max-width:1100px}.cd{background:var(--c1);border:1px solid var(--cb);border-radius:12px;padding:16px;position:relative}.m-opt{display:flex;justify-content:space-between;align-items:center;padding:9px 12px;border-radius:8px;border:1px solid var(--cb);background:rgba(10,14,26,.4);cursor:pointer;transition:.15s}.m-opt:hover{border-color:rgba(45,212,160,.2);background:rgba(45,212,160,.03)}.m-opt.pk{border-color:var(--t);background:var(--td);box-shadow:0 0 10px var(--td)}.lbe{display:flex;align-items:center;padding:12px 16px;border-radius:8px;border:1px solid transparent}.lbe.r1{background:linear-gradient(135deg,rgba(45,212,160,.05),transparent);border-color:rgba(45,212,160,.06)}.lbe.r2{background:linear-gradient(135deg,rgba(91,156,246,.04),transparent);border-color:rgba(91,156,246,.05)}.lbe.r3{background:linear-gradient(135deg,rgba(232,184,48,.04),transparent);border-color:rgba(232,184,48,.05)}.chtw{display:flex;flex-direction:column;height:calc(100vh - 140px)}.chts{flex:1;overflow-y:auto;padding:12px 0;display:flex;flex-direction:column;gap:10px}.bbl{max-width:78%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.6;animation:up .2s ease-out}.bbl.u{background:var(--td);border:1px solid rgba(45,212,160,.1);align-self:flex-end;border-bottom-right-radius:2px}.bbl.a{background:var(--c2);border:1px solid var(--cb);align-self:flex-start;border-bottom-left-radius:2px}.tst{position:fixed;top:16px;right:16px;z-index:300;padding:10px 18px;border-radius:8px;font-weight:700;font-size:12px;animation:up .2s ease-out;box-shadow:0 6px 20px rgba(0,0,0,.3)}.cnf{position:fixed;z-index:200;animation:cfall 3s linear forwards}.ldot{width:5px;height:5px;border-radius:50%;background:var(--r);animation:pulse 1.5s infinite;display:inline-block}.tag{display:inline-flex;align-items:center;gap:3px;padding:2px 8px;border-radius:4px;font-size:10px;font-weight:700;letter-spacing:.5px}.back-btn{display:inline-flex;align-items:center;gap:5px;padding:7px 12px;border-radius:6px;border:1px solid var(--cb);background:transparent;color:var(--w2);cursor:pointer;font-family:'Sora',sans-serif;font-size:11px;font-weight:600;transition:.15s;margin-bottom:14px}.back-btn:hover{border-color:var(--t);color:var(--t);background:var(--td)}.mrow{padding:11px 16px;border-bottom:1px solid rgba(255,255,255,.025);cursor:pointer;transition:.12s;display:flex;align-items:center;justify-content:space-between;gap:8px}.mrow:hover{background:rgba(45,212,160,.02)}.mrow:last-child{border-bottom:none}@media(max-width:768px){.side{display:none}.mn{margin-left:0;padding:16px 12px;padding-bottom:70px;max-width:100%}.mbn{position:fixed;bottom:0;left:0;right:0;background:var(--b2);border-top:1px solid var(--cb);display:flex!important;z-index:50;padding:6px 4px;padding-bottom:max(6px,env(safe-area-inset-bottom))}.mbi{flex:1;text-align:center;padding:6px 2px;font-size:9px;color:var(--w3);cursor:pointer;border-radius:6px;font-weight:600}.mbi.on{color:var(--t);background:var(--td)}.mrow{flex-wrap:wrap;padding:10px 12px!important;gap:4px!important}.mob-odds{display:flex;gap:6px;width:100%;margin-top:4px}.mob-odds>div{flex:1}.desk-odds{display:none!important}.desk-more{display:none!important}.cd{padding:12px}.lbe{padding:10px 12px;flex-wrap:wrap;gap:4px}.lb-header{display:none!important}.lb-mobile-stats{display:flex!important}.chtw{height:calc(100vh - 180px)}}@media(min-width:769px){.mob-odds{display:none!important}.lb-mobile-stats{display:none!important}}`;
function WC(){
  const[user,su]=useState(null);const[isA,sA]=useState(false);const[vw,sV]=useState("dash");
  const[D,sD]=useState({users:[],bets:[],matches:M_DATA});const[ok,sOk]=useState(false);
  const[le,sLe]=useState("");const[lp,sLp]=useState("");const[lerr,sLerr]=useState("");
  const[selM,sSelM]=useState(null);const[pick,sPick]=useState(null);const[ba,sBa]=useState("");
  const[conf,sConf]=useState(false);const[flt,sFlt]=useState("all");const[bFlt,sBFlt]=useState("all");
  const[msgs,sM]=useState([{r:"a",t:"Welcome! Ask me about any match or strategy."}]);
  const[ci,sCi]=useState("");const[cB,sCB]=useState(false);
  const[nu,sNu]=useState({username:"",password:"",displayName:"",budget:100});
  const[tst,sTst]=useState(null);const[token,setToken]=useState(null);const er=useRef(null);

  const flash=(m,t)=>{sTst({m,t:t||"ok"});setTimeout(()=>sTst(null),2500)};
  const boom=()=>{sConf(true);setTimeout(()=>sConf(false),2500)};
  const cu=isA?null:D.users.find(u=>u.id===(user&&user.id));
  const myB=()=>D.bets.filter(b=>b.userId===(user&&user.id)).sort((a,b)=>new Date(b.ts)-new Date(a.ts));
  const groups=["A","B","C","D","E","F","G","H"];
  const filteredM=flt==="all"?D.matches:D.matches.filter(m=>m.group===flt);

  const apiCall=async(method,path,body)=>{
    const opts={method,headers:{"Content-Type":"application/json"}};
    if(token)opts.headers["Authorization"]="Bearer "+token;
    if(body)opts.body=JSON.stringify(body);
    const res=await fetch("/api"+path,opts);const data=await res.json();
    if(!res.ok)throw new Error(data.error||"Failed");return data;
  };
  const loadData=async(tok)=>{
    try{const opts={headers:{"Content-Type":"application/json","Authorization":"Bearer "+tok}};
    const res=await fetch("/api/data",opts);if(!res.ok)return;
    const d=await res.json();sD({users:d.users,bets:d.bets,matches:M_DATA});if(t)loadMatches(t)}catch(e){}
  };
  const reload=async()=>{if(token)await loadData(token)};
  const loadMatches=async(tok)=>{
    try{
      const res=await fetch("/api/matches",{headers:{"Authorization":"Bearer "+tok}});
      if(!res.ok)return;
      const d=await res.json();
      if(d.matches&&d.matches.length>0){
        const real=d.matches.filter(m=>m.hO>0).map(m=>({...m,st:m.st||"upcoming"}));
        if(real.length>0)sD(prev=>({...prev,matches:real}));
        console.log("Loaded "+real.length+" live matches from Cloudbet");
      }
    }catch(e){console.log("Cloudbet fetch failed, using cached matches")}
  };

  useEffect(()=>{(async()=>{
    const t=localStorage.getItem("wc_token");
    if(t){try{const opts={headers:{"Content-Type":"application/json","Authorization":"Bearer "+t}};
      const res=await fetch("/api/data",opts);
      if(res.ok){const d=await res.json();setToken(t);
        const hasP=d.users.length>0&&d.users[0].password;
        if(hasP){su({id:"admin",displayName:"Adam",isAdmin:true});sA(true)}
        else{const uid=localStorage.getItem("wc_userId");const u=d.users.find(x=>x.id===uid);
          if(u){su(u);sA(false)}else{localStorage.removeItem("wc_token");localStorage.removeItem("wc_userId")}}
        sD({users:d.users,bets:d.bets,matches:M_DATA})
      }else{localStorage.removeItem("wc_token")}}catch(e){localStorage.removeItem("wc_token")}}
    sOk(true)})()},[]);
  useEffect(()=>{if(er.current)er.current.scrollIntoView({behavior:"smooth"})},[msgs]);

  const login=async()=>{sLerr("");try{
    const res=await fetch("/api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:le.trim(),password:lp.trim()})});
    const data=await res.json();if(!res.ok){sLerr(data.error||"Invalid credentials");return}
    setToken(data.token);localStorage.setItem("wc_token",data.token);localStorage.setItem("wc_userId",data.user.id);
    su(data.user);sA(data.user.isAdmin);await loadData(data.token);loadMatches(data.token)}catch(e){sLerr("Connection error")}};
  const addU=async()=>{if(!nu.username||!nu.password||!nu.displayName)return flash("Fill all fields","err");
    try{await apiCall("POST","/users",nu);sNu({username:"",password:"",displayName:"",budget:100});flash(nu.displayName+" added!");await reload()}catch(e){flash(e.message,"err")}};
  const delU=async id=>{try{await apiCall("DELETE","/users/"+id);flash("Removed");await reload()}catch(e){flash(e.message,"err")}};
  const rstU=async id=>{try{await apiCall("POST","/users/"+id+"/reset");flash("Reset");await reload()}catch(e){flash(e.message,"err")}};
  const doBet=async()=>{if(!selM||!pick||!ba)return;const amt=parseFloat(ba);
    if(!amt||amt<=0||amt>(cu?cu.balance:0))return flash("Check amount","err");
    try{await apiCall("POST","/bets",{matchId:selM.id,team:pick.label,market:pick.marketName,sel:pick.key,amount:amt,odds:pick.odds,label:selM.home+" vs "+selM.away});
    sPick(null);sBa("");boom();flash(pick.label+" @ "+pick.odds+"x");await reload()}catch(e){flash(e.message,"err")}};
  const doChat=async()=>{if(!ci.trim()||cB)return;const q=ci.trim();sCi("");sM(p=>[...p,{r:"u",t:q}]);sCB(true);
    try{const data=await apiCall("POST","/chat",{message:q});sM(p=>[...p,{r:"a",t:data.text||"Try again!"}])}catch(e){sM(p=>[...p,{r:"a",t:"AI unavailable: "+e.message}])}sCB(false)};
  const getLb=()=>D.users.map(u=>{const ub=D.bets.filter(b=>b.userId===u.id);const pend=ub.filter(b=>b.status==="pending").reduce((s,b)=>s+b.amount,0);const pv=+(u.balance+pend-u.budget).toFixed(2);
    return{...u,pend,active:ub.filter(b=>b.status==="pending").length,profitVal:pv,roi:u.budget>0?(pv/u.budget*100).toFixed(1):"0"}}).sort((a,b)=>b.profitVal-a.profitVal);
  const quickPick=(m,key,label,odds,e)=>{e.stopPropagation();if(isA)return;sSelM(m);sPick({marketId:"1x2",marketName:"Full Time Result",key,label,odds});sBa("")};

  const BetSlipFloat=()=>{if(!pick||!selM||isA)return null;const m=selM;const amt=parseFloat(ba)||0;const pot=amt>0?(amt*pick.odds).toFixed(2):"0.00";const profit=amt>0?((amt*pick.odds)-amt).toFixed(2):"0.00";
    return React.createElement(React.Fragment,null,
      React.createElement("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",zIndex:80,backdropFilter:"blur(3px)"},onClick:()=>{sPick(null);sBa("")}}),
      React.createElement("div",{style:{position:"fixed",bottom:0,left:0,right:0,zIndex:90,animation:"slideUp .3s ease-out"}},
        React.createElement("div",{style:{background:"var(--c1)",borderTop:"2px solid var(--t)",borderRadius:"16px 16px 0 0",padding:"20px 16px",paddingBottom:"max(20px,env(safe-area-inset-bottom))",maxHeight:"80vh",overflowY:"auto"}},
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
            <p style={{fontSize:12,fontWeight:700,color:"var(--t)",textTransform:"uppercase",letterSpacing:1}}>Bet Slip</p>
            <button onClick={()=>{sPick(null);sBa("")}} style={{background:"none",border:"none",color:"var(--w3)",cursor:"pointer",fontSize:18,padding:4}}>{"\u2715"}</button>
          </div>,
          <div style={{background:"var(--td)",borderRadius:10,padding:14,marginBottom:16,border:"1px solid rgba(45,212,160,.08)"}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8}}>
              <div><p style={{fontSize:10,color:"var(--w3)",fontWeight:600}}>{pick.marketName}</p><p style={{fontSize:16,fontWeight:800,color:"var(--t)",marginTop:2}}>{pick.label}</p></div>
              <div style={{background:"rgba(45,212,160,.15)",borderRadius:8,padding:"6px 12px",textAlign:"center"}}><p style={{fontSize:8,color:"var(--w3)",fontWeight:600}}>ODDS</p><p className="jm" style={{fontSize:18,fontWeight:700,color:"var(--t)"}}>{pick.odds.toFixed(2)}</p></div>
            </div>
            <p style={{fontSize:11,color:"var(--w2)"}}>{(FL[m.home]||"")+" "+m.home+" vs "+m.away+" "+(FL[m.away]||"")}</p>
            <p style={{fontSize:9,color:"var(--w4)",marginTop:2}}>{"Grp "+m.group+" \u2022 "+m.date+" "+m.time}</p>
          </div>,
          <div style={{marginBottom:14}}>
            <div style={{display:"flex",justifyContent:"space-between",marginBottom:6}}><p style={{fontSize:10,color:"var(--w3)",fontWeight:600}}>Stake (USDT)</p><p style={{fontSize:10,color:"var(--w3)",fontWeight:600}}>{"Balance: "}<span className="jm" style={{color:"var(--t)"}}>{"$"+(cu?cu.balance:0)}</span></p></div>
            <input className="inp jm" type="number" placeholder="0.00" value={ba} onChange={e=>sBa(e.target.value)} style={{fontSize:22,textAlign:"center",fontWeight:700,padding:"14px 16px"}}/>
            <div style={{display:"flex",gap:5,marginTop:8}}>{[5,10,25,50,100].map(a=><button key={a} onClick={()=>sBa(String(Math.min(a,cu?cu.balance:0)))} style={{flex:1,padding:"8px 0",borderRadius:7,border:"1px solid "+(parseFloat(ba)===a?"var(--t)":"var(--cb)"),background:parseFloat(ba)===a?"var(--td)":"rgba(255,255,255,.02)",color:parseFloat(ba)===a?"var(--t)":"var(--w2)",cursor:"pointer",fontFamily:"'JetBrains Mono',monospace",fontWeight:700,fontSize:12}}>{"$"+a}</button>)}</div>
          </div>,
          amt>0&&<div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:14}}>
            <div style={{background:"rgba(45,212,160,.04)",borderRadius:8,padding:"10px 12px",textAlign:"center"}}><p style={{fontSize:9,color:"var(--w3)",fontWeight:600}}>POTENTIAL RETURN</p><p className="jm" style={{fontSize:20,fontWeight:700,color:"var(--t)",marginTop:2}}>{"$"+pot}</p></div>
            <div style={{background:"rgba(45,212,160,.04)",borderRadius:8,padding:"10px 12px",textAlign:"center"}}><p style={{fontSize:9,color:"var(--w3)",fontWeight:600}}>PROFIT</p><p className="jm" style={{fontSize:20,fontWeight:700,color:"var(--t)",marginTop:2}}>{"$"+profit}</p></div>
          </div>,
          <button className="bt" onClick={doBet} disabled={!amt||amt<=0||amt>(cu?cu.balance:0)} style={{padding:14,fontSize:14,opacity:(!amt||amt<=0)?0.5:1}}>{amt>0?"Place Bet \u2022 $"+ba+" to win $"+pot:"Enter amount to bet"}</button>,
          selM&&<button onClick={()=>{sPick(null);sBa("");sV("match")}} style={{width:"100%",marginTop:8,padding:10,background:"transparent",border:"1px solid var(--cb)",borderRadius:8,color:"var(--bl)",cursor:"pointer",fontFamily:"'Sora'",fontSize:11,fontWeight:600}}>{"View all "+mkMarkets(selM).length+" markets \u2192"}</button>
        )))};

  const MatchDetailView=()=>{const m=selM;const markets=mkMarkets(m);const totalSel=markets.reduce((s,mk)=>s+mk.opts.length,0);
    return(<div><button className="back-btn" onClick={()=>{sSelM(null);sPick(null);sBa("")}}>{"\u2190 Back"}</button>
      <div className="cd au" style={{marginBottom:16,padding:24}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14}}><span className="tag" style={{background:"var(--bld)",color:"var(--bl)"}}>{m.date+" \u2022 "+m.time}</span><span style={{fontSize:10,color:"var(--w3)"}}>{"Group "+m.group}</span></div>
        <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}><div style={{display:"flex",alignItems:"center",gap:12,flex:1}}><span style={{fontSize:36}}>{FL[m.home]||""}</span><div><p style={{fontWeight:800,fontSize:16}}>{m.home}</p><p style={{fontSize:10,color:"var(--w3)"}}>Home</p></div></div><p style={{fontSize:14,fontWeight:800,color:"var(--w4)",padding:"0 16px"}}>VS</p><div style={{display:"flex",alignItems:"center",gap:12,flex:1,justifyContent:"flex-end"}}><div style={{textAlign:"right"}}><p style={{fontWeight:800,fontSize:16}}>{m.away}</p><p style={{fontSize:10,color:"var(--w3)"}}>Away</p></div><span style={{fontSize:36}}>{FL[m.away]||""}</span></div></div></div>
      <div style={{display:"grid",gridTemplateColumns:"1fr",gap:14,alignItems:"start"}}><div><p style={{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:1,color:"var(--w3)",marginBottom:12}}>{totalSel+" selections \u2022 "+markets.length+" markets"}</p>
        {markets.map((mk,mi)=>{const cols=mk.opts.length<=3?mk.opts.length:mk.opts.length<=4?2:3;return(<div key={mk.id} className={"au d"+Math.min(mi+1,6)} style={{marginBottom:12}}><p style={{fontSize:10,fontWeight:700,textTransform:"uppercase",letterSpacing:.8,color:"var(--w3)",marginBottom:6}}>{mk.cat}</p><div style={{display:"grid",gridTemplateColumns:"repeat("+cols+",1fr)",gap:5}}>{mk.opts.map(o=>(<div key={o.key} className={"m-opt"+(pick&&pick.key===o.key?" pk":"")} onClick={()=>{sSelM(m);sPick({marketId:mk.id,marketName:mk.cat,key:o.key,label:o.label,odds:o.odds});sBa("")}}><span style={{fontSize:12,fontWeight:600}}>{o.label}</span><span className="jm" style={{fontSize:12,fontWeight:700,color:"var(--t)"}}>{o.odds.toFixed(2)}</span></div>))}</div></div>)})}</div></div></div>)};

  const MatchListView=()=>(<div>
    <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4}}><h1 style={{fontSize:20,fontWeight:800}}>Match Center</h1>{!isA&&<span className="jm" style={{color:"var(--t)",fontSize:13,fontWeight:700}}>{"$"+(cu?cu.balance:0)}</span>}</div>
    <p style={{color:"var(--w3)",fontSize:11,marginBottom:16}}>{D.matches.length+" matches \u2022 Tap odds to bet"}</p>
    <div style={{display:"flex",gap:4,marginBottom:16,overflowX:"auto",WebkitOverflowScrolling:"touch",paddingBottom:4}}><button onClick={()=>sFlt("all")} style={{padding:"5px 12px",borderRadius:6,border:"1px solid "+(flt==="all"?"var(--t)":"var(--cb)"),background:flt==="all"?"var(--td)":"transparent",color:flt==="all"?"var(--t)":"var(--w3)",cursor:"pointer",fontFamily:"'Sora'",fontSize:10,fontWeight:700,whiteSpace:"nowrap",flexShrink:0}}>All</button>
      {groups.map(g=><button key={g} onClick={()=>sFlt(g)} style={{padding:"5px 10px",borderRadius:6,border:"1px solid "+(flt===g?"var(--t)":"var(--cb)"),background:flt===g?"var(--td)":"transparent",color:flt===g?"var(--t)":"var(--w3)",cursor:"pointer",fontFamily:"'Sora'",fontSize:10,fontWeight:700,whiteSpace:"nowrap",flexShrink:0}}>{g}</button>)}</div>
    <div className="cd" style={{padding:0,overflow:"hidden"}}>
      <div className="desk-odds" style={{display:"flex",padding:"8px 16px",borderBottom:"1px solid rgba(255,255,255,.04)",background:"rgba(255,255,255,.015)",gap:8}}><span style={{flex:1,fontSize:9,fontWeight:700,color:"var(--w4)"}}>MATCH</span><span style={{width:52,textAlign:"center",fontSize:9,fontWeight:700,color:"var(--w4)"}}>1</span><span style={{width:52,textAlign:"center",fontSize:9,fontWeight:700,color:"var(--w4)"}}>X</span><span style={{width:52,textAlign:"center",fontSize:9,fontWeight:700,color:"var(--w4)"}}>2</span><span style={{width:50,textAlign:"right",fontSize:9,fontWeight:700,color:"var(--w4)"}}>MORE</span></div>
      {filteredM.map(m=>(<div key={m.id} className="mrow">
        <div style={{flex:1,minWidth:0,cursor:"pointer"}} onClick={()=>{sSelM(m);sPick(null);sBa("")}}><div style={{display:"flex",alignItems:"center",gap:5,flexWrap:"wrap"}}><span style={{fontSize:16}}>{FL[m.home]||""}</span><span style={{fontWeight:700,fontSize:12}}>{m.home}</span><span style={{color:"var(--w4)",fontSize:10}}>vs</span><span style={{fontWeight:700,fontSize:12}}>{m.away}</span><span style={{fontSize:16}}>{FL[m.away]||""}</span></div><p style={{fontSize:9,color:"var(--w4)",marginTop:2}}>{"Grp "+m.group+" \u2022 "+m.date+" "+m.time}</p></div>
        {[[m.home,m.hO,"1"],["Draw",m.dO,"X"],[m.away,m.aO,"2"]].map(p=><div key={p[2]} className="desk-odds jm" onClick={e=>quickPick(m,p[2],p[0],p[1],e)} style={{width:52,textAlign:"center",fontSize:12,fontWeight:600,color:"#c8f06e",cursor:"pointer",padding:"4px 2px",borderRadius:4,border:"1px solid transparent"}} onMouseEnter={e=>{e.currentTarget.style.background="var(--td)";e.currentTarget.style.borderColor="var(--t)"}} onMouseLeave={e=>{e.currentTarget.style.background="transparent";e.currentTarget.style.borderColor="transparent"}}>{p[1]}</div>)}
        <div className="desk-more" style={{width:50,textAlign:"right",cursor:"pointer"}} onClick={()=>{sSelM(m);sPick(null);sBa("")}}><span style={{fontSize:10,color:"var(--t)",fontWeight:600}}>{mkMarkets(m).length+" \u2192"}</span></div>
        <div className="mob-odds" onClick={e=>e.stopPropagation()}>{[[m.home,m.hO,"1"],["Draw",m.dO,"X"],[m.away,m.aO,"2"]].map(p=><div key={p[2]} onClick={e=>quickPick(m,p[2],p[0],p[1],e)} style={{flex:1,padding:"7px 0",borderRadius:6,border:"1px solid var(--cb)",background:"rgba(255,255,255,.02)",textAlign:"center",cursor:"pointer"}}><span style={{fontSize:9,color:"var(--w4)",marginRight:3}}>{p[2]}</span><span className="jm" style={{fontSize:12,fontWeight:700,color:"#c8f06e"}}>{p[1]}</span></div>)}</div>
      </div>))}</div></div>);
  const DashView=()=>{const bets=isA?D.bets.slice().sort((a,b)=>new Date(b.ts)-new Date(a.ts)):myB();
    const stats=isA?[{l:"Players",v:D.users.length,c:"var(--bl)"},{l:"Total Bets",v:D.bets.length,c:"var(--t)"},{l:"In Play",v:"$"+D.bets.filter(b=>b.status==="pending").reduce((s,b)=>s+b.amount,0).toFixed(0),c:"var(--a)"}]:[{l:"Balance",v:"$"+(cu?cu.balance:0),c:"var(--t)"},{l:"Profit",v:(cu?(cu.balance-cu.budget>=0?"+":"")+(cu.balance-cu.budget).toFixed(2):"0"),c:cu&&cu.balance>=cu.budget?"var(--t)":"var(--r)"},{l:"Active Bets",v:myB().filter(b=>b.status==="pending").length,c:"var(--a)"},{l:"Started",v:"$"+(cu?cu.budget:0),c:"var(--w2)"}];
    return(<div><h1 style={{fontSize:20,fontWeight:800,marginBottom:4}}>{isA?"Command Center":"Welcome, "+(user.displayName||"").split(" ")[0]}</h1><p style={{color:"var(--w3)",fontSize:11,marginBottom:24}}>{"World Cup 2026 \u2022 "+D.matches.length+" matches"}</p>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(130px,1fr))",gap:10,marginBottom:24}}>{stats.map((s,i)=><div key={i} className={"cd au d"+(i+1)} style={{padding:16}}><p style={{fontSize:9,fontWeight:700,color:"var(--w3)",textTransform:"uppercase",letterSpacing:.8,marginBottom:6}}>{s.l}</p><p className="jm" style={{fontSize:20,fontWeight:700,color:s.c}}>{s.v}</p></div>)}</div>
      <p style={{fontSize:10,fontWeight:700,color:"var(--w3)",textTransform:"uppercase",letterSpacing:1,marginBottom:12}}>{isA?"Recent Activity":"Your Bets"}</p>
      {bets.length===0?<div className="cd" style={{textAlign:"center",padding:32}}><p style={{color:"var(--w3)",fontSize:12}}>No bets yet. Head to Matches!</p></div>
      :<div style={{display:"flex",flexDirection:"column",gap:5}}>{bets.slice(0,10).map((b,i)=>{const bu=D.users.find(u=>u.id===b.userId);return(<div key={b.id} className={"cd au d"+Math.min(i+1,6)} style={{padding:12}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}><div>{isA&&bu&&<p style={{fontSize:9,color:"var(--t)",fontWeight:700}}>{bu.displayName}</p>}<p style={{fontWeight:700,fontSize:12}}>{b.label}</p><p style={{fontSize:10,color:"var(--w3)",marginTop:1}}>{b.team}<span className="jm" style={{color:"var(--t)",fontSize:10,marginLeft:4}}>{"@"+b.odds+"x"}</span>{b.market&&<span style={{color:"var(--w4)",marginLeft:5,fontSize:9}}>{b.market}</span>}</p></div><div style={{textAlign:"right"}}><p className="jm" style={{fontWeight:700,color:"var(--t)",fontSize:13}}>{"$"+b.amount}</p><span className="tag" style={{background:b.status==="pending"?"var(--ad)":"var(--rd)",color:b.status==="pending"?"var(--a)":"var(--r)"}}>{b.status==="pending"?"PENDING":"SETTLED"}</span></div></div></div>)})}</div>}</div>)};

  const AllBetsView=()=>{const allBets=D.bets.slice().sort((a,b)=>new Date(b.ts)-new Date(a.ts));const filtered=bFlt==="all"?allBets:allBets.filter(b=>b.status===bFlt);
    const totalStaked=allBets.reduce((s,b)=>s+b.amount,0);const pendCount=allBets.filter(b=>b.status==="pending").length;const wonCount=allBets.filter(b=>b.status==="won").length;const lostCount=allBets.filter(b=>b.status==="lost").length;
    const totalPot=allBets.filter(b=>b.status==="pending").reduce((s,b)=>s+b.pot,0);
    const tabBg={all:"rgba(91,156,246,.1)",pending:"rgba(232,184,48,.1)",won:"rgba(45,212,160,.1)",lost:"rgba(255,92,92,.1)"};
    const tabs=[{id:"all",label:"All",count:allBets.length,color:"var(--bl)"},{id:"pending",label:"Live",count:pendCount,color:"var(--a)"},{id:"won",label:"Won",count:wonCount,color:"var(--t)"},{id:"lost",label:"Lost",count:lostCount,color:"var(--r)"}];
    return(<div><h1 style={{fontSize:20,fontWeight:800,marginBottom:4}}>All Bets</h1><p style={{color:"var(--w3)",fontSize:11,marginBottom:16}}>Family betting activity</p>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(110px,1fr))",gap:8,marginBottom:18}}>
        <div className="cd au d1" style={{padding:14,textAlign:"center"}}><p style={{fontSize:8,fontWeight:700,color:"var(--w4)",textTransform:"uppercase",letterSpacing:1,marginBottom:4}}>Total Staked</p><p className="jm" style={{fontSize:18,fontWeight:700,color:"var(--bl)"}}>{"$"+totalStaked.toFixed(0)}</p></div>
        <div className="cd au d2" style={{padding:14,textAlign:"center"}}><p style={{fontSize:8,fontWeight:700,color:"var(--w4)",textTransform:"uppercase",letterSpacing:1,marginBottom:4}}>At Risk</p><p className="jm" style={{fontSize:18,fontWeight:700,color:"var(--a)"}}>{"$"+allBets.filter(b=>b.status==="pending").reduce((s,b)=>s+b.amount,0).toFixed(0)}</p></div>
        <div className="cd au d3" style={{padding:14,textAlign:"center"}}><p style={{fontSize:8,fontWeight:700,color:"var(--w4)",textTransform:"uppercase",letterSpacing:1,marginBottom:4}}>Potential Win</p><p className="jm" style={{fontSize:18,fontWeight:700,color:"var(--t)"}}>{"$"+totalPot.toFixed(0)}</p></div></div>
      <div style={{display:"flex",gap:4,marginBottom:16}}>{tabs.map(t=><button key={t.id} onClick={()=>sBFlt(t.id)} style={{flex:1,padding:"8px 4px",borderRadius:8,border:"1px solid "+(bFlt===t.id?t.color:"var(--cb)"),background:bFlt===t.id?tabBg[t.id]:"transparent",color:bFlt===t.id?t.color:"var(--w3)",cursor:"pointer",fontFamily:"'Sora'",fontSize:11,fontWeight:700,textAlign:"center"}}><div>{t.label}</div><div className="jm" style={{fontSize:14,marginTop:2}}>{t.count}</div></button>)}</div>
      {filtered.length===0?<div className="cd" style={{textAlign:"center",padding:40}}><p style={{color:"var(--w3)",fontSize:12}}>No bets</p></div>
      :<div style={{display:"flex",flexDirection:"column",gap:6}}>{filtered.map((b,i)=>{const bu=D.users.find(u=>u.id===b.userId);const isP=b.status==="pending";const isW=b.status==="won";const profitIfWin=+(b.pot-b.amount).toFixed(2);
        const colors=["#2dd4a0","#5b9cf6","#e8b830","#ff5c5c","#a78bfa","#f472b6","#38bdf8","#fb923c"];const ac=bu?colors[bu.id.charCodeAt(bu.id.length-1)%colors.length]:"#555";const ini=bu?bu.displayName.split(" ").map(w=>w[0]).join("").slice(0,2):"?";
        return(<div key={b.id} className={"cd au d"+Math.min(i+1,6)} style={{padding:0,overflow:"hidden"}}>
          {isP&&<div style={{height:2,background:"linear-gradient(90deg,var(--a),transparent)",width:"60%"}}/>}{isW&&<div style={{height:2,background:"linear-gradient(90deg,var(--t),transparent)"}}/>}{!isP&&!isW&&<div style={{height:2,background:"linear-gradient(90deg,var(--r),transparent)",width:"40%"}}/>}
          <div style={{padding:"12px 14px"}}><div style={{display:"flex",gap:10,alignItems:"flex-start"}}>
            <div style={{width:36,height:36,borderRadius:8,background:ac+"22",border:"1px solid "+ac+"33",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:800,fontSize:12,color:ac,flexShrink:0}}>{ini}</div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4}}><p style={{fontWeight:700,fontSize:12,color:ac}}>{bu?bu.displayName:"Unknown"}</p><span className="tag" style={{background:isP?"var(--ad)":isW?"rgba(45,212,160,.1)":"var(--rd)",color:isP?"var(--a)":isW?"var(--t)":"var(--r)"}}>{isP&&<span className="ldot" style={{width:4,height:4,background:"var(--a)"}}/>}{isP?"LIVE":isW?"WON":"LOST"}</span></div>
              <p style={{fontWeight:700,fontSize:13,marginBottom:2}}>{b.label}</p>
              <div style={{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"}}><span style={{fontSize:11,color:"var(--w2)"}}>{b.team}</span><span className="jm" style={{fontSize:10,color:"var(--t)",background:"var(--td)",padding:"1px 6px",borderRadius:4}}>{"@"+b.odds}</span>{b.market&&<span style={{fontSize:9,color:"var(--w4)"}}>{b.market}</span>}</div>
              <div style={{display:"flex",gap:12,marginTop:8,paddingTop:8,borderTop:"1px solid rgba(255,255,255,.03)"}}>
                <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>STAKE</p><p className="jm" style={{fontSize:13,fontWeight:700,color:"var(--w)"}}>{"$"+b.amount}</p></div>
                <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>{isP?"TO WIN":"RETURN"}</p><p className="jm" style={{fontSize:13,fontWeight:700,color:isP?"var(--a)":isW?"var(--t)":"var(--w4)"}}>{isP||isW?"$"+b.pot.toFixed(2):"$0"}</p></div>
                <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>{isP?"POTENTIAL":"P&L"}</p><p className="jm" style={{fontSize:13,fontWeight:700,color:isP?"var(--t)":isW?"var(--t)":"var(--r)"}}>{isP?"+"+profitIfWin:isW?"+"+profitIfWin:"-$"+b.amount}</p></div></div>
              <p style={{fontSize:9,color:"var(--w4)",marginTop:6}}>{new Date(b.ts).toLocaleString()}</p>
            </div></div></div></div>)})}</div>}</div>)};

  const LbView=()=>{const L=getLb();return(<div><h1 style={{fontSize:20,fontWeight:800,marginBottom:4}}>Leaderboard</h1><p style={{color:"var(--w3)",fontSize:11,marginBottom:20}}>Who makes the most from their $100?</p>
    {L.length===0?<div className="cd" style={{textAlign:"center",padding:40}}><p style={{color:"var(--w3)"}}>No players yet</p></div>
    :<div className="cd" style={{padding:0}}>
      <div className="lb-header" style={{padding:"10px 16px",borderBottom:"1px solid var(--cb)",display:"flex"}}><span style={{width:32,fontSize:9,fontWeight:700,color:"var(--w4)"}}>#</span><span style={{flex:1,fontSize:9,fontWeight:700,color:"var(--w4)"}}>PLAYER</span><span style={{width:70,textAlign:"right",fontSize:9,fontWeight:700,color:"var(--w4)"}}>PROFIT</span><span style={{width:60,textAlign:"right",fontSize:9,fontWeight:700,color:"var(--w4)"}}>BAL</span><span style={{width:50,textAlign:"right",fontSize:9,fontWeight:700,color:"var(--w4)"}}>BETS</span><span style={{width:50,textAlign:"right",fontSize:9,fontWeight:700,color:"var(--w4)"}}>ROI</span></div>
      {L.map((u,i)=><div key={u.id} className={"lbe au d"+Math.min(i+1,6)+(i===0?" r1":i===1?" r2":i===2?" r3":"")}>
        <span style={{width:32,fontSize:i<3?16:13,fontWeight:700}}>{i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":i+1}</span>
        <div style={{flex:1,minWidth:0}}><p style={{fontWeight:700,fontSize:13}}>{u.displayName}</p><p style={{fontSize:9,color:"var(--w4)"}}>{"Started $"+u.budget+" \u2022 "+u.active+" active"}</p>
          <div className="lb-mobile-stats" style={{display:"none",gap:10,marginTop:6}}>
            <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>PROFIT</p><p className="jm" style={{fontSize:13,fontWeight:700,color:u.profitVal>=0?"var(--t)":"var(--r)"}}>{(u.profitVal>=0?"+":"")+u.profitVal}</p></div>
            <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>BALANCE</p><p className="jm" style={{fontSize:13,fontWeight:600,color:"var(--w2)"}}>{"$"+u.balance}</p></div>
            <div><p style={{fontSize:8,color:"var(--w4)",fontWeight:600}}>ROI</p><p className="jm" style={{fontSize:13,fontWeight:700,color:parseFloat(u.roi)>=0?"var(--t)":"var(--r)"}}>{u.roi+"%"}</p></div></div></div>
        <p className="jm lb-header" style={{width:70,textAlign:"right",fontWeight:700,color:u.profitVal>=0?"var(--t)":"var(--r)",fontSize:13}}>{(u.profitVal>=0?"+":"")+u.profitVal}</p>
        <p className="jm lb-header" style={{width:60,textAlign:"right",fontWeight:600,color:"var(--w2)",fontSize:12}}>{"$"+u.balance}</p>
        <p className="lb-header" style={{width:50,textAlign:"right",color:"var(--w2)",fontSize:12}}>{u.totalBets}</p>
        <p className="jm lb-header" style={{width:50,textAlign:"right",fontWeight:700,fontSize:11,color:parseFloat(u.roi)>=0?"var(--t)":"var(--r)"}}>{u.roi+"%"}</p></div>)}</div>}</div>)};

  const AiView=()=>(<div><h1 style={{fontSize:20,fontWeight:800,marginBottom:4}}>AI Advisor</h1><p style={{color:"var(--w3)",fontSize:11,marginBottom:16}}>Claude-powered</p>
    <div className="cd chtw"><div className="chts">{msgs.map((m,i)=><div key={i} className={"bbl "+(m.r==="u"?"u":"a")}>{m.r==="a"&&<span style={{fontSize:9,color:"var(--t)",fontWeight:700,display:"block",marginBottom:2}}>ADVISOR</span>}<p style={{whiteSpace:"pre-wrap"}}>{m.t}</p></div>)}{cB&&<div className="bbl a"><span style={{fontSize:9,color:"var(--t)",fontWeight:700,display:"block",marginBottom:2}}>ADVISOR</span><span style={{color:"var(--w3)"}}>Thinking...</span></div>}<div ref={er}/></div>
      <div style={{display:"flex",gap:6,paddingTop:10,borderTop:"1px solid var(--cb)"}}><input className="inp" style={{flex:1,fontSize:12}} placeholder="Ask anything..." value={ci} onChange={e=>sCi(e.target.value)} onKeyDown={e=>e.key==="Enter"&&doChat()}/><button className="bt" style={{width:"auto",padding:"10px 18px"}} onClick={doChat} disabled={cB||!ci.trim()}>Send</button></div></div>
    <div style={{display:"flex",gap:5,marginTop:10,flexWrap:"wrap"}}>{["Best bets?","USA vs Paraguay","Underdog picks?","Germany goals?"].map(q=><button key={q} onClick={()=>sCi(q)} style={{padding:"6px 10px",background:"var(--c1)",border:"1px solid var(--cb)",borderRadius:6,color:"var(--w3)",fontSize:10,cursor:"pointer",fontFamily:"'Sora'",fontWeight:500}}>{q}</button>)}</div></div>);

  const AdmView=()=>(<div><h1 style={{fontSize:20,fontWeight:800,marginBottom:4}}>Admin</h1><p style={{color:"var(--w3)",fontSize:11,marginBottom:20}}>Manage players</p>
    <div className="cd au" style={{marginBottom:14}}><p style={{fontSize:10,fontWeight:700,color:"var(--t)",textTransform:"uppercase",letterSpacing:.8,marginBottom:12}}>Add Player</p>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))",gap:8}}><input className="inp" placeholder="Username" value={nu.username} onChange={e=>sNu({...nu,username:e.target.value})}/><input className="inp" placeholder="Display Name" value={nu.displayName} onChange={e=>sNu({...nu,displayName:e.target.value})}/><input className="inp" type="password" placeholder="Password" value={nu.password} onChange={e=>sNu({...nu,password:e.target.value})}/><div style={{display:"flex",gap:6}}><input className="inp" type="number" placeholder="Budget" value={nu.budget} onChange={e=>sNu({...nu,budget:parseFloat(e.target.value)||0})}/><button className="bt" style={{width:"auto",padding:"10px 16px",fontSize:11}} onClick={addU}>Add</button></div></div></div>
    <div className="cd au d2">{D.users.length===0?<p style={{color:"var(--w4)",textAlign:"center",padding:20,fontSize:12}}>No players</p>
      :<div style={{display:"flex",flexDirection:"column",gap:6}}>{D.users.map(u=><div key={u.id} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:12,borderRadius:8,background:"rgba(255,255,255,.015)",border:"1px solid var(--cb)",flexWrap:"wrap",gap:8}}>
        <div><p style={{fontWeight:700,fontSize:13}}>{u.displayName}</p><p style={{fontSize:10,color:"var(--w4)"}}>{"Login: "}<span style={{color:"var(--t)",fontWeight:600}}>{u.username}</span>{" \u2022 Pass: "}<span style={{color:"var(--w2)",fontWeight:600}}>{u.password}</span>{" \u2022 Budget: $"+u.budget}</p></div>
        <div style={{display:"flex",alignItems:"center",gap:8}}><span className="jm" style={{color:"var(--t)",fontWeight:700,fontSize:13}}>{"$"+u.balance}</span><button className="bt bt-ghost" style={{width:"auto",padding:"5px 12px",fontSize:10}} onClick={()=>rstU(u.id)}>Reset</button><button className="bt" style={{width:"auto",padding:"5px 12px",fontSize:10,background:"linear-gradient(135deg,#a33,#ff5c5c)"}} onClick={()=>delU(u.id)}>Remove</button></div></div>)}</div>}</div></div>);
  const renderContent=()=>{
    if(vw==="match"&&selM)return MatchDetailView();
    if(vw==="match")return MatchListView();
    if(vw==="bets")return AllBetsView();
    if(vw==="lb")return LbView();
    if(vw==="ai")return AiView();
    if(vw==="adm")return AdmView();
    return DashView();
  };

  useEffect(()=>{if(!token||!user)return;const iv=setInterval(()=>loadMatches(token),30*60*1000);return()=>clearInterval(iv)},[token,user]);
  if(!ok)return(<div style={{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"#0a0e1a"}}><style>{STYLE}</style><p style={{color:"#2dd4a0",fontWeight:700,letterSpacing:2}}>LOADING...</p></div>);

  if(!user)return(<div className="log-wrap"><style>{STYLE}</style><div className="log-card au"><div style={{textAlign:"center",marginBottom:28}}><div style={{width:90,height:90,borderRadius:14,background:"#fff",display:"inline-flex",alignItems:"center",justifyContent:"center",marginBottom:14,boxShadow:"0 4px 20px rgba(0,0,0,.3)"}}><img src="/wc2026.png" style={{width:80,height:80,objectFit:"contain"}}/></div><h1 style={{fontSize:18,fontWeight:800}}>World Cup 2026</h1><p style={{color:"#4a5a76",fontSize:11,fontWeight:600,letterSpacing:1.5,textTransform:"uppercase"}}>Family Betting Arena</p></div><div style={{display:"flex",flexDirection:"column",gap:10}}><div><label style={{fontSize:10,fontWeight:600,color:"#4a5a76",marginBottom:3,display:"block"}}>EMAIL / USERNAME</label><input className="inp" value={le} onChange={e=>sLe(e.target.value)} onKeyDown={e=>e.key==="Enter"&&login()}/></div><div><label style={{fontSize:10,fontWeight:600,color:"#4a5a76",marginBottom:3,display:"block"}}>PASSWORD</label><input className="inp" type="password" value={lp} onChange={e=>sLp(e.target.value)} onKeyDown={e=>e.key==="Enter"&&login()}/></div>{lerr&&<p style={{color:"#ff5c5c",fontSize:11,textAlign:"center"}}>{lerr}</p>}<button className="bt" onClick={login}>Sign In</button></div><p style={{textAlign:"center",marginTop:20,fontSize:9,color:"#2d3a52",letterSpacing:1,fontWeight:600}}>CLOUDBET x ROOMERANG</p></div></div>);

  const NAV=[{id:"dash",ic:"\u{1F4CA}",lb:"Dashboard"},{id:"match",ic:"\u26BD",lb:"Matches"},{id:"bets",ic:"\u{1F4B0}",lb:"All Bets"},{id:"lb",ic:"\u{1F3C6}",lb:"Leaderboard"},{id:"ai",ic:"\u{1F916}",lb:"AI Advisor"}];
  if(isA)NAV.push({id:"adm",ic:"\u2699\uFE0F",lb:"Admin"});

  return(<div style={{background:"var(--b1)",minHeight:"100vh"}}><style>{STYLE}</style>
    {tst&&<div className="tst" style={{background:tst.t==="err"?"rgba(255,92,92,.15)":"rgba(45,212,160,.15)",color:tst.t==="err"?"var(--r)":"var(--t)"}}>{tst.m}</div>}
    {conf&&Array.from({length:20}).map((_,i)=><div key={i} className="cnf" style={{left:Math.random()*100+"%",width:5+Math.random()*6+"px",height:5+Math.random()*6+"px",background:["var(--t)","var(--a)","var(--bl)","var(--r)","#a78bfa"][i%5],animationDelay:Math.random()*1.5+"s",borderRadius:Math.random()>.5?"50%":"2px",top:-10}}/>)}
    <div className="side">
      <div style={{padding:"0 6px",marginBottom:24}}><div style={{display:"flex",alignItems:"center",gap:6}}><div style={{width:32,height:32,borderRadius:6,background:"#fff",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden"}}><img src="/wc2026.png" style={{width:28,height:28,objectFit:"contain"}}/></div><div><span style={{fontSize:13,fontWeight:800}}>WC 2026</span><p style={{fontSize:8,color:"var(--w4)",letterSpacing:1}}>ARENA</p></div></div></div>
      <div style={{display:"flex",flexDirection:"column",gap:1,flex:1}}>{NAV.map(n=><div key={n.id} className={"nl"+(vw===n.id?" on":"")} onClick={()=>{sV(n.id);sSelM(null);sPick(null)}}><span style={{fontSize:14}}>{n.ic}</span>{n.lb}</div>)}</div>
      <div style={{borderTop:"1px solid var(--cb)",paddingTop:12,marginTop:12}}><div style={{display:"flex",alignItems:"center",gap:6,padding:"0 4px",marginBottom:8}}><div style={{width:28,height:28,borderRadius:7,display:"flex",alignItems:"center",justifyContent:"center",background:isA?"linear-gradient(135deg,#1a9e78,var(--t))":"linear-gradient(135deg,#3b5ee8,var(--bl))",fontWeight:800,fontSize:11,color:"#fff"}}>{user.displayName?user.displayName[0]:""}</div><div><p style={{fontWeight:700,fontSize:11}}>{user.displayName}</p><p style={{fontSize:9,color:"var(--w4)"}}>{isA?"Admin":"$"+(cu?cu.balance:0)}</p></div></div>
        <div className="nl" onClick={()=>{su(null);sA(false);sV("dash");sSelM(null);setToken(null);localStorage.removeItem("wc_token");localStorage.removeItem("wc_userId")}} style={{color:"var(--r)",fontSize:11}}><span>{"\u21A9"}</span>Sign Out</div></div>
    </div>
    <div className="mn">{renderContent()}</div>
    {BetSlipFloat()}
    <div className="mbn" style={{display:"none"}}>{NAV.map(n=><div key={n.id} className={"mbi"+(vw===n.id?" on":"")} onClick={()=>{sV(n.id);sSelM(null)}}><div style={{fontSize:14}}>{n.ic}</div><div>{n.lb}</div></div>)}</div>
  </div>);
}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(WC));
