// Hermes Console — Projects view + NavRail

const { useState: usePV, useMemo: useMV } = React;

// Inline SVG icons (avoid emoji)
const Icon = {
  console: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/><path d="M7 14l3 2-3 2"/><path d="M13 18h4"/></svg>,
  projects: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/><path d="M8 5v14"/></svg>,
  library: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v14"/><path d="M4 5v15a1 1 0 0 0 1 1h15"/><path d="M8 7v10"/><path d="M12 7v10"/></svg>,
  settings: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>,
  plus: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M8 3v10M3 8h10"/></svg>,
  search: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="7" cy="7" r="4"/><path d="m13 13-3-3"/></svg>,
};

function NavRail({ view, setView }) {
  const items = [
    { id: 'console', label: 'Console', icon: Icon.console },
    { id: 'projects', label: 'Projects', icon: Icon.projects },
    { id: 'library', label: 'Skill Library', icon: Icon.library },
    { id: 'settings', label: 'Settings', icon: Icon.settings },
  ];
  return (
    <nav className="navrail">
      {items.map((item) => (
        <button
          key={item.id}
          className={`nav-btn ${view === item.id ? 'active' : ''}`}
          onClick={() => setView(item.id)}
          title={item.label}
        >
          {item.icon}
          <span className="nav-tip">{item.label}</span>
        </button>
      ))}
      <div className="navrail-spacer" />
    </nav>
  );
}

const STAGE_INDEX = { req: 0, prd: 1, proto: 2, done: 3 };

function MiniPipeline({ project }) {
  const idx = STAGE_INDEX[project.stage] ?? 0;
  const stages = ['req', 'prd', 'proto'];
  return (
    <div className="mini-pipe">
      {stages.map((s, i) => {
        let cls = '';
        if (project.status === 'done' || i < idx) cls = 'done';
        else if (i === idx) {
          if (project.status === 'running') cls = 'run';
          else if (project.status === 'failed') cls = 'fail';
          else if (project.status === 'paused') cls = '';
        }
        return (
          <React.Fragment key={s}>
            <span className={`dot ${cls}`} />
            {i < stages.length - 1 && (
              <span className={`ln ${i < idx || project.status === 'done' ? 'done' : ''}`} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function StatusPill({ status }) {
  const labels = {
    running: '运行中', done: '已完成', queued: '排队',
    paused: '暂停', failed: '失败',
  };
  return <span className={`status-pill-table ${status}`}>{labels[status] || status}</span>;
}

function ProjectsView({ projects, onOpenProject, onNewProject, currentProjectId }) {
  const [filter, setFilter] = usePV('all');
  const [query, setQuery] = usePV('');

  const filtered = useMV(() => {
    let list = projects;
    if (filter === 'active') list = list.filter(p => ['running', 'queued'].includes(p.status));
    else if (filter === 'done') list = list.filter(p => p.status === 'done');
    else if (filter === 'attention') list = list.filter(p => ['paused', 'failed'].includes(p.status));
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter(p =>
        p.name.toLowerCase().includes(q) ||
        String(p.id).includes(q) ||
        p.desc.toLowerCase().includes(q)
      );
    }
    return list;
  }, [projects, filter, query]);

  const filters = [
    { id: 'all', label: `全部 ${projects.length}` },
    { id: 'active', label: `进行中 ${projects.filter(p => ['running', 'queued'].includes(p.status)).length}` },
    { id: 'attention', label: `需关注 ${projects.filter(p => ['paused', 'failed'].includes(p.status)).length}` },
    { id: 'done', label: `已完成 ${projects.filter(p => p.status === 'done').length}` },
  ];

  return (
    <div className="proj-view">
      <div className="proj-head">
        <div className="proj-head-l">
          <h1>项目</h1>
          <p>所有由 Hermes Pipeline 驱动的工作流。新建项目将依次经过 需求分析 → PRD → 原型 三阶段。</p>
        </div>
        <div className="proj-head-r">
          <button className="hdr-btn">导入需求</button>
          <button className="hdr-btn primary" onClick={onNewProject}>
            {Icon.plus} 新建项目
          </button>
        </div>
      </div>

      <div className="proj-kpis">
        {window.PROJECT_KPIS.map((k) => (
          <div className="kpi" key={k.label}>
            <div className="kpi-label">{k.label}</div>
            <div className={`kpi-val ${k.tone}`}>{k.value}</div>
            <div className="kpi-sub">{k.sub}</div>
          </div>
        ))}
      </div>

      <div className="proj-toolbar">
        <div className="proj-filter-group">
          {filters.map(f => (
            <button key={f.id} className={filter === f.id ? 'on' : ''} onClick={() => setFilter(f.id)}>
              {f.label}
            </button>
          ))}
        </div>
        <input
          className="proj-search"
          type="text"
          placeholder="搜索项目编号、名称、描述…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        <div className="proj-toolbar-spacer" />
        <button className="hdr-btn">导出 CSV</button>
        <button className="hdr-btn">列设置</button>
      </div>

      <div className="proj-table-wrap">
        <table className="proj-table">
          <thead>
            <tr>
              <th className="col-id">编号</th>
              <th className="col-priority">P</th>
              <th className="col-name">项目</th>
              <th className="col-stage">Pipeline 阶段</th>
              <th className="col-progress">进度</th>
              <th className="col-skills">Skill 调用</th>
              <th className="col-owner">负责人</th>
              <th className="col-updated">更新</th>
              <th className="col-status">状态</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(p => (
              <tr key={p.id} onClick={() => onOpenProject(p.id)}
                  style={p.id === currentProjectId ? { background: 'var(--accent-soft)' } : {}}>
                <td className="col-id">#{p.id}</td>
                <td className="col-priority"><span className={`priority ${p.priority}`}>{p.priority}</span></td>
                <td className="col-name">
                  <b>{p.name}</b>
                  <span>{p.desc}</span>
                </td>
                <td className="col-stage"><MiniPipeline project={p} /></td>
                <td className="col-progress">
                  <div className={`progress-bar ${p.status}`}>
                    <i style={{ width: `${p.progress}%` }} />
                  </div>
                  <div className="progress-num">{p.progress}% · {p.duration}</div>
                </td>
                <td className="col-skills">{p.skillCalls}</td>
                <td className="col-owner">
                  <div className="owner">
                    <span className="owner-av" style={{ background: p.owner.color }}>{p.owner.initial}</span>
                    <span>{p.owner.name}</span>
                  </div>
                </td>
                <td className="col-updated">{p.updated}</td>
                <td className="col-status"><StatusPill status={p.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PlaceholderView({ title, desc }) {
  return (
    <div className="placeholder-view">
      <div>
        <h2>{title}</h2>
        <p>{desc}</p>
      </div>
    </div>
  );
}

Object.assign(window, { NavRail, ProjectsView, PlaceholderView, Icon });
