// Shell: sidebar + topbar
const { useState, useEffect, useMemo, useRef } = React;

// -------------------- Brand Logo --------------------
const BKSLogo = ({ size = 22 }) => (
  <div className="brand-mark" style={{ width: size, height: size, fontSize: size * 0.5 }}>
    BK
  </div>
);

// -------------------- Sidebar --------------------
// Collapsible app sidebar — full (232px) ↔ icon rail (56px), persistent via tweak.
// Nav items show only their icon + tooltip when collapsed. Project list shows
// the project's color swatch in icon-rail mode (no per-node submenu).

const NavItem = ({ icon, label, active, badge, onClick, dot, swatch, collapsed, kbd }) => {
  const ref = React.useRef(null);
  const tipRef = React.useRef(null);
  const onEnter = () => {
    if (!collapsed || !ref.current || !tipRef.current) return;
    const r = ref.current.getBoundingClientRect();
    tipRef.current.style.left = (r.right + 8) + 'px';
    tipRef.current.style.top = (r.top + r.height / 2) + 'px';
  };
  return (
    <button
      type="button"
      ref={ref}
      onMouseEnter={onEnter}
      onFocus={onEnter}
      className={`nav-item ${active ? 'active' : ''} ${collapsed ? 'is-collapsed' : ''}`}
      onClick={onClick}
      title={collapsed ? label : undefined}
      aria-label={label}
    >
      <span className="nav-item-icon">
        {icon && <Icon name={icon} size={15} className="nav-icon" />}
        {swatch && <span className="nav-swatch" style={{ background: swatch }} />}
      </span>
      <span className="nav-item-label">{label}</span>
      {badge != null && <span className="nav-badge">{badge}</span>}
      {kbd && !collapsed && <kbd className="nav-kbd">{kbd}</kbd>}
      {dot && <span className="engine-indicator" style={{ color: dot }} />}
      {collapsed && <span ref={tipRef} className="nav-tooltip">{label}</span>}
    </button>
  );
};

const Sidebar = ({ page, setPage, lang, collapsed, onToggle, theme, setTheme, setLang, onSearch }) => {
  const t = I18N[lang];
  return (
    <aside className={`sidebar ${collapsed ? 'collapsed' : ''}`} aria-label="Primary">
      <div className="sidebar-head">
        <div className="brand">
          <BKSLogo />
          <span className="brand-text">BKS</span>
          <span className="brand-mono brand-text">v0.6</span>
        </div>
        <button
          type="button"
          className="sidebar-toggle"
          onClick={onToggle}
          title={collapsed ? 'Expand sidebar (⌘B)' : 'Collapse sidebar (⌘B)'}
          aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        >
          <Icon name={collapsed ? 'panelLeftOpen' : 'panelLeftClose'} size={15} />
        </button>
      </div>
      <nav className="nav">
        <NavItem collapsed={collapsed} icon="dashboard" label={t.dashboard} active={page==='dashboard'} onClick={() => setPage('dashboard')} />
        <NavItem collapsed={collapsed} icon="inbox"     label={t.inbox}     badge="8" onClick={() => setPage('inbox')} active={page==='inbox'} />
        <NavItem collapsed={collapsed} icon="file"      label={t.notes}     onClick={() => setPage('notes')} active={page==='notes'} />
        <NavItem collapsed={collapsed} icon="search"    label={t.search || 'Search'} onClick={onSearch} kbd="⌘K" />

        <div className="nav-section">
          <div className="nav-label"><span>{t.workspace}</span></div>
          <NavItem collapsed={collapsed} icon="project" label={t.projects} active={page==='projects'} onClick={() => setPage('projects')} />
          <NavItem collapsed={collapsed} icon="bot"     label={t.agents || 'Agents'} active={page==='operators'} onClick={() => setPage('operators')} />
          <NavItem collapsed={collapsed} icon="skills"  label={t.skills}   active={page==='skills'} onClick={() => setPage('skills')} badge="23" />
          <NavItem collapsed={collapsed} icon="engine"  label={t.nodes} active={page==='nodes'} onClick={() => setPage('nodes')} />
        </div>

      </nav>

      <div className="sidebar-foot">
        <UserCardMenu collapsed={collapsed} setPage={setPage} theme={theme} setTheme={setTheme} lang={lang} setLang={setLang} onSearch={onSearch} />
      </div>
    </aside>
  );
};

