/**
 * Initialisation du SDK Facebook
 */

declare global {
  interface Window {
    FB: any;
    fbAsyncInit: () => void;
  }
}

export const initFacebookSDK = (): Promise<void> => {
  return new Promise((resolve) => {
    // Si le SDK est déjà chargé
    if (window.FB) {
      resolve();
      return;
    }

    // Définir la fonction de callback
    window.fbAsyncInit = function() {
      window.FB.init({
        appId: process.env.NEXT_PUBLIC_FACEBOOK_APP_ID,
        cookie: true,
        xfbml: true,
        version: 'v18.0'
      });
      resolve();
    };

    // Charger le SDK
    (function(d, s, id) {
      const fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      const js = d.createElement(s) as HTMLScriptElement;
      js.id = id;
      js.src = "https://connect.facebook.net/fr_FR/sdk.js";
      fjs?.parentNode?.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  });
};

export const loginWithFacebook = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    if (!window.FB) {
      reject(new Error('Facebook SDK not loaded'));
      return;
    }

    window.FB.login((response: any) => {
      if (response.authResponse) {
        resolve(response.authResponse.accessToken);
      } else if (response.status === 'unknown') {
        // Facebook app is being updated or unavailable
        reject(new Error('Facebook Login est actuellement indisponible. Veuillez utiliser la connexion par email ou Google.'));
      } else {
        reject(new Error('Facebook login cancelled'));
      }
    }, { scope: 'email,public_profile' });
  });
};

export const getFacebookLoginStatus = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    if (!window.FB) {
      reject(new Error('Facebook SDK not loaded'));
      return;
    }

    window.FB.getLoginStatus((response: any) => {
      resolve(response);
    });
  });
};
