// Right-to-left navigation for manga
// Feature Registration Pattern implementation

import type { ReaderContext } from "../core/reader-context";

export function init(context: ReaderContext): void {
  let state: RTLNavigatorState | null = null;

  context.events.on("reader:loaded", (detail: { totalPages: number; currentPage?: number }) => {
    state = createRTLNavigator(detail.totalPages);
    if (detail.currentPage) {
      state.currentPage = detail.currentPage;
    }
  });

  context.events.on("navigation:next-page", () => {
    if (state) {
      const nextPage = getNextPage(state);
      state.currentPage = nextPage;
      context.events.emit("navigation:to-page", { page: nextPage });
    }
  });

  context.events.on("navigation:previous-page", () => {
    if (state) {
      const previousPage = getPreviousPage(state);
      state.currentPage = previousPage;
      context.events.emit("navigation:to-page", { page: previousPage });
    }
  });

  context.events.on("navigation:to-page", (detail: { page: number }) => {
    if (state) {
      state = navigateToPage(state, detail.page);
      const progress = getReadingProgressPercentage(state);
      context.events.emit("navigation:progress", { progress });
    }
  });

  context.events.on("navigation:get-progress", () => {
    if (state) {
      const progress = getProgress(state);
      context.events.emit("navigation:progress-current", progress);
    }
  });
}

interface RTLNavigatorState {
  currentPage: number;
  totalPages: number;
  readingDirection: "rtl" | "ltr";
}

function createRTLNavigator(totalPages: number): RTLNavigatorState {
  return {
    currentPage: 1,
    totalPages,
    readingDirection: "rtl",
  };
}

function getNextPage(state: RTLNavigatorState): number {
  if (state.readingDirection === "rtl") {
    return Math.max(1, state.currentPage - 1);
  }
  return Math.min(state.totalPages, state.currentPage + 1);
}

function getPreviousPage(state: RTLNavigatorState): number {
  if (state.readingDirection === "rtl") {
    return Math.min(state.totalPages, state.currentPage + 1);
  }
  return Math.max(1, state.currentPage - 1);
}

function navigateToPage(
  state: RTLNavigatorState,
  pageNumber: number,
): RTLNavigatorState {
  state.currentPage = Math.max(1, Math.min(state.totalPages, pageNumber));
  return state;
}

function getProgress(state: RTLNavigatorState): {
  current: number;
  total: number;
} {
  return {
    current: state.currentPage,
    total: state.totalPages,
  };
}

function getReadingProgressPercentage(state: RTLNavigatorState): number {
  return (state.currentPage / state.totalPages) * 100;
}