/* ============================================================
   Dinasty Control — Positions blotter
   Accepts optional focusSet to filter to a single EA (row drill-down).
   ============================================================ */

function Positions({ positions, focusSet, onClearFocus }) {
  const [side, setSide] = useState(null);
  const [q, setQ] = useState("");

  const list = useMemo(() => {
    const qq = q.trim().toUpperCase();
    return positions.filter((p) => {
      if (focusSet && p.set !== focusSet) return false;
      if (side && p.side !== side) return false;
      if (qq && !(p.set.includes(qq) || p.symbol.includes(qq) || String(p.ticket).includes(qq))) return false;
      return true;
    });
  }, [positions, focusSet, side, q]);

  const sum = useMemo(() => {
    let pl = 0, lots = 0, buy = 0, sell = 0;
    for (const p of list) { pl += p.pl; lots += p.lots; if (p.side === "BUY") buy++; else sell++; }
    return { pl, lots: Math.round(lots * 100) / 100, buy, sell, n: list.length };
  }, [list]);

  return (
    <div className="screen screen-matrix">
      <div className="screen-head">
        <div className="screen-title">Positions</div>
        <div className="screen-sub">Live blotter · <b className="mono">{sum.n}</b> open · net <Num value={sum.pl} money showArrow={false} /></div>
        {focusSet && (
          <button className="focus-chip" onClick={onClearFocus}>
            <span className="focus-lbl">EA</span><span className="mono">{focusSet}</span><span className="focus-x">✕</span>
          </button>
        )}
      </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">VOLUME</span><span className="bs-val mono">{sum.lots.toFixed(2)} <i>lots</i></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="bs-item"><span className="bs-lbl">FLOATING P/L</span><span className="bs-val"><Num value={sum.pl} money /></span></div>
        <div className="filter-spacer"></div>
        <div className="filter-grp" style={{ borderRight: "none", paddingRight: 0 }}>
          <button className={`chip ${side === "BUY" ? "active" : ""}`} onClick={() => setSide(side === "BUY" ? null : "BUY")}>BUY</button>
          <button className={`chip ${side === "SELL" ? "active" : ""}`} onClick={() => setSide(side === "SELL" ? null : "SELL")}>SELL</button>
        </div>
        <input className="search mono" placeholder="ticket / set / symbol…" value={q} onChange={(e) => setQ(e.target.value)} />
      </div>

      {/* blotter table */}
      <div className="tablewrap">
        <table className="matrix blotter">
          <thead>
            <tr>
              <th className="sticky-h sticky-c">Ticket</th>
              <th className="sticky-h">SetID</th>
              <th className="sticky-h">Symbol</th>
              <th className="sticky-h">Side</th>
              <th className="sticky-h r">Lots</th>
              <th className="sticky-h r">Entry</th>
              <th className="sticky-h r">Current</th>
              <th className="sticky-h r">Pips</th>
              <th className="sticky-h r">Swap</th>
              <th className="sticky-h r">Age</th>
              <th className="sticky-h r">P/L</th>
            </tr>
          </thead>
          <tbody>
            {list.map((p, i) => (
              <tr key={p.ticket} className={`mrow ${i % 2 ? "odd" : "even"}`}>
                <td className="sticky-c mono dim">{p.ticket}</td>
                <td className="mono"><span className="setid">{p.set}</span></td>
                <td className="mono">{p.symbol}</td>
                <td><span className={`mode ${p.side === "BUY" ? "side-buy" : "side-sell"}`}>{p.side === "BUY" ? "▲ BUY" : "▼ SELL"}</span></td>
                <td className="r mono">{p.lots.toFixed(2)}</td>
                <td className="r mono dim">{p.entry}</td>
                <td className="r mono">{p.cur}</td>
                <td className={`r mono ${p.pips >= 0 ? "pos" : "neg"}`}>{p.pips >= 0 ? "+" : "−"}{Math.abs(p.pips)}</td>
                <td className={`r mono ${p.swap >= 0 ? "dim" : "neg"}`}>{p.swap >= 0 ? "" : "−"}{Math.abs(p.swap).toFixed(2)}</td>
                <td className="r mono dim">{p.age}</td>
                <td className="r mono heat" style={{ background: plHeat(p.pl, i % 2 ? "odd" : "even") }}><Num value={p.pl} money /></td>
              </tr>
            ))}
            {list.length === 0 && <tr><td colSpan="11" className="empty">No open positions match.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.Positions = Positions;
