// screens/workspace.jsx — role-based home

function ScreenWorkspace({ role, scenario, onOpenTask, onOpenPatient, onAlert, onRoleClick }) {
  const tasks = tasksFor(role.id, scenario.id);
  const alert = scenario.alert;

  // partition: 等我的球 (urgent/mine), 任务 (active/pending), 已完成
  const mine = tasks.filter(t => t.pri === 'urgent' || t.pri === 'mine');
  const ongoing = tasks.filter(t => t.pri === 'active' || t.pri === 'pending' || t.pri === 'blocked');
  const done = tasks.filter(t => t.pri === 'done');

  // role-specific greeting/stat
  const stat = STAT_FOR_ROLE[role.id] || { l: '待办', n: tasks.length, sub: '今日' };

  // watched patients (all 3, ordered by relevance to current scenario)
  const watchedIds = scenario.alert?.patient
    ? [scenario.alert.patient, ...ALL_PATIENTS.filter(p => p !== scenario.alert.patient)]
    : ALL_PATIENTS;

  return (
    <div>
      <TopBar
        role={role}
        onRoleClick={onRoleClick}
        title={role.workbench}
        subtitle={`${greeting()} · ${role.me} ${role.meTitle}`}
      />

      {/* hero alert */}
      <div style={{ marginTop: 6 }}>
        <HeroAlert alert={alert} onAction={() => onAlert(alert)} />
      </div>

      {/* KPI strip */}
      <div style={{ display:'flex', gap: 8, padding: '4px 16px 0' }}>
        <KpiTile main={stat.n} label={stat.l} sub={stat.sub} />
        <KpiTile main={mine.length} label="等我的球" sub="需我处理" highlight={mine.length>0} />
        <KpiTile main="3" label="关注患者" sub="已订阅" />
      </div>

      {/* 等我的球 */}
      {mine.length > 0 && (
        <>
          <SectionLabel right={`${mine.length} 项`}>
            <span style={{ display:'inline-flex', alignItems:'center', gap: 4 }}>
              <I.Bolt size={11}/> 等我的球
            </span>
          </SectionLabel>
          <div style={{ display:'flex', flexDirection:'column', gap: 10, padding: '0 16px' }}>
            {mine.map(t => <TaskCard key={t.id} task={t} onClick={() => onOpenTask(t)} />)}
          </div>
        </>
      )}

      {/* 我的任务 */}
      {ongoing.length > 0 && (
        <>
          <SectionLabel right="按节点排序">我的任务</SectionLabel>
          <div style={{ display:'flex', flexDirection:'column', gap: 10, padding: '0 16px' }}>
            {ongoing.map(t => <TaskCard key={t.id} task={t} onClick={() => onOpenTask(t)} />)}
          </div>
        </>
      )}

      {/* 我关注的患者 */}
      <SectionLabel right="全科可搜">我关注的患者</SectionLabel>
      <div style={{ padding: '0 16px', display:'flex', flexDirection:'column', gap: 10 }}>
        {watchedIds.map(pid => (
          <WatchedPatientCard key={pid} patientId={pid} onClick={() => onOpenPatient(pid)} />
        ))}
      </div>

      {/* 已完成 折叠 */}
      {done.length > 0 && (
        <>
          <SectionLabel>近期完成</SectionLabel>
          <div style={{ padding: '0 16px', display:'flex', flexDirection:'column', gap: 10 }}>
            {done.map(t => <TaskCardCompact key={t.id} task={t} onClick={() => onOpenTask(t)} />)}
          </div>
        </>
      )}

      <div style={{ height: 110 }}/>
    </div>
  );
}

// ─────────── KPI tile (small, in row of 3) ───────────
function KpiTile({ main, label, sub, highlight }) {
  return (
    <div style={{
      flex: 1, background: 'var(--surface)',
      borderRadius: 12, border: '1px solid var(--border)',
      padding: '10px 12px', boxShadow: 'var(--sh-card)',
    }}>
      <div style={{
        fontSize: 22, fontWeight: 700, color: highlight ? '#C0252F' : 'var(--t1)',
        letterSpacing: -0.6, lineHeight: 1.1,
        fontFamily: "'IBM Plex Mono', monospace",
      }}>{main}</div>
      <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--t1)', marginTop: 4 }}>{label}</div>
      <div style={{ fontSize: 10.5, color: 'var(--t3)', marginTop: 1 }}>{sub}</div>
    </div>
  );
}

