(function(){
    'use strict';
    var cfg=window.yatoonDiscovery||{};
    var key=cfg.storageKey||'yatoon_favorite_services_v1';
    var promptEvent=null;
    function read(){try{return JSON.parse(localStorage.getItem(key)||'[]').map(String);}catch(e){return [];}}
    function write(items){try{localStorage.setItem(key,JSON.stringify(items));}catch(e){}}
    function server(mode,items){if(!cfg.syncEnabled||!cfg.ajaxUrl||!cfg.nonce)return Promise.resolve(null);var body=new URLSearchParams({action:'yatoon_sync_favorites',nonce:cfg.nonce,mode:mode});if(items)body.set('favorites',JSON.stringify(items));return fetch(cfg.ajaxUrl,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'},body:body.toString()}).then(function(response){return response.json();}).then(function(payload){return payload&&payload.success&&payload.data?payload.data.favorites:null;}).catch(function(){return null;});}
    function toast(message){var old=document.querySelector('.yatoon-favorite-toast');if(old)old.remove();var el=document.createElement('div');el.className='yatoon-favorite-toast';el.setAttribute('role','status');el.textContent=message;document.body.appendChild(el);setTimeout(function(){el.remove();},2200);}
    function paint(){var saved=read();document.querySelectorAll('[data-favorite-service]').forEach(function(button){button.setAttribute('aria-pressed',saved.indexOf(String(button.dataset.favoriteService))!==-1?'true':'false');});}
    document.addEventListener('click',function(event){var button=event.target.closest('[data-favorite-service]');if(!button)return;var id=String(button.dataset.favoriteService),saved=read(),index=saved.indexOf(id),added=index===-1;if(added)saved.push(id);else saved.splice(index,1);write(saved);paint();server('replace',saved);toast(added?(cfg.saved||'Saved to favorites'):(cfg.removed||'Removed from favorites'));});
    window.addEventListener('beforeinstallprompt',function(event){event.preventDefault();promptEvent=event;document.querySelectorAll('.yatoon-install-app').forEach(function(button){button.hidden=false;});});
    document.addEventListener('click',function(event){var button=event.target.closest('.yatoon-install-app');if(!button||!promptEvent)return;promptEvent.prompt();promptEvent.userChoice.finally(function(){promptEvent=null;button.hidden=true;});});
    document.addEventListener('DOMContentLoaded',function(){paint();server('list').then(function(remote){if(!remote)return;var merged=Array.from(new Set(read().concat(remote.map(String))));write(merged);paint();server('replace',merged);});});
})();
