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

try{
  var data = JSON.parse( localStorage.getItem( 'store' ) );
  if(data.commit !== store.get('commit')){
    console.warn('STORE:outdated, new state → localStorage');
    console.warn('\tSTORE:currentData #'+ store.get('commit'), store._props);
    console.warn('\tSTORE:savedData # '+ window.CommitID, 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 !== 'commit'){
          store.set( k, data[ k ] );
        }
      }
    };
    Store.update = function() {
      for( var k in latest ){
        if(k !== 'commit'){
          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 = {
    commit: window.CommitID
  });
  try{
    var data = JSON.parse( localStorage.getItem( name ) );
    if(data.commit === store.get('commit')){
      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
});

