// Shared · Strategy Guide — the four XAU/USD strategies, shown at the
// right depth for the audience. window.StrategyGuide({ mode, tier }).
//   mode  = 'admin' | 'coach' | 'student'
//   tier  = for students, the level to show ('basic'|'inter'|'adv').
//           Admin/Coach see full technical tables regardless.
// Depends on brand.css tokens (already loaded in both dashboards).
(function(){
const { useState, useEffect } = React;
const COMPLIANCE = "Demo signal-testing — not financial advice.";

const SG_STRATS = [
  { key:'A', name:'Trend + Pullback', color:'#f5d97a', style:'Trend-following · pullback entry', freq:'Lowest frequency',
    student:{
      basic:"Waits for gold to be clearly trending, then joins the move after a small dip — like catching a wave once it pulls back. It's the most patient of the four, so it takes the fewest trades.",
      inter:"Strategy A only trades in the direction of the bigger trend. It waits for gold to pull back to a fair price inside that trend, checks that the 5-minute direction and the 15-minute bias both point the same way, then enters as the move continues. Because it needs everything lined up, it trades the least often — but with the most agreement.",
      adv:"Strategy A is a trend-following, pullback-entry scalp. It reads direction from fast and slow EMAs on the 5-minute chart and uses the 5-minute EMA50 as the pullback anchor, only firing when the 5-minute direction and the 15-minute bias agree on the same side. A short RSI keeps it from entering when price is already stretched, and a closed 5-minute confirmation candle is required before entry. It's the most selective and lowest-frequency of the four."
    },
    teach:"Frame A as the ‘patient’ strategy. Emphasise alignment: it only acts when the 5-minute entry direction and the 15-minute bias agree, which is why it's rare but clean. It's a great way to teach students that choosing NOT to trade is a valid, disciplined decision.",
    params:[
      ['Type','Trend-following, pullback entry (the most selective of the four)'],
      ['Indicators','EMA9 / EMA21 (direction), EMA50 (pullback anchor), RSI7 (exhaustion) — all on 5M'],
      ['Direction gate','5M EMA9/21 direction AND the 15M bias must agree with the side'],
      ['Pullback rule','Price within ~0.25% of the 5M EMA50'],
      ['Exhaustion rule','RSI7 between 30–70 (room to move, not already extreme)'],
      ['Confirmation','5M candle, body ≥ 30% of its range'],
      ['Fires when','All 3 confluences pass + confirmation candle closes'],
    ],
    glance:{ style:'Trend + pullback', indicators:'EMA9/21/50, RSI7', direction:'5M + 15M bias', chop:'Pullback + RSI room', confirmation:'5M candle ≥30%', frequency:'Low' },
  },
  { key:'B', name:'Bollinger Bands + ADX', color:'#7aa2f7', style:'Trend-following · band pullback', freq:'Medium frequency',
    student:{
      basic:"Trades gold back toward the middle when it stretches to the edge of its normal range — but only when the market is clearly trending, not choppy.",
      inter:"Strategy B looks for gold to stretch toward the edge of its usual range, then trade back toward the middle. It only acts when the trend is strong enough to be worth trading — a strength check keeps it out of choppy, going-nowhere markets. Which half of the range price sits in decides the direction.",
      adv:"Strategy B trades Bollinger Band position filtered by trend strength, on the 5-minute chart. It needs ADX above a threshold to confirm a real trend and avoid chop, then sells in the upper half of the band and buys in the lower half. A closed 5-minute confirmation candle is required. It is deliberately simple — two conditions, no higher-timeframe filter."
    },
    teach:"Use B to teach ‘trend strength + location.’ The band shows location (price is stretched); ADX shows whether the trend is strong enough to be worth trading. It's the clearest example of why we stay out of choppy markets — and the simplest of the four, which makes it a good first strategy to explain.",
    params:[
      ['Type','Trend-strength filter + band position'],
      ['Indicators','Bollinger Bands (20, 2) and ADX (14), both on 5M'],
      ['Strength gate','ADX ≥ 25 (anti-chop filter)'],
      ['Direction gate','None — band position decides the side'],
      ['Position rule','SELL when price is in the upper half of the BB; BUY in the lower half'],
      ['Confirmation','5M candle, body ≥ 30% of its range'],
      ['Fires when','Strong trend + band position + confirmation candle'],
    ],
    glance:{ style:'Trend strength + band', indicators:'Bollinger + ADX', direction:'None', chop:'ADX ≥ 25', confirmation:'5M candle ≥30%', frequency:'Medium' },
  },
  { key:'C', name:'Stochastic RSI', color:'#34d399', style:'Momentum oscillator · mean-reversion', freq:'Highest frequency',
    student:{
      basic:"Watches for gold to swing too far in one direction, then trades the snap-back the other way. It's the quickest of the four to react, so it takes the most trades.",
      inter:"This one looks for moments when gold has stretched too far, too fast — overbought or oversold — and enters as momentum starts to turn back. Because it's watching for quick turns, it fires more often than the others and can go against the wider trend.",
      adv:"Strategy C is a standalone Stochastic RSI system on the 5-minute chart. It triggers when %K crosses %D emerging from the 70/30 zone, with no trend filter — counter-trend entries are allowed by design. A 5-minute confirmation candle is required before entry. It's the highest-frequency of the four and is meant to catch turning points."
    },
    teach:"Use C to teach momentum and mean-reversion, and as a contrast to A. Stress that it's counter-trend by design and the highest-frequency — then remind students that more trades ≠ better. It's always about the quality of the setup, not the count.",
    params:[
      ['Type','Momentum oscillator, mean-reversion (standalone)'],
      ['Indicator','Stochastic RSI (8 / 8 / 3 / 3) on 5M'],
      ['Bands','70 / 30 (overbought / oversold)'],
      ['Direction gate','None — pure oscillator, counter-trend allowed'],
      ['Chop filter','None'],
      ['Trigger','%K crosses %D emerging from the 70/30 zone (BUY out of oversold, SELL out of overbought)'],
      ['Confirmation','5M candle, body ≥ 30% of its range'],
    ],
    glance:{ style:'Momentum reversal', indicators:'Stochastic RSI 8/8/3/3', direction:'None (counter-trend OK)', chop:'None', confirmation:'5M candle ≥30%', frequency:'High' },
  },
  { key:'D', name:'SMI Supply & Demand', color:'#c084fc', style:'Institutional supply & demand · scored', freq:'Selective',
    student:{
      basic:"Looks for the price areas where big institutions likely bought or sold before, waits for gold to come back to one of those areas, and only trades if it gets clearly rejected there. It's fussy on purpose — it scores every setup and skips anything that doesn't earn a high enough mark.",
      inter:"Strategy D works from supply and demand zones — areas where a large, fast move started, which suggests serious money was involved. It marks those zones on the 15-minute chart, then waits for price to return to one. Before entering it checks several things at once: is the bigger trend agreeing, has price retraced to the right depth, has market structure broken, and did the candle at the zone reject the level with a long wick. Each check earns points, and it only trades when the total is high enough. It also only runs during the London and New York sessions.",
      adv:"Strategy D is a scored supply-and-demand system. Zones are identified on the 15-minute chart as the origin candle before a displacement move of at least 1.5× ATR, and remain valid until price trades more than 1× ATR beyond them. Higher-timeframe bias comes from a stacked 15-minute EMA 20/50/200. Market structure (BOS/CHOCH) is read on the 5-minute entry chart, along with liquidity sweeps and fair value gaps. Six weighted factors produce a score out of 100 and the strategy only fires at 80 or above. Unlike A, B and C it does not use the shared body-confirmation candle — it requires a rejection candle whose wick is at least 1.3× its body, because it is entering against the immediate move rather than with it. Restricted to London and New York sessions."
    },
    teach:"Use D to introduce institutional / smart-money thinking, and as the counterweight to C. The key teaching point is patience through scoring: D grades every setup and refuses anything below 80, so students see a system that says no far more often than it says yes. It's also the clearest example of confluence — no single factor is enough on its own. Worth noting the zone requirement is effectively mandatory: without a valid supply or demand zone, no combination of the other factors can reach the threshold.",
    params:[
      ['Type','Institutional supply & demand with scored confluence'],
      ['Zones','15M — origin candle before a ≥ 1.5× ATR displacement, still unmitigated'],
      ['Zone tolerance','0.5 price-unit buffer · invalidated only past 1× ATR beyond the zone'],
      ['Bias','15M EMA 20 / 50 / 200 fully stacked (not just a cross)'],
      ['Fibonacci','0.5 – 0.79 retracement of the displacement leg'],
      ['Structure','5M — BOS / CHOCH break of the last swing point'],
      ['Scoring','Bias 20 · Zone 25 · Fib 20 · Structure 20 · Liquidity sweep 8 · FVG 7'],
      ['Fires when','Score ≥ 80/100 + rejection candle (wick ≥ 1.3× body)'],
      ['Session','London or New York only'],
    ],
    glance:{ style:'Supply & demand (scored)', indicators:'S&D zones, EMA 20/50/200, Fib, BOS/CHOCH', direction:'15M stacked EMA', chop:'Score ≥ 80 threshold', confirmation:'5M rejection wick ≥1.3× body', frequency:'Selective' },
  },
];
const SG_SHARED = [
  ['Timeframe stack','15M bias → 5M confluence → 5M entry candle'],
  ['Confirmation (A/B/C)','Last closed 5M candle must close in the trade direction, body ≥ 30% of range'],
  ['Confirmation (D)','Own gate — 5M rejection candle, wick ≥ 1.3× body (reversal, not continuation)'],
  ['Simulated lot','0.08'],
  ['Stop loss','14 pts  (−$112)'],
  ['Take profit','TP1 +14 pts → moves stop to breakeven · TP2 +22 pts  (+$176)'],
  ['Outcomes','LOSS_SL (−14) · BE (0, reversed after TP1) · WIN_TP2 (+22)'],
  ['Gates','Market-hours + high-impact USD news blackout (all four) · D additionally London/NY only'],
];
const SG_INTERNALS = [
  ['5M scalp reset','The intraday experiment (15-minute entries, 4-hour regime gates, wide 80/150pt targets, multi-hour holds) has been reverted. A, B and C are back on the documented 5-minute scalp stack.'],
  ['Higher-timeframe gates','The 4-hour regime gate has been removed from A and B — it was added during the intraday build and was never part of the original specification. A still checks the 15-minute bias; B now uses band position alone.'],
  ['Strategy D','New. A scored supply-and-demand system, added because the three existing strategies were all momentum-based and none traded institutional zones. It is the only strategy with its own confirmation rule and its own session restriction.'],
  ['Duplicate-close guard','Dedupe protection so a single trade can’t be closed/counted twice (data integrity).'],
  ['Outcomes model','Every trade resolves to exactly one of LOSS_SL, BE (after TP1) or WIN_TP2 — no partial/ambiguous states.'],
];
const SG_TIERS = [ ['basic','Basic'], ['inter','Intermediate'], ['adv','Advanced'] ];
const SG_TIDX = { basic:0, inter:1, adv:2 };

const SG_CSS = `
.sg-wrap{--sg-max:960px;}
.sg-top{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:6px;}
.sg-compliance{display:inline-flex;align-items:center;gap:8px;font-family:var(--font-mono);font-size:.72rem;letter-spacing:.05em;color:var(--gold-2);background:var(--gold-soft);border:1px solid var(--border-gold);padding:6px 13px;border-radius:999px;}
.sg-lead{color:var(--ink-dim);font-size:1rem;max-width:660px;line-height:1.6;margin:6px 0 22px;}
.sg-controls{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin-bottom:6px;}
.sg-ctl-label{font-family:var(--font-mono);font-size:.66rem;letter-spacing:.14em;text-transform:uppercase;color:var(--ink-faint);}
.sg-seg{display:inline-flex;background:var(--navy-950);border:1px solid var(--border);border-radius:999px;padding:4px;gap:3px;}
.sg-seg button{border:none;background:none;cursor:pointer;font-family:var(--font-body);font-weight:600;font-size:.86rem;color:var(--ink-faint);padding:8px 16px;border-radius:999px;transition:all .18s;white-space:nowrap;}
.sg-seg button:hover{color:var(--ink-dim);}
.sg-seg button.on{background:var(--gold-soft);color:var(--gold-2);border:1px solid var(--border-gold);}
.sg-viewnote{font-size:.85rem;color:var(--ink-faint);margin:12px 0 22px;max-width:680px;line-height:1.55;}
.sg-card{background:linear-gradient(165deg,var(--surface-2),var(--surface));border:1px solid var(--border);border-radius:var(--radius);padding:24px 24px;margin-bottom:16px;position:relative;overflow:hidden;}
.sg-card .sg-accent{position:absolute;top:0;left:0;right:0;height:3px;}
.sg-head{display:flex;align-items:center;gap:13px;flex-wrap:wrap;}
.sg-letter{width:38px;height:38px;border-radius:10px;display:grid;place-items:center;font-family:var(--font-mono);font-weight:700;font-size:1.05rem;color:#0a1124;flex-shrink:0;}
.sg-head h3{font-family:var(--font-display);font-size:1.35rem;margin:0;font-weight:600;}
.sg-style{font-family:var(--font-mono);font-size:.72rem;color:var(--ink-faint);}
.sg-freq{margin-left:auto;font-family:var(--font-mono);font-size:.66rem;letter-spacing:.06em;text-transform:uppercase;color:var(--ink-dim);background:var(--navy-950);border:1px solid var(--border);padding:5px 11px;border-radius:999px;}
.sg-prose{color:var(--ink);font-size:1.02rem;line-height:1.7;max-width:660px;margin:14px 0 0;}
.sg-depth{display:flex;gap:5px;margin-top:15px;}
.sg-depth span{height:4px;width:32px;border-radius:2px;background:var(--border);}
.sg-depth span.on{background:var(--gold-2);}
.sg-scroll{overflow-x:auto;}
table.sg-params{width:100%;border-collapse:collapse;margin-top:15px;}
table.sg-params td{padding:10px 12px;border-top:1px solid var(--border);vertical-align:top;font-size:.88rem;}
table.sg-params td.k{font-family:var(--font-mono);font-size:.72rem;letter-spacing:.04em;text-transform:uppercase;color:var(--ink-faint);width:185px;}
table.sg-params td.v{color:var(--ink-dim);}
.sg-teach{margin-top:15px;background:var(--gold-soft);border:1px solid var(--border-gold);border-radius:var(--radius-sm);padding:13px 15px;}
.sg-teach .tl{font-family:var(--font-mono);font-size:.66rem;letter-spacing:.1em;text-transform:uppercase;color:var(--gold-2);margin-bottom:6px;}
.sg-teach p{margin:0;color:var(--ink);font-size:.9rem;line-height:1.6;}
.sg-panel{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px 22px;margin-bottom:16px;}
.sg-panel h4{font-family:var(--font-display);font-size:1.15rem;margin:0 0 3px;}
.sg-panel .sub{color:var(--ink-faint);font-size:.82rem;margin:0 0 14px;}
.sg-fw{display:grid;gap:8px;}
.sg-fw-row{display:grid;grid-template-columns:200px 1fr;gap:14px;font-size:.88rem;}
.sg-fw-row .k{font-family:var(--font-mono);font-size:.72rem;color:var(--ink-faint);text-transform:uppercase;letter-spacing:.04em;}
.sg-fw-row .v{color:var(--ink-dim);}
table.sg-glance{width:100%;border-collapse:collapse;font-size:.84rem;}
table.sg-glance th,table.sg-glance td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:top;}
table.sg-glance thead th{font-family:var(--font-mono);font-size:.66rem;letter-spacing:.08em;text-transform:uppercase;color:var(--ink-faint);font-weight:500;}
table.sg-glance td.rowlbl{font-family:var(--font-mono);font-size:.7rem;color:var(--ink-faint);text-transform:uppercase;}
table.sg-glance td strong{color:var(--ink);}
.sg-foot{margin-top:24px;padding-top:18px;border-top:1px solid var(--border);color:var(--ink-faint);font-size:.79rem;line-height:1.6;}
@media (max-width:680px){ .sg-fw-row{grid-template-columns:1fr;gap:2px;} table.sg-params td.k{width:120px;} }
`;

function injectCSS(){ if(document.getElementById('sg-css')) return; const s=document.createElement('style'); s.id='sg-css'; s.textContent=SG_CSS; document.head.appendChild(s); }

function SGCard({s, mode, tier}){
  const isStudent = mode==='student';
  const showTables = mode==='admin' || mode==='coach';
  const showTeach = mode==='coach';
  const depth = isStudent ? (SG_TIDX[tier]+1) : 3;
  return <div className="sg-card">
    <div className="sg-accent" style={{background:s.color}}></div>
    <div className="sg-head">
      <span className="sg-letter" style={{background:s.color}}>{s.key}</span>
      <div><h3>Strategy {s.key} — {s.name}</h3><div className="sg-style">{s.style}</div></div>
      <span className="sg-freq">{s.freq}</span>
    </div>
    {isStudent && <React.Fragment>
      <p className="sg-prose">{s.student[tier]}</p>
      <div className="sg-depth" title="Explanation depth">{[0,1,2].map(i=><span key={i} className={i<depth?"on":""}></span>)}</div>
    </React.Fragment>}
    {showTables && <div className="sg-scroll"><table className="sg-params"><tbody>
      {s.params.map(([k,v])=>(<tr key={k}><td className="k">{k}</td><td className="v">{v}</td></tr>))}
    </tbody></table></div>}
    {showTeach && <div className="sg-teach"><div className="tl">How to explain this to students</div><p>{s.teach}</p></div>}
  </div>;
}

function SGGlance(){
  const rows=[['Style','style'],['Indicators','indicators'],['Direction gate','direction'],['Chop filter','chop'],['Confirmation','confirmation'],['Frequency','frequency']];
  return <div className="sg-panel">
    <h4>At a glance</h4><p className="sub">The four strategies side by side.</p>
    <div className="sg-scroll"><table className="sg-glance">
      <thead><tr><th></th>{SG_STRATS.map(s=><th key={s.key}><span style={{color:s.color}}>■</span> Strategy {s.key}</th>)}</tr></thead>
      <tbody>{rows.map(([label,field])=>(<tr key={field}><td className="rowlbl">{label}</td>{SG_STRATS.map(s=><td key={s.key}><strong>{s.glance[field]}</strong></td>)}</tr>))}</tbody>
    </table></div>
  </div>;
}

function SGFramework(){
  return <React.Fragment>
    <div className="sg-panel"><h4>Shared framework</h4><p className="sub">Applies to all four strategies · 5M scalp build (2026-07-31)</p>
      <div className="sg-fw">{SG_SHARED.map(([k,v])=>(<div className="sg-fw-row" key={k}><span className="k">{k}</span><span className="v">{v}</span></div>))}</div></div>
    <div className="sg-panel"><h4>Engine internals</h4><p className="sub">Engine-level details — Admin &amp; Coach reference.</p>
      <div className="sg-fw">{SG_INTERNALS.map(([k,v])=>(<div className="sg-fw-row" key={k}><span className="k">{k}</span><span className="v">{v}</span></div>))}</div></div>
  </React.Fragment>;
}

const SG_NOTE = {
  admin:"Full technical configuration — every parameter, the shared risk framework, and the engine internals. Nothing hidden.",
  coach:"The full technical configuration, plus a short teaching note on each strategy so you can explain it at the right level.",
  student:"Plain-language explanations, matched to your level. The same four strategies — the depth grows as you unlock higher tiers.",
};

// StrategyGuide({ mode, tier, tierLabel })
//   mode 'admin'|'coach'|'student'. For students, tier is fixed to their level
//   (basic|inter|adv) — no switcher (auto-depth). Admin/coach show full tables.
function StrategyGuide({ mode, tier, tierLabel }){
  useEffect(()=>{ injectCSS(); },[]);
  mode = mode || 'admin';
  const isStudent = mode==='student';
  const t = isStudent ? (tier||'basic') : 'adv';
  const showFramework = mode==='admin' || mode==='coach';
  const showGlance = mode==='coach' || (isStudent && t==='adv');

  return <div className="sg-wrap">
    <div className="sg-top">
      <div>
        <span className="eyebrow" style={{color:'var(--gold-2)'}}>XAU/USD signal-testing · strategy guide</span>
        <h2 style={{fontFamily:'var(--font-display)',fontSize:'1.7rem',fontWeight:600,margin:'6px 0 0'}}>How the four strategies think</h2>
      </div>
      <span className="sg-compliance">● {COMPLIANCE}</span>
    </div>
    <p className="sg-lead">Chart Growth Hub tests four independent gold strategies. Each runs separately — opening, tracking and closing its own trades. Here's what each does, shown at the right depth for you.</p>

    {isStudent && <p className="sg-viewnote">{SG_NOTE.student}{tierLabel? ' Showing the '+tierLabel+' level.':''}</p>}
    {!isStudent && <p className="sg-viewnote">{SG_NOTE[mode]}</p>}

    {SG_STRATS.map(s=><SGCard key={s.key} s={s} mode={mode} tier={t} />)}
    {showGlance && <SGGlance/>}
    {showFramework && <SGFramework/>}

    <div className="sg-foot"><strong style={{color:'var(--ink-dim)'}}>{COMPLIANCE}</strong> These are learning illustrations of how each strategy makes decisions — not trading results, earnings claims, or signals to copy. Trading gold carries substantial risk.</div>
  </div>;
}

window.StrategyGuide = StrategyGuide;
})();
