/* ===== pages-settings.jsx — /settings/users + /settings/thresholds ===== */
(function () {
  const { Icon, Button, IconBtn, Card, Badge, EmptyState, Input, Field, Avatar, Table,
    useStore, navigate, useRoute, cls, fmtDate, fmtRel } = window;

  function SettingsLayout({ children, mobile, active }) {
    const sub = [
      { id: 'users', label: '用户管理',     icon: Icon.users,    to: '/settings/users' },
      { id: 'thr',   label: '低库存阈值',   icon: Icon.settings, to: '/settings/thresholds' },
      { id: 'org',   label: '组织 / 仓库',  icon: Icon.building, to: '/settings/org', disabled: true },
      { id: 'lang',  label: '语言 / i18n',  icon: Icon.tag,      to: '/settings/lang', disabled: true },
      { id: 'api',   label: '集成 / API',   icon: Icon.layers,   to: '/settings/api', disabled: true },
    ];

    if (mobile) {
      return (
        <div className="p-3">
          <div className="mb-3">
            <h1 className="text-lg font-semibold">系统设置</h1>
          </div>
          <Card className="mb-3 divide-y divide-ink-100">
            {sub.map(s => (
              <button key={s.id} onClick={() => !s.disabled && navigate(s.to)}
                className={cls('w-full flex items-center gap-3 px-3 py-3 active:bg-ink-50',
                  s.disabled && 'opacity-40', active === s.id && 'bg-ink-50')}>
                <s.icon size={16} className="text-ink-500" />
                <span className="flex-1 text-left text-sm">{s.label}</span>
                {s.disabled && <Badge tone="neutral">即将上线</Badge>}
                <Icon.chevRight size={14} className="text-ink-300" />
              </button>
            ))}
          </Card>
          {children}
        </div>
      );
    }

    return (
      <div className="flex h-full">
        <aside className="w-56 shrink-0 bg-white border-r border-ink-100 p-3">
          <div className="px-2 py-2 mb-1">
            <h2 className="text-sm font-semibold">系统设置</h2>
            <p className="text-[11px] text-ink-500 mt-0.5">仅管理员可见</p>
          </div>
          {sub.map(s => (
            <button key={s.id} onClick={() => !s.disabled && navigate(s.to)}
              className={cls(
                'w-full flex items-center gap-2.5 rounded-md px-2.5 h-9 text-sm transition-colors my-0.5',
                active === s.id ? 'bg-ink-900 text-white font-medium'
                                : 'text-ink-700 hover:bg-ink-100',
                s.disabled && 'opacity-40 pointer-events-none'
              )}>
              <s.icon size={14} />
              <span className="flex-1 text-left">{s.label}</span>
              {s.disabled && <Badge tone="neutral" className={cls(active === s.id && 'opacity-80')}>WIP</Badge>}
            </button>
          ))}
        </aside>
        <div className="flex-1 overflow-y-auto">{children}</div>
      </div>
    );
  }

  /* ---------- Users ---------- */
  function SettingsUsers({ mobile }) {
    const store = useStore();
    const [editing, setEditing] = React.useState(null);

    const roles = [
      { id: 'admin',   label: '管理员',   tone: 'violet', desc: '所有权限 + 用户管理' },
      { id: 'manager', label: '操作员',   tone: 'blue',   desc: '录入数据 / 出入库 / 修改主数据' },
      { id: 'viewer',  label: '只读',     tone: 'neutral',desc: '仅查看，无操作权限' },
    ];

    const columns = [
      { header: '用户', cell: (u) => (
        <div className="flex items-center gap-3">
          <Avatar name={u.avatar} size={36} />
          <div>
            <div className="text-sm font-medium">{u.name}</div>
            <div className="text-xs text-ink-500">{u.email}</div>
          </div>
        </div>
      )},
      { header: '角色', cell: (u) => {
        const r = roles.find(r => r.id === u.role);
        return <Badge tone={r?.tone}>{r?.label}</Badge>;
      }},
      { header: '状态', cell: (u) => u.active
        ? <Badge tone="green" dot="bg-emerald-500">活跃</Badge>
        : <Badge tone="zinc">停用</Badge>
      },
      { header: '最近登录', cell: (u) => (
        <div>
          <div className="text-xs font-mono">{fmtDate(u.last_login)}</div>
          <div className="text-[11px] text-ink-500">{fmtRel(u.last_login)}</div>
        </div>
      )},
      { header: '', width: 60, cell: (u) => (
        <div className="flex gap-1">
          <IconBtn icon={Icon.edit} label="编辑" onClick={(e) => { e.stopPropagation(); setEditing(u); }} />
          <IconBtn icon={Icon.moreH} label="更多" />
        </div>
      )},
    ];

    return (
      <SettingsLayout mobile={mobile} active="users">
        <div className={cls(mobile ? '' : 'p-6')}>
          <div className="flex items-start justify-between gap-3 mb-5">
            <div>
              <h1 className={cls('font-semibold tracking-tight', mobile ? 'text-lg' : 'text-xl')}>用户管理</h1>
              <p className="text-xs text-ink-500 mt-1">{store.users.length} 个账户 · {store.users.filter(u=>u.active).length} 活跃</p>
            </div>
            <Button size="sm" icon={Icon.plus}>新建用户</Button>
          </div>

          {/* Role legend */}
          <div className="grid md:grid-cols-3 gap-3 mb-5">
            {roles.map(r => (
              <Card key={r.id} className="p-3.5">
                <div className="flex items-center gap-2 mb-1">
                  <Badge tone={r.tone}>{r.label}</Badge>
                  <span className="text-xs text-ink-500 font-mono">{store.users.filter(u=>u.role===r.id).length} 人</span>
                </div>
                <div className="text-xs text-ink-600">{r.desc}</div>
              </Card>
            ))}
          </div>

          <Card className="overflow-hidden">
            <Table columns={columns} rows={store.users} onRow={(u) => setEditing(u)} />
          </Card>
        </div>

        <window.Modal open={!!editing} onClose={() => setEditing(null)} size="md" title={editing && `编辑 · ${editing.name}`}
          footer={
            <>
              <Button variant="ghost" size="sm" onClick={() => setEditing(null)}>取消</Button>
              <Button size="sm" onClick={() => { store.toast('已更新用户'); setEditing(null); }}>保存</Button>
            </>
          }>
          {editing && (
            <div className="grid gap-4">
              <div className="flex items-center gap-3 pb-3 border-b border-ink-100">
                <Avatar name={editing.avatar} size={48} />
                <div>
                  <div className="font-medium">{editing.name}</div>
                  <div className="text-xs text-ink-500">{editing.email}</div>
                </div>
              </div>
              <Field label="角色">
                <div className="flex flex-col gap-1.5">
                  {roles.map(r => (
                    <label key={r.id} className={cls('flex items-start gap-2 px-3 py-2 rounded-md ring-1 cursor-pointer hover:bg-ink-50',
                      editing.role === r.id ? 'ring-ink-900 bg-ink-50' : 'ring-ink-200')}>
                      <input type="radio" checked={editing.role === r.id} onChange={() => setEditing({ ...editing, role: r.id })} className="mt-0.5" />
                      <div className="flex-1">
                        <div className="text-sm font-medium">{r.label}</div>
                        <div className="text-[11px] text-ink-500">{r.desc}</div>
                      </div>
                    </label>
                  ))}
                </div>
              </Field>
              <Field label="状态">
                <label className="flex items-center gap-2 text-sm">
                  <input type="checkbox" checked={editing.active}
                    onChange={(e) => setEditing({ ...editing, active: e.target.checked })}
                    className="rounded ring-1 ring-ink-300" />
                  允许登录
                </label>
              </Field>
            </div>
          )}
        </window.Modal>
      </SettingsLayout>
    );
  }

  /* ---------- Thresholds (batch config) ---------- */
  function SettingsThresholds({ mobile }) {
    const store = useStore();
    const [edits, setEdits] = React.useState({});
    const [dirty, setDirty] = React.useState(false);

    const handle = (id, v) => {
      setEdits({ ...edits, [id]: v === '' ? '' : parseInt(v) || 0 });
      setDirty(true);
    };
    const reset = () => { setEdits({}); setDirty(false); };
    const save = () => {
      for (const id in edits) {
        store.update('reagent_products', id, { low_threshold: edits[id] });
      }
      store.toast(`已保存 ${Object.keys(edits).length} 个阈值`);
      setEdits({}); setDirty(false);
    };

    const products = store.reagent_products;

    return (
      <SettingsLayout mobile={mobile} active="thr">
        <div className={cls(mobile ? '' : 'p-6')}>
          <div className="flex items-start justify-between gap-3 mb-5">
            <div>
              <h1 className={cls('font-semibold tracking-tight', mobile ? 'text-lg' : 'text-xl')}>低库存阈值</h1>
              <p className="text-xs text-ink-500 mt-1">
                库存低于阈值时触发 🟡 报警 · 按产品配置，单位是「盒」
              </p>
            </div>
            {dirty && (
              <div className="flex items-center gap-2">
                <Button variant="ghost" size="sm" onClick={reset}>重置</Button>
                <Button size="sm" icon={Icon.check} onClick={save}>
                  保存 {Object.keys(edits).length} 项
                </Button>
              </div>
            )}
          </div>

          {/* Bulk presets */}
          <Card className="p-4 mb-4 bg-ink-50/40 ring-ink-200">
            <div className="flex items-center justify-between flex-wrap gap-2">
              <div className="text-sm">
                <span className="font-medium">批量预设</span>
                <span className="text-xs text-ink-500 ml-2">为所有产品一键设置</span>
              </div>
              <div className="flex gap-1.5">
                {[
                  { label: '保守 (×2 月销)', v: (p) => 6 },
                  { label: '标准 (×1 月销)', v: (p) => 3 },
                  { label: '紧凑 (×0.5)',    v: (p) => 2 },
                ].map(preset => (
                  <Button key={preset.label} variant="secondary" size="sm"
                    onClick={() => {
                      const next = {};
                      for (const p of products) next[p.id] = preset.v(p);
                      setEdits(next); setDirty(true);
                    }}>{preset.label}</Button>
                ))}
              </div>
            </div>
          </Card>

          <Card className="overflow-hidden">
            <Table
              columns={[
                { header: '产品', cell: (p) => (
                  <div>
                    <div className="text-sm font-medium">{p.name}</div>
                    <div className="text-xs text-ink-500 font-mono">{p.code}</div>
                  </div>
                )},
                { header: '当前在库', align: 'right', cell: (p) => {
                  const total = store.reagent_batches.filter(b => b.product_id === p.id).reduce((a, b) => a + b.on_hand_boxes, 0);
                  return <span className={cls('font-mono text-sm', total <= (edits[p.id] ?? p.low_threshold) && 'text-amber-700 font-semibold')}>
                    {total} 盒
                  </span>;
                }},
                { header: '当前阈值', align: 'right', cell: (p) => (
                  <span className="font-mono text-sm text-ink-500">≤ {p.low_threshold}</span>
                )},
                { header: '新阈值', align: 'right', cell: (p) => {
                  const val = edits[p.id] ?? p.low_threshold;
                  return (
                    <div className="flex justify-end">
                      <div className="inline-flex items-center bg-white ring-1 ring-ink-200 rounded-md">
                        <button onClick={(e) => { e.stopPropagation(); handle(p.id, Math.max(0, val - 1)); }}
                          className="h-8 w-7 text-ink-500 hover:bg-ink-100">−</button>
                        <input type="number" value={val} onChange={(e) => handle(p.id, e.target.value)}
                          onClick={(e) => e.stopPropagation()}
                          className={cls('h-8 w-12 text-center font-mono text-sm focus:outline-none',
                            edits[p.id] != null && edits[p.id] !== p.low_threshold ? 'text-emerald-700 font-medium bg-emerald-50' : '')} />
                        <button onClick={(e) => { e.stopPropagation(); handle(p.id, val + 1); }}
                          className="h-8 w-7 text-ink-500 hover:bg-ink-100">+</button>
                      </div>
                    </div>
                  );
                }},
                { header: '状态', cell: (p) => {
                  const val = edits[p.id] ?? p.low_threshold;
                  const total = store.reagent_batches.filter(b => b.product_id === p.id).reduce((a, b) => a + b.on_hand_boxes, 0);
                  if (total <= val) return <Badge tone="amber">🟡 当前会触发</Badge>;
                  if (total <= val * 1.5) return <Badge tone="neutral">接近</Badge>;
                  return <span className="text-[11px] text-ink-400">正常</span>;
                }},
              ]}
              rows={products}
            />
          </Card>

          <Card className="p-4 mt-4">
            <h3 className="text-sm font-semibold mb-2">关于「低库存」</h3>
            <ul className="text-xs text-ink-600 space-y-1.5 list-disc list-inside">
              <li>规则：所有批次的剩余「盒」数 ≤ 阈值，即触发 🟡 LOW_STOCK 报警。</li>
              <li>修改阈值后，下一次自动评估周期（每 15 分钟）会重算报警；点「保存」后立即生效。</li>
              <li>建议根据月平均消耗 × 1.5 设置阈值，避免补给来不及到货。</li>
            </ul>
          </Card>
        </div>
      </SettingsLayout>
    );
  }

  Object.assign(window, { SettingsUsers, SettingsThresholds, SettingsLayout });
})();