// -------------------- User card with popover menu --------------------
const UserCardMenu = ({ collapsed, setPage, theme, setTheme, lang, setLang, onSearch }) => {
  const [open, setOpen] = useState(false);
  const cardRef = useRef(null);
  const popRef = useRef(null);

  const positionPop = () => {
    if (!cardRef.current || !popRef.current) return;
    const r = cardRef.current.getBoundingClientRect();
    const pop = popRef.current;
    // Place above the card, aligned to its left edge.
    pop.style.left = r.left + 'px';
    pop.style.bottom = (window.innerHeight - r.top + 8) + 'px';
    pop.style.top = 'auto';
    pop.style.minWidth = collapsed ? '220px' : (r.width + 'px');
  };

  useEffect(() => {
    if (!open) return;
    positionPop();
    const onDoc = (e) => {
      if (popRef.current?.contains(e.target) || cardRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    window.addEventListener('resize', positionPop);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
      window.removeEventListener('resize', positionPop);
    };
  }, [open]);

  const go = (page) => { setOpen(false); setPage(page); };

  return (
    <>
      <button
        type="button"
        ref={cardRef}
        className={`user-card ${open ? 'is-open' : ''}`}
        onClick={() => setOpen(o => !o)}
        title={collapsed ? 'Xie Ming · Platform · Owner' : undefined}
        onMouseEnter={(e) => {
          if (!collapsed) return;
          const tip = e.currentTarget.querySelector('.nav-tooltip');
          if (!tip) return;
          const r = e.currentTarget.getBoundingClientRect();
          tip.style.left = (r.right + 8) + 'px';
          tip.style.top = (r.top + r.height / 2) + 'px';
        }}
      >
        <div className="user-avatar">XM</div>
        <div className="user-info">
          <div className="user-name">Xie Ming</div>
          <div className="user-role">Platform · Owner</div>
        </div>
        <Icon name={open ? 'chevDown' : 'dots'} size={14} className="dim user-settings" />
        {collapsed && <span className="nav-tooltip">Xie Ming · Settings</span>}
      </button>

      {open && (
        <div ref={popRef} className="user-popover" role="menu">
          <div className="user-popover-head">
            <div className="admin-avatar" style={{background: 'linear-gradient(135deg, #FF9A56, #D97757)'}}>XM</div>
            <div style={{minWidth: 0}}>
              <div className="user-popover-name">Xie Ming</div>
              <div className="user-popover-handle">@xieming · acme</div>
            </div>
          </div>
          <button className="user-popover-item" onClick={() => go('me')}>
            <Icon name="person" size={13} /> Profile
            <span className="pop-shortcut">⌘P</span>
          </button>
          <button className="user-popover-item" onClick={() => go('admin')}>
            <Icon name="settings" size={13} /> Settings
            <span className="pop-shortcut">⌘,</span>
          </button>
          <button className="user-popover-item" onClick={() => go('admin')}>
            <Icon name="users" size={13} /> Invite teammates
          </button>
          <div className="user-popover-sep" />
          <button className="user-popover-item" onClick={() => setTheme(theme==='light'?'dark':'light')}>
            <Icon name={theme==='light' ? 'moon' : 'sun'} size={13} /> {theme==='light' ? 'Dark mode' : 'Light mode'}
          </button>
          <button className="user-popover-item" onClick={() => setLang(lang==='en'?'zh':'en')}>
            <Icon name="globe" size={13} /> Language
            <span className="pop-shortcut">{lang==='en' ? 'EN' : '中'}</span>
          </button>
          <div className="user-popover-sep" />
          <button className="user-popover-item">
            <Icon name="alert" size={13} /> Help & shortcuts
            <span className="pop-shortcut">?</span>
          </button>
          <button className="user-popover-item danger">
            <Icon name="external" size={13} /> Sign out
          </button>
        </div>
      )}
    </>
  );
};

// -------------------- Topbar --------------------
const DETAIL_PARENTS = {
  'node-detail':    { page: 'nodes',    label: (lang) => I18N[lang].nodes },
  'issue-detail':   { page: 'project-detail', label: (lang, ctx) => ctx?.projName || I18N[lang].projects },
};

const Topbar = ({ crumbs, page, setPage, lang, onNewIssue, onMenu }) => {
  const parent = DETAIL_PARENTS[page];
  // For issue-detail, derive the parent project from the current issue
  let parentCtx = null;
  if (page === 'issue-detail') {
    const issId = window.__currentIssue;
    const iss = (typeof ISSUES !== 'undefined') ? ISSUES.find(i => i.id === issId) : null;
    const proj = iss && (typeof PROJECTS !== 'undefined') ? PROJECTS.find(p => p.id === iss.proj) : null;
    if (proj) {
      parentCtx = { projName: proj.name, projId: proj.id };
    }
  }
  return (
  <div className={`topbar ${parent ? 'is-detail' : ''}`}>
    <button className="topbar-menu" onClick={onMenu} aria-label="Menu"><Icon name="menu" size={18} /></button>
    <div className="topbar-brand-mobile"><BKSLogo /><span style={{fontSize:13,fontWeight:600,letterSpacing:'0.02em'}}>BKS</span></div>
    <div className="topbar-crumbs">
      {parent ? (
        <button type="button" className="crumb-back" onClick={() => {
          if (page === 'issue-detail' && parentCtx) {
            window.__currentProj = parentCtx.projId;
          }
          setPage(parent.page);
        }}>
          <Icon name="chevLeft" size={14} />
          <span>{parent.label(lang, parentCtx)}</span>
        </button>
      ) : (
        crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon name="chevRight" size={13} className="crumb-sep" />}
            <span className={i === crumbs.length - 1 ? 'crumb-active' : ''}>{c}</span>
          </React.Fragment>
        ))
      )}
    </div>
    <div className="topbar-actions">
      <button className="ibtn topbar-search-mobile" onClick={onMenu} aria-label="Search"><Icon name="search" size={16} /></button>
    </div>
  </div>
  );
};

