"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { createContext, useContext, useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { useAuth } from "../hooks/useAuth";
import { TeamSwitchModal } from "../components/teams/TeamSwitchModal";
import { APP_CONFIG_MERGED } from "../lib/config/config-sync";
import { canUserCreateTeam } from "../lib/teams/helpers";
const TeamContext = createContext(void 0);
function TeamProvider({ children }) {
  const { user } = useAuth();
  const router = useRouter();
  const queryClient = useQueryClient();
  const [currentTeam, setCurrentTeam] = useState(null);
  const [userTeams, setUserTeams] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSwitching, setIsSwitching] = useState(false);
  const [canCurrentUserCreateTeam, setCanCurrentUserCreateTeam] = useState(true);
  const [switchModalOpen, setSwitchModalOpen] = useState(false);
  const [previousTeam, setPreviousTeam] = useState(null);
  const [targetTeam, setTargetTeam] = useState(null);
  const loadUserTeams = useCallback(async () => {
    if (!user) {
      setUserTeams([]);
      setCurrentTeam(null);
      setIsLoading(false);
      return;
    }
    try {
      setIsLoading(true);
      const response = await fetch("/api/v1/teams");
      const data = await response.json();
      if (response.ok && data.data) {
        const teams = data.data.map((t) => ({
          team: {
            id: t.id,
            name: t.name,
            slug: t.slug,
            description: t.description,
            ownerId: t.owner_id || t.ownerId,
            avatarUrl: t.avatar_url || t.avatarUrl,
            settings: t.settings || {},
            createdAt: t.created_at || t.createdAt,
            updatedAt: t.updated_at || t.updatedAt
          },
          role: t.userRole || t.user_role || t.role,
          joinedAt: t.joinedAt || t.joined_at
        }));
        setUserTeams(teams);
        const storedTeamId = typeof window !== "undefined" ? localStorage.getItem("activeTeamId") : null;
        const storedTeam = teams.find((t) => t.team.id === storedTeamId);
        const activeTeam = storedTeam || teams[0];
        if (activeTeam) {
          setCurrentTeam(activeTeam.team);
          if (typeof window !== "undefined" && storedTeamId !== activeTeam.team.id) {
            localStorage.setItem("activeTeamId", activeTeam.team.id);
          }
          if (typeof window !== "undefined") {
            fetch("/api/v1/teams/switch", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ teamId: activeTeam.team.id })
            }).catch((err) => console.error("Failed to sync team cookie:", err));
          }
        }
      }
    } catch (error) {
      console.error("Failed to load teams:", error);
    } finally {
      setIsLoading(false);
    }
  }, [user]);
  const handleSwitchComplete = useCallback(() => {
    setSwitchModalOpen(false);
    setIsSwitching(false);
    queryClient.clear();
    if (typeof window !== "undefined") {
      window.dispatchEvent(new CustomEvent("team-switched", { detail: { teamId: targetTeam == null ? void 0 : targetTeam.id } }));
    }
    router.refresh();
  }, [queryClient, targetTeam, router]);
  const switchTeam = useCallback(async (teamId) => {
    const membership = userTeams.find((t) => t.team.id === teamId);
    if (!membership) {
      throw new Error("Team not found or not a member");
    }
    if ((currentTeam == null ? void 0 : currentTeam.id) === teamId) {
      return;
    }
    setIsSwitching(true);
    setPreviousTeam(currentTeam);
    setTargetTeam(membership.team);
    setSwitchModalOpen(true);
    setCurrentTeam(membership.team);
    if (typeof window !== "undefined") {
      localStorage.setItem("activeTeamId", teamId);
    }
    try {
      await fetch("/api/v1/teams/switch", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ teamId })
      });
    } catch (error) {
      console.error("Failed to update team context on server:", error);
    }
  }, [userTeams, currentTeam]);
  const refreshTeams = useCallback(async () => {
    await loadUserTeams();
  }, [loadUserTeams]);
  useEffect(() => {
    loadUserTeams();
  }, [loadUserTeams]);
  useEffect(() => {
    if (!user || !userTeams) {
      setCanCurrentUserCreateTeam(false);
      return;
    }
    const { mode, options } = APP_CONFIG_MERGED.teams;
    const ownedTeamsCount = userTeams.filter((m) => m.role === "owner").length;
    const canCreate = canUserCreateTeam(mode, options || {}, ownedTeamsCount);
    setCanCurrentUserCreateTeam(canCreate);
  }, [userTeams, user]);
  return /* @__PURE__ */ jsxs(
    TeamContext.Provider,
    {
      value: {
        currentTeam,
        userTeams,
        isLoading,
        isSwitching,
        canCurrentUserCreateTeam,
        switchTeam,
        refreshTeams
      },
      children: [
        children,
        /* @__PURE__ */ jsx(
          TeamSwitchModal,
          {
            isOpen: switchModalOpen,
            fromTeam: previousTeam,
            toTeam: targetTeam,
            onComplete: handleSwitchComplete
          }
        )
      ]
    }
  );
}
function useTeamContext() {
  const context = useContext(TeamContext);
  if (context === void 0) {
    throw new Error("useTeamContext must be used within TeamProvider");
  }
  return context;
}
export {
  TeamProvider,
  useTeamContext
};
