// ============ TEAM TAB ============
// Members, role pips, invite UI, and the workspace audit feed.

const TM_PALETTE = ["#E85D1A", "#3B7CFF", "#2DAF6B", "#B4488C", "#7A5BCF", "#D17C2A", "#3DA28A"];
const TM_SERVER = () =>
  (typeof window !== "undefined" && window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) ||
  "http://localhost:3001";

function TeamTab() {
  const [members, setMembers] = useState([]);
  const [audit, setAudit]     = useState([]);
  const [showAdd, setShowAdd] = useState(false);
  const [email, setEmail]     = useState("");
  const [role, setRole]       = useState("Member");
  const [openMore, setOpenMore] = useState(null);

  // Hydrate from server on mount.
  useEffect(() => {
    fetch(`${TM_SERVER()}/team`)
      .then((r) => r.ok ? r.json() : [])
      .then(setMembers)
      .catch(() => {});
    fetch(`${TM_SERVER()}/team/audit`)
      .then((r) => r.ok ? r.json() : [])
      .then((rows) => setAudit(rows.map((r) => ({
        who:    r.who,
        what:   r.what,
        amount: r.amount || "",
        t:      r.t ? new Date(r.t).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }) : "recently",
      }))))
      .catch(() => {});
  }, []);

  const initialsFor = (e) => {
    const stub = e.split("@")[0].replace(/[^a-zA-Z]/g, "");
    return (stub.slice(0, 2) || "?").toUpperCase();
  };
  const sendInvite = () => {
    const trimmed = email.trim();
    if (!trimmed.includes("@")) { window.toast("Enter a valid email", "warn"); return; }
    fetch(`${TM_SERVER()}/team/invite`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ email: trimmed, role }),
    })
      .then((r) => r.ok ? r.json() : Promise.reject(r))
      .then((member) => {
        setMembers((xs) => [...xs, { ...member, joined: "Just invited" }]);
        setAudit((xs) => [{ who: "You", what: `invited a teammate as ${role}`, amount: trimmed, t: "just now" }, ...xs]);
        setEmail("");
        setRole("Member");
        setShowAdd(false);
        window.toast(`Invite sent to ${trimmed}`, "good");
      })
      .catch(async (r) => {
        const j = await (r.json ? r.json().catch(() => ({})) : Promise.resolve({}));
        window.toast(j.error || "Invite failed", "warn");
      });
  };
  const removeMember = (m) => {
    if (m.role === "Owner") { window.toast("Can't remove the workspace owner", "warn"); return; }
    if (!window.confirm(`Remove ${m.name}?`)) return;
    fetch(`${TM_SERVER()}/team/${m.id}`, { method: "DELETE" })
      .then((r) => r.ok ? r.json() : Promise.reject())
      .then(() => {
        setMembers((xs) => xs.filter((x) => x.id !== m.id));
        setAudit((xs) => [{ who: "You", what: "removed a teammate", amount: m.email, t: "just now" }, ...xs]);
        setOpenMore(null);
        window.toast(`${m.name} removed`, "warn");
      })
      .catch(() => window.toast("Couldn't remove — server error", "warn"));
  };
  const changeRole = (m, newRole) => {
    fetch(`${TM_SERVER()}/team/${m.id}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ role: newRole }),
    })
      .then((r) => r.ok ? r.json() : Promise.reject())
      .then((updated) => {
        setMembers((xs) => xs.map((x) => x.id === m.id ? { ...x, ...updated } : x));
        setAudit((xs) => [{ who: "You", what: `changed a role to ${newRole}`, amount: m.email, t: "just now" }, ...xs]);
        setOpenMore(null);
        window.toast(`${m.name} is now a ${newRole}`, "good");
      })
      .catch(() => window.toast("Couldn't update role", "warn"));
  };

  return (
    <div className="tm-page">
      <div className="tm-head">
        <div>
          <h2 className="tm-h">Your team.</h2>
          <p className="tm-s">Who can see what your agents are doing — and step in when they need to.</p>
        </div>
        <button className="btn btn-primary btn-sm" onClick={() => setShowAdd(true)}>+ Invite teammate</button>
      </div>

      <div className="tm-list">
        {members.map(m => (
          <div key={m.id} className="tm-row">
            <div className="tm-avatar" style={{ background: m.color }}>{m.initials}</div>
            <div className="tm-body">
              <div className="tm-n">{m.name}</div>
              <div className="tm-e">{m.email}</div>
            </div>
            <div className="tm-role">
              <span className={`tm-role-pip tm-role-${m.role.toLowerCase()}`}>{m.role}</span>
            </div>
            <div className="tm-joined">{m.joined}</div>
            <div className="tm-more-wrap">
              <button className="tm-more" onClick={() => setOpenMore(openMore === m.id ? null : m.id)} aria-label="More">⋯</button>
              {openMore === m.id ? (
                <div className="tm-more-menu" onMouseLeave={() => setOpenMore(null)}>
                  {["Owner", "Admin", "Member", "Viewer"].filter((r) => r !== m.role && m.role !== "Owner").map((r) => (
                    <button key={r} className="tm-more-item" onClick={() => changeRole(m, r)}>Make {r}</button>
                  ))}
                  <button className="tm-more-item tm-more-item-danger" onClick={() => removeMember(m)} disabled={m.role === "Owner"}>Remove</button>
                </div>
              ) : null}
            </div>
          </div>
        ))}
        {showAdd ? (
          <div className="tm-add">
            <input
              className="tm-add-i"
              placeholder="email@yourcompany.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") sendInvite(); if (e.key === "Escape") setShowAdd(false); }}
              autoFocus
            />
            <select className="tm-add-r" value={role} onChange={(e) => setRole(e.target.value)}>
              <option>Member</option>
              <option>Admin</option>
              <option>Viewer</option>
            </select>
            <button className="btn btn-primary btn-sm" onClick={sendInvite}>Send invite</button>
            <button className="btn btn-ghost btn-sm" onClick={() => { setShowAdd(false); setEmail(""); }}>Cancel</button>
          </div>
        ) : null}
      </div>

      <div className="tm-audit">
        <div className="tm-audit-head">
          <h3 className="tm-audit-h">Recent activity</h3>
          <span className="tm-audit-s">Every approval, edit, take-over, and connection</span>
        </div>
        <div className="tm-audit-list">
          {audit.map((a, i) => (
            <div key={i} className="tm-audit-row">
              <div className="tm-audit-t">{a.t}</div>
              <div className="tm-audit-text">
                <strong>{a.who}</strong> {a.what} <span className="tm-audit-d">— {a.amount}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.TeamTab = TeamTab;
