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

const PHASE_ORDER = [
  'normal_work', 'unease', 'suspicion', 'investigation', 'conflict', 'resolution'
];

class NarrativePhaseTracker {
  constructor() {
    this._phase = 'normal_work';
  }

  initialize(state) {
    const saved = state?.narrative_phase;
    this._phase = PHASE_ORDER.includes(saved) ? saved : 'normal_work';
  }

  advance(questId) {
    const quest = contentLoader.get('quests', questId);
    if (!quest?.narrative_phase) return;

    const questRank   = PHASE_ORDER.indexOf(quest.narrative_phase);
    const currentRank = PHASE_ORDER.indexOf(this._phase);

    if (questRank <= currentRank) return;

    const from = this._phase;
    this._phase = quest.narrative_phase;
    this._persist();
    eventBus.emit('narrative:phase_changed', { from, to: this._phase });
  }

  getPhase() {
    return this._phase;
  }

  forcePhase(phase) {
    if (!PHASE_ORDER.includes(phase)) return;
    const from = this._phase;
    this._phase = phase;
    this._persist();
    eventBus.emit('narrative:phase_changed', { from, to: this._phase });
  }

  _persist() {
    saveState.set({ narrative_phase: this._phase });
  }
}

export const narrativePhaseTracker = new NarrativePhaseTracker();
