// pages-inst-b.jsx — 機構端: 優先關注 / 教具 / 教具詳情 / 報表中心 / 報表產生 / 設定與權限
const { useState: useIB } = React;

// ---------- 優先關注 (四象限) ----------
function PagePriority({ go }) {
  const { ASSESSED, INST_MEAN, quadrantOf, QUADRANT_META, PageHeader, SectionTitle, Kicker, Note, QuadrantScatter } = window;
  const groups = ['maintain', 'follow', 'acute', 'risk'].map((key) => ({ key, meta: QUADRANT_META[key], list: ASSESSED.filter((s) => quadrantOf(s) === key) }));
  return (
    <div>
      <PageHeader kicker="機構 · dual-anchor 評估" title="優先關注"
        blurb={'交叉兩個錨點看每位長輩：自己的前測基準，與機構同期平均（' + INST_MEAN + '）。把「最近沒來」升級為臨床上有意義的關注順序。'} />
      <div style={{ display: 'grid', gridTemplateColumns: '1.15fr 1fr' }}>
        <div style={{ paddingRight: 24 }}>
          <QuadrantScatter go={go} />
          <div style={{ display: 'flex', gap: 18, marginTop: 6 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-2)' }}><span style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--mark)' }} />一般</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-2)' }}><span style={{ width: 9, height: 9, borderRadius: '50%', background: 'var(--canvas)', border: '1.5px solid var(--attention)' }} />需關注</span>
          </div>
        </div>
        <div style={{ paddingLeft: 24, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>優先順序與建議</SectionTitle>
          {groups.map((g) => (
            <div key={g.key} style={{ padding: '13px 0', borderTop: '0.5px solid var(--border)' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}><span className="sr" style={{ fontSize: 15 }}>{g.meta.label}</span><span className="fr" style={{ fontSize: 18, color: 'var(--ink-2)' }}>{g.list.length}</span></div>
              <Kicker style={{ marginTop: 3, lineHeight: 1.6 }}>{g.meta.note}</Kicker>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
                {g.list.map((s) => <span key={s.id} onClick={() => go('inst.member', { studentId: s.id })} style={{ fontSize: 13, cursor: 'pointer', borderBottom: '1px solid var(--border-strong)', paddingBottom: 1 }}>{s.name}</span>)}
              </div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 18 }}><Note>語氣為鼓勵而非警報：左下象限以空心圈與中性灰標記「建議關注」，刻意不使用紅色；紅色僅保留給個別能力的退步變化量（↓）。</Note></div>
    </div>
  );
}

// ---------- 教具 ----------
function PageDevices({ go }) {
  const { DEVICES, toolById, Kicker, PageHeader, TrendMark, Row } = window;
  return (
    <div>
      <PageHeader kicker="機構 · 康寧日間照顧中心" title="教具" blurb="5 款 AIoT 教具於封閉網路內運作，活動即紀錄。點選檢視量測參數與使用班別。" />
      <div style={{ display: 'flex', paddingBottom: 7 }}>
        <Kicker style={{ flex: 1 }}>教具</Kicker><Kicker style={{ width: 90 }}>類型</Kicker><Kicker style={{ width: 90, textAlign: 'right' }}>在線／台數</Kicker><Kicker style={{ width: 80, textAlign: 'right' }}>本週使用</Kicker><Kicker style={{ width: 48, textAlign: 'right' }}>趨勢</Kicker>
      </div>
      {DEVICES.map((d) => { const t = toolById(d.toolId); return (
        <Row key={d.toolId} onClick={() => go('inst.device', { toolId: d.toolId })} pad={13}>
          <span className="sr" style={{ flex: 1, fontSize: 15 }}>{t.name}</span>
          <span style={{ width: 90, fontSize: 13, color: 'var(--ink-2)' }}>{t.type}</span>
          <span className="fr" style={{ width: 90, textAlign: 'right', fontSize: 14, color: d.online < d.units ? 'var(--ink)' : 'var(--ink-2)' }}>{d.online} / {d.units}</span>
          <span className="fr" style={{ width: 80, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{d.weekUses}</span>
          <span style={{ width: 48, textAlign: 'right', fontSize: 14 }}><TrendMark trend={d.trend} /></span>
        </Row>
      ); })}
    </div>
  );
}

// ---------- 教具詳情 ----------
function PageDeviceDetail({ go, toolId }) {
  const { DEVICES, toolById, Kicker, PageHeader, StatStrip, SectionTitle, KV, Note, BackLink } = window;
  const t = toolById(toolId); const d = DEVICES.find((x) => x.toolId === toolId);
  return (
    <div>
      <BackLink onClick={() => go('inst.devices')}>教具</BackLink>
      <PageHeader kicker={t.type + ' · AIoT 教具'} title={t.name} />
      <StatStrip items={[{ value: d.units, label: '裝置台數' }, { value: d.online, label: '在線', tone: d.online < d.units ? 'var(--ink)' : undefined }, { value: d.weekUses, label: '本週使用次數' }]} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 26 }}>
        <div style={{ paddingRight: 24 }}>
          <SectionTitle>量測參數（本週均值）</SectionTitle>
          {d.sample.map(([k, v]) => <KV key={k} k={k} v={v} />)}
          <div style={{ marginTop: 14 }}><Note>參數為 mockup 示意，借用真實參數詞彙。依 Minimal-Sensing 設計哲學，感測由 AI 推論需求反推，追求最小可行感測。</Note></div>
        </div>
        <div style={{ paddingLeft: 24, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>使用班別</SectionTitle>
          {d.classes.map((c) => <div key={c} style={{ padding: '10px 0', borderTop: '0.5px solid var(--border)', fontSize: 14 }}>{c}</div>)}
          <div style={{ marginTop: 16 }}><Kicker style={{ lineHeight: 1.7 }}>感知透明 · 被動採集 · 臨床對齊 · 環境耐用（BMEiCON 四原則）</Kicker></div>
        </div>
      </div>
    </div>
  );
}

// ---------- 報表中心 ----------
function PageReports({ go }) {
  const { REPORTS, Kicker, PageHeader, OutlineButton, Row, Note } = window;
  return (
    <div>
      <PageHeader kicker="機構 · 康寧日間照顧中心" title="報表中心"
        right={<OutlineButton solid onClick={() => go('inst.reportgen')}>產生新報表</OutlineButton>}
        blurb="一鍵彙整操作數據、訓練頻率與表現變化，依轄區（縣市衛生局）格式輸出前後測對比，把評鑑行政整理成本轉為標準化輸出。" />
      <div style={{ display: 'flex', paddingBottom: 7 }}>
        <Kicker style={{ flex: 1 }}>報表</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>範圍</Kicker><Kicker style={{ width: 110, textAlign: 'right' }}>期間</Kicker><Kicker style={{ width: 120, textAlign: 'right' }}>轄區格式</Kicker><Kicker style={{ width: 90, textAlign: 'right' }}>產出</Kicker>
      </div>
      {REPORTS.map((r, i) => (
        <Row key={i} pad={13}>
          <span style={{ flex: 1, fontSize: 14 }}>{r.title}</span>
          <span style={{ width: 64, textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{r.scope}</span>
          <span className="fr" style={{ width: 110, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{r.period}</span>
          <span style={{ width: 120, textAlign: 'right', fontSize: 12, color: 'var(--ink-2)' }}>{r.juri}</span>
          <span className="fr" style={{ width: 90, textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{r.date}</span>
        </Row>
      ))}
      <div style={{ marginTop: 14 }}><Note>評鑑為地方主管機關（縣市衛生局，長照服務法第 39 條）；報表可依轄區設定格式，不寫死為單一中央標準。</Note></div>
    </div>
  );
}

// ---------- 報表產生 ----------
const JURISDICTIONS = [
  { id: 'pt', name: '屏東縣衛生局', form: '日間照顧服務評鑑 · 成效面' },
  { id: 'ty', name: '桃園市衛生局', form: '社區式服務類評鑑指標 C 構面' },
  { id: 'kh', name: '高雄市衛生局', form: '長照機構服務品質 · 個案進展' },
];
function PageReportGen({ go, studentId }) {
  const { studentById, classById, SIX_ORDER, PSYCHOSOCIAL, recentAvg, baselineAvg, deltaAvg, round1,
    Kicker, SectionTitle, OutlineButton, Note, SlopeChart, TrendLine, TrendBars, BackLink } = window;
  const [juri, setJuri] = useIB('pt'); const [state, setState] = useIB('idle');
  const s = studentId ? studentById(studentId) : null;
  const j = JURISDICTIONS.find((x) => x.id === juri);
  const run = () => { setState('gen'); setTimeout(() => setState('done'), 1100); };
  const slope = s ? SIX_ORDER.map((k) => ({ name: k, b: s.sp[k][0], r: s.sp[k][1], soft: PSYCHOSOCIAL.includes(k) })) : [];
  const comp = s ? (() => { const b = baselineAvg(s), r = recentAvg(s); return [b, b + (r - b) * 0.4, b + (r - b) * 0.7, r].map((v) => round1(v)); })() : null;
  return (
    <div>
      <BackLink onClick={() => go('inst.reports')}>報表中心</BackLink>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '14px 0 18px' }}>
        <span className="sr" style={{ fontSize: 22 }}>{s ? s.name + ' · 前後測成效報告' : '康寧日間照顧中心 · 機構成效報告'}</span>
        <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
          <Kicker>輸出格式 ·</Kicker>
          {JURISDICTIONS.map((x) => <span key={x.id} onClick={() => { setJuri(x.id); setState('idle'); }} style={{ fontSize: 12, cursor: 'pointer', color: juri === x.id ? 'var(--ink)' : 'var(--ink-3)', borderBottom: juri === x.id ? '1px solid var(--ink)' : '1px solid transparent', paddingBottom: 1 }}>{x.name}</span>)}
        </div>
      </div>
      <div style={{ background: 'var(--surface)', border: '0.5px solid var(--border-strong)', padding: '28px 32px' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', borderBottom: '0.5px solid var(--border-strong)', paddingBottom: 14 }}>
          <div><div className="sr" style={{ fontSize: 20 }}>{s ? s.name : '康寧日間照顧中心'}</div><Kicker style={{ marginTop: 6 }}>{j.name} · {j.form}</Kicker></div>
          <div style={{ textAlign: 'right' }}><Kicker>報告期間</Kicker><div className="fr" style={{ fontSize: 16, marginTop: 4 }}>2026.02 – 2026.05</div></div>
        </div>
        {s ? (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 22 }}>
            <div style={{ paddingRight: 26 }}><SectionTitle style={{ fontSize: 15 }}>六力前後測對比</SectionTitle><SlopeChart rows={slope} /></div>
            <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border)' }}>
              <SectionTitle style={{ fontSize: 15 }}>整體趨勢（四次評估）</SectionTitle>
              <TrendLine vals={comp} labels={['初評', '第 1 月', '第 2 月', '近期']} />
              <div style={{ display: 'flex', borderTop: '0.5px solid var(--border-strong)', borderBottom: '0.5px solid var(--border-strong)', marginTop: 18 }}>
                <div style={{ flex: 1, padding: '12px 0' }}><div className="fr" style={{ fontSize: 22 }}>{Math.round(baselineAvg(s))}<span style={{ fontSize: 14, color: 'var(--ink-3)' }}> → {Math.round(recentAvg(s))}</span></div><Kicker style={{ marginTop: 3 }}>六力平均</Kicker></div>
                <div style={{ flex: 1, padding: '12px 0 12px 16px', borderLeft: '0.5px solid var(--border)' }}><div className="fr" style={{ fontSize: 22, color: deltaAvg(s) >= 0 ? 'var(--gain)' : 'var(--loss)' }}>{deltaAvg(s) >= 0 ? '↑ ' : '↓ '}{Math.abs(round1(deltaAvg(s)))}</div><Kicker style={{ marginTop: 3 }}>淨變化</Kicker></div>
              </div>
            </div>
          </div>
        ) : (
          <div style={{ marginTop: 22 }}>
            <SectionTitle style={{ fontSize: 15 }}>機構整體參與趨勢（近六週）</SectionTitle>
            <TrendBars vals={[71, 76, 79, 83, 85, 87]} />
            <div style={{ marginTop: 14 }}><Note>整體參與率自 71% 升至 87%；41 位長輩中 10 位完成前後測對比，六力平均淨變化 +6。完整個別對比可由各學員檔案逐一輸出。</Note></div>
          </div>
        )}
        <div style={{ marginTop: 24, paddingTop: 14, borderTop: '0.5px solid var(--border)' }}><Note>本報告為健康促進與功能維持之教育型日常活動成效記錄，用於照護溝通與服務優化，明確排除醫療診斷用途。心理社會三力為參與行為推估值。</Note></div>
      </div>
      <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Kicker>{state === 'idle' && '依 ' + j.name + ' 格式一鍵輸出。'}{state === 'gen' && '正在彙整操作數據、清洗與視覺化…'}{state === 'done' && <span style={{ color: 'var(--active-text)' }}>● 已產出　{j.name}_成效報告_2026Q2.pdf</span>}</Kicker>
        <OutlineButton solid onClick={run}>{state === 'done' ? '重新匯出' : state === 'gen' ? '產生中…' : '一鍵匯出評鑑報表'}</OutlineButton>
      </div>
    </div>
  );
}

// ---------- 設定與權限 ----------
function PageInstSettings({ go }) {
  const { ACCOUNTS, INSTITUTIONS, Kicker, PageHeader, SectionTitle, KV, Note, StatusMark } = window;
  const [juri, setJuri] = useIB('pt');
  const inst = INSTITUTIONS.find((i) => i.id === 'i1');
  const local = ACCOUNTS.filter((a) => a.org === '康寧日間照顧中心');
  return (
    <div>
      <PageHeader kicker="機構 · 康寧日間照顧中心" title="設定與權限" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0 }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>機構資料</SectionTitle>
          <KV k="機構名稱" v={inst.name} /><KV k="類型" v={inst.type} /><KV k="市場分層" v={inst.tier + '（示範）'} /><KV k="所在縣市" v={inst.county} /><KV k="主責督導" v={inst.lead} /><KV k="服務長輩" v={inst.members + ' 位'} />
          <div style={{ marginTop: 24 }}>
            <SectionTitle>評鑑轄區格式</SectionTitle>
            <div style={{ display: 'flex', gap: 14, marginBottom: 8 }}>
              {JURISDICTIONS.map((x) => <span key={x.id} onClick={() => setJuri(x.id)} style={{ fontSize: 13, cursor: 'pointer', color: juri === x.id ? 'var(--ink)' : 'var(--ink-3)', borderBottom: juri === x.id ? '1px solid var(--ink)' : '1px solid transparent', paddingBottom: 2 }}>{x.name}</span>)}
            </div>
            <Note>目前套用：{JURISDICTIONS.find((x) => x.id === juri).form}。報表將依此轄區格式輸出。</Note>
          </div>
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>本機構帳號（C 層服務員 / B 層管理）</SectionTitle>
          {local.map((a) => (
            <div key={a.name} style={{ padding: '12px 0', borderTop: '0.5px solid var(--border)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}><span style={{ fontSize: 14 }}>{a.name}<span style={{ fontSize: 12, color: 'var(--ink-3)', marginLeft: 8 }}>{a.roleLabel}</span></span><span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{a.last}</span></div>
              <Kicker style={{ marginTop: 4 }}>可見範圍：{a.scope}</Kicker>
            </div>
          ))}
          <div style={{ marginTop: 16 }}><Note>C 層以班別為入口，先看整班再下鑽個人；B 層可見全機構並匯出評鑑。權限三層由平台方（A）統一管理。</Note></div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PagePriority, PageDevices, PageDeviceDetail, PageReports, PageReportGen, PageInstSettings });
