// Woodbury Operator — Users (super-admin onboarding & roles). Registers window.UsersScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, Avatar, StatCard, Input, Modal, Select, Checkbox, Switch } = NS;

  const ROLE_OPTS = ["Super Administrator", "Site Administrator", "Site Operator", "Leasing Agent"];

  function statusBadge(s) {
    if (s === "Active") return <Badge tone="success" dot>Active</Badge>;
    if (s === "Invited") return <Badge tone="warning">Invited</Badge>;
    return <Badge tone="danger">Suspended</Badge>;
  }

  function UsersScreen() {
    const [users, setUsers] = React.useState(window.WB_DATA.users);
    const [q, setQ] = React.useState("");
    const [modal, setModal] = React.useState(null); // 'invite' | user
    const [scopeAll, setScopeAll] = React.useState(false);
    const [manage2FA, setManage2FA] = React.useState(false);
    const close = () => setModal(null);
    const openManage = (u) => { setManage2FA(!!u.twoFA); setModal(u); };
    React.useEffect(() => { const f = window.WBFocus; if (f && f.kind === "user") { const u = users.find((x) => x.name === f.key); if (u) openManage(u); window.WBFocus = null; } }, []);
    const save2FA = (on) => {
      setManage2FA(on);
      setUsers((list) => list.map((x) => x.email === modal.email ? { ...x, twoFA: on } : x));
      window.WBToast(on ? "2FA required for " + modal.name : "2FA disabled for " + modal.name, on ? undefined : "danger");
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Access Control" title="Users & Roles"
          sub="Onboard team members, assign roles, and scope them to sites or the whole portfolio."
          actions={<Button variant="primary" icon="user-plus" onClick={() => setModal("invite")}>Invite User</Button>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Users")} label="Total Users" value={String(users.length)} icon="users" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Users")} label="Site Admins" value="1" icon="shield-check" iconTone="success" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Users")} label="Operators" value="2" icon="hard-hat" iconTone="accent" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Users")} label="Pending Invites" value="1" icon="mail" iconTone="sunken" />
        </div>

        {/* Role legend */}
        <Card style={{ padding: 24 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20 }}>
            {[
              { r: "Super Administrator", d: "National scope. Manages users & all sites.", i: "globe" },
              { r: "Site Administrator", d: "Runs one site: tenants, leases, screening.", i: "building-2" },
              { r: "Site Operator", d: "Maintenance & vendors at one site.", i: "wrench" },
              { r: "Leasing Agent", d: "Screening & leases across assigned sites.", i: "file-signature" },
            ].map((x) => (
              <div key={x.r} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span className="wb-ico" style={{ width: 18, height: 18, color: "var(--brand)" }}><i data-lucide={x.i}></i></span>
                  <span style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{x.r}</span>
                </div>
                <span style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.5 }}>{x.d}</span>
              </div>
            ))}
          </div>
        </Card>

        <Card>
          <CardHeader title="Team Members" action={<Input icon="search" placeholder="Search users..." size="sm" value={q} onChange={(e) => setQ(e.target.value)} containerStyle={{ width: 260 }} />} />
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1.1fr 1.1fr 0.6fr 0.7fr 0.6fr", padding: "14px 24px", borderBottom: "1px solid var(--border)" }}>
            {["Member", "Role", "Site Scope", "2FA", "Status", "Action"].map((h, i) => (
              <span key={h} style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)", textAlign: i === 5 ? "right" : "left" }}>{h}</span>
            ))}
          </div>
          {users.filter((u) => !q || (u.name + u.email + u.role + u.site).toLowerCase().includes(q.toLowerCase())).map((u, i) => (
            <div key={u.email} style={{ display: "grid", gridTemplateColumns: "1.4fr 1.1fr 1.1fr 0.6fr 0.7fr 0.6fr", alignItems: "center", padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={u.avatar} name={u.name} size={40} />
                <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{u.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{u.email}</div></div>
              </div>
              <span style={{ fontSize: 14, color: "var(--text-heading)" }}>{u.role}</span>
              <span style={{ fontSize: 14, color: "var(--text-body)" }}>{u.site}</span>
              <div>{u.twoFA
                ? <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: "var(--success)" }}><span className="wb-ico" style={{ width: 14, height: 14 }}><i data-lucide="shield-check"></i></span>On</span>
                : <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: "var(--text-muted)" }}><span className="wb-ico" style={{ width: 14, height: 14 }}><i data-lucide="shield-off"></i></span>Off</span>}
              </div>
              <div>{statusBadge(u.status)}</div>
              <div style={{ textAlign: "right" }}><Button variant="secondary" size="sm" onClick={() => openManage(u)}>Manage</Button></div>
            </div>
          ))}
          {users.filter((u) => !q || (u.name + u.email + u.role + u.site).toLowerCase().includes(q.toLowerCase())).length === 0 && <div style={{ padding: 32, textAlign: "center", color: "var(--text-muted)", fontSize: 14 }}>No users match “{q}”.</div>}
        </Card>

        {/* Invite user */}
        <Modal open={modal === "invite"} onClose={close} icon="user-plus" title="Invite User" subtitle="Onboard a team member and set their access."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="send" onClick={() => { close(); window.WBToast("Invitation sent"); }}>Send Invite</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Full name" placeholder="e.g. Adjoa Owusu" />
            <Input label="Work email" icon="mail" placeholder="name@woodbury.com" />
            <Select label="Role" options={ROLE_OPTS} />
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <Checkbox label="Grant access to all sites (national scope)" checked={scopeAll} onChange={setScopeAll} />
              {!scopeAll && <Select label="Assign to site(s)" options={window.WB_SITES} />}
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, paddingTop: 6 }}>
              <span style={{ fontSize: 14, color: "var(--text-body)" }}>Require two-factor authentication</span>
              <Switch defaultChecked />
            </div>
          </div>
        </Modal>

        {/* Manage user */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="user-cog" title={modal && modal.name} subtitle={modal && modal.email} width={520}
          footer={<React.Fragment>
            <Button variant="danger" onClick={async () => { const yes = await window.WBConfirm({ title: modal.status === "Suspended" ? "Reactivate user?" : "Suspend user?", message: (modal.status === "Suspended" ? "Restore access for " : "This revokes portal access for ") + modal.name + ".", confirmLabel: modal.status === "Suspended" ? "Reactivate" : "Suspend", danger: modal.status !== "Suspended" }); if (!yes) return; close(); window.WBToast(modal.status === "Suspended" ? "User reactivated" : "User suspended", "danger"); }}>{modal && modal.status === "Suspended" ? "Reactivate" : "Suspend"}</Button>
            <Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Access updated for " + modal.name); }}>Save Changes</Button>
          </React.Fragment>}>
          {modal && typeof modal === "object" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Select label="Role" defaultValue={modal.role} options={ROLE_OPTS} />
              <Select label="Site scope" defaultValue={modal.site} options={["All Ghana Locations", ...window.WB_SITES]} />
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--cream-50)", boxShadow: "inset 0 0 0 1px var(--border)" }}>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>Two-Factor Authentication</div>
                  <div style={{ fontSize: 12, color: "var(--text-muted)", maxWidth: 300, marginTop: 2 }}>Require a 6-digit code at sign-in for this user.</div>
                </div>
                <Switch checked={manage2FA} onChange={save2FA} />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderTop: "1px solid var(--border)" }}>
                <span style={{ fontSize: 13, color: "var(--text-muted)" }}>Current status</span>{statusBadge(modal.status)}
              </div>
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.UsersScreen = UsersScreen;
})();
