import type { ReaderMetadata, ReaderState } from "./reader-context";

type CurrentReader = import("./reader-context").CurrentReader;

let currentState: ReaderState = {
  currentReader: null,
  readerMetadata: null,
};

export function getState(): ReaderState {
  return { ...currentState };
}

export function setState(updates: Partial<ReaderState>): void {
  const oldState = { ...currentState };
  currentState = { ...currentState, ...updates };

  // Emit events for significant changes
  if (
    updates.currentReader &&
    oldState.currentReader !== updates.currentReader
  ) {
    readerEvents.emit("readerReady", currentState.currentReader);
  }
}

export function getCurrentReader(): CurrentReader | null {
  return currentState.currentReader;
}

export function getReaderMetadata(): ReaderMetadata | null {
  return currentState.readerMetadata;
}

export function getCurrentPage(): number {
  const reader = currentState.currentReader;
  if (!reader) return 0;

  if (reader.type === "ebook") {
    return reader.currentSpineIndex;
  }
  return reader.currentPage;
}

import { readerEvents } from "./reader-events";
