/* ============================================================
   Dinasty Control — shared UI atoms & chrome
   ============================================================ */
const { useState, useEffect, useMemo, useRef } = React;

/* ---------- formatters ---------- */
const fmtInt = (n) => Math.round(n).toLocaleString("en-US");
const fmtMoney = (n) => "$" + fmtInt(Math.abs(n));
const fmtSignedMoney = (n) => (n >= 0 ? "+$" : "−$") + fmtInt(Math.abs(n));
const fmtSignedNum = (n) => (n >= 0 ? "+" : "−") + Math.abs(n).toLocaleString("en-US");
const arrow = (n) => (n > 0 ? "▲" : n < 0 ? "▼" : "■");

/* ---------- signed numeric cell ---------- */
function Num({ value, money = false, className = "", showArrow = true }) {
  const cls = value > 0 ? "pos" : value < 0 ? "neg" : "flat";
  const txt = money ? fmtSignedMoney(value) : fmtSignedNum(value);
  return (
    <span className={`num ${cls} ${className}`}>
      {showArrow && <span className="num-arw">{arrow(value)}</span>}
      {txt}
    </span>
  );
}

/* ---------- recommendation pill ---------- */
function RecPill({ rec }) {
  return <span className={`pill pill-${rec.toLowerCase()}`}>{rec}</span>;
}

/* ---------- AI status badge ---------- */
const AI_META = {
  NORMAL: { cls: "ai-normal", dot: "AI" },
  WATCH:  { cls: "ai-watch",  dot: "AI" },
  REDUCE: { cls: "ai-reduce", dot: "AI" },
  PAUSE:  { cls: "ai-pause",  dot: "AI" },
};
function AIBadge({ status, large = false }) {
  const m = AI_META[status] || AI_META.NORMAL;
  return (
    <span className={`aibadge ${m.cls} ${large ? "aibadge-lg" : ""}`}>
      <span className="aibadge-glyph">◆</span>
      <span className="aibadge-label">AI</span>
      <span className="aibadge-state">{status}</span>
    </span>
  );
}

/* ---------- nav icons (functional line icons) ---------- */
const Icon = ({ name }) => {
  const common = { width: 16, height: 16, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "overview":
      return (<svg {...common}><rect x="1.5" y="1.5" width="5.5" height="5.5" rx="1"/><rect x="9" y="1.5" width="5.5" height="5.5" rx="1"/><rect x="1.5" y="9" width="5.5" height="5.5" rx="1"/><rect x="9" y="9" width="5.5" height="5.5" rx="1"/></svg>);
    case "matrix":
      return (<svg {...common}><rect x="1.5" y="2" width="13" height="12" rx="1"/><path d="M1.5 6h13M1.5 10h13M6 2v12"/></svg>);
    case "positions":
      return (<svg {...common}><path d="M2 12.5 6 8l3 2.6L14 4"/><path d="M14 7V4h-3"/></svg>);
    case "monitor":
      return (<svg {...common}><path d="M1.5 8h3l1.5-4 2.5 8 1.5-4h3"/></svg>);
    case "ai":
      return (<svg {...common}><rect x="4" y="4" width="8" height="8" rx="1.5"/><path d="M6 1.5v2M10 1.5v2M6 12.5v2M10 12.5v2M1.5 6h2M1.5 10h2M12.5 6h2M12.5 10h2"/></svg>);
    case "daily":
      return (<svg {...common}><rect x="2" y="2.5" width="12" height="12" rx="1.5"/><path d="M2 5.5h12M5 1.5v2M11 1.5v2"/><path d="M5.4 9.6 7 11.1l3.1-3.3"/></svg>);
    case "chevron":
      return (<svg {...common}><path d="M6 3.5 10.5 8 6 12.5"/></svg>);
    case "signout":
      return (<svg {...common}><path d="M6 14H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h3"/><path d="M10.5 11 14 8l-3.5-3M14 8H6"/></svg>);
    default: return null;
  }
};

