// institution.jsx — 機構端（暖版 + 六力 + LLM 文字建議）
const { useState: useI } = React;

// —— LLM 文字建議產生器（把六力翻成白話建議，取代純報表）——
const POWER_SUGGEST = {
  '認知力': '多安排「互動式認知遊戲機」「觸控記憶配對」，從簡單關卡開始累積成就感。',
  '反應力': '建議多玩「響叮噹」，鈴聲反應練習能幫助專注與手眼協調。',
  '體適能力': '可加入「沙鈴」「腳響樂」等律動活動，溫和提升肢體活動量。',
  '自主力': '讓長輩自己選活動與音樂，多給選擇權能提升參與動機。',
  '社交力': '安排雙人或小組一起進行的活動，鼓勵彼此加油、共同完成。',
  '情緒力': '多給正向回饋與小獎勵，完成後的肯定能維持愉快與持續參與。',
};
function llmSuggestion(s) {
  const recent = window.round1(window.recentAvg(s));
  const base = window.round1(window.baselineAvg(s));
  const delta = window.round1(window.deltaAvg(s));
  const rec = window.SIX_ORDER.map((k) => ({ k, b: s.sp[k][0], r: s.sp[k][1], d: s.sp[k][1] - s.sp[k][0] }));
  const strongest = [...rec].sort((a, b) => b.r - a.r)[0];
  const improved = [...rec].sort((a, b) => b.d - a.d)[0];
  const weakest = [...rec].sort((a, b) => a.r - b.r)[0];
  const trendWord = delta > 1.5 ? '穩定進步' : delta < -1.5 ? '需要多點陪伴' : '大致持平';
  const summary = `${s.name}最近整體參與${trendWord}。六力平均 ${base} 分 → ${recent} 分（${delta >= 0 ? '+' : ''}${delta} 分）。`;
  const highlights = [
    `表現最好的是「${strongest.k}」（${strongest.r} 分），可作為帶動其他活動的切入點。`,
    improved.d > 0 ? `進步最多的是「${improved.k}」（${improved.d >= 0 ? '+' : ''}${improved.d} 分），這套訓練對他有效，值得持續。`
      : `各項變化不大，可嘗試換個活動方式增加新鮮感。`,
  ];
  const suggestions = [
    `${weakest.k}是目前較需要加強的一項（${weakest.r} 分）。${POWER_SUGGEST[weakest.k]}`,
    POWER_SUGGEST[strongest.k],
  ];
  return { summary, highlights, suggestions, recent, base, delta };
}

