// Simulator · what if each coin hits its bull peak?

function Simulator() {
  const { state, prices, setBullPeak } = useStore();
  const cur = state.settings.currency;
  const portfolio = React.useMemo(() => computePortfolio(state, prices), [state, prices]);

  if (portfolio.rows.length === 0) {
    return (
      <div className="exos-page">
        <PageHeadSim title="Scenario Simulator" sub="What if each coin hits its bull-cycle peak? See the upside math without the wishful thinking." />
        <Card><EmptyState title="Add holdings to simulate" sub="The simulator needs at least one holding." /></Card>
      </div>
    );
  }

  // Compute scenarios
  const peakValue = portfolio.rows.reduce((a, r) => {
    const p = state.scenarios.bullPeaks[r.coinId] ?? r.price * 2;
    return a + r.amount * p;
  }, 0);
  const gainFromHere = peakValue - portfolio.total;
  const multiple = peakValue / portfolio.total;

  return (
    <div className="exos-page">
      <PageHeadSim
        title="Scenario Simulator"
        sub="What if each coin hits its bull-cycle peak? See the upside math without the wishful thinking."
      />

      <div className="exos-grid cols-3" style={{ marginBottom: 14 }}>
        <StatCard label="Today" value={fmtCurrency(portfolio.total, cur, { compact: true })} sub={`${portfolio.rows.length} positions`} />
        <StatCard
          label="If all peaks hit"
          value={fmtCurrency(peakValue, cur, { compact: true })}
          tone="accent"
          sub={<span className="mono">{multiple.toFixed(2)}× from here</span>}
        />
        <StatCard
          label="Additional upside"
          value={fmtCurrency(gainFromHere, cur, { compact: true })}
          tone="gain"
          sub={<span className="mono" style={{ color: "var(--gain)" }}>+{fmtPct((gainFromHere / portfolio.total) * 100)}</span>}
        />
      </div>

      <Card style={{ marginBottom: 14 }}>
        <SectionHeader kicker="PER COIN" title="Set your bull-cycle peak prices" />
        <div className="exos-sim-rows">
          {portfolio.rows.map(r => {
            const peak = state.scenarios.bullPeaks[r.coinId] ?? r.price * 2;
            const peakVal = r.amount * peak;
            const upside = peakVal - r.value;
            return (
              <div key={r.id} className="exos-sim-row">
                <div className="exos-sim-coin">
                  <CoinIcon coinId={r.coinId} size={32} />
                  <div>
                    <div style={{ fontWeight: 500 }}>{r.meta.symbol}</div>
                    <div className="mono" style={{ fontSize: 11, color: "var(--text-mute)" }}>now {fmtCurrency(r.price, cur, { precise: r.price < 10 })}</div>
                  </div>
                </div>
                <div className="exos-sim-input">
                  <div className="exos-label" style={{ marginBottom: 5 }}>Bull peak price</div>
                  <NumInput value={peak} onChange={v => setBullPeak(r.coinId, v ?? 0)} prefix={CURRENCY_SYMBOLS[cur]} />
                </div>
                <div className="exos-sim-mult">
                  <div className="exos-label">Multiple</div>
                  <div className="mono" style={{ fontSize: 18, fontWeight: 500 }}>{(peak / r.price).toFixed(2)}×</div>
                </div>
                <div className="exos-sim-val">
                  <div className="exos-label">Peak value</div>
                  <div className="mono" style={{ fontWeight: 500, fontSize: 15 }}>{fmtCurrency(peakVal, cur, { compact: true })}</div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--gain)" }}>+{fmtCurrency(upside, cur, { compact: true })}</div>
                </div>
                <div className="exos-sim-bar">
                  <div className="exos-sim-bar-now" style={{ width: `${Math.min(100, (r.price / peak) * 100)}%` }} />
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      <ScenarioGrid portfolio={portfolio} state={state} peakValue={peakValue} currency={cur} />
    </div>
  );
}

function PageHeadSim({ title, sub }) {
  return (
    <div className="exos-page-head">
      <div>
        <div className="exos-kicker mono">{title.toUpperCase()}</div>
        <h1 className="exos-h1">{title}</h1>
        <div className="exos-page-head-sub">{sub}</div>
      </div>
    </div>
  );
}

function ScenarioGrid({ portfolio, state, peakValue, currency }) {
  const scenarios = [
    { label: "Light correction", pct: -20, mood: "warn" },
    { label: "Bear retrace", pct: -50, mood: "loss" },
    { label: "Cycle bottom", pct: -75, mood: "loss" },
    { label: "Today", pct: 0, mood: "default" },
    { label: "Modest run", pct: +50, mood: "gain" },
    { label: "Bull peak (your plan)", pct: ((peakValue / portfolio.total) - 1) * 100, mood: "accent" },
  ];
  return (
    <Card>
      <SectionHeader kicker="WHAT IF" title="Portfolio value across scenarios" />
      <div className="exos-scenario-grid">
        {scenarios.map((s, i) => {
          const val = portfolio.total * (1 + s.pct / 100);
          const delta = val - portfolio.total;
          const color = s.mood === "gain" || s.mood === "accent" ? "var(--gain)" : s.mood === "warn" ? "var(--warn)" : s.mood === "loss" ? "var(--loss)" : "var(--text)";
          return (
            <div key={i} className="exos-scenario">
              <div className="exos-label">{s.label}</div>
              <div className="mono" style={{ fontSize: 22, fontWeight: 500, color, marginTop: 6, letterSpacing: "-0.01em" }}>{fmtCurrency(val, currency, { compact: true })}</div>
              <div className="mono" style={{ fontSize: 12, color: "var(--text-mute)", marginTop: 2 }}>
                {delta >= 0 ? "+" : ""}{fmtCurrency(delta, currency, { compact: true })} <span style={{ color }}>({fmtPct(s.pct, { digits: 0 })})</span>
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

const SIM_STYLES = `
.exos-sim-rows { display: flex; flex-direction: column; gap: 0; }
.exos-sim-row {
  display: grid; grid-template-columns: 160px 200px 110px 160px 1fr; gap: 18px;
  padding: 16px 0; border-bottom: 1px solid var(--line); align-items: center;
}
.exos-sim-row:last-child { border-bottom: 0; }
.exos-sim-coin { display: flex; align-items: center; gap: 12px; }
.exos-sim-bar { height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; position: relative; }
.exos-sim-bar-now { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); transition: width .4s; }

@media (max-width: 1024px) {
  .exos-sim-row { grid-template-columns: 1fr 1fr; gap: 12px; }
  .exos-sim-bar { grid-column: 1 / -1; }
}

.exos-scenario-grid {
  display: grid; grid-template-columns: repeat(3, 1fr);
  border-top: 1px solid var(--line); border-left: 1px solid var(--line);
  border-radius: 10px; overflow: hidden;
}
.exos-scenario { padding: 18px 18px; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); }
@media (max-width: 760px) {
  .exos-scenario-grid { grid-template-columns: repeat(2, 1fr); }
}
`;
(function(){ if(document.getElementById("exos-sim-styles")) return; const t=document.createElement("style"); t.id="exos-sim-styles"; t.textContent=SIM_STYLES; document.head.appendChild(t); })();

window.Simulator = Simulator;
