// Shared · Advanced XAU/USD risk calculator — window.RiskCalc
// Lot size + stop / target (in $ price movement) → dollar risk, % of
// account risked, reward and R:R, with a safe / caution / danger banner.
// Gold contract = 100 oz per 1.00 lot, so a $1.00 price move = $100 per lot.
// Thresholds: Safe ≤ 2% · Caution 2–5% · Danger > 5%.
(function(){
const { useState, useMemo } = React;

const CONTRACT = 100;           // troy oz per 1.00 lot (standard XAUUSD)
const LS_KEY   = 'cg_riskcalc_v1';
const usd = n => (n<0?'-':'')+'$'+Math.abs(Number(n)||0).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2});

function load(){ try{ return JSON.parse(localStorage.getItem(LS_KEY)||'{}'); }catch(e){ return {}; } }

function band(pct){
  if(pct<=2)  return { key:'safe',    label:'Safe',    color:'var(--green)',  bg:'rgba(52,211,153,.10)',  border:'rgba(52,211,153,.35)', msg:'Within a healthy risk range.' };
  if(pct<=5)  return { key:'caution', label:'Caution', color:'var(--gold-2)', bg:'var(--gold-soft)',       border:'var(--border-gold)',   msg:'Above the usual 1–2% guideline — size down if you can.' };
  return              { key:'danger',  label:'Too much',color:'var(--red)',    bg:'rgba(248,113,113,.10)', border:'rgba(248,113,113,.4)', msg:'You are risking too much on one trade. Reduce your lot size or widen your account.' };
}

function Inp({label, value, onChange, placeholder, prefix, suffix}){
  return <div className="field">
    <label>{label}</label>
    <div style={{position:'relative',display:'flex',alignItems:'center'}}>
      {prefix && <span style={{position:'absolute',left:13,color:'var(--ink-faint)',fontFamily:'var(--font-mono)',fontSize:'.9rem',pointerEvents:'none'}}>{prefix}</span>}
      <input type="number" inputMode="decimal" value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
        style={{width:'100%',padding:'13px 14px',paddingLeft:prefix?26:14,paddingRight:suffix?54:14,borderRadius:'var(--radius-sm)',background:'var(--navy-950)',border:'1px solid var(--border)',color:'var(--ink)',fontFamily:'var(--font-mono)',fontSize:'.98rem'}}/>
      {suffix && <span style={{position:'absolute',right:13,color:'var(--ink-faint)',fontFamily:'var(--font-mono)',fontSize:'.76rem',pointerEvents:'none'}}>{suffix}</span>}
    </div>
  </div>;
}

function Stat({label, value, color, sub}){
  return <div style={{background:'var(--surface)',border:'1px solid var(--border)',borderRadius:'var(--radius-sm)',padding:'14px 16px'}}>
    <div style={{fontSize:'.68rem',color:'var(--ink-faint)',fontFamily:'var(--font-mono)',letterSpacing:'.08em',textTransform:'uppercase'}}>{label}</div>
    <div style={{fontFamily:'var(--font-mono)',fontSize:'1.5rem',fontWeight:600,color:color||'var(--ink)',marginTop:4,lineHeight:1.1}}>{value}</div>
    {sub && <div style={{fontSize:'.72rem',color:'var(--ink-faint)',marginTop:3}}>{sub}</div>}
  </div>;
}

