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

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";

// ---- CitrusSupportSection ----
// Business-facing support request panel. Owners/Admins can open a request;
// Citrus assigns a team member and access is granted immediately.
// Access is revoked on resolution.
function CitrusSupportSection({ userRole }) {
  const normalizedRole = String(userRole || "").trim().toLowerCase();
  const legacyPrivileged = !normalizedRole && window.CITRUS_CONFIG?.AUTH_REQUIRED === false;
  const canManage =
    normalizedRole === "owner" ||
    normalizedRole === "admin" ||
    normalizedRole === "masteradmin" ||
    legacyPrivileged;
  const [requests, setRequests] = useState(null);   // null = loading
  const [showForm, setShowForm] = useState(false);
  const [subject, setSubject]   = useState("");
  const [desc, setDesc]         = useState("");
  const [submitting, setSubmitting] = useState(false);

  const reload = () =>
    fetch(`${TM_SERVER()}/auth/support-requests`)
      .then((r) => r.ok ? r.json() : [])
      .then(setRequests)
      .catch(() => setRequests([]));

  useEffect(() => { if (canManage) reload(); }, [canManage]);

  const submit = () => {
    if (!subject.trim()) { window.toast("Add a subject", "warn"); return; }
    setSubmitting(true);
    fetch(`${TM_SERVER()}/auth/support-requests`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ subject: subject.trim(), description: desc.trim() }),
    })
      .then((r) => r.ok ? r.json() : r.json().then((j) => Promise.reject(j)))
      .then((req) => {
        setRequests((xs) => [req, ...(xs || [])]);
        setSubject(""); setDesc(""); setShowForm(false);
        window.toast("Support request sent — we'll be in touch", "good");
      })
      .catch((j) => window.toast(j?.error || "Couldn't send request", "warn"))
      .finally(() => setSubmitting(false));
  };

  const cancel = (id) => {
    if (!window.confirm("Cancel this support request?")) return;
    fetch(`${TM_SERVER()}/auth/support-requests/${id}`, { method: "DELETE" })
      .then((r) => r.ok ? r.json() : Promise.reject())
      .then(() => {
        setRequests((xs) => xs.map((r) => r.id === id ? { ...r, status: "cancelled" } : r));
        window.toast("Request cancelled", "warn");
      })
      .catch(() => window.toast("Couldn't cancel", "warn"));
  };

  if (!canManage) {
    return (
      <div className="tm-section" style={{ marginTop: "2rem" }}>
        <div className="tm-card" style={{ padding: "0.85rem 1rem", border: "1px solid #EEE", borderRadius: 8, color: "#6B7280", fontSize: "0.85rem" }}>
          Citrus support is available to Owner, Admin, and MasterAdmin roles.
        </div>
      </div>
    );
  }

  const open = (requests || []).filter((r) => r.status === "pending" || r.status === "awaiting_business_approval" || r.status === "assigned");
  const past = (requests || []).filter((r) => r.status === "resolved" || r.status === "cancelled");

  const statusBadge = (r) => {
    if (r.status === "pending")  return { label: "Waiting for Citrus", bg: "#FFF7ED", color: "#B45309", border: "#FCD34D" };
    if (r.status === "awaiting_business_approval") return { label: "In progress", bg: "#ECFDF5", color: "#065F46", border: "#6EE7B7" };
    if (r.status === "assigned") return { label: "In progress",        bg: "#ECFDF5", color: "#065F46", border: "#6EE7B7" };
    if (r.status === "resolved") return { label: "Resolved",           bg: "#F0FDF4", color: "#166534", border: "#BBF7D0" };
    return                               { label: "Cancelled",         bg: "#F9FAFB", color: "#6B7280", border: "#D1D5DB" };
  };

  return (
    <div className="tm-section" style={{ marginTop: "2rem" }}>
      <div className="tm-head" style={{ marginBottom: "0.75rem" }}>
        <div>
          <h3 className="tm-h" style={{ fontSize: "1rem" }}>Citrus support</h3>
          <p className="tm-s" style={{ fontSize: "0.85rem" }}>
            Need help from us? Open a request and we'll assign someone from the
            Citrus team. Access is granted while the issue is in progress and
            removed when we mark it resolved.
          </p>
        </div>
        {!showForm && open.length === 0 && (
          <button className="btn btn-primary btn-sm" onClick={() => setShowForm(true)}>
            Request support
          </button>
        )}
      </div>

      {showForm && (
        <div className="tm-add" style={{ flexDirection: "column", alignItems: "stretch", gap: "0.5rem", padding: "1rem", background: "#FAFAFA", borderRadius: 8, marginBottom: "1rem", border: "1px solid #EEE" }}>
          <input
            className="tm-add-i"
            placeholder="What do you need help with? (e.g. Agent not responding correctly)"
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            style={{ width: "100%" }}
            autoFocus
          />
          <textarea
            className="tm-add-i"
            placeholder="Describe the issue in more detail (optional)"
            value={desc}
            onChange={(e) => setDesc(e.target.value)}
            rows={3}
            style={{ width: "100%", resize: "vertical", fontFamily: "inherit", fontSize: "inherit" }}
          />
          <div style={{ display: "flex", gap: "0.5rem" }}>
            <button className="btn btn-primary btn-sm" onClick={submit} disabled={submitting}>
              {submitting ? "Sending…" : "Send request"}
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => { setShowForm(false); setSubject(""); setDesc(""); }}>
              Cancel
            </button>
          </div>
        </div>
      )}

      {requests === null && <div className="tm-s" style={{ padding: "0.5rem 0" }}>Loading…</div>}

      {open.length > 0 && (
        <div className="tm-list" style={{ marginBottom: "0.5rem" }}>
          {open.map((r) => {
            const badge = statusBadge(r);
            return (
              <div key={r.id} className="tm-row" style={{ flexWrap: "wrap", gap: "0.25rem" }}>
                <div className="tm-avatar" style={{ background: "#E85D1A", fontSize: "0.7rem", flexShrink: 0 }}>CS</div>
                <div className="tm-body" style={{ flex: "1 1 200px" }}>
                  <div className="tm-n">{r.subject}</div>
                  <div className="tm-e" style={{ marginTop: 2 }}>
                    {((r.status === "assigned") || (r.status === "awaiting_business_approval")) && r.assignedTo
                      ? <span style={{ color: "#065F46" }}>✓ {r.assignedTo.name || r.assignedTo.email} from Citrus is on this</span>
                      : <span>Submitted {r.createdAt ? new Date(r.createdAt).toLocaleDateString(undefined, { month: "short", day: "numeric" }) : "recently"}</span>
                    }
                  </div>
                </div>
                <span style={{ display: "inline-flex", alignItems: "center", padding: "3px 10px", borderRadius: 999, fontSize: 11, fontWeight: 600, background: badge.bg, color: badge.color, border: `1px solid ${badge.border}`, whiteSpace: "nowrap" }}>
                  {badge.label}
                </span>
                {r.status === "pending" && (
                  <button
                    className="btn btn-ghost btn-sm"
                    style={{ color: "#9CA3AF", fontSize: "0.75rem" }}
                    onClick={() => cancel(r.id)}
                  >
                    Cancel
                  </button>
                )}
              </div>
            );
          })}
          {!showForm && (
            <div style={{ paddingTop: "0.5rem" }}>
              <button className="btn btn-ghost btn-sm" onClick={() => setShowForm(true)}>+ Another request</button>
            </div>
          )}
        </div>
      )}

      {past.length > 0 && (
        <details style={{ marginTop: "0.75rem" }}>
          <summary style={{ fontSize: "0.8rem", color: "#9CA3AF", cursor: "pointer", userSelect: "none" }}>
            {past.length} past request{past.length !== 1 ? "s" : ""}
          </summary>
          <div className="tm-list" style={{ marginTop: "0.5rem", opacity: 0.7 }}>
            {past.map((r) => {
              const badge = statusBadge(r);
              return (
                <div key={r.id} className="tm-row">
                  <div className="tm-body" style={{ flex: 1 }}>
                    <div className="tm-n" style={{ fontSize: "0.85rem" }}>{r.subject}</div>
                  </div>
                  <span style={{ display: "inline-flex", alignItems: "center", padding: "2px 8px", borderRadius: 999, fontSize: 11, fontWeight: 600, background: badge.bg, color: badge.color, border: `1px solid ${badge.border}` }}>
                    {badge.label}
                  </span>
                </div>
              );
            })}
          </div>
        </details>
      )}
    </div>
  );
}


