// ── Control-plane: operator (KYNA staff) management ───────────────────────
function CpOperators() {
  const notify = useToast();
  const [data, setData] = React.useState(null);
  const [meId, setMeId] = React.useState(null);
  const [invite, setInvite] = React.useState(false);
  const [otp, setOtp] = React.useState(null);
  const [editEmail, setEditEmail] = React.useState(null); // operator being edited

  const load = () => cpApi.listOperators().then((d) => { setData(d.data); setMeId(d.me); }).catch((e) => notify(e.message));
  React.useEffect(() => { load(); }, []);

  const patch = async (o, body, msg) => {
    try { await cpApi.updateOperator(o.id, body); notify(msg); load(); }
    catch (e) { notify(e.message); }
  };
  const reset = async (o) => {
    try { const r = await cpApi.resetOperatorPassword(o.id); setOtp({ ...r, who: o.email }); }
    catch (e) { notify(e.message); }
  };
  const del = async (o) => {
    if (!window.confirm(`Delete operator ${o.email}?`)) return;
    try { await cpApi.deleteOperator(o.id); notify("Operator deleted"); load(); }
    catch (e) { notify(e.message); }
  };

  if (!data) return <div style={{ color: "var(--ink-mute)" }}><Spinner /> Loading…</div>;

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", marginBottom: 16 }}>
        <h1 style={{ fontSize: 24, flex: 1 }}>Operators</h1>
        <button className="btn primary" onClick={() => setInvite(true)}>+ Invite operator</button>
      </div>
      <div className="panel tablewrap">
        <table className="grid">
          <thead><tr><th>Email</th><th>Name</th><th>Role</th><th>Status</th><th>Last login</th><th></th></tr></thead>
          <tbody>
            {data.map((o) => {
              const self = o.id === meId;
              return (
                <tr key={o.id}>
                  <td>{o.email} {self && <Pill tone="accent">you</Pill>}</td>
                  <td>{o.name || "—"}</td>
                  <td>
                    <select value={o.role} disabled={self}
                      onChange={(e) => patch(o, { role: e.target.value }, "Role changed")}
                      style={{ padding: "4px 8px", borderRadius: 6, border: "1px solid var(--line-strong)", background: "var(--panel)" }}>
                      <option value="operator">operator</option>
                      <option value="cp_admin">cp_admin</option>
                    </select>
                  </td>
                  <td>
                    <Pill tone={o.status === "active" ? "ok" : "warn"}>{o.status}</Pill>
                    {o.mustChangePassword && <span style={{ marginLeft: 6, fontSize: 11, color: "var(--ink-mute)" }}>pending pw</span>}
                  </td>
                  <td style={{ color: "var(--ink-mute)" }}>{o.lastLoginAt ? timeAgo(o.lastLoginAt) : "never"}</td>
                  <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                    <button className="btn sm ghost" onClick={() => setEditEmail(o)}>Edit email</button>
                    <button className="btn sm ghost" onClick={() => reset(o)}>Reset pw</button>
                    {!self && o.status === "active" &&
                      <button className="btn sm ghost" onClick={() => patch(o, { status: "suspended" }, "Suspended")}>Suspend</button>}
                    {o.status === "suspended" &&
                      <button className="btn sm ghost" onClick={() => patch(o, { status: "active" }, "Reactivated")}>Activate</button>}
                    {!self && <button className="btn sm ghost" style={{ color: "var(--danger)" }} onClick={() => del(o)}>Delete</button>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {invite && (
        <InviteOperator onClose={() => setInvite(false)}
          onDone={(res) => { setInvite(false); load(); setOtp({ ...res, who: res.operator.email }); }} />
      )}
      {editEmail && (
        <EditOperatorEmail operator={editEmail} self={editEmail.id === meId} onClose={() => setEditEmail(null)}
          onDone={() => { setEditEmail(null); notify("Email updated — sign-in codes now go to the new address"); load(); }} />
      )}
      {otp && (
        <Modal title={`One-time password — ${otp.who}`} onClose={() => setOtp(null)}>
          <p style={{ color: "var(--ink-mute)", marginTop: 0 }}>Share securely. They'll set their own password + get an email code on first sign-in.</p>
          <CopyBox value={otp.oneTimePassword} />
          <div style={{ marginTop: 16, textAlign: "right" }}><button className="btn primary" onClick={() => setOtp(null)}>Done</button></div>
        </Modal>
      )}
    </div>
  );
}

// Your own email needs your current password; another operator's email can
// only be changed by a cp_admin (enforced server-side).
function EditOperatorEmail({ operator, self, onClose, onDone }) {
  const [email, setEmail] = React.useState(operator.email);
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const submit = async (e) => {
    e.preventDefault(); setBusy(true); setErr(null);
    try {
      if (self) await cpApi.changeEmail(email.trim(), password);
      else await cpApi.updateOperator(operator.id, { email: email.trim() });
      onDone();
    } catch (e) { setErr(e.message); setBusy(false); }
  };
  return (
    <Modal title={self ? "Change your email" : `Change email — ${operator.email}`} onClose={onClose}>
      <form onSubmit={submit}>
        <p style={{ color: "var(--ink-mute)", marginTop: 0, fontSize: 13 }}>Sign-in codes are sent to this address.</p>
        <Field label="New email" required><input type="email" autoFocus value={email} onChange={(e) => setEmail(e.target.value)} required /></Field>
        {self && (
          <Field label="Current password" required>
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="current-password" />
          </Field>
        )}
        {err && <div style={{ color: "var(--danger)", fontSize: 13, marginBottom: 12 }}>{err}</div>}
        <button className="btn primary" disabled={busy || !email.trim()}>{busy ? <Spinner /> : "Save email"}</button>
      </form>
    </Modal>
  );
}

function InviteOperator({ onClose, onDone }) {
  const [email, setEmail] = React.useState("");
  const [name, setName] = React.useState("");
  const [role, setRole] = React.useState("operator");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const submit = async (e) => {
    e.preventDefault(); setBusy(true); setErr(null);
    try { onDone(await cpApi.inviteOperator({ email, name, role })); }
    catch (e) { setErr(e.message); setBusy(false); }
  };
  return (
    <Modal title="Invite operator" onClose={onClose}>
      <form onSubmit={submit}>
        <Field label="Email" required><input type="email" autoFocus value={email} onChange={(e) => setEmail(e.target.value)} required /></Field>
        <Field label="Name"><input value={name} onChange={(e) => setName(e.target.value)} /></Field>
        <Field label="Role">
          <select value={role} onChange={(e) => setRole(e.target.value)}>
            <option value="operator">operator — manage tenants</option>
            <option value="cp_admin">cp_admin — + manage operators</option>
          </select>
        </Field>
        {err && <div style={{ color: "var(--danger)", fontSize: 13, marginBottom: 12 }}>{err}</div>}
        <button className="btn primary" disabled={busy}>{busy ? <Spinner /> : "Create & get password"}</button>
      </form>
    </Modal>
  );
}

window.CpOperators = CpOperators;
