// Detect reading direction from metadata or user preference
// Feature Registration Pattern implementation

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

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

  context.events.on("reader:loaded", async (detail: { metadata: any }) => {
    state = await detectReadingDirection(detail.metadata);
    const effectiveDirection = getEffectiveDirection(state);
    context.events.emit("reading-direction:detected", { direction: effectiveDirection });
  });

  context.events.on("reading-direction:set", (detail: { direction: "auto" | "ltr" | "rtl" | "vertical" }) => {
    if (state) {
      state.direction = detail.direction;
      const effectiveDirection = getEffectiveDirection(state);
      context.events.emit("reading-direction:changed", { direction: effectiveDirection });
    }
  });

  context.events.on("reading-direction:get", () => {
    if (state) {
      const effectiveDirection = getEffectiveDirection(state);
      context.events.emit("reading-direction:current", { direction: effectiveDirection });
    }
  });

  context.events.on("reading-direction:is-rtl", () => {
    if (state) {
      const isRTL = shouldUseRTL(state);
      context.events.emit("reading-direction:is-rtl-result", { isRTL });
    }
  });

  context.events.on("reading-direction:is-vertical", () => {
    if (state) {
      const isVertical = shouldUseVerticalScroll(state);
      context.events.emit("reading-direction:is-vertical-result", { isVertical });
    }
  });
}

type ReadingDirection = "auto" | "ltr" | "rtl" | "vertical";

interface ReadingDirectionState {
  direction: ReadingDirection;
  detectedDirection: "ltr" | "rtl" | "vertical";
  userPreference: ReadingDirection | null;
}

async function detectReadingDirection(
  metadata: any,
): Promise<ReadingDirectionState> {
  const userPreference = await getUserReadingDirectionPreference();
  if (userPreference && userPreference !== "auto") {
    return {
      direction: userPreference,
      detectedDirection: "ltr",
      userPreference,
    };
  }

  const detectedDirection = detectFromMetadata(metadata);

  return {
    direction: "auto",
    detectedDirection,
    userPreference: null,
  };
}

function detectFromMetadata(
  metadata: any,
): "ltr" | "rtl" | "vertical" {
  const mangaType = (metadata as any).manga_type;
  if (mangaType === "yes_and_right_to_left" || mangaType === "yes") {
    return "rtl";
  }

  const readingDirection = (metadata as any).reading_direction;
  if (readingDirection === "rtl" || readingDirection === "vertical") {
    return readingDirection;
  }

  const filename = metadata.filePath.toLowerCase();
  if (
    filename.includes("manga") ||
    filename.includes("manhwa") ||
    filename.includes("webtoon")
  ) {
    return "vertical";
  }

  return "ltr";
}

async function getUserReadingDirectionPreference(): Promise<ReadingDirection | null> {
  const userId = localStorage.getItem("userId");
  if (!userId) return null;

  try {
    const response = await fetch(`/api/users/${userId}/settings`);
    if (!response.ok) return null;

    const settings = await response.json();
    return settings.reading_direction || null;
  } catch {
    return null;
  }
}

function getEffectiveDirection(
  state: ReadingDirectionState,
): "ltr" | "rtl" | "vertical" {
  if (state.direction !== "auto") {
    return state.direction as "ltr" | "rtl" | "vertical";
  }
  return state.detectedDirection;
}

function shouldUseRTL(state: ReadingDirectionState): boolean {
  return getEffectiveDirection(state) === "rtl";
}

function shouldUseVerticalScroll(state: ReadingDirectionState): boolean {
  return getEffectiveDirection(state) === "vertical";
}