// React loaded via CDN
const { useState, useEffect, useCallback, useRef, createContext, useContext } = React;

/* ── Font loader ─────────────────────────────────────────────────────── */
function FontLoader() {
  useEffect(() => {
    const id = "iq-fonts";
    if (document.getElementById(id)) return;
    const l = document.createElement("link");
    l.id = id; l.rel = "stylesheet";
    l.href = "https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,600;0,700;1,300;1,400&family=DM+Sans:wght@300;400;500;600&display=swap";
    document.head.appendChild(l);
  }, []);
  return null;
}

/* ── CSS ─────────────────────────────────────────────────────────────── */
const CSS = `
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body { background: #07090f; transition: background 0.35s; }
  body.light { background: #f5f0e8; }
  select option { background: #161c2a; color: #f0ebe0; }
  body.light select option { background: #fff; color: #0a0804; }
  body.light { color: #0a0804; font-weight: 500; }
  body.light h1, body.light h2, body.light h3, body.light strong, body.light b { font-weight: 800; color: #000; }
  input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; }
  input::placeholder  { color: rgba(240,235,224,0.22); }
  body.light input::placeholder { color: rgba(30,20,10,0.3); }
  textarea::placeholder { color: rgba(240,235,224,0.22); }
  body.light textarea::placeholder { color: rgba(30,20,10,0.3); }
  ::-webkit-scrollbar { width: 4px; }
  ::-webkit-scrollbar-thumb { background: rgba(200,169,110,0.35); border-radius: 4px; }
  * { transition: background-color 0.25s, border-color 0.25s, color 0.15s; }

  @keyframes fadeUp  { from{opacity:0;transform:translateY(18px)} to{opacity:1;transform:translateY(0)} }
  @keyframes floatIn { from{opacity:0;transform:translateY(32px) scale(0.97)} to{opacity:1;transform:translateY(0) scale(1)} }
  @keyframes spin    { to{transform:rotate(360deg)} }
  @keyframes shimTxt { 0%{background-position:-200% center} 100%{background-position:200% center} }
  @keyframes meshA   { 0%,100%{transform:translate(0,0) scale(1)} 40%{transform:translate(40px,-28px) scale(1.07)} 70%{transform:translate(-18px,36px) scale(0.95)} }
  @keyframes meshB   { 0%,100%{transform:translate(0,0)} 50%{transform:translate(-55px,28px) rotate(11deg)} }
  @keyframes glow    { 0%,100%{box-shadow:0 4px 20px rgba(200,169,110,0.22)} 50%{box-shadow:0 4px 38px rgba(200,169,110,0.42)} }
  @keyframes imgPop  { from{opacity:0;transform:scale(0.94)} to{opacity:1;transform:scale(1)} }

  .fi  { animation: floatIn 0.85s cubic-bezier(0.22,1,0.36,1) both; }
  .fu  { animation: fadeUp  0.6s  cubic-bezier(0.22,1,0.36,1) both; }
  .sht {
    background: linear-gradient(90deg,#c8a96e 0%,#e2c98a 40%,#f0ebe0 50%,#e2c98a 60%,#c8a96e 100%);
    background-size: 200% auto; -webkit-background-clip:text;
    -webkit-text-fill-color:transparent; background-clip:text;
    animation: shimTxt 4s linear infinite;
  }
  .ch  { transition:transform 0.15s,filter 0.15s; cursor:pointer; }
  .ch:hover  { transform:scale(1.04); filter:brightness(1.16); }
  .bg  { transition:filter 0.18s,transform 0.18s; cursor:pointer; }
  .bg:hover  { filter:brightness(1.1); transform:translateY(-1px); }
  .bo  { transition:border-color 0.18s,color 0.18s; cursor:pointer; }
  .bo:hover  { border-color:#c8a96e !important; color:#c8a96e !important; }
  .tb  { transition:color 0.2s,border-bottom-color 0.2s; cursor:pointer; }
  .tb:hover  { color:#e2c98a !important; }
  .ie:focus  { border-color:#c8a96e !important; box-shadow:0 0 0 3px rgba(200,169,110,0.13) !important; outline:none; }
  .img-thumb { animation: imgPop 0.3s ease both; }
  .upload-zone:hover { border-color: rgba(200,169,110,0.5) !important; background: rgba(200,169,110,0.06) !important; }
`;

/* ── Theme palettes ─────────────────────────────────────────────────── */
const DARK_THEME = {
  bg:"#07090f", card:"#111520", card2:"#161c2a",
  gold:"#c8a96e", goldLight:"#e2c98a",
  cream:"#f0ebe0", muted:"rgba(240,235,224,0.32)",
  green:"#2a9d74", red:"#b84040",
  border:"rgba(200,169,110,0.15)",
  headerBg:"rgba(9,11,17,0.97)",
  tabBg:"rgba(10,12,18,0.93)",
  inputBg:"rgba(240,235,224,0.04)",
  inputBorder:"rgba(200,169,110,0.16)",
  overlayBg:"rgba(7,9,15,0.9)",
  statBg:"#161c2a",
  blobA:"rgba(155,35,53,0.17)",
  blobB:"rgba(200,169,110,0.09)",
  gridLine:"rgba(200,169,110,0.027)",
  cellEmpty:"rgba(240,235,224,0.02)",
  cellBorderDefault:"rgba(200,169,110,0.07)",
  encBg:"rgba(200,169,110,0.06)",
  encBorder:"rgba(200,169,110,0.14)",
  footerBg:"rgba(7,9,15,0.55)",
};
const LIGHT_THEME = {
  bg:"#f5f0e8", card:"#ffffff", card2:"#f0ebe0",
  gold:"#9b6e2a", goldLight:"#c8902a",
  cream:"#0a0804", muted:"rgba(10,8,4,0.5)",
  green:"#1a7a55", red:"#a03030",
  border:"rgba(155,110,42,0.22)",
  headerBg:"rgba(255,252,245,0.97)",
  tabBg:"rgba(245,240,232,0.98)",
  inputBg:"rgba(26,18,8,0.04)",
  inputBorder:"rgba(155,110,42,0.22)",
  overlayBg:"rgba(30,20,10,0.7)",
  statBg:"#efe9da",
  blobA:"rgba(155,35,53,0.08)",
  blobB:"rgba(200,169,110,0.12)",
  gridLine:"rgba(155,110,42,0.06)",
  cellEmpty:"rgba(26,18,8,0.02)",
  cellBorderDefault:"rgba(155,110,42,0.1)",
  encBg:"rgba(155,110,42,0.06)",
  encBorder:"rgba(155,110,42,0.18)",
  footerBg:"rgba(245,240,232,0.9)",
};

function mkStyles(T){
  const IS={ width:"100%", padding:"11px 14px", background:T.inputBg, border:"1px solid "+T.inputBorder, borderRadius:9, color:T.cream, fontFamily:"'DM Sans',sans-serif", fontSize:"0.9rem", outline:"none", transition:"border-color 0.2s,box-shadow 0.2s" };
  const LS={ display:"block", fontFamily:"'DM Sans',sans-serif", fontSize:"0.62rem", color:T.muted, letterSpacing:2, textTransform:"uppercase", marginBottom:7 };
  return{IS,LS};
}

/* ── Theme Context — every component calls useT() for current theme ─── */
const ThemeCtx = createContext(DARK_THEME);
function useT(){ return useContext(ThemeCtx); }
function useStyles(){ const T=useT(); return {...mkStyles(T), T}; }

/* ── Data ────────────────────────────────────────────────────────────── */
const CURRENCIES = [
  {code:"USD",symbol:"$",flag:"🇺🇸"},{code:"EUR",symbol:"€",flag:"🇪🇺"},
  {code:"GBP",symbol:"£",flag:"🇬🇧"},{code:"JPY",symbol:"¥",flag:"🇯🇵"},
  {code:"CAD",symbol:"CA$",flag:"🇨🇦"},{code:"AUD",symbol:"A$",flag:"🇦🇺"},
  {code:"BTC",symbol:"₿",flag:"🪙"},{code:"ETH",symbol:"Ξ",flag:"🔷"},
];
const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const WDAYS  = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
const ATYPES = ["Stocks","Forex","Crypto","Options","Futures","Commodities","ETFs","Other"];
const DTYPES = ["days","weeks","months","years"];

/* ── Personalized encouragements ─────────────────────────────────────── */
const ENCOURAGEMENTS = [
  (n) => `Good morning, ${n}! Every trade is a step closer to your freedom. 🔥`,
  (n) => `${n}, discipline today builds the lifestyle you want tomorrow. 💪`,
  (n) => `You're on the path, ${n}. Stay consistent — compounding rewards patience. 📈`,
  (n) => `${n}, the market rewards those who show up prepared. Let's get it! 🎯`,
  (n) => `Keep stacking those wins, ${n}. Your goal is getting closer every day. 🚀`,
  (n) => `${n}, one focused session can change your week. Go make it count. ⚡`,
  (n) => `Legends are built one trade at a time, ${n}. Today's your day. 👑`,
  (n) => `${n}, trust the process. Your strategy + consistency = freedom. 💎`,
];

function getDailyEncouragement(firstName) {
  const day = new Date().getDay();
  return ENCOURAGEMENTS[day % ENCOURAGEMENTS.length](firstName || "Trader");
}

/* ── Utils ───────────────────────────────────────────────────────────── */
function fmtDate(y,m,d){ return y+"-"+String(m+1).padStart(2,"0")+"-"+String(d).padStart(2,"0"); }
function todayStr(){ const n=new Date(); return fmtDate(n.getFullYear(),n.getMonth(),n.getDate()); }
function isWknd(y,m,d){ const w=new Date(y,m,d).getDay(); return w===0||w===6; }
function firstName(name){ return name ? name.trim().split(" ")[0] : "Trader"; }

