;
/*
 * @var gameBar : game-bar.vue.js
 * @var vault: Vault.js
 */
// Howler.autoUnlock = false;
// 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');

	  	// @todo: AFRAME.createElement('');
	
	// Request game descriptor and set assets nodes on aframe library
	  let descriptor = vault.get('descriptor');
	  if(descriptor == '') {
	  	  const res = await fetch(window.apiUrl);
	  	  descriptor = await res.json();
	  	  	// store descriptor on local vault
     	vault.save('descriptor', descriptor);
	  }
	  
	descriptor.character.sizes.forEach((item, i) => {
		addAssetItem(item, i == 0); // Only preload first item
	});
	
	  
	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('click', function() {
		let bite = new Howl({
			src: ['./sounds/01.mp3'],
			volume: 1,
		});
		bite.play();
	});  
  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', '-35 180 0 0');// fpModel.rotation);
  
  if(fpModel.props)
	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 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.model_loader, '#' + fpModel.slug);
        fp.setAttribute('scale', fpModel.scale);
        fp.setAttribute('rotation', fpModel.rotation);
		
		if(fpModel.props)
			fp.setAttribute('material', fpModel.props);
      	  
        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 headers = new Headers();
			  headers.append('Authorization', 'Bearer ' + vault.get('token'));
			  
			  
				const body = new FormData();
				
				body.append('user_id', user.id);
				body.append('fruit_location_id', ev.detail.withEl.id);
				body.append('score', fp.dataset.totalPoints);
				body.append('character_size_id', 1);
				
				const res = await fetch(WS_URL + '/fruits/collected', { method, body, headers });
				
			  if(!res.ok)
				  throw new Error('Error logging in with sanctum token');
			  
				if(res.ok) {
					const bd = await res.json();				
					vault.save('user', bd.data.user);
					gameBar.updateUser(bd.data.user);
					
				}
			  
			  
			}
		})();
		
    }
		
    
  });
  
descriptor.fruits.forEach(addAssetItem);  
  
  // Add the configured model to the scene
  document.querySelector('a-scene').appendChild(fp);
  
  
  document.querySelector('.arjs-loader').classList.remove('loading');
  console.info('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.'));
    }
  });
  
}
