import { readLocalStorage, writeLocalStorage, removeLocalStorage } from "@/lib/safeStorage";

const DISMISS_KEY = "pwa_install_dismissed_until";

export type BeforeInstallPromptEvent = Event & {
  prompt: () => Promise<void>;
  userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
};

export function isStandaloneMode(): boolean {
  if (typeof window === "undefined") return false;

  const nav = window.navigator as Navigator & { standalone?: boolean };
  return (
    window.matchMedia("(display-mode: standalone)").matches ||
    nav.standalone === true
  );
}

export function isIosDevice(): boolean {
  if (typeof window === "undefined") return false;
  return /iphone|ipad|ipod/i.test(window.navigator.userAgent);
}

export function isDismissed(): boolean {
  const until = Number(readLocalStorage(DISMISS_KEY) || 0);
  return Date.now() < until;
}

/** عدم نمایش تا ۷ روز */
export function dismissInstallPrompt(days = 7): void {
  const until = Date.now() + days * 24 * 60 * 60 * 1000;
  writeLocalStorage(DISMISS_KEY, String(until));
}

export function clearInstallDismissal(): void {
  removeLocalStorage(DISMISS_KEY);
}