// ─────────── Watched patient card — name + dx + node strip ───────────
function WatchedPatientCard({ patientId, onClick }) {
  const p = PATIENTS[patientId];
  // determine current node — first non-done forward
  const cur = NODES.find(n => p.progress[n.id]?.state !== 'done')?.id;
  const curState = p.progress[cur]?.state;
  const curOwner = p.progress[cur]?.by;
  const curWait = p.progress[cur]?.waiting;
  const curTag = p.progress[cur]?.tag;
  const fr = p.progress.tx?.fraction;

  return (
    <Card onClick={onClick} pad={0}>
      <div style={{ padding: '12px 14px 12px 16px' }}>
        <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
          <PatientSigil tag={p.photoTag} size={32}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display:'flex', alignItems:'baseline', gap: 8 }}>
              <div style={{ fontSize: 15, fontWeight: 600, color:'var(--t1)' }}>{p.name}</div>
              <div style={{ fontSize: 11.5, color:'var(--t3)' }}>{p.sex} · {p.age}岁</div>
              {fr && <div style={{ marginLeft: 'auto', fontSize: 11.5 }} className="mono">{fr}</div>}
            </div>
            <div style={{ fontSize: 12, color: 'var(--t2)', marginTop: 1 }}>{p.dx}</div>
          </div>
        </div>
        <div style={{ marginTop: 10 }}>
          <NodeStrip progress={p.progress} current={cur} />
        </div>
        <div style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          marginTop: 8, fontSize: 12, color: 'var(--t2)',
        }}>
          <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
            <span style={{
              width: 6, height: 6, borderRadius: 6,
              background: curState==='mine'?'#C0252F':curState==='blocked'?'#B14B0E':curState==='active'?'#1F5AA8':'#A9B3BB',
            }}/>
            <span style={{ color: 'var(--t1)', fontWeight: 500 }}>{NODES.find(n=>n.id===cur)?.label}</span>
            {curTag && <span style={{ color:'var(--st-block-ink)' }}>· {curTag}</span>}
          </div>
          <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
            {curOwner && <span>{ROLES[curOwner.role]?.name} {curOwner.name}</span>}
            {curWait && <span className="mono" style={{ color: 'var(--t1)' }}>{curWait}</span>}
          </div>
        </div>
      </div>
    </Card>
  );
}

// ─────────── compact done task ───────────
function TaskCardCompact({ task, onClick }) {
  const p = PATIENTS[task.patient];
  return (
    <Card onClick={onClick} pad={0} style={{ background: 'var(--surface-2)' }}>
      <div style={{ padding: '10px 14px', display:'flex', alignItems:'center', gap: 10 }}>
        <PatientSigil tag={p.photoTag} size={26}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 500, color: 'var(--t1)' }}>{task.title}</div>
          <div style={{ fontSize: 11.5, color: 'var(--t3)' }}>{task.sub}</div>
        </div>
        <Chip kind="done">已完成</Chip>
      </div>
    </Card>
  );
}

// ─────────── role stat config ───────────
const STAT_FOR_ROLE = {
  physician:   { l: '今日待办', n: '5',  sub: '勾画 2 · 处方 1 · 审核 2' },
  physicist:   { l: '审核积压', n: '3',  sub: '当日 + 2 待 QA' },
  dosimetrist: { l: '在制计划', n: '4',  sub: '抢单池 6' },
  therapist:   { l: '今日分次', n: '24', sub: 'LA-2 已完成 7' },
  nurse:       { l: '当日预约', n: '38', sub: '冲突 1' },
};

function greeting() {
  const h = new Date().getHours();
  if (h < 5) return '夜班好';
  if (h < 11) return '早上好';
  if (h < 14) return '中午好';
  if (h < 18) return '下午好';
  return '晚上好';
}

Object.assign(window, { ScreenWorkspace });