function InstitutionApp({ onExit }) {
  const [view, setView] = useI({ name: 'overview', params: {} });
  const go = (name, params = {}) => setView({ name, params });
  const NAV = [
    { key: 'overview', label: '總覽' },
    { key: 'members', label: '學員' },
    { key: 'priority', label: '優先關注' },
    { key: 'reports', label: '成效報告' },
    { key: 'settings', label: '設定' },
  ];
  const activeNav = view.name === 'member' ? 'members' : view.name;

  return (
    <div style={{ display: 'flex', minHeight: '100vh' }}>
      {/* sidebar */}
      <div style={{ width: 232, flex: '0 0 232px', background: 'var(--surface)', borderRight: '1.5px solid var(--border)',
        padding: '22px 16px', position: 'sticky', top: 0, height: '100vh', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 6px 18px' }}>
          <window.Mascot mood="happy" size={40} />
          <div>
            <div style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, lineHeight: 1 }}>樂睦</div>
            <div style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)' }}>機構端</div>
          </div>
        </div>
        {NAV.map((n) => (
          <button key={n.key} onClick={() => go(n.key)} style={{
            textAlign: 'left', background: activeNav === n.key ? 'var(--sunken)' : 'transparent', border: 'none',
            borderRadius: 14, padding: '14px 16px', fontSize: 'var(--fs-lead)', fontWeight: activeNav === n.key ? 900 : 700,
            color: activeNav === n.key ? 'var(--ink)' : 'var(--ink-2)', cursor: 'pointer', marginBottom: 4 }}>
            {n.label}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <window.GhostButton onClick={onExit} style={{ minHeight: 48 }}>登出</window.GhostButton>
      </div>

      {/* main */}
      <div id="scroll" style={{ flex: 1, overflowY: 'auto', height: '100vh' }}>
        <div style={{ background: 'var(--surface)', borderBottom: '1.5px solid var(--border)', padding: '14px 30px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'sticky', top: 0, zIndex: 4 }}>
          <span style={{ fontSize: 'var(--fs-h3)', fontWeight: 900 }}>康寧日間照顧中心</span>
          <span style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)', fontWeight: 700 }}>林淑芬 · 機構管理員</span>
        </div>
        <div style={{ padding: '28px 30px 60px', maxWidth: 1080 }}>
          {view.name === 'overview' && <Overview go={go} />}
          {view.name === 'members' && <Members go={go} />}
          {view.name === 'member' && <MemberProfile id={view.params.id} go={go} />}
          {view.name === 'priority' && <Priority go={go} />}
          {view.name === 'reports' && <Reports />}
          {view.name === 'settings' && <Settings />}
        </div>
      </div>
    </div>
  );
}

function KPI({ label, value, unit, tone: t = 'primary', hint }) {
  const c = window.tone(t);
  return (
    <window.Card pad={20} style={{ flex: '1 1 200px' }}>
      <div style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)', fontWeight: 700 }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, margin: '6px 0' }}>
        <span className="num" style={{ fontSize: 'var(--fs-display)', fontWeight: 900, color: c.solid, lineHeight: 1 }}>{value}</span>
        <span style={{ fontSize: 'var(--fs-lead)', color: 'var(--ink-2)', fontWeight: 800 }}>{unit}</span>
      </div>
      {hint && <div style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)' }}>{hint}</div>}
    </window.Card>
  );
}

// 狀態標記：形狀 + 文字 + 顏色 三重編碼
function StatusBadge({ status }) {
  const map = {
    '活躍': { tone: 'mint', shape: '●' },
    '需關注': { tone: 'sun', shape: '◐' },
    '未啟用': { tone: 'primary', shape: '○' },
  };
  const m = map[status]; const c = window.tone(m.tone);
  const color = status === '未啟用' ? 'var(--ink-3)' : c.ink;
  const bg = status === '未啟用' ? 'var(--sunken)' : c.soft;
  return <span style={{ background: bg, color, borderRadius: 999, padding: '4px 12px', fontSize: 'var(--fs-small)', fontWeight: 800, whiteSpace: 'nowrap' }}>{m.shape} {status}</span>;
}

function Overview({ go }) {
  const inst = window.INSTITUTIONS[0];
  const watch = window.WATCH.slice(0, 5);
  const activeCount = window.STUDENTS.filter((s) => s.status === '活躍').length;
  return (
    <div className="screen">
      <window.MascotSay text="今天有 38 位長輩來活動，整體狀況不錯！有 3 位想多陪陪。" mood="happy" size={84} />
      <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', margin: '24px 0' }}>
        <KPI label="今日活動人次" value="38" unit="人次" tone="primary" hint="昨日 31" />
        <KPI label="本週參與率" value={inst.rate} unit="%" tone="mint" hint="↑ 比上週 +4%" />
        <KPI label="需要多陪陪" value={window.WATCH.length} unit="位" tone="sun" hint="溫和關心即可" />
        <KPI label="平均六力" value={window.INST_MEAN} unit="分" tone="sky" hint="全機構近期平均" />
      </div>

      <h3 style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, margin: '8px 0 14px' }}>需要多陪陪的長輩</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {watch.map((s) => (
          <div key={s.id} className="hoverrow" onClick={() => go('member', { id: s.id })} style={{
            display: 'flex', alignItems: 'center', gap: 16, background: 'var(--surface)', border: '1.5px solid var(--border)',
            borderRadius: 16, padding: '14px 18px', cursor: 'pointer' }}>
            <window.Avatar tone="sun" name={s.name} size={48} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 'var(--fs-lead)', fontWeight: 800 }}>{s.name}</div>
              <div style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)' }}>{window.classById(s.classId).name} · 本週 {s.weekUses} 次</div>
            </div>
            <StatusBadge status={s.status} />
            <span style={{ color: 'var(--ink-3)', fontSize: 'var(--fs-lead)' }}>›</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Members({ go }) {
  const [q, setQ] = useI('');
  const [filter, setFilter] = useI('全部');
  const list = window.STUDENTS.filter((s) =>
    (filter === '全部' || s.status === filter) && (!q || s.name.includes(q)));
  const filters = ['全部', '活躍', '需關注', '未啟用'];
  return (
    <div className="screen">
      <h2 style={{ fontSize: 'var(--fs-h2)', fontWeight: 900, margin: '0 0 16px' }}>學員（{window.STUDENTS.length} 位）</h2>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
        <div style={{ flex: '1 1 220px', position: 'relative', display: 'flex', alignItems: 'center' }}>
          <span style={{ position: 'absolute', left: 14, display: 'flex' }}><window.IcSearch size={18} color="var(--ink-3)" /></span>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜尋姓名" style={{
            width: '100%', fontSize: 'var(--fs-body)', padding: '12px 16px 12px 42px', borderRadius: 12,
            border: '2px solid var(--border)', background: 'var(--surface)', fontFamily: 'inherit' }} />
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {filters.map((f) => (
            <button key={f} onClick={() => setFilter(f)} style={{
              border: '2px solid var(--border)', background: filter === f ? 'var(--primary)' : 'var(--surface)',
              color: filter === f ? '#fff' : 'var(--ink-2)', borderColor: filter === f ? 'var(--primary)' : 'var(--border)',
              borderRadius: 999, padding: '10px 18px', fontSize: 'var(--fs-body)', fontWeight: 800, cursor: 'pointer' }}>{f}</button>
          ))}
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 12 }}>
        {list.map((s) => (
          <div key={s.id} className="card-hover" onClick={() => go('member', { id: s.id })} style={{
            display: 'flex', alignItems: 'center', gap: 14, background: 'var(--surface)', border: '1.5px solid var(--border)',
            borderRadius: 16, padding: 16, cursor: 'pointer', boxShadow: 'var(--shadow-soft)' }}>
            <window.Avatar tone="mint" name={s.name} size={48} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 'var(--fs-lead)', fontWeight: 800 }}>{s.name}</div>
              <div style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)' }}>{window.classById(s.classId).name}</div>
            </div>
            <StatusBadge status={s.status} />
          </div>
        ))}
      </div>
    </div>
  );
}

