import * as bus from './bus.js';

const STORAGE_KEY = 'el3ab_state';

const defaultState = {
  auth: { token: null, refreshToken: null, userId: null, isGuest: false, guestId: null },
  player: null,
  notifications: { unreadCount: 0 },
  friends: { onlineCount: 0 },
  currentGame: null,
  features: {},
  activeWorld: 'play',
  audioEnabled: true,
  language: 'ar'
};

let state = loadPersistedState();

function loadPersistedState() {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      return { ...defaultState, ...JSON.parse(saved) };
    }
  } catch (e) {}
  return { ...defaultState };
}

function persist() {
  try {
    const toSave = {
      auth: state.auth,
      player: state.player,
      activeWorld: state.activeWorld,
      audioEnabled: state.audioEnabled,
      language: state.language
    };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
  } catch (e) {}
}

export function get(path) {
  if (!path) return state;
  return path.split('.').reduce((o, k) => o?.[k], state);
}

export function set(path, value) {
  const keys = path.split('.');
  const last = keys.pop();
  let obj = state;
  for (const k of keys) {
    if (!obj[k] || typeof obj[k] !== 'object') obj[k] = {};
    obj = obj[k];
  }
  obj[last] = value;
  persist();
  bus.emit('store:change', { path, value });
  bus.emit(`store:${path}`, value);
}

export function update(path, updater) {
  const current = get(path);
  set(path, updater(current));
}

export function reset() {
  state = { ...defaultState };
  persist();
  bus.emit('store:reset');
}
