// Tiny primitive components.
const fmtTs = (t, opt = {}) => {
  const d = new Date(t);
  const pad = n => String(n).padStart(2, '0');
  if (opt.short) return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  if (opt.dateOnly) return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
const fmtNum = (n, dp = 2) => {
  if (n == null || isNaN(n)) return '—';
  const sign = n < 0 ? '-' : '';
  const a = Math.abs(n);
  return sign + a.toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp });
};
const fmtPct = (n, dp = 2) => `${n >= 0 ? '+' : ''}${(n*100).toFixed(dp)}%`;
const since = (t) => {
  const d = Math.floor((Date.now() - t)/1000);
  if (d < 60) return `${d}s ago`;
  if (d < 3600) return `${Math.floor(d/60)}m ago`;
  if (d < 86400) return `${Math.floor(d/3600)}h ago`;
  return `${Math.floor(d/86400)}d ago`;
};

// Pill — used everywhere for state/severity/mode tags.
function Pill({ tone = 'ink', children, dot = false, className = '' }) {
  const tones = {
    ink:   'text-ink-1 bg-bg-2 border-line-1',
    pos:   'text-pos-0 bg-pos-2/30 border-pos-1/40',
    neg:   'text-neg-0 bg-neg-2/30 border-neg-1/40',
    amb:   'text-amb-0 bg-amb-1/15 border-amb-1/40',
    inf:   'text-inf-0 bg-inf-1/15 border-inf-1/40',
    live:  'text-neg-0 bg-neg-2/30 border-neg-1/50',
    paper: 'text-amb-0 bg-amb-1/15 border-amb-1/40',
    testnet:'text-inf-0 bg-inf-1/15 border-inf-1/40',
  };
  return (
    <span className={`inline-flex items-center gap-1.5 px-1.5 py-0.5 border text-[10.5px] uppercase tracking-[0.08em] font-medium mono ${tones[tone] || tones.ink} ${className}`}>
      {dot && <span className="w-1 h-1 bg-current"></span>}
      {children}
    </span>
  );
}

// Card — every panel uses this. Hairline border, dim header.
function Card({ title, sub, action, children, padded = true, className = '' }) {
  return (
    <section className={`bg-bg-1 border border-line-0 ${className}`}>
      {(title || action) && (
        <header className="flex items-center justify-between border-b border-line-0 px-3 py-2">
          <div className="flex items-baseline gap-2">
            {title && <h2 className="text-[11px] uppercase tracking-[0.16em] text-ink-2 font-medium">{title}</h2>}
            {sub && <span className="text-[11px] text-ink-3 mono">{sub}</span>}
          </div>
          {action}
        </header>
      )}
      <div className={padded ? 'p-3' : ''}>{children}</div>
    </section>
  );
}

// Stat — big number + label + delta. Used in dashboard top row.
function Stat({ label, value, sub, delta, deltaTone, mono = true }) {
  return (
    <div className="bg-bg-1 border border-line-0 p-3 flex flex-col gap-1.5">
      <div className="flex items-center justify-between">
        <span className="text-[10.5px] uppercase tracking-[0.14em] text-ink-3 font-medium">{label}</span>
        {delta != null && (
          <span className={`text-[10.5px] mono ${deltaTone === 'pos' ? 'text-pos-0' : deltaTone === 'neg' ? 'text-neg-0' : 'text-ink-2'}`}>{delta}</span>
        )}
      </div>
      <div className={`text-[24px] leading-none ${mono ? 'num' : ''} text-ink-0 font-medium`}>{value}</div>
      {sub && <span className="text-[11px] text-ink-3 mono">{sub}</span>}
    </div>
  );
}

// Click-to-copy text. Used for client_order_ids etc.
function Copy({ text, display, className = '' }) {
  const [done, setDone] = React.useState(false);
  return (
    <button
      onClick={(e) => { e.stopPropagation(); navigator.clipboard?.writeText(text); setDone(true); setTimeout(() => setDone(false), 900); }}
      className={`group inline-flex items-center gap-1 mono text-[11px] hover:text-ink-0 ${done ? 'text-pos-0' : 'text-ink-2'} ${className}`}
      title={text}
    >
      <span>{display || text}</span>
      {done ? <Icon.Check size={11} /> : <Icon.Copy size={11} className="opacity-0 group-hover:opacity-100 transition-opacity" />}
    </button>
  );
}

// Tiny inline sparkline.
function Sparkline({ data, w = 80, h = 22, color = '#7aaed8' }) {
  if (!data || !data.length) return null;
  const min = Math.min(...data), max = Math.max(...data);
  const span = max - min || 1;
  const step = w / (data.length - 1);
  const pts = data.map((v, i) => `${i*step},${h - ((v-min)/span)*h}`).join(' ');
  return (
    <svg width={w} height={h} className="block">
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1" strokeLinejoin="round" />
    </svg>
  );
}

// Section divider with a small title — used inside dense panels.
function Divider({ children, className = '' }) {
  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <span className="text-[10px] uppercase tracking-[0.14em] text-ink-3">{children}</span>
      <div className="flex-1 h-px bg-line-0"></div>
    </div>
  );
}

window.UI = { fmtTs, fmtNum, fmtPct, since, Pill, Card, Stat, Copy, Sparkline, Divider };