// -------------------- i18n --------------------
const I18N = {
  en: {
    dashboard: 'Dashboard', inbox: 'Inbox', notes: 'Notes', search: 'Search', issues: 'Issues', kanban: 'Board', activity: 'Activity',
    workspace: 'Workspace', projects: 'Projects', teams: 'Teams', skills: 'Skills', agents: 'Agents', workflows: 'Agents', operators: 'Agents',
    engines: 'Engines', allEngines: 'All engines', nodes: 'Nodes', allNodes: 'All nodes',
    today: 'Today', week: 'This week',
    goodMorning: 'Good afternoon, Xie Ming',
    overview: 'Your platform, right now',
    openIssues: 'Open issues', activeAgents: 'Active agents', runsToday: 'Runs today', avgCycle: 'Avg cycle',
    liveWork: 'Live work', recentActivity: 'Recent activity', engineLoad: 'Engine load · last 24h',
    allProjects: 'All projects', topSkills: 'Top skills',
  },
  zh: {
    dashboard: '工作台', inbox: '收件箱', notes: '笔记', search: '搜索', issues: '工单', kanban: '看板', activity: '动态',
    workspace: '空间', projects: '项目', teams: '团队', skills: '技能', agents: '智能体', workflows: '智能体', operators: '智能体',
    engines: '引擎', allEngines: '全部引擎', nodes: '节点', allNodes: '全部节点',
    today: '今日', week: '本周',
    goodMorning: '下午好，谢明',
    overview: '你的平台，此刻状态',
    openIssues: '未完成工单', activeAgents: '活跃 Agent', runsToday: '今日运行', avgCycle: '平均周期',
    liveWork: '实时工作', recentActivity: '最近动态', engineLoad: '引擎负载 · 24 小时',
    allProjects: '全部项目', topSkills: '热门技能',
  },
};

