interface OneSignalInitConfig {
  appId: string;
  allowLocalhostAsSecureOrigin?: boolean;
  welcomeNotification?: {
    disable: boolean;
  };
  promptOptions?: {
    slidedown?: {
      prompts?: Array<{
        type: string;
        autoPrompt: boolean;
        text?: {
          actionMessage: string;
          acceptButton: string;
          cancelButton: string;
        };
      }>;
    };
  };
}

// Extend Window interface for TypeScript
declare global {
  interface Window {
    OneSignal: any;
  }
}

// In-app subscriber callback
type NotificationCallback = (notification: {
  title: string;
  body: string;
  type: 'MATCH' | 'DEPOSIT' | 'WITHDRAW' | 'SYSTEM';
}) => void;

let callbackRegistry: NotificationCallback[] = [];

export const registerInAppHandler = (cb: NotificationCallback) => {
  callbackRegistry.push(cb);
  return () => {
    callbackRegistry = callbackRegistry.filter(c => c !== cb);
  };
};

export const triggerCustomNotification = (
  title: string,
  body: string,
  type: 'MATCH' | 'DEPOSIT' | 'WITHDRAW' | 'SYSTEM'
) => {
  console.log(`[Notification Triggered] Title: ${title}, Body: ${body}, Type: ${type}`);

  // 1. Try Native Web Notification API if permitted
  if ('Notification' in window) {
    if (Notification.permission === 'granted') {
      try {
        new Notification(title, {
          body,
          icon: '/logo.png', // Fallback icon path
        });
      } catch (e) {
        console.warn('Native notification failed, likely in iframe context:', e);
      }
    }
  }

  // 2. Sync to OneSignal if loaded
  if (window.OneSignal) {
    window.OneSignal.push(() => {
      // Send tags to OneSignal so we can segment/trigger push from dashboard
      const tagKey = `last_${type.toLowerCase()}`;
      window.OneSignal.User.addTag(tagKey, body);
      window.OneSignal.User.addTag('last_notification_time', new Date().toISOString());
      console.log(`[OneSignal Tag Updated] Key: ${tagKey}, Value: ${body}`);
    });
  }

  // 3. Trigger In-App animated toast notification
  callbackRegistry.forEach(cb => {
    try {
      cb({ title, body, type });
    } catch (err) {
      console.error('Error invoking in-app notification callback', err);
    }
  });
};

export const initOneSignal = () => {
  const appId = import.meta.env.VITE_ONESIGNAL_APP_ID || '8bd04d3e-b7d1-4db8-9293-1caef6ded2c5';
  
  if (typeof window === 'undefined') return;

  // Insert OneSignal CDN script dynamically if not present
  if (!document.getElementById('onesignal-sdk')) {
    const script = document.createElement('script');
    script.id = 'onesignal-sdk';
    script.src = 'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js';
    script.defer = true;
    script.async = true;
    document.head.appendChild(script);
  }

  window.OneSignal = window.OneSignal || [];
  window.OneSignal.push(() => {
    window.OneSignal.init({
      appId: appId,
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
        disable: false
      },
      promptOptions: {
        slidedown: {
          prompts: [
            {
              type: 'push',
              autoPrompt: true,
              text: {
                actionMessage: 'আমরা আপনাকে খেলা শুরু ও টাকা উত্তোলনের নোটিফিকেশন পাঠাতে চাই।',
                acceptButton: 'হ্যাঁ, নোটিফাই করুন',
                cancelButton: 'পরে করব'
              }
            }
          ]
        }
      }
    } as OneSignalInitConfig);

    console.log('OneSignal initialized successfully with App ID:', appId);
  });
};

export const requestNativeNotificationPermission = async (): Promise<string> => {
  if (!('Notification' in window)) {
    return 'unsupported';
  }

  if (Notification.permission === 'granted') {
    return 'granted';
  }

  try {
    const result = await Notification.requestPermission();
    return result;
  } catch (e) {
    return 'denied';
  }
};
