;
/*
 * @var gameBar : game-bar.vue.js
 * @var vault: Vault.js
 */

// Load the main character 3D Model on scene and attach its collision actions when getting fruits.
document.addEventListener('DOMContentLoaded', async function() {
  
	const vault = Vault.init('fruitpick');   
  
  	// Request game descriptor and set assets nodes on library
	const res = await fetch(window.apiUrl);
	const descriptor = await res.json();
	
	// store descriptor on local vault
	vault.save('descriptor', descriptor);
	
	descriptor.fruits.forEach(addAssetItem);
	descriptor.character.sizes.forEach(addAssetItem);


	let fpModel = getFpModel(
	  descriptor.character.sizes, vault.get('points', 0)
	); // First model on array

	let fp = document.createElement('a-entity'),
		pickableEl = document.querySelector('[pickable]')
	;
    
  
  fp.setAttribute('id', 'fp');
  
  if(pickableEl != null)
	fp.setAttribute('look-at', pickableEl);

  fp.setAttribute('obb-collider', true);
  fp.setAttribute('preserve-location', true);
  
  fp.addEventListener('model-loaded', function(ev) {
	  if(window.debug)
		console.log('Model loaded: ' + fpModel.slug);
  });
  fp.addEventListener('model-error', function(ev) {
	  if(window.debug)
		console.log('Error loading: ' + fpModel.slug);
  });
  
  // Starting characteristics, first model at 0 points
  fp.dataset.totalPoints = vault.get('points', 0);
  fp.dataset.current = vault.get('current', fpModel.slug);
  fp.setAttribute(fpModel.model_loader, '#' + fpModel.slug); // current: gltf-model, "#id"
  fp.setAttribute('scale', fpModel.scale);
  fp.setAttribute('rotation', fpModel.rotation);
  
  fp.setAttribute('material', fpModel.props);
  
  fp.addEventListener("obbcollisionstarted", function(ev) {
    
 // const vault = Vault.init('fruitpick');   
    // Sum points on every "collision" with fruits    
    if ('pickable' in ev.detail.withEl.components) {
	  let fruitPoints = parseInt(ev.detail.withEl.getAttribute('data-points'));
	  const descriptor = vault.get('descriptor');
      fp.dataset.totalPoints = parseInt(fp.dataset.totalPoints) + fruitPoints;
      gameBar.setScore(fp.dataset.totalPoints);
	  gameBar.fruitsFound = parseInt(gameBar.fruitsFound) - 1;
      vault.save('points', fp.dataset.totalPoints);
	  
      ev.detail.withEl.remove();
      
      // Is a change upcoming?
      let upcomingModel = hasUpcoming(descriptor.character.sizes, fp);
      
      if(upcomingModel) {
        let diff = upcomingModel.grows_at - fp.dataset.totalPoints;
        /*
		@todo: enable gamebar logs
		if(diff > 0) {
          gameBar.log(
            i18nfp.ngettext(
                '%1 point more!',
                '%1 %2 more and the cat grows, keep eating.',
                diff,
                diff,
                'points'
            )
          );
        }
		*/
      }
      
      // If model may change immediately after collecting certain points, change the 3D Model to its corresponding.
      let mayChange = getFpModel(descriptor.character.sizes, fp.dataset.totalPoints);
      
      if (mayChange.slug != fp.dataset.current) {
        let fpModel = mayChange;
        
        fp.dataset.current = mayChange.slug;
        vault.save('current', mayChange.slug);
        
        fp.setAttribute(fpModel.loader, '#' + fpModel.slug);
        fp.setAttribute('scale', fpModel.scale);
        fp.setAttribute('rotation', fpModel.rotation);
        
        if (window.basicRendering)
          fp.setAttribute('material', fpModel.material);
        
        setTimeout(function() {
          gameBar.log(`😺 Yay! cat iz grown`);
          gameBar.log(`Keep on eating fruits`);
        }, 10000);
        
      }
	
		(async () => {
			const user = vault.get('user');
			
			if(user) {
				const method = 'post';
				const body = new FormData();
				
				body.append('user_id', user.id);
				body.append('fruit_location_id', ev.detail.withEl.id);
				body.append('fruit_points', fruitPoints);
				body.append('character_phase_id', 1);
				
				const res = await fetch(WS_URL + '/collected', { method, body });
				
				if(res.ok) {
					const bd = await res.json();				
					vault.save('user', bd.data.user);
					gameBar.updateUser(bd.data.user);
					
				}
			}
		})();
		
    }
		
    
  });
  
  // Add the configured model to the scene
  document.querySelector('a-scene').appendChild(fp);
  
  document.querySelector('.arjs-loader').classList.remove('loading');
  console.log('Fruit Pick! © Devignia 2025. Enjoy finding fruits on the material world for your pet.')

});

if (!GAME.isInstalled) {
  
  let installer = document.querySelector('#installer'),
    installPrompt;
  
  window.addEventListener('beforeinstallprompt', function(ev) {
    ev.preventDefault();
    installPrompt = ev;
    installer.removeAttribute('hidden');
  });
  
  installer.addEventListener('click', async (ev) => {
    ev.preventDefault();
    if (!installPrompt) {
      return;
    }
    
    gameBar.log(i18nfp.ngettext('Installing...'));
    const result = await installPrompt.prompt();
    
    if (result.outcome == 'accepted') {
      GAME.isInstalled = true;
      gameBar.log(i18nfp.ngettext('Thank you! follow the steps on next screen.'));
      installer.setAttribute('hidden', true);
    } else {
      gameBar.log(i18nfp.ngettext('Ok, see you next time.'));
    }
  });
  
}
