// Background color options for manga/comics
// Feature Registration Pattern implementation

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

export function init(context: ReaderContext): void {
  const state = createBackgroundColorState();
  applyBackgroundColor(state.current);

  context.events.on("background-color:set", (detail: { color: BackgroundColor; customColor?: string }) => {
    setBackgroundColor(state, detail.color, detail.customColor);
  });

  context.events.on("background-color:toggle", () => {
    toggleBackgroundColor(state);
  });

  context.events.on("ui:show-settings", (detail: { container: HTMLElement }) => {
    renderBackgroundColorPicker(detail.container, state);
  });

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

type BackgroundColor = "black" | "white" | "gray" | "sepia" | "custom";

interface BackgroundColorState {
  current: BackgroundColor;
  customColor: string;
}

const backgroundColors: Record<BackgroundColor, string> = {
  black: "#000000",
  white: "#ffffff",
  gray: "#333333",
  sepia: "#f4ecd8",
  custom: "",
};

function createBackgroundColorState(
  initial: BackgroundColor = "black",
): BackgroundColorState {
  const saved = localStorage.getItem("reader-background-color") as BackgroundColor;
  return {
    current: saved || initial,
    customColor: "#000000",
  };
}

function applyBackgroundColor(color: BackgroundColor): void {
  const bgColor = backgroundColors[color];
  document.documentElement.style.setProperty("--reader-bg-color", bgColor);
  const viewer = document.querySelector(".reader-content") as HTMLElement;
  if (viewer) {
    viewer.style.backgroundColor = bgColor;
  }
}

function setBackgroundColor(
  state: BackgroundColorState,
  color: BackgroundColor,
  customColor?: string,
): BackgroundColorState {
  state.current = color;
  state.customColor = customColor || state.customColor;

  const bgColor = color === "custom" ? state.customColor : backgroundColors[color];
  document.documentElement.style.setProperty("--reader-bg-color", bgColor);

  const viewer = document.querySelector(".reader-content") as HTMLElement;
  if (viewer) {
    viewer.style.backgroundColor = bgColor;
  }

  localStorage.setItem("reader-background-color", color);

  const picker = document.querySelector(".background-color-picker");
  if (picker) {
    updateBackgroundColorUI(picker as HTMLElement, state);
  }

  return state;
}

function toggleBackgroundColor(state: BackgroundColorState): BackgroundColorState {
  const order: BackgroundColor[] = ["black", "white", "gray", "sepia"];
  const currentIndex = order.indexOf(state.current);
  const nextIndex = (currentIndex + 1) % order.length;
  return setBackgroundColor(state, order[nextIndex]);
}

function renderBackgroundColorPicker(
  container: HTMLElement,
  state: BackgroundColorState,
): void {
  const existing = container.querySelector(".background-color-picker");
  existing?.remove();

  const picker = document.createElement("div");
  picker.className =
    "background-color-picker fixed bottom-24 left-4 bg-gray-900 bg-opacity-90 rounded-lg p-2 flex gap-2 z-40";

  const colors: BackgroundColor[] = ["black", "white", "gray", "sepia"];

  colors.forEach((color) => {
    const btn = document.createElement("button");
    btn.className = `w-8 h-8 rounded-full border-2 ${
      state.current === color ? "border-blue-500" : "border-transparent"
    }`;
    btn.style.backgroundColor = backgroundColors[color];
    btn.title = color.charAt(0).toUpperCase() + color.slice(1);
    btn.addEventListener("click", () => {
      setBackgroundColor(state, color);
      updateBackgroundColorUI(picker, state);
    });
    picker.appendChild(btn);
  });

  container.appendChild(picker);
}

function updateBackgroundColorUI(
  container: HTMLElement,
  state: BackgroundColorState,
): void {
  const buttons = container.querySelectorAll("button");
  const colors: BackgroundColor[] = ["black", "white", "gray", "sepia"];

  buttons.forEach((btn, index) => {
    btn.classList.toggle("border-blue-500", colors[index] === state.current);
  });
}