function MemberProfile({ id, go }) {
  const s = window.studentById(id);
  const sug = llmSuggestion(s);
  const rows = window.SIX_ORDER.map((k) => ({ name: k, b: s.sp[k][0], r: s.sp[k][1], soft: window.PSYCHOSOCIAL.includes(k) }));
  return (
    <div className="screen">
      <button onClick={() => go('members')} style={{ background: 'none', border: 'none', color: 'var(--ink-2)', fontSize: 'var(--fs-body)', fontWeight: 800, cursor: 'pointer', padding: 0, marginBottom: 14 }}>← 學員名單</button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 22 }}>
        <window.Avatar tone="mint" name={s.name} size={72} />
        <div>
          <div style={{ fontSize: 'var(--fs-h1)', fontWeight: 900, lineHeight: 1 }}>{s.name}</div>
          <div style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)', marginTop: 6, fontWeight: 700 }}>
            {window.classById(s.classId).name} · 加入 {s.joinMonths} 個月
          </div>
        </div>
        <div style={{ marginLeft: 'auto' }}><StatusBadge status={s.status} /></div>
      </div>

      <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
        {/* radar */}
        <window.Card style={{ flex: '1 1 360px' }}>
          <h3 style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, margin: '0 0 4px' }}>樂齡六力</h3>
          <p style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)', margin: '0 0 10px' }}>實線＝近期，虛線＝初評。標 ◦ 為推估值</p>
          <window.Radar student={s} />
        </window.Card>
        {/* 前後測 */}
        <window.Card style={{ flex: '1 1 320px' }}>
          <h3 style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, margin: '0 0 14px' }}>前後測變化</h3>
          <window.SlopeChart rows={rows} />
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
            <span style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)', fontWeight: 700 }}>六力平均</span>
            <span className="num" style={{ fontSize: 'var(--fs-lead)', fontWeight: 900 }}>
              {sug.base} → {sug.recent}
              <span style={{ color: sug.delta >= 0 ? 'var(--gain)' : 'var(--loss)' }}>{sug.delta >= 0 ? '▲ +' : '▼ '}{sug.delta}</span>
            </span>
          </div>
        </window.Card>
      </div>

      {/* LLM 文字建議 */}
      <window.Card style={{ marginTop: 20, borderColor: 'var(--primary)', borderWidth: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <window.Mascot mood="happy" size={44} />
          <h3 style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, margin: 0 }}>給照服員的訓練建議</h3>
          <window.Tag tone="grape">AI 整理</window.Tag>
        </div>
        <p style={{ fontSize: 'var(--fs-lead)', fontWeight: 700, lineHeight: 1.6, margin: '0 0 14px' }}>{sug.summary}</p>
        <div style={{ marginBottom: 12 }}>
          {sug.highlights.map((h, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 8, alignItems: 'flex-start' }}>
              <span style={{ flex: '0 0 auto', marginTop: 3 }}><window.IcCheck size={18} color="var(--gain)" /></span>
              <span style={{ fontSize: 'var(--fs-body)', lineHeight: 1.55 }}>{h}</span>
            </div>
          ))}
        </div>
        <div style={{ background: 'var(--sunken)', borderRadius: 14, padding: 16 }}>
          <div style={{ fontSize: 'var(--fs-body)', fontWeight: 900, marginBottom: 8 }}>建議下一步</div>
          {sug.suggestions.map((x, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
              <span style={{ color: 'var(--primary)', fontWeight: 900 }}>{i + 1}.</span>
              <span style={{ fontSize: 'var(--fs-body)', lineHeight: 1.55 }}>{x}</span>
            </div>
          ))}
        </div>
        <p style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)', marginTop: 12, marginBottom: 0 }}>
          ※ 自主力／社交力／情緒力為參與行為推估值，建議搭配現場觀察。本建議為健康促進參考，非醫療診斷。
        </p>
      </window.Card>
    </div>
  );
}

