import { reduxWrapper } from '../store'
import numeral from 'numeral';
import Script from 'next/script';
import jwt from 'jsonwebtoken';
//import 'https://chat.autofaq.ai/widget/static/css/main.css';

import '../css/style.css';

const m = Math.random();
numeral.register('locale', `locale_${ m }`, {
	delimiters: {
		thousands: ' ',
		decimal: ','
	},
	abbreviations: {
		thousand: 'k',
		million: 'm',
		billion: 'b',
		trillion: 't'
	},
	currency: {
		symbol: '₽'
	}
});
numeral.locale(`locale_${ m }`);

const WrappedApp = (props) => 
{
	const { Component, pageProps, } = props;

	return (
		<>
			{ !props.observer && (
				<>
					<Script id="yandex-metrica" strategy={'afterInteractive'}>
						{`
							(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
							m[i].l=1*new Date();
							for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
							k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
							(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

							ym(${ process.env.NEXT_PUBLIC_YANDEX_METRIKA_ID }, "init", { clickmap: true, trackLinks: true, accurateTrackBounce: true, webvisor: true });
							console.log(ym, ${ process.env.NEXT_PUBLIC_YANDEX_METRIKA_ID });
						`}
					</Script>
					{ process.env.NEXT_PUBLIC_AUTOFAQ_AI_ENABLED == 1 && (
						<>
							<link href="//chat.autofaq.ai/widget/static/css/main.css" rel="stylesheet" />
							<Script id="auto-faq" strategy={'afterInteractive'}>
								{`
									window.widgetHost = "https://chat.autofaq.ai";
									window.widgetServiceId = "${ process.env.NEXT_PUBLIC_AUTOFAQ_AI_SERVICE_ID }";
									window.widgetChannelId = "${ process.env.NEXT_PUBLIC_AUTOFAQ_AI_CHANNEL_ID }";

									window.widgetUserLogin = ${ props.acc !== null ? `"${ props.acc }"` : "undefined" };
									window.widgetUserEmail = ${ props.email !== null ? `"${ props.email }"` : "undefined" }; 
									window.widgetUserPayload = ${ props.acc !== null ? `{ "acc_number": "${ props.acc }" }` : "undefined" };
									window.widgetOperatorName = true;

									window.widgetStyleParams = { "headerBackgroundColor": "#1c01a9", "messageToWidgetBackgroundColor": "#3d21f8" };

									const script = document.createElement('script');
									script.id = "autofaqWidget";
									script.type = "text/javascript";
									script.src = "https://chat.autofaq.ai/widget/static/js/main.js";
									document.head.appendChild(script);
								`}
							</Script>
						</>
					) }
					<noscript>
						<div>
							<img src={`https://mc.yandex.ru/watch/${ process.env.NEXT_PUBLIC_YANDEX_METRIKA_ID }`} style={{ position:'absolute', left:'-9999px' }} alt=""/>
						</div>
					</noscript>
				</>
			) }
			<Component {...pageProps} />
		</>
	)
}

WrappedApp.getInitialProps = async (props) => 
{
	const { req } = props.ctx;

	let observer = false;
	let acc = null;
	let email = null;

	if(req !== undefined)
	{
		const { cookies } = req;

		if(cookies !== undefined && cookies !== null)
		{
			if(cookies.jwt !== undefined && cookies.jwt !== null)
			{
				let client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);
				console.log({ client_jwt_decoded });
				acc = client_jwt_decoded.acc_number;
				email = client_jwt_decoded.login;
			}
		}
	}

	if(req !== undefined && req.url !== null && req.url.indexOf("offstage") > -1)
	{
		observer = true;
	}

	if(req !== undefined && req.cookies !== undefined && req.cookies.observer !== undefined && req.cookies.observer === "true")
	{
		observer = true;
	}

	return {
		observer, 
		acc, 
		email, 
	}
}

export default reduxWrapper.withRedux(WrappedApp);