"use client";

const PERMISSION_PROMPTED_KEY = "mindavio-browser-notifications-prompted";

export function canUseBrowserNotifications() {
  return typeof window !== "undefined" && "Notification" in window;
}

export async function requestBrowserNotificationPermissionOnce() {
  if (!canUseBrowserNotifications()) return false;
  if (Notification.permission === "granted") return true;
  if (Notification.permission === "denied") return false;

  try {
    const alreadyPrompted = window.localStorage.getItem(PERMISSION_PROMPTED_KEY) === "1";
    if (alreadyPrompted) return false;
    window.localStorage.setItem(PERMISSION_PROMPTED_KEY, "1");
    const permission = await Notification.requestPermission();
    return permission === "granted";
  } catch {
    return false;
  }
}

export function showBrowserNotification({
  body,
  tag,
  title,
  url,
}: {
  body?: string | null;
  tag?: string;
  title: string;
  url?: string;
}) {
  if (!canUseBrowserNotifications() || Notification.permission !== "granted") return;

  try {
    const notification = new Notification(title, {
      body: body || undefined,
      icon: "/mindavio-logo-transparent.png",
      tag,
    });

    if (url) {
      notification.onclick = () => {
        window.focus();
        window.location.href = url;
        notification.close();
      };
    }
  } catch {
    // Browser notification support varies, especially in dev and private windows.
  }
}
