// ViG Command Center — Alliance War Room UI kit (dark, game-like) + SVG charts
const { useState: useStateWU, useMemo: useMemoWU, useRef: useRefWU } = React;

const WARROOM_CSS = `
.warroom { position:relative; --wr-bg:#0a0b0f; --wr-panel:#13151c; --wr-panel2:#181b24; --wr-line:#262a36; --wr-text:#e7e9ef; --wr-dim:#8b8fa0; --wr-faint:#565b6e;
  background:
    radial-gradient(1100px 500px at 80% -10%, rgba(255,107,0,.07), transparent 60%),
    radial-gradient(900px 500px at 0% 0%, rgba(168,85,247,.06), transparent 55%),
    var(--wr-bg);
  color:var(--wr-text); margin:-20px; padding:20px; min-height:calc(100vh - 58px);
  font-feature-settings:"tnum";
}
.warroom::before{ content:''; position:absolute; inset:0; pointer-events:none; z-index:0;
  background-image:linear-gradient(rgba(255,255,255,.018) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.018) 1px,transparent 1px);
  background-size:40px 40px; mask-image:radial-gradient(circle at 50% 0%,#000,transparent 80%); }
.warroom > * { position:relative; z-index:1; }
.wr-panel{ background:linear-gradient(180deg,var(--wr-panel),var(--wr-panel2)); border:1px solid var(--wr-line); border-radius:14px; }
.wr-glow{ box-shadow:0 0 0 1px rgba(255,107,0,.08), 0 18px 40px -24px rgba(255,107,0,.4); }
.wr-chip{ background:rgba(255,255,255,.04); border:1px solid var(--wr-line); }
.wr-mono{ font-family:'Geist Mono',ui-monospace,monospace; }
.wr-grad-text{ background:linear-gradient(180deg,#fff,#aab); -webkit-background-clip:text; background-clip:text; color:transparent; }
.wr-scan{ position:absolute; inset:0; border-radius:inherit; pointer-events:none; background:linear-gradient(180deg,rgba(255,255,255,.05),transparent 30%); }
.wr-tab{ position:relative; transition:color .15s; }
.wr-tab-on::after{ content:''; position:absolute; left:8px; right:8px; bottom:-9px; height:2px; border-radius:2px; background:var(--accent,#FF6B00); box-shadow:0 0 10px var(--accent,#FF6B00); }
.wr-row:hover{ background:rgba(255,255,255,.025); }
.wr-input{ background:#0d0f15; border:1px solid var(--wr-line); color:var(--wr-text); border-radius:8px; outline:none; }
.wr-input:focus{ border-color:var(--accent,#FF6B00); box-shadow:0 0 0 3px rgba(255,107,0,.12); }
`;
function WarRoomStyles() { return <style dangerouslySetInnerHTML={{ __html: WARROOM_CSS }} />; }

const AL_COLOR = { VIG: '#FF6B00', RSP: '#3B82F6', NEF: '#A855F7' };
const fmtB = (n) => (n >= 1000 ? (n / 1000).toFixed(2) + 'K' : (+n).toFixed(1)) + 'B';
const fmtAdd = (n) => (n > 0 ? '+' : '') + (+n).toFixed(1);

function WarPanel({ title, sub, action, accent, glow, className = '', children, style }) {
  return (
    <section className={`wr-panel ${glow ? 'wr-glow' : ''} relative overflow-hidden ${className}`} style={style}>
      <div className="wr-scan"></div>
      {(title || action) && (
        <header className="relative flex items-center justify-between gap-3 px-4 pt-3.5 pb-3">
          <div className="min-w-0">
            {accent && <span className="mb-1 block h-0.5 w-7 rounded-full" style={{ background: accent, boxShadow: `0 0 8px ${accent}` }}></span>}
            <h3 className="truncate text-[12.5px] font-semibold uppercase tracking-[0.13em]" style={{ color: '#cfd2dc' }}>{title}</h3>
            {sub && <p className="mt-0.5 text-[11.5px]" style={{ color: 'var(--wr-faint)' }}>{sub}</p>}
          </div>
          {action}
        </header>
      )}
      <div className="relative">{children}</div>
    </section>
  );
}

