export const DEFAULT_BOOKMARK_HIGHLIGHT_COLOR = "#fde047";

export const BOOKMARK_HIGHLIGHT_PRESETS = [
  { id: "yellow", value: "#fde047", labelKey: "annotations.highlightYellow" },
  { id: "green", value: "#86efac", labelKey: "annotations.highlightGreen" },
  { id: "pink", value: "#f9a8d4", labelKey: "annotations.highlightPink" },
  { id: "blue", value: "#93c5fd", labelKey: "annotations.highlightBlue" },
  { id: "purple", value: "#d8b4fe", labelKey: "annotations.highlightPurple" },
] as const;

const HEX_COLOR_RE = /^#[0-9A-Fa-f]{6}$/;

export function normalizeHighlightColor(value: string | undefined | null): string {
  const v = (value ?? "").trim();
  return HEX_COLOR_RE.test(v) ? v.toLowerCase() : DEFAULT_BOOKMARK_HIGHLIGHT_COLOR;
}

export function markerPassageStyle(color: string): {
  borderLeft: string;
  backgroundColor: string;
  paddingLeft: number;
  margin: string;
  borderRadius: number;
} {
  const c = normalizeHighlightColor(color);
  return {
    borderLeft: `4px solid ${c}`,
    backgroundColor: `${c}26`,
    paddingLeft: 10,
    margin: "8px 0",
    borderRadius: 4,
  };
}

export function highlightBackgroundStyle(color: string): {
  backgroundColor: string;
  boxDecorationBreak: "clone";
  WebkitBoxDecorationBreak: "clone";
  padding: string;
  borderRadius: number;
} {
  return {
    backgroundColor: color,
    boxDecorationBreak: "clone",
    WebkitBoxDecorationBreak: "clone",
    padding: "0 2px",
    borderRadius: 2,
  };
}

export const BOOKMARK_COLOR_STORAGE_KEY = "cloud-reader:lastBookmarkHighlightColor";

export function loadLastHighlightColor(): string {
  try {
    return normalizeHighlightColor(localStorage.getItem(BOOKMARK_COLOR_STORAGE_KEY));
  } catch {
    return DEFAULT_BOOKMARK_HIGHLIGHT_COLOR;
  }
}

export function saveLastHighlightColor(color: string): void {
  try {
    localStorage.setItem(BOOKMARK_COLOR_STORAGE_KEY, normalizeHighlightColor(color));
  } catch {
    /* ignore */
  }
}
