// ===== User Management Screen =====

const UserAdminScreen = ({ onBack, currentUserId }) => {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState("");
  const [inviteEmail, setInviteEmail] = React.useState("");
  const [inviting, setInviting] = React.useState(false);
  const [inviteMsg, setInviteMsg] = React.useState(null); // { text, ok }
  const [showInvite, setShowInvite] = React.useState(false);
  const [actionState, setActionState] = React.useState({}); // { [userId]: "loading"|"done"|"error" }
  const [confirmDelete, setConfirmDelete] = React.useState(null); // userId to confirm
  const [resetLinks, setResetLinks] = React.useState({}); // { [userId]: link }

  const authFetch = React.useCallback(async (url, opts = {}) => {
    const token = await window.MEI_AUTH.getAccessToken().catch(() => null);
    const headers = { "content-type": "application/json", ...(opts.headers || {}) };
    if (token) headers["Authorization"] = `Bearer ${token}`;
    return fetch(url, { ...opts, headers });
  }, []);

  const loadUsers = React.useCallback(async () => {
    setLoading(true); setErr("");
    try {
      const res = await authFetch("/api/admin/users");
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || `HTTP ${res.status}`);
      }
      const data = await res.json();
      // Sort: confirmed first, then by created_at desc
      const sorted = [...(data.users || [])].sort((a, b) => {
        if (!!a.email_confirmed_at !== !!b.email_confirmed_at)
          return a.email_confirmed_at ? -1 : 1;
        return new Date(b.created_at) - new Date(a.created_at);
      });
      setUsers(sorted);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  }, [authFetch]);

  React.useEffect(() => { loadUsers(); }, [loadUsers]);

  const handleInvite = async (e) => {
    e.preventDefault();
    if (!inviteEmail.includes("@")) return;
    setInviting(true); setInviteMsg(null);
    try {
      const res = await authFetch("/api/admin/users", {
        method: "POST",
        body: JSON.stringify({ email: inviteEmail, redirectTo: window.location.origin }),
      });
      const d = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(d.error || "Failed to invite");
      setInviteMsg({ text: `✓ ส่ง Invite ไปที่ ${inviteEmail} แล้ว`, ok: true });
      setInviteEmail("");
      await loadUsers();
    } catch (e) {
      setInviteMsg({ text: e.message, ok: false });
    } finally {
      setInviting(false);
    }
  };

  const handleDelete = async (userId) => {
    setConfirmDelete(null);
    setActionState(s => ({ ...s, [userId]: "loading" }));
    try {
      const res = await authFetch(`/api/admin/users/${userId}`, { method: "DELETE" });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || "Failed to delete");
      }
      setUsers(u => u.filter(x => x.id !== userId));
      setActionState(s => ({ ...s, [userId]: "done" }));
    } catch (e) {
      setActionState(s => ({ ...s, [userId]: "error_" + e.message }));
    }
  };

  const handleSetRole = async (u, newRole) => {
    setActionState(s => ({ ...s, [u.id]: "loading" }));
    try {
      const res = await authFetch(`/api/admin/users/${u.id}`, {
        method: "PATCH",
        body: JSON.stringify({ role: newRole }),
      });
      const d = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(d.error || "Failed");
      setUsers(list => list.map(x => x.id === u.id
        ? { ...x, app_metadata: { ...(x.app_metadata || {}), role: newRole } }
        : x));
      setActionState(s => ({ ...s, [u.id]: "role_done" }));
      setTimeout(() => setActionState(s => ({ ...s, [u.id]: null })), 1500);
    } catch (e) {
      setActionState(s => ({ ...s, [u.id]: "error_" + e.message }));
    }
  };

  const handleResetPassword = async (u) => {
    setActionState(s => ({ ...s, [u.id]: "loading" }));
    try {
      const res = await authFetch(`/api/admin/users/${u.id}`, {
        method: "POST",
        body: JSON.stringify({ email: u.email, redirectTo: window.location.origin }),
      });
      const d = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(d.error || "Failed");
      if (d.link) {
        setResetLinks(r => ({ ...r, [u.id]: d.link }));
      }
      setActionState(s => ({ ...s, [u.id]: "reset_done" }));
    } catch (e) {
      setActionState(s => ({ ...s, [u.id]: "error_" + e.message }));
    }
  };

  const fmtDate = (iso) => {
    if (!iso) return "—";
    const d = new Date(iso);
    return d.toLocaleDateString("th-TH", { day: "numeric", month: "short", year: "2-digit" }) +
      " " + d.toLocaleTimeString("th-TH", { hour: "2-digit", minute: "2-digit" });
  };

  const initials = (email) => (email || "?").slice(0, 2).toUpperCase();
  const colorFor = (email) => {
    const colors = ["#7c5cff","#00d4a8","#ff5d8f","#ffc94d","#4ec3ff","#ff8a4c"];
    let h = 0; for (const c of (email || "")) h = (h * 31 + c.charCodeAt(0)) & 0xffff;
    return colors[h % colors.length];
  };

  return (
    <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>

      {/* Header */}
      <header style={{
        padding: "0 32px", height: 64, display: "flex", alignItems: "center",
        gap: 16, borderBottom: "1px solid var(--border)",
        background: "var(--bg-card)", position: "sticky", top: 0, zIndex: 50,
      }}>
        <button className="btn btn-ghost btn-sm" onClick={onBack} style={{ gap: 6 }}>
          <Icon name="chevron-l" size={14} /> กลับ
        </button>
        <div style={{ width: 1, height: 20, background: "var(--border)" }} />
        <div className="row gap-8" style={{ fontSize: 15, fontWeight: 600 }}>
          <Icon name="users" size={16} color="var(--teal)" /> จัดการผู้ใช้งาน
        </div>
        <div className="spacer" />
        <button className="btn btn-primary btn-sm shine" onClick={() => { setShowInvite(v => !v); setInviteMsg(null); }}>
          <Icon name="user-plus" size={14} /> เชิญผู้ใช้ใหม่
        </button>
        <button className="btn btn-ghost btn-sm" onClick={loadUsers} disabled={loading}>
          <Icon name="refresh" size={14} />
        </button>
      </header>

      <div style={{ padding: "24px 32px", flex: 1 }}>

        {/* Invite form */}
        {showInvite && (
          <div className="glass page-enter" style={{ padding: "20px 24px", marginBottom: 20, borderRadius: 14 }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 14 }}>
              <Icon name="mail" size={14} color="var(--teal)" style={{ marginRight: 8 }} />
              เชิญผู้ใช้ใหม่เข้าระบบ
            </div>
            <form onSubmit={handleInvite} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <div style={{ position: "relative", flex: 1 }}>
                <Icon name="mail" size={15} color="var(--text-faint)"
                  style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }} />
                <input className="input" type="email" placeholder="email@company.co.th"
                  value={inviteEmail} onChange={e => { setInviteEmail(e.target.value); setInviteMsg(null); }}
                  style={{ paddingLeft: 38 }} autoFocus />
              </div>
              <button type="submit" className="btn btn-primary shine"
                disabled={inviting || !inviteEmail.includes("@")}
                style={{ height: 40, paddingInline: 20, whiteSpace: "nowrap" }}>
                {inviting ? <><span className="live-dot" /> กำลังส่ง…</> : <>ส่ง Invite <Icon name="mail" size={14} /></>}
              </button>
            </form>
            {inviteMsg && (
              <div style={{
                marginTop: 10, fontSize: 13, padding: "8px 12px", borderRadius: 8,
                background: inviteMsg.ok ? "rgba(0,212,168,0.1)" : "rgba(255,93,143,0.1)",
                color: inviteMsg.ok ? "var(--teal)" : "var(--pink)",
                border: `1px solid ${inviteMsg.ok ? "rgba(0,212,168,0.3)" : "rgba(255,93,143,0.3)"}`,
              }}>{inviteMsg.text}</div>
            )}
            <div className="faint" style={{ fontSize: 12, marginTop: 10 }}>
              ระบบจะส่งอีเมลเชิญให้ผู้ใช้ใหม่ตั้งรหัสผ่านและเข้าใช้งานได้ทันที
            </div>
          </div>
        )}

        {/* Setup needed — Service key missing */}
        {err && err.includes("SUPABASE_SERVICE_KEY") && (
          <div className="glass page-enter" style={{ padding: 32, borderRadius: 16, marginBottom: 20 }}>
            <div style={{ textAlign: "center", marginBottom: 24 }}>
              <div style={{
                width: 64, height: 64, borderRadius: "50%", margin: "0 auto 16px",
                background: "rgba(255,201,77,0.15)", border: "2px solid rgba(255,201,77,0.4)",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <Icon name="lock" size={28} color="var(--yellow)" />
              </div>
              <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 6 }}>
                ต้องตั้งค่า Service Role Key ก่อนใช้งาน
              </div>
              <div className="muted" style={{ fontSize: 13.5, maxWidth: 540, margin: "0 auto", lineHeight: 1.6 }}>
                การจัดการผู้ใช้งานต้องใช้สิทธิ์ admin ของ Supabase
                จึงต้องเพิ่ม Service Role Key เป็น secret ใน Cloudflare Pages (ทำครั้งเดียว)
              </div>
            </div>

            {/* Steps */}
            <div style={{ maxWidth: 680, margin: "0 auto", display: "flex", flexDirection: "column", gap: 14 }}>

              {/* Step 1 */}
              <div style={{
                padding: 18, borderRadius: 12,
                background: "rgba(255,255,255,0.03)",
                border: "1px solid var(--border)",
              }}>
                <div className="row gap-10" style={{ marginBottom: 10 }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: "50%",
                    background: "var(--teal)", color: "#0a0e1a",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 13, fontWeight: 700, flexShrink: 0,
                  }}>1</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>คัดลอก Service Role Key จาก Supabase</div>
                </div>
                <div style={{ paddingLeft: 36, fontSize: 13, lineHeight: 1.7 }}>
                  เปิด <a href="https://supabase.com/dashboard/project/rqakqbizzytqrczfrnpq/settings/api"
                    target="_blank" rel="noreferrer"
                    style={{ color: "var(--teal)", textDecoration: "underline" }}>
                    Supabase → Project Settings → API ↗
                  </a>
                  <br/>
                  ในส่วน <strong>Project API keys</strong> → กดปุ่ม <strong>Reveal</strong> ที่ <code style={{
                    padding: "2px 8px", borderRadius: 4, background: "rgba(255,93,143,0.15)",
                    color: "var(--pink)", fontFamily: "monospace", fontSize: 12.5,
                  }}>service_role</code> แล้ว <strong>คัดลอก</strong>
                  <div className="faint" style={{ fontSize: 12, marginTop: 6 }}>
                    ⚠️ Service Role Key เป็น key ลับ — ห้ามแชร์หรือใส่ในโค้ดที่ commit ขึ้น git
                  </div>
                </div>
              </div>

              {/* Step 2 */}
              <div style={{
                padding: 18, borderRadius: 12,
                background: "rgba(255,255,255,0.03)",
                border: "1px solid var(--border)",
              }}>
                <div className="row gap-10" style={{ marginBottom: 12 }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: "50%",
                    background: "var(--teal)", color: "#0a0e1a",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 13, fontWeight: 700, flexShrink: 0,
                  }}>2</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>เพิ่มเป็น Secret ใน Cloudflare Pages</div>
                </div>

                <div style={{ paddingLeft: 36, fontSize: 13, lineHeight: 1.6 }}>
                  เลือกวิธีใดก็ได้:
                </div>

                {/* Method A: Dashboard */}
                <div style={{ paddingLeft: 36, marginTop: 10 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--teal)", marginBottom: 4 }}>
                    วิธี A — ผ่าน Cloudflare Dashboard (ง่ายสุด)
                  </div>
                  <div style={{ fontSize: 12.5, lineHeight: 1.7, paddingLeft: 4 }}>
                    เปิด <a href="https://dash.cloudflare.com/?to=/:account/pages/view/myempinfo/settings/environment-variables"
                      target="_blank" rel="noreferrer"
                      style={{ color: "var(--teal)", textDecoration: "underline" }}>
                      Cloudflare → Pages → myempinfo → Settings → Environment Variables ↗
                    </a>
                    <br/>
                    → กด <strong>Add variable</strong> ใต้หัวข้อ <strong>Production</strong> และ <strong>Preview</strong>
                    <br/>
                    → ชื่อตัวแปร: <code style={{
                      padding: "2px 6px", borderRadius: 4, background: "rgba(0,0,0,0.3)",
                      fontFamily: "monospace", fontSize: 12,
                    }}>SUPABASE_SERVICE_KEY</code>
                    <br/>
                    → ค่า: paste Service Role Key
                    <br/>
                    → ติ๊กช่อง <strong>Encrypt</strong> 🔒 → กด <strong>Save</strong>
                  </div>
                </div>

                {/* Method B: CLI */}
                <div style={{ paddingLeft: 36, marginTop: 14 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--blue)", marginBottom: 4 }}>
                    วิธี B — ผ่าน Wrangler CLI (Terminal)
                  </div>
                  <div style={{ fontSize: 12.5, lineHeight: 1.7, paddingLeft: 4 }}>
                    รันคำสั่งใน terminal ที่โฟลเดอร์โปรเจ็ค:
                  </div>
                  <code style={{
                    display: "block", marginTop: 6, padding: "10px 14px", borderRadius: 8,
                    background: "rgba(0,0,0,0.35)", border: "1px solid var(--border)",
                    fontFamily: "monospace", fontSize: 12.5, color: "var(--text)",
                    marginLeft: 4,
                  }}>
                    npx wrangler pages secret put SUPABASE_SERVICE_KEY
                  </code>
                  <div className="faint" style={{ fontSize: 11.5, marginTop: 6, paddingLeft: 4 }}>
                    เมื่อ prompt ขึ้น ให้ paste key แล้วกด Enter
                  </div>
                </div>
              </div>

              {/* Step 3 */}
              <div style={{
                padding: 18, borderRadius: 12,
                background: "rgba(0,212,168,0.06)",
                border: "1px solid rgba(0,212,168,0.3)",
              }}>
                <div className="row gap-10" style={{ marginBottom: 8 }}>
                  <div style={{
                    width: 26, height: 26, borderRadius: "50%",
                    background: "var(--teal)", color: "#0a0e1a",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 13, fontWeight: 700, flexShrink: 0,
                  }}>3</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>รอ 30 วินาที แล้วลองใหม่</div>
                </div>
                <div style={{ paddingLeft: 36, fontSize: 12.5, lineHeight: 1.6, marginBottom: 12 }}>
                  Cloudflare Pages จะ deploy ค่าใหม่อัตโนมัติ (ใช้เวลา ~30 วินาที)
                  จากนั้นกดปุ่มข้างล่างนี้
                </div>
                <div style={{ paddingLeft: 36 }}>
                  <button className="btn btn-primary btn-sm shine" onClick={loadUsers} disabled={loading}>
                    {loading ? <><span className="live-dot" /> กำลังตรวจสอบ…</> : <><Icon name="refresh" size={13} /> ลองใหม่อีกครั้ง</>}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Other errors */}
        {err && !err.includes("SUPABASE_SERVICE_KEY") && (
          <div style={{
            padding: "14px 18px", borderRadius: 12, marginBottom: 20,
            background: "rgba(255,93,143,0.1)", border: "1px solid rgba(255,93,143,0.3)",
            fontSize: 13, color: "var(--pink)",
          }}>
            <strong>เกิดข้อผิดพลาด:</strong> {err}
          </div>
        )}

        {/* Loading */}
        {loading && (
          <div style={{ textAlign: "center", padding: "48px 0" }}>
            <div style={{
              width: 36, height: 36, borderRadius: "50%", margin: "0 auto 12px",
              border: "3px solid rgba(255,255,255,0.1)", borderTopColor: "var(--teal)",
              animation: "spin 0.9s linear infinite",
            }} />
            <div className="faint" style={{ fontSize: 13 }}>กำลังโหลดข้อมูล…</div>
          </div>
        )}

        {/* Users table */}
        {!loading && !err && (
          <div className="glass" style={{ borderRadius: 14, overflow: "hidden" }}>
            {/* Table header */}
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 100px 120px 150px 230px",
              padding: "10px 20px", borderBottom: "1px solid var(--border)",
              background: "rgba(255,255,255,0.03)",
            }}>
              {["ผู้ใช้งาน", "สิทธิ์", "สถานะ", "เข้าระบบล่าสุด", ""].map((h, i) => (
                <div key={i} className="faint" style={{ fontSize: 11.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5 }}>
                  {h}
                </div>
              ))}
            </div>

            {/* Rows */}
            {users.length === 0 && (
              <div className="faint" style={{ textAlign: "center", padding: "32px 0", fontSize: 13 }}>
                ไม่พบผู้ใช้งาน
              </div>
            )}
            {users.map((u, idx) => {
              const isConfirmed = !!u.email_confirmed_at;
              const state = actionState[u.id];
              const isActing = state === "loading";
              const resetDone = state === "reset_done";
              const roleDone = state === "role_done";
              const color = colorFor(u.email);
              const resetLink = resetLinks[u.id];
              const isUserAdmin = u.app_metadata?.role === "admin";
              const isSelf = currentUserId && u.id === currentUserId;

              return (
                <div key={u.id}>
                  <div style={{
                    display: "grid", gridTemplateColumns: "1fr 100px 120px 150px 230px",
                    padding: "14px 20px", alignItems: "center",
                    borderBottom: idx < users.length - 1 ? "1px solid var(--border)" : "none",
                    transition: "background .12s",
                  }}
                    onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.025)"}
                    onMouseLeave={e => e.currentTarget.style.background = "transparent"}
                  >
                    {/* User info */}
                    <div className="row gap-12">
                      <div style={{
                        width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                        background: color + "22", border: `1px solid ${color}44`,
                        display: "flex", alignItems: "center", justifyContent: "center",
                        fontSize: 13, fontWeight: 700, color,
                      }}>{initials(u.email)}</div>
                      <div className="col gap-2">
                        <div className="row gap-6" style={{ alignItems: "center" }}>
                          <div style={{ fontSize: 13.5, fontWeight: 500 }}>{u.email}</div>
                          {isSelf && <span className="faint" style={{ fontSize: 10.5 }}>(คุณ)</span>}
                        </div>
                        <div className="faint" style={{ fontSize: 11.5, fontFamily: "monospace" }}>
                          {u.id?.slice(0, 8)}…
                        </div>
                      </div>
                    </div>

                    {/* Role */}
                    <div>
                      {(() => {
                        const r = u.app_metadata?.role;
                        if (r === "admin") return <span className="chip" style={{
                          padding: "3px 9px", fontSize: 11,
                          background: "rgba(124,92,255,0.18)", color: "#a48cff",
                          border: "1px solid rgba(124,92,255,0.4)",
                        }}>👑 Admin</span>;
                        if (r === "hr" || r === "hr_staff") return <span className="chip" style={{
                          padding: "3px 9px", fontSize: 11,
                          background: "rgba(0,212,168,0.18)", color: "var(--teal)",
                          border: "1px solid rgba(0,212,168,0.4)",
                        }}>🛠 HR Staff</span>;
                        return <span className="faint" style={{ fontSize: 11.5 }}>User</span>;
                      })()}
                    </div>

                    {/* Status */}
                    <div>
                      {isConfirmed ? (
                        <span className="chip chip-teal" style={{ padding: "3px 9px", fontSize: 11 }}>✓ ยืนยันแล้ว</span>
                      ) : (
                        <span className="chip" style={{ padding: "3px 9px", fontSize: 11, opacity: 0.7 }}>รอยืนยัน</span>
                      )}
                    </div>

                    {/* Last sign in */}
                    <div className="faint" style={{ fontSize: 12 }}>
                      {u.last_sign_in_at ? fmtDate(u.last_sign_in_at) : "ยังไม่เคยเข้า"}
                    </div>

                    {/* Actions */}
                    <div className="row gap-6" style={{ justifyContent: "flex-end" }}>
                      {confirmDelete === u.id ? (
                        <>
                          <span className="faint" style={{ fontSize: 12 }}>ยืนยันลบ?</span>
                          <button className="btn btn-sm" style={{
                            background: "rgba(255,93,143,0.15)", color: "var(--pink)",
                            border: "1px solid rgba(255,93,143,0.4)", padding: "4px 12px",
                          }} onClick={() => handleDelete(u.id)}>ลบ</button>
                          <button className="btn btn-ghost btn-sm" onClick={() => setConfirmDelete(null)}>ยกเลิก</button>
                        </>
                      ) : roleDone ? (
                        <span style={{ fontSize: 12, color: "var(--teal)" }}>✓ บันทึกแล้ว</span>
                      ) : (
                        <>
                          {/* Role selector */}
                          <select
                            className="input"
                            value={u.app_metadata?.role || "user"}
                            disabled={isActing || (isSelf && isUserAdmin)}
                            onChange={(e) => handleSetRole(u, e.target.value)}
                            title={isSelf && isUserAdmin ? "ไม่สามารถเปลี่ยน role ของตัวเองได้" : "เปลี่ยน role"}
                            style={{ padding: "4px 8px", fontSize: 11.5, height: 28, width: 105 }}
                          >
                            <option value="user">User</option>
                            <option value="hr">HR Staff</option>
                            <option value="admin">Admin</option>
                          </select>

                          {/* Reset password */}
                          {resetDone ? (
                            <span style={{ fontSize: 11.5, color: "var(--teal)" }}>✓ ส่งแล้ว</span>
                          ) : (
                            <button className="btn btn-ghost btn-sm" style={{ fontSize: 11.5 }}
                              disabled={isActing}
                              onClick={() => handleResetPassword(u)}
                              title="ส่งลิงก์รีเซ็ตรหัสผ่าน">
                              <Icon name="lock" size={13} />
                            </button>
                          )}

                          {/* Delete */}
                          <button className="btn btn-ghost btn-sm" style={{ fontSize: 11.5, color: "var(--pink)" }}
                            disabled={isActing || isSelf}
                            onClick={() => setConfirmDelete(u.id)}
                            title={isSelf ? "ไม่สามารถลบบัญชีตัวเองได้" : "ลบผู้ใช้"}>
                            <Icon name="trash" size={13} />
                          </button>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Reset link (if returned) */}
                  {resetLink && (
                    <div style={{
                      margin: "0 20px 12px", padding: "10px 14px", borderRadius: 8,
                      background: "rgba(0,212,168,0.08)", border: "1px solid rgba(0,212,168,0.25)",
                      fontSize: 12,
                    }}>
                      <div style={{ fontWeight: 600, color: "var(--teal)", marginBottom: 6 }}>
                        🔗 ลิงก์รีเซ็ตรหัสผ่าน (ใช้ได้ครั้งเดียว):
                      </div>
                      <div style={{
                        fontFamily: "monospace", wordBreak: "break-all",
                        padding: "6px 10px", borderRadius: 6,
                        background: "rgba(0,0,0,0.2)", cursor: "pointer",
                      }} onClick={() => { navigator.clipboard.writeText(resetLink); }}
                        title="คลิกเพื่อคัดลอก">
                        {resetLink}
                      </div>
                      <div className="faint" style={{ marginTop: 4 }}>คลิกที่ลิงก์เพื่อคัดลอก แล้วส่งให้ผู้ใช้ด้วยตนเอง</div>
                    </div>
                  )}
                </div>
              );
            })}

            {/* Footer count */}
            {users.length > 0 && (
              <div className="faint" style={{
                padding: "10px 20px", fontSize: 12,
                borderTop: "1px solid var(--border)",
                background: "rgba(255,255,255,0.02)",
              }}>
                ทั้งหมด {users.length} บัญชี · ยืนยันแล้ว {users.filter(u => u.email_confirmed_at).length} · Admin {users.filter(u => u.app_metadata?.role === "admin").length} · HR Staff {users.filter(u => ["hr","hr_staff"].includes(u.app_metadata?.role)).length}
              </div>
            )}
          </div>
        )}

      </div>
    </div>
  );
};

window.UserAdminScreen = UserAdminScreen;
