import { sessionStorage } from "@applicaster/zapp-react-native-bridge/ZappStorage/SessionStorage";

const NETWORK_STATUS_LOCALIZATIONS_KEY = "network_status_localizations";
const THEME_STORAGE_NAMESPACE = "quick-brick-theme";

const DEFAULT_NETWORK_STATUS_LOCALIZATIONS: Record<string, string> = {
  offline_notification_title: "No internet connection",
  offline_notification_subtitle: "Please check your connection",
  online_notification_title: "You are back online",
  online_notification_subtitle: "Feel free to continue where you left off",
};

const NETWORK_STATUS_KEYS = Object.keys(
  DEFAULT_NETWORK_STATUS_LOCALIZATIONS
) as (keyof typeof DEFAULT_NETWORK_STATUS_LOCALIZATIONS)[];

export async function saveNetworkStatusLocalizations(
  themeOrLocalizations: Record<string, unknown>
) {
  try {
    const storedLocalizations = await sessionStorage.getItem(
      NETWORK_STATUS_LOCALIZATIONS_KEY,
      THEME_STORAGE_NAMESPACE
    );

    if (storedLocalizations) {
      return;
    }

    const networkStatusLocalizations = NETWORK_STATUS_KEYS.reduce(
      (acc, key) => {
        const value = themeOrLocalizations[key];

        acc[key] =
          typeof value === "string"
            ? value
            : DEFAULT_NETWORK_STATUS_LOCALIZATIONS[key];

        return acc;
      },
      {} as Record<string, string>
    );

    if (Object.keys(networkStatusLocalizations).length > 0) {
      await sessionStorage.setItem(
        NETWORK_STATUS_LOCALIZATIONS_KEY,
        JSON.stringify(networkStatusLocalizations),
        THEME_STORAGE_NAMESPACE
      );
    }
  } catch (error) {
    console.error("Error saving network status localizations", error);
  }
}
