// pages-vendor.jsx — AIoT 廠商端: 總覽 / 型號 / 型號詳情 / 導入機構 / 裝置 / 趨勢分析
const { useState: useV } = React;

// ---------- 總覽 ----------
function PageVendorOverview({ go }) {
  const { VENDOR, Kicker, SectionTitle, Hero, StatStrip, TrendMark, Row } = window;
  const maxCounty = Math.max(...VENDOR.counties.map((c) => c.n));
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}><Kicker>教具品牌總覽</Kicker><Kicker>{VENDOR.brand} · 本月</Kicker></div>
      <Hero value={VENDOR.activeInst} unit=" 家" label="活躍機構" blurb={'你的教具本月在 ' + VENDOR.activeInst + ' 家機構、' + VENDOR.devices + ' 台裝置上被長輩使用。'} />
      <StatStrip items={[{ value: VENDOR.devices, label: '活躍裝置（台）' }, { value: VENDOR.totalUses.toLocaleString(), label: '累積使用次數' }, { value: VENDOR.avgCompletion + '%', label: '平均完成率' }]} />
      <div style={{ display: 'grid', gridTemplateColumns: '1.25fr 1fr', marginTop: 26 }}>
        <div style={{ paddingRight: 24 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}><SectionTitle style={{ marginBottom: 0 }}>各型號表現</SectionTitle><span onClick={() => go('ven.models')} 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: 64, textAlign: 'right' }}>使用次數</Kicker><Kicker style={{ width: 56, textAlign: 'right' }}>完成率</Kicker></div>
          {VENDOR.models.map((m) => (
            <Row key={m.id} onClick={() => go('ven.model', { modelId: m.id })} pad={9}>
              <span style={{ flex: 1, fontSize: 13 }}>{m.name}</span>
              <span className="fr" style={{ width: 64, textAlign: 'right', fontSize: 14 }}>{m.uses.toLocaleString()}</span>
              <span className="fr" style={{ width: 56, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{m.completion}%</span>
            </Row>
          ))}
        </div>
        <div style={{ paddingLeft: 24, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>機構縣市分佈</SectionTitle>
          {VENDOR.counties.map((c) => (
            <div key={c.name} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}><span style={{ width: 40, fontSize: 13 }}>{c.name}</span><div style={{ flex: 1, height: 2, background: 'var(--border)', position: 'relative' }}><div style={{ position: 'absolute', left: 0, top: 0, height: 2, width: Math.round((c.n / maxCounty) * 100) + '%', background: 'var(--mark)' }} /></div><span className="fr" style={{ width: 42, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{c.n} 家</span></div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}><SectionTitle style={{ marginBottom: 0 }}>導入機構</SectionTitle><span onClick={() => go('ven.adopters')} 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: 54, textAlign: 'right' }}>裝置</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>使用</Kicker><Kicker style={{ width: 56, textAlign: 'right' }}>完成率</Kicker><Kicker style={{ width: 48, textAlign: 'right' }}>趨勢</Kicker></div>
        {VENDOR.adopters.map((a) => (
          <Row key={a.name} pad={11}>
            <span style={{ flex: 1, fontSize: 14 }}>{a.name}</span>
            <span className="fr" style={{ width: 54, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.devices}</span>
            <span className="fr" style={{ width: 64, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.uses}</span>
            <span className="fr" style={{ width: 56, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.completion}%</span>
            <span style={{ width: 48, textAlign: 'right', fontSize: 14 }}><TrendMark trend={a.trend} /></span>
          </Row>
        ))}
      </div>
    </div>
  );
}

// ---------- 型號 ----------
function PageModels({ go }) {
  const { VENDOR, Kicker, PageHeader, TrendMark, Row } = window;
  return (
    <div>
      <PageHeader kicker="廠商 · 悅動智慧教具" title="型號" blurb="5 款型號的市場表現。點選檢視量測參數與導入分布。" />
      <div style={{ display: 'flex', paddingBottom: 7 }}><Kicker style={{ flex: 1 }}>型號</Kicker><Kicker style={{ width: 90 }}>類型</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>裝置</Kicker><Kicker style={{ width: 72, textAlign: 'right' }}>使用次數</Kicker><Kicker style={{ width: 60, textAlign: 'right' }}>完成率</Kicker><Kicker style={{ width: 44, textAlign: 'right' }}>趨勢</Kicker></div>
      {VENDOR.models.map((m) => (
        <Row key={m.id} onClick={() => go('ven.model', { modelId: m.id })} pad={13}>
          <span className="sr" style={{ flex: 1, fontSize: 15 }}>{m.name}</span>
          <span style={{ width: 90, fontSize: 13, color: 'var(--ink-2)' }}>{m.type}</span>
          <span className="fr" style={{ width: 64, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{m.units}</span>
          <span className="fr" style={{ width: 72, textAlign: 'right', fontSize: 14 }}>{m.uses.toLocaleString()}</span>
          <span className="fr" style={{ width: 60, textAlign: 'right', fontSize: 14, color: 'var(--ink-2)' }}>{m.completion}%</span>
          <span style={{ width: 44, textAlign: 'right', fontSize: 14 }}><TrendMark trend={m.trend} /></span>
        </Row>
      ))}
    </div>
  );
}

// ---------- 型號詳情 ----------
function PageModelDetail({ go, modelId }) {
  const { VENDOR, Kicker, PageHeader, StatStrip, SectionTitle, KV, Note, BackLink } = window;
  const m = VENDOR.models.find((x) => x.id === modelId);
  const using = VENDOR.adopters.slice(0, 4);
  return (
    <div>
      <BackLink onClick={() => go('ven.models')}>型號</BackLink>
      <PageHeader kicker={m.type + ' · AIoT 教具型號'} title={m.name} />
      <StatStrip items={[{ value: m.units, label: '裝置（台）' }, { value: m.uses.toLocaleString(), label: '累積使用次數' }, { value: m.completion + '%', label: '完成率' }]} />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 26 }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>量測參數（跨機構均值）</SectionTitle>
          {m.sample.map(([k, v]) => <KV key={k} k={k} v={v} />)}
          <div style={{ marginTop: 14 }}><Note>參數為 mockup 示意。實際感測規格由 AI 推論需求反推（Minimal-Sensing），追求最小可行感測。</Note></div>
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>導入機構</SectionTitle>
          {using.map((a) => (
            <div key={a.name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '10px 0', borderTop: '0.5px solid var(--border)' }}><span style={{ fontSize: 14 }}>{a.name}</span><span className="fr" style={{ fontSize: 13, color: 'var(--ink-2)' }}>{a.devices} 台</span></div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- 導入機構 ----------
function PageAdopters({ go }) {
  const { VENDOR, Kicker, PageHeader, FilterRow, TrendMark, Row, Note } = window;
  const [county, setCounty] = useV('全部');
  const counties = ['全部', ...new Set(VENDOR.adopters.map((a) => a.county))];
  const list = VENDOR.adopters.filter((a) => county === '全部' || a.county === county);
  return (
    <div>
      <PageHeader kicker="廠商 · 悅動智慧教具" title="導入機構" blurb="教具被哪些機構採用、用得好不好。這是雙向平台的廠商視角，用於招商與續約溝通。" />
      <div style={{ marginBottom: 18 }}><FilterRow label="縣市" options={counties} value={county} onChange={setCounty} /></div>
      <div style={{ display: 'flex', paddingBottom: 7 }}><Kicker style={{ flex: 1 }}>機構</Kicker><Kicker style={{ width: 48, textAlign: 'right' }}>縣市</Kicker><Kicker style={{ width: 54, textAlign: 'right' }}>裝置</Kicker><Kicker style={{ width: 64, textAlign: 'right' }}>使用</Kicker><Kicker style={{ width: 56, textAlign: 'right' }}>完成率</Kicker><Kicker style={{ width: 70, textAlign: 'right' }}>導入</Kicker><Kicker style={{ width: 40, textAlign: 'right' }}>趨勢</Kicker></div>
      {list.map((a) => (
        <Row key={a.name} pad={13}>
          <span style={{ flex: 1, fontSize: 14 }}>{a.name}</span>
          <span style={{ width: 48, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.county}</span>
          <span className="fr" style={{ width: 54, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.devices}</span>
          <span className="fr" style={{ width: 64, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.uses}</span>
          <span className="fr" style={{ width: 56, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{a.completion}%</span>
          <span className="fr" style={{ width: 70, textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>{a.since}</span>
          <span style={{ width: 40, textAlign: 'right', fontSize: 14 }}><TrendMark trend={a.trend} /></span>
        </Row>
      ))}
      <div style={{ marginTop: 14 }}><Note>長青養護中心完成率與趨勢偏低，建議搭配機構帶課人力扶植；廠商與平台可共同設計介入。</Note></div>
    </div>
  );
}

// ---------- 裝置 ----------
function PageVendorDevices({ go }) {
  const { VENDOR, Kicker, PageHeader, SectionTitle, Note } = window;
  const rows = VENDOR.models.map((m) => ({ name: m.name, units: m.units, online: Math.max(0, m.units - (m.trend === 'down' ? 2 : m.trend === 'flat' ? 1 : 0)) }));
  const totalUnits = rows.reduce((a, r) => a + r.units, 0); const totalOnline = rows.reduce((a, r) => a + r.online, 0);
  return (
    <div>
      <PageHeader kicker="廠商 · 悅動智慧教具" title="裝置" blurb="跨機構裝置在線狀況。低在線多半反映機構網路不穩或裝置閒置，是續約與維運的早期訊號。" />
      <div style={{ display: 'flex', borderTop: '0.5px solid var(--border-strong)', borderBottom: '0.5px solid var(--border-strong)', marginBottom: 26 }}>
        <div style={{ flex: 1, padding: '14px 0' }}><div className="fr" style={{ fontSize: 23 }}>{totalUnits}</div><Kicker style={{ marginTop: 3 }}>裝置總數</Kicker></div>
        <div style={{ flex: 1, padding: '14px 0 14px 18px', borderLeft: '0.5px solid var(--border)' }}><div className="fr" style={{ fontSize: 23 }}>{totalOnline}</div><Kicker style={{ marginTop: 3 }}>在線</Kicker></div>
        <div style={{ flex: 1, padding: '14px 0 14px 18px', borderLeft: '0.5px solid var(--border)' }}><div className="fr" style={{ fontSize: 23 }}>{Math.round(totalOnline / totalUnits * 100)}%</div><Kicker style={{ marginTop: 3 }}>在線率</Kicker></div>
      </div>
      <SectionTitle>各型號在線</SectionTitle>
      <div style={{ display: 'flex', paddingBottom: 7 }}><Kicker style={{ flex: 1 }}>型號</Kicker><Kicker style={{ width: 100, textAlign: 'right' }}>在線／台數</Kicker><Kicker style={{ width: 120 }}></Kicker></div>
      {rows.map((r) => (
        <div key={r.name} style={{ display: 'flex', alignItems: 'center', padding: '11px 0', borderTop: '0.5px solid var(--border)', gap: 14 }}>
          <span style={{ flex: 1, fontSize: 14 }}>{r.name}</span>
          <span className="fr" style={{ width: 100, textAlign: 'right', fontSize: 14, color: r.online < r.units ? 'var(--ink)' : 'var(--ink-2)' }}>{r.online} / {r.units}</span>
          <div style={{ width: 120, height: 2, background: 'var(--border)', position: 'relative' }}><div style={{ position: 'absolute', left: 0, top: 0, height: 2, width: (r.online / r.units * 100) + '%', background: 'var(--mark)' }} /></div>
        </div>
      ))}
      <div style={{ marginTop: 14 }}><Note>全程於機構封閉網路運作，邊緣緩存；在線狀態為近端回報，資料不出機構。</Note></div>
    </div>
  );
}

// ---------- 趨勢分析 ----------
function PageVendorTrends({ go }) {
  const { VENDOR, Kicker, PageHeader, SectionTitle, TrendBars, TrendLine, Note } = window;
  const maxUses = Math.max(...VENDOR.models.map((m) => m.uses));
  return (
    <div>
      <PageHeader kicker="廠商 · 悅動智慧教具" title="趨勢分析" blurb="累積使用與完成率的時間走勢，以及型號使用占比。用於判斷哪些型號值得加碼、哪些需迭代。" />
      <SectionTitle>月使用次數（近六月）</SectionTitle>
      <TrendBars vals={[2980, 3210, 3460, 3680, 3950, 4210].map((v) => Math.round(v / 50))} prefix="M" max={Math.round(4210 / 50)} />
      <div style={{ marginTop: 8 }}><Note>數值為次數／50 之示意縮放；近六月累積使用自約 2,980 升至 4,210。</Note></div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', marginTop: 28 }}>
        <div style={{ paddingRight: 26 }}>
          <SectionTitle>平均完成率走勢</SectionTitle>
          <TrendLine vals={[71, 73, 74, 76, 77, 78]} labels={['M1', 'M2', 'M3', 'M4', 'M5', 'M6']} min={60} max={85} />
        </div>
        <div style={{ paddingLeft: 26, borderLeft: '0.5px solid var(--border-strong)' }}>
          <SectionTitle>型號使用占比</SectionTitle>
          {VENDOR.models.map((m) => (
            <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 13 }}><span style={{ flex: 1, fontSize: 13 }}>{m.name}</span><div style={{ width: 110, height: 2, background: 'var(--border)', position: 'relative' }}><div style={{ position: 'absolute', left: 0, top: 0, height: 2, width: (m.uses / maxUses * 100) + '%', background: 'var(--mark)' }} /></div><span className="fr" style={{ width: 50, textAlign: 'right', fontSize: 13, color: 'var(--ink-2)' }}>{m.uses.toLocaleString()}</span></div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PageVendorOverview, PageModels, PageModelDetail, PageAdopters, PageVendorDevices, PageVendorTrends });
