/* ============================================================
   shell.jsx — 应用外壳：侧栏 / 顶部栏 / 角色切换 / 路由
   ============================================================ */
const { Ico, Btn, Tag, Chip, Card, CardHead, Switch, Avatar, Drawer, Modal, Empty, Bar, Ring, StackBar, Spark, Toasts, useApp, Timeline, SrcDot } = window;
const { useState, Fragment } = React;



function UserBox() {
  const { user, logout } = useApp();
  if (!user) return null;
  return (
    <div className="role-switch" title={user.dept + ' · ' + user.username}>
      <span className="avatar" style={{ background: user.tint, color: '#fff', width: 22, height: 22, borderRadius: 99, display: 'inline-grid', placeItems: 'center', fontSize: 11 }}>{user.initials}</span>
      <span className="rl" style={{ color: 'var(--ink)' }}>{user.dept}</span>
      <button onClick={logout} title="退出登录" style={{ height: 24, padding: '0 10px', borderRadius: 99, fontSize: 12, color: 'var(--ink-2)' }}>退出</button>
    </div>
  );
}

function Rail() {
  const app = useApp();
  const { route, go, role, todo, decls, nav } = app;
  const myTodo = todo.length;
  const roleName = window.ROLES[role];
  const visible = window.NAV.filter((n) => !n.roles || n.roles.includes(role));

  const badgeFor = (key) => {
    if (key === 'approvals' && role === 'finance') { const n = todo.filter((t) => t.kind === 'approve').length; return n || null; }
    if (key === 'declarations') { const n = todo.filter((t) => t.kind === 'fill').length; return n || null; }
    if (key === 'sync' && role === 'supply') { const n = app.sync.diffs.filter((d) => d.status === 'open').length; return n || null; }
    return null;
  };

  return (
    <aside className="rail">
      <div className="rail-head">
        <span className="rail-logo"><Ico name="sigma" size={13} /></span>
        <span className="rail-title">成本预测管理系统</span>
        <button className="dots"><Ico name="drag" size={14} /></button>
      </div>
      <nav className="rail-nav">
        {visible.map((n, i) => n.group ? (
          <div className="rail-group" key={'g' + i}>{n.group}</div>
        ) : (
          <button key={n.key} className={'rail-item' + (route === n.key ? ' on' : '')} title={n.label} onClick={() => go(n.key)}>
            <span className="ico"><Ico name={n.icon} size={15} /></span>
            <span className="nowrap" style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{n.label}</span>
            {badgeFor(n.key) && <span className="badge">{badgeFor(n.key)}</span>}
          </button>
        ))}
      </nav>
      <div className="rail-foot">
        <span className="avatar" style={{ background: roleName.tint, color: '#fff' }}>{roleName.initials}</span>
        <div style={{ minWidth: 0 }}>
          <div className="who nowrap">{roleName.user}</div>
          <div className="role nowrap">{roleName.name}</div>
        </div>
        <span className="spacer" />
        <button className="icon-btn" title="设置"><Ico name="settings" size={14} /></button>
      </div>
    </aside>
  );
}

