"use client";

export const FAVORITE_ENTRY_QUERY_PARAM = "favorite";
export const FAVORITE_ENTRY_QUERY_VALUE = "1";

const FAVORITE_ENTRY_STORAGE_KEY = "cozsweet:favorite_entry";

export type FavoriteEntryMode = "favorite" | "download" | "saved";

export interface FavoriteEntryModeInput {
  hasFavoriteIntent: boolean;
  isAndroid: boolean;
  isIOS: boolean;
  isInAppBrowser: boolean;
  isInstalled: boolean;
}

export function resolveFavoriteEntryMode({
  hasFavoriteIntent,
  isAndroid,
  isIOS,
  isInAppBrowser,
  isInstalled,
}: FavoriteEntryModeInput): FavoriteEntryMode {
  if (isInAppBrowser) return "favorite";
  if (isInstalled) return "saved";
  if (!hasFavoriteIntent) return "favorite";
  if (isAndroid) return "download";
  if (isIOS) return "download";
  return "saved";
}

export function isFavoriteEntryRequest(value?: string | null): boolean {
  return value?.trim() === FAVORITE_ENTRY_QUERY_VALUE;
}

export function persistFavoriteEntryIntent(): void {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(
    FAVORITE_ENTRY_STORAGE_KEY,
    FAVORITE_ENTRY_QUERY_VALUE,
  );
}

export function hasPersistedFavoriteEntryIntent(): boolean {
  if (typeof window === "undefined") return false;
  return (
    window.localStorage.getItem(FAVORITE_ENTRY_STORAGE_KEY) ===
    FAVORITE_ENTRY_QUERY_VALUE
  );
}
