/* global React */
// Mock data + helpers shared by all pages.

const TYPE_COLORS = {
  '一般': 'var(--t-normal)', '火': 'var(--t-fire)', '水': 'var(--t-water)',
  '电': 'var(--t-electric)', '草': 'var(--t-grass)', '冰': 'var(--t-ice)',
  '格斗': 'var(--t-fighting)', '毒': 'var(--t-poison)', '地面': 'var(--t-ground)',
  '飞行': 'var(--t-flying)', '超能力': 'var(--t-psychic)', '虫': 'var(--t-bug)',
  '岩石': 'var(--t-rock)', '幽灵': 'var(--t-ghost)', '龙': 'var(--t-dragon)',
  '恶': 'var(--t-dark)', '钢': 'var(--t-steel)', '妖精': 'var(--t-fairy)',
};

const AREAS = [
  { code: 'GUANDU',  name: '关都',    color: '#EF4444', count: 56 },
  { code: 'CHENGDU', name: '城都',    color: '#10B981', count: 42 },
  { code: 'FENGYUAN',name: '丰缘',    color: '#3B82F6', count: 38 },
  { code: 'SHENAO',  name: '神奥',    color: '#A855F7', count: 31 },
  { code: 'HEYI',    name: '合一',    color: '#F59E0B', count: 22 },
];

const NPCS_GUANDU = [
  { id: 'xiao-mao', name: '小茂', team_count: 12 },
  { id: 'xiao-zhi', name: '小智', team_count: 9 },
  { id: 'lv-zhi',   name: '绿吉', team_count: 6 },
  { id: 'kana',     name: '坎娜', team_count: 4 },
  { id: 'shi-ji',   name: '石矶', team_count: 5 },
  { id: 'la-pa',    name: '拉帕', team_count: 3 },
  { id: 'da-mu',    name: '大木', team_count: 7 },
  { id: 'xiao-gang',name: '小刚', team_count: 5 },
  { id: 'xiao-xia', name: '小霞', team_count: 5 },
  { id: 'a-qi',     name: '阿琦', team_count: 4 },
];

const POKEMON = [
  { name: '喷火龙', types: ['火','飞行'], color: '#F08030' },
  { name: '水箭龟', types: ['水'],        color: '#6890F0' },
  { name: '妙蛙花', types: ['草','毒'],   color: '#78C850' },
  { name: '皮卡丘', types: ['电'],        color: '#F8D030' },
  { name: '快龙',   types: ['龙','飞行'], color: '#7038F8' },
  { name: '超梦',   types: ['超能力'],    color: '#F85888' },
  { name: '耿鬼',   types: ['幽灵','毒'], color: '#705898' },
  { name: '钢铁人', types: ['钢','超能力'], color: '#B8B8D0' },
  { name: '吉利蛋', types: ['一般'],      color: '#A8A878' },
  { name: '岩石蛇', types: ['岩石','地面'], color: '#B8A038' },
  { name: '巨钳螳螂',types:['虫','钢'],   color: '#A8B820' },
  { name: '比卡丘', types: ['电'],        color: '#F8D030' },
  { name: '杰尼龟', types: ['水'],        color: '#6890F0' },
  { name: '可达鸭', types: ['水'],        color: '#6890F0' },
  { name: '凯西',   types: ['超能力'],    color: '#F85888' },
];

function rndPick(arr, n) {
  const copy = [...arr];
  const out = [];
  for (let i = 0; i < n; i++) out.push(copy[(i * 7 + n) % copy.length]);
  return out;
}
function deterministicTeam(seed, n = 6) {
  const out = [];
  for (let i = 0; i < n; i++) {
    out.push(POKEMON[(seed * 13 + i * 7) % POKEMON.length]);
  }
  return out;
}

