"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { TeamRoleForm, buildTeamRolePayload } from "@open-mercato/core/modules/staff/components/TeamRoleForm";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
function StaffTeamRoleCreatePage() {
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const scopeVersion = useOrganizationScopeVersion();
  const [teams, setTeams] = React.useState([]);
  const initialTeamId = searchParams?.get("teamId")?.trim() || null;
  React.useEffect(() => {
    let cancelled = false;
    async function loadTeams() {
      try {
        const params = new URLSearchParams({ page: "1", pageSize: "100" });
        const call = await apiCall(`/api/staff/teams?${params.toString()}`);
        const items = Array.isArray(call.result?.items) ? call.result.items : [];
        const options = items.map((team) => {
          const id = typeof team.id === "string" ? team.id : null;
          const name = typeof team.name === "string" ? team.name : null;
          if (!id || !name) return null;
          return { id, name };
        }).filter((entry) => entry !== null);
        if (!cancelled) setTeams(options);
      } catch {
        if (!cancelled) setTeams([]);
      }
    }
    loadTeams();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion]);
  const handleSubmit = React.useCallback(async (values) => {
    const payload = buildTeamRolePayload(values);
    await createCrud("staff/team-roles", payload, {
      errorMessage: t("staff.teamRoles.errors.save", "Failed to save team role.")
    });
    flash(t("staff.teamRoles.messages.saved", "Team role saved."), "success");
    router.push("/backend/staff/team-roles");
  }, [router, t]);
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    TeamRoleForm,
    {
      title: t("staff.teamRoles.form.createTitle", "Add team role"),
      backHref: "/backend/staff/team-roles",
      cancelHref: "/backend/staff/team-roles",
      submitLabel: t("staff.teamRoles.form.actions.create", "Create"),
      initialValues: { name: "", description: "", appearance: { icon: null, color: null }, teamId: initialTeamId },
      teamOptions: teams,
      onSubmit: handleSubmit
    }
  ) }) });
}
export {
  StaffTeamRoleCreatePage as default
};
//# sourceMappingURL=page.js.map