function WrTag({ id, children, size = 'sm' }) {
  const c = AL_COLOR[id] || '#FF6B00';
  return <span className={`inline-flex items-center gap-1 rounded-md font-semibold ${size === 'sm' ? 'px-1.5 py-0.5 text-[10.5px]' : 'px-2 py-1 text-[12px]'}`} style={{ background: c + '1f', color: c, border: '1px solid ' + c + '40' }}>{children || id}</span>;
}

function WrStat({ label, value, sub, accent, delta }) {
  return (
    <div className="wr-panel relative overflow-hidden px-4 py-3.5">
      <div className="wr-scan"></div>
      <div className="text-[11px] uppercase tracking-[0.12em]" style={{ color: 'var(--wr-faint)' }}>{label}</div>
      <div className="mt-1 flex items-baseline gap-2">
        <span className="text-[26px] font-bold leading-none wr-grad-text" style={accent ? { background: `linear-gradient(180deg,#fff,${accent})`, WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent' } : {}}>{value}</span>
        {delta != null && <span className="text-[12px] font-semibold wr-mono" style={{ color: delta >= 0 ? '#34d399' : '#fb7185' }}>{fmtAdd(delta)}</span>}
      </div>
      {sub && <div className="mt-1 text-[11.5px]" style={{ color: 'var(--wr-dim)' }}>{sub}</div>}
    </div>
  );
}

/* ---------- charts ---------- */
function niceBounds(min, max) {
  if (min === max) { return [min - 1, max + 1]; }
  const pad = (max - min) * 0.12; return [min - pad, max + pad];
}

function LineChart({ series, labels, height = 200, area = true, yFmt = (v) => v.toFixed(0) }) {
  const W = 640, H = height, padL = 44, padR = 14, padT = 12, padB = 24;
  const all = series.flatMap(s => s.data);
  let [lo, hi] = niceBounds(Math.min(...all), Math.max(...all));
  const n = labels.length;
  const x = i => padL + (i / (n - 1)) * (W - padL - padR);
  const y = v => padT + (1 - (v - lo) / (hi - lo)) * (H - padT - padB);
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }}>
      {Array.from({ length: ticks + 1 }).map((_, i) => {
        const v = lo + (i / ticks) * (hi - lo), yy = y(v);
        return <g key={i}><line x1={padL} x2={W - padR} y1={yy} y2={yy} stroke="#23262f" strokeWidth="1" /><text x={padL - 7} y={yy + 3} textAnchor="end" fontSize="9.5" fill="#565b6e" className="wr-mono">{yFmt(v)}</text></g>;
      })}
      {labels.map((l, i) => <text key={i} x={x(i)} y={H - 7} textAnchor="middle" fontSize="9.5" fill="#565b6e">{l}</text>)}
      {series.map((s, si) => {
        const pts = s.data.map((v, i) => [x(i), y(v)]);
        const d = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
        const ad = d + ` L ${x(n - 1).toFixed(1)} ${y(lo).toFixed(1)} L ${x(0).toFixed(1)} ${y(lo).toFixed(1)} Z`;
        return (
          <g key={si}>
            {area && <><defs><linearGradient id={'g' + si} x1="0" x2="0" y1="0" y2="1"><stop offset="0" stopColor={s.color} stopOpacity="0.22" /><stop offset="1" stopColor={s.color} stopOpacity="0" /></linearGradient></defs><path d={ad} fill={`url(#g${si})`} /></>}
            <path d={d} fill="none" stroke={s.color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round" style={{ filter: `drop-shadow(0 0 5px ${s.color}66)` }} />
            <circle cx={x(n - 1)} cy={y(s.data[n - 1])} r="3.4" fill={s.color} style={{ filter: `drop-shadow(0 0 4px ${s.color})` }} />
          </g>
        );
      })}
    </svg>
  );
}