// Sample submissions
const SUBMISSIONS = [
  { id: 247, area_code: 'GUANDU',  npc: '小茂', npc_id: 'xiao-mao', status: 'pending',
    speed: 'S+', drug: '极王果', weather: '晴天', ding: true, lock: false, chu: false,
    submitter: '198.51.100.42', submitter_short: '198.51.x.42',
    note: '玩家 Lv50 实测的双攻反差队,中速', created_at: '2026-05-19T13:42:00',
    team: deterministicTeam(247) },
  { id: 246, area_code: 'CHENGDU', npc: '阿渡', npc_id: 'a-du',     status: 'pending',
    speed: 'S', drug: '哑铃果', weather: '雨天', ding: false, lock: true, chu: false,
    submitter: '203.0.113.18', submitter_short: '203.0.x.18',
    note: '主打防守反击,2 只锁血', created_at: '2026-05-19T12:18:00',
    team: deterministicTeam(246) },
  { id: 245, area_code: 'GUANDU',  npc: '小茂', npc_id: 'xiao-mao', status: 'pending',
    speed: 'S+', drug: '极王果', weather: '沙暴', ding: true, lock: false, chu: true,
    submitter: '198.51.100.42', submitter_short: '198.51.x.42',
    note: '同一玩家变体,沙暴天气', created_at: '2026-05-19T11:54:00',
    team: deterministicTeam(248) },
  { id: 244, area_code: 'FENGYUAN', npc: '大吾', npc_id: 'da-wu',   status: 'pending',
    speed: 'S', drug: '哑铃果', weather: '晴天', ding: false, lock: false, chu: false,
    submitter: '192.0.2.7', submitter_short: '192.0.x.7',
    note: '', created_at: '2026-05-19T10:30:00',
    team: deterministicTeam(244) },
  { id: 243, area_code: 'SHENAO',  npc: '竹兰', npc_id: 'zhu-lan',  status: 'approved',
    speed: 'S+', drug: '极王果', weather: '晴天', ding: true, lock: true, chu: false,
    submitter: '198.51.100.99', submitter_short: '198.51.x.99',
    note: '竹兰传统冠军队', created_at: '2026-05-19T09:12:00',
    team: deterministicTeam(243) },
  { id: 242, area_code: 'GUANDU',  npc: '小智', npc_id: 'xiao-zhi', status: 'rejected',
    speed: 'S', drug: '极王果', weather: '晴天', ding: false, lock: false, chu: false,
    submitter: '203.0.113.55', submitter_short: '203.0.x.55',
    note: '玩家备注: 不知道对不对', created_at: '2026-05-19T08:00:00',
    reject_reason: '阵容明显复制于现有数据,无新增价值',
    team: deterministicTeam(242) },
  { id: 241, area_code: 'CHENGDU', npc: '小遥', npc_id: 'xiao-yao', status: 'merged',
    speed: 'S+', drug: '极王果', weather: '雨天', ding: true, lock: false, chu: false,
    submitter: '203.0.113.18', submitter_short: '203.0.x.18',
    note: '', created_at: '2026-05-18T22:15:00',
    team: deterministicTeam(241) },
];

// "Current" data (simple_match.json) — used in compare view
const CURRENT_TEAMS = {
  'GUANDU::小茂': [
    { idx: '第1套', speed:'S', drug:'哑铃果', weather:'晴天', ding:false, lock:false, chu:false,
      team: deterministicTeam(100), note: '小茂初见标配' },
    { idx: '第2套', speed:'S', drug:'哑铃果', weather:'晴天', ding:false, lock:false, chu:false,
      team: deterministicTeam(101), note: '小茂二轮' },
  ],
  'CHENGDU::阿渡': [
    { idx: '第1套', speed:'S+', drug:'极王果', weather:'雨天', ding:true, lock:false, chu:false,
      team: deterministicTeam(102), note: '阿渡常规' },
  ],
};

// Staging changes (data editor)
const STAGING = [
  { id: 's1', kind: 'edit', area: '关都', npc: '小茂', target: '第2套', summary: '替换 P3: 可达鸭 → 钢铁人', actor: 'admin', at: '14:02' },
  { id: 's2', kind: 'add',  area: '丰缘', npc: '小光', target: '第3套(新增)', summary: '新增阵容,合并自 #244', actor: 'admin', at: '13:48' },
  { id: 's3', kind: 'delete', area: '关都', npc: '小霞', target: '第4套', summary: '删除阵容(数据过时)', actor: 'admin', at: '11:22' },
  { id: 's4', kind: 'edit', area: '神奥', npc: '竹兰', target: '第1套', summary: '修改 weather: 晴天 → 雨天', actor: 'admin', at: '10:09' },
  { id: 's5', kind: 'add',  area: '城都', npc: '阿渡', target: '第2套(新增)', summary: '新增阵容,合并自 #241', actor: 'admin', at: '昨日 22:31' },
];