function buildDays(start,durType,durVal,inclWknd){
  const days=[],d=new Date(start);
  const total=durType==="weeks"?durVal*7:durType==="months"?durVal*30:durType==="years"?durVal*365:durVal;
  let n=0;
  while(n<total){
    const y=d.getFullYear(),m=d.getMonth(),day=d.getDate();
    if(inclWknd||!isWknd(y,m,day)){days.push(fmtDate(y,m,day));n++;}
    d.setDate(d.getDate()+1);
  }
  return days;
}
function calcCompound(dep,pct,rv,days){
  // dep = starting deposit (principal)
  // pct = daily profit target %
  // rv  = reinvest % (100 = full compound, 0 = no compound)
  // Each day:
  //   dailyProfit = currentPrincipal x (pct/100)
  //   reinvested  = dailyProfit x (rv/100)   -> grows principal
  //   cashOut     = dailyProfit - reinvested  -> liquid cash kept
  let principal=dep, totalCash=0;
  const sc=[];
  for(const date of days){
    const dailyProfit = principal*(pct/100);
    const reinvested  = dailyProfit*(rv/100);
    const cashOut     = dailyProfit - reinvested;
    principal  += reinvested;
    totalCash  += cashOut;
    sc.push({
      date,
      dailyProfit,
      principal,
      cashOut,
      totalCash,
      totalWealth: principal + totalCash,
    });
  }
  return{ sc, goalAmount: principal + totalCash };
}
function money(sym,n){
  if(n===undefined||n===null) return sym+"0.00";
  return(n<0?"-":"")+sym+Math.abs(n).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});
}
function getSym(code){ return(CURRENCIES.find(c=>c.code===code)||{symbol:"$"}).symbol; }

/* ── Storage ─────────────────────────────────────────────────────────── */
async function dbGet(k){ try{const r=await window.storage.get(k);return r?JSON.parse(r.value):null;}catch(_){return null;} }
async function dbSet(k,v){ try{await window.storage.set(k,JSON.stringify(v));}catch(_){} }

/* ── Notifications ───────────────────────────────────────────────────── */
function askNotif(){ if(typeof Notification!=="undefined"&&Notification.permission==="default") Notification.requestPermission(); }
function pushNotif(title,body){ if(typeof Notification!=="undefined"&&Notification.permission==="granted") try{new Notification(title,{body});}catch(_){} }

/* ── Logo ────────────────────────────────────────────────────────────── */
function Logo({sz=48,showText=true}){
  const T=useT();
  return(
    <div style={{display:"flex",alignItems:"center",gap:12}}>
      <svg width={sz} height={sz} viewBox="0 0 48 48" fill="none">
        <defs>
          <linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#e2c98a"/><stop offset="100%" stopColor="#9b6e2a"/>
          </linearGradient>
          <linearGradient id="lg2" x1="0" y1="1" x2="1" y2="0">
            <stop offset="0%" stopColor="#c8a96e"/><stop offset="100%" stopColor="#f0d898"/>
          </linearGradient>
        </defs>
        <circle cx="24" cy="24" r="22" stroke="url(#lg1)" strokeWidth="1.4" fill="none" opacity="0.55"/>
        <circle cx="24" cy="24" r="18" fill="rgba(200,169,110,0.07)"/>
        <text x="24" y="30" textAnchor="middle" style={{fontFamily:"'Cormorant Garamond',serif",fontWeight:700,fontSize:17}} fill="url(#lg1)">IQ</text>
        <polyline points="33,10 40,10 40,17" stroke="url(#lg2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        <line x1="33" y1="17" x2="40" y2="10" stroke="url(#lg2)" strokeWidth="2" strokeLinecap="round"/>
        <circle cx="40" cy="10" r="2.3" fill="#e2c98a"/>
      </svg>
      {showText&&(
        <div style={{display:"flex",flexDirection:"column",gap:1}}>
          <span style={{fontFamily:"'Cormorant Garamond',serif",fontSize:sz*0.4,fontWeight:700,color:T.gold,letterSpacing:2,lineHeight:1}}>I QUIT</span>
          <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:sz*0.17,color:T.muted,letterSpacing:3,textTransform:"uppercase",lineHeight:1}}>Goal Tracker</span>
        </div>
      )}
    </div>
  );
}

