"use client";

import { useEffect, useMemo, useState } from "react";
import {
  AlertTriangle,
  Bot,
  BriefcaseBusiness,
  Calendar,
  CheckSquare,
  Copy,
  Crown,
  FileText,
  Flag,
  FolderKanban,
  GitPullRequestArrow,
  Link2,
  LockKeyhole,
  Mail,
  MessageSquareText,
  Plus,
  Shield,
  Sparkles,
  Users2,
} from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { useTeams } from "@/hooks/use-teams";
import { useTeamAudit } from "@/hooks/use-team-audit";
import {
  PERMISSION_LEVELS,
  TEAM_RESOURCES,
  useTeamPermissions,
} from "@/hooks/use-team-permissions";
import { useWorkspaceStore } from "@/stores/workspace-store";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Select } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import { EmptyState } from "@/components/ui/empty-state";
import { Skeleton } from "@/components/ui/skeleton";
import { Modal } from "@/components/ui/modal";
import type { PermissionLevel, TeamResource, TeamRole } from "@/types";
import { formatDate, formatRelativeDate, isTaskDeadlineOverdue } from "@/lib/utils";

const MEMBER_ROLES: Array<{ value: Exclude<TeamRole, "owner">; label: string }> = [
  { value: "admin", label: "Admin" },
  { value: "member", label: "Member" },
  { value: "viewer", label: "Viewer" },
];

interface WorkspaceStats {
  projects: number;
  openTasks: number;
  notes: number;
  events: number;
  pendingReviews: number;
  pendingApprovals: number;
  unassignedTasks: number;
}

interface TeamWorkloadRow {
  userId: string;
  name: string;
  title: string;
  avatarUrl: string | null;
  openTasks: number;
  overdueTasks: number;
  pendingReviews: number;
  changesRequestedForMe: number;
  completedThisWeek: number;
}

interface ReviewQueueItem {
  id: string;
  title: string;
  review_status: "pending_review" | "changes_requested";
  review_requested_at: string | null;
  deadline: string | null;
  reviewerId: string | null;
  reviewerName: string;
  assigneeId: string | null;
  assigneeName: string;
}

interface ProjectApprovalQueueItem {
  id: string;
  name: string;
  approval_status: "pending_approval" | "changes_requested";
  approval_requested_at: string | null;
  approverName: string;
  ownerName: string;
  health: "on_track" | "at_risk" | "stuck";
}

type TeamWorkspaceTab =
  | "overview"
  | "members"
  | "invites"
  | "access"
  | "activity";

type ActivityFilter = "all" | "members" | "invites" | "permissions" | "comments";

function getRoleBadge(role: TeamRole | null) {
  if (role === "owner") return "border-amber-500/25 bg-amber-500/[0.08] text-amber-300";
  if (role === "admin") return "border-sky-500/25 bg-sky-500/[0.08] text-sky-300";
  if (role === "viewer") return "border-white/[0.10] bg-white/[0.04] text-white/50";
  return "border-indigo-500/25 bg-indigo-500/[0.08] text-indigo-300";
}

// Shared surface tokens — keep Teams visually aligned with the Tasks hero design.
const CARD = "rounded-[20px] border border-white/[0.06] bg-white/[0.025]";
const SUBTLE_TILE =
  "rounded-xl border border-white/[0.05] bg-white/[0.02] p-3.5 transition-colors hover:bg-white/[0.04]";

function roleLabel(role: TeamRole | null) {
  if (role === "owner") return "Owner";
  if (role === "admin") return "Admin";
  if (role === "viewer") return "Viewer";
  return "Member";
}

const EMPTY_STATS: WorkspaceStats = {
  projects: 0,
  openTasks: 0,
  notes: 0,
  events: 0,
  pendingReviews: 0,
  pendingApprovals: 0,
  unassignedTasks: 0,
};

const PERMISSION_MATRIX_ROLES: TeamRole[] = ["owner", "admin", "member", "viewer"];

const RESOURCE_LABELS: Record<TeamResource, string> = {
  projects: "Projects",
  tasks: "Tasks",
  notes: "Notes",
  calendar: "Calendar",
  comments: "Comments",
  members: "Members",
};

const RESOURCE_HELP: Record<TeamResource, string> = {
  projects: "Shared projects, links, and project activity",
  tasks: "Tasks, subtasks, and assignee workflows",
  notes: "Notes, folders, and note metadata",
  calendar: "Events, participants, and scheduling",
  comments: "Discussion threads and moderation",
  members: "Invites, roles, titles, and access management",
};

const PERMISSION_LABELS: Record<PermissionLevel, string> = {
  none: "No access",
  view: "View",
  comment: "Comment",
  edit: "Edit",
  manage: "Manage",
};

const WORKSPACE_TAB_ICONS: Record<TeamWorkspaceTab, typeof Sparkles> = {
  overview: Sparkles,
  members: Users2,
  invites: Mail,
  access: LockKeyhole,
  activity: Shield,
};

const TAB_ACTIVE_CLASS = "border-indigo-500/30 bg-indigo-500/[0.10] text-indigo-300";
const TAB_ICON_ACTIVE_CLASS = "bg-indigo-500/15 text-indigo-300";
const TAB_COUNT_ACTIVE_CLASS = "bg-indigo-500/20 text-indigo-300";

const ACTIVITY_FILTER_OPTIONS: Array<{ id: ActivityFilter; label: string }> = [
  { id: "all", label: "All" },
  { id: "members", label: "Members" },
  { id: "invites", label: "Invites" },
  { id: "permissions", label: "Permissions" },
  { id: "comments", label: "Comments" },
];

const AUDIT_CATEGORY_LABELS: Record<Exclude<ActivityFilter, "all"> | "other", string> = {
  members: "Members",
  invites: "Invites",
  permissions: "Permissions",
  comments: "Comments",
  other: "Other",
};

function getAuditCategory(
  action: string
): Exclude<ActivityFilter, "all"> | "other" {
  if (action.startsWith("invite_")) return "invites";
  if (action === "permission_updated") return "permissions";
  if (action.startsWith("member_")) return "members";
  if (action.startsWith("comment_")) return "comments";
  return "other";
}

function describeAuditAction(action: string, details: Record<string, unknown>) {
  if (action === "member_role_changed") {
    return `Role changed from ${String(details.from_role || "unknown")} to ${String(details.to_role || "unknown")}`;
  }
  if (action === "member_title_changed") {
    return `Title updated to ${String(details.to_title || "not set")}`;
  }
  if (action === "task_status_changed") {
    return `Status moved from ${String(details.from_status || "unknown")} to ${String(details.to_status || "unknown")}`;
  }
  if (action === "invite_created" && details.delivery === "email_sent") {
    return "Invitation email was sent successfully";
  }
  if (action === "invite_created" && details.delivery === "stored_only") {
    return "Invite stored and link can be copied manually";
  }
  if (action === "comment_created") {
    return "New collaboration comment added";
  }
  if (action === "permission_updated") {
    return `${String(details.role || "role")} on ${String(details.resource || "resource")} changed to ${String(details.access_level || "unknown")}`;
  }
  if (action === "project_approval_requested") {
    return "Project approval was requested";
  }
  if (action === "project_approved") {
    return "Project was approved";
  }
  if (action === "project_changes_requested") {
    return "Project was sent back with requested changes";
  }
  if (action === "event_created") {
    return `Event created with ${String(details.participant_count || 0)} participants`;
  }
  if (action === "event_updated") {
    return `Event updated, now tracking ${String(details.participant_count || 0)} participants`;
  }
  return action.replaceAll("_", " ");
}

