const apiuri = 'https://0ewu6bqzbi.execute-api.eu-west-1.amazonaws.com/v1';

// let COGNITO;
(function () {
//IIFE
    const staff_auth_url = 'https://spstaff.auth.eu-west-1.amazoncognito.com';
    const client_auth_url = 'https://spclients.auth.eu-west-1.amazoncognito.com';
    const staff_client_id = 'aa2tgcuisvvkcv53kv4ptjk05';
    // const staff_client_id = '62nlo8kkgdv424jbe87ug4kkj4';
    // const staff_client_secret = '1n2pk4g60qippnblqubf3h2ufhvhbm3d46b1it0qndm6b1gvb5i8';
    
    const client_client_id = '2omu2foj1g5em1uhqkianbffd2';
    // const client_client_secret = '';
    const response_type = 'code';
    const auth_scope = 'email openid phone';
    const home_url = 'http://localhost:3000';
    const staffzone_url = `${home_url}/staffzone`;
    const clientzone_url = `${home_url}/clientzone`;
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);


    const COGNITO = {
        client_id: '20jhjpqk9h2pqrlcgm4ulgkerj',
        staff_client_id: staff_client_id,
        client_client_id: client_client_id,
        // staff_client_secret: staff_client_secret,
        // client_client_secret: client_client_secret,
        response_type: response_type,
        scope: auth_scope,
        staff_redirect_uri: staffzone_url,
        client_redirect_uri: clientzone_url,
        // redirect_uri: home_url,
        logout_uri: home_url,
        staff_url: `${staff_auth_url}/`,
        client_url: `${client_auth_url}/`,
        // client_secret: 'l0usk2nabqlcf3g7eir4aakov8osmrbsgq6k6faf3u9kgju6ujv',
        staff_token_url: `${staff_auth_url}/oauth2/token`,
        client_token_url: `${client_auth_url}/oauth2/token`,
        user_type: (Data.get('cog_user_type') || ''),
        code: urlParams.get('code')
    }

    window.COGNITO = COGNITO;
    // const code = urlParams.get('code');
})();


const LOGIN_PARAMS = {
    staff: {
        client_id: COGNITO.staff_client_id,
        response_type: COGNITO.response_type,
        scope: COGNITO.scope,
        redirect_uri: COGNITO.staff_redirect_uri
    },
    client: {
        client_id: COGNITO.client_client_id,
        response_type: COGNITO.response_type,
        scope: COGNITO.scope,
        redirect_uri: COGNITO.client_redirect_uri
    }
}

const LOGOUT_PARAMS = {
    staff:{
        client_id: COGNITO.staff_client_id,
        response_type: COGNITO.response_type,
        logout_uri: COGNITO.logout_uri
    },
    client: {
        client_id: COGNITO.client_client_id,
        response_type: COGNITO.response_type,
        logout_uri: COGNITO.logout_uri
    }
}


const STAFF_LOGIN_PARAMS = {
    client_id: COGNITO.staff_client_id,
    response_type: COGNITO.response_type,
    scope: COGNITO.scope,
    redirect_uri: COGNITO.staff_redirect_uri
}

const STAFF_LOGOUT_PARAMS = {
    client_id: COGNITO.staff_client_id,
    response_type: COGNITO.response_type,
    logout_uri: COGNITO.logout_uri
}

const CLIENT_LOGIN_PARAMS = {
    client_id: COGNITO.client_client_id,
    response_type: COGNITO.response_type,
    scope: COGNITO.scope,
    redirect_uri: COGNITO.client_redirect_uri
}
const CLIENT_LOGOUT_PARAMS = {
    client_id: COGNITO.client_client_id,
    response_type: COGNITO.response_type,
    logout_uri: COGNITO.logout_uri
}



function isLoggedIn() {
    // let d = Data.get('cognito_creds', true);
    // console.log('creds is: ', d );
    const token = getCookie('cog_access_token');

    if (token) {
        // console.log('LOGGED IN WITH CREDS', d.access_token);
        return true;
    } else {
        // console.log("NOT LOGGED IN");
        return false;
    }
}

function getAccessToken() {
    return getCookie('cog_access_token');
}

function setCookie(name, value, expires_in) {
    var expirationTime = new Date( (new Date).getTime() + expires_in * 1000);
    var expires = "expires=" + expirationTime.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

function createCookies(data) {
    setCookie('cog_id_token', data.id_token, data.expires_in);
    setCookie('cog_access_token', data.access_token, data.expires_in);
    setCookie('cog_refresh_token', data.refresh_token, data.expires_in);
    setCookie('cog_token_type', data.token_type, data.expires_in);
}

function getCookie(name) {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? match[2] : null;
}


function clearCookies() {
    // Clear Cognito-related cookies
    deleteCookie('cog_id_token');
    deleteCookie('cog_access_token');
    deleteCookie('cog_refresh_token');
    deleteCookie('cog_expiration_time');

    Data.set('combined_vendees', '', true);
    Data.set('all_vendees_keyed', '', true);
    // Additional logout steps, e.g., redirect to login page
    // ...

    // Optional: Force a page reload to ensure cookies are removed
    // window.location.reload(true);
}

function isUserMarkupDone(){
    if( document.getElementById('datawrap') ) return 1;
    return 0;
}



/*
async function fetchAuthStaffMarkup(){
    return;
    let s3path = 'https://sp-portal-appfiles.s3.amazonaws.com/partials/staff-authwrap.html';
    
    const response = await fetch(s3path);
    const html = await response.text();
    console.log('Got S3 Markup: ');
    return html;  
}
*/
async function mw_fetchAuthStaffMarkup(ctx, next) {
    return;
    if(!isUserMarkupDone()) ctx.authstaffmarkup = await fetchAuthStaffMarkup();
    next();
}

function mw_insertAuthMarkup(ctx, next){
    return;
    if(!isUserMarkupDone()){
        document.getElementById('authwrap').innerHTML = ctx.authstaffmarkup;
        
        var datalinksDiv = document.querySelector('.datalinks');
        datalinksDiv.addEventListener('click', function(event) {
            // Check if the clicked element is an anchor tag
            if (event.target.tagName === 'A') {
                let a = event.target;
                if(a.dataset.cb === 'processJoinData') a = null;
            }
        });
    }
    
    next();
}

