// Chapter markers for manga/comics
// Visual indicators for chapter boundaries
// Feature Registration Pattern implementation

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

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

  context.events.on("reader:loaded", (detail: { chapters: ChapterInfo[]; currentPage: number }) => {
    state = createChapterMarkerState(detail.chapters, detail.currentPage);
    renderChapterMarkers(context.elements.readerContent, state);
  });

  context.events.on("page-changed", (detail: { page: number }) => {
    if (state) {
      updateCurrentChapter(state, detail.page);
    }
  });

  context.events.on("chapter-markers:toggle", () => {
    if (state) {
      toggleChapterMarkers(state);
    }
  });

  context.events.on("chapter-markers:navigate", (detail: { chapterNumber: number }) => {
    if (state) {
      scrollToChapter(state, detail.chapterNumber);
    }
  });

  context.events.on("reader:unload", () => {
    const markers = document.querySelector(".chapter-markers");
    markers?.remove();
  });
}

interface ChapterInfo {
  chapterNumber: number;
  pageStart: number;
  pageEnd: number;
  title?: string;
}

interface ChapterMarkerState {
  chapters: ChapterInfo[];
  currentChapter: number;
  showMarkers: boolean;
}

function createChapterMarkerState(
  chapters: ChapterInfo[],
  currentPage: number,
): ChapterMarkerState {
  const currentChapter =
    chapters.find((c) => currentPage >= c.pageStart && currentPage <= c.pageEnd)
      ?.chapterNumber || 1;

  return {
    chapters,
    currentChapter,
    showMarkers: true,
  };
}

function renderChapterMarkers(
  container: HTMLElement,
  state: ChapterMarkerState,
): void {
  if (!state.showMarkers) return;

  const markersContainer = document.createElement("div");
  markersContainer.className =
    "chapter-markers absolute left-0 right-0 pointer-events-none z-10";

  state.chapters.forEach((chapter) => {
    const marker = document.createElement("div");
    marker.className =
      "chapter-marker flex items-center gap-2 text-sm text-gray-400";

    const isCurrentChapter = chapter.chapterNumber === state.currentChapter;

    marker.style.position = "absolute";
    marker.style.top = `${((chapter.pageStart - 1) / 100) * 100}%`;
    marker.style.left = "10px";

    marker.innerHTML = `
      <span class="chapter-number ${isCurrentChapter ? "text-blue-400 font-bold" : ""}">
        ${chapter.title || `Chapter ${chapter.chapterNumber}`}
      </span>
      <span class="page-number text-xs">p.${chapter.pageStart}</span>
      ${isCurrentChapter ? '<span class="current-indicator">←</span>' : ""}
    `;

    markersContainer.appendChild(marker);
  });

  const existing = container.querySelector(".chapter-markers");
  existing?.remove();
  container.appendChild(markersContainer);
}

function updateCurrentChapter(
  state: ChapterMarkerState,
  currentPage: number,
): ChapterMarkerState {
  const currentChapter =
    state.chapters.find(
      (c) => currentPage >= c.pageStart && currentPage <= c.pageEnd,
    )?.chapterNumber || state.currentChapter;

  if (currentChapter !== state.currentChapter) {
    state.currentChapter = currentChapter;

    const markers = document.querySelector(".chapter-markers");
    if (markers) {
      renderChapterMarkers(markers.parentElement!, state);
    }
  }

  return state;
}

function toggleChapterMarkers(state: ChapterMarkerState): ChapterMarkerState {
  state.showMarkers = !state.showMarkers;

  const markers = document.querySelector(".chapter-markers");
  if (markers) {
    markers.classList.toggle("hidden", !state.showMarkers);
  }

  return state;
}

function scrollToChapter(
  state: ChapterMarkerState,
  chapterNumber: number,
): void {
  const chapter = state.chapters.find((c) => c.chapterNumber === chapterNumber);
  if (chapter) {
    window.dispatchEvent(
      new CustomEvent("navigate-to-page", {
        detail: { page: chapter.pageStart },
      }),
    );
  }
}