I am not a trader. I don't follow markets. I wouldn't know a sector rotation from a roundabout. But the world is on fire right now — the Strait of Hormuz is effectively closed, oil prices are swinging wildly, and the news is full of talk about war, money, and who benefits from both.I know nothing about investing. I watched one video, got curious, and asked an AI to teach me.

In the middle of all this I came across a short Facebook video of a Jewish rabbi explaining, calmly and matter-of-factly, how people in business pay close attention to geopolitical crises because certain economic patterns become almost inevitable. Defense companies receive emergency orders. Energy prices spike on supply fears. Later, when the shooting stops, construction firms benefit from rebuilding. He described it almost like reading a recurring chapter in a book — destruction, then repair, then recovery.

It stuck with me. Not because it revealed any secret — it didn't — but because it made me wonder: is this actually true? Do wars really move money in predictable ways? And then a darker thought followed: I could see how someone could take exactly that observation and twist it into something ugly. The old trope that certain people engineer wars for financial gain. It is a lie with a very long history, and a very persistent one.

So I did what I always do when I get curious about something I don't understand. I asked an AI.

Specifically, I used Grok — the AI built by Elon Musk's xAI — and asked it a simple question: could it create an investment tutorial based entirely on war observations? Not a lecture. Not a PDF. Something I could actually play with and learn from.

What it built in under a minute genuinely surprised me.

What Grok Created

The result is a browser-based mentor training simulator. Six scenarios, each built around a fictional-but-realistic news headline drawn from historical conflict patterns. A mentor appears before each move and explains exactly what is about to happen — which sector is likely to surge, which is about to fall, and crucially, where to move your money and why.

The scenarios follow the natural arc of a conflict cycle:

  • Pre-war uncertainty — military exercises are announced. Defense contractors begin receiving early orders.
  • War outbreak — first strikes confirmed. Defense stocks surge. The broad market panics and falls.
  • Supply disruption — oil facilities are struck. Energy companies post windfall profits as crude prices spike.
  • Sustained conflict — fighting drags on. Munitions stockpiles run low. Defense gets repeat multi-year contracts.
  • Ceasefire — reconstruction funds are pledged. Construction and infrastructure firms begin to rally.
  • Peace deal — risk evaporates overnight. The broad market roars back.

You start with $100,000 and a portfolio sitting entirely in the broad market. At each stage the mentor reads the headline, explains what history suggests is about to happen, and recommends where to move your money. You choose, the table updates instantly to show exactly where every dollar now sits, and then you confirm. The game applies the returns and your portfolio value changes — visibly, in the status bar at the top — before you move to the next scenario. By the end, if you have followed the mentor's rotations, you can see your $100,000 has grown substantially. If you ignored the advice, you can see exactly what that cost you, sector by sector, month by month.

The mentor doesn't just tell you what to do. It tells you why, grounding every move in real historical precedent: Raytheon and Lockheed up 30% in the weeks after 9/11. Energy stocks surging 20–40% during the 1990 Gulf War. Construction firms winning government-funded contracts after Kosovo and the Gulf War before a single brick was laid.

What I Learned

I learned more in twenty minutes of playing it than I had from years of half-reading financial headlines.

The core concept is something called sector rotation — the practice of moving money between different parts of the economy depending on what phase of a cycle you are in. It sounds sophisticated. It isn't, once you see it laid out. Wars create predictable demand. Governments spend enormous sums on defense immediately. Energy supply gets disrupted, so energy companies profit. Eventually reconstruction begins, and construction companies benefit. Then peace arrives and the broad economy recovers.

None of this is secret knowledge. None of it requires inside information or special access. It is supply and demand responding to real events, visible to anyone paying attention.

That is the thing the rabbi in the video understood, and the thing the game makes undeniable: these patterns are not a conspiracy. They are macroeconomics. Investors of every background, nationality, and religion rotate into the same sectors during conflicts because the demand is real and the contracts are public. The idea that any one group engineers wars in order to profit from them is not just morally repugnant — it is economically illiterate. The patterns exist regardless of who is watching.

Why It Matters That AI Can Build This

The speed is what strikes me most. I asked Grok to build an interactive investment tutorial grounded in geopolitical history, and it produced working, playable code almost immediately. Not a rough draft. Something genuinely educational, with honest maths, transparent breakdowns, and historically grounded scenarios.

That is a remarkable thing for someone with no coding ability and no financial background to be able to access. A year ago, turning a question like mine into a working interactive tool would have required a developer, a financial educator, and probably several weeks. Now it takes a conversation.

The game is not financial advice. The returns are illustrative. Real investing involves timing risk, transaction costs, and a great deal of noise that tidy historical patterns smooth over. But as a way of understanding why markets behave the way they do during crises — and of demystifying observations that are too easily weaponised into harmful myths — it works remarkably well.

You can paste the HTML code directly into any text file, save it with a .html extension, and open it in your browser. No login, no app, no server required.

Play it yourself. See exactly how the mechanics work. Then decide whether any of it requires believing in a secret cabal — or just reading the news.

The simulator was built using Grok (xAI). All returns are illustrative and based on historical sector patterns during real conflicts. This is not financial advice.

None

As you progress through training it shows you how much your portfolio increases.

None

Finally at the end you receive a synopsis of the profit cycle.

