/* atoms.jsx — Avero Operator Console — shared primitives
   Exposed on window for cross-file <script type="text/babel"> use. */
const { useState, useEffect, useRef, useMemo } = React;

/* ── format helpers ─────────────────────────────────────────────── */
const fmtNum = (n, dp = 2) => (n == null || isNaN(n)) ? '0'
  : Number(n).toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp });
const fmtPct = (n, dp = 2) => (n == null || isNaN(n)) ? '0%'
  : (n >= 0 ? '+' : '−') + Math.abs(n).toFixed(dp) + '%';
const fmtTime = (d) => {
  const p = (n) => String(n).padStart(2, '0');
  return `${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}`;
};

/* ── LED ────────────────────────────────────────────────────────── */
function LED({ tone = 'cyan', off = false }) {
  return <span className={off ? 'led off' : `led ${tone === 'cyan' ? '' : tone}`.trim()} />;
}

/* ── Chip / Badge ───────────────────────────────────────────────── */
function Chip({ tone = 'cyan', children }) { return <span className={`chip ${tone}`}>{children}</span>; }
function Badge({ kind, children }) { return <span className={`badge badge-${kind}`}>{children}</span>; }

/* ── AveroMark — the console "A" ────────────────────────────────── */
function AveroMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" fill="none">
      <defs>
        <linearGradient id="aGradAtom" x1="0" y1="0" x2="40" y2="40" gradientUnits="userSpaceOnUse">
          <stop offset="0" stopColor="#00f5ff" stopOpacity="0.7" />
          <stop offset="1" stopColor="#00f5ff" stopOpacity="1" />
        </linearGradient>
      </defs>
      <rect x="2" y="2" width="36" height="36" rx="8" stroke="url(#aGradAtom)" strokeWidth="1.4" opacity="0.35" />
      <path d="M8 32 L20 6 L32 32" stroke="url(#aGradAtom)" strokeWidth="2" strokeLinejoin="round" />
      <path d="M12 27 L20 13 L28 27" stroke="url(#aGradAtom)" strokeWidth="1.2" opacity="0.5" strokeLinejoin="round" />
      <rect x="13" y="22" width="14" height="2.5" rx="1" fill="#00f5ff" opacity="0.8" />
      <circle cx="20" cy="4" r="1.8" fill="#00f5ff">
        <animate attributeName="opacity" values="1;0.3;1" dur="2s" repeatCount="indefinite" />
      </circle>
      <path d="M6 34 L10 34 M30 34 L34 34" stroke="url(#aGradAtom)" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

/* ── MetricCard ─────────────────────────────────────────────────── */
function MetricCard({ label, value, sub, subColor, accent = 'cyan' }) {
  return (
    <div className={`metric-card stat-accent-${accent}`}>
      <div className="mc-label">{label}</div>
      <div className="mc-value">{value}</div>
      {sub && <div className="mc-sub" style={subColor ? { color: subColor } : null}>{sub}</div>}
    </div>
  );
}

/* ── Spark — tiny inline sparkline ──────────────────────────────── */
function Spark({ data, w = 72, h = 22, color = 'var(--cyan)' }) {
  if (!data || data.length < 2) return null;
  const min = Math.min(...data), max = Math.max(...data), range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1) * w).toFixed(1)},${(h - (v - min) / range * h).toFixed(1)}`).join(' ');
  return <svg width={w} height={h} style={{ display: 'block', opacity: 0.85 }}><polyline points={pts} stroke={color} strokeWidth="1.2" fill="none" /></svg>;
}

/* ── GradientRing — confidence gauge ────────────────────────────── */
function GradientRing({ value = 0, size = 150, strokeWidth = 8, children }) {
  const R = size / 2 - strokeWidth - 4, C = 2 * Math.PI * R, offset = C - value / 100 * C, c = size / 2;
  return (
    <div style={{ position: 'relative', width: size, height: size, margin: '0 auto' }}>
      <svg width={size} height={size}>
        <defs>
          <linearGradient id="ringGradAtom" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="var(--cyan)" stopOpacity="0.9" />
            <stop offset="100%" stopColor="var(--violet-hi)" stopOpacity="1" />
          </linearGradient>
        </defs>
        <circle cx={c} cy={c} r={R} fill="none" stroke="rgba(0,245,255,0.07)" strokeWidth={strokeWidth} />
        <circle cx={c} cy={c} r={R} fill="none" stroke="url(#ringGradAtom)" strokeWidth={strokeWidth}
          strokeDasharray={C} strokeDashoffset={offset} strokeLinecap="round"
          transform={`rotate(-90 ${c} ${c})`} style={{ transition: 'stroke-dashoffset .6s cubic-bezier(.16,1,.3,1)' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>{children}</div>
    </div>
  );
}

Object.assign(window, { useState, useEffect, useRef, useMemo, fmtNum, fmtPct, fmtTime, LED, Chip, Badge, AveroMark, MetricCard, Spark, GradientRing });