/* ── Login / Sign-up ─────────────────────────────────────────────────── */
/* ── Login / Sign-up ─────────────────────────────────────────────────── */
function LoginPage({onLogin}){
  const T=useT();
  const {IS,LS}=mkStyles(T);
  const [mode,setMode]=useState("login");
  const [firstName_,setFirstName]=useState("");
  const [lastName,setLastName]=useState("");
  const [email,setEmail]=useState("");
  const [pass,setPass]=useState("");
  const [err,setErr]=useState("");
  const [loading,setLoading]=useState(false);
  const [isMobile,setIsMobile]=useState(()=>window.innerWidth<700);

  useEffect(()=>{
    const fn=()=>setIsMobile(window.innerWidth<700);
    window.addEventListener("resize",fn);
    return()=>window.removeEventListener("resize",fn);
  },[]);

  const submit=async()=>{
    setErr(""); setLoading(true);
    await new Promise(r=>setTimeout(r,700));
    if(mode==="signup"){
      if(!firstName_.trim()){setErr("Please enter your first name.");setLoading(false);return;}
      if(!email.trim()){setErr("Please enter your email address.");setLoading(false);return;}
      const fullName=(firstName_.trim()+" "+lastName.trim()).trim();
      await dbSet("iq-user",{name:fullName,firstName:firstName_.trim(),email});
      onLogin({name:fullName,firstName:firstName_.trim(),email});
    }else{
      const saved=await dbGet("iq-user");
      if(saved){ onLogin(saved); }
      else{ const fn=email.split("@")[0]||"Trader"; onLogin({name:fn,firstName:fn,email}); }
    }
    setLoading(false);
  };

  const FormFields=(
    <>
      {mode==="signup"&&(
        <>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:12}}>
            <div>
              <label style={LS}>First Name *</label>
              <input className="ie" style={IS} placeholder="Jas" value={firstName_} onChange={e=>setFirstName(e.target.value)}/>
            </div>
            <div>
              <label style={LS}>Last Name</label>
              <input className="ie" style={IS} placeholder="Washington-Brown" value={lastName} onChange={e=>setLastName(e.target.value)}/>
            </div>
          </div>
          <div style={{marginBottom:12}}>
            <label style={LS}>Email Address *</label>
            <input className="ie" style={IS} type="email" placeholder="jas@example.com" value={email} onChange={e=>setEmail(e.target.value)}/>
          </div>
        </>
      )}
      {mode==="login"&&(
        <div style={{marginBottom:12}}>
          <label style={LS}>Email Address</label>
          <input className="ie" style={IS} type="email" placeholder="you@example.com" value={email} onChange={e=>setEmail(e.target.value)}/>
        </div>
      )}
      <div style={{marginBottom:14}}>
        <label style={LS}>Password</label>
        <input className="ie" style={IS} type="password" placeholder="••••••••" value={pass} onChange={e=>setPass(e.target.value)} onKeyDown={e=>{if(e.key==="Enter")submit();}}/>
      </div>
      {err&&(
        <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.76rem",color:"#e07070",marginBottom:12,padding:"9px 12px",background:"rgba(184,64,64,0.11)",borderRadius:7,border:"1px solid rgba(184,64,64,0.22)"}}>{err}</div>
      )}
      <button className="bg" onClick={submit}
        style={{width:"100%",padding:"14px",marginBottom:16,background:"linear-gradient(135deg,#c8a96e 0%,#9b6e2a 100%)",border:"none",borderRadius:10,color:"#07090f",fontFamily:"'DM Sans',sans-serif",fontWeight:700,fontSize:"0.95rem",letterSpacing:0.5,animation:"glow 3s ease-in-out infinite",display:"flex",alignItems:"center",justifyContent:"center",gap:8}}>
        {loading
          ?<span style={{width:17,height:17,border:"2.5px solid rgba(7,9,15,0.25)",borderTopColor:"#07090f",borderRadius:"50%",display:"inline-block",animation:"spin 0.7s linear infinite"}}/>
          :(mode==="login"?"Sign In \u2192":"Create Account \u2192")
        }
      </button>
      <div style={{textAlign:"center",marginBottom:18}}>
        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.78rem",color:T.muted}}>
          {mode==="login"?"No account? ":"Already have one? "}
        </span>
        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.78rem",color:T.gold,cursor:"pointer",fontWeight:500}}
          onClick={()=>{setMode(m=>m==="login"?"signup":"login");setErr("");}}>
          {mode==="login"?"Sign up free":"Sign in"}
        </span>
      </div>
      <div style={{paddingTop:14,borderTop:"1px solid "+T.border,textAlign:"center"}}>
        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.6rem",color:"rgba(240,235,224,0.18)",letterSpacing:2,textTransform:"uppercase"}}>
          Your data \u00b7 Your goals \u00b7 Your freedom
        </span>
      </div>
    </>
  );

  /* ════ MOBILE PORTRAIT ════ */
  if(isMobile){
    return(
      <div style={{minHeight:"100vh",background:T.bg,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column"}}>
        <div style={{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",pointerEvents:"none"}}>
          <div style={{position:"absolute",width:420,height:420,borderRadius:"50%",background:"radial-gradient(circle,rgba(155,35,53,0.2) 0%,transparent 70%)",top:"-10%",left:"-15%",animation:"meshA 18s ease-in-out infinite"}}/>
          <div style={{position:"absolute",width:500,height:500,borderRadius:"50%",background:"radial-gradient(circle,rgba(200,169,110,0.1) 0%,transparent 65%)",bottom:"-20%",right:"-15%",animation:"meshB 22s ease-in-out infinite"}}/>
          <div style={{position:"absolute",top:0,right:0,bottom:0,left:0,backgroundImage:"linear-gradient(rgba(200,169,110,0.025) 1px,transparent 1px),linear-gradient(90deg,rgba(200,169,110,0.025) 1px,transparent 1px)",backgroundSize:"40px 40px"}}/>
        </div>

        {/* Hero top */}
        <div style={{position:"relative",zIndex:1,padding:"52px 28px 26px",textAlign:"center"}}>
          <div style={{display:"flex",justifyContent:"center",marginBottom:18}}>
            <Logo sz={46}/>
          </div>
          <div style={{width:36,height:1,background:"rgba(200,169,110,0.3)",margin:"0 auto 16px"}}/>
          <p style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.12rem",lineHeight:1.5,color:T.cream,fontWeight:300,fontStyle:"italic",maxWidth:320,margin:"0 auto 18px"}}>
            {"\"Quit trading for a "}
            <span style={{color:T.gold,fontWeight:600,fontStyle:"normal"}}>paycheck</span>
            {" \u2014 and let trading become your paycheck.\""}
          </p>
          <div style={{display:"flex",justifyContent:"center",gap:22}}>
            {[["$2.4M","Avg Goal"],["84%","Win Rate"],["12K+","Days"]].map(([v,l])=>(
              <div key={l} style={{textAlign:"center"}}>
                <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.05rem",fontWeight:700,color:T.gold}}>{v}</div>
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.48rem",color:T.muted,letterSpacing:2,textTransform:"uppercase",marginTop:1}}>{l}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Form card */}
        <div style={{position:"relative",zIndex:2,flex:1,background:"rgba(9,11,17,0.97)",borderTop:"1px solid "+T.border,borderTopLeftRadius:26,borderTopRightRadius:26,padding:"10px 24px 40px",boxShadow:"0 -10px 44px rgba(0,0,0,0.55)"}}>
          <div style={{width:34,height:4,borderRadius:2,background:"rgba(200,169,110,0.2)",margin:"12px auto 22px"}}/>
          <h2 style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.6rem",fontWeight:600,color:T.cream,marginBottom:4}}>
            {mode==="login"?"Welcome back.":"Start your journey."}
          </h2>
          <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.76rem",color:T.muted,marginBottom:20,fontWeight:300}}>
            {mode==="login"?"Sign in to your personal dashboard.":"Create your free account below."}
          </p>
          {FormFields}
        </div>
      </div>
    );
  }

  /* ════ DESKTOP ════ */
  return(
    <div style={{minHeight:"100vh",background:T.bg,display:"flex",position:"relative",overflow:"hidden"}}>
      <div style={{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",pointerEvents:"none"}}>
        <div style={{position:"absolute",width:700,height:700,borderRadius:"50%",background:"radial-gradient(circle,rgba(155,35,53,0.17) 0%,transparent 70%)",top:"-15%",left:"-10%",animation:"meshA 18s ease-in-out infinite"}}/>
        <div style={{position:"absolute",width:900,height:900,borderRadius:"50%",background:"radial-gradient(circle,rgba(200,169,110,0.09) 0%,transparent 65%)",bottom:"-30%",right:"-20%",animation:"meshB 22s ease-in-out infinite"}}/>
        <div style={{position:"absolute",width:400,height:400,borderRadius:"50%",background:"radial-gradient(circle,rgba(42,157,116,0.08) 0%,transparent 70%)",top:"45%",left:"52%",animation:"meshA 28s ease-in-out infinite reverse"}}/>
        <div style={{position:"absolute",top:0,right:0,bottom:0,left:0,backgroundImage:"linear-gradient(rgba(200,169,110,0.027) 1px,transparent 1px),linear-gradient(90deg,rgba(200,169,110,0.027) 1px,transparent 1px)",backgroundSize:"60px 60px"}}/>
      </div>
      <div style={{flex:1,minWidth:0,display:"flex",flexDirection:"column",justifyContent:"space-between",padding:"48px 52px",position:"relative"}}>
        <Logo sz={50}/>
        <div style={{maxWidth:460}}>
          <p style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"2.6rem",lineHeight:1.2,color:T.cream,fontWeight:300,fontStyle:"italic",marginBottom:28}}>
            {"\"The moment you decide to "}
            <span style={{color:T.gold,fontWeight:600,fontStyle:"normal"}}>quit trading for a paycheck</span>
            {" is the moment trading becomes your paycheck.\""}
          </p>
          <div style={{display:"flex",gap:28,flexWrap:"wrap"}}>
            {[["$2.4M","Avg. Goal Set"],["84%","Win Rate"],["12K+","Days Logged"]].map(([v,l])=>(
              <div key={l}>
                <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.45rem",fontWeight:700,color:T.gold}}>{v}</div>
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.58rem",color:T.muted,letterSpacing:2,textTransform:"uppercase",marginTop:2}}>{l}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.65rem",color:"rgba(240,235,224,0.18)",letterSpacing:1}}>
          \u00a9 2025 I Quit Goal Tracker \u00b7 Built for Freedom
        </div>
      </div>
      <div style={{width:460,flexShrink:0,background:"rgba(9,11,17,0.92)",borderLeft:"1px solid "+T.border,display:"flex",alignItems:"center",justifyContent:"center",padding:"44px 38px",position:"relative",zIndex:1}}>
        <div className="fi" style={{width:"100%"}}>
          <div style={{marginBottom:28}}><Logo sz={40}/></div>
          <h2 style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.9rem",fontWeight:600,color:T.cream,marginBottom:5}}>
            {mode==="login"?"Welcome back.":"Start your journey."}
          </h2>
          <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.78rem",color:T.muted,marginBottom:22,fontWeight:300}}>
            {mode==="login"?"Sign in to your personal dashboard.":"Create your free account below."}
          </p>
          {FormFields}
        </div>
      </div>
    </div>
  );
}
/* ── Overlay Modal ───────────────────────────────────────────────────── */
function Modal({onClose,children}){
  const T=useT();
  useEffect(()=>{
    const fn=e=>{if(e.key==="Escape")onClose();};
    window.addEventListener("keydown",fn);
    return()=>window.removeEventListener("keydown",fn);
  },[onClose]);
  return(
    <div onClick={e=>{if(e.target===e.currentTarget)onClose();}}
      style={{position:"fixed",top:0,right:0,bottom:0,left:0,background:T.overlayBg,backdropFilter:"blur(8px)",zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",padding:16}}>
      <div className="fi" style={{background:T.card,border:"1px solid "+T.border,borderRadius:20,width:"100%",maxWidth:580,maxHeight:"92vh",overflow:"auto",boxShadow:"0 32px 80px rgba(0,0,0,0.6)"}}>
        {children}
      </div>
    </div>
  );
}

/* ── Trade Modal ─────────────────────────────────────────────────────── */
function TradeModal({dateStr,existing,currency,onSave,onClose}){
  const T=useT();
  const {IS,LS}=mkStyles(T);
  const sym=getSym(currency);
  const fileRef=useRef(null);
  const cameraRef=useRef(null);

  const [form,setForm]=useState(()=>({
    asset:"", assetType:"Stocks", direction:"Long",
    entry:"", exit:"", size:"", pnl:"", notes:"", win:null,
    setupImage: null,
    ...(existing||{})
  }));

  const set=k=>e=>setForm(f=>({...f,[k]:e.target.value}));

  // Dynamic labels based on asset type
  const isOptions  = form.assetType==="Options";
  const isFutures  = form.assetType==="Futures";
  const dir1Label  = isOptions ? "📞 Call" : "▲ Long";
  const dir2Label  = isOptions ? "🅿 Put"  : "▼ Short";
  const dir1Val    = isOptions ? "Call"    : "Long";
  const dir2Val    = isOptions ? "Put"     : "Short";
  const entryLabel = isFutures ? "Entry Ticks" : "Entry Price";
  const exitLabel  = isFutures ? "Exit Ticks"  : "Exit Price";
  const entryPh    = isFutures ? "e.g. 4520"  : "0.00";
  const exitPh     = isFutures ? "e.g. 4535"  : "0.00";

  // When asset type changes, reset direction to default for that type
  const handleAssetType=e=>{
    const t=e.target.value;
    setForm(f=>({...f,assetType:t,direction:t==="Options"?"Call":"Long"}));
  };

  const autoCalc=()=>{
    const p=parseFloat(form.entry),q=parseFloat(form.exit),s=parseFloat(form.size);
    if(!isNaN(p)&&!isNaN(q)&&!isNaN(s)){
      let raw=(q-p)*s;
      if(form.direction==="Short"||form.direction==="Put") raw=-raw;
      setForm(f=>({...f,pnl:raw.toFixed(2),win:raw>=0}));
    }
  };

  // Image upload handler
  const handleImageFile=file=>{
    if(!file) return;
    const reader=new FileReader();
    reader.onload=e=>setForm(f=>({...f,setupImage:e.target.result}));
    reader.readAsDataURL(file);
  };

  const save=()=>{
    const n=parseFloat(form.pnl);
    onSave({...form,pnl:n,win:n>=0});
  };

  const pnlNum=parseFloat(form.pnl);
  const pnlColor=pnlNum>=0?T.green:T.red;

  return(
    <Modal onClose={onClose}>
      {/* Header */}
      <div style={{padding:"20px 24px",borderBottom:"1px solid "+T.border,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div>
          <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.25rem",fontWeight:600,color:T.cream}}>Trade Journal</div>
          <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:T.gold,letterSpacing:2,marginTop:2}}>{dateStr}</div>
        </div>
        <button onClick={onClose} style={{background:T.inputBg,border:"none",color:T.muted,width:31,height:31,borderRadius:"50%",cursor:"pointer",fontSize:"0.82rem"}}>✕</button>
      </div>

      <div style={{padding:"20px 24px"}}>
        {/* Row 1: Asset + Type */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}>
          <div>
            <label style={LS}>Asset / Pair</label>
            <input className="ie" style={IS} value={form.asset} onChange={set("asset")} placeholder="AAPL, /ES, EUR/USD…"/>
          </div>
          <div>
            <label style={LS}>Asset Type</label>
            <select className="ie" style={IS} value={form.assetType} onChange={handleAssetType}>
              {ATYPES.map(t=><option key={t}>{t}</option>)}
            </select>
          </div>
        </div>

        {/* Row 2: Direction (dynamic labels) + Size */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}>
          <div>
            <label style={LS}>{isOptions?"Option Type":"Direction"}</label>
            <div style={{display:"flex",gap:6}}>
              {[dir1Val,dir2Val].map((val,idx)=>{
                const lbl=idx===0?dir1Label:dir2Label;
                const isActive=form.direction===val;
                const activeCol=isOptions?(idx===0?"#2a9d74":"#b84040"):(idx===0?T.green:T.red);
                return(
                  <button key={val} onClick={()=>setForm(f=>({...f,direction:val}))}
                    style={{flex:1,padding:"9px 6px",borderRadius:8,border:"1px solid",cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.76rem",fontWeight:600,transition:"all 0.15s",
                      background:isActive?(idx===0?"rgba(42,157,116,0.18)":"rgba(184,64,64,0.18)"):"transparent",
                      borderColor:isActive?activeCol:"rgba(200,169,110,0.14)",
                      color:isActive?activeCol:T.muted}}>
                    {lbl}
                  </button>
                );
              })}
            </div>
          </div>
          <div>
            <label style={LS}>{isOptions?"Number of Contracts":isFutures?"Position Size (contracts)":"Position Size"}</label>
            <input className="ie" style={IS} type="number" value={form.size} onChange={set("size")} onBlur={autoCalc} placeholder={isOptions||isFutures?"1":"100"}/>
          </div>
        </div>

        {/* Row 3: Entry + Exit (dynamic labels for Futures) */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:12}}>
          <div>
            <label style={LS}>{entryLabel}</label>
            <input className="ie" style={IS} type="number" value={form.entry} onChange={set("entry")} onBlur={autoCalc} placeholder={entryPh}/>
          </div>
          <div>
            <label style={LS}>{exitLabel}</label>
            <input className="ie" style={IS} type="number" value={form.exit} onChange={set("exit")} onBlur={autoCalc} placeholder={exitPh}/>
          </div>
        </div>

        {/* P&L */}
        <div style={{marginBottom:12}}>
          <label style={LS}>Profit / Loss ({sym})</label>
          <input className="ie"
            style={{...IS,fontSize:"1.4rem",fontWeight:700,letterSpacing:-0.5,color:form.pnl!==""?pnlColor:T.muted}}
            type="number" value={form.pnl}
            onChange={e=>setForm(f=>({...f,pnl:e.target.value,win:parseFloat(e.target.value)>=0}))}
            placeholder="0.00"/>
        </div>

        {/* Notes */}
        <div style={{marginBottom:16}}>
          <label style={LS}>Notes & Reflection</label>
          <textarea className="ie" style={{...IS,minHeight:68,resize:"vertical",lineHeight:1.55}}
            value={form.notes} onChange={set("notes")} placeholder="Strategy, mindset, lessons learned…"/>
        </div>

        {/* ── Trade Setup Photo ─────────────────────────────────────────── */}
        <div style={{marginBottom:18}}>
          <label style={LS}>Trade Setup Screenshot</label>

          {form.setupImage?(
            /* Image preview */
            <div style={{position:"relative",borderRadius:10,overflow:"hidden",border:"1px solid rgba(200,169,110,0.2)"}}>
              <img src={form.setupImage} alt="Trade setup" className="img-thumb"
                style={{width:"100%",maxHeight:200,objectFit:"contain",background:"rgba(0,0,0,0.4)",display:"block"}}/>
              <div style={{position:"absolute",top:8,right:8,display:"flex",gap:6}}>
                <button onClick={()=>fileRef.current&&fileRef.current.click()}
                  style={{background:"rgba(7,9,15,0.8)",border:"1px solid rgba(200,169,110,0.3)",color:T.gold,borderRadius:6,padding:"4px 10px",cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem"}}>
                  Replace
                </button>
                <button onClick={()=>setForm(f=>({...f,setupImage:null}))}
                  style={{background:"rgba(184,64,64,0.8)",border:"none",color:"#fff",borderRadius:6,padding:"4px 10px",cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem"}}>
                  Remove
                </button>
              </div>
            </div>
          ):(
            /* Upload zone */
            <div>
              <div className="upload-zone"
                style={{border:"1.5px dashed rgba(200,169,110,0.25)",borderRadius:10,padding:"20px 16px",textAlign:"center",cursor:"pointer",transition:"all 0.2s",background:T.cellEmpty}}
                onClick={()=>fileRef.current&&fileRef.current.click()}
                onDragOver={e=>{e.preventDefault();}}
                onDrop={e=>{e.preventDefault();const f=e.dataTransfer.files[0];if(f&&f.type.startsWith("image/"))handleImageFile(f);}}>
                <div style={{fontSize:"1.8rem",marginBottom:8}}>📸</div>
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.78rem",color:T.muted,marginBottom:4}}>
                  Drag & drop your chart screenshot here
                </div>
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:"rgba(200,169,110,0.5)"}}>
                  or click to browse · PNG, JPG, WEBP
                </div>
              </div>

              {/* Camera button — shows on mobile, also works on desktop */}
              <div style={{display:"flex",gap:8,marginTop:8}}>
                <button onClick={()=>fileRef.current&&fileRef.current.click()}
                  style={{flex:1,padding:"9px",background:T.cellBorderDefault,border:"1px solid rgba(200,169,110,0.18)",borderRadius:8,color:T.muted,cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:6}}>
                  🗂 Browse Files
                </button>
                <button onClick={()=>cameraRef.current&&cameraRef.current.click()}
                  style={{flex:1,padding:"9px",background:T.cellBorderDefault,border:"1px solid rgba(200,169,110,0.18)",borderRadius:8,color:T.muted,cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:6}}>
                  📷 Take Photo
                </button>
              </div>
            </div>
          )}

          {/* Hidden file inputs */}
          <input ref={fileRef} type="file" accept="image/*" style={{display:"none"}}
            onChange={e=>{if(e.target.files[0])handleImageFile(e.target.files[0]);e.target.value="";}}/>
          <input ref={cameraRef} type="file" accept="image/*" capture="environment" style={{display:"none"}}
            onChange={e=>{if(e.target.files[0])handleImageFile(e.target.files[0]);e.target.value="";}}/>
        </div>

        {/* Actions */}
        <div style={{display:"flex",gap:8,justifyContent:"flex-end"}}>
          {existing&&(
            <button onClick={()=>onSave(null)}
              style={{padding:"9px 16px",background:"transparent",border:"1px solid rgba(184,64,64,0.35)",borderRadius:9,color:T.red,cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.78rem"}}>
              Clear Day
            </button>
          )}
          <button className="bg" onClick={save}
            style={{padding:"9px 24px",background:"linear-gradient(135deg,#c8a96e,#9b6e2a)",border:"none",borderRadius:9,color:"#07090f",fontFamily:"'DM Sans',sans-serif",fontWeight:700,cursor:"pointer",fontSize:"0.86rem"}}>
            Save Trade ✓
          </button>
        </div>
      </div>
    </Modal>
  );
}

/* ── P&L Calendar ────────────────────────────────────────────────────── */
function PnLCalendar({year,month,trades,goalSchedule,currency,onDayClick,onNav,userName}){
  const T=useT();
  const {IS,LS}=mkStyles(T);
  const sym=getSym(currency);
  const firstDay=new Date(year,month,1).getDay();
  const daysInMonth=new Date(year,month+1,0).getDate();
  const cells=[...Array(firstDay).fill(null),...Array.from({length:daysInMonth},(_,i)=>i+1)];
  const tday=todayStr();

  const allT=Object.values(trades);
  const totalPnL=allT.reduce((s,t)=>s+(t?t.pnl||0:0),0);
  const wins=allT.filter(t=>t&&t.win).length;
  const losses=allT.filter(t=>t&&!t.win).length;
  const wr=wins+losses>0?Math.round(wins/(wins+losses)*100):0;

  // Daily encouragement banner
  const encouragement=getDailyEncouragement(userName);

  return(
    <div className="fu">
      {/* Encouragement banner */}
      <div style={{background:T.encBg,border:"1px solid "+T.encBorder,borderRadius:12,padding:"12px 18px",marginBottom:18,display:"flex",alignItems:"center",gap:10}}>
        <span style={{fontSize:"1.1rem"}}>💬</span>
        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.8rem",color:"rgba(240,235,224,0.7)",fontStyle:"italic",lineHeight:1.4}}>{encouragement}</span>
      </div>

      {/* Month nav */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16}}>
        <button className="bo" onClick={()=>onNav(-1)} style={{width:37,height:37,background:T.cellBorderDefault,border:"1px solid "+T.border,borderRadius:9,color:T.gold,fontSize:"1.1rem"}}>‹</button>
        <div style={{textAlign:"center"}}>
          <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.65rem",fontWeight:600,color:T.cream}}>{MONTHS[month]}</div>
          <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.65rem",color:T.muted,letterSpacing:3}}>{year}</div>
        </div>
        <button className="bo" onClick={()=>onNav(1)} style={{width:37,height:37,background:T.cellBorderDefault,border:"1px solid "+T.border,borderRadius:9,color:T.gold,fontSize:"1.1rem"}}>›</button>
      </div>

      {/* Stats */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:7,marginBottom:16}}>
        {[
          {l:"Total P&L",v:money(sym,totalPnL),c:totalPnL>=0?T.green:T.red},
          {l:"Wins",v:String(wins),c:T.green},
          {l:"Losses",v:String(losses),c:T.red},
          {l:"Win Rate",v:wr+"%",c:T.gold},
        ].map(({l,v,c})=>(
          <div key={l} style={{background:T.statBg,border:"1px solid "+T.border,borderRadius:10,padding:"10px 11px"}}>
            <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.54rem",color:T.muted,letterSpacing:2,textTransform:"uppercase",marginBottom:4}}>{l}</div>
            <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.1rem",fontWeight:700,color:c}}>{v}</div>
          </div>
        ))}
      </div>

      {/* Day headers */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:3,marginBottom:4}}>
        {WDAYS.map(d=>(
          <div key={d} style={{textAlign:"center",fontFamily:"'DM Sans',sans-serif",fontSize:"0.56rem",color:T.muted,letterSpacing:2,padding:"3px 0"}}>{d}</div>
        ))}
      </div>

      {/* Calendar grid */}
      <div style={{display:"grid",gridTemplateColumns:"repeat(7,1fr)",gap:4}}>
        {cells.map((d,i)=>{
          if(!d) return <div key={"e"+i} style={{minHeight:72}}/>;
          const ds=fmtDate(year,month,d);
          const tr=trades[ds];
          const gs=goalSchedule?goalSchedule.find(s=>s.date===ds):null;
          const isToday=ds===tday;
          const we=isWknd(year,month,d);
          let bg=T.cellEmpty,bc=T.cellBorderDefault;
          if(tr&&tr.win===true){bg="rgba(42,157,116,0.11)";bc="rgba(42,157,116,0.27)";}
          if(tr&&tr.win===false){bg="rgba(184,64,64,0.10)";bc="rgba(184,64,64,0.27)";}
          if(isToday)bc=T.gold;
          return(
            <div key={ds} className="ch" onClick={()=>onDayClick(ds)}
              style={{minHeight:72,borderRadius:9,padding:"6px 7px",background:bg,border:"1px solid "+bc,opacity:we?0.52:1,boxShadow:isToday?"0 0 0 1px rgba(200,169,110,0.22)":undefined,position:"relative"}}>
              <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.63rem",fontWeight:isToday?700:400,color:isToday?T.gold:T.muted,marginBottom:2}}>{d}</div>
              {tr&&(
                <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"0.82rem",fontWeight:700,color:tr.win?T.green:T.red,lineHeight:1.1}}>
                  {tr.win?"+":""}{money(sym,tr.pnl)}
                </div>
              )}
              {tr&&tr.asset&&(
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.5rem",color:T.muted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>
                  {tr.direction?tr.direction+" · ":""}{tr.asset}
                </div>
              )}
              {/* Screenshot indicator */}
              {tr&&tr.setupImage&&(
                <div style={{position:"absolute",top:5,right:5,fontSize:"0.6rem"}} title="Has screenshot">📸</div>
              )}
              {gs&&!tr&&(
                <div style={{marginTop:2}}>
                  <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.58rem",fontWeight:600,color:"rgba(200,169,110,0.75)"}}>{money(sym,gs.dailyProfit)}</div>
                  <div style={{fontSize:"0.42rem",letterSpacing:1,color:"rgba(200,169,110,0.42)"}}>TARGET</div>
                </div>
              )}
              {gs&&tr&&(
                <div style={{marginTop:2}}>
                  <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.5rem",color:"rgba(200,169,110,0.4)"}}>{money(sym,gs.dailyProfit)}</div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Goal Calculator ─────────────────────────────────────────────────── */
function GoalCalc({currency,setCurrency,onGoalSet,userName}){
  const T=useT();
  const {IS,LS}=mkStyles(T);
  const sym=getSym(currency);
  const fn=userName||"Trader";
  const [dep,setDep]=useState("1000");
  const [pct,setPct]=useState("2");
  const [rv,setRv]=useState("100");
  const [dt,setDt]=useState("months");
  const [dv,setDv]=useState("6");
  const [we,setWe]=useState(false);
  const [res,setRes]=useState(null);

  const calculate=()=>{
    const d=parseFloat(dep),p=parseFloat(pct),r=parseFloat(rv),v=parseInt(dv);
    if([d,p,r,v].some(isNaN))return;
    const days=buildDays(new Date(),dt,v,we);
    const{sc,goalAmount}=calcCompound(d,p,r,days);
    setRes({deposit:d,goalAmount,sc,pct:p,rv:r});
    askNotif();
  };

  const apply=()=>{
    if(res){
      onGoalSet(res);
      pushNotif("📈 I Quit Goal Tracker","Goal set: "+money(sym,res.goalAmount)+". Let's go, "+fn+"! 🔥");
    }
  };

  return(
    <div className="fu" style={{maxWidth:680,margin:"0 auto"}}>
      <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.85rem",fontWeight:600,color:T.cream,marginBottom:5}}>
        Compound Goal Calculator
      </div>
      <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.76rem",color:T.muted,marginBottom:24,fontWeight:300}}>
        {fn !== "Trader" ? fn+", set" : "Set"} your target, define your daily edge, and let compounding do the rest.
      </div>

      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(195px,1fr))",gap:13,marginBottom:20}}>
        <div>
          <label style={LS}>Currency</label>
          <select className="ie" style={IS} value={currency} onChange={e=>setCurrency(e.target.value)}>
            {CURRENCIES.map(c=><option key={c.code} value={c.code}>{c.flag} {c.code}</option>)}
          </select>
        </div>
        <div>
          <label style={LS}>Starting Deposit ({sym})</label>
          <input className="ie" style={IS} type="number" value={dep} onChange={e=>setDep(e.target.value)} placeholder="1000"/>
        </div>
        <div>
          <label style={LS}>Daily Profit Target (%)</label>
          <input className="ie" style={IS} type="number" value={pct} onChange={e=>setPct(e.target.value)} placeholder="2"/>
        </div>
        <div>
          <label style={LS}>Reinvest Percentage (%)</label>
          <input className="ie" style={IS} type="number" value={rv} onChange={e=>setRv(e.target.value)} placeholder="100"/>
        </div>
        <div>
          <label style={LS}>Duration</label>
          <div style={{display:"flex",gap:7}}>
            <input className="ie" style={{...IS,flex:1}} type="number" value={dv} onChange={e=>setDv(e.target.value)}/>
            <select className="ie" style={{...IS,flex:1}} value={dt} onChange={e=>setDt(e.target.value)}>
              {DTYPES.map(t=><option key={t}>{t}</option>)}
            </select>
          </div>
        </div>
        <div>
          <label style={LS}>Trading Days</label>
          <div style={{display:"flex",borderRadius:9,overflow:"hidden",border:"1px solid rgba(200,169,110,0.15)"}}>
            {[false,true].map(v=>(
              <button key={String(v)} onClick={()=>setWe(v)}
                style={{flex:1,padding:"11px 5px",border:"none",cursor:"pointer",fontFamily:"'DM Sans',sans-serif",fontSize:"0.72rem",fontWeight:500,transition:"all 0.2s",background:we===v?"rgba(200,169,110,0.14)":"transparent",color:we===v?T.gold:T.muted}}>
                {v?"All 7 Days":"Weekdays"}
              </button>
            ))}
          </div>
        </div>
      </div>

      <button className="bg" onClick={calculate}
        style={{width:"100%",padding:"14px",background:"linear-gradient(135deg,#c8a96e 0%,#9b6e2a 100%)",border:"none",borderRadius:11,color:"#07090f",fontFamily:"'DM Sans',sans-serif",fontWeight:700,fontSize:"0.97rem",letterSpacing:0.5,boxShadow:"0 4px 28px rgba(200,169,110,0.22)",marginBottom:24}}>
        Calculate My Goal →
      </button>

      {res&&(
        <div className="fu" style={{background:T.card2,border:"1px solid rgba(200,169,110,0.2)",borderRadius:18,padding:"24px 26px",boxShadow:"0 8px 40px rgba(0,0,0,0.3)"}}>

          {/* Freedom Number */}
          <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.56rem",color:T.muted,letterSpacing:3,textTransform:"uppercase",marginBottom:4}}>
            {fn !== "Trader" ? fn+"'s Freedom Number" : "Your Freedom Number"}
          </div>
          <div className="sht" style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"3.2rem",fontWeight:700,letterSpacing:-1,lineHeight:1,marginBottom:6}}>
            {money(sym,res.goalAmount)}
          </div>
          <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:T.muted,marginBottom:16}}>
            Principal {money(sym,res.sc[res.sc.length-1].principal)} + Cash {money(sym,res.sc[res.sc.length-1].totalCash)}
          </div>

          {/* Summary chips */}
          <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:8,marginBottom:20}}>
            {[
              {l:"Starting Deposit",v:money(sym,res.deposit)},
              {l:"Daily Target",v:res.pct+"%"},
              {l:"Reinvest Rate",v:res.rv+"%"},
              {l:"Total Growth",v:"+"+((res.goalAmount/res.deposit-1)*100).toFixed(1)+"%"},
            ].map(({l,v})=>(
              <div key={l} style={{background:T.inputBg,borderRadius:9,padding:"10px 10px"}}>
                <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.52rem",color:T.muted,letterSpacing:1.5,textTransform:"uppercase",marginBottom:4}}>{l}</div>
                <div style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"0.95rem",fontWeight:600,color:T.gold}}>{v}</div>
              </div>
            ))}
          </div>

          {/* Formula explanation */}
          <div style={{background:T.encBg,border:"1px solid "+T.encBorder,borderRadius:10,padding:"10px 14px",marginBottom:16}}>
            <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.62rem",color:T.gold,marginBottom:4,fontWeight:600}}>How it compounds</div>
            <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:T.muted,lineHeight:1.6}}>
              Each trading day: <span style={{color:T.cream}}>Daily Profit = Principal × {res.pct}%</span>
              {"  →  "}
              <span style={{color:"#2a9d74"}}>{res.rv}% reinvested</span> back into principal
              {res.rv < 100 && (<>{" + "}<span style={{color:T.gold}}>{(100-res.rv).toFixed(0)}% taken as cash</span></>)}
            </div>
          </div>

          {/* Full schedule table */}
          <div style={{background:T.inputBg,borderRadius:10,overflow:"hidden",marginBottom:16}}>
            {/* Table header */}
            <div style={{display:"grid",gridTemplateColumns:"2fr 2fr 2fr 2fr 2fr",gap:0,padding:"8px 12px",borderBottom:"1px solid rgba(200,169,110,0.12)",background:T.encBg}}>
              {["Date","Daily Target","Principal","Cash Acc.","Total Value"].map(h=>(
                <div key={h} style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.52rem",color:T.gold,letterSpacing:1.5,textTransform:"uppercase"}}>{h}</div>
              ))}
            </div>
            {/* Scrollable rows */}
            <div style={{maxHeight:320,overflowY:"auto"}}>
              {res.sc.map((s,i)=>{
                const isLast=i===res.sc.length-1;
                const rowBg=i%2===0?"transparent":"rgba(255,255,255,0.015)";
                return(
                  <div key={i} style={{display:"grid",gridTemplateColumns:"2fr 2fr 2fr 2fr 2fr",gap:0,padding:"7px 12px",background:isLast?"rgba(200,169,110,0.08)":rowBg,borderBottom:isLast?"none":"1px solid rgba(255,255,255,0.03)"}}>
                    <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:T.muted}}>{s.date}</span>
                    <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:"#2a9d74",fontWeight:600}}>+{money(sym,s.dailyProfit)}</span>
                    <span style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"0.75rem",fontWeight:600,color:T.cream}}>{money(sym,s.principal)}</span>
                    <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:T.gold}}>{money(sym,s.totalCash)}</span>
                    <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",color:"#e2c98a",fontWeight:600}}>{money(sym,s.totalWealth)}</span>
                  </div>
                );
              })}
            </div>
            <div style={{padding:"7px 12px",borderTop:"1px solid rgba(200,169,110,0.1)",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.6rem",color:T.muted}}>{res.sc.length} trading days total</span>
              <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.6rem",color:T.muted}}>Scroll to see all ↓</span>
            </div>
          </div>

          <button className="bo" onClick={apply}
            style={{width:"100%",padding:"12px",background:"rgba(200,169,110,0.08)",color:T.gold,border:"1px solid rgba(200,169,110,0.27)",borderRadius:10,fontFamily:"'DM Sans',sans-serif",fontWeight:600,fontSize:"0.84rem",letterSpacing:0.3}}>
            📅 Apply Goal to Calendar + Enable Daily Reminders
          </button>
        </div>
      )}
    </div>
  );
}


