// Browser push notifications for alert rules. Uses the Web Notifications API
// (works while the tab is backgrounded, in another window, or minimised on
// desktop OSes). Persists a single boolean in localStorage so the toggle in
// the alert-rules card survives reloads.
//
// This intentionally does NOT register a service worker — that would be
// needed only for delivery while the browser is fully closed, which is out
// of scope here.

const KEY = "delta.alertPush.v1";

export type PushPermission = "granted" | "denied" | "default" | "unsupported";

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

export function getPushPermission(): PushPermission {
  if (!pushSupported()) return "unsupported";
  return Notification.permission as PushPermission;
}

export function readPushEnabled(): boolean {
  if (typeof window === "undefined") return false;
  return window.localStorage.getItem(KEY) === "1";
}

export function writePushEnabled(v: boolean) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(KEY, v ? "1" : "0");
  window.dispatchEvent(new CustomEvent("delta:push-enabled-changed"));
}

/** Prompts for permission the first time; resolves to the final permission. */
export async function ensurePushPermission(): Promise<PushPermission> {
  if (!pushSupported()) return "unsupported";
  if (Notification.permission === "granted") return "granted";
  if (Notification.permission === "denied") return "denied";
  try {
    const p = await Notification.requestPermission();
    return p as PushPermission;
  } catch {
    return "denied";
  }
}

export interface PushOptions {
  title: string;
  body: string;
  severity: "warn" | "critical";
  tag?: string; // dedupe key — replacing an existing notification with the same tag
}

/**
 * Fires a Notification if the user is opted in and permission is granted.
 * No-ops silently otherwise. Returns true if a notification was created.
 */
export function firePushNotification(opts: PushOptions): boolean {
  if (!pushSupported()) return false;
  if (Notification.permission !== "granted") return false;
  if (!readPushEnabled()) return false;
  // Only surface OS notifications when the tab is actually backgrounded /
  // hidden — otherwise the sonner toast is already visible and firing a
  // native banner on top of it is noisy and duplicative.
  if (typeof document !== "undefined" && document.visibilityState === "visible") return false;
  try {
    const n = new Notification(opts.title, {
      body: opts.body,
      tag: opts.tag,
      silent: opts.severity === "warn",
      requireInteraction: opts.severity === "critical",
      icon: "/favicon.ico",
    });
    n.onclick = () => {
      try {
        window.focus();
        n.close();
      } catch {
        /* noop */
      }
    };
    return true;
  } catch {
    return false;
  }
}