function Topbar() {
  const app = useApp();
  const { route, nav, role, todo } = app;
  const item = window.NAV.find((n) => n.key === route);
  const titles = {
    dashboard: ['成本测算看板', '当前工况与六方案比较'],
    drugs: ['药品管理', '切换 / 新增 / 导入车间数据'],
    sync: ['主数据同步', '中台 / SAP / BOM / 物料价格库 4 源与差异确认'],
    materials: ['物料与价格', 'BOM 单耗与价格库双轨单价'],
    rates: ['费用报工单价', 'KL01–KL10 · 财务录入'],
    formula: ['公式口径', '9 条口径 · 字段来源标注'],
    tasks: ['测算任务下发', '财务发起数据收集'],
    declarations: ['成本测算单', '生产车间填报 · 供应部确认 · 财务审批'],
    approvals: ['审批中心', '财务复核与审核锁定'],
    forecast: ['成本核算结果', '测算成本 / 最小单位成本 / 成本明细'],
    audit: ['审计日志', '全流程留痕与追溯'],
  };
  const t = titles[route] || ['成本预测管理系统', ''];
  const myTodo = todo.length;

  return (
    <header className="topbar">
      <div className="crumb">
        <span>{role === 'finance' ? '财务部' : role === 'prod' ? '生产车间' : '供应部'}</span>
        <Ico name="right" size={12} style={{ color: 'var(--ink-4)' }} />
        <b>{t[0]}</b>
      </div>
      <span className="tiny muted nowrap" style={{ marginLeft: 6 }}>{t[1]}</span>
      <div className="topbar-right">
        <span className="tiny muted nowrap">静态演示</span>
        <button className="icon-btn" title="通知" style={{ position: 'relative' }}>
          <Ico name="bell" size={16} />
          {myTodo > 0 && <span style={{ position: 'absolute', top: 4, right: 4, width: 7, height: 7, borderRadius: 99, background: 'var(--danger)', border: '1.5px solid #fff' }} />}
        </button>
        <div className="divider v" />
        <UserBox />
      </div>
    </header>
  );
}

const PAGES = {
  dashboard: () => <Dashboard />,
  drugs: () => <DrugsPage />,
  sync: () => <SyncPage />,
  materials: () => <MaterialsPage />,
  rates: () => <RatesPage />,
  formula: () => <FormulaPage />,
  tasks: () => <TasksPage />,
  declarations: () => <DeclarationsPage />,
  approvals: () => <ApprovalsPage />,
  forecast: () => <ForecastPage />,
  audit: () => <AuditPage />,
};

function Shell() {
  const app = useApp();
  const Page = PAGES[app.route] || PAGES.dashboard;
  return (
    <div className="app">
      <Rail />
      <div className="main">
        <Topbar />
        <Page key={app.route} />
      </div>
      <Toasts items={app.toasts} />
    </div>
  );
}

function LoginScreen() {
  const { login } = useApp();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (!username.trim() || !password) { setErr('请输入账号和密码'); return; }
    setBusy(true);
    setErr('');
    login(username.trim(), password).catch((ex) => { setErr(ex.message || '登录失败'); setBusy(false); });
  };

  const accounts = [
    ['finance', '财务部'],
    ['workshop', '生产车间'],
    ['supply', '供应部'],
  ];

  return (
    <div className="intro-wrap">
      <form className="intro" onSubmit={submit} style={{ width: 420, padding: '28px 30px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="rail-logo"><Ico name="sigma" size={13} /></span>
          <h1 style={{ margin: 0 }}>成本预测管理系统</h1>
        </div>
        <p className="lead">请使用本人账号登录。登录后只能看到和操作本部门的内容。</p>

        <label className="login-label">账号
          <input className="login-input" autoFocus value={username} placeholder="例如 finance"
            onChange={(e) => setUsername(e.target.value)} />
        </label>
        <label className="login-label">密码
          <input className="login-input" type="password" value={password} placeholder="初始密码 123456"
            onChange={(e) => setPassword(e.target.value)} />
        </label>
        {err && <div className="login-err">{err}</div>}

        <div className="intro-foot">
          <Btn kind="primary" size="lg" wide onClick={submit}>{busy ? '正在登录…' : '登录'}</Btn>
        </div>

        <div className="login-hint">
          {accounts.map(([u, dept]) => (
            <button type="button" key={u} onClick={() => { setUsername(u); setPassword('123456'); setErr(''); }}>
              <b>{dept}</b><code>{u}</code>
            </button>
          ))}
        </div>
      </form>
    </div>
  );
}

function LoginGate() {
  const { authed, authReady } = useApp();
  if (!authReady) return <div className="boot">正在确认登录状态…</div>;
  if (!authed) return <LoginScreen />;
  return <Shell />;
}

function App() {
  return <AppProvider><LoginGate /></AppProvider>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
Object.assign(window, { Shell, App, Rail, Topbar, UserBox, PAGES });