function Priority({ go }) {
  return (
    <div className="screen">
      <h2 style={{ fontSize: 'var(--fs-h2)', fontWeight: 900, margin: '0 0 6px' }}>優先關注</h2>
      <p style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)', margin: '0 0 18px' }}>
        橫軸＝比起初評的進退步，縱軸＝相對機構平均。空心圈＝需多陪陪（刻意不用紅色警報）。
      </p>
      <window.Card>
        <window.QuadrantScatter go={(name, p) => go('member', { id: p.studentId })} />
      </window.Card>
    </div>
  );
}

function Reports() {
  const [gen, setGen] = useI(null); // null | 'running' | 'done'
  return (
    <div className="screen">
      <h2 style={{ fontSize: 'var(--fs-h2)', fontWeight: 900, margin: '0 0 16px' }}>成效報告</h2>
      <window.Card style={{ marginBottom: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div style={{ fontSize: 'var(--fs-h3)', fontWeight: 900 }}>產生機構成效報告</div>
            <div style={{ fontSize: 'var(--fs-body)', color: 'var(--ink-2)' }}>依轄區格式 · 屏東縣衛生局</div>
          </div>
          <window.BigButton size="md" onClick={() => { setGen('running'); setTimeout(() => setGen('done'), 1400); }}>
            {gen === 'running' ? '產生中…' : '一鍵產生'}
          </window.BigButton>
        </div>
        {gen === 'running' && <p style={{ color: 'var(--ink-2)', marginTop: 14 }}>正在彙整參與數據、清洗與視覺化…</p>}
        {gen === 'done' && (
          <div style={{ marginTop: 16, background: 'var(--sunken)', borderRadius: 14, padding: 18 }}>
            <div style={{ fontWeight: 900, fontSize: 'var(--fs-lead)', marginBottom: 8 }}>✓ 已產出：康寧 · 機構成效報告（2026 Q2）</div>
            <p style={{ fontSize: 'var(--fs-body)', margin: '0 0 10px', lineHeight: 1.6 }}>
              本季 41 位長輩平均六力 {window.INST_MEAN} 分，較上季穩定成長。律動健身班參與率最高，建議持續；
              失智友善班可增加團體互動以提升社交參與。
            </p>
            <window.Tag tone="mint">PDF</window.Tag> <window.Tag tone="sky">Word</window.Tag>
            <p style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)', marginTop: 12, marginBottom: 0 }}>
              ※ 健康促進與功能維持之教育型活動報告，排除醫療診斷；心理社會三力為推估值。
            </p>
          </div>
        )}
      </window.Card>
      <h3 style={{ fontSize: 'var(--fs-h3)', fontWeight: 900, margin: '0 0 12px' }}>已存檔報告</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {window.REPORTS.map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 14, background: 'var(--surface)',
            border: '1.5px solid var(--border)', borderRadius: 14, padding: '14px 18px' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 'var(--fs-lead)', fontWeight: 800 }}>{r.title}</div>
              <div style={{ fontSize: 'var(--fs-small)', color: 'var(--ink-3)' }}>{r.period} · {r.juri} · {r.by}</div>
            </div>
            <window.Tag tone="primary">{r.scope}</window.Tag>
            <span style={{ color: 'var(--ink-3)', fontSize: 'var(--fs-body)', fontWeight: 800 }}>{r.date}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Settings() {
  return (
    <div className="screen">
      <h2 style={{ fontSize: 'var(--fs-h2)', fontWeight: 900, margin: '0 0 16px' }}>設定</h2>
      <window.Card>
        <p style={{ fontSize: 'var(--fs-lead)', color: 'var(--ink-2)', fontWeight: 700, margin: 0 }}>
          轄區報告格式、班別與帳號權限設定 — 下週版本提供。
        </p>
      </window.Card>
    </div>
  );
}

Object.assign(window, { InstitutionApp });
