export const DEFAULT_DIGIT_COLOR = '#2563eb';
export const DEFAULT_SYMBOL_COLOR = '#dc2626';
const STORAGE_KEY = 'password_display_scheme';
const HEX_RE = /^#[0-9a-fA-F]{6}$/;

export interface ColorScheme {
  digit_color: string;
  symbol_color: string;
}

export const DEFAULT_SCHEME: ColorScheme = {
  digit_color: DEFAULT_DIGIT_COLOR,
  symbol_color: DEFAULT_SYMBOL_COLOR,
};

function isValid(s: ColorScheme): boolean {
  return HEX_RE.test(s.digit_color) && HEX_RE.test(s.symbol_color);
}

export async function loadColorScheme(): Promise<ColorScheme> {
  const result = await chrome.storage.sync.get(STORAGE_KEY);
  const stored = result[STORAGE_KEY] as Partial<ColorScheme> | undefined;
  if (!stored) return { ...DEFAULT_SCHEME };
  return {
    digit_color: typeof stored.digit_color === 'string' && HEX_RE.test(stored.digit_color)
      ? stored.digit_color : DEFAULT_DIGIT_COLOR,
    symbol_color: typeof stored.symbol_color === 'string' && HEX_RE.test(stored.symbol_color)
      ? stored.symbol_color : DEFAULT_SYMBOL_COLOR,
  };
}

export async function saveColorScheme(scheme: ColorScheme): Promise<void> {
  if (!isValid(scheme)) {
    throw new Error('Invalid color values; expected #rrggbb hex strings.');
  }
  await chrome.storage.sync.set({ [STORAGE_KEY]: scheme });
}

export async function resetColorScheme(): Promise<void> {
  await chrome.storage.sync.remove(STORAGE_KEY);
}

export async function applyColorScheme(): Promise<void> {
  const scheme = await loadColorScheme();
  const root = document.documentElement.style;
  root.setProperty('--relicario-pwd-digit-color', scheme.digit_color);
  root.setProperty('--relicario-pwd-symbol-color', scheme.symbol_color);
}