/* ── Onboarding Slides ───────────────────────────────────────────────── */
const SLIDES = [
  {
    emoji:"📊",
    headline:"Your Trading Journal, Perfected",
    sub:"Every trade logged in seconds. Win days glow green, loss days red — your entire month visible at a glance. No spreadsheets. No guessing. Just clarity.",
    highlights:["One-tap trade logging","Photo & screenshot upload","Auto P&L calculation from entry/exit"],
    accent:"#2a9d74",
  },
  {
    emoji:"🎯",
    headline:"Your Freedom Number, Calculated",
    sub:"Set a compounding goal and watch the math work in your favor. See exactly what you need to make each trading day to hit your target — to the cent.",
    highlights:["Compound interest calculator","Daily target shown on every calendar day","Full schedule: principal, cash & total wealth"],
    accent:"#c8a96e",
  },
  {
    emoji:"📈",
    headline:"Watch Your Principal Grow in Real Time",
    sub:"Every trade you log updates your running principal instantly. Green means you are building. Your freedom number is always in sight at the top of the screen.",
    highlights:["Live principal counter in the header","Tracks deposits + logged P&L","Separate cash-out and reinvested totals"],
    accent:"#9b6e2a",
  },
  {
    emoji:"💬",
    headline:"Daily Motivation, Personalized to You",
    sub:"Your first name. Your goal. Your encouragement. Every session opens with a message built around your journey — because the mental game is half the battle.",
    highlights:["Personalized daily encouragement","Push notification reminders","Rotating messages keyed to your progress"],
    accent:"#b84040",
  },
  {
    emoji:"🔒",
    headline:"Your Data. Your Privacy.",
    sub:"Everything lives on your device. No ads. No data selling. No third-party trackers. Just you, your trades, and your path to financial freedom.",
    highlights:["100% private local storage","No ads. Ever.","Dark and light mode for any environment"],
    accent:"#c8a96e",
  },
];

