"use client";

import { Suspense, useState, useEffect, useCallback } from "react";
import type { ReactElement } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { ArrowLeft, Clock, CheckCircle2, XCircle, Loader2, Pause } from "lucide-react";

import { MosaicSpinner } from "@/components/ui/MosaicSpinner";
import { fetchProjects, fetchProject, ProjectStatus } from "@/lib/api/projects";
import type { Project } from "@/lib/api/projects";
import { fetchTasks } from "@/lib/api/tasks";
import { fetchRunnerJobs, RunnerJobStatus } from "@/lib/api/runner-jobs";
import type { RunnerJob } from "@/lib/api/runner-jobs";
import { useWorkspaceId } from "@/lib/hooks";
import { TaskStatus, TaskPriority } from "@mosaic/shared";
import type { Task } from "@mosaic/shared";

/* ---------------------------------------------------------------------------
   Tab types
   --------------------------------------------------------------------------- */

type WorkspaceTab = "tasks" | "sessions" | "settings";

/* ---------------------------------------------------------------------------
   Status badge helpers
   --------------------------------------------------------------------------- */

interface StatusStyle {
  label: string;
  bg: string;
  color: string;
}

function getProjectStatusStyle(status: ProjectStatus): StatusStyle {
  switch (status) {
    case ProjectStatus.PLANNING:
      return { label: "Planning", bg: "rgba(47,128,255,0.15)", color: "var(--primary)" };
    case ProjectStatus.ACTIVE:
      return { label: "Active", bg: "rgba(20,184,166,0.15)", color: "var(--success)" };
    case ProjectStatus.PAUSED:
      return { label: "Paused", bg: "rgba(245,158,11,0.15)", color: "var(--warn)" };
    case ProjectStatus.COMPLETED:
      return { label: "Completed", bg: "rgba(139,92,246,0.15)", color: "var(--purple)" };
    case ProjectStatus.ARCHIVED:
      return { label: "Archived", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    default:
      return { label: String(status), bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
  }
}

function getTaskStatusStyle(status: TaskStatus): StatusStyle {
  switch (status) {
    case TaskStatus.NOT_STARTED:
      return { label: "Not Started", bg: "rgba(47,128,255,0.15)", color: "var(--primary)" };
    case TaskStatus.IN_PROGRESS:
      return { label: "In Progress", bg: "rgba(245,158,11,0.15)", color: "var(--warn)" };
    case TaskStatus.PAUSED:
      return { label: "Paused", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    case TaskStatus.COMPLETED:
      return { label: "Completed", bg: "rgba(20,184,166,0.15)", color: "var(--success)" };
    case TaskStatus.ARCHIVED:
      return { label: "Archived", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    default:
      return { label: status as string, bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
  }
}

function getTaskPriorityStyle(priority: TaskPriority): StatusStyle {
  switch (priority) {
    case TaskPriority.HIGH:
      return { label: "High", bg: "rgba(229,72,77,0.15)", color: "var(--danger)" };
    case TaskPriority.MEDIUM:
      return { label: "Medium", bg: "rgba(245,158,11,0.15)", color: "var(--warn)" };
    case TaskPriority.LOW:
      return { label: "Low", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    default:
      return { label: priority as string, bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
  }
}

function getJobStatusStyle(status: RunnerJobStatus): StatusStyle {
  switch (status) {
    case RunnerJobStatus.PENDING:
      return { label: "Pending", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    case RunnerJobStatus.QUEUED:
      return { label: "Queued", bg: "rgba(47,128,255,0.15)", color: "var(--primary)" };
    case RunnerJobStatus.RUNNING:
      return { label: "Running", bg: "rgba(245,158,11,0.15)", color: "var(--warn)" };
    case RunnerJobStatus.COMPLETED:
      return { label: "Completed", bg: "rgba(20,184,166,0.15)", color: "var(--success)" };
    case RunnerJobStatus.FAILED:
      return { label: "Failed", bg: "rgba(229,72,77,0.15)", color: "var(--danger)" };
    case RunnerJobStatus.CANCELLED:
      return { label: "Cancelled", bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
    default:
      return { label: String(status), bg: "rgba(143,157,183,0.15)", color: "var(--muted)" };
  }
}

function getJobStatusIcon(status: RunnerJobStatus): ReactElement {
  const size = 14;
  switch (status) {
    case RunnerJobStatus.RUNNING:
      return <Loader2 size={size} style={{ animation: "spin 1s linear infinite" }} />;
    case RunnerJobStatus.COMPLETED:
      return <CheckCircle2 size={size} />;
    case RunnerJobStatus.FAILED:
      return <XCircle size={size} />;
    case RunnerJobStatus.CANCELLED:
      return <Pause size={size} />;
    default:
      return <Clock size={size} />;
  }
}

function formatTimestamp(iso: string): string {
  try {
    return new Date(iso).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

function formatDatetime(iso: string): string {
  try {
    return new Date(iso).toLocaleString("en-US", {
      month: "short",
      day: "numeric",
      hour: "numeric",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

/* ---------------------------------------------------------------------------
   StatusBadge
   --------------------------------------------------------------------------- */

interface StatusBadgeProps {
  style: StatusStyle;
  icon?: ReactElement;
}

function StatusBadge({ style: statusStyle, icon }: StatusBadgeProps): ReactElement {
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        padding: "2px 10px",
        borderRadius: "var(--r)",
        background: statusStyle.bg,
        color: statusStyle.color,
        fontSize: "0.75rem",
        fontWeight: 500,
        whiteSpace: "nowrap",
      }}
    >
      {icon}
      {statusStyle.label}
    </span>
  );
}

/* ---------------------------------------------------------------------------
   Project Selector Card
   --------------------------------------------------------------------------- */

interface SelectorCardProps {
  project: Project;
}

function ProjectSelectorCard({ project }: SelectorCardProps): ReactElement {
  const [hovered, setHovered] = useState(false);
  const status = getProjectStatusStyle(project.status);

  return (
    <div
      onMouseEnter={() => {
        setHovered(true);
      }}
      onMouseLeave={() => {
        setHovered(false);
      }}
      style={{
        background: "var(--surface)",
        border: `1px solid ${hovered ? "var(--primary)" : "var(--border)"}`,
        borderRadius: "var(--r-lg)",
        padding: 20,
        cursor: "pointer",
        transition: "border-color 0.2s var(--ease)",
        display: "flex",
        flexDirection: "column",
        gap: 12,
      }}
    >
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <h3
          style={{
            fontWeight: 600,
            color: "var(--text)",
            fontSize: "1rem",
            margin: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            flex: 1,
            minWidth: 0,
          }}
        >
          {project.name}
        </h3>
      </div>

      {project.description ? (
        <p
          style={{
            color: "var(--muted)",
            fontSize: "0.85rem",
            margin: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
            lineHeight: 1.5,
          }}
        >
          {project.description}
        </p>
      ) : (
        <p style={{ color: "var(--muted)", fontSize: "0.85rem", margin: 0, fontStyle: "italic" }}>
          No description
        </p>
      )}

      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginTop: "auto",
        }}
      >
        <StatusBadge style={status} />
        <span
          style={{
            fontSize: "0.75rem",
            color: "var(--muted)",
            fontFamily: "var(--mono)",
          }}
        >
          {formatTimestamp(project.createdAt)}
        </span>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Project Selector View
   --------------------------------------------------------------------------- */

interface ProjectSelectorProps {
  workspaceId: string | null;
}

function ProjectSelector({ workspaceId }: ProjectSelectorProps): ReactElement {
  const router = useRouter();
  const [projects, setProjects] = useState<Project[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadProjects = useCallback(async (wsId: string | null): Promise<void> => {
    try {
      setIsLoading(true);
      setError(null);
      const data = await fetchProjects(wsId ?? undefined);
      setProjects(data);
    } catch (err: unknown) {
      console.error("[Workspace] Failed to fetch projects:", err);
      setError(err instanceof Error ? err.message : "Something went wrong loading projects.");
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!workspaceId) {
      setIsLoading(false);
      return;
    }

    let cancelled = false;

    async function load(): Promise<void> {
      try {
        setIsLoading(true);
        setError(null);
        const data = await fetchProjects(workspaceId ?? undefined);
        if (!cancelled) {
          setProjects(data);
        }
      } catch (err: unknown) {
        if (!cancelled) {
          console.error("[Workspace] Failed to fetch projects:", err);
          setError(err instanceof Error ? err.message : "Something went wrong loading projects.");
        }
      } finally {
        if (!cancelled) {
          setIsLoading(false);
        }
      }
    }

    void load();

    return (): void => {
      cancelled = true;
    };
  }, [workspaceId]);

  function handleRetry(): void {
    void loadProjects(workspaceId);
  }

  function handleProjectClick(projectId: string): void {
    router.push(`/workspace?project=${projectId}`);
  }

  return (
    <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
      <div style={{ marginBottom: 32 }}>
        <h1
          style={{
            fontSize: "1.875rem",
            fontWeight: 700,
            color: "var(--text)",
            margin: 0,
          }}
        >
          Select a Project
        </h1>
        <p
          style={{
            fontSize: "0.9rem",
            color: "var(--muted)",
            marginTop: 4,
          }}
        >
          Choose a project to open its workspace
        </p>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-16">
          <MosaicSpinner label="Loading projects..." />
        </div>
      ) : error !== null ? (
        <div
          style={{
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--r-lg)",
            padding: 32,
            textAlign: "center",
          }}
        >
          <p style={{ color: "var(--danger)", margin: "0 0 16px" }}>{error}</p>
          <button
            onClick={handleRetry}
            style={{
              padding: "8px 16px",
              background: "var(--danger)",
              border: "none",
              borderRadius: "var(--r)",
              color: "#fff",
              fontSize: "0.85rem",
              fontWeight: 500,
              cursor: "pointer",
            }}
          >
            Try again
          </button>
        </div>
      ) : projects.length === 0 ? (
        <div
          style={{
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--r-lg)",
            padding: 48,
            textAlign: "center",
          }}
        >
          <p style={{ color: "var(--muted)", margin: 0, fontSize: "0.9rem" }}>
            No projects found. Create a project first from the Projects page.
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {projects.map((project) => (
            <div
              key={project.id}
              role="button"
              tabIndex={0}
              onClick={() => {
                handleProjectClick(project.id);
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  handleProjectClick(project.id);
                }
              }}
            >
              <ProjectSelectorCard project={project} />
            </div>
          ))}
        </div>
      )}
    </main>
  );
}

/* ---------------------------------------------------------------------------
   Tasks Section
   --------------------------------------------------------------------------- */

interface TasksSectionProps {
  tasks: Task[];
  isLoading: boolean;
  error: string | null;
  onRetry: () => void;
}

function TasksSection({ tasks, isLoading, error, onRetry }: TasksSectionProps): ReactElement {
  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <MosaicSpinner label="Loading tasks..." />
      </div>
    );
  }

  if (error !== null) {
    return (
      <div
        style={{
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: "var(--r-lg)",
          padding: 24,
          textAlign: "center",
        }}
      >
        <p style={{ color: "var(--danger)", margin: "0 0 12px" }}>{error}</p>
        <button
          onClick={onRetry}
          style={{
            padding: "6px 14px",
            background: "var(--danger)",
            border: "none",
            borderRadius: "var(--r)",
            color: "#fff",
            fontSize: "0.85rem",
            fontWeight: 500,
            cursor: "pointer",
          }}
        >
          Try again
        </button>
      </div>
    );
  }

  if (tasks.length === 0) {
    return (
      <div
        style={{
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: "var(--r-lg)",
          padding: 32,
          textAlign: "center",
        }}
      >
        <p style={{ color: "var(--muted)", margin: 0, fontSize: "0.9rem" }}>
          No tasks for this project
        </p>
      </div>
    );
  }

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 1,
        background: "var(--border)",
        borderRadius: "var(--r-lg)",
        overflow: "hidden",
        border: "1px solid var(--border)",
      }}
    >
      {tasks.map((task) => {
        const statusStyle = getTaskStatusStyle(task.status);
        const priorityStyle = getTaskPriorityStyle(task.priority);

        return (
          <div
            key={task.id}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              padding: "12px 16px",
              background: "var(--surface)",
            }}
          >
            <div style={{ flex: 1, minWidth: 0 }}>
              <p
                style={{
                  margin: 0,
                  color: "var(--text)",
                  fontSize: "0.9rem",
                  fontWeight: 500,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
              >
                {task.title}
              </p>
            </div>
            <StatusBadge style={priorityStyle} />
            <StatusBadge style={statusStyle} />
          </div>
        );
      })}
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Agent Sessions Section
   --------------------------------------------------------------------------- */

interface SessionsSectionProps {
  jobs: RunnerJob[];
  isLoading: boolean;
  error: string | null;
  onRetry: () => void;
}

function SessionsSection({ jobs, isLoading, error, onRetry }: SessionsSectionProps): ReactElement {
  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <MosaicSpinner label="Loading agent sessions..." />
      </div>
    );
  }

  if (error !== null) {
    return (
      <div
        style={{
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: "var(--r-lg)",
          padding: 24,
          textAlign: "center",
        }}
      >
        <p style={{ color: "var(--danger)", margin: "0 0 12px" }}>{error}</p>
        <button
          onClick={onRetry}
          style={{
            padding: "6px 14px",
            background: "var(--danger)",
            border: "none",
            borderRadius: "var(--r)",
            color: "#fff",
            fontSize: "0.85rem",
            fontWeight: 500,
            cursor: "pointer",
          }}
        >
          Try again
        </button>
      </div>
    );
  }

  if (jobs.length === 0) {
    return (
      <div
        style={{
          background: "var(--surface)",
          border: "1px solid var(--border)",
          borderRadius: "var(--r-lg)",
          padding: 32,
          textAlign: "center",
        }}
      >
        <p style={{ color: "var(--muted)", margin: 0, fontSize: "0.9rem" }}>
          No agent sessions found
        </p>
      </div>
    );
  }

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 1,
        background: "var(--border)",
        borderRadius: "var(--r-lg)",
        overflow: "hidden",
        border: "1px solid var(--border)",
      }}
    >
      {jobs.map((job) => {
        const statusStyle = getJobStatusStyle(job.status);

        return (
          <div
            key={job.id}
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              padding: "12px 16px",
              background: "var(--surface)",
            }}
          >
            <div style={{ flex: 1, minWidth: 0 }}>
              <p
                style={{
                  margin: 0,
                  color: "var(--text)",
                  fontSize: "0.9rem",
                  fontWeight: 500,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
              >
                {job.type}
              </p>
              <p
                style={{
                  margin: "2px 0 0",
                  color: "var(--muted)",
                  fontSize: "0.75rem",
                  fontFamily: "var(--mono)",
                }}
              >
                {formatDatetime(job.createdAt)}
                {job.completedAt ? ` \u2014 ${formatDatetime(job.completedAt)}` : ""}
              </p>
            </div>
            <StatusBadge style={statusStyle} icon={getJobStatusIcon(job.status)} />
          </div>
        );
      })}
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Project Settings Section
   --------------------------------------------------------------------------- */

interface SettingsSectionProps {
  project: Project;
}

function SettingsSection({ project }: SettingsSectionProps): ReactElement {
  const rows: { label: string; value: string | ReactElement }[] = [
    { label: "Project ID", value: project.id },
    { label: "Created", value: formatTimestamp(project.createdAt) },
    { label: "Updated", value: formatTimestamp(project.updatedAt) },
    {
      label: "Status",
      value: <StatusBadge style={getProjectStatusStyle(project.status)} />,
    },
    { label: "Domain ID", value: project.domainId ?? "None" },
    { label: "Color", value: project.color ?? "Default" },
  ];

  return (
    <div
      style={{
        background: "var(--surface)",
        border: "1px solid var(--border)",
        borderRadius: "var(--r-lg)",
        overflow: "hidden",
      }}
    >
      {rows.map((row, idx) => (
        <div
          key={row.label}
          style={{
            display: "flex",
            alignItems: "center",
            padding: "12px 16px",
            borderTop: idx === 0 ? "none" : "1px solid var(--border)",
          }}
        >
          <span
            style={{
              color: "var(--text-2)",
              fontSize: "0.85rem",
              fontWeight: 500,
              width: 140,
              flexShrink: 0,
            }}
          >
            {row.label}
          </span>
          <span
            style={{
              color: "var(--text)",
              fontSize: "0.85rem",
              fontFamily: row.label === "Project ID" ? "var(--mono)" : "inherit",
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {row.value}
          </span>
        </div>
      ))}

      <div
        style={{
          padding: "16px",
          borderTop: "1px solid var(--border)",
        }}
      >
        <a
          href="/projects"
          style={{
            color: "var(--primary)",
            fontSize: "0.85rem",
            textDecoration: "none",
          }}
        >
          View on Projects page
        </a>
      </div>
    </div>
  );
}

/* ---------------------------------------------------------------------------
   Workspace View (project selected)
   --------------------------------------------------------------------------- */

interface WorkspaceViewProps {
  projectId: string;
  workspaceId: string | null;
}

function WorkspaceView({ projectId, workspaceId }: WorkspaceViewProps): ReactElement {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<WorkspaceTab>("tasks");

  // Project state
  const [project, setProject] = useState<Project | null>(null);
  const [projectLoading, setProjectLoading] = useState(true);
  const [projectError, setProjectError] = useState<string | null>(null);

  // Tasks state
  const [tasks, setTasks] = useState<Task[]>([]);
  const [tasksLoading, setTasksLoading] = useState(true);
  const [tasksError, setTasksError] = useState<string | null>(null);

  // Runner jobs state
  const [jobs, setJobs] = useState<RunnerJob[]>([]);
  const [jobsLoading, setJobsLoading] = useState(true);
  const [jobsError, setJobsError] = useState<string | null>(null);

  // Load project
  const loadProject = useCallback(async (): Promise<void> => {
    try {
      setProjectLoading(true);
      setProjectError(null);
      const data = await fetchProject(projectId, workspaceId ?? undefined);
      setProject(data);
    } catch (err: unknown) {
      console.error("[Workspace] Failed to fetch project:", err);
      setProjectError(err instanceof Error ? err.message : "Failed to load project.");
    } finally {
      setProjectLoading(false);
    }
  }, [projectId, workspaceId]);

  // Load tasks
  const loadTasks = useCallback(async (): Promise<void> => {
    if (!workspaceId) return;
    try {
      setTasksLoading(true);
      setTasksError(null);
      const allTasks = await fetchTasks({ workspaceId });
      // Filter client-side by projectId
      const projectTasks = allTasks.filter((t) => t.projectId === projectId);
      setTasks(projectTasks);
    } catch (err: unknown) {
      console.error("[Workspace] Failed to fetch tasks:", err);
      setTasksError(err instanceof Error ? err.message : "Failed to load tasks.");
    } finally {
      setTasksLoading(false);
    }
  }, [projectId, workspaceId]);

  // Load runner jobs
  const loadJobs = useCallback(async (): Promise<void> => {
    if (!workspaceId) return;
    try {
      setJobsLoading(true);
      setJobsError(null);
      const data = await fetchRunnerJobs({ workspaceId });
      setJobs(data);
    } catch (err: unknown) {
      console.error("[Workspace] Failed to fetch runner jobs:", err);
      setJobsError(err instanceof Error ? err.message : "Failed to load agent sessions.");
    } finally {
      setJobsLoading(false);
    }
  }, [workspaceId]);

  // Initial loads
  useEffect(() => {
    void loadProject();
  }, [loadProject]);

  useEffect(() => {
    if (workspaceId) {
      void loadTasks();
      void loadJobs();
    } else {
      setTasksLoading(false);
      setJobsLoading(false);
    }
  }, [workspaceId, loadTasks, loadJobs]);

  // Loading state for the whole project
  if (projectLoading) {
    return (
      <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
        <div className="flex justify-center py-16">
          <MosaicSpinner label="Loading project..." />
        </div>
      </main>
    );
  }

  // Project error state
  if (projectError !== null) {
    return (
      <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
        <div
          style={{
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--r-lg)",
            padding: 32,
            textAlign: "center",
          }}
        >
          <p style={{ color: "var(--danger)", margin: "0 0 16px" }}>{projectError}</p>
          <button
            onClick={() => {
              void loadProject();
            }}
            style={{
              padding: "8px 16px",
              background: "var(--danger)",
              border: "none",
              borderRadius: "var(--r)",
              color: "#fff",
              fontSize: "0.85rem",
              fontWeight: 500,
              cursor: "pointer",
            }}
          >
            Try again
          </button>
        </div>
      </main>
    );
  }

  if (!project) {
    return (
      <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
        <div
          style={{
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--r-lg)",
            padding: 32,
            textAlign: "center",
          }}
        >
          <p style={{ color: "var(--muted)", margin: 0 }}>Project not found</p>
        </div>
      </main>
    );
  }

  const projectStatus = getProjectStatusStyle(project.status);
  const tabs: { key: WorkspaceTab; label: string }[] = [
    { key: "tasks", label: "Tasks" },
    { key: "sessions", label: "Agent Sessions" },
    { key: "settings", label: "Settings" },
  ];

  return (
    <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
      {/* Back link */}
      <button
        onClick={() => {
          router.push("/workspace");
        }}
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          background: "transparent",
          border: "none",
          cursor: "pointer",
          color: "var(--muted)",
          fontSize: "0.85rem",
          padding: 0,
          marginBottom: 16,
          transition: "color 0.15s",
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.color = "var(--text)";
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.color = "var(--muted)";
        }}
      >
        <ArrowLeft size={16} />
        All projects
      </button>

      {/* Header */}
      <div style={{ marginBottom: 32 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
          <h1
            style={{
              fontSize: "1.875rem",
              fontWeight: 700,
              color: "var(--text)",
              margin: 0,
            }}
          >
            {project.name}
          </h1>
          <StatusBadge style={projectStatus} />
        </div>
        {project.description && (
          <p
            style={{
              fontSize: "0.9rem",
              color: "var(--muted)",
              margin: 0,
              lineHeight: 1.5,
            }}
          >
            {project.description}
          </p>
        )}
      </div>

      {/* Tabs */}
      <div
        style={{
          display: "flex",
          gap: 0,
          borderBottom: "1px solid var(--border)",
          marginBottom: 24,
        }}
      >
        {tabs.map((tab) => {
          const isActive = activeTab === tab.key;

          return (
            <button
              key={tab.key}
              onClick={() => {
                setActiveTab(tab.key);
              }}
              style={{
                padding: "10px 20px",
                background: "transparent",
                border: "none",
                borderBottom: isActive ? "2px solid var(--primary)" : "2px solid transparent",
                color: isActive ? "var(--text)" : "var(--muted)",
                fontSize: "0.9rem",
                fontWeight: isActive ? 600 : 400,
                cursor: "pointer",
                transition: "color 0.15s, border-color 0.15s",
              }}
            >
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Tab content */}
      {activeTab === "tasks" && (
        <TasksSection
          tasks={tasks}
          isLoading={tasksLoading}
          error={tasksError}
          onRetry={() => {
            void loadTasks();
          }}
        />
      )}
      {activeTab === "sessions" && (
        <SessionsSection
          jobs={jobs}
          isLoading={jobsLoading}
          error={jobsError}
          onRetry={() => {
            void loadJobs();
          }}
        />
      )}
      {activeTab === "settings" && <SettingsSection project={project} />}
    </main>
  );
}

/* ---------------------------------------------------------------------------
   Workspace Page (entry point)
   --------------------------------------------------------------------------- */

export default function WorkspacePage(): ReactElement {
  return (
    <Suspense
      fallback={
        <main className="container mx-auto px-4 py-8" style={{ maxWidth: 960 }}>
          <div className="flex justify-center py-16">
            <MosaicSpinner label="Loading workspace..." />
          </div>
        </main>
      }
    >
      <WorkspacePageContent />
    </Suspense>
  );
}

function WorkspacePageContent(): ReactElement {
  const searchParams = useSearchParams();
  const workspaceId = useWorkspaceId();
  const projectId = searchParams.get("project");

  if (projectId) {
    return <WorkspaceView projectId={projectId} workspaceId={workspaceId} />;
  }

  return <ProjectSelector workspaceId={workspaceId} />;
}
