/**
 * Browser Notification System
 * Uses Chrome Notifications API to display native OS notifications
 * Similar to MetaMask's notification system
 */

// Use chrome API directly for notifications (Chrome/Chromium only)
// Check for chrome or browser namespace (Firefox also supports chrome.* for compatibility)
const notificationsAPI = (() => {
  if (typeof chrome !== "undefined" && chrome.notifications) {
    return chrome.notifications;
  }
  if (typeof browser !== "undefined" && browser.notifications) {
    return browser.notifications;
  }
  return null;
})();

const DEFAULT_ICON = "public/xrpl universe.png";

/**
 * Get the extension icon URL for notifications
 */
function getNotificationIcon() {
  try {
    // Try chrome first, then browser
    const runtimeAPI = typeof chrome !== "undefined" && chrome.runtime 
      ? chrome.runtime 
      : (typeof browser !== "undefined" && browser.runtime ? browser.runtime : null);
    
    if (runtimeAPI && runtimeAPI.getURL) {
      return runtimeAPI.getURL(DEFAULT_ICON);
    }
    return undefined;
  } catch (error) {
    console.warn("[XRP Universe] Failed to get notification icon URL:", error);
    return undefined;
  }
}

/**
 * Request notification permission if not already granted
 */
export async function requestNotificationPermission() {
  if (!notificationsAPI) {
    return false;
  }

  try {
    // Chrome notifications don't require explicit permission request
    // Permission is granted automatically when extension uses notifications API
    // Check if the API is available - if so, we can use it
    if (typeof notificationsAPI.create === "function") {
      return true;
    }
    return false;
  } catch (error) {
    console.warn("[XRP Universe] Failed to check notification permission:", error);
    return false;
  }
}

/**
 * Show a success notification for transaction
 */
export async function showTransactionSuccessNotification({ hash, amount, type = "Transaction" }) {
  if (!(await requestNotificationPermission())) {
    return;
  }

  try {
    const iconUrl = getNotificationIcon();
    const message = amount 
      ? `${type} successful: ${amount}`
      : `${type} successful`;
    
    const notificationId = await new Promise((resolve, reject) => {
      notificationsAPI.create(
        {
          type: "basic",
          iconUrl: iconUrl,
          title: "Transaction Successful",
          message: message,
          contextMessage: hash ? `Hash: ${hash.slice(0, 8)}...${hash.slice(-6)}` : undefined,
          priority: 1,
        },
        (id) => {
          const runtimeAPI = typeof chrome !== "undefined" && chrome.runtime 
            ? chrome.runtime 
            : (typeof browser !== "undefined" && browser.runtime ? browser.runtime : null);
          const lastError = runtimeAPI?.lastError;
          if (lastError) {
            reject(new Error(lastError.message));
          } else {
            resolve(id);
          }
        }
      );
    });

    // Auto-close notification after 5 seconds
    setTimeout(() => {
      try {
        notificationsAPI.clear(notificationId);
      } catch (error) {
        // Ignore errors when clearing
      }
    }, 5000);

    return notificationId;
  } catch (error) {
    console.error("[XRP Universe] Failed to show success notification:", error);
  }
}

/**
 * Show a failure notification for transaction
 */
export async function showTransactionFailureNotification({ hash, error, type = "Transaction" }) {
  if (!(await requestNotificationPermission())) {
    return;
  }

  try {
    const iconUrl = getNotificationIcon();
    const errorMessage = error?.message || error || "Unknown error";
    const shortMessage = errorMessage.length > 100 
      ? errorMessage.substring(0, 100) + "..."
      : errorMessage;

    const notificationId = await new Promise((resolve, reject) => {
      notificationsAPI.create(
        {
          type: "basic",
          iconUrl: iconUrl,
          title: "Transaction Failed",
          message: `${type} failed: ${shortMessage}`,
          contextMessage: hash ? `Hash: ${hash.slice(0, 8)}...${hash.slice(-6)}` : undefined,
          priority: 2,
        },
        (id) => {
          const runtimeAPI = typeof chrome !== "undefined" && chrome.runtime 
            ? chrome.runtime 
            : (typeof browser !== "undefined" && browser.runtime ? browser.runtime : null);
          const lastError = runtimeAPI?.lastError;
          if (lastError) {
            reject(new Error(lastError.message));
          } else {
            resolve(id);
          }
        }
      );
    });

    // Auto-close notification after 8 seconds (longer for errors)
    setTimeout(() => {
      try {
        notificationsAPI.clear(notificationId);
      } catch (error) {
        // Ignore errors when clearing
      }
    }, 8000);

    return notificationId;
  } catch (error) {
    console.error("[XRP Universe] Failed to show failure notification:", error);
  }
}

/**
 * Show a pending notification for transaction
 */
export async function showTransactionPendingNotification({ hash, type = "Transaction" }) {
  if (!(await requestNotificationPermission())) {
    return;
  }

  try {
    const iconUrl = getNotificationIcon();
    
    const notificationId = await new Promise((resolve, reject) => {
      notificationsAPI.create(
        {
          type: "basic",
          iconUrl: iconUrl,
          title: "Transaction Pending",
          message: `${type} is being processed...`,
          contextMessage: hash ? `Hash: ${hash.slice(0, 8)}...${hash.slice(-6)}` : undefined,
          priority: 0,
        },
        (id) => {
          const runtimeAPI = typeof chrome !== "undefined" && chrome.runtime 
            ? chrome.runtime 
            : (typeof browser !== "undefined" && browser.runtime ? browser.runtime : null);
          const lastError = runtimeAPI?.lastError;
          if (lastError) {
            reject(new Error(lastError.message));
          } else {
            resolve(id);
          }
        }
      );
    });

    return notificationId;
  } catch (error) {
    console.error("[XRP Universe] Failed to show pending notification:", error);
  }
}

/**
 * Clear a notification by ID
 */
export function clearNotification(notificationId) {
  if (!notificationId || !notificationsAPI) return;
  
  try {
    notificationsAPI.clear(notificationId, (wasCleared) => {
      const runtimeAPI = typeof chrome !== "undefined" && chrome.runtime 
        ? chrome.runtime 
        : (typeof browser !== "undefined" && browser.runtime ? browser.runtime : null);
      const lastError = runtimeAPI?.lastError;
      if (!wasCleared && lastError) {
        console.warn("[XRP Universe] Failed to clear notification:", lastError);
      }
    });
  } catch (error) {
    console.warn("[XRP Universe] Error clearing notification:", error);
  }
}

/**
 * Handle notification click events
 * Opens XRPL explorer or extension popup based on notification type
 */
export function setupNotificationClickHandler() {
  if (!notificationsAPI || !notificationsAPI.onClicked) {
    return;
  }

  notificationsAPI.onClicked.addListener((notificationId) => {
    try {
      // Get notification details from the ID (we could store this in a map)
      // For now, just close the notification
      notificationsAPI.clear(notificationId);
      
      // Optionally open the extension popup or XRPL explorer
      // This could be enhanced to open specific transaction details
      const actionAPI = typeof chrome !== "undefined" && chrome.action 
        ? chrome.action 
        : (typeof browser !== "undefined" && browser.action ? browser.action : null);
      actionAPI?.openPopup?.();
    } catch (error) {
      console.warn("[XRP Universe] Error handling notification click:", error);
    }
  });
}