function OnboardingScreen({onDone, userName}){
  const T=useT();
  const [slide,setSlide]=useState(0);
  const s=SLIDES[slide];
  const isLast=slide===SLIDES.length-1;

  return(
    <div style={{minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column",position:"relative",overflow:"hidden"}}>
      {/* Background accent blob */}
      <div style={{position:"absolute",width:500,height:500,borderRadius:"50%",
        background:"radial-gradient(circle,"+s.accent+"22 0%,transparent 70%)",
        top:"-10%",right:"-10%",transition:"background 0.5s",pointerEvents:"none"}}/>
      <div style={{position:"absolute",width:300,height:300,borderRadius:"50%",
        background:"radial-gradient(circle,"+s.accent+"11 0%,transparent 70%)",
        bottom:"10%",left:"-5%",transition:"background 0.5s",pointerEvents:"none"}}/>

      {/* Skip */}
      {!isLast&&(
        <div style={{position:"absolute",top:20,right:20,zIndex:10}}>
          <button onClick={onDone} style={{background:"transparent",border:"none",
            fontFamily:"'DM Sans',sans-serif",fontSize:"0.75rem",color:T.muted,cursor:"pointer"}}>
            Skip →
          </button>
        </div>
      )}

      {/* Slide dots */}
      <div style={{position:"absolute",top:24,left:"50%",transform:"translateX(-50%)",
        display:"flex",gap:6,zIndex:10}}>
        {SLIDES.map((_,i)=>(
          <div key={i} onClick={()=>setSlide(i)} style={{
            width:i===slide?22:6, height:6, borderRadius:3,
            background:i===slide?s.accent:T.border,
            transition:"all 0.3s",cursor:"pointer"}}/>
        ))}
      </div>

      {/* Main content */}
      <div style={{flex:1,display:"flex",flexDirection:"column",alignItems:"center",
        justifyContent:"center",padding:"80px 32px 32px",maxWidth:520,margin:"0 auto",width:"100%"}}>

        {/* Emoji icon */}
        <div className="fi" key={slide+"icon"} style={{
          width:96,height:96,borderRadius:28,
          background:"linear-gradient(135deg,"+s.accent+"33,"+s.accent+"11)",
          border:"1px solid "+s.accent+"44",
          display:"flex",alignItems:"center",justifyContent:"center",
          fontSize:"2.6rem",marginBottom:32,
          boxShadow:"0 8px 40px "+s.accent+"33"}}>
          {s.emoji}
        </div>

        {/* Headline */}
        <h1 className="fi" key={slide+"h"} style={{
          fontFamily:"'Cormorant Garamond',serif",
          fontSize:"clamp(1.8rem,5vw,2.6rem)",fontWeight:700,
          color:T.cream,textAlign:"center",lineHeight:1.15,
          marginBottom:18,whiteSpace:"pre-line"}}>
          {s.headline}
        </h1>

        {/* Sub */}
        <p className="fi" key={slide+"p"} style={{
          fontFamily:"'DM Sans',sans-serif",fontSize:"0.9rem",
          color:T.muted,textAlign:"center",lineHeight:1.7,
          marginBottom:28,maxWidth:380}}>
          {s.sub}
        </p>

        {/* Highlights */}
        <div className="fi" key={slide+"hl"} style={{width:"100%",marginBottom:36}}>
          {s.highlights.map((h,i)=>(
            <div key={i} style={{display:"flex",alignItems:"center",gap:12,
              padding:"10px 16px",marginBottom:8,
              background:s.accent+"12",
              border:"1px solid "+s.accent+"25",
              borderRadius:10}}>
              <div style={{width:20,height:20,borderRadius:"50%",flexShrink:0,
                background:s.accent,display:"flex",alignItems:"center",
                justifyContent:"center",fontSize:"0.6rem",color:"#fff",fontWeight:700}}>✓</div>
              <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.82rem",
                color:T.cream,fontWeight:500}}>{h}</span>
            </div>
          ))}
        </div>

        {/* CTA */}
        {isLast?(
          <button className="bg" onClick={onDone}
            style={{width:"100%",padding:"15px",
              background:"linear-gradient(135deg,#c8a96e,#9b6e2a)",
              border:"none",borderRadius:12,color:"#07090f",
              fontFamily:"'DM Sans',sans-serif",fontWeight:800,
              fontSize:"1rem",letterSpacing:0.5,
              boxShadow:"0 4px 28px rgba(200,169,110,0.35)"}}>
            {userName&&userName!=="Trader"
              ? "Let's go, "+userName+" →"
              : "See Pricing →"}
          </button>
        ):(
          <button className="bg" onClick={()=>setSlide(s=>s+1)}
            style={{width:"100%",padding:"15px",
              background:"linear-gradient(135deg,"+s.accent+","+s.accent+"aa)",
              border:"none",borderRadius:12,color:"#fff",
              fontFamily:"'DM Sans',sans-serif",fontWeight:700,
              fontSize:"0.97rem",letterSpacing:0.3,
              boxShadow:"0 4px 24px "+s.accent+"44"}}>
            Next →
          </button>
        )}

        {/* Back link */}
        {slide>0&&(
          <button onClick={()=>setSlide(s=>s-1)}
            style={{background:"transparent",border:"none",marginTop:14,
              fontFamily:"'DM Sans',sans-serif",fontSize:"0.75rem",
              color:T.muted,cursor:"pointer"}}>
            ← Back
          </button>
        )}
      </div>

      {/* Logo watermark */}
      <div style={{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",opacity:0.3}}>
        <Logo sz={24} showText={false}/>
      </div>
    </div>
  );
}

/* ── Paywall / Subscription Screen ───────────────────────────────────── */
const STRIPE_LINK = "https://buy.stripe.com/9B6bJ1aAW4ioeuzdsy5EY0u";

function PaywallScreen({onSubscribe, userName}){
  const T=useT();
  const fn=userName||"Trader";
  const [confirming,setConfirming]=useState(false);

  // Opens Stripe in a new tab
  const goToStripe=()=>{
    window.open(STRIPE_LINK,"_blank","noopener,noreferrer");
    // After a short delay show the "I've subscribed" confirmation panel
    setTimeout(()=>setConfirming(true), 1800);
  };

  // Called when user returns and taps "I've subscribed"
  const confirmSubscription=async()=>{
    const trialStart=Date.now();
    await dbSet("iq-subscription",{
      status:"trial",
      trialStart,
      trialEnd:trialStart+(7*24*60*60*1000),
      plan:"monthly",
    });
    onSubscribe();
  };

  return(
    <div style={{minHeight:"100vh",background:T.bg,display:"flex",flexDirection:"column",
      position:"relative",overflow:"hidden",alignItems:"center",justifyContent:"center",
      padding:"32px 24px"}}>

      {/* Background blobs */}
      <div style={{position:"absolute",width:600,height:600,borderRadius:"50%",
        background:"radial-gradient(circle,rgba(200,169,110,0.1) 0%,transparent 70%)",
        top:"-20%",right:"-20%",animation:"meshA 18s ease-in-out infinite",pointerEvents:"none"}}/>
      <div style={{position:"absolute",width:400,height:400,borderRadius:"50%",
        background:"radial-gradient(circle,rgba(155,35,53,0.08) 0%,transparent 70%)",
        bottom:"-10%",left:"-10%",animation:"meshB 22s ease-in-out infinite",pointerEvents:"none"}}/>

      <div style={{width:"100%",maxWidth:440,position:"relative",zIndex:1}}>

        {/* Logo */}
        <div style={{textAlign:"center",marginBottom:24}}>
          <Logo sz={40}/>
        </div>

        {/* ── CONFIRMATION PANEL (shown after Stripe tab opens) ── */}
        {confirming&&(
          <div className="fi" style={{background:T.card,border:"1px solid rgba(42,157,116,0.35)",
            borderRadius:16,padding:"24px",marginBottom:20,textAlign:"center"}}>
            <div style={{fontSize:"2rem",marginBottom:10}}>🎉</div>
            <h3 style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.4rem",
              fontWeight:700,color:T.cream,marginBottom:8}}>
              Payment complete?
            </h3>
            <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.8rem",
              color:T.muted,lineHeight:1.6,marginBottom:18}}>
              Once your Stripe checkout is done, tap below to unlock your dashboard.
            </p>
            <button className="bg" onClick={confirmSubscription}
              style={{width:"100%",padding:"14px",
                background:"linear-gradient(135deg,#2a9d74,#1a7a55)",
                border:"none",borderRadius:10,color:"#fff",
                fontFamily:"'DM Sans',sans-serif",fontWeight:800,
                fontSize:"0.95rem",marginBottom:10}}>
              ✓ I've Subscribed — Enter the App
            </button>
            <button onClick={()=>setConfirming(false)}
              style={{background:"transparent",border:"none",cursor:"pointer",
                fontFamily:"'DM Sans',sans-serif",fontSize:"0.72rem",color:T.muted}}>
              ← Go back
            </button>
          </div>
        )}

        {/* ── MAIN PAYWALL ── */}
        {!confirming&&(
          <>
            {/* 7-day free badge */}
            <div style={{textAlign:"center",marginBottom:20}}>
              <div style={{display:"inline-flex",alignItems:"center",gap:6,
                background:"rgba(42,157,116,0.12)",border:"1px solid rgba(42,157,116,0.3)",
                borderRadius:20,padding:"5px 16px",marginBottom:14}}>
                <span style={{fontSize:"0.8rem"}}>🎁</span>
                <span style={{fontSize:"0.72rem",fontFamily:"'DM Sans',sans-serif",
                  color:"#2a9d74",fontWeight:700,letterSpacing:1}}>7 DAYS FREE TRIAL</span>
              </div>
              <h2 style={{fontFamily:"'Cormorant Garamond',serif",
                fontSize:"clamp(1.9rem,5vw,2.4rem)",fontWeight:700,
                color:T.cream,lineHeight:1.15,marginBottom:10}}>
                {fn!=="Trader"?fn+", unlock":"Unlock"} your{" "}
                <span style={{color:"#c8a96e"}}>Freedom Number</span>
              </h2>
              <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.82rem",
                color:T.muted,lineHeight:1.6,maxWidth:340,margin:"0 auto"}}>
                Try everything free for 7 days. Then just{" "}
                <strong style={{color:T.cream}}>$5.99/month</strong>.
                Cancel anytime — no questions asked.
              </p>
            </div>

            {/* Price card */}
            <div style={{background:"linear-gradient(135deg,rgba(200,169,110,0.12),rgba(200,169,110,0.04))",
              border:"1px solid rgba(200,169,110,0.3)",borderRadius:16,
              padding:"20px 22px",marginBottom:16,textAlign:"center"}}>
              <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.62rem",
                color:T.muted,letterSpacing:2,textTransform:"uppercase",marginBottom:6}}>
                Monthly Plan
              </div>
              <div style={{display:"flex",alignItems:"baseline",justifyContent:"center",gap:4,marginBottom:4}}>
                <span style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"3rem",
                  fontWeight:700,color:"#c8a96e",lineHeight:1}}>$5.99</span>
                <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.8rem",color:T.muted}}>/month</span>
              </div>
              <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.72rem",
                color:"#2a9d74",fontWeight:600}}>
                First 7 days completely free
              </div>
            </div>

            {/* Feature list */}
            <div style={{background:T.card,border:"1px solid "+T.border,borderRadius:16,
              padding:"16px 20px",marginBottom:20}}>
              {[
                ["📊","Full P&L calendar with trade journal"],
                ["🎯","Compound goal calculator"],
                ["📈","Live principal counter in the header"],
                ["📸","Trade setup screenshot uploads"],
                ["💬","Personalized daily encouragement"],
                ["🌙","Dark & light mode"],
                ["🔒","100% private — data stays on your device"],
              ].map(([icon,label])=>(
                <div key={label} style={{display:"flex",alignItems:"center",gap:10,
                  padding:"7px 0",borderBottom:"1px solid "+T.border+":last-child{border:none}"}}>
                  <span style={{fontSize:"0.95rem",flexShrink:0}}>{icon}</span>
                  <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.8rem",
                    color:T.cream,fontWeight:500,flex:1}}>{label}</span>
                  <span style={{color:"#2a9d74",fontWeight:700}}>✓</span>
                </div>
              ))}
            </div>

            {/* Main CTA — links to Stripe */}
            <button className="bg" onClick={goToStripe}
              style={{width:"100%",padding:"16px",marginBottom:12,
                background:"linear-gradient(135deg,#c8a96e 0%,#9b6e2a 100%)",
                border:"none",borderRadius:12,color:"#07090f",
                fontFamily:"'DM Sans',sans-serif",fontWeight:800,fontSize:"1rem",
                letterSpacing:0.5,animation:"glow 3s ease-in-out infinite",
                display:"flex",alignItems:"center",justifyContent:"center",gap:8,
                boxShadow:"0 4px 28px rgba(200,169,110,0.35)"}}>
              <span>🔐</span>
              Start 7-Day Free Trial — $5.99/mo
            </button>

            {/* Already subscribed link */}
            <div style={{textAlign:"center",marginBottom:14}}>
              <button onClick={confirmSubscription}
                style={{background:"transparent",border:"none",cursor:"pointer",
                  fontFamily:"'DM Sans',sans-serif",fontSize:"0.75rem",
                  color:T.muted,textDecoration:"underline",textDecorationStyle:"dotted"}}>
                Already subscribed? Tap here to enter →
              </button>
            </div>

            {/* Fine print */}
            <div style={{textAlign:"center"}}>
              <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.68rem",
                color:T.muted,lineHeight:1.7}}>
                Secure payment via Stripe · Cancel anytime · No hidden fees
              </p>
              <p style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.62rem",
                color:T.muted,marginTop:4,opacity:0.6}}>
                By subscribing you agree to our Terms &amp; Privacy Policy
              </p>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/* ── App ─────────────────────────────────────────────────────────────── */