export default function TeamsPage() {
  const supabase = createClient();
  const router = useRouter();
  const searchParams = useSearchParams();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);
  const setActiveTeamId = useWorkspaceStore((state) => state.setActiveTeamId);

  const {
    teams,
    loading,
    activeTeam,
    activeMembers,
    activeInvitations,
    incomingInvitations,
    activeRole,
    userId,
    createTeam,
    updateTeam,
    inviteMember,
    acceptInvitation,
    declineInvitation,
    revokeInvitation,
    updateMemberRole,
    updateMemberTitle,
    removeMember,
  } = useTeams();
  const { entries: auditEntries, loading: auditLoading, refetch: refetchAudit } =
    useTeamAudit(activeTeam?.id || null);
  const {
    can: canAccessTeamResource,
    getPermissionForRole,
    updatePermission,
    loading: permissionsLoading,
  } = useTeamPermissions(activeTeam?.id || null);
  const canManageWorkspace = !!activeTeam && canAccessTeamResource("members", "manage");

  const [stats, setStats] = useState<WorkspaceStats>(EMPTY_STATS);
  const [statsLoading, setStatsLoading] = useState(true);
  const [workloadRows, setWorkloadRows] = useState<TeamWorkloadRow[]>([]);
  const [reviewQueue, setReviewQueue] = useState<ReviewQueueItem[]>([]);
  const [approvalQueue, setApprovalQueue] = useState<ProjectApprovalQueueItem[]>([]);
  const [teamModalMode, setTeamModalMode] = useState<"create" | "edit" | null>(
    null
  );
  const [teamName, setTeamName] = useState("");
  const [teamDescription, setTeamDescription] = useState("");
  const [teamSubmitting, setTeamSubmitting] = useState(false);
  const [teamError, setTeamError] = useState<string | null>(null);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] =
    useState<Exclude<TeamRole, "owner">>("member");
  const [inviteMessage, setInviteMessage] = useState("");
  const [inviteSubmitting, setInviteSubmitting] = useState(false);
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [inviteSuccess, setInviteSuccess] = useState<{
    email: string;
    inviteUrl: string;
    delivery: "email_sent" | "stored_only";
  } | null>(null);
  const [copiedInviteToken, setCopiedInviteToken] = useState<string | null>(null);
  const [savingMemberId, setSavingMemberId] = useState<string | null>(null);
  const [memberDraftTitles, setMemberDraftTitles] = useState<Record<string, string>>(
    {}
  );
  const [activeWorkspaceTab, setActiveWorkspaceTab] =
    useState<TeamWorkspaceTab>("overview");
  const [memberSearch, setMemberSearch] = useState("");
  const [inviteSearch, setInviteSearch] = useState("");
  const [activityFilter, setActivityFilter] = useState<ActivityFilter>("all");

  useEffect(() => {
    const shouldCreate = searchParams.get("create");
    if (shouldCreate !== "1") return;

    const nextParams = new URLSearchParams(searchParams.toString());
    nextParams.delete("create");
    const nextQuery = nextParams.toString();
    router.replace(nextQuery ? `/teams?${nextQuery}` : "/teams", { scroll: false });

    const timer = window.setTimeout(() => {
      setTeamModalMode("create");
      setTeamName("");
      setTeamDescription("");
      setTeamError(null);
    }, 0);

    return () => window.clearTimeout(timer);
  }, [router, searchParams]);

  const pendingInvitations = useMemo(
    () => activeInvitations.filter((invitation) => invitation.status === "pending"),
    [activeInvitations]
  );

  const filteredMembers = useMemo(() => {
    const query = memberSearch.trim().toLowerCase();
    if (!query) return activeMembers;

    return activeMembers.filter((member) =>
      [
        member.profile?.full_name,
        member.profile?.email,
        member.title,
        roleLabel(member.role),
      ].some((value) => value?.toLowerCase().includes(query))
    );
  }, [activeMembers, memberSearch]);

  const filteredInvitations = useMemo(() => {
    const query = inviteSearch.trim().toLowerCase();
    if (!query) return pendingInvitations;

    return pendingInvitations.filter((invitation) =>
      [invitation.email, roleLabel(invitation.role)].some((value) =>
        value?.toLowerCase().includes(query)
      )
    );
  }, [inviteSearch, pendingInvitations]);

  const filteredAuditEntries = useMemo(() => {
    if (activityFilter === "all") return auditEntries;
    return auditEntries.filter((entry) => getAuditCategory(entry.action) === activityFilter);
  }, [activityFilter, auditEntries]);

  const activityFilterCounts = useMemo(() => {
    return ACTIVITY_FILTER_OPTIONS.reduce<Record<ActivityFilter, number>>(
      (counts, option) => {
        counts[option.id] =
          option.id === "all"
            ? auditEntries.length
            : auditEntries.filter((entry) => getAuditCategory(entry.action) === option.id)
                .length;
        return counts;
      },
      {
        all: 0,
        members: 0,
        invites: 0,
        permissions: 0,
        comments: 0,
      }
    );
  }, [auditEntries]);

  const actionItemsByMember = useMemo(() => {
    const map = new Map<string, ReviewQueueItem[]>();
    for (const item of reviewQueue) {
      const ownerId =
        item.review_status === "pending_review" ? item.reviewerId : item.assigneeId;
      if (!ownerId) continue;
      const existing = map.get(ownerId);
      if (existing) {
        existing.push(item);
      } else {
        map.set(ownerId, [item]);
      }
    }
    return map;
  }, [reviewQueue]);

  useEffect(() => {
    const nextTitles: Record<string, string> = {};
    activeMembers.forEach((member) => {
      nextTitles[member.user_id] = member.title || "";
    });
    setMemberDraftTitles(nextTitles);
  }, [activeMembers]);

  useEffect(() => {
    setActiveWorkspaceTab("overview");
    setMemberSearch("");
    setInviteSearch("");
    setActivityFilter("all");
  }, [activeTeamId]);

  useEffect(() => {
    const inviteToken = searchParams.get("invite");
    if (!inviteToken) return;

    const matchingInvitation = incomingInvitations.find(
      (invitation) => invitation.token === inviteToken
    );

    if (matchingInvitation && activeTeamId !== matchingInvitation.team_id) {
      setActiveTeamId(matchingInvitation.team_id);
    }
  }, [activeTeamId, incomingInvitations, searchParams, setActiveTeamId]);

  useEffect(() => {
    if (!initialized) return;

    async function fetchWorkspaceStats() {
      setStatsLoading(true);

      const projectsQuery = activeTeamId
        ? supabase
            .from("projects")
            .select(
              "id, name, user_id, approver_id, approval_status, approval_requested_at, health",
              { count: "exact" }
            )
            .eq("team_id", activeTeamId)
        : supabase
            .from("projects")
            .select(
              "id, name, user_id, approver_id, approval_status, approval_requested_at, health",
              { count: "exact" }
            )
            .is("team_id", null);
      const tasksQuery = activeTeamId
        ? supabase
            .from("tasks")
            .select(
              "id, title, status, deadline, completed_at, assignee_id, reviewer_id, review_status, review_requested_at"
            )
            .eq("team_id", activeTeamId)
            .is("parent_task_id", null)
        : supabase
            .from("tasks")
            .select(
              "id, title, status, deadline, completed_at, assignee_id, reviewer_id, review_status, review_requested_at"
            )
            .is("team_id", null)
            .is("parent_task_id", null);

      const notesQuery = activeTeamId
        ? supabase.from("notes").select("id", { count: "exact", head: true }).eq("team_id", activeTeamId)
        : supabase.from("notes").select("id", { count: "exact", head: true }).is("team_id", null);

      const eventsQuery = activeTeamId
        ? supabase.from("events").select("id", { count: "exact", head: true }).eq("team_id", activeTeamId)
        : supabase.from("events").select("id", { count: "exact", head: true }).is("team_id", null);

      const [projectsRes, tasksRes, notesRes, eventsRes] = await Promise.all([
        projectsQuery,
        tasksQuery,
        notesQuery,
        eventsQuery,
      ]);

      const taskRows =
        (tasksRes.data || []) as Array<{
          id: string;
          title: string;
          status: string;
          deadline: string | null;
          completed_at: string | null;
          assignee_id: string | null;
          reviewer_id: string | null;
          review_status:
            | "not_required"
            | "pending_review"
            | "changes_requested"
            | "approved";
          review_requested_at: string | null;
        }>;
      const projectRows =
        (projectsRes.data || []) as Array<{
          id: string;
          name: string;
          user_id: string;
          approver_id: string | null;
          approval_status:
            | "not_required"
            | "pending_approval"
            | "changes_requested"
            | "approved";
          approval_requested_at: string | null;
          health: "on_track" | "at_risk" | "stuck";
        }>;

      const openTaskRows = taskRows.filter((task) =>
        ["todo", "in_progress"].includes(task.status)
      );
      const weekAgo = new Date();
      weekAgo.setDate(weekAgo.getDate() - 7);
      const memberLookup = new Map(
        activeMembers.map((member) => [
          member.user_id,
          {
            name:
              member.profile?.full_name || member.profile?.email || "Team member",
            title: member.title || roleLabel(member.role),
          },
        ])
      );

      const nextWorkloadRows = activeMembers
        .map((member) => {
          const memberOpenTasks = openTaskRows.filter(
            (task) => task.assignee_id === member.user_id
          );
          const memberCompletedThisWeek = taskRows.filter(
            (task) =>
              task.assignee_id === member.user_id &&
              task.status === "done" &&
              !!task.completed_at &&
              new Date(task.completed_at) >= weekAgo
          ).length;

          return {
            userId: member.user_id,
            name:
              member.profile?.full_name || member.profile?.email || "Team member",
            title: member.title || roleLabel(member.role),
            avatarUrl: member.profile?.avatar_url || null,
            openTasks: memberOpenTasks.length,
            overdueTasks: memberOpenTasks.filter(
              (task) => !!task.deadline && isTaskDeadlineOverdue(task.deadline)
            ).length,
            pendingReviews: taskRows.filter(
              (task) =>
                task.reviewer_id === member.user_id &&
                task.review_status === "pending_review"
            ).length,
            changesRequestedForMe: taskRows.filter(
              (task) =>
                task.assignee_id === member.user_id &&
                task.review_status === "changes_requested"
            ).length,
            completedThisWeek: memberCompletedThisWeek,
          };
        })
        .sort(
          (a, b) =>
            b.pendingReviews +
            b.changesRequestedForMe -
            (a.pendingReviews + a.changesRequestedForMe) ||
            b.openTasks - a.openTasks ||
            b.overdueTasks - a.overdueTasks
        );

      const nextReviewQueue: ReviewQueueItem[] = taskRows
        .filter(
          (task) =>
            task.review_status === "pending_review" ||
            task.review_status === "changes_requested"
        )
        .sort((a, b) => {
          const aTime = a.review_requested_at
            ? new Date(a.review_requested_at).getTime()
            : 0;
          const bTime = b.review_requested_at
            ? new Date(b.review_requested_at).getTime()
            : 0;
          return bTime - aTime;
        })
        .map((task) => ({
          id: task.id,
          title: task.title,
          review_status:
            task.review_status === "changes_requested"
              ? "changes_requested"
              : "pending_review",
          review_requested_at: task.review_requested_at,
          deadline: task.deadline,
          reviewerId: task.reviewer_id,
          reviewerName: task.reviewer_id
            ? memberLookup.get(task.reviewer_id)?.name || "Reviewer"
            : "No reviewer",
          assigneeId: task.assignee_id,
          assigneeName: task.assignee_id
            ? memberLookup.get(task.assignee_id)?.name || "Assignee"
            : "Unassigned",
        }));

      const nextApprovalQueue: ProjectApprovalQueueItem[] = projectRows
        .filter(
          (project) =>
            project.approval_status === "pending_approval" ||
            project.approval_status === "changes_requested"
        )
        .sort((a, b) => {
          const aTime = a.approval_requested_at
            ? new Date(a.approval_requested_at).getTime()
            : 0;
          const bTime = b.approval_requested_at
            ? new Date(b.approval_requested_at).getTime()
            : 0;
          return bTime - aTime;
        })
        .map((project) => ({
          id: project.id,
          name: project.name,
          approval_status:
            project.approval_status === "changes_requested"
              ? "changes_requested"
              : "pending_approval",
          approval_requested_at: project.approval_requested_at,
          approverName: project.approver_id
            ? memberLookup.get(project.approver_id)?.name || "Approver"
            : "No approver",
          ownerName: memberLookup.get(project.user_id)?.name || "Project owner",
          health: project.health,
        }));

      setStats({
        projects: projectsRes.count || 0,
        openTasks: openTaskRows.length,
        notes: notesRes.count || 0,
        events: eventsRes.count || 0,
        pendingReviews: nextReviewQueue.filter(
          (task) => task.review_status === "pending_review"
        ).length,
        pendingApprovals: nextApprovalQueue.filter(
          (project) => project.approval_status === "pending_approval"
        ).length,
        unassignedTasks: openTaskRows.filter((task) => !task.assignee_id).length,
      });
      setWorkloadRows(nextWorkloadRows);
      setReviewQueue(nextReviewQueue);
      setApprovalQueue(nextApprovalQueue);
      setStatsLoading(false);
    }

    void fetchWorkspaceStats();
  }, [activeMembers, activeTeamId, initialized, supabase]);

  function openCreateModal() {
    setTeamModalMode("create");
    setTeamName("");
    setTeamDescription("");
    setTeamError(null);
  }

  function openWeeklySummary() {
    const prompt = activeTeam
      ? `Give me a weekly summary for the team workspace "${activeTeam.name}". Use the active workspace context and highlight wins, blockers, overdue work, and what the team should focus on next.`
      : "Give me a weekly summary for my personal workspace. Highlight wins, blockers, overdue work, and what I should focus on next.";

    router.push(`/ai?prompt=${encodeURIComponent(prompt)}`);
  }

  function openEditModal() {
    if (!activeTeam) return;
    setTeamModalMode("edit");
    setTeamName(activeTeam.name);
    setTeamDescription(activeTeam.description || "");
    setTeamError(null);
  }

  async function handleSubmitTeam(e: React.FormEvent) {
    e.preventDefault();
    if (!teamName.trim() || teamSubmitting) return;

    setTeamSubmitting(true);
    setTeamError(null);

    try {
      if (teamModalMode === "edit" && activeTeam) {
        await updateTeam(activeTeam.id, {
          name: teamName,
          description: teamDescription,
        });
        await refetchAudit();
      } else {
        await createTeam({
          name: teamName,
          description: teamDescription,
        });
      }
      setTeamModalMode(null);
    } catch (error) {
      setTeamError(
        error instanceof Error ? error.message : "Team could not be saved."
      );
    } finally {
      setTeamSubmitting(false);
    }
  }

  async function handleInviteSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!activeTeam || !inviteEmail.trim() || inviteSubmitting) return;

    setInviteSubmitting(true);
    setInviteError(null);

    try {
      const result = await inviteMember(activeTeam.id, {
        email: inviteEmail,
        role: inviteRole,
        message: inviteMessage,
      });
      setInviteSuccess({
        email: inviteEmail.trim(),
        inviteUrl: result.inviteUrl,
        delivery: result.delivery,
      });
      setInviteEmail("");
      setInviteRole("member");
      setInviteMessage("");
      await refetchAudit();
    } catch (error) {
      setInviteError(
        error instanceof Error ? error.message : "Invitation could not be sent."
      );
    } finally {
      setInviteSubmitting(false);
    }
  }

  async function handleSaveMemberTitle(memberId: string) {
    if (!activeTeam) return;

    const originalTitle =
      activeMembers.find((member) => member.user_id === memberId)?.title || "";
    const nextTitle = memberDraftTitles[memberId] || "";

    if (originalTitle === nextTitle) return;

    setSavingMemberId(memberId);
    try {
      await updateMemberTitle(activeTeam.id, memberId, nextTitle);
      await refetchAudit();
    } finally {
      setSavingMemberId(null);
    }
  }

  async function handleCopyInviteLink(url: string, token?: string) {
    await navigator.clipboard.writeText(url);
    setCopiedInviteToken(token || "last");
    window.setTimeout(() => setCopiedInviteToken(null), 1500);
  }

  const statCards = [
    {
      label: activeTeam ? "Projects" : "Private projects",
      value: stats.projects,
      icon: FolderKanban,
    },
    {
      label: "Open tasks",
      value: stats.openTasks,
      icon: CheckSquare,
    },
    {
      label: activeTeam ? "Shared notes" : "Notes",
      value: stats.notes,
      icon: FileText,
    },
    {
      label: "Events",
      value: stats.events,
      icon: Calendar,
    },
    {
      label: "Reviews",
      value: stats.pendingReviews,
      icon: GitPullRequestArrow,
    },
    {
      label: "Approvals",
      value: stats.pendingApprovals,
      icon: FolderKanban,
    },
    {
      label: "Unassigned",
      value: stats.unassignedTasks,
      icon: AlertTriangle,
    },
  ];

  const workspaceTabs: Array<{
    id: TeamWorkspaceTab;
    label: string;
    count?: number;
  }> = [
    { id: "overview", label: "Overview" },
    { id: "members", label: "Members", count: activeMembers.length },
    { id: "invites", label: "Invites", count: pendingInvitations.length },
    { id: "access", label: "Access" },
    { id: "activity", label: "Activity", count: auditEntries.length },
  ];

  return (
    <div className="space-y-6">
      {/* Hero header */}
      <div
        className="relative overflow-hidden rounded-[28px] border border-white/[0.07] bg-[#0e0c15] p-8"
        style={{
          backgroundImage:
            "radial-gradient(ellipse at 15% -20%, rgba(99,102,241,0.18) 0%, transparent 55%), radial-gradient(ellipse at 85% 110%, rgba(16,185,129,0.07) 0%, transparent 50%)",
        }}
      >
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div>
            <div className="mb-3 inline-flex items-center gap-2 rounded-full border border-indigo-500/20 bg-indigo-500/[0.08] px-3 py-1">
              <Users2 className="h-3.5 w-3.5 text-indigo-400" />
              <span className="text-[10px] font-bold uppercase tracking-[0.18em] text-indigo-300">Teams</span>
            </div>
            <h1 className="text-[28px] font-bold tracking-tight text-white">
              {activeTeam ? activeTeam.name : "Personal workspace"}
            </h1>
            <p className="mt-1 text-[14px] text-white/40">
              Build real shared workspaces with members, roles, invites, shared
              projects, shared notes, and a shared calendar.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={openWeeklySummary}
              className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.08] bg-white/[0.03] px-3.5 py-2 text-[13px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
            >
              <Bot className="h-3.5 w-3.5" />
              AI weekly summary
            </button>
            {activeTeam && (
              <button
                onClick={() => router.push("/chat?scope=team")}
                className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.08] bg-white/[0.03] px-3.5 py-2 text-[13px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
              >
                <MessageSquareText className="h-3.5 w-3.5" />
                Open team chat
              </button>
            )}
            {activeTeam && canManageWorkspace && (
              <button
                onClick={openEditModal}
                className="inline-flex items-center gap-1.5 rounded-xl border border-white/[0.08] bg-white/[0.03] px-3.5 py-2 text-[13px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
              >
                Edit team
              </button>
            )}
            <button
              onClick={openCreateModal}
              className="inline-flex items-center gap-1.5 rounded-xl border border-indigo-500/30 bg-indigo-500/[0.15] px-3.5 py-2 text-[13px] font-bold text-indigo-200 transition-all hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]"
            >
              <Plus className="h-3.5 w-3.5" />
              New team
            </button>
          </div>
        </div>
      </div>

      {/* Incoming invitations banner */}
      {incomingInvitations.length > 0 && (
        <div className="rounded-[20px] border border-indigo-500/20 bg-indigo-500/[0.06] p-5">
          <div className="mb-1 flex items-center gap-2">
            <Mail className="h-4 w-4 text-indigo-400" />
            <p className="font-semibold text-white">Pending invitations</p>
          </div>
          <p className="mb-4 text-[13px] text-white/40">
            Join a shared workspace and it becomes available immediately in
            your workspace switcher.
          </p>
          <div className="space-y-3">
            {incomingInvitations.map((invitation) => {
              const team = teams.find((item) => item.id === invitation.team_id);

              return (
                <div
                  key={invitation.id}
                  className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/[0.06] bg-white/[0.03] p-4"
                >
                  <div>
                    <p className="font-medium text-white/80">{team?.name || "Shared workspace"}</p>
                    <p className="text-[13px] text-white/40">
                      Role: {roleLabel(invitation.role)}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        void (async () => {
                          await declineInvitation(invitation.id);
                          await refetchAudit();
                        })();
                      }}
                      className="rounded-xl border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-[12px] font-semibold text-white/60 transition-all hover:border-white/[0.14] hover:text-white"
                    >
                      Decline
                    </button>
                    <button
                      onClick={() => {
                        void (async () => {
                          await acceptInvitation(invitation.id);
                          await refetchAudit();
                        })();
                      }}
                      className="rounded-xl border border-indigo-500/30 bg-indigo-500/[0.15] px-3 py-1.5 text-[12px] font-bold text-indigo-200 transition-all hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]"
                    >
                      Accept
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Workspace selector grid */}
      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <button
          onClick={() => setActiveTeamId(null)}
          className={`group rounded-[18px] border p-5 text-left transition-all duration-150 ${
            activeTeamId === null
              ? "border-indigo-500/25 bg-indigo-500/[0.06]"
              : "border-white/[0.06] bg-white/[0.02] hover:border-white/[0.10] hover:bg-white/[0.04]"
          }`}
        >
          <div className="mb-4 flex items-center justify-between">
            <div className={`flex h-10 w-10 items-center justify-center rounded-xl transition-colors ${
              activeTeamId === null
                ? "bg-indigo-500/15 text-indigo-300"
                : "bg-white/[0.05] text-white/40 group-hover:bg-indigo-500/10 group-hover:text-indigo-400"
            }`}>
              <BriefcaseBusiness className="h-5 w-5" />
            </div>
            {activeTeamId === null && (
              <span className="rounded-full border border-indigo-500/25 bg-indigo-500/[0.10] px-2.5 py-0.5 text-[11px] font-semibold text-indigo-300">
                Active
              </span>
            )}
          </div>
          <h2 className={`font-semibold transition-colors ${activeTeamId === null ? "text-white" : "text-white/70 group-hover:text-white"}`}>
            Personal workspace
          </h2>
          <p className="mt-1 text-[13px] text-white/40">
            Keep your private notes, solo projects, and personal planning here.
          </p>
        </button>

        {teams.map((team) => (
          <button
            key={team.id}
            onClick={() => setActiveTeamId(team.id)}
            className={`group rounded-[18px] border p-5 text-left transition-all duration-150 ${
              activeTeamId === team.id
                ? "border-indigo-500/25 bg-indigo-500/[0.06]"
                : "border-white/[0.06] bg-white/[0.02] hover:border-white/[0.10] hover:bg-white/[0.04]"
            }`}
          >
            <div className="mb-4 flex items-center justify-between">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl transition-colors ${
                activeTeamId === team.id
                  ? "bg-indigo-500/15 text-indigo-300"
                  : "bg-white/[0.05] text-white/40 group-hover:bg-indigo-500/10 group-hover:text-indigo-400"
              }`}>
                <Users2 className="h-5 w-5" />
              </div>
              {activeTeamId === team.id && (
                <span className="rounded-full border border-indigo-500/25 bg-indigo-500/[0.10] px-2.5 py-0.5 text-[11px] font-semibold text-indigo-300">
                  Active
                </span>
              )}
            </div>
            <div className="space-y-1">
              <h2 className={`font-semibold transition-colors ${activeTeamId === team.id ? "text-white" : "text-white/70 group-hover:text-white"}`}>
                {team.name}
              </h2>
              <p className="line-clamp-2 text-[13px] text-white/40">
                {team.description || "Shared workspace for coordinated execution."}
              </p>
            </div>
          </button>
        ))}
      </div>

      {loading ? (
        <div className="grid gap-4 lg:grid-cols-2">
          <Skeleton className="h-72 rounded-2xl" />
          <Skeleton className="h-72 rounded-2xl" />
        </div>
      ) : activeTeam ? (
        <>
          {/* Role + stat strip */}
          <div className={CARD}>
            <div className="flex flex-wrap items-center gap-2 p-5 pb-4">
              <Badge variant="outline" className={getRoleBadge(activeRole)}>
                {roleLabel(activeRole)}
              </Badge>
              <p className="text-[13px] text-white/40">
                {activeTeam.description || "No description yet."} · Created {formatDate(activeTeam.created_at)}
              </p>
            </div>

            {/* Stat cards row */}
            <div className="border-t border-white/[0.06] p-5 pt-4">
              <div className="grid gap-3 grid-cols-2 sm:grid-cols-4">
                {statCards.map((card) => (
                  <div key={card.label} className={SUBTLE_TILE}>
                    <div className="mb-3 flex items-center gap-1.5 text-white/35">
                      <card.icon className="h-3.5 w-3.5 shrink-0" />
                      <span className="text-[10px] font-bold uppercase tracking-[0.14em]">
                        {card.label}
                      </span>
                    </div>
                    <p className="text-2xl font-bold text-white">
                      {statsLoading ? (
                        <span className="text-white/25">...</span>
                      ) : (
                        card.value
                      )}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Tab navigation */}
          <div className="sticky top-0 z-20 -mx-1 rounded-2xl border border-white/[0.06] bg-[#1a1c22]/95 p-1.5 backdrop-blur supports-[backdrop-filter]:bg-[#1a1c22]/80">
            <div className="flex flex-wrap gap-1.5">
              {workspaceTabs.map((tab) => {
                const Icon = WORKSPACE_TAB_ICONS[tab.id];
                const isActive = activeWorkspaceTab === tab.id;

                return (
                  <button
                    key={tab.id}
                    type="button"
                    onClick={() => setActiveWorkspaceTab(tab.id)}
                    className={`inline-flex items-center gap-2 rounded-xl border px-3 py-1.5 text-sm font-medium transition-colors duration-150 ${
                      isActive
                        ? TAB_ACTIVE_CLASS
                        : "border-transparent text-white/40 hover:bg-white/[0.04] hover:text-white/70"
                    }`}
                  >
                    <span
                      className={`flex h-6 w-6 items-center justify-center rounded-lg transition-colors ${
                        isActive ? TAB_ICON_ACTIVE_CLASS : "bg-white/[0.04] text-white/40"
                      }`}
                    >
                      <Icon className="h-3.5 w-3.5" />
                    </span>
                    <span>{tab.label}</span>
                    {typeof tab.count === "number" && (
                      <span
                        className={`rounded-full px-1.5 py-0.5 text-[11px] font-semibold transition-colors ${
                          isActive
                            ? TAB_COUNT_ACTIVE_CLASS
                            : "bg-white/[0.06] text-white/40"
                        }`}
                      >
                        {tab.count}
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Overview tab */}
          {activeWorkspaceTab === "overview" && (
            <div className="grid gap-4 xl:grid-cols-2">
              {/* Workspace snapshot */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="font-semibold text-white">Workspace snapshot</h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    A quick view of team size, invite pipeline, and your current control level.
                  </p>
                </div>
                <div className="p-5 space-y-4">
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4">
                      <p className="text-[10px] font-medium uppercase tracking-[0.16em] text-white/40">
                        Members
                      </p>
                      <p className="mt-2 text-3xl font-bold text-white">{activeMembers.length}</p>
                    </div>
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4">
                      <p className="text-[10px] font-medium uppercase tracking-[0.16em] text-white/40">
                        Pending invites
                      </p>
                      <p className="mt-2 text-3xl font-bold text-white">{pendingInvitations.length}</p>
                    </div>
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4">
                      <p className="text-[10px] font-medium uppercase tracking-[0.16em] text-white/40">
                        Review queue
                      </p>
                      <p className="mt-2 text-3xl font-bold text-white">
                        {statsLoading ? <span className="text-white/25">...</span> : stats.pendingReviews}
                      </p>
                    </div>
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4">
                      <p className="text-[10px] font-medium uppercase tracking-[0.16em] text-white/40">
                        Your role
                      </p>
                      <div className="mt-2">
                        <Badge variant="outline" className={getRoleBadge(activeRole)}>
                          {roleLabel(activeRole)}
                        </Badge>
                      </div>
                    </div>
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 sm:col-span-2">
                      <p className="text-[10px] font-medium uppercase tracking-[0.16em] text-white/40">
                        Access control
                      </p>
                      <p className="mt-2 text-sm font-medium text-white/70">
                        {canManageWorkspace ? "You can manage members and permissions." : "Managed by owners or admins."}
                      </p>
                    </div>
                  </div>
                  <div className="rounded-xl border border-white/[0.05] bg-white/[0.015] p-4 text-[13px] text-white/40">
                    Team created {formatDate(activeTeam.created_at)}. Use the tabs above to go deep on members, invites, rights, and audit activity.
                  </div>
                  <div className="rounded-xl border border-indigo-500/20 bg-indigo-500/[0.06] p-4">
                    <div className="flex flex-wrap items-center justify-between gap-3">
                      <div>
                        <p className="text-sm font-semibold text-white/80">AI weekly briefing</p>
                        <p className="mt-1 text-[13px] text-white/40">
                          Generate a team-level summary with wins, blockers, overdue work, and next focus areas.
                        </p>
                      </div>
                      <Button size="sm" onClick={openWeeklySummary} className="border border-indigo-500/30 bg-indigo-500/[0.15] text-indigo-200 hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]">
                        <Bot className="h-4 w-4" />
                        Open in AI
                      </Button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Shared execution stack */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="flex items-center gap-2 font-semibold text-white">
                    <Sparkles className="h-4 w-4 text-indigo-400" />
                    Shared execution stack
                  </h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    Everything this workspace already controls together.
                  </p>
                </div>
                <div className="p-5 space-y-2">
                  {[
                    { icon: Shield, text: "Role-based access with owner, admin, member, and viewer levels" },
                    { icon: CheckSquare, text: "Shared tasks with assignees and team-level ownership" },
                    { icon: FileText, text: "Shared notes, folders, project links, and activity" },
                    { icon: Calendar, text: "Shared events and shared deadlines inside the calendar" },
                  ].map(({ icon: Icon, text }) => (
                    <div key={text} className="flex items-center gap-3 rounded-xl border border-white/[0.05] bg-white/[0.03] p-3.5 transition-colors hover:bg-white/[0.05]">
                      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-indigo-500/10">
                        <Icon className="h-4 w-4 text-indigo-400" />
                      </div>
                      <span className="text-sm text-white/70">{text}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Invite pipeline */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="font-semibold text-white">Invite pipeline</h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    See whether people still need to accept access into this workspace.
                  </p>
                </div>
                <div className="p-5 space-y-3">
                  {pendingInvitations.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      No pending invitations right now.
                    </div>
                  ) : (
                    pendingInvitations.slice(0, 3).map((invitation) => (
                      <div
                        key={invitation.id}
                        className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4"
                      >
                        <p className="font-medium text-white/80">{invitation.email}</p>
                        <p className="mt-1 text-[13px] text-white/40">
                          {roleLabel(invitation.role)} access
                        </p>
                        {invitation.sent_at && (
                          <p className="mt-1 text-xs text-white/25">
                            Email sent {formatRelativeDate(invitation.sent_at)}
                          </p>
                        )}
                      </div>
                    ))
                  )}
                </div>
              </div>

              {/* People & reviews */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025] xl:col-span-2">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="flex items-center gap-2 font-semibold text-white">
                    <Users2 className="h-4 w-4 text-indigo-400" />
                    People &amp; reviews
                  </h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    Workload per teammate, and whose turn it is to take the lead on a review.
                  </p>
                </div>
                <div className="p-5 space-y-3">
                  {workloadRows.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      Assign a few tasks and this view will show where execution — and review ownership — is concentrated.
                    </div>
                  ) : (
                    workloadRows.slice(0, 8).map((member) => {
                      const actionItems = actionItemsByMember.get(member.userId) || [];
                      const actionCount = member.pendingReviews + member.changesRequestedForMe;
                      const isCurrentUser = member.userId === userId;

                      return (
                        <div
                          key={member.userId}
                          className={`rounded-xl border p-4 transition-colors hover:bg-white/[0.05] ${
                            actionCount > 0
                              ? "border-amber-500/20 bg-amber-500/[0.05]"
                              : "border-white/[0.06] bg-white/[0.03]"
                          }`}
                        >
                          <div className="flex flex-wrap items-center justify-between gap-3">
                            <div className="flex items-center gap-3">
                              <Avatar src={member.avatarUrl} name={member.name} />
                              <div>
                                <p className="font-medium text-white/80">
                                  {member.name}
                                  {isCurrentUser && (
                                    <span className="ml-1.5 text-xs font-normal text-white/40">(You)</span>
                                  )}
                                </p>
                                <p className="text-[13px] text-white/40">{member.title}</p>
                              </div>
                            </div>
                            <div className="text-right">
                              <p className="text-2xl font-bold text-white">{member.openTasks}</p>
                              <p className="text-[10px] uppercase tracking-[0.14em] text-white/25">
                                Open tasks
                              </p>
                            </div>
                          </div>
                          <div className="mt-3 grid gap-2 sm:grid-cols-3">
                            <div className="rounded-lg border border-white/[0.05] bg-white/[0.03] px-3 py-2 text-sm">
                              <span className="text-white/40">Overdue</span>
                              <div className="mt-1 font-semibold text-white/80">{member.overdueTasks}</div>
                            </div>
                            <div className="rounded-lg border border-white/[0.05] bg-white/[0.03] px-3 py-2 text-sm">
                              <span className="text-white/40">Reviews on them</span>
                              <div className="mt-1 font-semibold text-white/80">{actionCount}</div>
                            </div>
                            <div className="rounded-lg border border-white/[0.05] bg-white/[0.03] px-3 py-2 text-sm">
                              <span className="text-white/40">Done this week</span>
                              <div className="mt-1 font-semibold text-white/80">{member.completedThisWeek}</div>
                            </div>
                          </div>

                          {actionCount > 0 && (
                            <div className="mt-3 space-y-2 rounded-lg border border-amber-500/20 bg-amber-500/[0.06] p-3">
                              <p className="flex items-center gap-1.5 text-xs font-semibold text-amber-400">
                                <Flag className="h-3 w-3" />
                                {isCurrentUser
                                  ? "Waiting on you — take the lead"
                                  : `Waiting on ${member.name} — needs to take the lead`}
                              </p>
                              <div className="space-y-1.5">
                                {actionItems.slice(0, 3).map((item) => (
                                  <div
                                    key={item.id}
                                    className="flex items-center justify-between gap-2 text-xs text-white/50"
                                  >
                                    <span className="truncate">{item.title}</span>
                                    <Badge
                                      variant="outline"
                                      className={
                                        item.review_status === "changes_requested"
                                          ? "border-red-500/20 bg-red-500/10 text-red-400"
                                          : "border-amber-500/20 bg-amber-500/10 text-amber-400"
                                      }
                                    >
                                      {item.review_status === "changes_requested"
                                        ? "Changes requested"
                                        : "Needs review"}
                                    </Badge>
                                  </div>
                                ))}
                                {actionItems.length > 3 && (
                                  <p className="text-xs text-white/25">
                                    +{actionItems.length - 3} more
                                  </p>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      );
                    })
                  )}
                  <div className="flex justify-end">
                    <Button variant="outline" size="sm" onClick={() => router.push("/tasks")} className="border-white/[0.06] bg-white/[0.03] text-white/50 hover:bg-white/[0.06] hover:text-white">
                      <CheckSquare className="h-4 w-4" />
                      Open tasks
                    </Button>
                  </div>
                </div>
              </div>

              {/* Project sign-off queue */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="flex items-center gap-2 font-semibold text-white">
                    <FolderKanban className="h-4 w-4 text-amber-400" />
                    Project sign-off queue
                  </h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    Keep launches and stakeholder handoffs moving by surfacing every project that is waiting for sign-off.
                  </p>
                </div>
                <div className="p-5 space-y-3">
                  {approvalQueue.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      No projects are waiting for approval right now.
                    </div>
                  ) : (
                    approvalQueue.slice(0, 6).map((project) => (
                      <div
                        key={project.id}
                        className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 transition-all hover:bg-white/[0.05]"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <p className="font-medium text-white/80">{project.name}</p>
                            <p className="mt-1 text-[13px] text-white/40">
                              Approver: {project.approverName}
                            </p>
                            <p className="text-[13px] text-white/40">
                              Owner: {project.ownerName}
                            </p>
                          </div>
                          <Badge
                            variant="outline"
                            className={
                              project.approval_status === "changes_requested"
                                ? "border-red-500/25 bg-red-500/[0.08] text-red-300"
                                : "border-amber-500/25 bg-amber-500/[0.08] text-amber-300"
                            }
                          >
                            {project.approval_status === "changes_requested"
                              ? "Changes requested"
                              : "Pending approval"}
                          </Badge>
                        </div>
                        <div className="mt-3 flex flex-wrap items-center gap-3 text-xs text-white/25">
                          {project.approval_requested_at && (
                            <span>
                              Requested {formatRelativeDate(project.approval_requested_at)}
                            </span>
                          )}
                          <span>Health: {project.health.replaceAll("_", " ")}</span>
                        </div>
                      </div>
                    ))
                  )}
                  <div className="flex justify-end">
                    <Button variant="outline" size="sm" onClick={() => router.push("/projects")} className="border-white/[0.06] bg-white/[0.03] text-white/50 hover:bg-white/[0.06] hover:text-white">
                      <FolderKanban className="h-4 w-4" />
                      Open projects
                    </Button>
                  </div>
                </div>
              </div>

              {/* Recent activity */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="font-semibold text-white">Recent activity</h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    The latest changes across invites, permissions, collaboration, and membership.
                  </p>
                </div>
                <div className="p-5 space-y-3">
                  {auditLoading ? (
                    <p className="text-sm text-white/25">Loading activity...</p>
                  ) : auditEntries.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      No audit entries yet.
                    </div>
                  ) : (
                    auditEntries.slice(0, 4).map((entry) => (
                      <div
                        key={entry.id}
                        className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4"
                      >
                        <div className="flex items-center gap-2">
                          <p className="font-medium text-white/80">
                            {entry.actor?.full_name || entry.actor?.email || "System"}
                          </p>
                          <Badge variant="outline" className="border-white/[0.08] bg-white/[0.04] text-white/50">
                            {entry.entity_type}
                          </Badge>
                        </div>
                        <p className="mt-1 text-sm text-white/70">{entry.title}</p>
                        <p className="mt-1 text-[13px] text-white/40">
                          {describeAuditAction(entry.action, entry.details)}
                        </p>
                        <p className="mt-2 text-xs text-white/25">
                          {formatRelativeDate(entry.created_at)}
                        </p>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Members tab */}
          {activeWorkspaceTab === "members" && (
            <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
              <div className="border-b border-white/[0.06] p-5">
                <h3 className="font-semibold text-white">Members</h3>
                <p className="mt-0.5 text-[13px] text-white/40">
                  Assign tasks, define roles, and keep your execution team aligned.
                </p>
              </div>
              <div className="p-5 space-y-4">
                <div className="flex flex-col gap-3 rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 sm:flex-row sm:items-center sm:justify-between">
                  <div className="space-y-0.5">
                    <p className="text-sm font-medium text-white/80">Member directory</p>
                    <p className="text-[13px] text-white/40">
                      {filteredMembers.length} of {activeMembers.length} members shown
                    </p>
                  </div>
                  <Input
                    value={memberSearch}
                    onChange={(e) => setMemberSearch(e.target.value)}
                    placeholder="Search members, roles, or titles..."
                    className="w-full sm:max-w-sm"
                  />
                </div>

                {filteredMembers.length === 0 ? (
                  <div className="rounded-xl border border-dashed border-white/[0.08] p-6 text-sm text-white/25">
                    No members matched your search.
                  </div>
                ) : (
                  filteredMembers.map((member) => {
                  const isOwner = member.role === "owner";
                  const isCurrentUser = member.user_id === userId;
                  const canEditMember =
                    canManageWorkspace && !isOwner && member.user_id !== activeTeam.owner_id;
                  const actionCount = actionItemsByMember.get(member.user_id)?.length || 0;

                  return (
                    <div
                      key={member.user_id}
                      className={`rounded-xl border p-4 transition-colors hover:bg-white/[0.05] ${
                        actionCount > 0
                          ? "border-amber-500/20 bg-amber-500/[0.05]"
                          : "border-white/[0.06] bg-white/[0.03]"
                      }`}
                    >
                      <div className="flex flex-wrap items-center justify-between gap-3">
                        <div className="flex items-center gap-3">
                          <Avatar
                            src={member.profile?.avatar_url}
                            name={
                              member.profile?.full_name ||
                              member.profile?.email ||
                              "Team member"
                            }
                          />
                          <div>
                            <div className="flex items-center gap-2">
                              <p className="font-medium text-white/80">
                                {member.profile?.full_name ||
                                  member.profile?.email ||
                                  "Unknown member"}
                              </p>
                              {isOwner && (
                                <Badge variant="outline" className="border-amber-500/25 bg-amber-500/[0.08] text-amber-300">
                                  <Crown className="mr-1 h-3 w-3" />
                                  Owner
                                </Badge>
                              )}
                              {isCurrentUser && (
                                <Badge variant="outline" className="border-white/[0.10] bg-white/[0.05] text-white/50">
                                  You
                                </Badge>
                              )}
                              {actionCount > 0 && (
                                <Badge variant="outline" className="border-amber-500/25 bg-amber-500/[0.08] text-amber-300">
                                  <Flag className="mr-1 h-3 w-3" />
                                  {actionCount === 1
                                    ? "Take the lead on 1 review"
                                    : `Take the lead on ${actionCount} reviews`}
                                </Badge>
                              )}
                            </div>
                            <p className="text-[13px] text-white/40">
                              {member.profile?.email || "No email"}
                            </p>
                          </div>
                        </div>

                        <div className="flex items-center gap-2">
                          {canEditMember ? (
                            <Select
                              value={member.role}
                              onChange={(e) =>
                                void (async () => {
                                  await updateMemberRole(
                                    activeTeam.id,
                                    member.user_id,
                                    e.target.value as Exclude<TeamRole, "owner">
                                  );
                                  await refetchAudit();
                                })()
                              }
                            >
                              {MEMBER_ROLES.map((role) => (
                                <option key={role.value} value={role.value}>
                                  {role.label}
                                </option>
                              ))}
                            </Select>
                          ) : (
                            <Badge variant="outline" className={getRoleBadge(member.role)}>
                              {roleLabel(member.role)}
                            </Badge>
                          )}

                          {!isOwner && canManageWorkspace && (
                            <Button
                              size="sm"
                              variant="ghost"
                              className="text-red-500 hover:bg-red-500/10 hover:text-red-400"
                              onClick={() => {
                                void (async () => {
                                  await removeMember(activeTeam.id, member.user_id);
                                  await refetchAudit();
                                })();
                              }}
                            >
                              {isCurrentUser ? "Leave" : "Remove"}
                            </Button>
                          )}
                        </div>
                      </div>

                      <div className="mt-3 flex items-center gap-2">
                        <Input
                          value={memberDraftTitles[member.user_id] || ""}
                          onChange={(e) =>
                            setMemberDraftTitles((prev) => ({
                              ...prev,
                              [member.user_id]: e.target.value,
                            }))
                          }
                          onBlur={() => {
                            if (canManageWorkspace) {
                              void handleSaveMemberTitle(member.user_id);
                            }
                          }}
                          disabled={!canManageWorkspace}
                          placeholder="Role title, e.g. Product Lead"
                        />
                        {savingMemberId === member.user_id && (
                          <span className="text-xs text-white/25">Saving...</span>
                        )}
                      </div>
                    </div>
                  );
                  })
                )}
              </div>
            </div>
          )}

          {/* Invites tab */}
          {activeWorkspaceTab === "invites" && (
            <div className="grid gap-4 xl:grid-cols-[1.05fr_0.95fr]">
              {/* Invite form */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="flex items-center gap-2 font-semibold text-white">
                    <Mail className="h-4 w-4 text-sky-400" />
                    Invite people
                  </h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    Add teammates by email and give them the right level of access.
                  </p>
                </div>
                <div className="p-5">
                  {canManageWorkspace ? (
                    <form onSubmit={handleInviteSubmit} className="space-y-3">
                      <Input
                        type="email"
                        value={inviteEmail}
                        onChange={(e) => setInviteEmail(e.target.value)}
                        placeholder="teammate@company.com"
                        required
                      />
                      <Select
                        value={inviteRole}
                        onChange={(e) =>
                          setInviteRole(
                            e.target.value as Exclude<TeamRole, "owner">
                          )
                        }
                      >
                        {MEMBER_ROLES.map((role) => (
                          <option key={role.value} value={role.value}>
                            {role.label}
                          </option>
                        ))}
                      </Select>
                      <Textarea
                        value={inviteMessage}
                        onChange={(e) => setInviteMessage(e.target.value)}
                        placeholder="Optional message for the invite email or invite card..."
                        className="min-h-[84px]"
                      />
                      {inviteError && (
                        <p className="text-sm text-red-400">{inviteError}</p>
                      )}
                      {inviteSuccess && (
                        <div className="rounded-xl border border-indigo-500/20 bg-indigo-500/[0.06] p-4">
                          <p className="font-semibold text-indigo-300">
                            Invite ready for {inviteSuccess.email}
                          </p>
                          <p className="mt-1 text-[13px] text-white/40">
                            {inviteSuccess.delivery === "email_sent"
                              ? "The invitation email was sent."
                              : "Email delivery is not configured, but the invite link is ready to copy."}
                          </p>
                          <div className="mt-3 flex flex-wrap gap-2">
                            <Button
                              size="sm"
                              variant="outline"
                              className="border-white/[0.06] bg-white/[0.03] text-white/70 hover:bg-white/[0.06] hover:text-white"
                              onClick={() =>
                                void handleCopyInviteLink(inviteSuccess.inviteUrl)
                              }
                            >
                              <Copy className="h-4 w-4" />
                              Copy invite link
                            </Button>
                            <a
                              href={inviteSuccess.inviteUrl}
                              className="inline-flex items-center gap-2 rounded-md border border-white/[0.06] bg-white/[0.03] px-3 py-2 text-xs text-white/40 transition-colors hover:bg-white/[0.06] hover:text-white/70"
                            >
                              <Link2 className="h-3.5 w-3.5" />
                              Open invite
                            </a>
                          </div>
                        </div>
                      )}
                      <Button
                        type="submit"
                        className="w-full border border-indigo-500/30 bg-indigo-500/[0.15] text-indigo-200 hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]"
                        disabled={!inviteEmail.trim() || inviteSubmitting}
                      >
                        {inviteSubmitting ? "Sending..." : "Send invitation"}
                      </Button>
                    </form>
                  ) : (
                    <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 text-[13px] text-white/40">
                      Only owners and admins can invite new members into this workspace.
                    </div>
                  )}
                </div>
              </div>

              {/* Open invitations list */}
              <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
                <div className="border-b border-white/[0.06] p-5">
                  <h3 className="font-semibold text-white">Open invitations</h3>
                  <p className="mt-0.5 text-[13px] text-white/40">
                    Keep track of everyone who still needs to join the workspace.
                  </p>
                </div>
                <div className="p-5 space-y-3">
                  <div className="flex flex-col gap-3 rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="space-y-0.5">
                      <p className="text-sm font-medium text-white/80">Invitation queue</p>
                      <p className="text-[13px] text-white/40">
                        {filteredInvitations.length} of {pendingInvitations.length} invites shown
                      </p>
                    </div>
                    <Input
                      value={inviteSearch}
                      onChange={(e) => setInviteSearch(e.target.value)}
                      placeholder="Search pending invites..."
                      className="w-full sm:max-w-sm"
                    />
                  </div>

                  {pendingInvitations.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      No pending invitations right now.
                    </div>
                  ) : filteredInvitations.length === 0 ? (
                    <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                      No invites matched your search.
                    </div>
                  ) : (
                    filteredInvitations.map((invitation) => (
                      <div
                        key={invitation.id}
                        className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 transition-all hover:bg-white/[0.05]"
                      >
                        <div>
                          <p className="font-medium text-white/80">{invitation.email}</p>
                          <p className="text-[13px] text-white/40">
                            {roleLabel(invitation.role)} access
                          </p>
                          {invitation.sent_at && (
                            <p className="text-xs text-white/25">
                              Email sent {formatRelativeDate(invitation.sent_at)}
                            </p>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            className="border-white/[0.06] bg-white/[0.03] text-white/70 hover:bg-white/[0.06] hover:text-white"
                            onClick={() =>
                              void handleCopyInviteLink(
                                `${window.location.origin}/teams?invite=${invitation.token}`,
                                invitation.token
                              )
                            }
                          >
                            <Copy className="h-4 w-4" />
                            {copiedInviteToken === invitation.token ? "Copied" : "Copy link"}
                          </Button>
                          {canManageWorkspace && (
                            <Button
                              size="sm"
                              variant="ghost"
                              className="text-red-500 hover:bg-red-500/10 hover:text-red-400"
                              onClick={() => {
                                void (async () => {
                                  await revokeInvitation(invitation.id);
                                  await refetchAudit();
                                })();
                              }}
                            >
                              Revoke
                            </Button>
                          )}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Access tab */}
          {activeWorkspaceTab === "access" && (
            <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
              <div className="border-b border-white/[0.06] p-5">
                <h3 className="flex items-center gap-2 font-semibold text-white">
                  <LockKeyhole className="h-4 w-4 text-amber-400" />
                  Rights matrix
                </h3>
                <p className="mt-0.5 text-[13px] text-white/40">
                  Tune exactly what each team role can view, comment on, edit, or manage.
                </p>
              </div>
              <div className="p-5">
                {!canManageWorkspace ? (
                  <div className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 text-[13px] text-white/40">
                    Only roles with member-management access can change the team rights matrix.
                  </div>
                ) : permissionsLoading ? (
                  <p className="text-sm text-white/25">Loading permissions...</p>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="min-w-[860px] w-full text-sm">
                      <thead>
                        <tr className="border-b border-white/[0.06]">
                          <th className="px-3 py-3 text-left font-semibold text-white/70">
                            Resource
                          </th>
                          {PERMISSION_MATRIX_ROLES.map((role) => (
                            <th
                              key={role}
                              className="px-3 py-3 text-left font-semibold text-white/70"
                            >
                              {roleLabel(role)}
                            </th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {TEAM_RESOURCES.map((resource) => (
                          <tr key={resource} className="border-b border-white/[0.04] align-top transition-colors hover:bg-white/[0.02]">
                            <td className="px-3 py-3.5">
                              <p className="font-medium text-white/80">{RESOURCE_LABELS[resource]}</p>
                              <p className="mt-1 max-w-xs text-xs text-white/40">
                                {RESOURCE_HELP[resource]}
                              </p>
                            </td>
                            {PERMISSION_MATRIX_ROLES.map((role) => (
                              <td key={`${resource}-${role}`} className="px-3 py-3.5">
                                {role === "owner" ? (
                                  <Badge variant="outline" className="border-indigo-500/25 bg-indigo-500/[0.08] text-indigo-300">
                                    Manage
                                  </Badge>
                                ) : (
                                  <Select
                                    value={getPermissionForRole(role, resource)}
                                    onChange={(e) =>
                                      void (async () => {
                                        await updatePermission(
                                          role,
                                          resource,
                                          e.target.value as PermissionLevel
                                        );
                                        await refetchAudit();
                                      })()
                                    }
                                  >
                                    {PERMISSION_LEVELS.map((level) => (
                                      <option key={level} value={level}>
                                        {PERMISSION_LABELS[level]}
                                      </option>
                                    ))}
                                  </Select>
                                )}
                              </td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Activity tab */}
          {activeWorkspaceTab === "activity" && (
            <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
              <div className="border-b border-white/[0.06] p-5">
                <h3 className="font-semibold text-white">Audit log</h3>
                <p className="mt-0.5 text-[13px] text-white/40">
                  A running record of invitations, membership changes, collaboration,
                  and workspace execution.
                </p>
              </div>
              <div className="p-5 space-y-4">
                {/* Activity filter pills */}
                <div className="flex flex-wrap gap-2">
                  {ACTIVITY_FILTER_OPTIONS.map((option) => {
                    const isActive = activityFilter === option.id;
                    return (
                      <button
                        key={option.id}
                        type="button"
                        onClick={() => setActivityFilter(option.id)}
                        className={`inline-flex items-center gap-2 rounded-full px-3.5 py-1.5 text-sm font-medium transition-all duration-200 ${
                          isActive
                            ? "border border-indigo-500/30 bg-indigo-500/[0.10] text-indigo-300"
                            : "border border-white/[0.06] bg-white/[0.03] text-white/40 hover:bg-white/[0.06] hover:text-white/70"
                        }`}
                      >
                        <span>{option.label}</span>
                        <span
                          className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${
                            isActive
                              ? "bg-indigo-500/20 text-indigo-300"
                              : "bg-white/[0.06] text-white/25"
                          }`}
                        >
                          {activityFilterCounts[option.id]}
                        </span>
                      </button>
                    );
                  })}
                </div>

                {auditLoading ? (
                  <p className="text-sm text-white/25">Loading audit log...</p>
                ) : filteredAuditEntries.length === 0 ? (
                  <div className="rounded-xl border border-dashed border-white/[0.08] p-4 text-sm text-white/25">
                    {activityFilter === "all"
                      ? "No audit entries yet."
                      : `No ${activityFilter} activity yet.`}
                  </div>
                ) : (
                  <div className="space-y-0">
                    {filteredAuditEntries.map((entry, index) => {
                      const category = getAuditCategory(entry.action);

                      return (
                        <div
                          key={entry.id}
                          className="relative flex gap-4"
                        >
                          {/* Timeline line */}
                          {index < filteredAuditEntries.length - 1 && (
                            <div className="absolute left-[18px] top-10 h-full w-px bg-white/[0.06]" />
                          )}
                          {/* Timeline dot */}
                          <div className="mt-4 flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04]">
                            <Shield className="h-3.5 w-3.5 text-white/40" />
                          </div>
                          <div className="mb-4 min-w-0 flex-1 rounded-xl border border-white/[0.06] bg-white/[0.03] p-4">
                            <div className="flex flex-wrap items-start justify-between gap-2">
                              <div className="flex flex-wrap items-center gap-2">
                                <p className="font-medium text-white/80">
                                  {entry.actor?.full_name || entry.actor?.email || "System"}
                                </p>
                                <Badge variant="outline" className="border-white/[0.08] bg-white/[0.04] text-white/40">
                                  {entry.entity_type}
                                </Badge>
                                <Badge variant="outline" className="border-white/[0.06] bg-white/[0.03] text-white/25">
                                  {AUDIT_CATEGORY_LABELS[category]}
                                </Badge>
                              </div>
                              <p
                                className="shrink-0 text-xs text-white/25"
                                title={formatDate(entry.created_at)}
                              >
                                {formatRelativeDate(entry.created_at)}
                              </p>
                            </div>
                            <p className="mt-1.5 text-sm text-white/70">{entry.title}</p>
                            <p className="mt-1 text-[13px] text-white/40">
                              {describeAuditAction(entry.action, entry.details)}
                            </p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          )}
        </>
      ) : teams.length === 0 ? (
        <EmptyState
          icon={<Users2 className="h-10 w-10" />}
          title="No teams yet"
          description="Create your first shared workspace to invite people, assign work, and collaborate on projects, notes, and calendars."
          action={
            <Button onClick={openCreateModal} className="border border-indigo-500/30 bg-indigo-500/[0.15] text-indigo-200 hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]">
              <Plus className="h-4 w-4" />
              Create team
            </Button>
          }
        />
      ) : (
        <div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
          {/* Personal workspace stats */}
          <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
            <div className="border-b border-white/[0.06] p-5">
              <h3 className="font-semibold text-white">Personal workspace active</h3>
              <p className="mt-0.5 text-[13px] text-white/40">
                You are currently working privately. Switch to a team card above
                whenever you want shared projects, shared notes, shared tasks,
                and shared calendar access.
              </p>
            </div>
            <div className="p-5">
              <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                {statCards.map((card) => (
                  <div
                    key={card.label}
                    className="rounded-xl border border-white/[0.06] bg-white/[0.03] p-4 transition-all hover:bg-white/[0.05]"
                  >
                    <div className="mb-3 flex items-center gap-1.5 text-white/35">
                      <card.icon className="h-3.5 w-3.5 shrink-0" />
                      <span className="text-[10px] font-bold uppercase tracking-[0.14em]">
                        {card.label}
                      </span>
                    </div>
                    <p className="text-3xl font-bold text-white">
                      {statsLoading ? <span className="text-white/25">...</span> : card.value}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* What teams unlock */}
          <div className="rounded-[20px] border border-white/[0.06] bg-white/[0.025]">
            <div className="border-b border-white/[0.06] p-5">
              <h3 className="font-semibold text-white">What teams unlock</h3>
              <p className="mt-0.5 text-[13px] text-white/40">
                Shared workspaces are already wired into the rest of the app.
              </p>
            </div>
            <div className="p-5 space-y-2.5">
              {[
                "Assign tasks directly to teammates and manage roles per workspace.",
                "Collaborate on shared notes, folders, projects, project links, and project activity.",
                "Use one switch to move between private execution and team execution.",
              ].map((text) => (
                <div key={text} className="rounded-xl border border-white/[0.05] bg-white/[0.03] p-4 text-[13px] text-white/50 transition-colors hover:bg-white/[0.05] hover:text-white/70">
                  {text}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {teamModalMode && (
        <Modal
          open={!!teamModalMode}
          onClose={() => setTeamModalMode(null)}
          title={teamModalMode === "edit" ? "Edit team" : "Create team"}
          className="max-w-lg"
        >
          <form onSubmit={handleSubmitTeam} className="space-y-4">
            <Input
              value={teamName}
              onChange={(e) => setTeamName(e.target.value)}
              placeholder="Team name"
              autoFocus
              required
            />
            <Textarea
              value={teamDescription}
              onChange={(e) => setTeamDescription(e.target.value)}
              placeholder="What does this team own together?"
              className="min-h-[100px]"
            />
            {teamError && (
              <p className="text-sm text-red-400">{teamError}</p>
            )}
            <div className="flex justify-end gap-2">
              <Button
                type="button"
                variant="ghost"
                className="text-white/50 hover:bg-white/[0.04] hover:text-white/80"
                onClick={() => setTeamModalMode(null)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                className="border border-indigo-500/30 bg-indigo-500/[0.15] text-indigo-200 hover:border-indigo-500/50 hover:bg-indigo-500/[0.22]"
                disabled={!teamName.trim() || teamSubmitting}
              >
                {teamSubmitting
                  ? teamModalMode === "edit"
                    ? "Saving..."
                    : "Creating..."
                  : teamModalMode === "edit"
                  ? "Save changes"
                  : "Create team"}
              </Button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  );
}
