// CORE-05 · User management — list  (route: users)
// Admin list of all users with role + status.
const UsersListPage = ({ tweaks }) => {
  const Ic = window.Icons;
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.usersState) || "default";
  const loading = state === "loading";
  const firstRun = state === "empty";
  const forceNoResults = state === "noresults";

  const [search, setSearch] = useState("");
  const [roleF, setRoleF] = useState("all");
  const [sort, setSort] = useState({ key: "name", dir: "asc" });

  const ROLES = ["all", ...Array.from(new Set(window.MD.USERS.map(u => u.role)))];
  const STATUS_TONE = { active: "success", invited: "outline", deactivated: "destructive" };

  const rows = useMemo(() => {
    if (forceNoResults) return [];
    return window.MD.USERS.filter(u => {
      if (search && !`${u.name} ${u.email} ${u.role}`.toLowerCase().includes(search.toLowerCase())) return false;
      if (roleF !== "all" && u.role !== roleF) return false;
      return true;
    });
  }, [search, roleF, forceNoResults]);

  const counts = {
    total: window.MD.USERS.length,
    active: window.MD.USERS.filter(u => u.status === "active").length,
    invited: window.MD.USERS.filter(u => u.status === "invited").length,
  };

  if (firstRun) {
    return (
      <div className="page" style={{ maxWidth: 1280 }}>
        <div className="page-head"><div><h1 className="page-title">User management</h1><div className="page-sub">Invite teammates and assign roles</div></div></div>
        <Card><div style={{ padding: "64px 24px", textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
          <div style={{ width: 64, height: 64, borderRadius: 16, background: "var(--avocado-soft)", color: "var(--avocado-fg)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Ic.Users size={30}/></div>
          <div><div style={{ fontSize: 19, fontWeight: 600, letterSpacing: "-0.02em" }}>No users yet</div><div className="muted" style={{ fontSize: 13.5, maxWidth: 420, margin: "6px auto 0", lineHeight: 1.5 }}>Add your first teammate to get started. They'll receive an email invite to set their password.</div></div>
          <Button variant="primary" icon={Ic.UserPlus} onClick={()=> go("CORE-06.html")}>Add user</Button>
        </div></Card>
      </div>
    );
  }

  return (
    <div className="page" style={{ maxWidth: 1280 }}>
      <div className="page-head">
        <div><h1 className="page-title">User management</h1><div className="page-sub">{counts.total} users · {counts.active} active · {counts.invited} invited</div></div>
        <div className="page-actions">
          <Button variant="outline" icon={Ic.Shield} onClick={()=> go("CORE-08.html")}>Roles &amp; permissions</Button>
          <Button variant="primary" icon={Ic.UserPlus} onClick={()=> go("CORE-06.html")}>Add user</Button>
        </div>
      </div>

      <div className="proc-toolbar">
        <div className="proc-search"><Ic.Search size={15}/><input className="input" placeholder="Search name, email or role" value={search} onChange={(e)=> setSearch(e.target.value)}/></div>
        <div className="proc-chips">
          {ROLES.slice(0, 6).map(r => (
            <button key={r} className={`proc-chip${roleF === r ? " on" : ""}`} onClick={()=> setRoleF(r)}>{r === "all" ? "All roles" : r}</button>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
        <Button variant="outline" icon={Ic.Download} onClick={()=> toast({ title: "Export started", desc: `${rows.length} users → CSV` })}>Export</Button>
      </div>

      <Card>
        <div className="card-body flush">
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr><SortableTh label="User" col="name" sort={sort} setSort={setSort}/><SortableTh label="Role" col="role" sort={sort} setSort={setSort}/><SortableTh label="Status" col="status" sort={sort} setSort={setSort}/><SortableTh label="Last active" col="lastSeen" sort={sort} setSort={setSort}/><th className="actions"></th></tr></thead>
              {loading ? (
                <tbody>{Array.from({ length: 6 }).map((_, i) => (
                  <tr key={i}><td><div className="core-user-cell"><span className="core-sk" style={{ width: 32, height: 32, borderRadius: 9 }}/><div><div className="core-sk" style={{ width: 130 }}/><div className="core-sk" style={{ width: 90, marginTop: 6 }}/></div></div></td><td><div className="core-sk" style={{ width: 100 }}/></td><td><div className="core-sk" style={{ width: 60 }}/></td><td><div className="core-sk" style={{ width: 70 }}/></td><td></td></tr>
                ))}</tbody>
              ) : (
                <tbody>
                  {rows.length === 0 ? (
                    <tr><td colSpan={5}><div className="proc-inline-empty" style={{ justifyContent: "center" }}><Ic.Search size={20}/><div><div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--foreground)" }}>No users match your filters</div><div className="muted" style={{ fontSize: 12.5 }}>Try a different role or clear the search.</div></div><Button size="sm" variant="outline" onClick={()=> { setSearch(""); setRoleF("all"); }} style={{ marginLeft: 8 }}>Clear</Button></div></td></tr>
                  ) : sortRows(rows, sort).map(u => (
                    <tr key={u.email} className="proc-row" onClick={()=> go("CORE-07.html")}>
                      <td>
                        <div className="core-user-cell">
                          <Avatar initials={u.initials} size="sm"/>
                          <div><div style={{ fontSize: 13.5, fontWeight: 600 }}>{u.name}</div><div className="muted" style={{ fontSize: 12 }}>{u.email}</div></div>
                        </div>
                      </td>
                      <td><span style={{ fontSize: 13 }}>{u.role}</span></td>
                      <td><Badge tone={STATUS_TONE[u.status]}>{u.status === "active" ? "Active" : u.status === "invited" ? "Invite pending" : "Deactivated"}</Badge></td>
                      <td className="muted core-seen" style={{ fontSize: 12.5 }}>{u.lastSeen}</td>
                      <td className="actions"><button className="btn btn-ghost btn-icon btn-sm" onClick={(e)=> { e.stopPropagation(); go("CORE-07.html"); }} aria-label="Edit user"><Ic.Edit size={15}/></button></td>
                    </tr>
                  ))}
                </tbody>
              )}
            </table>
          </div>
        </div>
      </Card>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { users: UsersListPage });
