import buildUrl from '@connect/url-placeholders';
import { getCookie } from '@connect/cookies-lite';
import isInternal from 'lib2/isInternal';
import hasPermission from 'lib2/hasPermission';
import hasPaidServices from 'lib2/hasPaidServices';
import getOrganization from 'lib2/getOrganization';
import getHelpUrl from 'lib2/getHelpUrl';
import getUserUrl from 'lib2/getUserUrl';
import { ConfigStore, SessionStore } from 'lib2/stores';
import { i18n } from 'i18n2';

export const MenuOptions = {
    mail: {
        url: () => buildUrl(ConfigStore.get('ui.relatedServices.mail'), {
            uid: SessionStore.get('user.id'),
        }),
        text: i18n('related_services.mail'),
    },
    disk: {
        url: () => ConfigStore.get('ui.relatedServices.disk'),
        text: i18n('related_services.disk'),
    },
    passport: {
        url: () => ConfigStore.get('ui.relatedServices.passport'),
        text: i18n('related_services.passport'),
    },
    about_me: {
        url: () => getUserUrl(),
        available: isInternal,
        text: i18n('common_options.about_me'),
    },
    leave_org: {
        available: () => hasPermission('leave_organization'),
        url: () => '/portal/home#leave-organization',
        text: i18n('common_options.leave_organization'),
    },
    help: {
        url: () => getHelpUrl('ui.help.main', { tld: ConfigStore.get('app.tld') }),
        text: i18n('common_options.help'),
    },
    offer: {
        url: () => ConfigStore.get('ui.help.offer'),
        available: () => {
            let org = getOrganization();

            return hasPermission('can_pay') &&
                (org.subscription_plan !== 'free' || hasPaidServices() || org.has_debt);
        },
        text: i18n('common_options.offer'),
    },
    logout: {
        url: () => buildUrl(ConfigStore.get('passport.session.logout'), {
            uid: SessionStore.get('user.id'),
            yu: getCookie('yandexuid'),
            retpath: new URL(window.location.href).searchParams.get('retpath') || new URL(window.location.href).origin,
        }),
        text: i18n('common_options.logout'),
    },
};

export const services = [
    MenuOptions.mail,
    MenuOptions.disk,
    MenuOptions.passport,
];

export const personal = [
    MenuOptions.about_me,
    MenuOptions.leave_org,
    MenuOptions.help,
    MenuOptions.offer,
    MenuOptions.logout,
];
