import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
/* eslint-disable camelcase */
/**
 *
 * LoginSocialGoogle
 *
 */
/* "use client" */

import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
var JS_SRC = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
var SCRIPT_ID = 'apple-login';
var _window = global.window;
var LoginSocialApple = function LoginSocialApple(_ref) {
  var client_id = _ref.client_id,
    _ref$scope = _ref.scope,
    scope = _ref$scope === void 0 ? 'name email' : _ref$scope,
    _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    onLoginStart = _ref.onLoginStart,
    onReject = _ref.onReject,
    onResolve = _ref.onResolve,
    _ref$redirect_uri = _ref.redirect_uri,
    redirect_uri = _ref$redirect_uri === void 0 ? '/' : _ref$redirect_uri,
    children = _ref.children;
  var scriptNodeRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSdkLoaded = _useState2[0],
    setIsSdkLoaded = _useState2[1];
  useEffect(function () {
    !isSdkLoaded && load();
  }, [isSdkLoaded]);
  useEffect(function () {
    return function () {
      if (scriptNodeRef.current) scriptNodeRef.current.remove();
    };
  }, []);
  var checkIsExistsSDKScript = useCallback(function () {
    return !!document.getElementById(SCRIPT_ID);
  }, []);
  var insertScript = useCallback(function (d) {
    var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'script';
    var id = arguments.length > 2 ? arguments[2] : undefined;
    var jsSrc = arguments.length > 3 ? arguments[3] : undefined;
    var cb = arguments.length > 4 ? arguments[4] : undefined;
    var appleScriptTag = d.createElement(s);
    appleScriptTag.id = id;
    appleScriptTag.src = jsSrc;
    appleScriptTag.async = true;
    appleScriptTag.defer = true;
    var scriptNode = document.getElementsByTagName('script')[0];
    scriptNodeRef.current = appleScriptTag;
    scriptNode && scriptNode.parentNode && scriptNode.parentNode.insertBefore(appleScriptTag, scriptNode);
    appleScriptTag.onload = cb;
  }, []);
  var handleResponse = useCallback(function (res) {
    if (res !== null && res !== void 0 && res.access_token) {
      onResolve({
        provider: 'apple',
        data: res
      });
    } else {
      var data = res;
      onResolve({
        provider: 'apple',
        data: data
      });
    }
  }, [onResolve]);
  var load = useCallback(function () {
    if (checkIsExistsSDKScript()) {
      setIsSdkLoaded(true);
    } else {
      insertScript(document, 'script', SCRIPT_ID, JS_SRC, function () {
        var options = {
          clientId: client_id,
          // This is the service ID we created.
          scope: scope,
          // To tell apple we want the user name and emails fields in the response it sends us.
          redirectURI: redirect_uri,
          // As registered along with our service ID
          state: 'origin:web',
          // Any string of your choice that you may use for some logic. It's optional and you may omit it.
          usePopup: true // Important if we want to capture the data apple sends on the client side.
        };
        _window.AppleID.auth.init(options);
        setIsSdkLoaded(true);
      });
    }
  }, [scope, client_id, redirect_uri, insertScript, checkIsExistsSDKScript]);
  var loginApple = useCallback(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var response, _t;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (isSdkLoaded) {
            _context.next = 1;
            break;
          }
          return _context.abrupt("return");
        case 1:
          if (_window.AppleID) {
            _context.next = 2;
            break;
          }
          load();
          onReject("Apple SDK isn't loaded!");
          _context.next = 6;
          break;
        case 2:
          onLoginStart && onLoginStart();
          _context.prev = 3;
          _context.next = 4;
          return _window.AppleID.auth.signIn();
        case 4:
          response = _context.sent;
          handleResponse(response);
          _context.next = 6;
          break;
        case 5:
          _context.prev = 5;
          _t = _context["catch"](3);
          onReject({
            err: _t
          });
        case 6:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[3, 5]]);
  })), [handleResponse, isSdkLoaded, load, onLoginStart, onReject]);
  return /*#__PURE__*/React.createElement("div", {
    className: className,
    onClick: loginApple
  }, children);
};
export default /*#__PURE__*/memo(LoginSocialApple);