// pages-platform.jsx — 平台方 A 層: 總覽 / 機構列表 / 機構詳情 / 成效分析 / 帳號權限 / 設定
const { useState: useP } = React;

// ---------- 平台總覽 ----------
function PagePlatformOverview({ go }) {
  const { INSTITUTIONS, Kicker, SectionTitle, Hero, StatStrip, TrendMark, Row } = window;
  const totalMembers = INSTITUTIONS.reduce((a, i) => a + i.members, 0);
  const avgRate = Math.round(INSTITUTIONS.reduce((a, i) => a + i.rate, 0) / INSTITUTIONS.length);
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}><Kicker>平台總覽</Kicker><Kicker>樂動有感 · 本月</Kicker></div>
      <Hero value="5" unit=" 家" label="服務機構" blurb="智慧樂齡復能評估系統，本月在 5 家機構陪伴 187 位長輩。" />
      <StatStrip items={[{ value: totalMembers, label: '服務長輩' }, { value: '8,940', label: '本月教具使用' }, { value: avgRate + '%', label: '平均參與率' }]} />
      <div style={{ marginTop: 26 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
          <SectionTitle style={{ marginBottom: 0 }}>導入機構 · 依市場分層</SectionTitle>
          <span onClick={() => go('plat.institutions')} style={{ fontSize: 12, color: 'var(--ink-2)', cursor: 'pointer', borderBottom: '1px solid var(--ink-2)', paddingBottom: 1 }}>全部機構 →</span>
        </div>
        <div style={{ display: 'flex', paddingBottom: 7, marginTop: 10 }}><Kicker style={{ flex: 1 }}>機構</Kicker><Kicker style={{ width: 150, textAlign: 'right' }}>類型 · 分層</Kicker><Kicker style={{ width: 56, textAlign: 'right' }}>長輩</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>參與率</Kicker><Kicker style={{ width: 40, textAlign: 'right' }}>趨勢</Kicker></div>
        {INSTITUTIONS.map((inst) => (
          <Row key={inst.id} onClick={() => go('plat.institution', { instId: inst.id })} pad={13}>
            <span style={{ flex: 1, display: 'flex', alignItems: 'baseline', gap: 9 }}><span style={{ fontSize: 14 }}>{inst.name}</span>{inst.live ? <span style={{ fontSize: 11, color: 'var(--active-text)' }}>· 已上線</span> : <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>· 試辦籌備</span>}</span>
            <span style={{ width: 150, textAlign: 'right', fontSize: 12, color: 'var(--ink-2)' }}>{inst.type} · {inst.tier}{inst.tierNote ? '（' + inst.tierNote + '）' : ''}</span>
            <span className="fr" style={{ width: 56, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{inst.members}</span>
            <span className="fr" style={{ width: 64, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{inst.rate}%</span>
            <span style={{ width: 40, textAlign: 'right', fontSize: 14 }}><TrendMark trend={inst.trend} /></span>
          </Row>
        ))}
      </div>
    </div>
  );
}

// ---------- 機構列表 ----------
function PageInstitutions({ go }) {
  const { INSTITUTIONS, Kicker, PageHeader, FilterRow, TrendMark, Row, Note } = window;
  const [tier, setTier] = useP('全部');
  const list = INSTITUTIONS.filter((i) => tier === '全部' || i.tier === tier);
  return (
    <div>
      <PageHeader kicker="平台 · 樂動有感" title="機構" blurb="依商業計畫書市場分層（Tier 1／2／3）管理導入機構。日照為核心，醫事 C 與轉型養護為利基與潛力。" />
      <div style={{ marginBottom: 18 }}><FilterRow label="分層" options={['全部', 'Tier 1', 'Tier 2', 'Tier 3']} value={tier} onChange={setTier} /></div>
      <div style={{ display: 'flex', paddingBottom: 7 }}><Kicker style={{ flex: 1 }}>機構</Kicker><Kicker style={{ width: 96 }}>類型</Kicker><Kicker style={{ width: 60 }}>分層</Kicker><Kicker style={{ width: 48, textAlign: 'right' }}>縣市</Kicker><Kicker style={{ width: 56, textAlign: 'right' }}>長輩</Kicker><Kicker style={{ width: 60, textAlign: 'right' }}>參與率</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>狀態</Kicker></div>
      {list.map((inst) => (
        <Row key={inst.id} onClick={() => go('plat.institution', { instId: inst.id })} pad={13}>
          <span className="sr" style={{ flex: 1, fontSize: 15 }}>{inst.name}</span>
          <span style={{ width: 96, fontSize: 13, color: 'var(--ink-2)' }}>{inst.type}</span>
          <span style={{ width: 60, fontSize: 13, color: 'var(--ink-2)' }}>{inst.tier}</span>
          <span style={{ width: 48, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{inst.county}</span>
          <span className="fr" style={{ width: 56, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{inst.members}</span>
          <span className="fr" style={{ width: 60, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{inst.rate}%</span>
          <span style={{ width: 64, textAlign: 'right', fontSize: 12, color: inst.live ? 'var(--active-text)' : 'var(--ink-3)' }}>{inst.live ? '已上線' : '籌備'}</span>
        </Row>
      ))}
      <div style={{ marginTop: 14 }}><Note>渠道為 B2B2B：外聘講師與樂齡團隊作為 seed channel partner，由點到面反向擴散。約跨越 40 家機構達損益兩平。</Note></div>
    </div>
  );
}

// ---------- 機構詳情 ----------
function PageInstitutionDetail({ go, instId }) {
  const { INSTITUTIONS, Kicker, PageHeader, StatStrip, SectionTitle, KV, Note, OutlineButton, TrendBars, BackLink } = window;
  const inst = INSTITUTIONS.find((i) => i.id === instId);
  return (
    <div>
      <BackLink onClick={() => go('plat.institutions')}>機構</BackLink>
      <PageHeader kicker={inst.type + ' · ' + inst.tier + (inst.tierNote ? '（' + inst.tierNote + '）' : '')} title={inst.name}
        right={inst.live ? <OutlineButton solid onClick={() => window.__switchPersona('institution')}>進入機構端視角 →</OutlineButton> : <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>試辦籌備中</span>} />
      <StatStrip items={[{ value: inst.members, label: '服務長輩' }, { value: inst.classes, label: '開課班別' }, { value: inst.rate + '%', label: '參與率' }]} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 26 }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>機構資料</SectionTitle>
          <KV k="所在縣市" v={inst.county} /><KV k="市場分層" v={inst.tier} /><KV k="主責督導" v={inst.lead} /><KV k="上線狀態" v={inst.live ? '已上線' : '試辦籌備'} vTone={inst.live ? 'var(--active-text)' : undefined} />
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>參與率趨勢（近六週）</SectionTitle>
          <TrendBars vals={inst.live ? [78, 80, 83, 84, 86, 87] : [58, 60, 61, 62, 63, inst.rate]} />
        </div>
      </div>
      {!inst.live && <div style={{ marginTop: 16 }}><Note>此機構為市場分層中的試辦籌備對象，尚未上線。上線後即可下鑽至班別與學員六力。康寧為目前的示範機構。</Note></div>}
    </div>
  );
}

// ---------- 成效分析 ----------
function PagePlatformAnalytics({ go }) {
  const { INSTITUTIONS, Kicker, PageHeader, SectionTitle, DotRow, Note } = window;
  const tiers = [['Tier 1', 3], ['Tier 2', 1], ['Tier 3', 1]];
  const counties = [['屏東', 2], ['桃園', 1], ['台中', 1], ['高雄', 1]];
  return (
    <div>
      <PageHeader kicker="平台 · 跨機構" title="成效分析" blurb="跨機構的參與率與分層分布。機構層級成效對得上評鑑視角，也用於辨識需扶植的據點。" />
      <SectionTitle>各機構參與率</SectionTitle>
      {INSTITUTIONS.map((i) => <DotRow key={i.id} label={i.name} value={i.rate} labelWidth={150} />)}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 28 }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>市場分層分布</SectionTitle>
          {tiers.map(([t, n]) => (
            <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}><span style={{ width: 56, fontSize: 13 }}>{t}</span><div style={{ flex: 1, height: 2, background: 'var(--border)', position: 'relative' }}><div style={{ position: 'absolute', left: 0, top: 0, height: 2, width: (n / 3 * 100) + '%', background: 'var(--mark)' }} /></div><span className="fr" style={{ width: 40, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{n} 家</span></div>
          ))}
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>縣市分布</SectionTitle>
          {counties.map(([c, n]) => (
            <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}><span style={{ width: 40, fontSize: 13 }}>{c}</span><div style={{ flex: 1, height: 2, background: 'var(--border)', position: 'relative' }}><div style={{ position: 'absolute', left: 0, top: 0, height: 2, width: (n / 2 * 100) + '%', background: 'var(--mark)' }} /></div><span className="fr" style={{ width: 40, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{n} 家</span></div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 18 }}><Note>長青養護中心（Tier 3，轉型中）參與率偏低、趨勢下降，列為優先扶植；缺乏專業帶課人力是主要結構成因。</Note></div>
    </div>
  );
}

// ---------- 帳號與權限 ----------
function PageAccounts({ go }) {
  const { ACCOUNTS, Kicker, PageHeader, FilterRow, Note, Row } = window;
  const [role, setRole] = useP('全部');
  const list = ACCOUNTS.filter((a) => role === '全部' || a.role === role);
  const roleName = { A: 'A · 平台方', B: 'B · 機構管理者', C: 'C · 機構服務員' };
  return (
    <div>
      <PageHeader kicker="平台 · 權限架構" title="帳號與權限"
        blurb="三層權限：A 平台方見全平台；B 機構管理者見自己機構全部資料與評鑑匯出；C 服務員以班別為入口、下鑽至個人學員。" />
      <div style={{ marginBottom: 18 }}><FilterRow label="層級" options={[{ value: '全部', label: '全部' }, { value: 'A', label: 'A 平台' }, { value: 'B', label: 'B 管理' }, { value: 'C', label: 'C 服務員' }]} value={role} onChange={setRole} /></div>
      <div style={{ display: 'flex', paddingBottom: 7 }}><Kicker style={{ flex: 1 }}>姓名</Kicker><Kicker style={{ width: 120 }}>層級</Kicker><Kicker style={{ width: 150 }}>所屬</Kicker><Kicker style={{ width: 80, textAlign: 'right' }}>最近登入</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>狀態</Kicker></div>
      {list.map((a) => (
        <Row key={a.name} pad={12}>
          <span style={{ flex: 1, fontSize: 14 }}>{a.name}</span>
          <span style={{ width: 120, fontSize: 13, color: 'var(--ink-2)' }}>{roleName[a.role]}</span>
          <span style={{ width: 150, fontSize: 13, color: 'var(--ink-2)' }}>{a.org}</span>
          <span className="fr" style={{ width: 80, textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{a.last}</span>
          <span style={{ width: 64, textAlign: 'right', fontSize: 12, color: a.status === '啟用' ? 'var(--active-text)' : 'var(--ink-3)' }}>{a.status}</span>
        </Row>
      ))}
      <div style={{ marginTop: 14 }}><Note>選擇某帳號可檢視其可見範圍（scope）。廠商端為獨立入口，正式權限規格待定；家屬端未來規劃為極簡 app，不列入當前範圍。</Note></div>
    </div>
  );
}

// ---------- 平台設定 ----------
function PagePlatformSettings({ go }) {
  const { Kicker, PageHeader, SectionTitle, KV, Note } = window;
  const forms = [['屏東縣衛生局', '日間照顧服務評鑑 · 成效面'], ['桃園市衛生局', '社區式服務類評鑑指標 C 構面'], ['高雄市衛生局', '長照機構服務品質 · 個案進展'], ['台中市衛生局', '失智照顧服務 · 個案進展（待校）']];
  return (
    <div>
      <PageHeader kicker="平台 · 樂動有感" title="設定" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>評鑑轄區格式庫</SectionTitle>
          {forms.map(([n, f]) => <div key={n} style={{ padding: '11px 0', borderTop: '0.5px solid var(--border)' }}><div style={{ fontSize: 14 }}>{n}</div><Kicker style={{ marginTop: 3 }}>{f}</Kicker></div>)}
          <div style={{ marginTop: 14 }}><Note>評鑑為地方主管機關辦理（長照服務法第 39 條）；各轄區文件格式不同，報表須能依轄區設定。</Note></div>
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>服務邊界與資料治理</SectionTitle>
          <KV k="服務定位" v="健康促進 · 功能維持" /><KV k="醫療診斷" v="明確排除" /><KV k="運作網路" v="機構封閉網路 · 地端" /><KV k="資料留存" v="留在機構內" /><KV k="AI 揭露" v="依各 venue 政策" /><KV k="系統版本" v="v3 · 米白墨色" />
          <div style={{ marginTop: 14 }}><Note>邊緣緩存、地端 LLM、資料不出機構，回應隱私法遵與機構網路不穩的現實。</Note></div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PagePlatformOverview, PageInstitutions, PageInstitutionDetail, PagePlatformAnalytics, PageAccounts, PagePlatformSettings });
