// ─────────────────────────────────────────────────────────────
// USERS (admin only) — clickable profiles, roles, dedicated
// editors, client records, permanent user deletion
// ─────────────────────────────────────────────────────────────
function Users({ profile, profiles, clients, refresh }) {
  const { Card, Btn, Avatar, Select, SectionTitle, Empty } = window.PUI;
  const P = window.PORTAL;
  const [tab, setTab] = React.useState("users");
  const [userModal, setUserModal] = React.useState(null);   // profile being viewed
  const [clientModal, setClientModal] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const editors = profiles.filter(p => p.role === "editor");
  const ROLE_COLOR = { admin: "var(--gold-400)", editor: "#6E8BA8", client: "#3FB57A" };

  const setDedicated = async (clientId, editorId) => {
    await sb.from("clients").update({ dedicated_editor: editorId || null }).eq("id", clientId);
    refresh();
  };

  const saveClient = async (c) => {
    setBusy(true);
    try {
      const payload = { name: c.name, company: c.company, profile_id: c.profile_id || null, dedicated_editor: c.dedicated_editor || null };
      if (c.id) await sb.from("clients").update(payload).eq("id", c.id);
      else      await sb.from("clients").insert(payload);
      setClientModal(null); refresh();
    } catch (e) { alert("Save failed: " + e.message); }
    setBusy(false);
  };

  const delClient = async (id) => {
    if (!confirm("Delete this client record? Their projects and tasks will also be deleted.")) return;
    await sb.from("clients").delete().eq("id", id);
    setClientModal(null); refresh();
  };

  const tabBtn = (id, label) => (
    <button onClick={() => setTab(id)} style={{
      padding: "9px 18px", borderRadius: 9, fontSize: 13, fontWeight: 700, border: "none", cursor: "pointer",
      fontFamily: "var(--font-sans)",
      background: tab === id ? "var(--gold-500)" : "transparent",
      color: tab === id ? "#08080A" : "var(--text-tertiary)",
    }}>{label}</button>
  );

  return (
    <div>
      <SectionTitle right={tab === "clients" && <Btn onClick={() => setClientModal({})}>+ New Client</Btn>}>Users & Clients</SectionTitle>

      <div style={{ display: "flex", gap: 4, background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: 11, padding: 4, width: "fit-content", marginBottom: 20 }}>
        {tabBtn("users", "Portal Users")}
        {tabBtn("clients", "Client Records")}
      </div>

      {tab === "users" && (
        <Card padding={0}>
          {profiles.map(u => (
            <div key={u.id} onClick={() => setUserModal(u)} style={{
              display: "flex", alignItems: "center", gap: 14, padding: "15px 22px",
              borderBottom: "1px solid var(--border-subtle)", cursor: "pointer", transition: "background .12s",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "rgba(255,255,255,0.02)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <Avatar name={u.full_name || u.email} url={u.avatar_url} size={38} />
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text-primary)" }}>
                  {u.full_name || "—"} {u.id === profile.id && <span style={{ fontSize: 11, color: "var(--gold-400)" }}>(you)</span>}
                </div>
                <div style={{ fontSize: 12, color: "var(--text-tertiary)" }}>{u.email} · Joined {P.fmtDate(u.created_at?.split("T")[0])}</div>
              </div>
              <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.06em", textTransform: "uppercase", color: ROLE_COLOR[u.role] }}>{u.role}</span>
              <span style={{ fontSize: 13, color: "var(--text-tertiary)" }}>›</span>
            </div>
          ))}
        </Card>
      )}

      {tab === "clients" && (
        <Card padding={0}>
          {clients.length === 0
            ? <Empty icon="◎" title="No client records" sub="Create a client record, then link it to their portal login." />
            : clients.map(c => {
              const linked = profiles.find(p => p.id === c.profile_id);
              const ded = profiles.find(p => p.id === c.dedicated_editor);
              return (
                <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "15px 22px", borderBottom: "1px solid var(--border-subtle)", flexWrap: "wrap" }}>
                  <Avatar name={c.name} size={38} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text-primary)" }}>{c.name}{c.company ? <span style={{ color: "var(--text-tertiary)", fontWeight: 500 }}> · {c.company}</span> : ""}</div>
                    <div style={{ fontSize: 12, color: linked ? "#3FB57A" : "var(--text-tertiary)" }}>
                      {linked ? "Portal login: " + linked.email : "No portal login linked"}
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: ded ? "var(--gold-400)" : "var(--text-tertiary)" }}>
                      {ded ? "Editor" : "No editor"}
                    </span>
                    <Select value={c.dedicated_editor || ""} onChange={e => setDedicated(c.id, e.target.value)} style={{ width: "auto", padding: "7px 10px", fontSize: 12 }}>
                      <option value="">— Assign editor —</option>
                      {editors.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
                    </Select>
                  </div>
                  <Btn variant="secondary" size="sm" onClick={() => setClientModal(c)}>Edit</Btn>
                </div>
              );
            })}
        </Card>
      )}

      {userModal && (
        <UserModal user={userModal} me={profile} profiles={profiles} clients={clients}
          onClose={() => setUserModal(null)}
          onChanged={() => { setUserModal(null); refresh(); }} />
      )}

      {clientModal !== null && (
        <ClientModal client={clientModal.id ? clientModal : null} profiles={profiles} busy={busy}
          onSave={saveClient} onDelete={delClient} onClose={() => setClientModal(null)} />
      )}
    </div>
  );
}

