"use client";

import { useMemo, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import {
  AlertTriangle,
  ArrowLeft,
  Bot,
  CheckCheck,
  CheckSquare,
  Copy,
  Clock3,
  Eye,
  ExternalLink,
  FileText,
  GitPullRequestArrow,
  GripVertical,
  Link2,
  Mail,
  MessageSquare,
  Pencil,
  Plus,
  Sparkles,
  Target,
  Trash2,
  UserPlus,
  Users,
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { TaskList } from "@/components/tasks/task-list";
import { TaskForm, type TaskFormData } from "@/components/tasks/task-form";
import { ProjectForm } from "@/components/projects/project-form";
import { EmptyState } from "@/components/ui/empty-state";
import { NoteCard } from "@/components/notes/note-card";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Modal } from "@/components/ui/modal";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { useNotes } from "@/hooks/use-notes";
import { useTasks } from "@/hooks/use-tasks";
import { useProjectLinks } from "@/hooks/use-project-links";
import { useProjectActivity } from "@/hooks/use-project-activity";
import { useProjectGuests } from "@/hooks/use-project-guests";
import { useGoals } from "@/hooks/use-goals";
import { useProjects } from "@/hooks/use-projects";
import { useTeamPermissions } from "@/hooks/use-team-permissions";
import { useTeams } from "@/hooks/use-teams";
import { useTags } from "@/hooks/use-tags";
import { useWorkspaceStore } from "@/stores/workspace-store";
import { cn, formatDate, formatRelativeDate, isTaskDeadlineOverdue } from "@/lib/utils";
import type { Project, ProjectGuestRole } from "@/types";

type ProjectTab = "overview" | "war_room" | "tasks" | "notes" | "links" | "guests";

const PROJECT_TABS: Array<{ id: ProjectTab; label: string }> = [
  { id: "overview", label: "Overview" },
  { id: "war_room", label: "War Room" },
  { id: "tasks", label: "Tasks" },
  { id: "notes", label: "Notes" },
  { id: "links", label: "Links" },
  { id: "guests", label: "Guests" },
];

const LINK_KINDS = [
  { value: "link", label: "General link" },
  { value: "doc", label: "Document" },
  { value: "design", label: "Design" },
  { value: "repo", label: "Repository" },
];

const WAR_ROOM_TONE_CLASSES = {
  amber: "border-amber-500/20 bg-amber-500/10 text-amber-700",
  red: "border-red-500/20 bg-red-500/10 text-red-700",
  violet: "border-violet-500/20 bg-violet-500/10 text-violet-700",
};

function getHealthMeta(health: Project["health"]) {
  if (health === "at_risk") {
    return { label: "At risk", className: "bg-amber-500/15 text-amber-600 border-amber-500/20" };
  }
  if (health === "stuck") {
    return { label: "Stuck", className: "bg-red-500/15 text-red-600 border-red-500/20" };
  }
  return { label: "On track", className: "bg-green-500/15 text-green-600 border-green-500/20" };
}

function getApprovalMeta(status: Project["approval_status"]) {
  if (status === "pending_approval") {
    return {
      label: "Pending approval",
      className: "border-amber-500/20 bg-amber-500/10 text-amber-700",
    };
  }

  if (status === "changes_requested") {
    return {
      label: "Changes requested",
      className: "border-red-500/20 bg-red-500/10 text-red-700",
    };
  }

  if (status === "approved") {
    return {
      label: "Approved",
      className: "border-emerald-500/20 bg-emerald-500/10 text-emerald-700",
    };
  }

  return {
    label: "No approval requested",
    className: "border-border bg-muted/50 text-muted-foreground",
  };
}

function normalizeUrl(url: string) {
  if (/^https?:\/\//i.test(url)) return url;
  return `https://${url}`;
}

function aiPromptHref(prompt: string) {
  return `/ai?prompt=${encodeURIComponent(prompt)}`;
}

function getGuestRoleMeta(role: ProjectGuestRole) {
  if (role === "edit") {
    return {
      label: "Can edit",
      className: "border-primary/20 bg-primary/10 text-primary",
      icon: Pencil,
    };
  }

  if (role === "comment") {
    return {
      label: "Can comment",
      className: "border-amber-500/20 bg-amber-500/10 text-amber-600",
      icon: MessageSquare,
    };
  }

  return {
    label: "View only",
    className: "border-border bg-muted/50 text-muted-foreground",
    icon: Eye,
  };
}

export default function ProjectDetailPage() {
  const params = useParams();
  const router = useRouter();
  const projectId = params.id as string;

  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [editOpen, setEditOpen] = useState(false);
  const [taskFormOpen, setTaskFormOpen] = useState(false);
  const [linkFormOpen, setLinkFormOpen] = useState(false);
  const [activeTab, setActiveTab] = useState<ProjectTab>("overview");
  const [linkTitle, setLinkTitle] = useState("");
  const [linkUrl, setLinkUrl] = useState("");
  const [linkKind, setLinkKind] = useState("link");
  const [creatingLink, setCreatingLink] = useState(false);
  const [draggedPinnedNoteId, setDraggedPinnedNoteId] = useState<string | null>(null);
  const [draggedLinkId, setDraggedLinkId] = useState<string | null>(null);
  const [aiActionLoading, setAiActionLoading] = useState(false);
  const [aiActionMode, setAiActionMode] = useState<"tasks" | "risk" | null>(null);
  const [aiActionResult, setAiActionResult] = useState<string | null>(null);
  const [summaryOpen, setSummaryOpen] = useState(false);
  const [summaryCopied, setSummaryCopied] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState<ProjectGuestRole>("view");
  const [inviteMessage, setInviteMessage] = useState("");
  const [inviteSubmitting, setInviteSubmitting] = useState(false);
  const [guestFeedback, setGuestFeedback] = useState<string | null>(null);
  const [lastInviteUrl, setLastInviteUrl] = useState<string | null>(null);
  const [copiedInviteToken, setCopiedInviteToken] = useState<string | null>(null);
  const [approvalNotes, setApprovalNotes] = useState("");
  const [approvalSubmitting, setApprovalSubmitting] = useState(false);

  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const setActiveTeamId = useWorkspaceStore((state) => state.setActiveTeamId);
  const { projects, updateProject, deleteProject } = useProjects();
  const { goals } = useGoals();
  const { can } = useTeamPermissions(project?.team_id ?? null);
  const { activeMembers } = useTeams();
  const { tags, createTag } = useTags();
  const {
    guests,
    invitations,
    loading: guestsLoading,
    userId: guestViewerId,
    currentGuestRole,
    inviteGuest,
    revokeInvitation,
    removeGuest,
  } = useProjectGuests(projectId);
  const {
    tasks,
    loading: tasksLoading,
    createTask,
    refetch: refetchTasks,
  } = useTasks(projectId);
  const {
    notes,
    loading: notesLoading,
    createNote,
    deleteNote,
    togglePin,
    reorderPinnedNotes,
  } = useNotes();
  const {
    links,
    loading: linksLoading,
    createLink,
    deleteLink,
    reorderLinks,
  } = useProjectLinks(projectId);
  const { activity, loading: activityLoading, refetch: refetchActivity } = useProjectActivity(projectId);
  const taskActivitySignature = tasks
    .map((task) => `${task.id}:${task.status}:${task.updated_at}`)
    .join("|");
  const noteActivitySignature = notes
    .map((note) => `${note.id}:${note.is_pinned}:${note.updated_at}:${note.pinned_order}`)
    .join("|");
  const linkActivitySignature = links
    .map((link) => `${link.id}:${link.updated_at}:${link.sort_order}`)
    .join("|");

  useEffect(() => {
    async function fetchProject() {
      const { data } = await supabase
        .from("projects")
        .select("*")
        .eq("id", projectId)
        .single();

      if (data && data.team_id !== activeTeamId) {
        setActiveTeamId(data.team_id ?? null);
      }

      setProject(data);
      setLoading(false);
    }
    void fetchProject();
  }, [activeTeamId, projectId, setActiveTeamId, supabase]);

  useEffect(() => {
    if (loading) return;
    void refetchActivity();
  }, [
    loading,
    refetchActivity,
    taskActivitySignature,
    noteActivitySignature,
    linkActivitySignature,
  ]);

  useEffect(() => {
    setApprovalNotes(project?.approval_notes || "");
  }, [project?.approval_notes, project?.id]);

  async function handleUpdate(data: {
    name: string;
    color: string;
    icon: string;
    description: string;
    goal: string;
    goal_id: string | null;
    health: Project["health"];
  }) {
    if (!canEditProject) return;
    const updated = await updateProject(projectId, data);
    setProject(updated);
    await refetchActivity();
  }

  async function handleDelete() {
    if (!canEditProject) return;
    await deleteProject(projectId);
    router.push("/projects");
  }

  async function handleApproverChange(nextApproverId: string) {
    if (!project || !canEditProject) return;

    const updated = await updateProject(project.id, {
      approver_id: nextApproverId || null,
    });
    setProject(updated);
    await refetchActivity();
  }

  async function handleApproval(status: Project["approval_status"]) {
    if (!project) return;

    setApprovalSubmitting(true);
    try {
      const updated = await updateProject(project.id, {
        approver_id: project.approver_id,
        approval_status: status,
        approval_notes: approvalNotes.trim(),
      });
      setProject(updated);
      await refetchActivity();
    } finally {
      setApprovalSubmitting(false);
    }
  }

  async function handleCreateProjectNote() {
    if (!canCollaborateProjectNotes) return;
    const note = await createNote({
      project_id: projectId,
    });
    router.push(`/notes/${note.id}`);
  }

  async function handleCreateTask(data: TaskFormData) {
    if (!canCollaborateProjectTasks) return;
    await createTask({
      ...data,
      project_id: projectId,
      goal_id: data.goal_id || project?.goal_id || null,
    });
    await refetchActivity();
  }

  async function handleCreateLink(e: React.FormEvent) {
    e.preventDefault();
    if (!canEditProjectLinks) return;
    if (!linkTitle.trim() || !linkUrl.trim() || creatingLink) return;

    setCreatingLink(true);
    await createLink({
      title: linkTitle.trim(),
      url: normalizeUrl(linkUrl.trim()),
      kind: linkKind,
    });
    await refetchActivity();
    setCreatingLink(false);
    setLinkFormOpen(false);
    setLinkTitle("");
    setLinkUrl("");
    setLinkKind("link");
  }

  const projectNotes = useMemo(
    () => notes.filter((note) => note.project_id === projectId),
    [notes, projectId]
  );
  const pinnedProjectNotes = projectNotes
    .filter((note) => note.is_pinned)
    .sort((a, b) => a.pinned_order - b.pinned_order || new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
  const openTaskCount = tasks.filter((task) => task.status !== "done" && task.status !== "cancelled").length;
  const completedTaskCount = tasks.filter((task) => task.status === "done").length;
  const overdueTaskCount = tasks.filter(
    (task) => task.deadline && task.status !== "done" && isTaskDeadlineOverdue(task.deadline)
  ).length;
  const isPersonalOwner =
    !project?.team_id && !!project?.user_id && project.user_id === guestViewerId;
  const canEditProject = project?.team_id ? can("projects", "edit") : isPersonalOwner;
  const canEditProjectTasks = project?.team_id ? can("tasks", "edit") : isPersonalOwner;
  const canEditProjectNotes = project?.team_id ? can("notes", "edit") : isPersonalOwner;
  const canCommentAsWorkspaceMember = project?.team_id
    ? can("comments", "comment")
    : isPersonalOwner;
  const guestCanEdit = currentGuestRole === "edit";
  const guestCanComment =
    currentGuestRole === "comment" || currentGuestRole === "edit";
  const canCollaborateProjectTasks = canEditProjectTasks || guestCanEdit;
  const canCollaborateProjectNotes = canEditProjectNotes || guestCanEdit;
  const canEditProjectLinks = canEditProject || guestCanEdit;
  const canCommentOnProjectWork = canCommentAsWorkspaceMember || guestCanComment;
  const canManageGuestAccess = canEditProject;
  const pendingInvitations = invitations.filter(
    (invitation) => invitation.status === "pending"
  );
  const linkedGoal = useMemo(
    () => goals.find((goal) => goal.id === project?.goal_id) || null,
    [goals, project?.goal_id]
  );
  const approverMember = useMemo(
    () =>
      activeMembers.find((member) => member.user_id === project?.approver_id) ||
      null,
    [activeMembers, project?.approver_id]
  );
  const tabCounts = useMemo<Record<ProjectTab, number>>(
    () => ({
      overview: 0,
      war_room:
        overdueTaskCount +
        (project?.health === "on_track" ? 0 : 1) +
        (project?.approval_status === "pending_approval" ? 1 : 0),
      tasks: tasks.length,
      notes: projectNotes.length,
      links: links.length,
      guests: guests.length + pendingInvitations.length,
    }),
    [
      guests.length,
      links.length,
      overdueTaskCount,
      pendingInvitations.length,
      project?.approval_status,
      project?.health,
      projectNotes.length,
      tasks.length,
    ]
  );

  const summaryText = useMemo(() => {
    return [
      `Project: ${project?.name || "Not set"}`,
      `Aligned goal: ${linkedGoal?.title || "Not linked"}`,
      `Health: ${project ? getHealthMeta(project.health).label : "Not set"}`,
      `Approval status: ${
        project ? getApprovalMeta(project.approval_status).label : "Not set"
      }`,
      `Approver: ${
        approverMember?.profile?.full_name ||
        approverMember?.profile?.email ||
        (project?.approver_id ? "Assigned" : "Not set")
      }`,
      `Goal: ${project?.goal || "Not set"}`,
      `Description: ${project?.description || "Not set"}`,
      `Open tasks: ${openTaskCount}`,
      `Completed tasks: ${completedTaskCount}`,
      `Overdue tasks: ${overdueTaskCount}`,
      `Notes: ${projectNotes.length}`,
      `Pinned notes: ${pinnedProjectNotes.length}`,
      `Links: ${links.length}`,
      `Guests: ${guests.length}`,
      `Pending invitations: ${pendingInvitations.length}`,
    ].join("\n");
  }, [
    completedTaskCount,
    guests.length,
    linkedGoal?.title,
    links.length,
    openTaskCount,
    overdueTaskCount,
    pendingInvitations.length,
    pinnedProjectNotes.length,
    project,
    projectNotes.length,
    approverMember?.profile?.email,
    approverMember?.profile?.full_name,
  ]);

  async function handleGenerateTasksFromGoal() {
    if (aiActionLoading || !project || !canCollaborateProjectTasks) return;
    setAiActionLoading(true);
    setAiActionMode("tasks");
    setAiActionResult(null);

    const prompt = [
      `You are helping with the project "${project.name}" (project_id: ${project.id}).`,
      `Goal: ${project.goal || "not set"}.`,
      `Description: ${project.description || "not set"}.`,
      `Team id: ${project.team_id || "none"}.`,
      `Current health: ${healthMeta.label}.`,
      `Existing open tasks: ${tasks.filter((task) => task.status !== "done" && task.status !== "cancelled").map((task) => task.title).join("; ") || "none"}.`,
      "Use get_project_context if needed. Then create 5 concrete next tasks in the workspace for this exact project. Avoid duplicates with existing tasks. Prefer create_tasks_batch. After creating them, briefly summarize what you created.",
    ].join(" ");

    try {
      const res = await fetch("/api/ai/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: prompt,
          messages: [{ role: "user", content: prompt }],
          workspaceTeamId: project.team_id,
        }),
      });

      const data = await res.json();
      setAiActionResult(data.text || "Tasks generated.");
      await Promise.all([refetchTasks(), refetchActivity()]);
    } catch {
      setAiActionResult("AI task generation failed.");
    } finally {
      setAiActionLoading(false);
      setAiActionMode(null);
    }
  }

  async function handleGenerateRiskSnapshot() {
    if (aiActionLoading || !project) return;
    setAiActionLoading(true);
    setAiActionMode("risk");
    setAiActionResult(null);

    const prompt = [
      `Review project_id "${project.id}" for a risk snapshot.`,
      `Project name: "${project.name}".`,
      `Goal: ${project.goal || "not set"}.`,
      `Description: ${project.description || "not set"}.`,
      `Team id: ${project.team_id || "none"}.`,
      "Use get_project_risk_context first.",
      "Then explain whether this project is on track, at risk, or stuck, why you think that, and what the next best actions are.",
      "Keep it concise and practical. Do not create tasks unless I explicitly ask for them.",
    ].join(" ");

    try {
      const res = await fetch("/api/ai/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: prompt,
          messages: [{ role: "user", content: prompt }],
          workspaceTeamId: project.team_id,
        }),
      });

      const data = await res.json();
      setAiActionResult(data.text || "Risk snapshot generated.");
    } catch {
      setAiActionResult("AI risk snapshot failed.");
    } finally {
      setAiActionLoading(false);
      setAiActionMode(null);
    }
  }

  async function handleCopySummary() {
    await navigator.clipboard.writeText(summaryText);
    setSummaryCopied(true);
    setTimeout(() => setSummaryCopied(false), 1500);
  }

  function getInviteUrl(token: string) {
    if (typeof window === "undefined") return "";
    return `${window.location.origin}/guest/project/${encodeURIComponent(token)}`;
  }

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

    setInviteSubmitting(true);
    setGuestFeedback(null);

    try {
      const payload = await inviteGuest({
        email: inviteEmail.trim(),
        role: inviteRole,
        message: inviteMessage.trim(),
      });

      setLastInviteUrl(payload.inviteUrl);
      setGuestFeedback(
        payload.delivery === "email_sent"
          ? `Invitation sent to ${inviteEmail.trim()}.`
          : `Invitation created for ${inviteEmail.trim()}. Copy the link below to share it manually.`
      );
      setInviteEmail("");
      setInviteRole("view");
      setInviteMessage("");
    } catch (error) {
      setGuestFeedback(
        error instanceof Error ? error.message : "Invitation could not be created."
      );
    } finally {
      setInviteSubmitting(false);
    }
  }

  async function handleCopyInvite(token: string) {
    const inviteUrl = getInviteUrl(token);
    if (!inviteUrl) return;
    await navigator.clipboard.writeText(inviteUrl);
    setCopiedInviteToken(token);
    setTimeout(() => setCopiedInviteToken((current) => (current === token ? null : current)), 1500);
  }

  async function handlePinnedNoteDrop(targetId: string) {
    if (!canCollaborateProjectNotes) return;
    if (!draggedPinnedNoteId || draggedPinnedNoteId === targetId) return;

    const reordered = [...pinnedProjectNotes];
    const fromIndex = reordered.findIndex((note) => note.id === draggedPinnedNoteId);
    const toIndex = reordered.findIndex((note) => note.id === targetId);
    if (fromIndex < 0 || toIndex < 0) return;

    const [moved] = reordered.splice(fromIndex, 1);
    reordered.splice(toIndex, 0, moved);
    await reorderPinnedNotes(reordered);
    await refetchActivity();
    setDraggedPinnedNoteId(null);
  }

  async function handleLinkDrop(targetId: string) {
    if (!canEditProjectLinks) return;
    if (!draggedLinkId || draggedLinkId === targetId) return;

    const reordered = [...links];
    const fromIndex = reordered.findIndex((link) => link.id === draggedLinkId);
    const toIndex = reordered.findIndex((link) => link.id === targetId);
    if (fromIndex < 0 || toIndex < 0) return;

    const [moved] = reordered.splice(fromIndex, 1);
    reordered.splice(toIndex, 0, moved);
    await reorderLinks(reordered);
    await refetchActivity();
    setDraggedLinkId(null);
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-64 rounded-xl" />
      </div>
    );
  }

  if (!project) {
    return (
      <EmptyState
        title="Project not found"
        description="This project may have been deleted."
        action={
          <Button variant="outline" onClick={() => router.push("/projects")}>
            Back to projects
          </Button>
        }
      />
    );
  }

  const healthMeta = getHealthMeta(project.health);
  const approvalMeta = getApprovalMeta(project.approval_status);
  const canRequestApproval = canEditProject && !!project.approver_id;
  const canRespondToApproval =
    !!project.approver_id &&
    guestViewerId === project.approver_id &&
    project.approval_status === "pending_approval";
  const priorityRank: Record<string, number> = { urgent: 5, high: 4, medium: 3, low: 2, none: 1 };
  const openProjectTasks = tasks.filter((task) => task.status !== "done" && task.status !== "cancelled");
  const overdueProjectTasks = openProjectTasks.filter(
    (task) => task.deadline && isTaskDeadlineOverdue(task.deadline),
  );
  const nextWarRoomTasks = [...openProjectTasks]
    .sort((left, right) => {
      const leftScore =
        (left.deadline && isTaskDeadlineOverdue(left.deadline) ? 100 : 0) +
        (priorityRank[left.priority] || 0) * 12;
      const rightScore =
        (right.deadline && isTaskDeadlineOverdue(right.deadline) ? 100 : 0) +
        (priorityRank[right.priority] || 0) * 12;
      return rightScore - leftScore;
    })
    .slice(0, 5);
  const projectReadinessScore = Math.max(
    0,
    Math.min(
      100,
      Math.round(
        62 +
          completedTaskCount * 3 +
          Math.min(links.length, 5) * 3 +
          Math.min(pinnedProjectNotes.length, 4) * 4 -
          overdueTaskCount * 16 -
          (project.health === "at_risk" ? 18 : project.health === "stuck" ? 32 : 0) -
          (project.approval_status === "changes_requested" ? 18 : 0) -
          (project.approval_status === "pending_approval" ? 8 : 0) -
          (!project.goal ? 10 : 0),
      ),
    ),
  );
  const warRoomBlockers = [
    ...(overdueProjectTasks.length > 0
      ? [{
          title: `${overdueProjectTasks.length} overdue task${overdueProjectTasks.length === 1 ? "" : "s"}`,
          description: "Clear or reschedule overdue work before adding new scope.",
          tone: "red" as const,
        }]
      : []),
    ...(project.health === "stuck"
      ? [{
          title: "Project marked as stuck",
          description: "This needs a decision, owner change, or scope cut.",
          tone: "red" as const,
        }]
      : project.health === "at_risk"
        ? [{
            title: "Project at risk",
            description: "Review blockers and tighten the next concrete move.",
            tone: "amber" as const,
          }]
        : []),
    ...(project.approval_status === "pending_approval"
      ? [{
          title: "Approval is waiting",
          description: "Follow up with the approver or attach clearer approval notes.",
          tone: "amber" as const,
        }]
      : []),
    ...(!project.goal
      ? [{
          title: "No clear project goal",
          description: "A War Room works best with one measurable outcome.",
          tone: "violet" as const,
        }]
      : []),
    ...(projectNotes.length === 0
      ? [{
          title: "No project notes yet",
          description: "Add one source-of-truth note so decisions do not live in memory.",
          tone: "violet" as const,
        }]
      : []),
  ];
  const warRoomNextMove =
    overdueProjectTasks[0]
      ? {
          label: "Overdue pressure",
          title: overdueProjectTasks[0].title,
          description: "Clear, reschedule, or cut this first. Overdue work is the fastest way for a project to feel noisy.",
        }
      : project.health === "stuck"
        ? {
            label: "Decision needed",
            title: "Unblock the project before adding work",
            description: "Pick the missing decision, owner, or scope cut. A stuck project needs a choice more than another task.",
          }
        : project.health === "at_risk"
          ? {
              label: "Risk control",
              title: nextWarRoomTasks[0]?.title || "Tighten the next concrete move",
              description: "Reduce ambiguity with one task that makes the project visibly safer in the next 24 hours.",
            }
          : !project.goal
            ? {
                label: "Mission clarity",
                title: "Write one measurable project outcome",
                description: "The War Room gets sharper once the project has a finish line everyone can repeat.",
              }
            : nextWarRoomTasks[0]
              ? {
                  label: "Next tactical move",
                  title: nextWarRoomTasks[0].title,
                  description: "This is the highest-priority open task by deadline pressure and priority.",
                }
              : {
                  label: "Ready state",
                  title: "Create the next concrete task or request review",
                  description: "No urgent move is obvious. Convert the mission into one next task or move the project toward sign-off.",
                };
  const warRoomAiPrompt = `Act as a Project War Room Coach for "${project.name}" (project_id: ${project.id}). Goal: ${project.goal || "not set"}. Description: ${project.description || "not set"}. Health: ${project.health}. Approval: ${project.approval_status}. Open tasks: ${openTaskCount}. Overdue tasks: ${overdueTaskCount}. Notes: ${projectNotes.length}. Links: ${links.length}. Give me the next best move, the biggest blocker, what to cut or ignore, and a 24-hour recovery plan. Ask for Go before making any workspace changes.`;

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start gap-3">
        <Button
          variant="ghost"
          size="icon"
          onClick={() => router.push("/projects")}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>

        <div
          className="flex items-center justify-center h-12 w-12 rounded-xl text-2xl shrink-0"
          style={{ backgroundColor: project.color + "18" }}
        >
          {project.icon}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex flex-wrap items-center gap-3">
            <h1 className="text-2xl font-bold tracking-tight truncate">
              {project.name}
            </h1>
            <Badge variant="outline" className={healthMeta.className}>
              {healthMeta.label}
            </Badge>
            {(project.team_id || project.approver_id) && (
              <Badge variant="outline" className={approvalMeta.className}>
                {approvalMeta.label}
              </Badge>
            )}
            {currentGuestRole && (
              <Badge
                variant="outline"
                className={getGuestRoleMeta(currentGuestRole).className}
              >
                Guest access: {getGuestRoleMeta(currentGuestRole).label}
              </Badge>
            )}
          </div>
          {project.goal && (
            <p className="text-sm text-muted-foreground mt-1">
              <span className="font-medium text-foreground">Goal:</span> {project.goal}
            </p>
          )}
          {linkedGoal && (
            <p className="text-xs text-primary mt-1">
              Linked goal: {linkedGoal.icon} {linkedGoal.title}
            </p>
          )}
          <p className="text-xs text-muted-foreground mt-1">
            Updated {formatRelativeDate(project.updated_at)}
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <Button
            size="sm"
            variant="outline"
            onClick={() => setTaskFormOpen(true)}
            disabled={!canCollaborateProjectTasks}
          >
            <Plus className="h-4 w-4" />
            New task
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={handleCreateProjectNote}
            disabled={!canCollaborateProjectNotes}
          >
            <FileText className="h-4 w-4" />
            New note
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => setLinkFormOpen(true)}
            disabled={!canEditProjectLinks}
          >
            <Link2 className="h-4 w-4" />
            Add link
          </Button>
          <Button
            size="sm"
            onClick={() =>
              router.push(
                `/ai?prompt=${encodeURIComponent(
                  `Help me plan the next steps for the project "${project.name}". Goal: ${project.goal || "not set"}. Current description: ${project.description || "not set"}.`
                )}`
              )
            }
          >
            <Bot className="h-4 w-4" />
            Ask AI
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() =>
              router.push(
                `/ai?prompt=${encodeURIComponent(
                  `Turn the project "${project.name}" (project_id: ${project.id}) into a reusable template for this workspace. Reuse the existing project direction, generate sensible starter tasks from its structure, and preserve timing offsets where it makes sense.`
                )}`
              )
            }
            disabled={!canEditProject}
          >
            <Sparkles className="h-4 w-4" />
            Save as template
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={handleGenerateRiskSnapshot}
            disabled={aiActionLoading}
          >
            <Target className="h-4 w-4" />
            {aiActionLoading && aiActionMode === "risk" ? "Reviewing..." : "Risk snapshot"}
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={handleGenerateTasksFromGoal}
            disabled={aiActionLoading || !canCollaborateProjectTasks}
          >
            <Sparkles className="h-4 w-4" />
            {aiActionLoading && aiActionMode === "tasks" ? "Generating..." : "Generate tasks from goal"}
          </Button>
          <Button size="sm" variant="outline" onClick={() => setSummaryOpen(true)}>
            <Copy className="h-4 w-4" />
            Share summary
          </Button>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setEditOpen(true)}
            disabled={!canEditProject}
          >
            <Pencil className="h-4 w-4" />
          </Button>
          <Button variant="ghost" size="icon" onClick={handleDelete} disabled={!canEditProject}>
            <Trash2 className="h-4 w-4 text-destructive" />
          </Button>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        {PROJECT_TABS.map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setActiveTab(tab.id)}
            className={cn(
              "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",
              activeTab === tab.id
                ? "border-primary bg-primary text-primary-foreground"
                : "border-border bg-background text-muted-foreground hover:bg-accent"
            )}
          >
            {tab.label}
            {tabCounts[tab.id] > 0 && (
              <span
                className={cn(
                  "rounded-full px-2 py-0.5 text-[11px] font-medium",
                  activeTab === tab.id
                    ? "bg-primary-foreground/15 text-primary-foreground"
                    : "bg-muted text-muted-foreground"
                )}
              >
                {tabCounts[tab.id]}
              </span>
            )}
          </button>
        ))}
      </div>

      {aiActionResult && (
        <div className="rounded-xl border border-border bg-muted/30 p-4 text-sm whitespace-pre-wrap">
          {aiActionResult}
        </div>
      )}

      {activeTab === "war_room" && (
        <div className="space-y-6">
          <section className="overflow-hidden rounded-[28px] border border-violet-500/15 bg-[#0e0c15] shadow-[0_24px_80px_rgba(0,0,0,0.18)]">
            <div className="grid gap-5 p-5 lg:grid-cols-[1fr_0.9fr]">
              <div className="rounded-[24px] border border-white/[0.06] bg-[radial-gradient(circle_at_top_left,rgba(124,58,237,0.16),rgba(255,255,255,0.025)_48%,rgba(255,255,255,0.015)_100%)] p-5">
                <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-violet-300/60">
                  Project War Room
                </p>
                <h2 className="mt-2 text-[24px] font-black tracking-tight text-white">
                  {project.name}
                </h2>
                <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-white/42">
                  Mission control für Entscheidungen, nicht nur Status. Der War Room zeigt den stärksten nächsten Move, die echten Blocker und welche Arbeit gerade Sicherheit schafft.
                </p>
                <div className="mt-5 flex flex-wrap gap-2">
                  <span className="rounded-full border border-white/[0.08] bg-white/[0.035] px-3 py-1 text-[11px] font-semibold text-white/45">
                    Readiness {projectReadinessScore}%
                  </span>
                  <span className="rounded-full border border-white/[0.08] bg-white/[0.035] px-3 py-1 text-[11px] font-semibold text-white/45">
                    {warRoomBlockers.length} blocker
                  </span>
                  <span className="rounded-full border border-white/[0.08] bg-white/[0.035] px-3 py-1 text-[11px] font-semibold text-white/45">
                    {nextWarRoomTasks.length} moves
                  </span>
                </div>
              </div>

              <div className="rounded-[24px] border border-amber-500/15 bg-amber-500/[0.055] p-5">
                <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-amber-200/60">
                  Next Move
                </p>
                <p className="mt-1 text-[12px] font-semibold uppercase tracking-[0.14em] text-white/28">
                  {warRoomNextMove.label}
                </p>
                <h3 className="mt-3 text-[18px] font-bold tracking-tight text-white/88">
                  {warRoomNextMove.title}
                </h3>
                <p className="mt-2 text-[13px] leading-relaxed text-white/44">
                  {warRoomNextMove.description}
                </p>
                <div className="mt-5 flex flex-wrap gap-2">
                  <Button
                    size="sm"
                    onClick={() => router.push(aiPromptHref(warRoomAiPrompt))}
                    className="border border-violet-500/25 bg-violet-500/15 text-violet-100 hover:bg-violet-500/22"
                  >
                    <Bot className="h-4 w-4" />
                    Ask War Room AI
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={handleGenerateRiskSnapshot}
                    disabled={aiActionLoading}
                  >
                    <Target className="h-4 w-4" />
                    Risk scan
                  </Button>
                </div>
              </div>
            </div>
          </section>

          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Readiness</CardDescription>
                <CardTitle className="text-3xl">{projectReadinessScore}%</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-2 overflow-hidden rounded-full bg-muted">
                  <div
                    className={cn(
                      "h-full rounded-full",
                      projectReadinessScore >= 75
                        ? "bg-emerald-500"
                        : projectReadinessScore >= 45
                          ? "bg-amber-500"
                          : "bg-red-500",
                    )}
                    style={{ width: `${projectReadinessScore}%` }}
                  />
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Blockers</CardDescription>
                <CardTitle className="text-3xl">{warRoomBlockers.length}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Next moves</CardDescription>
                <CardTitle className="text-3xl">{nextWarRoomTasks.length}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Intel assets</CardDescription>
                <CardTitle className="text-3xl">{projectNotes.length + links.length}</CardTitle>
              </CardHeader>
            </Card>
          </div>

          <div className="grid gap-6 xl:grid-cols-[1.05fr_0.95fr]">
            <Card className="overflow-hidden">
              <CardHeader>
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <CardTitle className="text-base">Mission Control</CardTitle>
                    <CardDescription>
                      The highest-signal state of this project right now.
                    </CardDescription>
                  </div>
                  <Badge variant="outline" className={healthMeta.className}>
                    {healthMeta.label}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                  <div className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Mission
                  </div>
                  <p className="mt-2 text-sm leading-relaxed">
                    {project.goal || project.description || "No clear mission has been written yet."}
                  </p>
                </div>

                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                    <div className="text-xs uppercase tracking-wider text-muted-foreground">
                      Open / Done
                    </div>
                    <div className="mt-2 text-xl font-semibold">
                      {openTaskCount} / {completedTaskCount}
                    </div>
                  </div>
                  <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                    <div className="text-xs uppercase tracking-wider text-muted-foreground">
                      Approval
                    </div>
                    <div className="mt-2 text-sm font-medium">{approvalMeta.label}</div>
                  </div>
                </div>

                <div className="flex flex-wrap gap-2">
                  <Button
                    size="sm"
                    onClick={handleGenerateRiskSnapshot}
                    disabled={aiActionLoading}
                  >
                    <Target className="h-4 w-4" />
                    {aiActionLoading && aiActionMode === "risk" ? "Reviewing..." : "Refresh risk snapshot"}
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={handleGenerateTasksFromGoal}
                    disabled={aiActionLoading || !canCollaborateProjectTasks}
                  >
                    <Sparkles className="h-4 w-4" />
                    Generate next tasks
                  </Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Blockers & Risks</CardTitle>
                <CardDescription>Things that deserve a decision before more work is added.</CardDescription>
              </CardHeader>
              <CardContent>
                {warRoomBlockers.length === 0 ? (
                  <EmptyState
                    icon={<CheckCheck className="h-8 w-8" />}
                    title="No active blockers"
                    description="This project has no obvious structural warning right now."
                    className="py-6"
                  />
                ) : (
                  <div className="space-y-3">
                    {warRoomBlockers.map((blocker) => (
                      <div
                        key={blocker.title}
                        className={cn("rounded-xl border p-4", WAR_ROOM_TONE_CLASSES[blocker.tone])}
                      >
                        <div className="text-sm font-semibold">{blocker.title}</div>
                        <p className="mt-1 text-sm opacity-75">{blocker.description}</p>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <div className="grid gap-6 xl:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Next Tactical Moves</CardTitle>
                <CardDescription>Sorted by urgency, deadline pressure, and priority.</CardDescription>
              </CardHeader>
              <CardContent>
                {nextWarRoomTasks.length === 0 ? (
                  <EmptyState
                    icon={<CheckSquare className="h-8 w-8" />}
                    title="No open tasks"
                    description="Create the next concrete task or mark the project as ready for review."
                    className="py-6"
                  />
                ) : (
                  <div className="space-y-3">
                    {nextWarRoomTasks.map((task) => (
                      <Link
                        key={task.id}
                        href="/tasks"
                        className="block rounded-xl border border-border/60 bg-background/70 p-4 transition-colors hover:bg-accent"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div className="min-w-0">
                            <p className="truncate text-sm font-medium">{task.title}</p>
                            <p className="mt-1 text-xs text-muted-foreground">
                              {task.priority} priority
                              {task.deadline ? ` · ${formatDate(task.deadline)}` : " · no deadline"}
                            </p>
                          </div>
                          {task.deadline && isTaskDeadlineOverdue(task.deadline) && (
                            <Badge variant="outline" className="border-red-500/20 bg-red-500/10 text-red-700">
                              Overdue
                            </Badge>
                          )}
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Project Intelligence</CardTitle>
                <CardDescription>Pinned notes, links, and fresh activity in one place.</CardDescription>
              </CardHeader>
              <CardContent className="space-y-5">
                <div>
                  <div className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    <FileText className="h-3.5 w-3.5" />
                    Pinned notes
                  </div>
                  {pinnedProjectNotes.length === 0 ? (
                    <p className="rounded-xl border border-dashed border-border/70 p-3 text-sm text-muted-foreground">
                      No pinned project notes yet.
                    </p>
                  ) : (
                    <div className="space-y-2">
                      {pinnedProjectNotes.slice(0, 3).map((note) => (
                        <Link key={note.id} href={`/notes/${note.id}`} className="block rounded-xl border border-border/60 bg-background/70 p-3 text-sm hover:bg-accent">
                          {note.title}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                <div>
                  <div className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    <Link2 className="h-3.5 w-3.5" />
                    Key links
                  </div>
                  {links.length === 0 ? (
                    <p className="rounded-xl border border-dashed border-border/70 p-3 text-sm text-muted-foreground">
                      No links attached yet.
                    </p>
                  ) : (
                    <div className="space-y-2">
                      {links.slice(0, 3).map((link) => (
                        <a
                          key={link.id}
                          href={link.url}
                          target="_blank"
                          rel="noreferrer"
                          className="flex items-center justify-between gap-3 rounded-xl border border-border/60 bg-background/70 p-3 text-sm hover:bg-accent"
                        >
                          <span className="truncate">{link.title}</span>
                          <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {activeTab === "overview" && (
        <div className="space-y-6">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Open tasks</CardDescription>
                <CardTitle className="text-2xl">{tasksLoading ? "..." : openTaskCount}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Completed tasks</CardDescription>
                <CardTitle className="text-2xl">{tasksLoading ? "..." : completedTaskCount}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Notes</CardDescription>
                <CardTitle className="text-2xl">{notesLoading ? "..." : projectNotes.length}</CardTitle>
              </CardHeader>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardDescription>Overdue</CardDescription>
                <CardTitle className="text-2xl">{tasksLoading ? "..." : overdueTaskCount}</CardTitle>
              </CardHeader>
            </Card>
          </div>

          <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">Project Brief</CardTitle>
                  <CardDescription>Context the team and AI can use for better decisions.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1">
                      Aligned goal
                    </div>
                    <p className="text-sm">
                      {linkedGoal ? `${linkedGoal.icon} ${linkedGoal.title}` : "No linked goal yet."}
                    </p>
                  </div>
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1">
                      Goal
                    </div>
                    <p className="text-sm">
                      {project.goal || "No goal added yet."}
                    </p>
                  </div>
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-wider text-muted-foreground mb-1">
                      Description
                    </div>
                    <p className="text-sm whitespace-pre-wrap">
                      {project.description || "No description added yet."}
                    </p>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-base">Collaboration</CardTitle>
                  <CardDescription>Shared access for teammates, guests, and external partners.</CardDescription>
                </CardHeader>
                <CardContent className="grid gap-3 sm:grid-cols-3">
                  <div className="rounded-xl border border-border/60 bg-background/60 p-3">
                    <div className="text-xs uppercase tracking-wider text-muted-foreground">
                      Guests
                    </div>
                    <div className="mt-2 text-2xl font-semibold">{guests.length}</div>
                  </div>
                  <div className="rounded-xl border border-border/60 bg-background/60 p-3">
                    <div className="text-xs uppercase tracking-wider text-muted-foreground">
                      Pending invites
                    </div>
                    <div className="mt-2 text-2xl font-semibold">{pendingInvitations.length}</div>
                  </div>
                  <div className="rounded-xl border border-border/60 bg-background/60 p-3">
                    <div className="text-xs uppercase tracking-wider text-muted-foreground">
                      Your access
                    </div>
                    <div className="mt-2 text-sm font-medium">
                      {currentGuestRole
                        ? getGuestRoleMeta(currentGuestRole).label
                        : canEditProject
                        ? "Full workspace access"
                        : "View only"}
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-base">Project Sign-off</CardTitle>
                  <CardDescription>
                    Keep project approval visible so launches, handoffs, and stakeholder reviews do not drift.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div>
                      <div className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                        Current status
                      </div>
                      <Badge variant="outline" className={cn("mt-2", approvalMeta.className)}>
                        {approvalMeta.label}
                      </Badge>
                    </div>
                    <div className="rounded-xl border border-border/60 bg-background/60 px-3 py-2 text-right">
                      <div className="text-[11px] uppercase tracking-[0.16em] text-muted-foreground">
                        Timeline
                      </div>
                      <div className="mt-1 text-sm text-muted-foreground">
                        {project.approval_requested_at
                          ? `Requested ${formatRelativeDate(project.approval_requested_at)}`
                          : "No approval requested yet"}
                        {project.approved_at
                          ? `, last updated ${formatRelativeDate(project.approved_at)}`
                          : ""}
                      </div>
                    </div>
                  </div>

                  {project.team_id ? (
                    <div className="space-y-1.5">
                      <Label className="text-xs text-muted-foreground">Approver</Label>
                      <Select
                        value={project.approver_id || ""}
                        onChange={(event) => void handleApproverChange(event.target.value)}
                        disabled={!canEditProject || activeMembers.length === 0}
                      >
                        <option value="">No approver assigned</option>
                        {activeMembers.map((member) => (
                          <option key={member.user_id} value={member.user_id}>
                            {member.profile?.full_name || member.profile?.email || "Team member"}
                          </option>
                        ))}
                      </Select>
                    </div>
                  ) : (
                    <div className="rounded-xl border border-border/60 bg-background/60 p-3 text-sm text-muted-foreground">
                      Project sign-off is most useful in shared workspaces where an owner, lead, or reviewer can formally approve the project.
                    </div>
                  )}

                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="rounded-xl border border-border/60 bg-background/60 p-3">
                      <div className="text-[11px] uppercase tracking-[0.16em] text-muted-foreground">
                        Approver
                      </div>
                      <div className="mt-2 text-sm font-medium">
                        {approverMember?.profile?.full_name ||
                          approverMember?.profile?.email ||
                          (project.approver_id ? "Assigned reviewer" : "No approver assigned")}
                      </div>
                    </div>
                    <div className="rounded-xl border border-border/60 bg-background/60 p-3">
                      <div className="text-[11px] uppercase tracking-[0.16em] text-muted-foreground">
                        Ownership
                      </div>
                      <div className="mt-2 text-sm font-medium">
                        {project.team_id
                          ? "Team-managed approval flow"
                          : "Personal project"}
                      </div>
                    </div>
                  </div>

                  <div className="space-y-1.5">
                    <Label className="text-xs text-muted-foreground">Approval notes</Label>
                    <Textarea
                      value={approvalNotes}
                      onChange={(event) => setApprovalNotes(event.target.value)}
                      placeholder="Capture what should be approved, what changed, or what still needs sign-off..."
                      className="min-h-[110px]"
                      disabled={(!canRequestApproval && !canRespondToApproval) || approvalSubmitting}
                    />
                  </div>

                  <div className="flex flex-wrap justify-end gap-2">
                    {canRequestApproval && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => void handleApproval("pending_approval")}
                        disabled={approvalSubmitting || project.approval_status === "pending_approval"}
                      >
                        <GitPullRequestArrow className="h-4 w-4" />
                        {approvalSubmitting && project.approval_status !== "pending_approval"
                          ? "Updating..."
                          : "Request approval"}
                      </Button>
                    )}
                    {canRespondToApproval && (
                      <>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => void handleApproval("changes_requested")}
                          disabled={approvalSubmitting}
                        >
                          <AlertTriangle className="h-4 w-4" />
                          Request changes
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => void handleApproval("approved")}
                          disabled={approvalSubmitting}
                        >
                          <CheckCheck className="h-4 w-4" />
                          Approve
                        </Button>
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Pinned Project Notes</CardTitle>
                <CardDescription>Keep the most important project context at the top. Drag to reorder.</CardDescription>
              </CardHeader>
              <CardContent>
                  {notesLoading ? (
                    <div className="grid gap-3 sm:grid-cols-2">
                      {Array.from({ length: 2 }).map((_, i) => (
                        <Skeleton key={i} className="h-28 rounded-xl" />
                      ))}
                    </div>
                  ) : pinnedProjectNotes.length === 0 ? (
                    <EmptyState
                      title="No pinned project notes"
                      description="Pin important notes so they stay easy to find."
                      className="py-6"
                    />
                  ) : (
                    <div className="grid gap-3 sm:grid-cols-2">
                      {pinnedProjectNotes.map((note) => (
                        <div
                          key={note.id}
                          draggable={canCollaborateProjectNotes}
                          onDragStart={() => setDraggedPinnedNoteId(note.id)}
                          onDragOver={(e) => e.preventDefault()}
                          onDrop={() => void handlePinnedNoteDrop(note.id)}
                          className="relative"
                        >
                          <div className="absolute left-2 top-2 z-10 rounded-md bg-background/90 p-1 text-muted-foreground">
                            <GripVertical className="h-4 w-4" />
                          </div>
                          <NoteCard
                            note={note}
                            onTogglePin={() => togglePin(note.id, note.is_pinned)}
                            onDelete={() => deleteNote(note.id)}
                            canManage={canCollaborateProjectNotes}
                          />
                        </div>
                      ))}
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Recent Activity</CardTitle>
                <CardDescription>The latest work across tasks, notes, and links.</CardDescription>
              </CardHeader>
              <CardContent>
                {activityLoading ? (
                  <div className="space-y-3">
                    {Array.from({ length: 4 }).map((_, i) => (
                      <Skeleton key={i} className="h-14 rounded-xl" />
                    ))}
                  </div>
                ) : activity.length === 0 ? (
                  <EmptyState
                    title="No activity yet"
                    description="Create tasks, notes, or links to start building momentum."
                    className="py-6"
                  />
                ) : (
                  <div className="space-y-4">
                    {activity.slice(0, 8).map((item) => (
                      <div key={item.id} className="flex items-start gap-3">
                        <div className="mt-0.5 rounded-full bg-muted p-2">
                          {item.entity_type === "task" ? (
                            <CheckSquare className="h-4 w-4 text-muted-foreground" />
                          ) : item.entity_type === "note" ? (
                            <FileText className="h-4 w-4 text-muted-foreground" />
                          ) : (
                            <Link2 className="h-4 w-4 text-muted-foreground" />
                          )}
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium">
                            {item.action === "task_status_changed"
                              ? `Task status: ${(item.details.from_status as string) || "unknown"} -> ${(item.details.to_status as string) || "unknown"}`
                              : item.action === "project_approval_requested" ||
                                  item.action === "project_approved" ||
                                  item.action === "project_changes_requested"
                              ? `Project approval: ${
                                  (item.details.from_approval_status as string) || "not_required"
                                } -> ${
                                  (item.details.to_approval_status as string) || "unknown"
                                }`
                              : item.action.replaceAll("_", " ")}
                          </p>
                          <p className="text-sm text-muted-foreground truncate">
                            {item.title}
                          </p>
                          <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
                            <Clock3 className="h-3 w-3" />
                            {formatRelativeDate(item.created_at)}
                          </div>
                        </div>
                        {item.entity_type === "note" && item.entity_id ? (
                          <Link href={`/notes/${item.entity_id}`} className="text-xs text-primary hover:underline">
                            Open
                          </Link>
                        ) : item.entity_type === "task" ? (
                          <Link href="/tasks" className="text-xs text-primary hover:underline">
                            Open
                          </Link>
                        ) : null}
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {activeTab === "tasks" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3">
              <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                Tasks
              </h2>
              <span className="inline-flex rounded-full border border-border px-2.5 py-1 text-xs font-medium text-muted-foreground">
                {tasksLoading ? "..." : `${tasks.length} total, ${openTaskCount} open`}
              </span>
            </div>
            <Button
              size="sm"
              onClick={() => setTaskFormOpen(true)}
              disabled={!canCollaborateProjectTasks}
            >
              <Plus className="h-4 w-4" />
              New task
            </Button>
          </div>
          <TaskList
            projectId={projectId}
            allowEditOverride={canCollaborateProjectTasks}
            allowCommentOverride={canCommentOnProjectWork}
          />
        </div>
      )}

      {activeTab === "notes" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3">
              <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                Notes
              </h2>
              <span className="inline-flex rounded-full border border-border px-2.5 py-1 text-xs font-medium text-muted-foreground">
                {notesLoading ? "..." : `${projectNotes.length} total`}
              </span>
            </div>
            <Button
              size="sm"
              onClick={handleCreateProjectNote}
              disabled={!canCollaborateProjectNotes}
            >
              <Plus className="h-4 w-4" />
              New note
            </Button>
          </div>

          {pinnedProjectNotes.length > 0 && (
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Target className="h-4 w-4 text-muted-foreground" />
                <h3 className="text-sm font-medium">Pinned notes</h3>
              </div>
              <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                {pinnedProjectNotes.map((note) => (
                  <div
                    key={note.id}
                    draggable={canCollaborateProjectNotes}
                    onDragStart={() => setDraggedPinnedNoteId(note.id)}
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={() => void handlePinnedNoteDrop(note.id)}
                    className="relative"
                  >
                    <div className="absolute left-2 top-2 z-10 rounded-md bg-background/90 p-1 text-muted-foreground">
                      <GripVertical className="h-4 w-4" />
                    </div>
                    <NoteCard
                      note={note}
                      onTogglePin={() => togglePin(note.id, note.is_pinned)}
                      onDelete={() => deleteNote(note.id)}
                      canManage={canCollaborateProjectNotes}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {notesLoading ? (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-28 rounded-xl" />
              ))}
            </div>
          ) : projectNotes.length === 0 ? (
            <EmptyState
              icon={<FileText className="h-8 w-8" />}
              title="No project notes yet"
              description="Create the first note for this project to keep ideas, drafts, and research in one place."
              action={
                <Button
                  size="sm"
                  onClick={handleCreateProjectNote}
                  disabled={!canCollaborateProjectNotes}
                >
                  <Plus className="h-4 w-4" />
                  Create note
                </Button>
              }
              className="py-8"
            />
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {projectNotes.map((note) => (
                <NoteCard
                  key={note.id}
                  note={note}
                  onTogglePin={() => togglePin(note.id, note.is_pinned)}
                  onDelete={() => deleteNote(note.id)}
                  canManage={canCollaborateProjectNotes}
                />
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === "links" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3">
              <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
                Links
              </h2>
              <span className="inline-flex rounded-full border border-border px-2.5 py-1 text-xs font-medium text-muted-foreground">
                {linksLoading ? "..." : `${links.length} total`}
              </span>
            </div>
            <Button size="sm" onClick={() => setLinkFormOpen(true)} disabled={!canEditProjectLinks}>
              <Plus className="h-4 w-4" />
              Add link
            </Button>
          </div>

          {linksLoading ? (
            <div className="space-y-3">
              {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-16 rounded-xl" />
              ))}
            </div>
          ) : links.length === 0 ? (
            <EmptyState
              icon={<Link2 className="h-8 w-8" />}
              title="No project links yet"
              description="Keep important docs, repos, and references in one place."
              action={
                <Button size="sm" onClick={() => setLinkFormOpen(true)} disabled={!canEditProjectLinks}>
                  <Plus className="h-4 w-4" />
                  Add first link
                </Button>
              }
              className="py-8"
            />
          ) : (
            <div className="space-y-3">
              {links.map((link) => (
                <Card
                  key={link.id}
                  draggable={canEditProjectLinks}
                  onDragStart={() => setDraggedLinkId(link.id)}
                  onDragOver={(e) => e.preventDefault()}
                  onDrop={() => void handleLinkDrop(link.id)}
                >
                  <CardContent className="flex items-center justify-between gap-4 pt-6">
                    <div className="min-w-0 flex items-start gap-3">
                      <div className="rounded-md bg-muted p-2 text-muted-foreground">
                        <GripVertical className="h-4 w-4" />
                      </div>
                      <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-sm font-medium">{link.title}</span>
                        <Badge variant="outline" className="capitalize">
                          {link.kind}
                        </Badge>
                      </div>
                      <a
                        href={link.url}
                        target="_blank"
                        rel="noreferrer"
                        className="text-sm text-muted-foreground truncate hover:text-primary"
                      >
                        {link.url}
                      </a>
                      <p className="text-xs text-muted-foreground mt-1">
                        Added {formatDate(link.created_at)}
                      </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <a href={link.url} target="_blank" rel="noreferrer">
                        <Button size="icon" variant="ghost">
                          <ExternalLink className="h-4 w-4" />
                        </Button>
                      </a>
                      <Button
                        size="icon"
                        variant="ghost"
                        onClick={() => deleteLink(link.id)}
                        disabled={!canEditProjectLinks}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === "guests" && (
        <div className="space-y-6">
          <div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">External Collaboration</CardTitle>
                <CardDescription>
                  Invite guests by email so they can view, comment on, or edit this project without joining the whole workspace.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {currentGuestRole && (
                  <div className="rounded-xl border border-border/60 bg-muted/30 p-4 text-sm">
                    You are working in this project as a guest with{" "}
                    <span className="font-medium">
                      {getGuestRoleMeta(currentGuestRole).label.toLowerCase()}
                    </span>
                    .
                  </div>
                )}

                {canManageGuestAccess ? (
                  <form onSubmit={handleInviteGuest} className="space-y-4">
                    <div className="grid gap-4 md:grid-cols-[1fr_180px]">
                      <div className="space-y-1.5">
                        <Label htmlFor="guest-email">Guest email</Label>
                        <Input
                          id="guest-email"
                          type="email"
                          value={inviteEmail}
                          onChange={(e) => setInviteEmail(e.target.value)}
                          placeholder="partner@client.com"
                          required
                        />
                      </div>
                      <div className="space-y-1.5">
                        <Label htmlFor="guest-role">Access</Label>
                        <Select
                          id="guest-role"
                          value={inviteRole}
                          onChange={(e) => setInviteRole(e.target.value as ProjectGuestRole)}
                        >
                          <option value="view">View only</option>
                          <option value="comment">Can comment</option>
                          <option value="edit">Can edit</option>
                        </Select>
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <Label htmlFor="guest-message">Message</Label>
                      <Textarea
                        id="guest-message"
                        value={inviteMessage}
                        onChange={(e) => setInviteMessage(e.target.value)}
                        placeholder="Add context for this collaborator, what they should review, or what kind of help you need."
                        className="min-h-[96px]"
                      />
                    </div>

                    <div className="flex items-center justify-between gap-3 rounded-xl border border-border/60 bg-background/70 px-4 py-3 text-sm">
                      <div className="text-muted-foreground">
                        Invite links open a dedicated guest page and can optionally send an email if delivery is configured.
                      </div>
                      <Button type="submit" disabled={inviteSubmitting}>
                        <UserPlus className="h-4 w-4" />
                        {inviteSubmitting ? "Creating..." : "Invite guest"}
                      </Button>
                    </div>
                  </form>
                ) : (
                  <div className="rounded-xl border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground">
                    Only project managers can invite or remove guests. You can still see who currently has access.
                  </div>
                )}

                {guestFeedback && (
                  <div className="rounded-xl border border-border/60 bg-muted/30 p-4 text-sm">
                    {guestFeedback}
                  </div>
                )}

                {lastInviteUrl && (
                  <div className="space-y-2 rounded-xl border border-border/60 bg-background/70 p-4">
                    <div className="text-sm font-medium">Latest invite link</div>
                    <p className="break-all text-sm text-muted-foreground">{lastInviteUrl}</p>
                    <div className="flex justify-end">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => void navigator.clipboard.writeText(lastInviteUrl)}
                      >
                        <Copy className="h-4 w-4" />
                        Copy link
                      </Button>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Access Snapshot</CardTitle>
                <CardDescription>Who currently has project-specific access beyond the core workspace.</CardDescription>
              </CardHeader>
              <CardContent className="grid gap-3 sm:grid-cols-3 lg:grid-cols-1 xl:grid-cols-3">
                <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Active guests
                  </div>
                  <div className="mt-2 text-2xl font-semibold">{guests.length}</div>
                </div>
                <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Pending invites
                  </div>
                  <div className="mt-2 text-2xl font-semibold">{pendingInvitations.length}</div>
                </div>
                <div className="rounded-xl border border-border/60 bg-background/70 p-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Guest-friendly scope
                  </div>
                  <div className="mt-2 text-sm font-medium">
                    Tasks, notes, files, comments, and project links
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          <div className="grid gap-6 xl:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Current Guests</CardTitle>
                <CardDescription>People who can already open this project.</CardDescription>
              </CardHeader>
              <CardContent>
                {guestsLoading ? (
                  <div className="space-y-3">
                    {Array.from({ length: 3 }).map((_, i) => (
                      <Skeleton key={i} className="h-20 rounded-xl" />
                    ))}
                  </div>
                ) : guests.length === 0 ? (
                  <EmptyState
                    icon={<Users className="h-8 w-8" />}
                    title="No guests yet"
                    description="Invite a client, partner, or friend when you want focused collaboration without full workspace access."
                    className="py-8"
                  />
                ) : (
                  <div className="space-y-3">
                    {guests.map((guest) => {
                      const roleMeta = getGuestRoleMeta(guest.role);
                      const RoleIcon = roleMeta.icon;

                      return (
                        <div
                          key={`${guest.project_id}:${guest.user_id}`}
                          className="flex items-start justify-between gap-4 rounded-xl border border-border/60 bg-background/70 p-4"
                        >
                          <div className="space-y-1">
                            <div className="text-sm font-medium">
                              {guest.profile?.full_name || guest.profile?.email || "Guest"}
                            </div>
                            <div className="text-sm text-muted-foreground">
                              {guest.profile?.email || "External collaborator"}
                            </div>
                            <div className="flex flex-wrap items-center gap-2 pt-1">
                              <Badge variant="outline" className={roleMeta.className}>
                                <RoleIcon className="mr-1 h-3 w-3" />
                                {roleMeta.label}
                              </Badge>
                              <span className="text-xs text-muted-foreground">
                                Joined {formatRelativeDate(guest.joined_at)}
                              </span>
                            </div>
                          </div>

                          {canManageGuestAccess && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => void removeGuest(guest.user_id)}
                            >
                              Remove
                            </Button>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-base">Pending Invitations</CardTitle>
                <CardDescription>Share links directly or revoke invites that are no longer needed.</CardDescription>
              </CardHeader>
              <CardContent>
                {guestsLoading ? (
                  <div className="space-y-3">
                    {Array.from({ length: 3 }).map((_, i) => (
                      <Skeleton key={i} className="h-24 rounded-xl" />
                    ))}
                  </div>
                ) : pendingInvitations.length === 0 ? (
                  <EmptyState
                    icon={<Mail className="h-8 w-8" />}
                    title="No pending invites"
                    description="Once you invite someone, their access link and delivery state will show up here."
                    className="py-8"
                  />
                ) : (
                  <div className="space-y-3">
                    {pendingInvitations.map((invitation) => {
                      const roleMeta = getGuestRoleMeta(invitation.role);
                      const RoleIcon = roleMeta.icon;
                      const inviteUrl = getInviteUrl(invitation.token);

                      return (
                        <div
                          key={invitation.id}
                          className="space-y-3 rounded-xl border border-border/60 bg-background/70 p-4"
                        >
                          <div className="flex items-start justify-between gap-4">
                            <div className="space-y-1">
                              <div className="text-sm font-medium">{invitation.email}</div>
                              <div className="flex flex-wrap items-center gap-2">
                                <Badge variant="outline" className={roleMeta.className}>
                                  <RoleIcon className="mr-1 h-3 w-3" />
                                  {roleMeta.label}
                                </Badge>
                                <span className="text-xs text-muted-foreground">
                                  Created {formatRelativeDate(invitation.created_at)}
                                </span>
                                {invitation.sent_at && (
                                  <span className="text-xs text-emerald-600">
                                    Email sent
                                  </span>
                                )}
                              </div>
                            </div>
                            {canManageGuestAccess && (
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => void revokeInvitation(invitation.id)}
                              >
                                Revoke
                              </Button>
                            )}
                          </div>

                          {invitation.message && (
                            <p className="rounded-lg bg-muted/40 px-3 py-2 text-sm text-muted-foreground">
                              {invitation.message}
                            </p>
                          )}

                          <div className="rounded-lg border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground break-all">
                            {inviteUrl}
                          </div>

                          <div className="flex justify-end">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => void handleCopyInvite(invitation.token)}
                            >
                              <Copy className="h-4 w-4" />
                              {copiedInviteToken === invitation.token ? "Copied" : "Copy invite link"}
                            </Button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {editOpen && (
        <ProjectForm
          open={editOpen}
          onClose={() => setEditOpen(false)}
          onSubmit={handleUpdate}
          project={project}
          goals={goals}
        />
      )}

      {taskFormOpen && (
        <TaskForm
          open={taskFormOpen}
          onClose={() => setTaskFormOpen(false)}
          onSubmit={handleCreateTask}
          projects={projects}
          goals={goals}
          tags={tags}
          onCreateTag={createTag}
          defaultProjectId={projectId}
        />
      )}

      {linkFormOpen && (
        <Modal
          open={linkFormOpen}
          onClose={() => setLinkFormOpen(false)}
          title="Add project link"
          className="max-w-md"
        >
          <form onSubmit={handleCreateLink} className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="link-title">Title</Label>
              <Input
                id="link-title"
                value={linkTitle}
                onChange={(e) => setLinkTitle(e.target.value)}
                placeholder="Figma file, GitHub repo, PRD..."
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="link-url">URL</Label>
              <Input
                id="link-url"
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
                placeholder="https://..."
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="link-kind">Type</Label>
              <Select
                id="link-kind"
                value={linkKind}
                onChange={(e) => setLinkKind(e.target.value)}
              >
                {LINK_KINDS.map((kind) => (
                  <option key={kind.value} value={kind.value}>
                    {kind.label}
                  </option>
                ))}
              </Select>
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button type="button" variant="ghost" onClick={() => setLinkFormOpen(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={creatingLink}>
                {creatingLink ? "Adding..." : "Add link"}
              </Button>
            </div>
          </form>
        </Modal>
      )}

      {summaryOpen && (
        <Modal
          open={summaryOpen}
          onClose={() => setSummaryOpen(false)}
          title="Project Summary Card"
          className="max-w-lg"
        >
          <div className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="text-base">{project.name}</CardTitle>
                <CardDescription>{healthMeta.label}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                <p><span className="font-medium">Goal:</span> {project.goal || "Not set"}</p>
                <p><span className="font-medium">Description:</span> {project.description || "Not set"}</p>
                <div className="grid grid-cols-2 gap-3">
                  <div className="rounded-lg border p-3">
                    <div className="text-xs text-muted-foreground">Open tasks</div>
                    <div className="text-xl font-semibold">{openTaskCount}</div>
                  </div>
                  <div className="rounded-lg border p-3">
                    <div className="text-xs text-muted-foreground">Notes</div>
                    <div className="text-xl font-semibold">{projectNotes.length}</div>
                  </div>
                </div>
              </CardContent>
            </Card>
            <div className="rounded-lg border bg-muted/30 p-3 text-sm whitespace-pre-wrap">
              {summaryText}
            </div>
            {aiActionResult && (
              <div className="rounded-lg border border-border bg-muted/30 p-3 text-sm whitespace-pre-wrap">
                {aiActionResult}
              </div>
            )}
            <div className="flex justify-end gap-2">
              <Button variant="ghost" onClick={() => setSummaryOpen(false)}>
                Close
              </Button>
              <Button onClick={() => void handleCopySummary()}>
                <Copy className="h-4 w-4" />
                {summaryCopied ? "Copied" : "Copy summary"}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}
