/**
 * 军费总览 — Token 消耗归因、上下文压力、预算状态
 * 三国术语：军费/各营消耗/兵器消耗/军令消耗/粮草告急
 */

import { useStore } from '../store';
import type { OfficialInfo } from '../api';

export default function UsagePanel() {
  const officialsData = useStore((s) => s.officialsData);

  // 从真实数据构建归因，fallback 到空数组
  const officials = officialsData?.officials || [];
  const totals = officialsData?.totals || { tasks_done: 0, cost_cny: 0 };

  // 各营消耗（按 Agent）
  const byAgent: Array<{ name: string; emoji: string; tokens: number; cost: number; pct: number }> = [];
  const totalTokens = officials.reduce((s, o) => s + o.tokens_in + o.tokens_out + o.cache_read + o.cache_write, 0) || 1;
  for (const o of officials) {
    const tk = o.tokens_in + o.tokens_out + o.cache_read + o.cache_write;
    byAgent.push({
      name: o.role.split(' ')[0],
      emoji: o.emoji,
      tokens: tk,
      cost: o.cost_cny,
      pct: Math.round((tk / totalTokens) * 100),
    });
  }
  byAgent.sort((a, b) => b.tokens - a.tokens);

  // 兵器消耗（按模型）
  const modelMap = new Map<string, { tokens: number; cost: number }>();
  for (const o of officials) {
    const key = o.model_short || o.model;
    const tk = o.tokens_in + o.tokens_out + o.cache_read + o.cache_write;
    const existing = modelMap.get(key) || { tokens: 0, cost: 0 };
    existing.tokens += tk;
    existing.cost += o.cost_cny;
    modelMap.set(key, existing);
  }
  const byModel = Array.from(modelMap.entries()).map(([name, data]) => ({
    name,
    ...data,
    pct: Math.round((data.tokens / totalTokens) * 100),
  })).sort((a, b) => b.tokens - a.tokens);

  // 军令消耗（参与军令 top 5）
  const taskMap = new Map<string, { title: string; tokens: number; cost: number }>();
  for (const o of officials) {
    for (const e of o.participated_edicts) {
      const existing = taskMap.get(e.id) || { title: e.title, tokens: 0, cost: 0 };
      existing.tokens += o.tokens_in + o.tokens_out;
      existing.cost += o.cost_cny / Math.max(o.participated_edicts.length, 1);
      taskMap.set(e.id, existing);
    }
  }
  const byTask = Array.from(taskMap.values())
    .sort((a, b) => b.cost - a.cost)
    .slice(0, 5);

  // 粮草告急（上下文压力）
  const contextWindows = officials.map((o: OfficialInfo) => {
    const used = (o.tokens_in + o.tokens_out) / 2000; // 粗估 k tokens
    const max = 200; // 200k context
    const pct = Math.round((used / max) * 100);
    const status = pct > 80 ? 'high' : pct > 50 ? 'warn' : 'ok';
    return { agent: o.role.split(' ')[0], emoji: o.emoji, used: Math.round(used), max, pct, status };
  }).sort((a, b) => b.pct - a.pct);

  const totalCost = byAgent.reduce((s, a) => s + a.cost, 0);
  const highPressure = contextWindows.filter((cw) => cw.status === 'high').length;

  return (
    <div>
      {/* 军费摘要卡片 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 10, marginBottom: 24 }}>
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 14, padding: 18, textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: 'var(--acc)' }}>{(totalTokens / 1000000).toFixed(1)}M</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>总 Token</div>
        </div>
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 14, padding: 18, textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: '#f5c842' }}>¥{totalCost.toFixed(1)}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>军费总计</div>
        </div>
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 14, padding: 18, textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: 'var(--ok)' }}>{totals.tasks_done || 0}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>完成军令</div>
        </div>
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 14, padding: 18, textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: highPressure > 0 ? 'var(--danger)' : 'var(--ok)' }}>{highPressure}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>粮草告急</div>
        </div>
      </div>

      {/* 各营消耗 */}
      <div style={{ fontWeight: 700, color: 'var(--acc)', marginBottom: 10, fontSize: 14, borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
        ⚔️ 各营消耗
      </div>
      {byAgent.map((a) => (
        <div key={a.name} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
          <span style={{ width: 24 }}>{a.emoji}</span>
          <span style={{ width: 50, fontSize: 12 }}>{a.name}</span>
          <div style={{ flex: 1, height: 10, background: '#0e1320', borderRadius: 5, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${a.pct}%`, background: 'linear-gradient(90deg, var(--acc), #a07aff)', borderRadius: 5, transition: 'width .3s' }} />
          </div>
          <span style={{ fontSize: 11, color: 'var(--muted)', width: 60, textAlign: 'right' }}>{(a.tokens / 1000).toFixed(0)}k</span>
          <span style={{ fontSize: 11, color: '#f5c842', width: 50, textAlign: 'right' }}>¥{a.cost.toFixed(1)}</span>
          <span style={{ fontSize: 10, color: 'var(--muted)', width: 30, textAlign: 'right' }}>{a.pct}%</span>
        </div>
      ))}

      {/* 兵器消耗 */}
      <div style={{ fontWeight: 700, color: 'var(--acc)', marginTop: 20, marginBottom: 10, fontSize: 14, borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
        🗡️ 兵器消耗
      </div>
      {byModel.map((m) => (
        <div key={m.name} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
          <span style={{ fontSize: 12, width: 160, color: 'var(--text)' }}>{m.name}</span>
          <div style={{ flex: 1, height: 10, background: '#0e1320', borderRadius: 5, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${m.pct}%`, background: 'linear-gradient(90deg, #2ecc8a, var(--acc))', borderRadius: 5 }} />
          </div>
          <span style={{ fontSize: 11, color: 'var(--muted)', width: 60, textAlign: 'right' }}>{(m.tokens / 1000).toFixed(0)}k</span>
          <span style={{ fontSize: 11, color: '#f5c842', width: 50, textAlign: 'right' }}>¥{m.cost.toFixed(1)}</span>
        </div>
      ))}

      {/* 军令消耗 Top 5 */}
      <div style={{ fontWeight: 700, color: 'var(--acc)', marginTop: 20, marginBottom: 10, fontSize: 14, borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
        📜 军令消耗（前5）
      </div>
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12 }}>
        {byTask.length === 0 ? (
          <div style={{ padding: 14, fontSize: 12, color: 'var(--muted)' }}>暂无军令数据</div>
        ) : (
          byTask.map((t, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 14px', borderBottom: i < byTask.length - 1 ? '1px solid #0e1320' : 'none' }}>
              <span style={{ fontSize: 12 }}>{t.title}</span>
              <div style={{ display: 'flex', gap: 16 }}>
                <span style={{ fontSize: 11, color: 'var(--muted)' }}>{(t.tokens / 1000).toFixed(0)}k tokens</span>
                <span style={{ fontSize: 11, color: '#f5c842' }}>¥{t.cost.toFixed(1)}</span>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 粮草告急 */}
      <div style={{ fontWeight: 700, color: 'var(--acc)', marginTop: 20, marginBottom: 10, fontSize: 14, borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
        🌾 粮草告急
      </div>
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12 }}>
        {contextWindows.map((cw, i) => (
          <div key={cw.agent} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderBottom: i < contextWindows.length - 1 ? '1px solid #0e1320' : 'none' }}>
            <span style={{ width: 20 }}>{cw.emoji}</span>
            <span style={{ width: 50, fontSize: 12 }}>{cw.agent}</span>
            <div style={{ flex: 1, height: 6, background: '#0e1320', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{
                height: '100%',
                width: `${cw.pct}%`,
                borderRadius: 3,
                background: cw.status === 'high' ? '#ff5270' : cw.status === 'warn' ? '#f5c842' : '#2ecc8a',
              }} />
            </div>
            <span style={{ fontSize: 10, color: cw.status === 'high' ? '#ff5270' : cw.status === 'warn' ? '#f5c842' : 'var(--muted)' }}>
              {cw.used}k / {cw.max}k {cw.status === 'high' && '⚠️'}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