// ── User detail modal — role, dedicated editor, permanent delete ──
function UserModal({ user, me, profiles, clients, onClose, onChanged }) {
  const { Modal, Field, Select, Btn, Avatar, Input } = window.PUI;
  const P = window.PORTAL;
  const [role, setRole] = React.useState(user.role);
  const [busy, setBusy] = React.useState(false);
  const editors = profiles.filter(p => p.role === "editor");

  // Client record linked to this login (if any)
  const clientRec = clients.find(c => c.profile_id === user.id);
  const [dedEditor, setDedEditor] = React.useState(clientRec?.dedicated_editor || "");
  const [makeRecord, setMakeRecord] = React.useState(false);
  const [recName, setRecName] = React.useState(user.full_name || "");

  const isSelf = user.id === me.id;

  const save = async () => {
    setBusy(true);
    try {
      if (isSelf && role !== "admin" && !confirm("You're removing your own admin access. Continue?")) { setBusy(false); return; }
      await sb.from("profiles").update({ role }).eq("id", user.id);

      if (clientRec) {
        await sb.from("clients").update({ dedicated_editor: dedEditor || null }).eq("id", clientRec.id);
      } else if (role === "client" && makeRecord) {
        if (!recName.trim()) { setBusy(false); return alert("Enter a client name for the record."); }
        await sb.from("clients").insert({ name: recName.trim(), profile_id: user.id, dedicated_editor: dedEditor || null });
      }
      onChanged();
    } catch (e) { alert("Save failed: " + e.message); }
    setBusy(false);
  };

  const removeUser = async () => {
    if (isSelf) return alert("You cannot delete your own account.");
    if (!confirm("Permanently delete " + (user.full_name || user.email) + "?\n\nTheir login is removed from the database and they will no longer be able to sign in. Their comments are deleted; any tasks assigned to them become unassigned. This cannot be undone.")) return;
    setBusy(true);
    try {
      const { error } = await sb.rpc("admin_delete_user", { target: user.id });
      if (error) throw error;
      onChanged();
    } catch (e) {
      alert(e.message.includes("admin_delete_user")
        ? "The delete function isn't in your database yet — run portal-migration-2.sql in the Supabase SQL Editor first."
        : "Delete failed: " + e.message);
    }
    setBusy(false);
  };

  return (
    <Modal open onClose={onClose}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 24 }}>
        <Avatar name={user.full_name || user.email} url={user.avatar_url} size={52} />
        <div style={{ minWidth: 0 }}>
          <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 21, letterSpacing: "-0.02em" }}>
            {user.full_name || "—"} {isSelf && <span style={{ fontSize: 12, color: "var(--gold-400)" }}>(you)</span>}
          </h3>
          <div style={{ fontSize: 12, color: "var(--text-tertiary)" }}>{user.email} · Joined {P.fmtDate(user.created_at?.split("T")[0])}</div>
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="Role">
          <Select value={role} onChange={e => setRole(e.target.value)}>
            <option value="admin">Admin</option>
            <option value="editor">Editor</option>
            <option value="client">Client</option>
          </Select>
        </Field>

        {/* Dedicated editor — shown when this login is (or will be) a client */}
        {clientRec ? (
          <Field label={"Dedicated Editor · client record: " + clientRec.name}>
            <Select value={dedEditor} onChange={e => setDedEditor(e.target.value)}>
              <option value="">— Not assigned yet —</option>
              {editors.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
            </Select>
            <span style={{ fontSize: 11, color: "var(--text-tertiary)" }}>New tasks from this client are automatically assigned to this editor.</span>
          </Field>
        ) : role === "client" ? (
          <div style={{ padding: 16, borderRadius: 12, background: "rgba(251,208,40,0.05)", border: "1px solid rgba(251,208,40,0.2)" }}>
            <div style={{ fontSize: 13, color: "var(--text-secondary)", marginBottom: 10 }}>
              This login has no client record yet — without one they can't create tasks.
            </div>
            <label style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13, color: "var(--text-primary)", cursor: "pointer", marginBottom: makeRecord ? 12 : 0 }}>
              <input type="checkbox" checked={makeRecord} onChange={e => setMakeRecord(e.target.checked)} style={{ accentColor: "#FBD028", width: 15, height: 15 }} />
              Create a client record for this user
            </label>
            {makeRecord && (
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                <Field label="Client Name" required><Input value={recName} onChange={e => setRecName(e.target.value)} /></Field>
                <Field label="Dedicated Editor">
                  <Select value={dedEditor} onChange={e => setDedEditor(e.target.value)}>
                    <option value="">— Not assigned yet —</option>
                    {editors.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
                  </Select>
                </Field>
              </div>
            )}
          </div>
        ) : null}

        <div style={{ display: "flex", gap: 10 }}>
          <Btn onClick={save} disabled={busy}>{busy ? "Saving…" : "Save Changes"}</Btn>
          <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
        </div>

        {/* Danger zone */}
        {!isSelf && (
          <div style={{ marginTop: 6, padding: 16, borderRadius: 12, border: "1px solid rgba(226,73,46,0.25)", background: "rgba(226,73,46,0.04)" }}>
            <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: "0.08em", textTransform: "uppercase", color: "#E2492E", marginBottom: 8 }}>Danger zone</div>
            <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", lineHeight: 1.6, marginBottom: 12 }}>
              Permanently removes this user's login and profile from the database. They will no longer be able to sign in.
            </div>
            <Btn variant="danger" size="sm" onClick={removeUser} disabled={busy}>✕ Remove User Permanently</Btn>
          </div>
        )}
      </div>
    </Modal>
  );
}

