function ProjectDetail({ snapshot, onNav, onOpenProjectModal }) {
  const { project, rollups } = snapshot;
  const ff = window.ConstructProData.formatCurrency;
  const roots = snapshot.projectTree || [];
  const users = snapshot.users || [];
  const hasActiveProject = Boolean(project?.id);
  const projectSubtitle = [project.type, project.client, project.location].filter(Boolean).join(" · ");
  const timelineValue = hasActiveProject && project.startDate && project.endDate
    ? `${project.startDate} → ${project.endDate}`
    : "Not set";
  const openTeamEditor = () => {
    if (onOpenProjectModal) onOpenProjectModal("edit", 3);
    else onNav("createProject");
  };

  return (
    <div className="fade-in">
      <div className="mb-6 flex flex-wrap items-center gap-2">
        <Button onClick={() => onOpenProjectModal ? onOpenProjectModal("create") : onNav("createProject")}><Icons.plus/> New Project</Button>
        <Button variant="secondary" onClick={() => onOpenProjectModal ? onOpenProjectModal("edit") : onNav("createProject")}><Icons.settings/> Edit Project</Button>
        <Button variant="secondary" onClick={() => onNav("workItems")}><Icons.check/> Manage Work</Button>
      </div>

      <div className="mb-6 grid grid-cols-1 gap-4 xl:grid-cols-2">
        {snapshot.projects.filter((item) => item.status !== "archived").map((item) => {
          const teamCount = window.countAssignedTeam?.(item.teamAssignments) || 0;
          return (
          <Card key={item.id} className={item.id === project.id ? "border-primary/50 bg-primary-fixed/30" : "hover:border-primary/40 transition-colors"}>
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="font-bold">{item.name}</h3>
                <p className="mt-1 text-sm text-text-muted">{item.code} · {item.location}</p>
                {item.demoMeta?.label ? (
                  <p className="mt-1 text-xs font-semibold text-cta">{item.demoMeta.label}</p>
                ) : null}
                {teamCount > 0 ? (
                  <p className="mt-1 text-xs font-semibold text-primary">{teamCount} team member{teamCount === 1 ? "" : "s"}</p>
                ) : null}
              </div>
              <Badge tone={item.id === project.id ? "success" : "neutral"}>{item.id === project.id ? "active" : item.status}</Badge>
            </div>
            <div className="mt-4 rounded-xl bg-white/70 p-3">
              <div className="mb-2 flex justify-between text-sm">
                <span className="font-semibold">Progress</span>
                <span className="font-bold text-primary">{item.progressPct || 0}%</span>
              </div>
              <ProgressBar value={item.progressPct}/>
            </div>
            <div className="mt-4 flex flex-wrap items-center justify-between gap-2">
              <span className="text-xs font-semibold text-text-muted">
                {item.id === project.id ? "Current workspace project" : "Available in portfolio"}
              </span>
              {item.id === project.id ? (
                <Button variant="secondary" onClick={() => onOpenProjectModal ? onOpenProjectModal("edit") : onNav("createProject")}>Edit</Button>
              ) : (
                <Button variant="secondary" onClick={() => window.ConstructProData.setActiveProject(item.id)}>Set Active</Button>
              )}
            </div>
          </Card>
          );
        })}
      </div>

      <Card className="mb-6">
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1.2fr_.8fr]">
          <div>
            <div className="mb-3 flex flex-wrap items-center gap-2">
              <h2 className="text-xl font-bold">{project.name}</h2>
              <Badge tone="orange">{project.code}</Badge>
            </div>
            {projectSubtitle ? <p className="text-sm text-text-muted">{projectSubtitle}</p> : null}
            <div className="mt-5">
              <div className="mb-2 flex justify-between text-sm">
                <span className="font-semibold">Overall progress from tasks/subtasks</span>
                <span className="font-bold text-cta">{rollups.progressPct}%</span>
              </div>
              <ProgressBar value={rollups.progressPct}/>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <ProjectMetric label="Work Items" value={rollups.total}/>
            <ProjectMetric label="Open" value={rollups.open}/>
            <ProjectMetric label="Budget" value={ff(rollups.budgetPlanned || project.budgetTotal)}/>
            <ProjectMetric label="Timeline" value={timelineValue}/>
          </div>
        </div>
      </Card>

      <Card className="mb-6">
        <ProjectTeamSummary
          teamAssignments={project.teamAssignments}
          users={users}
          onEdit={hasActiveProject ? openTeamEditor : null}
        />
      </Card>

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        {roots.map((item) => (
          <Card key={item.id}>
            <div className="mb-3 flex items-center justify-between gap-3">
              <h3 className="font-bold">{item.title}</h3>
              <Badge tone={item.rollup.status === "done" || item.rollup.status === "approved" ? "success" : item.rollup.status === "blocked" ? "danger" : "warning"}>{item.rollup.status}</Badge>
            </div>
            <ProgressBar value={item.rollup.progressPct}/>
            <div className="mt-4 space-y-2">
              {(item.children || []).slice(0, 4).map((child) => (
                <div key={child.id} className="flex items-center justify-between gap-3 text-sm">
                  <span className="truncate">{child.title}</span>
                  <span className="font-semibold text-text-muted">
                    {child.rollup?.subtaskProgress?.total
                      ? `${child.rollup.subtaskProgress.done}/${child.rollup.subtaskProgress.total} · ${child.rollup.progressPct}%`
                      : `${child.rollup.progressPct}%`}
                  </span>
                </div>
              ))}
              {!item.children?.length && <p className="text-sm text-text-muted">No child work yet.</p>}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function ProjectMetric({ label, value }) {
  return (
    <div className="rounded-xl bg-gray-50 p-4">
      <p className="text-xs font-bold uppercase text-text-muted">{label}</p>
      <p className="mt-1 font-bold">{value}</p>
    </div>
  );
}

Object.assign(window, { ProjectDetail });
