import { eventBus } from '../lib/eventBus.js';
import { contentLoader } from './ContentLoader.js';
import { progressionSystem } from './ProgressionSystem.js';
import { saveState } from './SaveState.js';

class TrustSystem {
  constructor() {
    this._score = 50;
  }

  initialize(state) {
    this._score = Number(state.trust ?? 50);
    this._evaluateUnlocks();
  }

  getScore() {
    return this._score;
  }

  adjust(delta) {
    const numericDelta = Number(delta) || 0;
    const previousScore = this._score;
    this._score = Math.max(0, Math.min(100, previousScore + numericDelta));

    this._evaluateUnlocks();
    eventBus.emit('trust:changed', { score: this._score, delta: numericDelta });
    saveState.set({ trust: this._score });
  }

  _evaluateUnlocks() {
    for (const unlock of contentLoader.trustUnlocks ?? []) {
      if (this._score >= unlock.trust_threshold) {
        progressionSystem.grantUnlock(unlock);
      }

      if (unlock.revokes_below_trust >= 0 && this._score < unlock.revokes_below_trust) {
        progressionSystem.revokeUnlock(unlock);
      }
    }
  }
}

export const trustSystem = new TrustSystem();
