/* ============================================================
   Dinasty Control — Position Monitor (real-time open trades)
   ============================================================ */

function RCell({ r }) {
  const cls = r < 0 ? "neg" : r > 1 ? "pos" : "warn";
  const arw = r > 0 ? "▲" : r < 0 ? "▼" : "■";
  return <span className={`num ${cls}`}><span className="num-arw">{arw}</span>{r >= 0 ? "+" : "−"}{Math.abs(r).toFixed(1)}R</span>;
}

const TRAIL_LABEL = { idle: "● idle", armed: "◇ armed", trailing: "▸ trailing" };
function TrailPill({ s }) {
  return <span className={`trail trail-${s}`}>{TRAIL_LABEL[s]}</span>;
}

function Monitor({ monitor }) {
  const [hl, setHl] = useState(null); // hovered hedge group
  const [trailFilter, setTrailFilter] = useState(null);
  const [dir, setDir] = useState(null);

  const list = useMemo(() =>
    monitor.filter((p) => (!trailFilter || p.trail === trailFilter) && (!dir || p.dir === dir)),
    [monitor, trailFilter, dir]);

  const sum = useMemo(() => {
    let netR = 0, armed = 0, trailing = 0, hedged = 0, buy = 0, sell = 0;
    for (const p of monitor) {
      netR += p.r;
      if (p.trail === "armed") armed++;
      if (p.trail === "trailing") trailing++;
      if (p.hedge) hedged++;
      if (p.dir === "BUY") buy++; else sell++;
    }
    return { netR: Math.round(netR * 10) / 10, armed, trailing, hedgedPairs: hedged / 2, buy, sell, n: monitor.length };
  }, [monitor]);

  return (
    <div className="screen screen-matrix">
      <div className="screen-head">
        <div className="screen-title">Position Monitor</div>
        <div className="screen-sub">Real-time open trades · <b className="mono">{sum.n}</b> live · net <span className={`mono ${sum.netR >= 0 ? "pos" : "neg"}`}>{sum.netR >= 0 ? "+" : "−"}{Math.abs(sum.netR).toFixed(1)}R</span></div>
      </div>

      {/* summary strip */}
      <div className="blotter-sum">
        <div className="bs-item"><span className="bs-lbl">OPEN</span><span className="bs-val mono">{sum.n}</span></div>
        <div className="bs-item"><span className="bs-lbl">TRAILING</span><span className="bs-val mono pos">{sum.trailing}</span></div>
        <div className="bs-item"><span className="bs-lbl">ARMED</span><span className="bs-val mono" style={{ color: "var(--warn)" }}>{sum.armed}</span></div>
        <div className="bs-item"><span className="bs-lbl">HEDGED PAIRS</span><span className="bs-val mono">{sum.hedgedPairs}</span></div>
        <div className="bs-item"><span className="bs-lbl">BUY / SELL</span><span className="bs-val mono"><span className="pos-buy">{sum.buy}</span> / <span className="pos-sell">{sum.sell}</span></span></div>
        <div className="filter-spacer"></div>
        <div className="filter-grp" style={{ borderRight: "1px solid var(--border-soft)" }}>
          <button className={`chip ${dir === "BUY" ? "active" : ""}`} onClick={() => setDir(dir === "BUY" ? null : "BUY")}>BUY</button>
          <button className={`chip ${dir === "SELL" ? "active" : ""}`} onClick={() => setDir(dir === "SELL" ? null : "SELL")}>SELL</button>
        </div>
        <div className="filter-grp" style={{ borderRight: "none", paddingRight: 0 }}>
          {["trailing", "armed", "idle"].map((t) => (
            <button key={t} className={`chip ${trailFilter === t ? "active" : ""}`} onClick={() => setTrailFilter(trailFilter === t ? null : t)}>{t}</button>
          ))}
        </div>
      </div>

      {/* monitor table */}
      <div className="tablewrap">
        <table className="matrix monitor">
          <thead>
            <tr>
              <th className="sticky-h sticky-c">Symbol</th>
              <th className="sticky-h">Direction</th>
              <th className="sticky-h r">Lot</th>
              <th className="sticky-h r">Entry</th>
              <th className="sticky-h r">SL</th>
              <th className="sticky-h r">TP</th>
              <th className="sticky-h r">Current R</th>
              <th className="sticky-h">Trailing</th>
              <th className="sticky-h">Hedge Relation</th>
            </tr>
          </thead>
          <tbody>
            {list.map((p, i) => {
              const linked = hl && p.hedge && p.hedge.id === hl;
              return (
                <tr key={p.ticket}
                    className={`mrow ${i % 2 ? "odd" : "even"} ${linked ? "hedge-hl" : ""}`}
                    onMouseEnter={() => setHl(p.hedge ? p.hedge.id : null)}
                    onMouseLeave={() => setHl(null)}
                    style={linked ? { boxShadow: `inset 3px 0 0 ${p.hedge.color}` } : undefined}>
                  <td className="sticky-c"><span className="setid mono">{p.sym}</span></td>
                  <td><span className={`mode ${p.dir === "BUY" ? "side-buy" : "side-sell"}`}>{p.dir === "BUY" ? "▲ BUY" : "▼ SELL"}</span></td>
                  <td className="r mono">{p.lot.toFixed(2)}</td>
                  <td className="r mono dim">{p.entry}</td>
                  <td className="r mono sl">{p.sl}</td>
                  <td className="r mono tp">{p.tp}</td>
                  <td className="r"><RCell r={p.r} /></td>
                  <td><TrailPill s={p.trail} /></td>
                  <td>
                    {p.hedge ? (
                      <span className="hedge-pill" style={{ color: p.hedge.color, borderColor: p.hedge.color + "66", background: p.hedge.color + "1a" }}>
                        <span className="hedge-link">⇄</span>{p.hedge.id}<span className="hedge-vs">vs {p.hedge.partner}</span>
                      </span>
                    ) : (
                      <span className="hedge-none mono">— unhedged</span>
                    )}
                  </td>
                </tr>
              );
            })}
            {list.length === 0 && <tr><td colSpan="9" className="empty">No positions match the current filters.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.Monitor = Monitor;
