/**
 * otpNotificationManager.js
 * OTP Testing & Automation Framework — Notification System
 *
 * FOR DEV / STAGING / QA / ACCESSIBILITY TESTING ONLY.
 *
 * When OTP is required:
 *   - popup notification
 *   - sound alert (with autoplay restriction handling)
 *   - badge flash
 *   - browser notification
 *   - screen reader announcement (ARIA live region)
 *   - reduced motion fallback
 *
 * Does NOT crash if audio is blocked.
 */
(function initVisaFlowXOtpNotificationManager(global) {
  "use strict";

  function log(msg) {
    console.log("[VisaFlowX][OtpNotificationManager]", msg);
  }

  // ── Accessibility: ARIA live region ─────────────────────────
  let _ariaLiveEl = null;

  function _ensureAriaLive() {
    if (_ariaLiveEl || typeof document === "undefined") return;
    _ariaLiveEl = document.createElement("div");
    _ariaLiveEl.setAttribute("role", "alert");
    _ariaLiveEl.setAttribute("aria-live", "assertive");
    _ariaLiveEl.setAttribute("aria-atomic", "true");
    _ariaLiveEl.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;";
    document.body?.appendChild(_ariaLiveEl);
  }

  function announceForScreenReader(message) {
    _ensureAriaLive();
    if (_ariaLiveEl) {
      _ariaLiveEl.textContent = "";
      setTimeout(() => { if (_ariaLiveEl) _ariaLiveEl.textContent = message; }, 50);
    }
  }

  // ── Sound alert ──────────────────────────────────────────────
  async function playOtpSound(options = {}) {
    const handler = global.VisaFlowX?.NotificationHandler;
    if (!handler) {
      log("NotificationHandler not available");
      return { ok: false, error: "NotificationHandler_missing" };
    }
    try {
      return await handler.forcePlayOtpAlarm(options);
    } catch (err) {
      log(`Sound blocked or failed (non-fatal): ${err.message}`);
      return { ok: false, blocked: true, error: err.message };
    }
  }

  // ── Badge flash via service worker ───────────────────────────
  function flashBadge() {
    if (typeof chrome !== "undefined" && chrome?.runtime?.sendMessage) {
      chrome.runtime.sendMessage({ type: "OTP_BADGE_FLASH" }).catch(() => {});
    }
  }

  // ── Browser notification via SW ──────────────────────────────
  function sendBrowserNotification(title = "OTP Required", body = "Complete your verification now.") {
    if (typeof chrome !== "undefined" && chrome?.runtime?.sendMessage) {
      chrome.runtime.sendMessage({
        type:    "OTP_FALLBACK_NOTIFICATION",
        title,
        message: body
      }).catch(() => {});
    }
  }

  // ── Popup pulse ──────────────────────────────────────────────
  function pulsePopup() {
    if (typeof document !== "undefined") {
      document.dispatchEvent(new CustomEvent("VFX_OTP_PULSE", { bubbles: true }));
    }
    if (typeof chrome !== "undefined" && chrome?.runtime?.sendMessage) {
      chrome.runtime.sendMessage({ type: "OTP_POPUP_PULSE" }).catch(() => {});
    }
  }

  // ── Reduced motion check ─────────────────────────────────────
  function prefersReducedMotion() {
    if (typeof window === "undefined") return false;
    return window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true;
  }

  /**
   * notifyOtpRequired — master notification dispatcher.
   * Fires all available channels. Never throws.
   */
  async function notifyOtpRequired(options = {}) {
    const {
      title   = "OTP Required",
      message = "OTP page detected. Complete your verification now.",
      volume  = 1,
      muted   = false
    } = options;

    log("OTP page detected");

    // 1. Screen reader announcement (always works)
    announceForScreenReader(message);

    // 2. Sound (graceful — falls back automatically)
    const soundResult = await playOtpSound({ volume, muted });
    if (!soundResult.ok) {
      log("Fallback: sound blocked — using visual + notification channels");
    }

    // 3. Badge flash
    flashBadge();

    // 4. Browser notification
    sendBrowserNotification(title, message);

    // 5. Popup pulse (skip if reduced motion)
    if (!prefersReducedMotion()) {
      pulsePopup();
    }

    return { ok: true, soundResult };
  }

  /**
   * dismissOtpAlert — call when OTP is submitted or user dismisses.
   */
  function dismissOtpAlert() {
    const handler = global.VisaFlowX?.NotificationHandler;
    if (handler?.stopAlarm) handler.stopAlarm();
    log("OTP alert dismissed");
  }

  const OtpNotificationManager = Object.freeze({
    notifyOtpRequired,
    dismissOtpAlert,
    announceForScreenReader,
    flashBadge,
    sendBrowserNotification,
    pulsePopup,
    playOtpSound
  });

  global.VisaFlowX = Object.assign(global.VisaFlowX || {}, { OtpNotificationManager });

  if (typeof module !== "undefined" && module.exports) {
    module.exports = OtpNotificationManager;
  }
})(typeof globalThis !== "undefined" ? globalThis : this);