function RoutingTeamsSection({ canManage }) {
  const [routes, setRoutes] = useState([]);
  const [draft, setDraft] = useState(null);
  const [busy, setBusy] = useState(null);
  const load = () => fetch(`${TM_SERVER()}/team/routing`).then((r) => r.ok ? r.json() : []).then((rows) => setRoutes(Array.isArray(rows) ? rows : [])).catch(() => setRoutes([]));
  useEffect(() => { load(); }, []);
  const startAdd = () => setDraft({ id: null, keywords: "", emails: "" });
  const startEdit = (r) => setDraft({ id: r.id, keywords: (r.keywords || []).join(", "), emails: (r.emails || []).join(", ") });
  const save = () => {
    if (!draft) return;
    setBusy(draft.id || "new");
    fetch(`${TM_SERVER()}/team/routing${draft.id ? "/" + encodeURIComponent(draft.id) : ""}`, {
      method: draft.id ? "PATCH" : "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ keywords: draft.keywords, emails: draft.emails }),
    })
      .then((r) => r.ok ? r.json() : r.json().then((j) => Promise.reject(j)))
      .then((row) => {
        setRoutes((xs) => draft.id ? xs.map((x) => x.id === row.id ? row : x) : [row, ...xs]);
        setDraft(null);
        window.toast && window.toast("Routing team saved", "good");
      })
      .catch((j) => window.toast && window.toast(j?.error || "Couldn't save routing team", "warn"))
      .finally(() => setBusy(null));
  };
  const remove = (r) => {
    if (!window.confirm(`Delete routing team for ${(r.keywords || []).join(", ")}?`)) return;
    setBusy(r.id);
    fetch(`${TM_SERVER()}/team/routing/${encodeURIComponent(r.id)}`, { method: "DELETE" })
      .then((res) => res.ok ? res.json() : Promise.reject())
      .then(() => setRoutes((xs) => xs.filter((x) => x.id !== r.id)))
      .catch(() => window.toast && window.toast("Couldn't delete routing team", "warn"))
      .finally(() => setBusy(null));
  };
  return (
    <div className="tm-section" style={{ marginTop: "2rem" }}>
      <div className="tm-head">
        <div>
          <h3 className="tm-h" style={{ fontSize: "1rem" }}>Routing teams</h3>
          <p className="tm-s" style={{ fontSize: "0.85rem" }}>Map product/topic keywords to the people who should own matching leads.</p>
        </div>
        {canManage && !draft ? <button className="btn btn-primary btn-sm" onClick={startAdd}>+ Add Team</button> : null}
      </div>
      {draft ? (
        <div className="tm-add" style={{ flexWrap: "wrap", alignItems: "stretch", marginBottom: "0.75rem" }}>
          <input className="tm-add-i" style={{ minWidth: 220, flex: 1 }} placeholder="Products / Topics: pumps, hvac, chillers" value={draft.keywords} onChange={(e) => setDraft({ ...draft, keywords: e.target.value })} autoFocus />
          <input className="tm-add-i" style={{ minWidth: 260, flex: 1 }} placeholder="Emails: ahmed@gabtic.com, mohamed@gabtic.com" value={draft.emails} onChange={(e) => setDraft({ ...draft, emails: e.target.value })} />
          <button className="btn btn-primary btn-sm" onClick={save} disabled={!!busy}>Save</button>
          <button className="btn btn-ghost btn-sm" onClick={() => setDraft(null)}>Cancel</button>
        </div>
      ) : null}
      <div className="tm-list">
        {routes.length === 0 ? <div className="tm-card" style={{ padding: "0.85rem 1rem", color: "#6B7280", fontSize: "0.85rem" }}>No routing teams yet.</div> : null}
        {routes.map((r) => (
          <div key={r.id} className="tm-row" style={{ alignItems: "flex-start", gap: 12 }}>
            <div className="tm-avatar" style={{ background: "#2DAF6B", flexShrink: 0 }}>RT</div>
            <div className="tm-body" style={{ flex: 1 }}>
              <div className="tm-n">{(r.keywords || []).join(", ")}</div>
              <div className="tm-e">{(r.emails || []).join(", ")}</div>
            </div>
            {canManage ? <button className="btn btn-ghost btn-sm" onClick={() => startEdit(r)} disabled={!!busy}>Edit</button> : null}
            {canManage ? <button className="btn btn-ghost btn-sm" onClick={() => remove(r)} disabled={busy === r.id} style={{ color: "#B0234A" }}>Delete</button> : null}
          </div>
        ))}
      </div>
    </div>
  );
}

