/* ============================================
   USER MANAGEMENT — Roles & directory sync
   ============================================ */
const USERS = [
  { name: "Rio Pratama",       email: "rio.pratama@bjp-industries.id",    dept: "Maintenance · Line 3",    role: "Operator", status: "active",   lastSeen: "now",        sso: true },
  { name: "Anwar Santoso",     email: "anwar.santoso@bjp-industries.id",  dept: "Plant Operations",       role: "Operator", status: "active",   lastSeen: "12 min ago", sso: true },
  { name: "Maya Indrawan",     email: "maya.indrawan@bjp-industries.id",  dept: "Process Engineering",    role: "User",     status: "active",   lastSeen: "1 h ago",    sso: true },
  { name: "Surya Permana",     email: "surya.permana@bjp-industries.id",  dept: "Reliability",            role: "Operator", status: "active",   lastSeen: "today",      sso: true },
  { name: "Hadi Wijaya",       email: "hadi.wijaya@bjp-industries.id",    dept: "Quality Assurance",      role: "User",     status: "active",   lastSeen: "today",      sso: true },
  { name: "Dewi Lestari",      email: "dewi.lestari@bjp-industries.id",   dept: "Plant IT",               role: "Admin",    status: "active",   lastSeen: "now",        sso: true },
  { name: "Bayu Nugroho",      email: "bayu.nugroho@bjp-industries.id",   dept: "EHS / Safety",           role: "Admin",    status: "active",   lastSeen: "2 d ago",    sso: true },
  { name: "Tirta Anggoro",     email: "tirta.anggoro@bjp-industries.id",  dept: "Maintenance · Line 1",   role: "User",     status: "pending",  lastSeen: "—",          sso: false },
  { name: "Putri Sari",        email: "putri.sari@bjp-industries.id",     dept: "Process Engineering",    role: "User",     status: "active",   lastSeen: "3 d ago",    sso: true },
  { name: "Eko Saputra",       email: "eko.saputra@bjp-contractor.id",    dept: "External · Vendor",      role: "User",     status: "suspended",lastSeen: "21 d ago",   sso: false },
];

function UsersScreen() {
  const [users, setUsers] = useState(USERS);

  const updateRole = (email, role) => {
    setUsers(prev => prev.map(u => u.email === email ? { ...u, role } : u));
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">User Management</h1>
          <p className="page-subtitle">{users.filter(u => u.status === "active").length} active · {users.filter(u => u.status === "pending").length} pending · {users.filter(u => u.status === "suspended").length} suspended · last directory sync 14:00 today</p>
        </div>
        <div className="row">
          <button className="btn btn--ghost"><Icons.Download size={14} /> Export users</button>
          <button className="btn btn--secondary"><Icons.Plus size={14} /> Invite user</button>
          <button className="btn btn--primary"><Icons.Refresh size={14} /> Sync with Directory</button>
        </div>
      </div>

      {/* Roles legend */}
      <div className="grid-3" style={{ marginBottom: 16 }}>
        <RoleCard role="User" desc="Query, view citations, manage own chat history. Cannot edit knowledge base." count={users.filter(u => u.role === "User").length} icon={<Icons.User />} />
        <RoleCard role="Operator" desc="All User permissions + upload manuals, tag documents, view ingestion dashboard." count={users.filter(u => u.role === "Operator").length} icon={<Icons.Wrench />} />
        <RoleCard role="Admin" desc="Full system access: governance, prompt tuning, cost budgets, user roles, API keys." count={users.filter(u => u.role === "Admin").length} icon={<Icons.Settings />} />
      </div>

      <Card bodyFlush>
        <div style={{ padding: "10px 16px", borderBottom: "1px solid var(--ink-200)", display: "flex", gap: 10, alignItems: "center" }}>
          <div className="topbar__search" style={{ width: 280, background: "white" }}>
            <Icons.Search />
            <input placeholder="Search users by name or email…" />
          </div>
          <select className="select" style={{ width: 160 }}>
            <option>All departments</option>
            <option>Plant Operations</option>
            <option>Maintenance</option>
          </select>
          <select className="select" style={{ width: 140 }}>
            <option>All roles</option>
            <option>User</option>
            <option>Operator</option>
            <option>Admin</option>
          </select>
        </div>

        <table className="table">
          <thead>
            <tr>
              <th>User</th>
              <th>Department</th>
              <th style={{ width: 110 }}>Status</th>
              <th style={{ width: 90 }}>SSO</th>
              <th style={{ width: 160 }}>Role</th>
              <th style={{ width: 120 }}>Last Seen</th>
              <th style={{ width: 70 }}></th>
            </tr>
          </thead>
          <tbody>
            {users.map(u => (
              <tr key={u.email}>
                <td>
                  <div className="row gap-8">
                    <div style={{
                      width: 32, height: 32, borderRadius: "50%",
                      background: "var(--navy-50)",
                      color: "var(--navy-700)",
                      display: "grid", placeItems: "center",
                      fontWeight: 600, fontSize: 11,
                      flexShrink: 0,
                    }}>{u.name.split(" ").map(n => n[0]).join("").slice(0, 2)}</div>
                    <div>
                      <div className="doc-name">{u.name}</div>
                      <div className="mono text-xs muted">{u.email}</div>
                    </div>
                  </div>
                </td>
                <td className="text-sm">{u.dept}</td>
                <td>
                  {u.status === "active" && <Badge kind="complete">Active</Badge>}
                  {u.status === "pending" && <Badge kind="pending">Pending</Badge>}
                  {u.status === "suspended" && <Badge kind="failed">Suspended</Badge>}
                </td>
                <td>
                  {u.sso
                    ? <span className="badge badge--blue"><Icons.Lock size={11} />SSO</span>
                    : <span className="badge badge--neutral">Password</span>}
                </td>
                <td>
                  <select
                    className="select"
                    value={u.role}
                    onChange={e => updateRole(u.email, e.target.value)}
                    style={{ padding: "5px 10px", paddingRight: 26, fontSize: 12.5 }}
                  >
                    <option>User</option>
                    <option>Operator</option>
                    <option>Admin</option>
                  </select>
                </td>
                <td className="mono text-xs muted">{u.lastSeen}</td>
                <td><button className="btn btn--ghost btn--sm"><Icons.More /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
}

function RoleCard({ role, desc, count, icon }) {
  return (
    <div className="card" style={{ padding: 16 }}>
      <div className="row" style={{ marginBottom: 8 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 6,
          background: role === "Admin" ? "var(--orange-50)" : "var(--navy-50)",
          color: role === "Admin" ? "var(--orange-700)" : "var(--navy-700)",
          display: "grid", placeItems: "center",
        }}>{icon}</div>
        <div>
          <div style={{ fontWeight: 600, fontSize: 14 }}>{role}</div>
          <div className="text-xs muted">{count} member{count !== 1 ? "s" : ""}</div>
        </div>
        <span className="spacer" />
        <Badge kind={role === "Admin" ? "orange" : "blue"}>{role.toUpperCase()}</Badge>
      </div>
      <div className="text-xs" style={{ color: "var(--ink-600)", lineHeight: 1.55 }}>{desc}</div>
    </div>
  );
}

window.UsersScreen = UsersScreen;
