"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { createContext, useContext, useState, useEffect, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "../hooks/useAuth.js";
import { TeamSwitchModal } from "../components/teams/TeamSwitchModal.js";
import { APP_CONFIG_MERGED } from "../lib/config/config-sync.js";
import { canUserCreateTeam } from "../lib/teams/helpers.js";
const TeamContext = createContext(void 0);
const TEAMS_QUERY_KEY = ["user-teams"];
async function fetchUserTeams() {
  const response = await fetch("/api/v1/teams");
  const data = await response.json();
  if (!response.ok || !data.data) {
    throw new Error("Failed to fetch teams");
  }
  return 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
  }));
}
function TeamProvider({ children }) {
  const { user, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const queryClient = useQueryClient();
  const [currentTeam, setCurrentTeam] = useState(null);
  const [isSwitching, setIsSwitching] = useState(false);
  const [initialSyncDone, setInitialSyncDone] = useState(false);
  const [switchModalOpen, setSwitchModalOpen] = useState(false);
  const [previousTeam, setPreviousTeam] = useState(null);
  const [targetTeam, setTargetTeam] = useState(null);
  const {
    data: userTeams = [],
    isLoading: teamsLoading,
    refetch: refetchTeams
  } = useQuery({
    queryKey: TEAMS_QUERY_KEY,
    queryFn: fetchUserTeams,
    enabled: !!user && !authLoading,
    staleTime: 1e3 * 60 * 5,
    // Cache for 5 minutes - prevents refetch on navigation
    gcTime: 1e3 * 60 * 60,
    // Keep in cache for 1 hour
    refetchOnWindowFocus: false,
    // Don't refetch when window regains focus
    refetchOnMount: false
    // Don't refetch if data exists and is not stale
  });
  const isLoading = authLoading || teamsLoading;
  const canCurrentUserCreateTeam = useMemo(() => {
    if (!user || !userTeams.length) return false;
    const { mode, options } = APP_CONFIG_MERGED.teams;
    const ownedTeamsCount = userTeams.filter((m) => m.role === "owner").length;
    return canUserCreateTeam(mode, options || {}, ownedTeamsCount);
  }, [userTeams, user]);
  useEffect(() => {
    if (!user || !userTeams.length || initialSyncDone) return;
    const storedTeamId = typeof window !== "undefined" ? localStorage.getItem("activeTeamId") : null;
    const storedTeam = storedTeamId ? userTeams.find((t) => t.team.id === storedTeamId) : null;
    const activeTeam = storedTeam || userTeams[0];
    if (activeTeam) {
      setCurrentTeam(activeTeam.team);
      if (typeof window !== "undefined") {
        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));
      }
      setInitialSyncDone(true);
    }
  }, [user, userTeams, initialSyncDone]);
  useEffect(() => {
    if (!user && !authLoading) {
      setCurrentTeam(null);
      setInitialSyncDone(false);
      if (typeof window !== "undefined") {
        localStorage.removeItem("activeTeamId");
      }
      queryClient.clear();
    }
  }, [user, authLoading, queryClient]);
  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 } }));
    }
    if (typeof window !== "undefined") {
      window.location.reload();
    }
  }, [queryClient, targetTeam]);
  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 queryClient.invalidateQueries({ queryKey: TEAMS_QUERY_KEY });
    await refetchTeams();
  }, [queryClient, refetchTeams]);
  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 {
  TEAMS_QUERY_KEY,
  TeamProvider,
  fetchUserTeams,
  useTeamContext
};