function TeamTab({ userRole } = {}) {
  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);
  const [resetBusy, setResetBusy] = useState(null);
  const normalizedRole = String(userRole || "").trim().toLowerCase();
  const isOwner = normalizedRole === "owner";
  const isAdmin = normalizedRole === "admin";
  const isMasterAdmin = normalizedRole === "masteradmin";
  const canManageRoles = isOwner || isAdmin || isMasterAdmin;
  const canInvite = canManageRoles;
  const canInviteAdmin = canManageRoles;

  // 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 = () => {
    if (!canInvite) {
      window.toast("Only Owner and Admin can invite teammates", "warn");
      return;
    }
    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 (!canManageRoles) { window.toast("Only Owner and Admin can remove teammates", "warn"); return; }
    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 resetPassword = (m, sendEmail) => {
    if (!canManageRoles) { window.toast("Only Owner and Admin can reset passwords", "warn"); return; }
    if (m.role === "Owner" && !isOwner && !isMasterAdmin) { window.toast("Only an Owner can reset the workspace owner's password", "warn"); return; }
    let password = "";
    if (!sendEmail) {
      password = window.prompt(`Enter a new temporary password for ${m.email}. They will be asked to change it on next sign-in.`) || "";
      if (!password) return;
    } else if (!window.confirm(`Send ${m.email} a new temporary password email?`)) {
      return;
    }
    setResetBusy(m.id);
    fetch(`${TM_SERVER()}/team/${m.id}/password-reset`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(sendEmail ? { sendEmail: true } : { password }),
    })
      .then((r) => r.ok ? r.json() : Promise.reject(r))
      .then(() => {
        setAudit((xs) => [{ who: "You", what: sendEmail ? "sent a password reset email" : "reset a password", amount: m.email, t: "just now" }, ...xs]);
        setOpenMore(null);
        window.toast(sendEmail ? `Temporary password sent to ${m.email}` : `Temporary password set for ${m.email}`, "good");
      })
      .catch(async (r) => {
        const j = await (r.json ? r.json().catch(() => ({})) : Promise.resolve({}));
        window.toast(j.error || "Password reset failed", "warn");
      })
      .finally(() => setResetBusy(null));
  };
  const changeRole = (m, newRole) => {
    if (!canManageRoles) {
      window.toast("Only Owner and Admin can change roles", "warn");
      return;
    }
    if ((m.role === "Member" || m.role === "Viewer") && newRole === "Admin" && !canInviteAdmin) {
      window.toast("Only Owner and Admin can promote to Admin", "warn");
      return;
    }
    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>
        {canInvite ? (
          <button className="btn btn-primary btn-sm" onClick={() => setShowAdd(true)}>+ Invite teammate</button>
        ) : null}
      </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}
                {m.status === "invited" ? <span className="tm-pending-invite">Pending invite</span> : null}
              </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.status === "invited" ? "Invited" : m.joined}</div>
            <div className="tm-more-wrap">
              {canManageRoles ? (
                <button className="tm-more" onClick={() => setOpenMore(openMore === m.id ? null : m.id)} aria-label="More">⋯</button>
              ) : null}
              {canManageRoles && openMore === m.id ? (
                <div className="tm-more-menu" onMouseLeave={() => setOpenMore(null)}>
                  {["Owner", "Admin", "Manager", "Member", "Viewer"].filter((r) => {
                    if (m.role === "Owner") return false;
                    if (r === m.role) return false;
                    if (r === "Owner") return false;
                    if (r === "Admin" && !(m.role === "Manager" || m.role === "Member" || m.role === "Viewer")) return false;
                    if (r === "Admin" && !canInviteAdmin) return false;
                    return true;
                  }).map((r) => (
                    <button key={r} className="tm-more-item" onClick={() => changeRole(m, r)}>Make {r}</button>
                  ))}
                  <button className="tm-more-item" onClick={() => resetPassword(m, true)} disabled={resetBusy === m.id}>Send temp password</button>
                  <button className="tm-more-item" onClick={() => resetPassword(m, false)} disabled={resetBusy === m.id}>Set temp password…</button>
                  <button className="tm-more-item tm-more-item-danger" onClick={() => removeMember(m)} disabled={m.role === "Owner"}>Remove</button>
                </div>
              ) : null}
            </div>
          </div>
        ))}
        {canInvite && 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>
              {canInviteAdmin ? <option>Admin</option> : null}
              <option>Manager</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>

      <RoutingTeamsSection canManage={canManageRoles} />

      <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>

      <CitrusSupportSection userRole={userRole} />
    </div>
  );
}

window.TeamTab = TeamTab;
