import { LocalNotifications } from "@capacitor/local-notifications";
import { platformRuntime } from "../../platform/runtime.js";
import { notificationPreferenceEnabled } from "./notification-settings.js";

export function createSystemNotificationAdapter() {
  if (platformRuntime.isNative) {
    return {
      permission: async () => normalizeNativePermission((await LocalNotifications.checkPermissions()).display),
      requestPermission: async () => normalizeNativePermission((await LocalNotifications.requestPermissions()).display),
      show: async (notification) => LocalNotifications.schedule({ notifications: [{
        id: numericNotificationId(notification.id),
        title: systemNotificationTitle(notification),
        body: notification.detail || "Code Remote Manager",
        extra: { notificationId: notification.id, sessionId: notification.sessionId || "" }
      }] })
    };
  }

  return {
    permission: async () => webPermission(),
    requestPermission: async () => typeof Notification === "undefined" ? "unsupported" : Notification.requestPermission(),
    show: showWebNotification
  };
}

export async function getSystemNotificationPermission(adapter = createSystemNotificationAdapter()) {
  try { return await adapter.permission(); } catch { return "unsupported"; }
}

export async function requestSystemNotificationPermission(adapter = createSystemNotificationAdapter()) {
  try { return await adapter.requestPermission(); } catch { return "denied"; }
}

export async function deliverSystemNotifications(previous, next, preferences, adapter = createSystemNotificationAdapter()) {
  const previousIds = new Set((previous ?? []).map((item) => item.id));
  const pending = (next ?? []).filter((item) => !previousIds.has(item.id) && notificationPreferenceEnabled(preferences, item.type));
  if (pending.length === 0 || await adapter.permission() !== "granted") return;
  for (const notification of pending) {
    try { await adapter.show(notification); } catch {}
  }
}

function webPermission() {
  return typeof Notification === "undefined" ? "unsupported" : Notification.permission;
}

async function showWebNotification(notification) {
  const options = {
    body: notification.detail || "Code Remote Manager",
    icon: "/icons/icon-192.png?v=8",
    tag: notification.id,
    data: { notificationId: notification.id, sessionId: notification.sessionId || "" }
  };
  const registration = await globalThis.navigator?.serviceWorker?.getRegistration?.();
  const title = systemNotificationTitle(notification);
  if (registration?.showNotification) return registration.showNotification(title, options);
  return new Notification(title, options);
}

function systemNotificationTitle(notification) {
  return notification.conversationTitle?.trim() || notification.title;
}

function normalizeNativePermission(permission) {
  if (permission === "granted") return "granted";
  if (permission === "denied") return "denied";
  return "prompt";
}

function numericNotificationId(value) {
  let hash = 0;
  for (const character of String(value)) hash = ((hash << 5) - hash + character.charCodeAt(0)) | 0;
  return Math.max(1, Math.abs(hash));
}