function BarsCompare({ items, max, fmt = (v) => v }) {
  const m = max || Math.max(...items.map(i => i.value));
  return (
    <div className="space-y-2.5">
      {items.map((it, i) => (
        <div key={i} className="flex items-center gap-3">
          <div className="w-12 shrink-0 text-[12px] font-semibold" style={{ color: it.color }}>{it.label}</div>
          <div className="h-6 flex-1 overflow-hidden rounded-md" style={{ background: '#0d0f15' }}>
            <div className="flex h-full items-center justify-end rounded-md px-2 transition-all duration-700" style={{ width: Math.max(8, it.value / m * 100) + '%', background: `linear-gradient(90deg,${it.color}55,${it.color})`, boxShadow: `0 0 14px ${it.color}55` }}>
              <span className="text-[11px] font-bold text-white wr-mono">{fmt(it.value)}</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function KeepDistribution({ keeps, accent, max }) {
  const m = max || Math.max(...AL_KEEPS.map(k => keeps[k] || 0), 1);
  return (
    <div className="flex items-end gap-1.5" style={{ height: 96 }}>
      {AL_KEEPS.map(k => {
        const v = keeps[k] || 0;
        const hot = k === 'K49' || k === 'K50';
        return (
          <div key={k} className="flex flex-1 flex-col items-center justify-end gap-1.5" style={{ height: '100%' }}>
            <span className="text-[10px] font-semibold wr-mono" style={{ color: v ? '#cfd2dc' : '#3b3f4d' }}>{v || ''}</span>
            <div className="w-full rounded-t transition-all duration-500" style={{ height: Math.max(v ? 6 : 2, v / m * 70) + '%', background: v ? (hot ? `linear-gradient(180deg,${accent},${accent}99)` : '#3a3f4e') : '#1c1f29', boxShadow: v && hot ? `0 0 12px ${accent}66` : 'none' }}></div>
            <span className="text-[9.5px] wr-mono" style={{ color: hot ? accent : 'var(--wr-faint)' }}>{k}</span>
          </div>
        );
      })}
    </div>
  );
}

// heat color: t in 0..1 → dark slate to accent
function heatColor(t, accent = '#FF6B00') {
  const c = { '#FF6B00': [255, 107, 0], '#3B82F6': [59, 130, 246], '#A855F7': [168, 85, 247] }[accent] || [255, 107, 0];
  const bg = [18, 20, 28];
  const e = Math.pow(Math.max(0, Math.min(1, t)), 0.7);
  const mix = bg.map((b, i) => Math.round(b + (c[i] - b) * e));
  return `rgb(${mix[0]},${mix[1]},${mix[2]})`;
}

function Sparkline({ data, color = '#FF6B00', w = 88, h = 26 }) {
  const lo = Math.min(...data), hi = Math.max(...data);
  const x = i => (i / (data.length - 1)) * w;
  const y = v => hi === lo ? h / 2 : h - 2 - ((v - lo) / (hi - lo)) * (h - 4);
  const d = data.map((v, i) => (i ? 'L' : 'M') + x(i).toFixed(1) + ' ' + y(v).toFixed(1)).join(' ');
  return <svg width={w} height={h} style={{ display: 'block' }}><path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" style={{ filter: `drop-shadow(0 0 3px ${color}88)` }} /></svg>;
}

function WrBtn({ variant = 'ghost', size = 'md', className = '', children, ...p }) {
  const sz = size === 'sm' ? 'h-8 px-3 text-[12.5px]' : 'h-9 px-4 text-[13px]';
  const styles = {
    primary: { background: 'linear-gradient(180deg,#ff7d1a,#FF6B00)', color: '#fff', border: '1px solid #ff8a33', boxShadow: '0 6px 18px -8px rgba(255,107,0,.7)' },
    ghost: { background: 'rgba(255,255,255,.04)', color: '#cfd2dc', border: '1px solid var(--wr-line)' },
    danger: { background: 'rgba(251,113,133,.1)', color: '#fb7185', border: '1px solid rgba(251,113,133,.3)' },
  }[variant];
  return <button className={`inline-flex items-center justify-center gap-1.5 rounded-lg font-semibold transition-all hover:brightness-110 ${sz} ${className}`} style={styles} {...p}>{children}</button>;
}

Object.assign(window, { WarRoomStyles, WarPanel, WrTag, WrStat, LineChart, BarsCompare, KeepDistribution, heatColor, Sparkline, WrBtn, AL_COLOR, fmtB, fmtAdd });