None
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>War Economy Simulator – Mentor Training</title>
<style>
  :root{
    --bg:#020816;
    --bg2:#051127;
    --panel:#08162d;
    --panel2:#0c1f3f;
    --panel3:#0a1b35;
    --text:#dbeaff;
    --muted:#8fb0d4;
    --line:rgba(117, 190, 255, 0.18);
    --line-strong:rgba(117, 190, 255, 0.4);
    --cyan:#70c9ff;
    --cyan-2:#2aa6ff;
    --green:#58f3a4;
    --amber:#ffd36b;
    --orange:#ff9b49;
    --red:#ff6b7b;
    --white:#f5f9ff;
    --shadow:
      0 14px 38px rgba(0,0,0,0.45),
      0 0 24px rgba(42,166,255,0.10);
    --inner-glow:
      inset 0 0 24px rgba(42,166,255,0.05),
      inset 0 1px 0 rgba(255,255,255,0.04);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  html, body { min-height: 100%; }

  body {
    background:
      radial-gradient(circle at 50% -10%, rgba(66,138,255,0.22), transparent 28%),
      radial-gradient(circle at 50% 110%, rgba(32,119,255,0.14), transparent 30%),
      linear-gradient(180deg, #010612 0%, #041022 40%, #020916 100%);
    color: var(--text);
    font-family: Arial, sans-serif;
    padding: 20px;
    letter-spacing: 0.2px;
  }

  .wrap {
    max-width: 1120px;
    margin: 0 auto;
  }

  .frame {
    position: relative;
    border-radius: 28px;
    background:
      linear-gradient(180deg, rgba(7,18,38,0.97), rgba(3,10,23,0.98));
    border: 1px solid rgba(117,190,255,0.22);
    box-shadow:
      0 22px 60px rgba(0,0,0,0.6),
      0 0 0 1px rgba(255,255,255,0.02),
      0 0 40px rgba(42,166,255,0.08);
    overflow: hidden;
  }

  .frame::before {
    content: "";
    position: absolute;
    inset: 10px;
    border-radius: 20px;
    border: 1px solid rgba(117,190,255,0.14);
    pointer-events: none;
  }

  .frame::after {
    content: "";
    position: absolute;
    inset: 0;
    background:
      repeating-linear-gradient(
        to bottom,
        rgba(255,255,255,0.02) 0px,
        rgba(255,255,255,0.02) 1px,
        transparent 2px,
        transparent 4px
      );
    opacity: 0.12;
    pointer-events: none;
    mix-blend-mode: screen;
  }

  .screen-glow {
    position: absolute;
    inset: 0;
    pointer-events: none;
    background:
      radial-gradient(circle at 50% 0%, rgba(116,202,255,0.14), transparent 18%),
      radial-gradient(circle at 50% 100%, rgba(116,202,255,0.12), transparent 18%);
  }

  .ticker {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 18px;
    border-bottom: 1px solid rgba(117,190,255,0.14);
    background:
      linear-gradient(90deg,
        rgba(115,15,28,0.95) 0%,
        rgba(115,15,28,0.95) 13%,
        rgba(10,22,43,0.98) 13%,
        rgba(10,22,43,0.98) 77%,
        rgba(8,48,88,0.95) 77%,
        rgba(8,48,88,0.95) 100%);
    position: relative;
    z-index: 1;
  }

  .ticker-label {
    background: linear-gradient(180deg, #ff5967, #b81e2c);
    color: #fff;
    font-weight: bold;
    font-size: 0.78rem;
    letter-spacing: 0.9px;
    text-transform: uppercase;
    padding: 6px 10px;
    border-radius: 5px;
    border: 1px solid rgba(255,255,255,0.16);
    box-shadow: 0 0 18px rgba(255,89,103,0.24);
    white-space: nowrap;
  }

  .ticker-main {
    flex: 1;
    font-size: 0.96rem;
    font-weight: bold;
    color: #eef5ff;
    text-transform: uppercase;
    letter-spacing: 0.8px;
  }

  .ticker-side {
    font-size: 0.92rem;
    font-weight: bold;
    color: var(--cyan);
    text-transform: uppercase;
    letter-spacing: 0.8px;
    text-shadow: 0 0 12px rgba(112,201,255,0.25);
    white-space: nowrap;
  }

  .title-area {
    position: relative;
    z-index: 1;
    padding: 24px 24px 10px;
    text-align: center;
  }

  h1 {
    color: var(--white);
    text-align: center;
    font-size: 1.9rem;
    margin-bottom: 0.35rem;
    letter-spacing: 1px;
    text-transform: uppercase;
    text-shadow: 0 0 18px rgba(112,201,255,0.14);
  }

  .subtitle {
    font-size: 0.84rem;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: 1.7px;
  }

  #game-view {
    position: relative;
    z-index: 1;
    padding: 8px 22px 24px;
  }

  .status-bar {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 12px;
    margin-bottom: 16px;
  }

  .stat {
    position: relative;
    min-width: 0;
    background:
      linear-gradient(180deg, rgba(10,26,51,0.96), rgba(7,18,37,0.96));
    border-radius: 16px;
    border: 1px solid var(--line);
    padding: 0.95rem 1rem;
    box-shadow: var(--shadow), var(--inner-glow);
    overflow: hidden;
  }

  .stat::before {
    content: "";
    position: absolute;
    top: 0;
    left: 8%;
    right: 8%;
    height: 2px;
    background: linear-gradient(90deg, transparent, rgba(133,214,255,0.95), transparent);
    box-shadow: 0 0 14px rgba(112,201,255,0.26);
  }

  .stat-label {
    font-size: 11px;
    color: var(--muted);
    margin-bottom: 6px;
    text-transform: uppercase;
    letter-spacing: 1.1px;
  }

  .stat-val {
    font-size: 24px;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 0 12px rgba(112,201,255,0.12);
  }

  .stat-val.up { color: var(--green); }
  .stat-val.down { color: var(--red); }

  .dashboard {
    display: grid;
    grid-template-columns: 1.18fr 0.92fr;
    gap: 16px;
    align-items: start;
  }

  .card {
    position: relative;
    background:
      linear-gradient(180deg, rgba(8,22,45,0.97), rgba(4,13,28,0.98));
    border: 1px solid var(--line);
    border-radius: 18px;
    padding: 18px;
    box-shadow: var(--shadow), var(--inner-glow);
    overflow: hidden;
  }

  .card::before {
    content: "";
    position: absolute;
    inset: 0;
    background:
      linear-gradient(180deg, rgba(255,255,255,0.025), transparent 16%, transparent 84%, rgba(112,201,255,0.025));
    pointer-events: none;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding-bottom: 10px;
    margin-bottom: 14px;
    border-bottom: 1px solid rgba(117,190,255,0.12);
    position: relative;
    z-index: 1;
  }

  .section-title {
    color: #a2d4ff;
    font-size: 0.9rem;
    font-weight: bold;
    letter-spacing: 1.2px;
    text-transform: uppercase;
  }

  .phase-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 0.76rem;
    padding: 6px 12px;
    border-radius: 999px;
    background: linear-gradient(180deg, rgba(22,62,110,0.96), rgba(12,38,72,0.96));
    color: #bde0ff;
    margin-bottom: 0.9rem;
    border: 1px solid rgba(117,190,255,0.28);
    text-transform: uppercase;
    letter-spacing: 1px;
    box-shadow: 0 0 14px rgba(42,166,255,0.12);
  }

  .phase-badge::before {
    content: "●";
    font-size: 0.65rem;
    color: var(--cyan);
    text-shadow: 0 0 8px rgba(112,201,255,0.5);
  }

  .headline {
    font-size: 1.25rem;
    font-weight: bold;
    color: var(--white);
    line-height: 1.45;
    margin-bottom: 0.9rem;
    text-shadow: 0 0 12px rgba(112,201,255,0.08);
  }

  .advice {
    font-size: 0.95rem;
    color: #86efbc;
    line-height: 1.78;
    padding: 14px 15px;
    margin-bottom: 0.9rem;
    border-radius: 12px;
    border: 1px solid rgba(88,243,164,0.18);
    border-left: 4px solid rgba(88,243,164,0.75);
    background: linear-gradient(180deg, rgba(5,22,24,0.72), rgba(4,15,19,0.55));
    box-shadow: inset 0 0 18px rgba(88,243,164,0.04);
  }

  .prediction {
    font-size: 0.88rem;
    font-weight: bold;
    color: var(--cyan);
    margin-bottom: 0.8rem;
    background: rgba(42,166,255,0.08);
    border: 1px solid rgba(42,166,255,0.16);
    border-radius: 10px;
    padding: 10px 12px;
  }

  .rotation-note {
    font-size: 0.85rem;
    color: var(--amber);
    background: linear-gradient(180deg, rgba(59,40,10,0.44), rgba(41,25,6,0.36));
    border: 1px solid rgba(255,180,0,0.2);
    border-radius: 10px;
    padding: 10px 12px;
    margin-bottom: 1rem;
    line-height: 1.55;
    box-shadow: inset 0 0 14px rgba(255,211,107,0.03);
  }

  .hint {
    font-size: 0.79rem;
    color: var(--muted);
    margin-bottom: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.7px;
  }

  .btns {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 1rem;
  }

  button {
    padding: 11px 17px;
    border-radius: 12px;
    font-size: 0.92rem;
    cursor: pointer;
    border: 1px solid rgba(255,255,255,0.15);
    background:
      linear-gradient(180deg, rgba(16,42,77,0.98), rgba(9,25,48,0.98));
    color: #e0ecff;
    font-family: Arial, sans-serif;
    transition: 0.16s ease;
    box-shadow:
      0 8px 20px rgba(0,0,0,0.22),
      inset 0 1px 0 rgba(255,255,255,0.04);
  }

  button:hover {
    background:
      linear-gradient(180deg, rgba(22,57,103,0.98), rgba(12,33,64,0.98));
    border-color: rgba(145,210,255,0.34);
    transform: translateY(-1px);
    box-shadow:
      0 12px 26px rgba(0,0,0,0.3),
      0 0 18px rgba(42,166,255,0.1);
  }

  button.selected {
    background: linear-gradient(180deg, rgba(22,152,108,1), rgba(9,105,73,1));
    border-color: rgba(115,250,193,0.52);
    color: #fff;
    box-shadow: 0 0 20px rgba(88,243,164,0.16);
  }

  button.subopt.selected {
    background: linear-gradient(180deg, rgba(176,84,25,1), rgba(125,53,8,1));
    border-color: rgba(255,177,116,0.48);
    color: #fff;
    box-shadow: 0 0 18px rgba(255,155,73,0.18);
  }

  button:disabled {
    opacity: 0.42;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  .action-row {
    display: flex;
    gap: 10px;
    margin-top: 0.35rem;
  }

  .btn-primary,
  .btn-next {
    font-weight: bold;
    flex: 1;
    text-transform: uppercase;
    letter-spacing: 0.8px;
  }

  .btn-primary {
    background: linear-gradient(180deg, #2380da, #144e92);
    color: #fff;
    border-color: rgba(123,199,255,0.45);
  }

  .btn-primary:hover:not(:disabled) {
    background: linear-gradient(180deg, #2b91ef, #175cab);
  }

  .btn-next {
    background: linear-gradient(180deg, #0da36d, #08744c);
    color: #fff;
    border-color: rgba(114,242,188,0.34);
  }

  .btn-next:hover:not(:disabled) {
    background: linear-gradient(180deg, #10b77a, #0a8458);
  }

  .table-note {
    font-size: 0.78rem;
    color: var(--muted);
    text-transform: uppercase;
    letter-spacing: 0.8px;
  }

  table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 0.88rem;
  }

  th {
    text-align: left;
    padding: 10px 11px;
    color: #b5d6f5;
    font-weight: bold;
    font-size: 0.76rem;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    text-transform: uppercase;
    letter-spacing: 1px;
    background: rgba(255,255,255,0.02);
  }

  td {
    padding: 10px 11px;
    border-bottom: 1px solid rgba(255,255,255,0.06);
    color: #e3efff;
    vertical-align: middle;
  }

  tbody tr:hover {
    background: rgba(112,201,255,0.04);
  }

  td.changed {
    color: var(--amber);
    font-weight: bold;
    text-shadow: 0 0 8px rgba(255,211,107,0.08);
  }

  .sector-cell {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .sector-icon {
    width: 26px;
    height: 26px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    font-size: 0.95rem;
    background: linear-gradient(180deg, rgba(17,45,83,0.96), rgba(9,26,48,0.96));
    border: 1px solid rgba(117,190,255,0.16);
    box-shadow: inset 0 0 10px rgba(112,201,255,0.03);
  }

  .sector-name {
    font-weight: bold;
    color: #eff6ff;
  }

  .muted-dash {
    color: #58708d;
  }

  .result-box {
    padding: 18px;
    border-radius: 16px;
    margin: 1rem 0 0;
    text-align: center;
    background: linear-gradient(180deg, rgba(7,19,38,0.94), rgba(5,15,30,0.97));
    box-shadow: var(--shadow), var(--inner-glow);
  }

  .result-box.gain {
    border: 1px solid rgba(88,243,164,0.26);
  }

  .result-box.loss {
    border: 1px solid rgba(255,107,123,0.24);
  }

  .result-num {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 4px;
  }

  .result-num.gain { color: var(--green); }
  .result-num.loss { color: var(--red); }

  .result-amt {
    font-size: 1.08rem;
    font-weight: bold;
    margin-bottom: 8px;
  }

  .result-sub {
    font-size: 0.88rem;
    color: #b6cbe5;
    line-height: 1.55;
    margin-top: 6px;
  }

  .result-breakdown {
    font-size: 0.82rem;
    color: #9abce0;
    margin-top: 12px;
    line-height: 1.9;
    text-align: left;
    background: linear-gradient(180deg, rgba(1,7,18,0.62), rgba(0,0,0,0.32));
    padding: 13px 14px;
    border-radius: 10px;
    border: 1px solid rgba(117,190,255,0.12);
  }

  .summary {
    text-align: center;
    padding: 34px 20px 28px;
    position: relative;
    z-index: 1;
  }

  .summary h2 {
    font-size: 1.6rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
    color: var(--white);
    text-transform: uppercase;
    letter-spacing: 1px;
  }

  .final-num {
    font-size: 2.8rem;
    font-weight: bold;
    color: var(--green);
    margin: 0.55rem 0;
    text-shadow: 0 0 18px rgba(88,243,164,0.16);
  }

  .lessons {
    text-align: left;
    margin: 1.3rem auto 0;
    background: linear-gradient(180deg, rgba(9,24,47,0.96), rgba(5,17,34,0.97));
    border-radius: 18px;
    padding: 1.1rem 1.25rem;
    max-width: 760px;
    border: 1px solid rgba(117,190,255,0.14);
    box-shadow: var(--shadow), var(--inner-glow);
  }

  .lessons li {
    font-size: 0.9rem;
    color: #b7cee7;
    line-height: 1.9;
    margin-left: 1.15rem;
  }

  .restart-btn {
    margin-top: 1rem;
    background: linear-gradient(180deg, #2380da, #144e92);
    color: #fff;
    border-color: rgba(123,199,255,0.45);
    padding: 12px 30px;
    font-size: 1rem;
  }

  @keyframes pulseGlow {
    0%, 100% { box-shadow: 0 0 0 rgba(112,201,255,0); }
    50% { box-shadow: 0 0 16px rgba(112,201,255,0.18); }
  }

  .live-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--cyan);
    margin-right: 8px;
    box-shadow: 0 0 12px rgba(112,201,255,0.45);
    animation: pulseGlow 1.8s infinite ease-in-out;
    vertical-align: middle;
  }

  @media (max-width: 940px) {
    .dashboard {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 720px) {
    body { padding: 14px; }
    .title-area { padding: 18px 14px 8px; }
    h1 { font-size: 1.48rem; }
    #game-view { padding: 8px 14px 16px; }
    .status-bar { grid-template-columns: 1fr; }
    .ticker { flex-wrap: wrap; }
    .ticker-side { width: 100%; }
    .action-row { flex-direction: column; }
    .card { padding: 15px; }
    .stat-val { font-size: 22px; }
    table { font-size: 0.84rem; }
    th, td { padding: 9px 8px; }
  }
</style>
</head>
<body>
<div class="wrap">
  <div class="frame">
    <div class="screen-glow"></div>

    <div class="ticker">
      <div class="ticker-label">Breaking News</div>
      <div class="ticker-main">Conflict escalates in eastern region</div>
      <div class="ticker-side">Supply chains disrupted!</div>
    </div>

    <div class="title-area">
      <h1>War Economy Simulator</h1>
      <div class="subtitle">Mentor Training Interface</div>
    </div>

    <div id="game-view">
      <div class="status-bar">
        <div class="stat">
          <div class="stat-label">Portfolio value</div>
          <div class="stat-val" id="s-portfolio">$100,000</div>
        </div>
        <div class="stat">
          <div class="stat-label">Total return</div>
          <div class="stat-val" id="s-return">+0.0%</div>
        </div>
        <div class="stat">
          <div class="stat-label">Scenario</div>
          <div class="stat-val" id="s-month">1 of 6</div>
        </div>
      </div>

      <div class="dashboard">
        <div class="card">
          <div class="card-header">
            <div class="section-title"><span class="live-dot"></span>Mentor Advice</div>
          </div>

          <div class="phase-badge" id="phase-badge"></div>
          <div class="headline" id="headline"></div>
          <div class="advice" id="advice"></div>
          <div class="prediction" id="prediction"></div>
          <div class="rotation-note" id="rotation-note" style="display:none"></div>
          <div class="hint" id="step-hint"></div>
          <div class="btns" id="btns"></div>

          <div class="action-row">
            <button class="btn-primary" id="confirm-btn" disabled onclick="doConfirm()">See predicted result</button>
            <button class="btn-next" id="next-btn" style="display:none" onclick="doNext()">Next scenario →</button>
          </div>

          <div id="result-area"></div>
        </div>

        <div class="card">
          <div class="card-header">
            <div class="section-title">Portfolio Allocation</div>
            <div class="table-note">Amber = changed this move</div>
          </div>

          <table>
            <thead>
              <tr>
                <th>Sector</th>
                <th>Allocation %</th>
                <th>Value invested</th>
                <th>Monthly return</th>
                <th>Gain / loss</th>
              </tr>
            </thead>
            <tbody id="alloc-table"></tbody>
          </table>
        </div>
      </div>
    </div>

    <div id="summary-view" class="summary" style="display:none">
      <div style="font-size:0.86rem;color:#8fb0d4;margin-bottom:0.5rem;text-transform:uppercase;letter-spacing:1px;">Training complete</div>
      <h2>Final Portfolio</h2>
      <div class="final-num" id="final-num"></div>
      <div style="font-size:1rem;color:#b6cce7;margin:0.5rem 0" id="final-return"></div>

      <div class="lessons">
        <div style="font-size:0.88rem;font-weight:bold;margin-bottom:8px;color:#9fd2ff;text-transform:uppercase;letter-spacing:1px;">What you learned</div>
        <ul>
          <li>Defense surges early in conflict as governments rush emergency contracts</li>
          <li>Energy spikes when oil infrastructure is threatened or supply disrupted</li>
          <li>Construction leads in ceasefire and rebuild phases funded by aid</li>
          <li>Broad market recovers strongly once uncertainty lifts after a peace deal</li>
          <li>Sector rotation means actively moving money out of yesterday's winner into tomorrow's — the source matters as much as the destination</li>
        </ul>
      </div>

      <button onclick="restart()" class="restart-btn">Restart training</button>
    </div>
  </div>
</div>

<script>
const START = 100000;
const SECTOR_KEYS = ["defense", "energy", "construction", "market"];
const INITIAL_DOLLARS = {
  defense: 0,
  energy: 0,
  construction: 0,
  market: 100000
};

const SECTOR_META = {
  defense: { label: "Defense", icon: "🛡" },
  energy: { label: "Energy", icon: "⚡" },
  construction: { label: "Construction", icon: "🏗" },
  market: { label: "Market", icon: "📈" }
};

let turn = 0;
let dollars = copyD(INITIAL_DOLLARS);
let previewDollars = copyD(INITIAL_DOLLARS);
let beforeMoveDollars = null;
let selectedDelta = null;

const scenarios = [
  {
    phase: "Pre-war uncertainty",
    headline: "Tensions rise in key shipping lane — military exercises announced",
    advice: "In the months before the Gulf War (1990) and the Ukraine invasion (2022), investors who spotted early military build-up and rotated toward defense contractors gained 8–14% before most people had moved. Markets look calm, but the signal is clear.",
    prediction: "Mentor predicts: defense up ~8% this month. Broad market flat.",
    rotationExplain: "Moving money OUT OF broad market → INTO defense. The market is doing nothing — put it to work.",
    sector: "defense",
    sourceOrder: ["market", "energy", "construction"],
    options: [
      { label: "+10% into defense", pct: 10 },
      { label: "+15% into defense", pct: 15 }
    ],
    bestPct: 15,
    sectorReturns: { defense: 8, energy: 1, construction: 0, market: 0 }
  },
  {
    phase: "War outbreak",
    headline: "First strikes confirmed — governments announce emergency defense spending",
    advice: "When war breaks out, defense stocks move fast and big. After 9/11, Raytheon and Lockheed were up 30%+ within weeks. Ukraine 2022 saw the same surge. Governments need missiles, aircraft, and equipment immediately — contracts flood in overnight.",
    prediction: "Mentor predicts: defense up ~28% this month. Broad market falls ~9% on fear. Every % left in market costs you.",
    rotationExplain: "Moving money OUT OF broad market → INTO defense. War fear crashes the market — you want out of it and into defense contracts.",
    sector: "defense",
    sourceOrder: ["market", "energy", "construction"],
    options: [
      { label: "+20% into defense", pct: 20 },
      { label: "+25% into defense", pct: 25 }
    ],
    bestPct: 25,
    sectorReturns: { defense: 28, energy: 8, construction: -2, market: -9 }
  },
  {
    phase: "Supply disruption",
    headline: "Oil facilities struck — crude prices jump 18% in a single session",
    advice: "When oil infrastructure is hit, energy companies earn massive windfall profits from higher prices. In the 1990 Gulf War, crude doubled and energy stocks surged 20–40%. The same pattern repeated in 2022 when Russian pipelines were sanctioned.",
    prediction: "Mentor predicts: energy up ~30% this month. Defense still solid. Broad market falls ~5%.",
    rotationExplain: "Moving money OUT OF broad market → INTO energy. The market is still nervous — energy is the clear winner on this oil shock.",
    sector: "energy",
    sourceOrder: ["market", "construction", "defense"],
    options: [
      { label: "+20% into energy", pct: 20 },
      { label: "+25% into energy", pct: 25 }
    ],
    bestPct: 25,
    sectorReturns: { defense: 10, energy: 30, construction: 0, market: -5 }
  },
  {
    phase: "Sustained conflict",
    headline: "Fighting drags on — ammunition and missile stockpiles critically low",
    advice: "Prolonged wars generate repeat orders for years. During Afghanistan/Iraq, General Dynamics and Northrop Grumman compounded gains over a decade of restocking. Ukraine created 3-year backlogs at Lockheed and RTX.",
    prediction: "Mentor predicts: defense up another ~20% on new multi-year contracts.",
    rotationExplain: "Moving more money OUT OF broad market → INTO defense. You already have defense exposure — this adds to it while the market still struggles.",
    sector: "defense",
    sourceOrder: ["market", "construction", "energy"],
    options: [
      { label: "+15% more into defense", pct: 15 }
    ],
    bestPct: 15,
    sectorReturns: { defense: 20, energy: 8, construction: 5, market: -3 }
  },
  {
    phase: "Ceasefire",
    headline: "Ceasefire talks begin — $200bn reconstruction fund pledged by allies",
    advice: "Post-conflict rebuild is enormous. After Gulf War 1991 and Kosovo 1999, construction and engineering firms won huge government-funded contracts for infrastructure, housing, ports, and power grids. Stocks move before the first brick is laid.",
    prediction: "Mentor predicts: construction up ~30% this month. Defense cools to +1%. Rotate now.",
    rotationExplain: "Moving money OUT OF defense (which has peaked) → INTO construction. Classic sector hand-off — sell the winner, buy the next winner.",
    sector: "construction",
    sourceOrder: ["defense", "energy", "market"],
    options: [
      { label: "+25% into construction", pct: 25 },
      { label: "+30% into construction", pct: 30 }
    ],
    bestPct: 30,
    sectorReturns: { defense: 1, energy: -3, construction: 30, market: 9 }
  },
  {
    phase: "Peace deal",
    headline: "Peace agreement signed — global stock markets rally worldwide",
    advice: "When war ends, risk premium evaporates overnight and investors flood back into broad markets. Post-Gulf War 1991 and post-Kosovo 1999, the S&P and global indices surged 10–20%+ in the following months.",
    prediction: "Mentor predicts: broad market up ~16%. Defense falls ~5%. Construction still decent at +12%.",
    rotationExplain: "Moving money OUT OF defense (now losing) → INTO broad market. The war trade is over — defense contracts dry up, but the whole economy rebounds on peace.",
    sector: "market",
    sourceOrder: ["defense", "energy", "construction"],
    options: [
      { label: "+20% back into broad market", pct: 20 }
    ],
    bestPct: 20,
    sectorReturns: { defense: -5, energy: 2, construction: 12, market: 16 }
  }
];

function copyD(d) {
  return {
    defense: d.defense,
    energy: d.energy,
    construction: d.construction,
    market: d.market
  };
}

function total(d) {
  return d.defense + d.energy + d.construction + d.market;
}

function allocPct(d, key) {
  const t = total(d);
  return t > 0 ? (d[key] / t) * 100 : 0;
}

function fmt(n) {
  return "$" + Math.round(Math.abs(n)).toLocaleString();
}

function fmtSigned(n) {
  return (n >= 0 ? "+$" : "-$") + Math.round(Math.abs(n)).toLocaleString();
}

function pct(n) {
  return (n >= 0 ? "+" : "") + n.toFixed(1) + "%";
}

function sectorName(key) {
  return SECTOR_META[key]?.label || (key.charAt(0).toUpperCase() + key.slice(1));
}

function sectorIcon(key) {
  return SECTOR_META[key]?.icon || "•";
}

function getCurrentScenario() {
  return scenarios[Math.min(turn, scenarios.length - 1)];
}

function applyRotation(base, pctOfTotal, scenario) {
  const next = copyD(base);

  if (pctOfTotal <= 0) return next;

  const moveAmount = total(base) * (pctOfTotal / 100);
  let remaining = moveAmount;

  scenario.sourceOrder.forEach((src) => {
    if (remaining <= 0.005) return;
    const take = Math.min(next[src], remaining);
    next[src] -= take;
    remaining -= take;
  });

  const actualMoved = moveAmount - remaining;
  next[scenario.sector] += actualMoved;

  return next;
}

function describeRotation(before, after, scenario) {
  const moved = [];

  scenario.sourceOrder.forEach((src) => {
    const diff = before[src] - after[src];
    if (diff > 0.5) {
      moved.push(`${fmt(diff)} out of ${sectorName(src)}`);
    }
  });

  if (!moved.length) {
    return "No change — money stays where it is.";
  }

  const gained = after[scenario.sector] - before[scenario.sector];
  return `Moving ${moved.join(" + ")} → into ${sectorName(scenario.sector)} (${fmt(gained)})`;
}

function renderTable(displayDollars, highlightVs = null, showReturns = false, gainBaseDollars = null) {
  const scenario = getCurrentScenario();
  let html = "";

  SECTOR_KEYS.forEach((key) => {
    const value = displayDollars[key];
    const allocation = allocPct(displayDollars, key);
    const changed = highlightVs && Math.abs(displayDollars[key] - highlightVs[key]) > 0.5;

    let returnCell = '<span class="muted-dash">—</span>';
    let gainCell = '<span class="muted-dash">—</span>';

    if (showReturns) {
      const retPct = scenario.sectorReturns[key] || 0;
      const gainLoss = gainBaseDollars ? gainBaseDollars[key] * (retPct / 100) : 0;

      returnCell = `<span style="color:${retPct >= 0 ? '#58f3a4' : '#ff6b7b'};font-weight:bold">${pct(retPct)}</span>`;
      gainCell = `<span style="color:${gainLoss >= 0 ? '#58f3a4' : '#ff6b7b'};font-weight:bold">${fmtSigned(gainLoss)}</span>`;
    }

    html += `
      <tr>
        <td>
          <div class="sector-cell">
            <span class="sector-icon">${sectorIcon(key)}</span>
            <span class="sector-name">${sectorName(key)}</span>
          </div>
        </td>
        <td${changed ? ' class="changed"' : ''}>${allocation.toFixed(0)}%</td>
        <td${changed ? ' class="changed"' : ''}>${fmt(value)}</td>
        <td>${returnCell}</td>
        <td>${gainCell}</td>
      </tr>
    `;
  });

  document.getElementById("alloc-table").innerHTML = html;
}

function updateStatus() {
  const portfolioTotal = total(dollars);
  const totalReturnPct = ((portfolioTotal - START) / START) * 100;

  const portfolioEl = document.getElementById("s-portfolio");
  portfolioEl.textContent = fmt(portfolioTotal);
  portfolioEl.className = "stat-val";
  if (portfolioTotal > START) portfolioEl.classList.add("up");
  if (portfolioTotal < START) portfolioEl.classList.add("down");

  const returnEl = document.getElementById("s-return");
  returnEl.textContent = pct(totalReturnPct);
  returnEl.className = "stat-val";
  if (totalReturnPct > 0) returnEl.classList.add("up");
  if (totalReturnPct < 0) returnEl.classList.add("down");

  const scenarioNum = Math.min(turn + 1, scenarios.length);
  document.getElementById("s-month").textContent = `${scenarioNum} of ${scenarios.length}`;
}

function renderOptionButtons(scenario) {
  let html = "";

  scenario.options.forEach((option, index) => {
    html += `<button id="opt-${index}" onclick="selectOpt(${option.pct}, ${index})">${option.label}</button>`;
  });

  html += `<button class="subopt" id="opt-skip" onclick="selectOpt(0, -1)">No change (suboptimal)</button>`;

  document.getElementById("btns").innerHTML = html;
}

function loadScenario() {
  if (turn >= scenarios.length) {
    showSummary();
    return;
  }

  const scenario = scenarios[turn];

  selectedDelta = null;
  beforeMoveDollars = null;
  previewDollars = copyD(dollars);

  document.getElementById("phase-badge").textContent = scenario.phase;
  document.getElementById("headline").textContent = scenario.headline;
  document.getElementById("advice").textContent = scenario.advice;
  document.getElementById("prediction").textContent = scenario.prediction;

  document.getElementById("rotation-note").style.display = "none";
  document.getElementById("result-area").innerHTML = "";
  document.getElementById("confirm-btn").disabled = true;
  document.getElementById("confirm-btn").style.display = "";
  document.getElementById("next-btn").style.display = "none";
  document.getElementById("step-hint").textContent =
    "Step 1: Choose a mentor option — the table highlights exactly which values change and where the money comes from.";

  renderOptionButtons(scenario);
  renderTable(dollars);
  updateStatus();
}

function selectOpt(pctMove, idx) {
  selectedDelta = pctMove;

  document.querySelectorAll("#btns button").forEach((btn) => {
    btn.classList.remove("selected");
  });

  const selectedBtn = idx >= 0
    ? document.getElementById(`opt-${idx}`)
    : document.getElementById("opt-skip");

  if (selectedBtn) selectedBtn.classList.add("selected");

  document.getElementById("confirm-btn").disabled = false;
  document.getElementById("step-hint").textContent =
    'Step 2: Amber cells show what changed. Click "See predicted result" when ready.';

  const scenario = scenarios[turn];
  beforeMoveDollars = copyD(dollars);
  previewDollars = applyRotation(dollars, pctMove, scenario);

  const noteEl = document.getElementById("rotation-note");
  noteEl.innerHTML =
    `↔ ${describeRotation(beforeMoveDollars, previewDollars, scenario)}<br>` +
    `<span style="color:#b7cee7;font-size:0.82rem">${scenario.rotationExplain}</span>`;
  noteEl.style.display = "block";

  renderTable(previewDollars, beforeMoveDollars, false, null);
}

function buildBreakdown(preReturn, scenario, totalReturn, newTotal) {
  let breakdown = '<strong style="color:#e8f2ff">How each sector contributed:</strong><br>';

  SECTOR_KEYS.forEach((key) => {
    if (preReturn[key] < 0.5) return;

    const name = sectorName(key);
    const ret = scenario.sectorReturns[key] || 0;
    const gain = preReturn[key] * ret / 100;
    const color = gain >= 0 ? "#58f3a4" : "#ff6b7b";
    const arrow = gain >= 0 ? "▲" : "▼";

    breakdown +=
      `<span style="color:${color}">${arrow}</span> ${name}: ${fmt(preReturn[key])} invested × ${pct(ret)} = ` +
      `<strong style="color:${color}">${fmtSigned(gain)}</strong><br>`;
  });

  breakdown +=
    `<div style="border-top:1px solid rgba(255,255,255,0.1);margin-top:6px;padding-top:6px">` +
    `Net this month: <strong style="color:${totalReturn >= 0 ? '#58f3a4' : '#ff6b7b'}">${fmtSigned(totalReturn)}</strong>` +
    ` &nbsp;|&nbsp; Portfolio now: <strong style="color:#fff">${fmt(newTotal)}</strong>` +
    `</div>`;

  return breakdown;
}

function getMentorMessage(scenario, preReturn) {
  const perfectMove = selectedDelta === scenario.bestPct;
  const movedAtAll = selectedDelta > 0;

  if (perfectMove) {
    return "You matched the mentor's strongest rotation for this phase.";
  }

  if (movedAtAll) {
    return "You rotated in the right direction, but not at the strongest level.";
  }

  return preReturn[scenario.sector] > 0
    ? "You made no new move. You still had some exposure to the winning sector from earlier rounds."
    : "You made no change, so you missed the main winning sector this round.";
}

function doConfirm() {
  if (selectedDelta === null || turn >= scenarios.length) return;

  const scenario = scenarios[turn];

  dollars = copyD(previewDollars);
  const preReturn = copyD(dollars);

  let totalReturn = 0;

  SECTOR_KEYS.forEach((key) => {
    const ret = scenario.sectorReturns[key] || 0;
    const gain = preReturn[key] * (ret / 100);
    dollars[key] += gain;
    totalReturn += gain;
  });

  renderTable(dollars, null, true, preReturn);
  updateStatus();

  const preTotal = total(preReturn);
  const newTotal = total(dollars);
  const isGain = totalReturn >= 0;
  const mentorMsg = getMentorMessage(scenario, preReturn);
  const breakdown = buildBreakdown(preReturn, scenario, totalReturn, newTotal);
  const periodPct = preTotal > 0 ? (totalReturn / preTotal) * 100 : 0;

  document.getElementById("result-area").innerHTML = `
    <div class="result-box ${isGain ? 'gain' : 'loss'}">
      <div class="result-num ${isGain ? 'gain' : 'loss'}">${fmtSigned(totalReturn)} this month</div>
      <div class="result-amt" style="color:${isGain ? '#58f3a4' : '#ff6b7b'}">
        ${pct(periodPct)} on total portfolio
      </div>
      <div class="result-sub">${mentorMsg}</div>
      <div class="result-breakdown">${breakdown}</div>
    </div>
  `;

  document.getElementById("step-hint").textContent =
    'Read the breakdown, then click "Next scenario" to continue with your updated portfolio.';

  document.getElementById("confirm-btn").style.display = "none";
  document.getElementById("next-btn").style.display = "";
  document.querySelectorAll("#btns button").forEach((btn) => {
    btn.disabled = true;
  });
}

function doNext() {
  turn++;
  loadScenario();
}

function showSummary() {
  document.getElementById("game-view").style.display = "none";
  document.getElementById("summary-view").style.display = "block";

  const portfolioTotal = total(dollars);
  const totalReturnPct = ((portfolioTotal - START) / START) * 100;

  document.getElementById("final-num").textContent = fmt(portfolioTotal);
  document.getElementById("final-return").textContent =
    `${pct(totalReturnPct)} total return from $100,000 starting capital`;
}

function restart() {
  turn = 0;
  dollars = copyD(INITIAL_DOLLARS);
  previewDollars = copyD(INITIAL_DOLLARS);
  beforeMoveDollars = null;
  selectedDelta = null;

  document.getElementById("game-view").style.display = "block";
  document.getElementById("summary-view").style.display = "none";

  loadScenario();
}

loadScenario();
</script>
</body>
</html>