"use client";
import { Fragment, jsx } from "react/jsx-runtime";
import * as React from "react";
const DEFAULT_PLAN = "free";
const DEFAULT_FLAGS = [];
function getCachedUserFlags(userId) {
  try {
    const cached = localStorage.getItem(`user_flags_${userId}`);
    if (!cached) return null;
    const data = JSON.parse(cached);
    const now = Date.now();
    if (now - data.timestamp > 5 * 60 * 1e3) {
      localStorage.removeItem(`user_flags_${userId}`);
      return null;
    }
    return {
      flags: Array.isArray(data.flags) ? data.flags : DEFAULT_FLAGS,
      fromStorage: true
    };
  } catch (error) {
    console.error("Failed to get cached user flags:", error);
    return null;
  }
}
function getCachedUserPlanData(userId) {
  const flagsData = getCachedUserFlags(userId);
  if (!flagsData) return null;
  return {
    plan: DEFAULT_PLAN,
    // Always hardcoded
    flags: flagsData.flags,
    fromStorage: flagsData.fromStorage
  };
}
function cacheUserFlags(userId, flags) {
  try {
    const data = {
      flags,
      timestamp: Date.now()
    };
    localStorage.setItem(`user_flags_${userId}`, JSON.stringify(data));
  } catch (error) {
    console.error("Failed to cache user flags:", error);
  }
}
function clearCachedUserFlags(userId) {
  try {
    localStorage.removeItem(`user_flags_${userId}`);
  } catch (error) {
    console.error("Failed to clear cached user flags:", error);
  }
}
function cacheUserPlanData(userId, plan, flags) {
  cacheUserFlags(userId, flags);
}
async function fetchUserFlags(userId) {
  try {
    const response = await fetch(`/api/user/flags?userId=${userId}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch user flags: ${response.statusText}`);
    }
    const data = await response.json();
    const flags = Array.isArray(data.flags) ? data.flags : DEFAULT_FLAGS;
    cacheUserFlags(userId, flags);
    return {
      flags,
      fromStorage: false
    };
  } catch (error) {
    console.error("Failed to fetch user flags:", error);
    const cached = getCachedUserFlags(userId);
    if (cached) {
      return cached;
    }
    return {
      flags: DEFAULT_FLAGS,
      fromStorage: false
    };
  }
}
async function fetchUserPlanData(userId) {
  const flagsData = await fetchUserFlags(userId);
  return {
    plan: DEFAULT_PLAN,
    // Always hardcoded
    flags: flagsData.flags,
    fromStorage: flagsData.fromStorage
  };
}
async function getUserPlanDataWithCache(userId) {
  const cached = getCachedUserPlanData(userId);
  if (cached) {
    return cached;
  }
  return await fetchUserPlanData(userId);
}
async function updateUserPlanClient(userId, plan) {
  console.warn("updateUserPlanClient is deprecated - plans are hardcoded");
  return true;
}
async function updateUserFlagsClient(userId, flags) {
  try {
    const response = await fetch("/api/user/flags", {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        userId,
        flags
      })
    });
    if (!response.ok) {
      throw new Error(`Failed to update user flags: ${response.statusText}`);
    }
    cacheUserFlags(userId, flags);
    return true;
  } catch (error) {
    console.error("Failed to update user flags:", error);
    return false;
  }
}
function extractUserPlanDataWithCache(user) {
  if (!user) {
    return {
      plan: DEFAULT_PLAN,
      flags: DEFAULT_FLAGS,
      fromStorage: false
    };
  }
  const cached = getCachedUserPlanData(user.id);
  if (cached) {
    return cached;
  }
  return {
    plan: DEFAULT_PLAN,
    flags: DEFAULT_FLAGS,
    fromStorage: false
  };
}
function clearCachedUserPlanData(userId) {
  if (userId) {
    clearCachedUserFlags(userId);
  } else {
    const keys = Object.keys(localStorage).filter((key) => key.startsWith("user_flags_"));
    keys.forEach((key) => localStorage.removeItem(key));
  }
}
function useUserPlanData(user) {
  const [planData, setPlanData] = React.useState({
    plan: DEFAULT_PLAN,
    flags: DEFAULT_FLAGS,
    fromStorage: false
  });
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    if (!user) {
      setPlanData({
        plan: DEFAULT_PLAN,
        flags: DEFAULT_FLAGS,
        fromStorage: false
      });
      return;
    }
    const loadPlanData = async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await getUserPlanDataWithCache(user.id);
        setPlanData(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load user plan data");
        setPlanData({
          plan: DEFAULT_PLAN,
          flags: DEFAULT_FLAGS,
          fromStorage: false
        });
      } finally {
        setLoading(false);
      }
    };
    loadPlanData();
  }, [user]);
  const updatePlan = React.useCallback(async (plan) => {
    if (!user) return false;
    const success = await updateUserPlanClient(user.id, plan);
    if (success) {
      setPlanData((prev) => ({ ...prev, plan }));
    }
    return success;
  }, [user]);
  const updateFlags = React.useCallback(async (flags) => {
    if (!user) return false;
    const success = await updateUserFlagsClient(user.id, flags);
    if (success) {
      setPlanData((prev) => ({ ...prev, flags }));
    }
    return success;
  }, [user]);
  return {
    ...planData,
    loading,
    error,
    updatePlan,
    updateFlags,
    refetch: () => {
      if (user) {
        clearCachedUserPlanData(user.id);
        setPlanData((prev) => ({ ...prev }));
      }
    }
  };
}
function UserPlanDataProvider({
  children,
  user
}) {
  useUserPlanData(user);
  return /* @__PURE__ */ jsx(Fragment, { children });
}
export {
  UserPlanDataProvider,
  cacheUserFlags,
  cacheUserPlanData,
  clearCachedUserFlags,
  clearCachedUserPlanData,
  extractUserPlanDataWithCache,
  fetchUserFlags,
  fetchUserPlanData,
  getCachedUserFlags,
  getCachedUserPlanData,
  getUserPlanDataWithCache,
  updateUserFlagsClient,
  updateUserPlanClient,
  useUserPlanData
};
