All files / src/pages team.tsx

94.73% Statements 180/190
84.06% Branches 153/182
98.11% Functions 52/53
99.4% Lines 167/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736                                                                6x 128x   18x   16x   94x       6x 128x   88x   14x   26x         256x 256x 256x   256x 256x   256x       256x 256x     256x 256x       256x 256x 256x 256x   256x   256x 12x 12x 12x     256x   92x 92x 92x     92x     92x   92x   92x     92x   15x 15x 4x 4x     4x 4x       4x             256x 4x 4x 4x 4x 4x     4x 3x 3x 3x 3x 1x   2x   3x   1x 1x   4x       256x 3x 3x 3x 2x   1x 1x       256x 4x 4x 3x 3x 2x 2x   1x 1x       256x       2x 2x 2x     1x 1x   1x 1x       256x 4x 4x               1x   3x 3x 2x 2x   1x 1x       256x 3x 3x 3x 2x 2x   1x 1x       256x 4x 4x               1x   3x 3x 2x 2x   1x 1x         256x 133x                   133x 13x 13x                     133x       256x 58x 58x 58x     256x 58x 58x 58x       256x 136x 136x 136x   136x 3x   136x 1x 1x 3x     136x       256x           256x                 11x                     207x                                   1x                                                           1x 1x                                             64x                                                                                         1x         1x                                   1x         1x         1x                         2x                                                                 64x                                                                                                                                                     2x                 3x                         3x                 2x                 3x                                                               3x 3x 3x 3x     1x                 190x   190x       3x                                                                          
import { useState, useMemo, useRef, useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Users, X, Mail, Phone, HelpCircle, Search, UserX, UserCheck, Trash2, RefreshCw, ArrowUpDown, Clock, MoreVertical } from "lucide-react";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { EmptyState } from "../components/ui/empty-state";
import { Skeleton } from "../components/ui/skeleton";
import { FacetedFilter } from "../components/ui/faceted-filter";
import { DropdownMenu } from "../components/ui/dropdown-menu";
import { usePro } from "../lib/pro-context";
import { proApi, getErrorMessage, type TeamMember, type TeamInvitation, type ContactCheckResult } from "../lib/api";
import { notify } from "../lib/notify";
import { queryKeys } from "../lib/query-keys";
import { useTeamMembers, useTeamInvitations } from "../hooks/queries/useTeamQueries";
import { InviteMemberModal, detectContactType } from "../components/team/InviteMemberModal";
import { StickyPageHeader } from "../components/ui/sticky-page-header";
import { useConfirmDialog } from "../hooks";
import { useSortable } from "../hooks/useSortable";
 
type TeamTableRow = {
	key: string;
	name: string;
	email: string;
	role: string;
	status: "active" | "inactive" | "pending";
	dateCreated: string;
	sortableName: string;
	source:
		| { type: "member"; data: TeamMember }
		| { type: "invitation"; data: TeamInvitation };
};
 
const getRoleBadgeColor = (role: string) => {
	switch (role) {
		case "owner":
			return "bg-purple-100 text-purple-800";
		case "manager":
			return "bg-info-light text-info";
		default:
			return "bg-background-subtle text-foreground-default";
	}
};
 
const getStatusBadge = (status: "active" | "inactive" | "pending") => {
	switch (status) {
		case "active":
			return "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300";
		case "inactive":
			return "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400";
		case "pending":
			return "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300";
	}
};
 
