"use client";
import { jsx } from "react/jsx-runtime";
import { createContext, useContext, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTeam } from "../hooks/useTeam.js";
import { BILLING_REGISTRY } from "@nextsparkjs/registries/billing-registry";
const SubscriptionContext = createContext(void 0);
function SubscriptionProvider({ children }) {
  var _a;
  const { team } = useTeam();
  const {
    data: subscription,
    isLoading,
    isFetched,
    error,
    refetch
  } = useQuery({
    queryKey: ["subscription", team == null ? void 0 : team.id],
    queryFn: async () => {
      var _a2;
      if (!team) return null;
      const response = await fetch(`/api/v1/teams/${team.id}/subscription`);
      if (!response.ok) {
        if (response.status === 404) return null;
        throw new Error("Failed to fetch subscription");
      }
      const data = await response.json();
      return ((_a2 = data.data) == null ? void 0 : _a2.subscription) ?? data.data;
    },
    enabled: !!team && BILLING_REGISTRY.plans.length > 0,
    staleTime: 5 * 60 * 1e3,
    // 5 minutes
    refetchOnWindowFocus: false
  });
  const features = useMemo(() => {
    if (!(subscription == null ? void 0 : subscription.plan)) return [];
    const planConfig = BILLING_REGISTRY.plans.find((p) => p.slug === subscription.plan.slug);
    return (planConfig == null ? void 0 : planConfig.features) ?? [];
  }, [subscription == null ? void 0 : subscription.plan]);
  const limits = useMemo(() => {
    if (!(subscription == null ? void 0 : subscription.plan)) return {};
    const planConfig = BILLING_REGISTRY.plans.find((p) => p.slug === subscription.plan.slug);
    if (!planConfig) return {};
    const limitsObj = {};
    for (const [limitSlug, max] of Object.entries(planConfig.limits)) {
      const limitConfig = BILLING_REGISTRY.limits[limitSlug];
      limitsObj[limitSlug] = {
        max,
        resetPeriod: (limitConfig == null ? void 0 : limitConfig.resetPeriod) ?? "never"
      };
    }
    return limitsObj;
  }, [subscription == null ? void 0 : subscription.plan]);
  const customerProfile = useMemo(() => {
    var _a2;
    return {
      // Team metadata (business attributes from teams.metadata JSONB)
      teamMetadata: (team == null ? void 0 : team.metadata) ?? {},
      // Subscription data
      plan: (subscription == null ? void 0 : subscription.plan) ?? null,
      planSlug: ((_a2 = subscription == null ? void 0 : subscription.plan) == null ? void 0 : _a2.slug) ?? null,
      status: (subscription == null ? void 0 : subscription.status) ?? null,
      isTrialing: (subscription == null ? void 0 : subscription.status) === "trialing",
      isActive: (subscription == null ? void 0 : subscription.status) === "active",
      // Features and limits from plan config
      features,
      limits
    };
  }, [team, subscription, features, limits]);
  const value = {
    subscription: subscription ?? null,
    plan: (subscription == null ? void 0 : subscription.plan) ?? null,
    planSlug: ((_a = subscription == null ? void 0 : subscription.plan) == null ? void 0 : _a.slug) ?? null,
    status: (subscription == null ? void 0 : subscription.status) ?? null,
    isTrialing: (subscription == null ? void 0 : subscription.status) === "trialing",
    isActive: (subscription == null ? void 0 : subscription.status) === "active",
    isPastDue: (subscription == null ? void 0 : subscription.status) === "past_due",
    isCanceled: (subscription == null ? void 0 : subscription.status) === "canceled",
    isLoading,
    isReady: isFetched,
    error,
    refetch: () => {
      refetch();
    },
    features,
    limits,
    customerProfile
  };
  return /* @__PURE__ */ jsx(SubscriptionContext.Provider, { value, children });
}
function useSubscriptionContext() {
  const context = useContext(SubscriptionContext);
  if (context === void 0) {
    throw new Error("useSubscriptionContext must be used within a SubscriptionProvider");
  }
  return context;
}
export {
  SubscriptionProvider,
  useSubscriptionContext
};