function RiskCalc(){
  const saved = load();
  const [bal,setBal]   = useState(saved.bal ?? '');
  const [lot,setLot]   = useState(saved.lot ?? '0.03');
  const [sl,setSl]     = useState(saved.sl ?? '');
  const [tp,setTp]     = useState(saved.tp ?? '');

  useMemo(()=>{ try{ localStorage.setItem(LS_KEY, JSON.stringify({bal,lot,sl,tp})); }catch(e){} },[bal,lot,sl,tp]);

  const B=parseFloat(bal)||0, L=parseFloat(lot)||0, S=parseFloat(sl)||0, T=parseFloat(tp)||0;
  const riskUSD   = L*CONTRACT*S;
  const rewardUSD = L*CONTRACT*T;
  const riskPct   = B>0 ? riskUSD/B*100 : 0;
  const rr        = S>0 ? T/S : 0;
  const slPips    = S/0.1, tpPips = T/0.1;   // gold "pip" = $0.10 move
  const b = band(riskPct);
  const has = B>0 && L>0 && S>0;

  return <div>
    <div style={{display:'flex',alignItems:'flex-start',gap:14,marginBottom:20,flexWrap:'wrap'}}>
      <div>
        <span className="eyebrow" style={{color:'var(--gold-2)'}}>XAU/USD · Risk calculator</span>
        <p style={{color:'var(--ink-dim)',fontSize:'.94rem',maxWidth:620,marginTop:6}}>Enter your account size, lot and stop distance to see the exact dollar risk and the percentage of your account on the line. Gold trades in <strong>100&nbsp;oz</strong> per 1.00 lot — a <strong>$1.00</strong> price move is <strong>$100</strong> per lot.</p>
      </div>
    </div>

    <div style={{display:'grid',gridTemplateColumns:'minmax(0,1fr) minmax(0,1.1fr)',gap:22,alignItems:'start'}} className="calc-grid">
      {/* inputs */}
      <div style={{background:'linear-gradient(165deg,var(--surface-2),var(--surface))',border:'1px solid var(--border)',borderRadius:'var(--radius)',padding:'22px 22px',display:'grid',gap:14}}>
        <Inp label="Account balance" value={bal} onChange={setBal} placeholder="1000" prefix="$"/>
        <Inp label="Lot size" value={lot} onChange={setLot} placeholder="0.03" suffix="lots"/>
        <Inp label="Stop loss (price distance)" value={sl} onChange={setSl} placeholder="3.50" prefix="$"/>
        <Inp label="Take profit (price distance)" value={tp} onChange={setTp} placeholder="5.00" prefix="$"/>
        <div style={{fontFamily:'var(--font-mono)',fontSize:'.72rem',color:'var(--ink-faint)',lineHeight:1.6}}>
          Distances are the gold price movement in dollars. {S>0 && <span>SL ≈ {Math.round(slPips)} pips</span>}{S>0&&T>0?' · ':''}{T>0 && <span>TP ≈ {Math.round(tpPips)} pips</span>}
        </div>
      </div>

      {/* results */}
      <div style={{display:'grid',gap:14}}>
        <div style={{border:'1px solid '+b.border,background:b.bg,borderRadius:'var(--radius)',padding:'18px 20px'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',gap:12,flexWrap:'wrap'}}>
            <span style={{fontFamily:'var(--font-mono)',fontSize:'.72rem',letterSpacing:'.1em',textTransform:'uppercase',color:b.color}}>Risk level · {b.label}</span>
            <span style={{fontFamily:'var(--font-mono)',fontSize:'2rem',fontWeight:700,color:b.color,lineHeight:1}}>{has?riskPct.toFixed(2):'0.00'}%</span>
          </div>
          <p style={{color:'var(--ink-dim)',fontSize:'.86rem',margin:'10px 0 0'}}>{has? b.msg : 'Fill in balance, lot and stop loss to calculate.'}</p>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
          <Stat label="Dollar risk"   value={usd(riskUSD)}   color="var(--red)"   sub={has?('of '+usd(B)+' account'):null}/>
          <Stat label="Potential reward" value={usd(rewardUSD)} color="var(--green)" sub={T>0?null:'set a take profit'}/>
          <Stat label="Reward : risk" value={rr>0?('1 : '+rr.toFixed(2)):'—'} color="var(--gold-2)" sub={rr>0?(rr>=2?'strong':rr>=1?'ok':'thin'):null}/>
          <Stat label="Per 0.01 lot" value={S>0?usd(0.01*CONTRACT*S):'—'} sub="risk at this stop"/>
        </div>
      </div>
    </div>

    <p style={{fontSize:'.74rem',color:'var(--ink-faint)',fontFamily:'var(--font-mono)',marginTop:18,lineHeight:1.6}}>
      Educational tool · figures assume a standard 100&nbsp;oz XAU/USD contract and your broker's USD account. Not financial advice.
    </p>

    <style>{`@media (max-width:760px){ .calc-grid{ grid-template-columns:1fr !important; } }`}</style>
  </div>;
}

window.RiskCalc = RiskCalc;
})();
