/* ============================================================
   Dinasty Control — Overview screen
   ============================================================ */

/* compact metric card */
function MetricCard({ label, children, hint, tone }) {
  return (
    <div className={`metric ${tone ? "metric-" + tone : ""}`}>
      <div className="metric-label">{label}</div>
      <div className="metric-body">{children}</div>
      {hint && <div className="metric-hint">{hint}</div>}
    </div>
  );
}

/* SVG sparkline */
function Sparkline({ points, width = 560, height = 72 }) {
  const min = Math.min(...points), max = Math.max(...points);
  const span = max - min || 1;
  const stepX = width / (points.length - 1);
  const y = (v) => height - 6 - ((v - min) / span) * (height - 12);
  const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${(i * stepX).toFixed(1)} ${y(p).toFixed(1)}`).join(" ");
  const area = `${d} L${width} ${height} L0 ${height} Z`;
  const up = points[points.length - 1] >= points[0];
  const col = up ? "#36D98F" : "#F25C62";
  return (
    <svg className="spark" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="sparkfill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={col} stopOpacity="0.22" />
          <stop offset="100%" stopColor={col} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkfill)" />
      <path d={d} fill="none" stroke={col} strokeWidth="1.4" strokeLinejoin="round" />
      <circle cx={width} cy={y(points[points.length - 1])} r="2.4" fill={col} />
    </svg>
  );
}

/* Buy vs Sell exposure ratio bar */
function ExposureBar({ buy, sell }) {
  const total = buy + sell || 1;
  const bp = (buy / total) * 100;
  return (
    <div className="expo">
      <div className="expo-bar">
        <div className="expo-buy" style={{ width: bp + "%" }}></div>
        <div className="expo-sell" style={{ width: 100 - bp + "%" }}></div>
      </div>
      <div className="expo-legend">
        <span className="expo-side"><span className="sq sq-buy"></span>BUY {buy.toFixed(1)}</span>
        <span className="expo-side expo-right">SELL {sell.toFixed(1)}<span className="sq sq-sell"></span></span>
      </div>
    </div>
  );
}

const ALERT_TONE = { pause: "neg", reduce: "warn", watch: "accent", normal: "muted" };
const ALERT_TAG = { pause: "PAUSE", reduce: "REDUCE", watch: "WATCH", normal: "INFO" };

function Overview({ data, onGoMatrix }) {
  const { overview: o, equityCurve, alerts, vpsHealth } = data;
  return (
    <div className="screen">
      <div className="screen-head">
        <div className="screen-title">Overview</div>
        <div className="screen-sub">Portfolio snapshot · {o.counts.openSets} sets trading · {o.counts.openPositions} open positions</div>
      </div>

      {/* metric cards row */}
      <div className="metric-row">
        <MetricCard label="Total Equity" hint="2 VPS · 6 accounts">
          <div className="metric-big mono">{fmtMoney(o.totalEquity)}</div>
        </MetricCard>

        <MetricCard label="Floating P/L" hint={`${o.counts.openSets} sets open`}>
          <div className="metric-big mono"><Num value={o.floatingPL} money /></div>
        </MetricCard>

        <MetricCard label="Daily P/L" hint="since 00:00 UTC">
          <div className="metric-big mono"><Num value={o.dailyPL} money /></div>
        </MetricCard>

        <MetricCard label="Max Drawdown" tone={o.ddPct > 8 ? "danger" : "warn"} hint="peak-to-trough, 24h">
          <div className="metric-big mono dd">
            <span className="dd-pct">−{o.ddPct}%</span>
          </div>
          <div className="metric-sub mono">−{fmtMoney(o.ddAmount).slice(1)} </div>
        </MetricCard>

        <MetricCard label="Open Exposure" hint="net by volume">
          <ExposureBar buy={o.buyLots} sell={o.sellLots} />
        </MetricCard>

        <MetricCard label="AI Daily Status" hint={`${o.counts.pause} pause · ${o.counts.reduce} reduce`}>
          <div className="metric-ai"><AIBadge status={o.aiStatus} large /></div>
        </MetricCard>
      </div>

      {/* secondary operational row */}
      <div className="ov-grid">
        <section className="panel ov-equity">
          <div className="panel-head">
            <span className="panel-title">Equity · 24h</span>
            <span className="panel-meta mono"><Num value={o.floatingPL + o.dailyPL} money showArrow={false} /> session</span>
          </div>
          <Sparkline points={equityCurve} />
        </section>

        <section className="panel ov-vps">
          <div className="panel-head"><span className="panel-title">VPS Health</span></div>
          <table className="mini">
            <thead><tr><th>Node</th><th className="r">Sets</th><th className="r">Open</th><th className="r">Risky</th><th className="r">P/L</th></tr></thead>
            <tbody>
              {vpsHealth.map((v) => (
                <tr key={v.vps}>
                  <td><span className={`dot ${v.vps === "VPS-2" ? "dot-warn" : "dot-ok"}`}></span>{v.vps}</td>
                  <td className="r mono">{v.sets}</td>
                  <td className="r mono">{v.open}</td>
                  <td className="r mono risk-n">{v.risky}</td>
                  <td className="r mono"><Num value={v.pl} money showArrow={false} /></td>
                </tr>
              ))}
            </tbody>
          </table>
          <button className="ov-link" onClick={onGoMatrix}>Open EA Matrix →</button>
        </section>

        <section className="panel ov-alerts">
          <div className="panel-head"><span className="panel-title">AI Activity</span><span className="panel-meta">last 30 min</span></div>
          <ul className="feed">
            {alerts.map((a, i) => (
              <li key={i} className="feed-row">
                <span className="feed-time mono">{a.t}</span>
                <span className={`feed-tag tag-${a.level}`}>{ALERT_TAG[a.level]}</span>
                <span className="feed-set mono">{a.set}</span>
                <span className="feed-msg">{a.msg}</span>
              </li>
            ))}
          </ul>
        </section>
      </div>
    </div>
  );
}

window.Overview = Overview;
