/* global React */
// App shell: Sidebar + Topbar + Command Palette + Notification drawer.

const NAV = [
  { id: 'dashboard',   label: '仪表盘',     icon: 'home',     badge: null },
  { id: 'submissions', label: '审核台',     icon: 'inbox',    badge: 4 },
  { id: 'data',        label: '数据编辑',   icon: 'database', badge: { kind: 'subtle', text: '5' } },
  { id: 'wiki',        label: '攻略',       icon: 'bookOpen', badge: null },
  { id: 'scrape',      label: '抓取',       icon: 'refresh',  badge: null },
  { id: 'pokedex',     label: '图鉴',       icon: 'grid',     badge: { kind: 'subtle', text: '12' } },
  { id: 'feedback',    label: '反馈',       icon: 'message',  badge: 2 },
  { id: 'status',      label: '系统状态',   icon: 'activity', badge: null },
  { id: 'audit',       label: '操作日志',   icon: 'list',     badge: null },
  { id: 'settings',    label: '设置',       icon: 'settings', badge: null },
];

function Sidebar({ route, onNavigate, role, onForbidden }) {
  const renderGroup = (items) => items.map((n) => {
    const allowed = window.can(role, n.id, 'r');
    return (
      <NavItem key={n.id} item={n} active={route === n.id}
               locked={!allowed}
               onClick={() => allowed ? onNavigate(n.id) : onForbidden?.(n)}/>
    );
  });
  return (
    <aside className="sidebar">
      <div className="sidebar-section" style={{ paddingTop: 0 }}>工作区</div>
      {renderGroup(NAV.slice(0, 1))}

      <div className="sidebar-section">日常</div>
      {renderGroup(NAV.slice(1, 5))}

      <div className="sidebar-section">资源</div>
      {renderGroup(NAV.slice(5, 7))}

      <div className="sidebar-section">系统</div>
      {renderGroup(NAV.slice(7))}

      <div style={{ flex: 1 }}/>
      <div style={{
        margin: 'var(--s-3)', padding: 'var(--s-3)',
        background: 'var(--surface-2)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-md)',
        fontSize: 12, color: 'var(--text-2)'
      }}>
        <div className="hstack" style={{ marginBottom: 4 }}>
          <span className="status-dot ok"/>
          <span style={{ fontWeight: 500, color: 'var(--text)' }}>manifest v126</span>
        </div>
        <div style={{ color: 'var(--text-3)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>
          a1b2c3d · 2 小时前
        </div>
      </div>
    </aside>
  );
}

function NavItem({ item, active, onClick, locked }) {
  const Icon = window.I[item.icon];
  return (
    <div className={`nav-item ${active ? 'active' : ''} ${locked ? 'locked' : ''}`} onClick={onClick}
         title={locked ? '权限不足' : ''}
         style={locked ? { opacity: .42, cursor: 'not-allowed' } : {}}>
      <span className="icon">{Icon && <Icon size={18}/>}</span>
      <span className="label">{item.label}</span>
      {locked ? (
        <window.I.shield size={13} style={{ marginLeft: 'auto', opacity: .7 }}/>
      ) : (
        item.badge != null && (typeof item.badge === 'number'
          ? <span className="badge">{item.badge}</span>
          : <span className={`badge ${item.badge.kind || ''}`}>{item.badge.text}</span>)
      )}
    </div>
  );
}

// ─── Topbar ─────────────────────────────────────────────────────
function Topbar({ onOpenCmdK, onLogout, user }) {
  const role = user?.role || 'super-admin';
  const r = window.ROLES[role] || window.ROLES['super-admin'];
  const initial = (user?.name || 'A').slice(0, 1);
  return (
    <div className="topbar">
      <div className="brand">
        <window.Logo size={28}/>
        <div className="brand-text">
          <span className="name">PokeKING</span>
          <span className="role">Admin Console</span>
        </div>
      </div>

      <div className="global-search" onClick={onOpenCmdK} role="button" tabIndex={0}>
        <window.I.search size={15}/>
        <span>搜索阵容、攻略、精灵、NPC…</span>
        <span className="kbd"><window.KBD>⌘</window.KBD><window.KBD>K</window.KBD></span>
      </div>

      <div className="top-right">
        <button className="icon-btn" title="通知">
          <window.I.bell size={18}/>
          <span className="dot"/>
        </button>
        <button className="icon-btn" title="帮助 / 快捷键 (?)" >
          <window.I.info size={18}/>
        </button>
        <div className="hstack" style={{
          gap: 8, padding: '4px 6px 4px 4px',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-pill)',
          background: 'var(--surface)',
          cursor: 'pointer',
        }} onClick={onLogout} title="点击注销">
          <span className="avatar" style={{
            width: 26, height: 26, fontSize: 11,
            background: `linear-gradient(135deg, ${r.color}, ${r.color}99)`,
          }}>{initial}</span>
          <div style={{ display:'flex', flexDirection:'column', lineHeight: 1.1, paddingRight: 4 }}>
            <span style={{ fontSize: 12, fontWeight: 500 }}>{user?.name || '管理员'}</span>
            <span style={{ fontSize: 10, color: r.color, marginTop: 2, fontWeight: 500 }}>{r.label}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Command Palette ───────────────────────────────────────────
function CommandPalette({ open, onClose, onNavigate, onAction, role = 'super-admin' }) {
  const [q, setQ] = React.useState('');
  const [idx, setIdx] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setQ(''); setIdx(0);
      setTimeout(() => inputRef.current?.focus(), 30);
    }
  }, [open]);

  const commands = React.useMemo(() => {
    const navCmds = NAV.filter((n) => window.can(role, n.id, 'r')).map((n) => ({
      group: '导航', label: `跳到 ${n.label}`, icon: n.icon,
      meta: 'Go', run: () => onNavigate(n.id),
    }));
    const actionCmds = [
      window.can(role, 'scrape', 'w') && { group: '操作', label: '立即触发抓取',    icon: 'refresh',  meta: 'Action', run: () => onAction('scrape') },
      window.can(role, 'wiki', 'w')   && { group: '操作', label: '新建攻略',        icon: 'plus',     meta: 'Action', run: () => onAction('newWiki') },
      window.can(role, 'data', 'w')   && { group: '操作', label: '发布全部 staging', icon: 'upload',   meta: 'Action', run: () => onAction('publish') },
      window.can(role, 'data', 'r')   && { group: '操作', label: '打开 staging 抽屉', icon: 'layers',   meta: 'Action', run: () => onAction('staging') },
    ].filter(Boolean);
    const submitCmds = window.MOCK.SUBMISSIONS.slice(0, 4).map((s) => ({
      group: '提交', label: `#${s.id} · ${s.area_code} · ${s.npc}`,
      icon: 'inbox', meta: s.status, run: () => onAction('openSub', s.id),
    }));
    const wikiCmds = window.MOCK.WIKI.slice(0, 3).map((w) => ({
      group: '攻略', label: w.title, icon: 'bookOpen', meta: w.status, run: () => onAction('openWiki', w.id),
    }));
    const settingsCmds = [
      { group: '主题', label: '切换 浅色 / 深色 / 自动', icon: 'settings', meta: 'Theme', run: () => onAction('cycleTheme') },
    ];
    return [...navCmds, ...actionCmds, ...submitCmds, ...wikiCmds, ...settingsCmds];
  }, [onNavigate, onAction]);

  const filtered = React.useMemo(() => {
    if (!q.trim()) return commands;
    const lq = q.toLowerCase();
    return commands.filter((c) => c.label.toLowerCase().includes(lq) || c.group.toLowerCase().includes(lq));
  }, [q, commands]);

  React.useEffect(() => { setIdx(0); }, [q]);

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setIdx((i) => Math.min(filtered.length - 1, i + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setIdx((i) => Math.max(0, i - 1)); }
    else if (e.key === 'Enter') {
      e.preventDefault();
      const item = filtered[idx];
      if (item) { item.run(); onClose(); }
    } else if (e.key === 'Escape') { onClose(); }
  };

  if (!open) return null;

  const groups = {};
  filtered.forEach((c, i) => {
    if (!groups[c.group]) groups[c.group] = [];
    groups[c.group].push({ ...c, i });
  });

  return (
    <div className="cmdk-backdrop" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()} onKeyDown={onKey}>
        <input ref={inputRef} className="cmdk-input"
               placeholder="输入命令、页面或搜索关键词…"
               value={q} onChange={(e) => setQ(e.target.value)}/>
        <div className="cmdk-list">
          {filtered.length === 0 && (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 13 }}>
              未找到匹配项
            </div>
          )}
          {Object.entries(groups).map(([group, items]) => (
            <div key={group}>
              <div className="cmdk-group">{group}</div>
              {items.map((c) => {
                const Icon = window.I[c.icon];
                return (
                  <div key={c.i} className={`cmdk-item ${c.i === idx ? 'active' : ''}`}
                       onMouseEnter={() => setIdx(c.i)}
                       onClick={() => { c.run(); onClose(); }}>
                    <span className="icon">{Icon && <Icon size={16}/>}</span>
                    <span>{c.label}</span>
                    <span className="meta">{c.meta}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
        <div className="cmdk-foot">
          <span><window.KBD>↑↓</window.KBD> 选择</span>
          <span><window.KBD>↵</window.KBD> 执行</span>
          <span><window.KBD>Esc</window.KBD> 关闭</span>
          <span style={{ marginLeft: 'auto' }}>{filtered.length} 个匹配</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { NAV, Sidebar, Topbar, CommandPalette });