// -------------------- MobileTabBar (≤900px) --------------------
const MobileTabBar = ({ page, setPage, unread = 0 }) => {
  // Map any sub-page to its tab category
  const tabFor = (p) => {
    if (p === 'inbox') return 'inbox';
    if (p === 'dashboard' || p === 'activity') return 'activity';
    if (p === 'project-detail') return null;
    if (['projects','issues','issue-detail','kanban'].includes(p)) return 'projects';
    if (['teams','operators','skills','nodes','node-detail','engines'].includes(p)) return 'browse';
    return 'me';
  };
  const cur = tabFor(page);
  const tabs = [
    { id: 'activity', icon: 'dashboard', label: 'Home',     target: 'dashboard' },
    { id: 'inbox',    icon: 'inbox',     label: 'Inbox',    target: 'inbox', badge: unread },
    { id: 'projects', icon: 'project',   label: 'Projects', target: 'projects' },
    { id: 'browse',   icon: 'layers',    label: 'Browse',   target: 'nodes' },
    { id: 'me',       icon: 'team',      label: 'Me',       target: 'me' },
  ];
  return (
    <nav className="mtab-bar" aria-label="Primary">
      {tabs.map(t => {
        const active = cur === t.id;
        return (
          <button key={t.id} className={`mtab ${active ? 'on' : ''}`} onClick={() => setPage(t.target)}>
            <span className="mtab-icon-wrap">
              <Icon name={t.icon} size={20} />
              {t.badge ? <span className="mtab-badge">{t.badge > 9 ? '9+' : t.badge}</span> : null}
            </span>
            <span className="mtab-label">{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
};

Object.assign(window, { Sidebar, Topbar, BKSLogo, I18N, NavItem, MobileTabBar });

// -------------------- New Issue Modal --------------------
const PRIORITIES = [
  { id: 'none',   label: 'No priority', dot: '#9CA3AF' },
  { id: 'urgent', label: 'Urgent',      dot: '#E11D48' },
  { id: 'high',   label: 'High',        dot: '#F59E0B' },
  { id: 'med',    label: 'Medium',      dot: '#3D63FF' },
  { id: 'low',    label: 'Low',         dot: '#10B981' },
];

// Linear-style priority icon: dashed circle for none, staircase bars otherwise
const PrioIcon = ({ id, size = 14 }) => {
  if (id === 'none') {
    return (
      <svg width={size} height={size} viewBox="0 0 14 14" aria-hidden="true" style={{display:'block'}}>
        <circle cx="7" cy="7" r="5.5" fill="none" stroke="currentColor" strokeWidth="1.3" strokeDasharray="1.4 1.6" opacity="0.7" />
      </svg>
    );
  }
  if (id === 'urgent') {
    const c = '#E11D48';
    return (
      <svg width={size} height={size} viewBox="0 0 14 14" aria-hidden="true" style={{display:'block'}}>
        <rect x="1.5" y="1.5" width="11" height="11" rx="2.2" fill={c} />
        <rect x="6.2" y="3.3" width="1.6" height="5" fill="#fff" />
        <rect x="6.2" y="9" width="1.6" height="1.6" fill="#fff" />
      </svg>
    );
  }
  // high / med / low — 3 bars with progressive fills
  const p = PRIORITIES.find(x => x.id === id);
  const c = p?.dot || '#9CA3AF';
  const filled = id === 'high' ? 3 : id === 'med' ? 2 : 1;
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" aria-hidden="true" style={{display:'block'}}>
      {[0,1,2].map(i => (
        <rect key={i} x={2 + i*3.4} y={10 - i*2.8} width="2.2" height={3 + i*2.8} rx="0.6"
          fill={i < filled ? c : 'transparent'}
          stroke={i < filled ? 'none' : 'currentColor'} strokeWidth="1"
          opacity={i < filled ? 1 : 0.5}
        />
      ))}
    </svg>
  );
};

const Popover = ({ anchor, onClose, children }) => {
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target) && !anchor?.contains(e.target)) onClose(); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [anchor]);
  const r = anchor?.getBoundingClientRect();
  if (!r) return null;
  return (
    <div ref={ref} className="mini-pop" style={{ left: r.left, top: r.bottom + 4 }}>
      {children}
    </div>
  );
};

const NewIssueModal = ({ open, onClose, onCreate }) => {
  const [step, setStep] = useState(1);
  const [title, setTitle] = useState('');
  const [desc, setDesc] = useState('');
  const [projId, setProjId] = useState('');
  const [priorityId, setPriorityId] = useState('none');
  const [capId, setCapId] = useState(null); // null = no prompt injection
  const [assigneeId, setAssigneeId] = useState('@xieming'); // default: current user
  const [pop, setPop] = useState(null); // 'proj' | 'prio' | 'assn'
  const [promptText, setPromptText] = useState('');
  const [promptEdited, setPromptEdited] = useState(false);
  const anchors = useRef({});

  const HUMANS = (typeof AGENTS_BY_ENGINE !== 'undefined' && AGENTS_BY_ENGINE.human) || (window.AGENTS_BY_ENGINE?.human) || [];
  const me = HUMANS.find(h => h.handle === '@xieming') || HUMANS[0];
  const assignee = HUMANS.find(h => h.handle === assigneeId) || me;

  const proj = PROJECTS.find(p => p.id === projId);
  const node = proj ? NODES.find(n => n.id === proj.nodeId) : null;
  const cap = CAPABILITIES.find(c => c.id === capId);
  const priority = PRIORITIES.find(p => p.id === priorityId);
  const nodeEngines = new Set((node?.engines || []).map(e => e.id));

  // Resolved agent: capability × node
  const resolvedAgent = useMemo(() => {
    if (!cap || cap.id === 'manual') return { kind: 'human', label: 'Manual · Human' };
    const eid = cap.engines.find(x => nodeEngines.has(x));
    if (!eid) return { kind: 'human', label: 'Manual · Human' };
    const meta = ENGINES.find(e => e.id === eid);
    return { kind: 'engine', id: eid, label: meta?.name || eid };
  }, [capId, projId]);

  useEffect(() => {
    if (!open) {
      setStep(1); setTitle(''); setDesc(''); setProjId(''); setPriorityId('none');
      setCapId(null); setAssigneeId('@xieming'); setPop(null); setPromptText(''); setPromptEdited(false);
    }
  }, [open]);

  // When capability changes, refresh prompt template (unless user edited it)
  useEffect(() => {
    if (!promptEdited) {
      const c = CAPABILITIES.find(x => x.id === capId);
      setPromptText(c?.prompt || '');
    }
  }, [capId]);

  if (!open) return null;

  const canCreate = title.trim().length > 2;
  const canContinue = canCreate;

  const Chip = ({ id, icon, active, children, dashed }) => (
    <button
      type="button"
      ref={(el) => { anchors.current[id] = el; }}
      className={`mini-chip ${active?'on':''} ${dashed?'dashed':''}`}
      onClick={() => setPop(pop === id ? null : id)}
    >
      {icon && <Icon name={icon} size={12} />}
      <span>{children}</span>
    </button>
  );

  const doCreate = () => {
    onCreate?.({ title, desc, projId, capId, priority: priorityId, assignee: assigneeId, prompt: promptText });
    onClose();
  };

  return (
    <div className="modal-scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal ni-simple" role="dialog" aria-modal="true">
        <div className="ni-head">
          <div className="ni-crumbs">
            <span className="mono">{proj?.slug || 'bks'}</span>
            <Icon name="chevRight" size={11} className="dim" />
            <span className="ni-crumb-active">New issue</span>
            {step === 2 && <>
              <Icon name="chevRight" size={11} className="dim" />
              <span className="ni-crumb-active">Prompt</span>
            </>}
          </div>
          <button className="ibtn" onClick={onClose} aria-label="Close"><Icon name="close" size={14} /></button>
        </div>

        {step === 1 && <>
          <div className="ni-body">
            <input
              className="ni-title"
              autoFocus
              placeholder="Issue title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && canContinue) setStep(2); }}
            />
            <textarea
              className="ni-desc"
              placeholder="Add description…"
              rows={3}
              value={desc}
              onChange={(e) => setDesc(e.target.value)}
            />
          </div>

          <div className="ni-chips">
            <Chip id="prio" icon={null} dashed={priorityId==='none'}>
              <span className="prio-wrap" style={{color: priority.dot}}><PrioIcon id={priorityId} /></span>
              {priority.label}
            </Chip>
            <Chip id="assn" icon={null}>
              <span className="assn-avatar" style={{background: assignee?.color || '#6B7280'}}>{assignee?.avatar || 'ME'}</span>
              {assignee?.handle === me?.handle ? 'Me' : assignee?.name?.split(' ')[0]}
            </Chip>
            <Chip id="proj" icon="folder" dashed={!projId}>
              {proj ? proj.name : 'No project'}
            </Chip>
            {node && capId && (
              <span className="ni-route mono">
                <Icon name="server" size={11} /> {node.id}
                <Icon name="chevRight" size={10} className="dim" />
                {resolvedAgent.label}
              </span>
            )}
          </div>

          <div className="ni-foot">
            <button className="ibtn" title="Attach"><Icon name="file" size={13} /></button>
            <div style={{display:'flex', gap:8}}>
              <button className="ibtn ghost" onClick={doCreate} disabled={!canCreate}>Create</button>
              <button className="ibtn primary" disabled={!canContinue} onClick={() => setStep(2)}>
                Continue <Icon name="chevRight" size={11} />
              </button>
            </div>
          </div>
        </>}

        {step === 2 && <>
          <div className="ni-step2">
            <div className="ni-step2-summary">
              <div className="ni-s2-title">{title || 'Untitled'}</div>
              <div className="ni-s2-meta">
                <span className="mini-chip on"><span className="prio-wrap" style={{color: priority.dot}}><PrioIcon id={priorityId} /></span>{priority.label}</span>
                <span className="mini-chip on"><span className="assn-avatar" style={{background: assignee?.color}}>{assignee?.avatar}</span>{assignee?.handle === me?.handle ? 'Me' : assignee?.name?.split(' ')[0]}</span>
                {proj && <span className="mini-chip on"><Icon name="folder" size={12} />{proj.name}</span>}
                {cap && <span className="mini-chip on"><Icon name={cap.icon} size={12} />{cap.label}</span>}
              </div>
              {capId && (
                <div className="ni-resolve">
                  <Icon name="server" size={11} />
                  <span className="mono">{node?.id || '—'}</span>
                  <Icon name="chevRight" size={10} className="dim" />
                  <span>{resolvedAgent.label}</span>
                  {resolvedAgent.kind === 'engine' && !cap?.engines.some(eid => nodeEngines.has(eid)) && (
                    <span className="ni-fallback">falls back</span>
                  )}
                </div>
              )}
            </div>

            <div className="ni-prompt-head">
              <div>
                <div className="ni-prompt-label">System prompt</div>
                <div className="ni-prompt-sub">Pick a template to load, or write your own — injected when the agent starts</div>
              </div>
              {promptEdited && (
                <button className="ibtn ghost" onClick={() => { setPromptEdited(false); const c = CAPABILITIES.find(x => x.id === capId); setPromptText(c?.prompt || ''); }}>
                  <Icon name="refresh" size={11} /> Reset
                </button>
              )}
            </div>

            <div className="ni-cap-picker">
              {CAPABILITIES.map(c => {
                const available = !projId || c.id==='manual' || c.engines.some(eid => nodeEngines.has(eid));
                return (
                  <button
                    key={c.id}
                    type="button"
                    className={`cap-pill ${capId===c.id?'active':''} ${!available?'dim':''}`}
                    onClick={() => { setCapId(c.id); setPromptEdited(false); }}
                    title={c.desc}
                  >
                    <Icon name={c.icon} size={11} />
                    <span>{c.label}</span>
                  </button>
                );
              })}
              <button
                type="button"
                className={`cap-pill ${!capId?'active':''}`}
                onClick={() => { setCapId(null); setPromptEdited(false); setPromptText(''); }}
              >
                <Icon name="person" size={11} />
                <span>None</span>
              </button>
            </div>

            <textarea
              className="ni-prompt"
              rows={10}
              placeholder={capId ? 'System prompt injected when agent starts…' : 'Pick a capability above to load a prompt template, or leave empty for no injection.'}
              value={promptText}
              onChange={(e) => { setPromptText(e.target.value); setPromptEdited(true); }}
            />
          </div>

          <div className="ni-foot">
            <button className="ibtn ghost" onClick={() => setStep(1)}>
              <Icon name="chevLeft" size={11} /> Back
            </button>
            <button className="ibtn primary" disabled={!canCreate} onClick={doCreate}>
              Create issue
            </button>
          </div>
        </>}

        {pop === 'prio' && (
          <Popover anchor={anchors.current.prio} onClose={() => setPop(null)}>
            {PRIORITIES.map(p => (
              <button key={p.id} className="mini-row" onClick={() => { setPriorityId(p.id); setPop(null); }}>
                <span className="prio-wrap" style={{color: p.dot}}><PrioIcon id={p.id} /></span>
                <span>{p.label}</span>
                {priorityId===p.id && <Icon name="check" size={12} className="mini-check" />}
              </button>
            ))}
          </Popover>
        )}
        {pop === 'assn' && (
          <Popover anchor={anchors.current.assn} onClose={() => setPop(null)}>
            {HUMANS.map(h => (
              <button key={h.handle} className="mini-row" onClick={() => { setAssigneeId(h.handle); setPop(null); }}>
                <span className="assn-avatar sm" style={{background: h.color}}>{h.avatar}</span>
                <div style={{display:'flex', flexDirection:'column', minWidth:0}}>
                  <span style={{fontSize:12.5}}>{h.name}{h.handle === me?.handle && <span className="assn-me">you</span>}</span>
                  <span className="mono" style={{fontSize:10, color:'var(--fg-4)'}}>{h.handle}</span>
                </div>
                {assigneeId === h.handle && <Icon name="check" size={12} className="mini-check" />}
              </button>
            ))}
          </Popover>
        )}
        {pop === 'proj' && (
          <Popover anchor={anchors.current.proj} onClose={() => setPop(null)}>
            <button className="mini-row" onClick={() => { setProjId(''); setPop(null); }}>
              <Icon name="folder" size={12} className="dim" />
              <span>No project</span>
              {!projId && <Icon name="check" size={12} className="mini-check" />}
            </button>
            <div className="mini-sep" />
            {PROJECTS.map(p => (
              <button key={p.id} className="mini-row" onClick={() => { setProjId(p.id); setPop(null); }}>
                <span className="proj-mini" style={{background:p.color, width:14, height:14, fontSize:8}}>{p.id.slice(0,2)}</span>
                <span>{p.name}</span>
                {projId===p.id && <Icon name="check" size={12} className="mini-check" />}
              </button>
            ))}
          </Popover>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { NewIssueModal });
