import { getCookie } from '@connect/cookies-lite';
import { ConfigStore } from 'lib2/stores';
import meetsExperimentCriteria from 'lib2/meetsExperimentCriteria';
import isExperimentDeclined from 'lib2/isExperimentDeclined';
import isWithinExperimentPercentage from 'lib2/isWithinExperimentPercentage';

let ymId;
let ymScriptElement = document.querySelector('[data-ym-id]');

if (ymScriptElement) {
    ymId = Number(ymScriptElement.dataset.ymId);
}

const DEBUG = new URL(window.location.href).searchParams.get('debug') === '1';

function toNestedParams(path) {
    if (!Array.isArray(path)) {
        return;
    }

    let params = path[path.length - 1];

    for (let i = path.length - 2; i >= 0; i--) {
        params = {
            [path[i]]: params,
        };
    }

    return params;
}

function send(...paramsPath) {
    let params = toNestedParams(paramsPath);

    if (DEBUG) {
        // eslint-disable-next-line no-console
        console.log('[ym]', ymId, 'params', params);
    }

    if (window.ym && ymId) {
        window.ym(ymId, 'params', params);
    }
}

function reachGoal(goalId, paramsPath) {
    let params = toNestedParams(paramsPath);

    if (DEBUG) {
        // eslint-disable-next-line no-console
        console.log('[ym]', ymId, 'reachGoal', goalId, params);
    }

    if (window.ym && ymId) {
        window.ym(ymId, 'reachGoal', goalId, params);
    }
}

function sendExperiment([name, context], ...paramsPath) {
    const experimentParamsPath = ['Эксперимент', name, context];

    if (isWithinExperimentPercentage(name)) {
        experimentParamsPath.push('Попал в %-выборку');

        if (meetsExperimentCriteria(name)) {
            experimentParamsPath.push('Удовлетворяет условиям эксперимента');

            if (isExperimentDeclined(name)) {
                experimentParamsPath.push('Отказ пользователя');
            } else {
                experimentParamsPath.push('Участвует в эксперименте');
            }
        } else {
            experimentParamsPath.push('Не удовлетворяет условиям эксперимента');
        }
    } else {
        experimentParamsPath.push('Не попал в %-выборку');
    }

    experimentParamsPath.push(
        `${ConfigStore.get(['experiment', name, 'percentage'])}%`,
        getCookie('yandexuid')
    );

    send(...experimentParamsPath, ...paramsPath);
}

export default {
    send,
    reachGoal,
    sendExperiment,
};
