// app.jsx — shell: sidebar nav + top bar + per-persona multi-page router
const { useState: useS, useEffect: useE } = React;

const PERSONAS = {
  platform:    { label: '平台方',     org: '樂動有感', sub: 'A 層 · 平台方', account: '姚絜歆', accountRole: '平台管理者', home: 'plat.overview', host: 'funmotion.health' },
  institution: { label: '機構端',     org: '康寧日間照顧中心', sub: 'B／C 層 · 機構', account: '林淑芬', accountRole: '機構主任', home: 'inst.overview', host: 'kangning.funmotion.health' },
  vendor:      { label: 'AIoT 廠商端', org: '悅動智慧教具', sub: '教具夥伴入口', account: '周思妤', accountRole: '客戶成功', home: 'ven.overview', host: 'partner.funmotion.health' },
};

const MENUS = {
  platform: [
    { id: 'plat.overview', label: '平台總覽' },
    { id: 'plat.institutions', label: '機構' },
    { id: 'plat.analytics', label: '成效分析' },
    { id: 'plat.accounts', label: '帳號與權限' },
    { id: 'plat.settings', label: '設定' },
  ],
  institution: [
    { id: 'inst.overview', label: '總覽' },
    { id: 'inst.classes', label: '班別' },
    { id: 'inst.members', label: '學員' },
    { id: 'inst.priority', label: '優先關注' },
    { id: 'inst.devices', label: '教具' },
    { id: 'inst.reports', label: '報表中心' },
    { id: 'inst.settings', label: '設定與權限' },
  ],
  vendor: [
    { id: 'ven.overview', label: '總覽' },
    { id: 'ven.models', label: '型號' },
    { id: 'ven.adopters', label: '導入機構' },
    { id: 'ven.devices', label: '裝置' },
    { id: 'ven.trends', label: '趨勢分析' },
  ],
};

// detail section → parent (for sidebar highlight)
const PARENT = {
  'inst.member': 'inst.members', 'inst.class': 'inst.classes', 'inst.device': 'inst.devices',
  'inst.reportgen': 'inst.reports', 'plat.institution': 'plat.institutions', 'ven.model': 'ven.models',
};

const PERSONA_OF = (section) => section.startsWith('plat.') ? 'platform' : section.startsWith('ven.') ? 'vendor' : 'institution';

const WIN_W = 1280, WIN_H = 824;
const CHROME_H = 84, TOPBAR_H = 58;

