"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthProvider = void 0;
const react_1 = __importStar(require("react"));
const react_2 = require("@based/react");
const kabouter_1 = require("kabouter");
const Toast_1 = require("../Toast");
const icons_1 = require("../../icons");
const AuthProvider = ({ children }) => {
    const client = (0, react_2.useClient)();
    const toast = (0, Toast_1.useToast)();
    const [showLoader, setShowLoader] = (0, react_1.useState)(false);
    const { authType } = (0, kabouter_1.useRoute)('auth-[authType]').path;
    const isGoogleRedirect = authType === 'google';
    const isMicrosoftRedirect = authType === 'microsoft';
    const isGithubRedirect = authType === 'github';
    const thirdPartyRedirect = isGoogleRedirect
        ? 'google'
        : isMicrosoftRedirect
            ? 'microsoft'
            : isGithubRedirect
                ? 'github'
                : false;
    (0, react_1.useEffect)(() => {
        // TODO nuno fix => if we need to check for window, use typeof window !== 'undefined'
        if (thirdPartyRedirect && window) {
            setShowLoader(true);
            const params = new URLSearchParams(window.location.search);
            const code = params.get('code');
            const redirect = global.location.origin + `/auth-${thirdPartyRedirect}`;
            let state;
            try {
                state = JSON.parse(params.get('state') ?? '');
            }
            catch (error) {
                console.warn(error);
            }
            const clientId = window.sessionStorage.getItem('client_id');
            const codeVerifier = window.sessionStorage.getItem('code_verifier');
            client
                .call(`auth${thirdPartyRedirect.charAt(0).toUpperCase() +
                thirdPartyRedirect.slice(1)}`, {
                code,
                redirect,
                state,
                clientId,
                ...(codeVerifier ? { codeVerifier } : null),
            })
                .then(async (response) => {
                const { token, refreshToken, email, id } = response;
                // @ts-ignore
                await client.auth(token, { id, refreshToken });
                toast.add(react_1.default.createElement(Toast_1.Toast, { label: 'Signedin as ' + email, color: "brand" }));
                window.sessionStorage.removeItem('client_id');
                window.sessionStorage.removeItem('code_verifier');
                setShowLoader(false);
                // TODO nuno fix (cant check window like this)
                if (window && state.redirectUrl) {
                    window.location.href = state.redirectUrl;
                }
            })
                .catch((error) => {
                console.error(error);
                // TODO: get better error messages. Passing a BasedError?
                const description = error.message.includes('User already registered')
                    ? 'The email is already registered'
                    : error.message;
                toast.add(react_1.default.createElement(Toast_1.Toast, { label: "Authentication Error", color: "negative" }));
                setShowLoader(false);
            });
        }
    }, [isGoogleRedirect, isMicrosoftRedirect]);
    return showLoader ? (react_1.default.createElement("div", null,
        react_1.default.createElement("div", { style: {
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate3d(-50%,-50%,0)',
            } },
            react_1.default.createElement(icons_1.IconAlarmClock, null)))) : (react_1.default.createElement(react_1.default.Fragment, null, children));
};
exports.AuthProvider = AuthProvider;
//# sourceMappingURL=AuthProvider.js.map