// Audit log entries
const AUDIT = [
  { id: 'a1', at: '14:32:11', actor: 'admin', action: 'submission.approve', target: '#241', desc: '通过提交 #241 → 合并到 城都/阿渡' },
  { id: 'a2', at: '14:28:03', actor: 'admin', action: 'submission.reject',  target: '#242', desc: '驳回提交 #242,原因: 阵容明显复制' },
  { id: 'a3', at: '14:02:55', actor: 'admin', action: 'data.edit',          target: '关都/小茂/第2套', desc: '修改阵容: P3 可达鸭 → 钢铁人' },
  { id: 'a4', at: '13:48:21', actor: 'admin', action: 'data.add',           target: '丰缘/小光/第3套', desc: '新增阵容(staging)' },
  { id: 'a5', at: '13:22:09', actor: 'admin', action: 'pokedex.upload',     target: '#149 快龙', desc: '替换精灵图(版本 2)' },
  { id: 'a6', at: '12:55:40', actor: 'system', action: 'scrape.success',    target: 'cron-daily-12:00', desc: '抓取完成: 新增 3 条,修改 1 条,耗时 138s' },
  { id: 'a7', at: '11:22:15', actor: 'admin', action: 'data.delete',        target: '关都/小霞/第4套', desc: '删除阵容(staging)' },
  { id: 'a8', at: '10:09:33', actor: 'admin', action: 'data.edit',          target: '神奥/竹兰/第1套', desc: '修改 weather: 晴天 → 雨天' },
  { id: 'a9', at: '09:14:02', actor: 'admin', action: 'wiki.publish',       target: '#wiki-37', desc: '发布攻略: 双打速度计算公式' },
  { id: 'a10',at: '08:30:00', actor: 'system', action: 'deploy.success',    target: 'commit a1b2c3d', desc: '部署成功: manifest v126 已上线' },
];

// Wiki articles
const WIKI = [
  { id: 'w1', title: '关都·小茂常见队伍配置详解',     author: '管理员', updated: '2026-05-19 14:01', status: 'published', tags: ['攻略','关都'] },
  { id: 'w2', title: '双打速度计算公式 (含天气加成)', author: '管理员', updated: '2026-05-19 09:14', status: 'published', tags: ['机制'] },
  { id: 'w3', title: '草稿: 神兽配招参考(超梦篇)',    author: '管理员', updated: '2026-05-18 21:00', status: 'draft',     tags: ['草稿','配招'] },
  { id: 'w4', title: '外链: pokeking.icu 旧站存档',  author: '管理员', updated: '2026-05-15 16:20', status: 'outlink',   tags: ['存档'] },
  { id: 'w5', title: '版本更新日志 v126',             author: '系统',   updated: '2026-05-19 08:30', status: 'published', tags: ['更新'] },
];

// Pokedex: 230 sprite slots
const POKEDEX = Array.from({ length: 230 }, (_, i) => {
  const id = i + 1;
  // ~8% missing
  const missing = (id * 37) % 100 < 8;
  const recent = (id * 17) % 100 < 6;
  return {
    id, name: POKEMON[id % POKEMON.length].name + (id > POKEMON.length ? `·${id}` : ''),
    color: POKEMON[id % POKEMON.length].color,
    types: POKEMON[id % POKEMON.length].types,
    size_kb: 32 + ((id * 31) % 40),
    missing, recent,
  };
});

// Feedback
const FEEDBACK = [
  { id: 'f1', kind: 'data-fix', title: '小茂第2套阵容里讲究头巾应为讲究眼镜', status: 'new', at: '12 分钟前' },
  { id: 'f2', kind: 'bug',      title: 'App 在 iOS 17.4 启动后白屏',          status: 'reviewing', at: '1 小时前' },
  { id: 'f3', kind: 'feature',  title: '希望能筛选只看双打阵容',               status: 'new', at: '3 小时前' },
];

// Activity / Timeline (Dashboard)
const ACTIVITY = AUDIT.slice(0, 8);

