'use strict';

(function (global) {
  if (typeof global.RbxDiscord !== 'undefined') return;

  async function getDiscordToken() {
    const g = typeof globalThis !== 'undefined' ? globalThis : global;
    const b = g.RbxExtensionBridge;
    if (!b || typeof b.getDiscordToken !== 'function') {
      throw new Error('Chrome runtime not available');
    }
    const response = await b.getDiscordToken();
    if (response && response.success && response.token) {
      return response.token;
    }
    throw new Error((response && response.error) || 'Discord token not found. Log in to Discord first.');
  }

  async function validateDiscordToken(token) {
    if (!token || typeof token !== 'string') {
      throw new Error('Invalid token format');
    }

    try {
      const trimmed = token.trim();
      const authHeader = trimmed.startsWith('eyJ') ? 'Bearer ' + trimmed : trimmed;
      const response = await fetch('https://discord.com/api/v10/users/@me', {
        method: 'GET',
        headers: {
          Authorization: authHeader,
          'Content-Type': 'application/json',
          'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
        },
        credentials: 'omit'
      });

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('Discord token expired or invalid. Log in to Discord again.');
        }
        throw new Error(`Discord API error: ${response.status}`);
      }

      const user = await response.json();
      return {
        valid: true,
        user: {
          id: user.id,
          username: user.username,
          discriminator: user.discriminator,
          avatar: user.avatar,
          email: user.email,
          verified: user.verified
        }
      };
    } catch (error) {
      if (error.message.includes('Discord')) {
        throw error;
      }
      throw new Error('Failed to validate Discord token: ' + error.message);
    }
  }

  async function getGoogleAuth() {
    const g = typeof globalThis !== 'undefined' ? globalThis : global;
    const b = g.RbxExtensionBridge;
    if (!b || typeof b.getGoogleAuth !== 'function') {
      throw new Error('Chrome runtime not available');
    }
    const response = await b.getGoogleAuth();
    if (response && response.success) {
      return {
        cookies: response.cookies,
        authHeader: response.authHeader,
        sapisid: response.sapisid,
        email: response.email || null
      };
    }
    throw new Error((response && response.error) || 'Google auth cookies not found. Log in to Google first.');
  }

  async function validateGoogleAuth(authData) {
    if (!authData || !authData.sapisid) {
      throw new Error('Invalid Google auth data');
    }

    try {
      const response = await fetch('https://www.google.com/accounts/OAuthLogin', {
        method: 'GET',
        headers: {
          'Cookie': authData.authHeader
        },
        credentials: 'include'
      });

      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          throw new Error('Google session expired or invalid. Log in to Google again.');
        }
        throw new Error(`Google auth error: ${response.status}`);
      }

      return {
        valid: true,
        cookies: authData.cookies
      };
    } catch (error) {
      if (error.message.includes('Google')) {
        throw error;
      }
      throw new Error('Failed to validate Google auth: ' + error.message);
    }
  }

  function generateSAPISIDHash(sapisid, origin) {
    const timestamp = Math.floor(Date.now() / 1000);
    const message = `${timestamp} ${sapisid} ${origin}`;
    
    return crypto.subtle.digest('SHA-1', new TextEncoder().encode(message))
      .then(hashBuffer => {
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return `SAPISIDHASH ${timestamp}_${hashHex}`;
      });
  }

  global.RbxDiscord = {
    getDiscordToken,
    validateDiscordToken
  };

  global.RbxGoogle = {
    getGoogleAuth,
    validateGoogleAuth,
    generateSAPISIDHash
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
      RbxDiscord: global.RbxDiscord,
      RbxGoogle: global.RbxGoogle
    };
  }
})(typeof globalThis !== 'undefined' ? globalThis : window);
