function FieldTeams({ snapshot }) {
  const alerts = snapshot.alerts || [];
  const activeAlerts = alerts.filter((alert) => alert.status === "active");
  const submittedAlerts = alerts.filter((alert) => alert.status === "submitted");
  const escalatedAlerts = alerts.filter((alert) => alert.status === "escalated");
  const users = snapshot.users || [];
  const assignmentsByRole = users.map((user) => {
    const siteStatus = user.status || "off_site";
    return {
      ...user,
      siteStatus,
      assigned: (snapshot.workItems || []).filter((item) => item.assigneeRole === user.role && item.type !== "phase"),
      activeAlerts: activeAlerts.filter((alert) => (alert.roles || []).includes(user.role))
    };
  });

  return (
    <div className="fade-in">
      <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-4">
        <StatCard title="Team Members" value={users.length} trend={`${snapshot.project.teamSize || users.length} planned`} icon={<Icons.users/>} tone="success"/>
        <StatCard title="Active Alerts" value={activeAlerts.length} trend="Countdown running" icon={<Icons.bell/>} tone="warning"/>
        <StatCard title="Ready to Approve" value={submittedAlerts.length} trend="Evidence submitted" icon={<Icons.check/>} tone="info"/>
        <StatCard title="Escalated" value={escalatedAlerts.length} trend="SLA missed" icon={<Icons.alert/>} tone={escalatedAlerts.length ? "danger" : "success"}/>
      </div>

      <AlertLauncher/>

      <div className="grid grid-cols-1 gap-6 xl:grid-cols-[.9fr_1.1fr]">
        <Card>
          <SectionTitle title="Live Site Feed" subtitle="Users, assigned work, and alert routing." />
          <div className="space-y-3">
            {!users.length && (
              <p className="text-sm text-text-muted text-center py-6">
                No team members configured yet. Add team assignments when creating or editing a project.
              </p>
            )}
            {assignmentsByRole.map((person) => (
              <div key={person.id} className="grid grid-cols-1 gap-2 rounded-xl bg-gray-50 p-4 md:grid-cols-[1fr_auto_auto] md:items-center">
                <div>
                  <p className="font-bold">{person.name}</p>
                  <p className="text-xs text-text-muted">{person.role} · {person.company || "Site Team"} · {person.assigned.length} assigned</p>
                </div>
                <Badge tone={person.siteStatus === "outside_perimeter" ? "danger" : person.siteStatus === "on_site" ? "success" : "warning"}>{person.siteStatus.replace(/_/g, " ")}</Badge>
                <span className="text-xs font-semibold text-text-muted">{person.activeAlerts.length} alerts</span>
              </div>
            ))}
          </div>
        </Card>

        <AlertPanel snapshot={snapshot}/>
      </div>
    </div>
  );
}

Object.assign(window, { FieldTeams });