function App(){
  const [screen,   setScreen]   = useState("login"); // login|onboarding|paywall|app
  const [user,     setUser]     = useState(null);
  const [sub,      setSub]      = useState(null);
  const [tab,      setTab]      = useState("tracker");
  const [currency, setCurrency] = useState("USD");
  const [trades,   setTrades]   = useState({});
  const [goal,     setGoal]     = useState(null);
  const [calYear,  setCalYear]  = useState(new Date().getFullYear());
  const [calMonth, setCalMonth] = useState(new Date().getMonth());
  const [activeDay,setActiveDay]= useState(null);
  const [loaded,   setLoaded]   = useState(false);
  const [darkMode, setDarkMode] = useState(true);

  // Apply body class for dark/light
  useEffect(()=>{
    document.body.classList.toggle("light", !darkMode);
  },[darkMode]);

  useEffect(()=>{
    (async()=>{
      const[t,g,c,u,dm,sb]=await Promise.all([dbGet("iq-trades"),dbGet("iq-goal"),dbGet("iq-currency"),dbGet("iq-user"),dbGet("iq-darkmode"),dbGet("iq-subscription")]);
      if(t)setTrades(t); if(g)setGoal(g); if(c)setCurrency(c);
      if(dm!==null)setDarkMode(dm);
      if(sb)setSub(sb);
      if(u){
        setUser(u);
        // Returning user: check if they have seen onboarding
        const seenOnboard=await dbGet("iq-onboarded");
        if(!sb){setScreen("onboarding");}
        else{setScreen("app");}
        if(sb)setSub(sb);
      }
      setLoaded(true);
    })();
  },[]);

  useEffect(()=>{if(loaded)dbSet("iq-trades",trades);},[trades,loaded]);
  useEffect(()=>{if(loaded)dbSet("iq-goal",goal);},[goal,loaded]);
  useEffect(()=>{if(loaded)dbSet("iq-currency",currency);},[currency,loaded]);
  useEffect(()=>{if(loaded)dbSet("iq-darkmode",darkMode);},[darkMode,loaded]);
  useEffect(()=>{if(loaded&&sub)dbSet("iq-subscription",sub);},[sub,loaded]);

  useEffect(()=>{
    if(!goal||!loaded||screen!=="app")return;
    const fn=user?firstName(user.name):"Trader";
    const timer=setTimeout(()=>{
      const sym=getSym(currency);
      const pnl=Object.values(trades).reduce((s,t)=>s+(t?t.pnl||0:0),0);
      const wins=Object.values(trades).filter(t=>t&&t.win).length;
      const goalAmt=goal.goalAmount||0;
      pushNotif("📈 I Quit — Daily Check-In",
        fn+", your P&L is "+money(sym,pnl)+" · "+wins+" wins · Goal: "+money(sym,goalAmt)+" 🔥");
    },3000);
    return()=>clearTimeout(timer);
  },[loaded,goal,screen]);

  const navMonth=dir=>{
    let m=calMonth+dir,y=calYear;
    if(m<0){m=11;y--;}else if(m>11){m=0;y++;}
    setCalMonth(m);setCalYear(y);
  };

  const saveTrade=useCallback((ds,data)=>{
    setTrades(prev=>{
      if(data===null){const n={...prev};delete n[ds];return n;}
      return{...prev,[ds]:data};
    });
    setActiveDay(null);
  },[]);

  const T = darkMode ? DARK_THEME : LIGHT_THEME;
  const {IS, LS} = mkStyles(T);
  const sym=getSym(currency);
  const goalAmt=goal?(goal.goalAmount||0):null;
  const fn=user?firstName(user.name):"Trader";
  const trialDaysLeft=sub&&sub.status==="trial"?Math.max(0,Math.ceil((sub.trialEnd-Date.now())/(1000*60*60*24))):null;

  return(
    <ThemeCtx.Provider value={T}>
      <style dangerouslySetInnerHTML={{__html:CSS}}/>
      <FontLoader/>

      <div style={{minHeight:"100vh",background:T.bg,fontFamily:"'DM Sans',sans-serif",display:"flex",flexDirection:"column"}}>

        {screen==="login"&&(
          <LoginPage onLogin={async u=>{
            setUser(u);
            const seenOnboard=await dbGet("iq-onboarded");
            const existingSub=await dbGet("iq-subscription");
            if(existingSub){setSub(existingSub);setScreen("app");}
            else{setScreen("onboarding");}
          }}/>
        )}

        {screen==="onboarding"&&(
          <OnboardingScreen
            userName={user?firstName(user.name):"Trader"}
            onDone={async()=>{
              await dbSet("iq-onboarded",true);
              setScreen("paywall");
            }}/>
        )}

        {screen==="paywall"&&(
          <PaywallScreen
            userName={user?firstName(user.name):"Trader"}
            onSubscribe={()=>{setScreen("app");}}/>
        )}

        {screen==="app"&&(
          <>
            {/* Header */}
            <header style={{background:T.headerBg,backdropFilter:"blur(14px)",borderBottom:"1px solid "+T.border,padding:"0 20px",display:"flex",alignItems:"center",justifyContent:"space-between",height:60,position:"sticky",top:0,zIndex:100}}>
              <Logo sz={32}/>
              {trialDaysLeft!==null&&trialDaysLeft<=7&&(
                <div style={{background:"rgba(42,157,116,0.12)",border:"1px solid rgba(42,157,116,0.3)",
                  borderRadius:20,padding:"3px 10px",display:"flex",alignItems:"center",gap:4}}>
                  <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.58rem",
                    color:"#2a9d74",fontWeight:700,letterSpacing:0.5}}>
                    {trialDaysLeft===0?"Trial ends today":"Trial: "+trialDaysLeft+"d left"}
                  </span>
                </div>
              )}
              {goalAmt!==null&&(
                <div style={{textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:0}}>
                  <div style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.46rem",color:T.muted,letterSpacing:3,textTransform:"uppercase"}}>
                    {fn !== "Trader" ? fn+"'s Freedom Number" : "Freedom Number"}
                  </div>
                  <div className="sht" style={{fontFamily:"'Cormorant Garamond',serif",fontSize:"1.25rem",fontWeight:700,letterSpacing:-0.5,lineHeight:1.1}}>
                    {money(sym,goalAmt)}
                  </div>
                  {goal&&(()=>{
                    const deposit=goal.deposit||0;
                    const tradedPnL=Object.values(trades).reduce((s,t)=>s+(t&&t.pnl?t.pnl:0),0);
                    const running=deposit+tradedPnL;
                    const isUp=tradedPnL>=0;
                    return(
                      <div style={{display:"flex",alignItems:"center",gap:4,marginTop:2}}>
                        <div style={{width:5,height:5,borderRadius:"50%",background:isUp?"#2a9d74":"#b84040",flexShrink:0}}/>
                        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.62rem",fontWeight:700,color:isUp?"#2a9d74":"#b84040",letterSpacing:0.3}}>
                          {money(sym,running)}
                        </span>
                        <span style={{fontFamily:"'DM Sans',sans-serif",fontSize:"0.44rem",color:isUp?"rgba(42,157,116,0.55)":"rgba(184,64,64,0.55)",letterSpacing:1,textTransform:"uppercase"}}>principal</span>
                      </div>
                    );
                  })()}
                </div>
              )}
              <div style={{display:"flex",alignItems:"center",gap:9}}>
                <div style={{width:31,height:31,borderRadius:"50%",flexShrink:0,background:"linear-gradient(135deg,#c8a96e,#9b6e2a)",display:"flex",alignItems:"center",justifyContent:"center",fontFamily:"'Cormorant Garamond',serif",fontWeight:700,fontSize:"0.88rem",color:"#07090f"}}>
                  {user&&user.name?user.name.charAt(0):"T"}
                </div>
                <div style={{display:"flex",flexDirection:"column"}}>
                  <span style={{fontSize:"0.71rem",color:T.cream,fontWeight:500,maxWidth:90,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>
                    {fn}
                  </span>
                  <span style={{fontSize:"0.56rem",color:T.muted,cursor:"pointer"}} onClick={()=>setScreen("login")}>Sign out</span>
                </div>
              </div>

              {/* Theme toggle */}
              <button onClick={()=>setDarkMode(d=>!d)}
                title={darkMode?"Switch to Light Mode":"Switch to Dark Mode"}
                style={{background:darkMode?"rgba(240,235,224,0.07)":"rgba(155,110,42,0.12)",
                  border:"1px solid "+(darkMode?"rgba(240,235,224,0.12)":"rgba(155,110,42,0.25)"),
                  borderRadius:20, padding:"5px 11px", cursor:"pointer",
                  display:"flex", alignItems:"center", gap:5,
                  fontFamily:"'DM Sans',sans-serif", fontSize:"0.68rem",
                  color:T.muted, flexShrink:0,
                  transition:"all 0.25s"}}>
                <span style={{fontSize:"0.9rem"}}>{darkMode?"☀️":"🌙"}</span>
                <span style={{display:"none"}}>{darkMode?"Light":"Dark"}</span>
              </button>
            </header>

            {/* Tabs */}
            <div style={{background:T.tabBg,borderBottom:"1px solid "+T.border,padding:"0 20px",display:"flex"}}>
              {[["tracker","📊  P&L Tracker"],["calc","⚡  Goal Calculator"]].map(([id,lbl])=>(
                <button key={id} className="tb" onClick={()=>setTab(id)}
                  style={{background:"transparent",border:"none",padding:"12px 18px",fontFamily:"'DM Sans',sans-serif",fontSize:"0.74rem",fontWeight:500,letterSpacing:0.5,color:tab===id?T.gold:T.muted,borderBottom:tab===id?"2px solid "+T.gold:"2px solid transparent"}}>
                  {lbl}
                </button>
              ))}
            </div>

            {/* Content */}
            <main style={{flex:1,padding:"24px 18px",maxWidth:960,margin:"0 auto",width:"100%"}}>
              {tab==="tracker"
                ?<PnLCalendar year={calYear} month={calMonth} trades={trades}
                    goalSchedule={goal?(goal.sc||goal.schedule):null} currency={currency}
                    onDayClick={setActiveDay} onNav={navMonth} userName={fn}/>
                :<GoalCalc currency={currency} setCurrency={setCurrency}
                    onGoalSet={g=>{setGoal(g);setTab("tracker");}} userName={fn}/>
              }
            </main>

            {/* Footer */}
            <footer style={{borderTop:"1px solid "+T.border,padding:"11px 20px",display:"flex",alignItems:"center",justifyContent:"space-between",background:T.footerBg}}>
              <span style={{fontSize:"0.6rem",color:"rgba(240,235,224,0.18)",letterSpacing:1}}>
                I Quit Goal Tracker · Your data stays private
              </span>
              <button className="bo" onClick={()=>{askNotif();pushNotif("📈 I Quit Goal Tracker","One day closer to freedom, "+fn+". Keep going! 🔥");}}
                style={{background:"transparent",border:"1px solid "+T.border,color:T.muted,borderRadius:20,padding:"5px 13px",fontSize:"0.66rem",letterSpacing:0.5,fontFamily:"'DM Sans',sans-serif"}}>
                🔔 Enable Reminders
              </button>
            </footer>

            {activeDay&&(
              <TradeModal dateStr={activeDay} existing={trades[activeDay]} currency={currency}
                onSave={data=>saveTrade(activeDay,data)} onClose={()=>setActiveDay(null)}/>
            )}
          </>
        )}
      </div>
    </ThemeCtx.Provider>
  );
}

// Mount the app
const rootEl = document.getElementById("root");
const root = ReactDOM.createRoot(rootEl);
root.render(React.createElement(App));