/* ---------- brand mark: crown + D + arrow monogram ---------- */
function BrandMark({ size = 26, gid = "bm" }) {
  return (
    <svg className="brandmark" width={size} height={size * 1.24} viewBox="0 0 120 150" fill="none" aria-label="Dinasty Future">
      <defs>
        <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#F7D488" />
          <stop offset="52%" stopColor="#ECBA5A" />
          <stop offset="100%" stopColor="#D79A30" />
        </linearGradient>
      </defs>
      <g stroke={`url(#${gid})`} strokeWidth="5.4" strokeLinejoin="round" strokeLinecap="round">
        <path d="M32 50 L24 14 L47 33 L60 6 L73 33 L96 14 L88 50 Z" />
        <path d="M36 146 L36 58 L62 58 C79 58 89 77 89 102 C89 127 79 146 62 146 Z" />
        <path d="M46 126 L82 78" />
        <path d="M82 78 L64 78 M82 78 L82 96" />
      </g>
    </svg>
  );
}

/* ---------- top bar ---------- */
function ServerClock() {
  const [now, setNow] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const hh = String(now.getUTCHours()).padStart(2, "0");
  const mm = String(now.getUTCMinutes()).padStart(2, "0");
  const ss = String(now.getUTCSeconds()).padStart(2, "0");
  return (
    <div className="clock">
      <span className="clock-label">SRV</span>
      <span className="clock-time">{hh}:{mm}:{ss}</span>
      <span className="clock-tz">UTC</span>
    </div>
  );
}

function VpsDot({ name, state, ping }) {
  return (
    <div className="vpsdot" title={`${name} · ${state}`}>
      <span className={`dot dot-${state}`}></span>
      <span className="vpsdot-name">{name}</span>
      <span className="vpsdot-ping">{ping}ms</span>
    </div>
  );
}

function TopBar({ aiStatus }) {
  return (
    <header className="topbar">
      <div className="topbar-left">
        <div className="logo">
          <span className="logo-mark"><BrandMark size={26} gid="bm-top" /></span>
          <span className="logo-name">DINASTY<span className="logo-sub">CONTROL</span></span>
        </div>
        <span className="env-tag">LIVE</span>
      </div>
      <div className="topbar-right">
        <ServerClock />
        <div className="divider"></div>
        <div className="vps-cluster">
          <VpsDot name="VPS-1" state="ok" ping={42} />
          <VpsDot name="VPS-2" state="warn" ping={214} />
        </div>
        <div className="divider"></div>
        <AIBadge status={aiStatus} />
      </div>
    </header>
  );
}

/* ---------- sidebar ---------- */
const NAV = [
  { id: "overview", label: "Overview", icon: "overview" },
  { id: "matrix", label: "Matrix", icon: "matrix" },
  { id: "positions", label: "Positions", icon: "positions" },
  { id: "monitor", label: "Monitor", icon: "monitor" },
  { id: "ai", label: "AI Eval", icon: "ai" },
  { id: "daily", label: "Daily Eval", icon: "daily" },
];
function Sidebar({ active, onNav, collapsed, onToggle, onSignOut }) {
  return (
    <nav className={`sidebar ${collapsed ? "collapsed" : ""}`}>
      <button className="side-toggle" onClick={onToggle} title="Toggle sidebar">
        <span className={`side-toggle-icon ${collapsed ? "" : "open"}`}><Icon name="chevron" /></span>
      </button>
      <div className="side-nav">
        {NAV.map((n) => (
          <button key={n.id} className={`navitem ${active === n.id ? "active" : ""}`} onClick={() => onNav(n.id)} title={n.label}>
            <span className="navitem-icon"><Icon name={n.icon} /></span>
            <span className="navitem-label">{n.label}</span>
          </button>
        ))}
      </div>
      <div className="side-foot">
        <button className="navitem signout" onClick={onSignOut} title="Sign Out">
          <span className="navitem-icon"><Icon name="signout" /></span>
          <span className="navitem-label">Sign Out</span>
        </button>
        <div className="side-foot-row"><span className="dot dot-ok"></span><span className="navitem-label">Feed live</span></div>
      </div>
    </nav>
  );
}

Object.assign(window, { useState, useEffect, useMemo, useRef, fmtInt, fmtMoney, fmtSignedMoney, fmtSignedNum, arrow, Num, RecPill, AIBadge, Icon, BrandMark, TopBar, Sidebar });
