let latest, STORE_VERSION = 'v0.1';
const store = new Store(latest = {
  _VERSION_: STORE_VERSION,
  'navigation': {
    current: 'Login'
  },
  loaded: {
    cards: false
  },
  'account': {
    userID: 5,
    name: 'Диогроген Курославович',
    phone: '79999877414',
  }
});

try{
  var data = JSON.parse( localStorage.getItem( 'store' ) );
  if(data._VERSION_ !== store.get('_VERSION_')){
    console.warn('STORE:outdated, new state → localStorage');
    console.warn('\tSTORE:currentData #'+ store.get('_VERSION_'), store._props);
    console.warn('\tSTORE:savedData #'+ STORE_VERSION, data);
    console.warn('\tSTORE:hint → Run Store.restore() for restore saved state');
    console.warn('\tStore:hint → Run Store.update() for load latest default state');

    Store.restore = function() {
      for( var k in data ){
        if(k !== '_VERSION_'){
          store.set( k, data[ k ] );
        }
      }
    };
    Store.update = function() {
      for( var k in latest ){
        if(k !== '_VERSION_'){
          store.set( k, latest[ k ] );
        }
      }
    };
  }else{
    for( var k in data ){
      store.set( k, data[ k ] );
    }
    console.log('STORE:loaded ← localStorage', data);

  }
}catch( e ){}
store.on('change', function() {
  localStorage.setItem('store', JSON.stringify(store._props));
});

const createSavableStore = function(name) {
  const store = new Store(latest = {
    _VERSION_: STORE_VERSION
  });
  try{
    var data = JSON.parse( localStorage.getItem( name ) );
    if(data._VERSION_ === store.get('_VERSION_')){
      for( var k in data ){
        store.set( k, data[ k ] );
      }
    }
  }catch( e ){}
  let shouldSave,
    saveFn = function() {
      localStorage.setItem(name, JSON.stringify(store._props));
      shouldSave = false;
    };
  store.on('change', function() {
    if(!shouldSave)
      shouldSave = setTimeout(saveFn, 500);
  });
  return store;
};

const cards = createSavableStore('cards');
const tmpStore = new Store({
  loaded: false,
  navigation: {current: 'Login'},
  isMobile: false,
  width: window.innerWidth,
  newItemCount: 1000
});

let lastNav = null;
store.sub('navigation.current', function(val) {
  console.log('APP:navigation', lastNav,'→', val);
  lastNav = val;
});