// Mock admin users (for user management)
const ADMIN_USERS = [
  { id: 'u1', email: 'admin@pokeking.icu',    name: '主管理员', role: 'super-admin', status: 'active', last_login: '2 分钟前',  ip: '198.51.100.42', created: '2025-01-12', is_self: true,
    actions: { last7d: { approve: 18, reject: 5, edit: 34, publish: 6 } } },
  { id: 'u2', email: 'editor@pokeking.icu',   name: '内容编辑', role: 'editor',      status: 'active', last_login: '3 小时前', ip: '203.0.113.7',   created: '2025-03-04', is_self: false,
    actions: { last7d: { approve: 7,  reject: 2, edit: 19, publish: 0 } } },
  { id: 'u3', email: 'reviewer@pokeking.icu', name: '审核员',   role: 'reviewer',    status: 'active', last_login: '昨日',     ip: '203.0.113.18',  created: '2025-04-22', is_self: false,
    actions: { last7d: { approve: 22, reject: 12, edit: 0,  publish: 0 } } },
  { id: 'u4', email: 'aki@pokeking.icu',      name: '阿琦',     role: 'reviewer',    status: 'invited', last_login: '—',        ip: '—',             created: '2 天前',     is_self: false,
    actions: null },
  { id: 'u5', email: 'former@pokeking.icu',   name: '前编辑',   role: 'editor',      status: 'revoked', last_login: '14 天前',  ip: '—',             created: '2024-10-01', is_self: false,
    actions: { last7d: { approve: 0, reject: 0, edit: 0, publish: 0 } } },
];

window.MOCK = {
  TYPE_COLORS, AREAS, NPCS_GUANDU, POKEMON,
  SUBMISSIONS, CURRENT_TEAMS, STAGING, AUDIT, WIKI, POKEDEX, FEEDBACK, ACTIVITY,
  ADMIN_USERS,
  deterministicTeam, rndPick,
};

// Bootstrap: 加载真实静态 JSON 替换 MOCK 项（API 可用时）
window.bootstrapData = async function () {
  try {
    const [areas, lineups, docs] = await Promise.all([
      window.API.areas(),
      window.API.lineups(),
      window.API.docsIndex(),
    ]);
    if (Array.isArray(areas) && areas.length) {
      const palette = { GUANDU:'#EF4444', CHENGDU:'#10B981', FENGYUAN:'#3B82F6', SHENAO:'#A855F7', HEZHONG:'#F59E0B', OTHER:'#6366F1' };
      window.MOCK.AREAS = areas.map((a) => ({
        code: a.code, name: a.name, color: palette[a.code] || '#6366F1',
        count: (lineups && lineups[a.code]?.reduce((n, g) => n + g.lineupList.length, 0)) || 0,
      }));
    }
    if (lineups && Object.keys(lineups).length) {
      window.MOCK.LINEUPS_BY_AREA = lineups;
    }
    if (Array.isArray(docs) && docs.length) {
      window.MOCK.WIKI = docs.slice(0, 200).map((d) => ({
        id: d.id, title: d.title, author: d.author || '未署名',
        updated: d.createAt || '',
        status: d.outLink ? 'outlink' : 'published', tags: [],
      }));
    }
  } catch (e) { /* demo mode */ }
};

// Submissions: API row → UI shape
window.normalizeSubmission = function (row) {
  let payload = {};
  try { payload = typeof row.payload === 'string' ? JSON.parse(row.payload) : (row.payload || {}); } catch {}
  const team = (payload.playerList || []).slice(0, 6).map((p) => {
    const types = [p.firstAttribute, p.secondAttribute].filter(Boolean);
    return {
      name: p.name,
      color: window.MOCK.POKEMON.find((x) => x.name === p.name)?.color || '#999',
      types,
    };
  });
  const ip = row.submitter_id || '';
  const parts = ip.split('.');
  return {
    id: row.id, area_code: row.area_code, npc: row.npc_name, npc_id: '',
    status: row.status,
    speed: payload.speed || '', drug: payload.drug || '', weather: payload.weather || '',
    ding: !!payload.ding, lock: !!payload.lock, chu: !!payload.chu,
    submitter: ip,
    submitter_short: parts.length === 4 ? `${parts[0]}.${parts[1]}.x.${parts[3]}` : ip,
    note: row.submitter_note || payload.note || '',
    created_at: row.created_at ? new Date(row.created_at).toISOString() : new Date().toISOString(),
    reject_reason: row.reject_reason,
    team, _raw: payload,
  };
};