function ClientModal({ client, profiles, busy, onSave, onDelete, onClose }) {
  const { Modal, Field, Input, Select, Btn } = window.PUI;
  const [name, setName] = React.useState(client?.name || "");
  const [company, setCompany] = React.useState(client?.company || "");
  const [profileId, setProfileId] = React.useState(client?.profile_id || "");
  const [dedEditor, setDedEditor] = React.useState(client?.dedicated_editor || "");
  const clientLogins = profiles.filter(p => p.role === "client");
  const editors = profiles.filter(p => p.role === "editor");

  return (
    <Modal open onClose={onClose}>
      <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 22, letterSpacing: "-0.02em", marginBottom: 22 }}>
        {client ? "Edit Client" : "New Client"}
      </h3>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="Client Name" required><Input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. John Rivera" /></Field>
        <Field label="Company"><Input value={company} onChange={e => setCompany(e.target.value)} placeholder="e.g. Rivera Realty Group" /></Field>
        <Field label="Dedicated Editor">
          <Select value={dedEditor} onChange={e => setDedEditor(e.target.value)}>
            <option value="">— Not assigned yet —</option>
            {editors.map(ed => <option key={ed.id} value={ed.id}>{ed.full_name || ed.email}</option>)}
          </Select>
          <span style={{ fontSize: 11, color: "var(--text-tertiary)" }}>New tasks from this client are automatically assigned to this editor.</span>
        </Field>
        <Field label="Linked Portal Login">
          <Select value={profileId} onChange={e => setProfileId(e.target.value)}>
            <option value="">— Not linked yet —</option>
            {clientLogins.map(p => <option key={p.id} value={p.id}>{p.full_name || p.email} ({p.email})</option>)}
          </Select>
          <span style={{ fontSize: 11, color: "var(--text-tertiary)" }}>The client signs up first, then you link their account here so they can see their projects.</span>
        </Field>
        <div style={{ display: "flex", gap: 10 }}>
          <Btn disabled={busy || !name.trim()} onClick={() => onSave({ id: client?.id, name: name.trim(), company: company.trim(), profile_id: profileId, dedicated_editor: dedEditor })}>
            {busy ? "Saving…" : client ? "Save Changes" : "Create Client"}
          </Btn>
          <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
          {client && <Btn variant="danger" onClick={() => onDelete(client.id)} style={{ marginLeft: "auto" }}>Delete</Btn>}
        </div>
      </div>
    </Modal>
  );
}
window.Users = Users;