function App() {
  const [section, setSection] = useS('plat.overview');
  const [params, setParams] = useS({});
  const [persona, setPersona] = useS('platform');
  const [search, setSearch] = useS('');
  const [scale, setScale] = useS(1);

  useE(() => {
    const fit = () => setScale(Math.min((window.innerWidth - 28) / WIN_W, (window.innerHeight - 28) / WIN_H, 1));
    fit(); window.addEventListener('resize', fit); return () => window.removeEventListener('resize', fit);
  }, []);

  const go = (sec, p = {}) => {
    setSection(sec); setParams(p); setSearch('');
    const sc = document.getElementById('appscroll'); if (sc) sc.scrollTop = 0;
  };
  const switchPersona = (id) => { setPersona(id); go(PERSONAS[id].home); };
  window.__switchPersona = switchPersona;

  const P = PERSONAS[persona];
  const activeTop = PARENT[section] || section;
  const url = P.host + '/' + (MENUS[persona].find((m) => m.id === activeTop)?.label || '') ;

  return (
    <div style={{ position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--stage-bg)' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'center center' }}>
        <window.ChromeWindow width={WIN_W} height={WIN_H} url={url} tabs={[{ title: P.org + ' · 智慧樂齡復能評估系統' }]}>
          <div style={{ height: WIN_H - CHROME_H, display: 'flex', flexDirection: 'column', background: 'var(--canvas)', fontFamily: "'Noto Sans TC',sans-serif" }}>
            <TopBar persona={persona} P={P} switchPersona={switchPersona} go={go} search={search} setSearch={setSearch} />
            <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
              <Sidebar persona={persona} section={activeTop} go={go} P={P} />
              <div id="appscroll" style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', borderLeft: '0.5px solid var(--border-strong)' }}>
                <div key={section + (params.studentId || params.classId || params.instId || params.toolId || params.modelId || '')} className="screen" style={{ padding: '30px 38px 40px', maxWidth: 1000 }}>
                  {renderSection(persona, section, params, go)}
                </div>
              </div>
            </div>
          </div>
        </window.ChromeWindow>
      </div>
    </div>
  );
}

function TopBar({ persona, P, switchPersona, go, search, setSearch }) {
  const { STUDENTS } = window;
  const results = persona === 'institution' && search.trim()
    ? STUDENTS.filter((s) => s.name.includes(search.trim())).slice(0, 6) : [];
  return (
    <div style={{ height: TOPBAR_H, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px 0 26px', borderBottom: '0.5px solid var(--border-strong)', position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 11 }}>
        <span className="sr" style={{ fontSize: 17 }}>樂動有感</span>
        <span style={{ fontSize: 11.5, letterSpacing: '.06em', color: 'var(--ink-3)' }}>智慧樂齡復能評估系統 · N4 即時回饋</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
        {persona === 'institution' && (
          <div style={{ position: 'relative' }}>
            <window.SearchField value={search} onChange={setSearch} placeholder="搜尋學員…" />
            {results.length > 0 && (
              <div style={{ position: 'absolute', top: 30, right: 0, left: 0, background: 'var(--surface)', border: '0.5px solid var(--border-strong)', zIndex: 20 }}>
                {results.map((s) => (
                  <div key={s.id} onClick={() => go('inst.member', { studentId: s.id })} className="hoverrow"
                    style={{ padding: '9px 12px', fontSize: 13, cursor: 'pointer', borderTop: '0.5px solid var(--border)', display: 'flex', justifyContent: 'space-between' }}>
                    <span>{s.name}</span><span style={{ color: 'var(--ink-3)', fontSize: 12 }}>{window.classById(s.classId).name}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
        {/* demo persona switch */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ fontSize: 11, letterSpacing: '.08em', color: 'var(--ink-3)' }}>示範視角</span>
          {Object.keys(PERSONAS).map((id) => (
            <span key={id} onClick={() => switchPersona(id)} style={{
              cursor: 'pointer', fontSize: 12.5,
              color: persona === id ? 'var(--ink)' : 'var(--ink-3)',
              borderBottom: persona === id ? '1px solid var(--ink)' : '1px solid transparent', paddingBottom: 2,
            }}>{PERSONAS[id].label}</span>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, paddingLeft: 16, borderLeft: '0.5px solid var(--border)' }}>
          <span style={{ width: 28, height: 28, borderRadius: '50%', border: '0.5px solid var(--border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: 'var(--ink-2)' }} className="sr">{P.account[0]}</span>
          <div style={{ lineHeight: 1.25 }}>
            <div style={{ fontSize: 12.5 }}>{P.account}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{P.accountRole}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Sidebar({ persona, section, go, P }) {
  return (
    <div style={{ width: 206, flexShrink: 0, padding: '22px 0 18px', display: 'flex', flexDirection: 'column', background: 'var(--canvas)' }}>
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ fontSize: 11, letterSpacing: '.08em', color: 'var(--ink-3)', marginBottom: 6 }}>{P.sub}</div>
        <div className="sr" style={{ fontSize: 15, lineHeight: 1.3 }}>{P.org}</div>
      </div>
      <div style={{ flex: 1 }}>
        {MENUS[persona].map((m) => {
          const active = m.id === section;
          return (
            <div key={m.id} onClick={() => go(m.id)} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '9px 22px', cursor: 'pointer',
              color: active ? 'var(--ink)' : 'var(--ink-2)',
            }} className="navitem">
              <span style={{ width: 2, height: 14, background: active ? 'var(--ink)' : 'transparent', flexShrink: 0, marginLeft: -8 }} />
              <span style={{ fontSize: 13.5, fontWeight: active ? 500 : 400 }} className={active ? 'sr' : ''}>{m.label}</span>
            </div>
          );
        })}
      </div>
      <div style={{ padding: '14px 22px 0', borderTop: '0.5px solid var(--border)', margin: '0 0', fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.6 }}>
        封閉網路 · 地端運作<br />資料留存機構內
      </div>
    </div>
  );
}

function renderSection(persona, section, params, go) {
  const R = window;
  switch (section) {
    // platform
    case 'plat.overview': return <R.PagePlatformOverview go={go} />;
    case 'plat.institutions': return <R.PageInstitutions go={go} />;
    case 'plat.institution': return <R.PageInstitutionDetail go={go} instId={params.instId} />;
    case 'plat.analytics': return <R.PagePlatformAnalytics go={go} />;
    case 'plat.accounts': return <R.PageAccounts go={go} />;
    case 'plat.settings': return <R.PagePlatformSettings go={go} />;
    // institution
    case 'inst.overview': return <R.PageInstOverview go={go} />;
    case 'inst.classes': return <R.PageClasses go={go} />;
    case 'inst.class': return <R.PageClassDetail go={go} classId={params.classId} />;
    case 'inst.members': return <R.PageMembers go={go} />;
    case 'inst.member': return <R.PageMember go={go} studentId={params.studentId} />;
    case 'inst.priority': return <R.PagePriority go={go} />;
    case 'inst.devices': return <R.PageDevices go={go} />;
    case 'inst.device': return <R.PageDeviceDetail go={go} toolId={params.toolId} />;
    case 'inst.reports': return <R.PageReports go={go} />;
    case 'inst.reportgen': return <R.PageReportGen go={go} studentId={params.studentId} />;
    case 'inst.settings': return <R.PageInstSettings go={go} />;
    // vendor
    case 'ven.overview': return <R.PageVendorOverview go={go} />;
    case 'ven.models': return <R.PageModels go={go} />;
    case 'ven.model': return <R.PageModelDetail go={go} modelId={params.modelId} />;
    case 'ven.adopters': return <R.PageAdopters go={go} />;
    case 'ven.devices': return <R.PageVendorDevices go={go} />;
    case 'ven.trends': return <R.PageVendorTrends go={go} />;
    default: return <div>—</div>;
  }
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