export function TeamPage() {
	const { proId, proRole } = usePro();
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
 
	const { data: teamMembers = [], isLoading: membersLoading } = useTeamMembers(proId);
	const { data: invitations = [] } = useTeamInvitations(proId);
 
	const [searchQuery, setSearchQuery] = useState("");
	// Default filter includes "inactive" so deactivated members remain visible
	// in the owner's view with a Reactivate action (see issue #582). Owners can
	// still narrow the view via the Status filter.
	const [statusFilter, setStatusFilter] = useState<Set<string>>(() => new Set(["active", "inactive", "pending"]));
	const [roleFilter, setRoleFilter] = useState<Set<string>>(() => new Set());
 
	// Invite member modal
	const [showInviteModal, setShowInviteModal] = useState(false);
	const [newInvite, setNewInvite] = useState({
		contact: "",
		role: "staff" as "owner" | "manager" | "staff",
	});
	const [isInviting, setIsInviting] = useState(false);
	const [contactCheck, setContactCheck] = useState<ContactCheckResult | null>(null);
	const [isChecking, setIsChecking] = useState(false);
	const checkTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
 
	const isOwner = proRole === "owner";
 
	const invalidateTeam = () => {
		Iif (!proId) return;
		queryClient.invalidateQueries({ queryKey: queryKeys.team.members(proId) });
		queryClient.invalidateQueries({ queryKey: queryKeys.team.invitations(proId) });
	};
 
	const handleContactChange = useCallback(
		(value: string) => {
			setNewInvite((prev) => ({ ...prev, contact: value }));
			setContactCheck(null);
			setIsChecking(false);
 
			// Clear existing timer
			if (checkTimer.current) clearTimeout(checkTimer.current);
 
			// Only check if we have a valid-looking contact and a proId
			Iif (!proId || !value.trim()) return;
 
			const type = detectContactType(value);
			const isValid =
				(type === "email" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) ||
				(type === "phone" && /^[6-9]\d{9}$/.test(value.trim().replace(/\D/g, "").replace(/^91/, "")));
 
			if (!isValid) return;
 
			setIsChecking(true);
			checkTimer.current = setTimeout(async () => {
				try {
					const data = type === "email"
						? { email: value.trim() }
						: { phone: value.trim() };
					const response = await proApi.checkTeamContact(proId, data);
					Eif (response.data) setContactCheck(response.data);
				} catch {
					// Silently fail — the server will catch it on submit
				} finally {
					setIsChecking(false);
				}
			}, 500);
		},
		[proId],
	);
 
	const handleInviteMember = async () => {
		Iif (!proId || !newInvite.contact.trim()) return;
		setIsInviting(true);
		try {
			const type = detectContactType(newInvite.contact);
			const payload = type === "phone"
				? { phone: newInvite.contact.trim(), role: newInvite.role }
				: { email: newInvite.contact.trim(), role: newInvite.role };
			const response = await proApi.inviteTeamMember(proId, payload);
			setShowInviteModal(false);
			setNewInvite({ contact: "", role: "staff" });
			setContactCheck(null);
			if (response.data && response.data.emailSent === false) {
				notify.warning("Invitation created but email delivery failed. Share the invitation link manually.");
			} else {
				notify.success("Invitation sent successfully");
			}
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to send invitation:", err);
			notify.error(getErrorMessage(err));
		} finally {
			setIsInviting(false);
		}
	};
 
	const handleResendInvitation = async (invitation: TeamInvitation) => {
		Iif (!proId) return;
		try {
			await proApi.resendInvitation(proId, invitation.id);
			notify.success(`Invitation resent to ${invitation.email || invitation.phone}`);
		} catch (err: unknown) {
			console.error("Failed to resend invitation:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleCancelInvitation = async (invitation: TeamInvitation) => {
		Iif (!proId) return;
		if (!(await confirm({ title: "Cancel invitation", description: `Cancel invitation for ${invitation.email || invitation.phone}?`, confirmLabel: "Yes, cancel", cancelLabel: "Keep", variant: "destructive" }))) return;
		try {
			await proApi.cancelInvitation(proId, invitation.id);
			notify.success("Invitation cancelled");
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to cancel invitation:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleUpdateRole = async (
		member: TeamMember,
		newRole: "manager" | "staff",
	) => {
		Iif (!proId) return;
		try {
			await proApi.updateTeamMember(proId, member.id, {
				role: newRole,
			});
			notify.success("Role updated successfully");
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to update role:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleDeactivateMember = async (member: TeamMember) => {
		Iif (!proId) return;
		if (
			!(await confirm({
				title: "Deactivate member",
				description: `Deactivate ${member.user?.name || "this member"}? They will lose access to the team.`,
				confirmLabel: "Deactivate",
				variant: "destructive",
			}))
		) {
			return;
		}
		try {
			await proApi.deactivateTeamMember(proId, member.id);
			notify.success("Team member deactivated");
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to deactivate team member:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleReactivateMember = async (member: TeamMember) => {
		Iif (!proId) return;
		try {
			await proApi.reactivateTeamMember(proId, member.id);
			notify.success("Team member reactivated");
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to reactivate team member:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleRemoveMember = async (member: TeamMember) => {
		Iif (!proId) return;
		if (
			!(await confirm({
				title: "Remove member",
				description: `Permanently remove ${member.user?.name || "this member"} from the team? This cannot be undone.`,
				confirmLabel: "Remove",
				variant: "destructive",
			}))
		) {
			return;
		}
		try {
			await proApi.removeTeamMember(proId, member.id);
			notify.success("Team member removed");
			invalidateTeam();
		} catch (err: unknown) {
			console.error("Failed to remove team member:", err);
			notify.error(getErrorMessage(err));
		}
	};
 
	// Build unified table rows from members + invitations
	const tableRows = useMemo<TeamTableRow[]>(() => {
		const memberRows: TeamTableRow[] = teamMembers.map((m) => ({
			key: `member-${m.id}`,
			name: m.user?.name || "Unknown User",
			email: m.user?.email || "No email",
			role: m.role,
			status: m.isActive ? "active" as const : "inactive" as const,
			dateCreated: m.dateCreated,
			sortableName: (m.user?.name || "").toLowerCase(),
			source: { type: "member" as const, data: m },
		}));
		const inviteRows: TeamTableRow[] = invitations.map((inv) => {
			const contact = inv.email || inv.phone || "Unknown";
			return {
				key: `invite-${inv.id}`,
				name: contact,
				email: contact,
				role: inv.role,
				status: "pending" as const,
				dateCreated: inv.dateCreated,
				sortableName: contact.toLowerCase(),
				source: { type: "invitation" as const, data: inv },
			};
		});
		return [...memberRows, ...inviteRows];
	}, [teamMembers, invitations]);
 
	// Counts for filter badges
	const statusCounts = useMemo(() => ({
		active: tableRows.filter((r) => r.status === "active").length,
		inactive: tableRows.filter((r) => r.status === "inactive").length,
		pending: tableRows.filter((r) => r.status === "pending").length,
	}), [tableRows]);
 
	const roleCounts = useMemo(() => ({
		owner: tableRows.filter((r) => r.role === "owner").length,
		manager: tableRows.filter((r) => r.role === "manager").length,
		staff: tableRows.filter((r) => r.role === "staff").length,
	}), [tableRows]);
 
	// Filter rows
	const filteredRows = useMemo(() => {
		let result = tableRows;
		Eif (statusFilter.size > 0) {
			result = result.filter((r) => statusFilter.has(r.status));
		}
		if (roleFilter.size > 0) {
			result = result.filter((r) => roleFilter.has(r.role));
		}
		if (searchQuery.trim()) {
			const q = searchQuery.toLowerCase();
			result = result.filter(
				(r) => r.name.toLowerCase().includes(q) || r.email.toLowerCase().includes(q),
			);
		}
		return result;
	}, [tableRows, statusFilter, roleFilter, searchQuery]);
 
	// Sort
	const { sorted: sortedRows, sortKey, sortOrder, setSort } = useSortable(
		filteredRows,
		"dateCreated" as keyof TeamTableRow,
		"desc",
	);
 
	return (
		<div className="space-y-6">
			<StickyPageHeader>
				<div className="flex items-center justify-between w-full">
					<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2">
						<Users className="h-6 w-6" />
						Team Members
					</h1>
					{isOwner && (
						<Button size="sm" onClick={() => setShowInviteModal(true)}>
							<Mail className="h-4 w-4" />
							Invite Team Member
						</Button>
					)}
				</div>
			</StickyPageHeader>
 
			{membersLoading ? (
				<div className="space-y-3">
					{[1, 2, 3].map((i) => (
						<Skeleton key={i} className="h-12 w-full" />
					))}
				</div>
			) : tableRows.length === 0 ? (
				<EmptyState
					icon={Users}
					title="No team members yet."
					description={isOwner ? 'Click "Invite Team Member" to add someone.' : undefined}
				/>
			) : (
				<>
					{/* Search, Filters & Sort */}
					<div className="space-y-2 sm:space-y-0 sm:flex sm:flex-wrap sm:items-center sm:gap-2">
						<div className="relative w-full sm:min-w-0 sm:flex-1 sm:basis-40 sm:max-w-sm">
							<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
							<Input
								placeholder="Filter team..."
								value={searchQuery}
								onChange={(e) => setSearchQuery(e.target.value)}
								className="pl-10"
							/>
						</div>
						<div className="flex items-center gap-2">
						<FacetedFilter
							title="Status"
							options={[
								{ value: "active", label: "Active", count: statusCounts.active },
								{ value: "inactive", label: "Inactive", count: statusCounts.inactive },
								{ value: "pending", label: "Pending", count: statusCounts.pending },
							]}
							selected={statusFilter}
							onChange={setStatusFilter}
						/>
						<FacetedFilter
							title="Role"
							options={[
								{ value: "owner", label: "Owner", count: roleCounts.owner },
								{ value: "manager", label: "Manager", count: roleCounts.manager },
								{ value: "staff", label: "Staff", count: roleCounts.staff },
							]}
							selected={roleFilter}
							onChange={setRoleFilter}
						/>
						<div className="relative shrink-0">
							<ArrowUpDown className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-foreground-subtle pointer-events-none" />
							<select
								value={`${sortKey as string}-${sortOrder}`}
								onChange={(e) => {
									const [key, order] = e.target.value.split("-");
									setSort(key as keyof TeamTableRow, order as "asc" | "desc");
								}}
								className="h-9 rounded-md border border-dashed border-border-default bg-transparent pl-8 pr-3 text-sm font-medium cursor-pointer hover:bg-background-muted transition-colors focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500 appearance-none"
							>
								<option value="dateCreated-desc">Newest</option>
								<option value="dateCreated-asc">Oldest</option>
								<option value="sortableName-asc">Name A→Z</option>
								<option value="sortableName-desc">Name Z→A</option>
							</select>
						</div>
						</div>
					</div>
 
					{/* List */}
					{sortedRows.length === 0 ? (
						<div className="py-12 text-center text-foreground-muted">
							No team members match your {searchQuery.trim() ? "search" : "filter"}.
						</div>
					) : (
						<div data-testid="team-list">
							{/* Mobile card view */}
							<div className="sm:hidden space-y-3">
								{sortedRows.map((row) => (
									<div
										key={row.key}
										className={`bg-background-elevated rounded-lg border border-border-default p-4 ${row.status === "inactive" ? "opacity-60" : ""}`}
									>
										{/* Top row: avatar + name/email + overflow menu */}
										<div className="flex items-center gap-3">
											<div className={`h-10 w-10 rounded-full flex items-center justify-center shrink-0 ${
												row.source.type === "invitation"
													? "bg-amber-100 dark:bg-amber-900/30"
													: row.status === "active"
														? "bg-info-light"
														: "bg-background-muted"
											}`}>
												{row.source.type === "invitation" ? (
													(row.source.data as TeamInvitation).phone && !(row.source.data as TeamInvitation).email
														? <Phone className="h-4 w-4 text-amber-600 dark:text-amber-400" />
														: <Mail className="h-4 w-4 text-amber-600 dark:text-amber-400" />
												) : (
													<span className={`text-sm font-medium ${
														row.status === "active" ? "text-info" : "text-foreground-muted"
													}`}>
														{(row.source.type === "member" ? row.source.data.user?.name?.charAt(0).toUpperCase() : row.name.charAt(0).toUpperCase()) || "?"}
													</span>
												)}
											</div>
											<div className="flex-1 min-w-0">
												<p className="font-semibold text-sm text-foreground-default truncate">
													{row.name}
												</p>
												{row.source.type === "member" && (
													<p className="text-xs text-foreground-muted truncate">{row.email}</p>
												)}
											</div>
											{/* Mobile overflow menu */}
											{isOwner && row.source.type === "invitation" && (
												<DropdownMenu
													trigger={
														<span className="inline-flex items-center justify-center p-2 rounded-md hover:bg-background-muted transition-colors">
															<MoreVertical className="h-4 w-4" />
														</span>
													}
													items={[
														{
															label: "Resend invitation",
															icon: <RefreshCw className="h-4 w-4" />,
															onClick: () => handleResendInvitation(row.source.data as TeamInvitation),
														},
														{
															label: "Cancel invitation",
															icon: <X className="h-4 w-4" />,
															onClick: () => handleCancelInvitation(row.source.data as TeamInvitation),
															variant: "destructive" as const,
														},
													]}
												/>
											)}
											{isOwner && row.source.type === "member" && row.source.data.role !== "owner" && (
												<DropdownMenu
													trigger={
														<span className="inline-flex items-center justify-center p-2 rounded-md hover:bg-background-muted transition-colors">
															<MoreVertical className="h-4 w-4" />
														</span>
													}
													items={[
														...(row.status === "active"
															? [{
																	label: "Deactivate",
																	icon: <UserX className="h-4 w-4" />,
																	onClick: () => handleDeactivateMember(row.source.data as TeamMember),
																}]
															: [{
																	label: "Reactivate",
																	icon: <UserCheck className="h-4 w-4" />,
																	onClick: () => handleReactivateMember(row.source.data as TeamMember),
																}]),
														{
															label: "Remove",
															icon: <Trash2 className="h-4 w-4" />,
															onClick: () => handleRemoveMember(row.source.data as TeamMember),
															variant: "destructive" as const,
														},
													]}
												/>
											)}
										</div>
										{/* Bottom row: role badge + status badge + date */}
										<div className="flex items-center gap-2 mt-3 flex-wrap">
											{isOwner && row.source.type === "member" && row.source.data.role !== "owner" && row.status === "active" ? (
												<select
													value={row.source.data.role}
													onChange={(e) =>
														handleUpdateRole(row.source.data as TeamMember, e.target.value as "manager" | "staff")
													}
													className={`text-xs font-medium rounded-full px-3 py-1 border-0 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-500/40 shrink-0 ${getRoleBadgeColor(row.role)}`}
												>
													<option value="manager">Manager</option>
													<option value="staff">Staff</option>
												</select>
											) : (
												<span className={`px-3 py-1 text-xs font-medium rounded-full shrink-0 ${getRoleBadgeColor(row.role)}`}>
													{row.role}
												</span>
											)}
											<span className={`px-2 py-0.5 text-xs font-medium rounded-full shrink-0 ${getStatusBadge(row.status)}`}>
												{row.status === "active" ? "Active" : row.status === "inactive" ? "Inactive" : "Pending"}
											</span>
											<span className="text-xs text-foreground-subtle ml-auto whitespace-nowrap">
												{row.source.type === "invitation" ? (
													<span className="flex items-center gap-1">
														<Clock className="h-3.5 w-3.5" />
														Expires {new Date(row.source.data.expiresAt).toLocaleDateString()}
													</span>
												) : (
													new Date(row.dateCreated).toLocaleDateString()
												)}
											</span>
										</div>
									</div>
								))}
							</div>
 
							{/* Desktop row view */}
							<div className="hidden sm:block space-y-2">
								{sortedRows.map((row) => (
									<div
										key={row.key}
										className={`flex items-center gap-4 p-3 border border-border-default rounded-lg bg-background-elevated hover:bg-background-muted/50 transition-colors ${row.status === "inactive" ? "opacity-60" : ""}`}
									>
										{/* Avatar */}
										<div className={`h-10 w-10 rounded-full flex items-center justify-center shrink-0 ${
											row.source.type === "invitation"
												? "bg-amber-100 dark:bg-amber-900/30"
												: row.status === "active"
													? "bg-info-light"
													: "bg-background-muted"
										}`}>
											{row.source.type === "invitation" ? (
												(row.source.data as TeamInvitation).phone && !(row.source.data as TeamInvitation).email
													? <Phone className="h-4 w-4 text-amber-600 dark:text-amber-400" />
													: <Mail className="h-4 w-4 text-amber-600 dark:text-amber-400" />
											) : (
												<span className={`text-sm font-medium ${
													row.status === "active" ? "text-info" : "text-foreground-muted"
												}`}>
													{(row.source.type === "member" ? row.source.data.user?.name?.charAt(0).toUpperCase() : row.name.charAt(0).toUpperCase()) || "?"}
												</span>
											)}
										</div>
 
										{/* Name + badges */}
										<div className="flex items-center gap-2 min-w-0 flex-1 flex-wrap">
											<div className="min-w-0">
												<p className="font-semibold text-sm text-foreground-default truncate">
													{row.name}
												</p>
												{row.source.type === "member" && (
													<p className="text-xs text-foreground-muted truncate">{row.email}</p>
												)}
											</div>
											{isOwner && row.source.type === "member" && row.source.data.role !== "owner" && row.status === "active" ? (
												<select
													value={row.source.data.role}
													onChange={(e) =>
														handleUpdateRole(row.source.data as TeamMember, e.target.value as "manager" | "staff")
													}
													className={`text-xs font-medium rounded-full px-3 py-1 border-0 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-500/40 shrink-0 ${getRoleBadgeColor(row.role)}`}
												>
													<option value="manager">Manager</option>
													<option value="staff">Staff</option>
												</select>
											) : (
												<span className={`px-3 py-1 text-xs font-medium rounded-full shrink-0 ${getRoleBadgeColor(row.role)}`}>
													{row.role}
												</span>
											)}
											<span className={`px-2 py-0.5 text-xs font-medium rounded-full shrink-0 ${getStatusBadge(row.status)}`}>
												{row.status === "active" ? "Active" : row.status === "inactive" ? "Inactive" : "Pending"}
											</span>
										</div>
 
										{/* Date */}
										<span className="text-xs text-foreground-subtle shrink-0 whitespace-nowrap">
											{row.source.type === "invitation" ? (
												<span className="flex items-center gap-1">
													<Clock className="h-3.5 w-3.5" />
													Expires {new Date(row.source.data.expiresAt).toLocaleDateString()}
												</span>
											) : (
												new Date(row.dateCreated).toLocaleDateString()
											)}
										</span>
 
										{/* Action buttons */}
										{isOwner && (
											<div className="flex items-center gap-1 shrink-0">
												{row.source.type === "invitation" ? (
													<>
														<button
															type="button"
															onClick={() => handleResendInvitation(row.source.data as TeamInvitation)}
															className="flex items-center gap-1 p-1.5 text-info hover:bg-info-light rounded"
															title="Resend invitation"
														>
															<RefreshCw className="h-4 w-4" />
															<span className="text-xs">Resend</span>
														</button>
														<button
															type="button"
															onClick={() => handleCancelInvitation(row.source.data as TeamInvitation)}
															className="flex items-center gap-1 p-1.5 text-error hover:bg-error-light rounded"
															title="Cancel invitation"
														>
															<X className="h-4 w-4" />
															<span className="text-xs">Cancel</span>
														</button>
													</>
												) : row.source.data.role !== "owner" ? (
													<>
														{row.status === "active" ? (
															<button
																type="button"
																onClick={() => handleDeactivateMember(row.source.data as TeamMember)}
																className="p-1.5 text-warning hover:bg-warning-light rounded"
																title="Deactivate member"
															>
																<UserX className="h-4 w-4" />
															</button>
														) : (
															<button
																type="button"
																onClick={() => handleReactivateMember(row.source.data as TeamMember)}
																className="p-1.5 text-success hover:bg-success-light rounded"
																title="Reactivate member"
															>
																<UserCheck className="h-4 w-4" />
															</button>
														)}
														<button
															type="button"
															onClick={() => handleRemoveMember(row.source.data as TeamMember)}
															className="p-1.5 text-error hover:bg-error-light rounded"
															title="Remove permanently"
														>
															<Trash2 className="h-4 w-4" />
														</button>
													</>
												) : null}
											</div>
										)}
									</div>
								))}
							</div>
						</div>
					)}
				</>
			)}
 
			{/* Role Descriptions - Collapsible */}
			{!membersLoading && (
				<RolePermissionsHelp />
			)}
 
			{/* Invite Member Modal */}
			<InviteMemberModal
				isOpen={showInviteModal}
				contact={newInvite.contact}
				role={newInvite.role}
				isInviting={isInviting}
				contactCheck={contactCheck}
				isChecking={isChecking}
				onClose={() => {
					setShowInviteModal(false);
					setNewInvite({ contact: "", role: "staff" });
					setContactCheck(null);
					if (checkTimer.current) clearTimeout(checkTimer.current);
				}}
				onContactChange={handleContactChange}
				onRoleChange={(role) => setNewInvite({ ...newInvite, role })}
				onSubmit={handleInviteMember}
			/>
			{confirmDialog}
		</div>
	);
}
 
function RolePermissionsHelp() {
	const [isOpen, setIsOpen] = useState(false);
 
	return (
		<div className="flex flex-col items-start">
			<button
				type="button"
				onClick={() => setIsOpen(!isOpen)}
				className="inline-flex items-center gap-1.5 text-sm text-foreground-muted hover:text-foreground-default transition-colors"
			>
				<HelpCircle className="h-4 w-4" />
				{isOpen ? "Hide role permissions" : "View role permissions"}
			</button>
			{isOpen && (
				<div className="mt-3 w-full rounded-lg border border-border-default bg-background-elevated p-4 space-y-3">
					<div className="flex items-start gap-3">
						<span className="inline-block px-3 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300">
							Owner
						</span>
						<p className="text-sm text-foreground-muted">
							Full access. Can manage team members, projects, inquiries, and profile settings.
						</p>
					</div>
					<div className="flex items-start gap-3">
						<span className="inline-block px-3 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
							Manager
						</span>
						<p className="text-sm text-foreground-muted">
							Can manage projects and inquiries. Cannot manage team members or critical settings.
						</p>
					</div>
					<div className="flex items-start gap-3">
						<span className="inline-block px-3 py-1 text-xs font-medium rounded-full bg-background-subtle text-foreground-default">
							Staff
						</span>
						<p className="text-sm text-foreground-muted">
							Read-only access to projects and inquiries.
						</p>
					</div>
				</div>
			)}
		</div>
	);
}