import { writable, type Writable } from 'svelte/store';

export const MESSAGE_SPACING_MIN = 0;
export const MESSAGE_SPACING_MAX = 16;
export const MESSAGE_SPACING_DEFAULT = 3;

function persisted<T>(key: string, fallback: T, valid: (v: unknown) => v is T): Writable<T> {
  let initial = fallback;
  try {
    const raw = localStorage.getItem(key);
    if (raw !== null) {
      const parsed: unknown = JSON.parse(raw);
      if (valid(parsed)) initial = parsed;
    }
  } catch {}
  const store = writable(initial);
  store.subscribe((value) => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch {}
  });
  return store;
}

const isBool = (v: unknown): v is boolean => typeof v === 'boolean';
const isSpacing = (v: unknown): v is number =>
  typeof v === 'number' && Number.isFinite(v) && v >= MESSAGE_SPACING_MIN && v <= MESSAGE_SPACING_MAX;

export const navFolded = persisted('malice.navFolded', false, isBool);
export const railFolded = persisted('malice.railFolded', false, isBool);
export const messageSpacing = persisted('malice.messageSpacing', MESSAGE_SPACING_DEFAULT, isSpacing);

export const LINE_HEIGHT_MIN = 1.1;
export const LINE_HEIGHT_MAX = 2;
export const LINE_HEIGHT_DEFAULT = 1.5;

const isLineHeight = (v: unknown): v is number =>
  typeof v === 'number' && Number.isFinite(v) && v >= LINE_HEIGHT_MIN && v <= LINE_HEIGHT_MAX;

export const lineHeight = persisted('malice.lineHeight', LINE_HEIGHT_DEFAULT, isLineHeight);

const isStringRecord = (v: unknown): v is Record<string, string> =>
  typeof v === 'object' && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === 'string');

export const lastSpaceRooms = persisted<Record<string, string>>('malice.lastSpaceRooms', {}, isStringRecord);

export const THEMES = [
  { id: 'system', label: 'Match system' },
  { id: 'dark', label: 'Dark' },
  { id: 'light', label: 'Light' },
  { id: 'black', label: 'Black' },
  { id: 'nord', label: 'Nord' }
] as const;

export type ThemeId = (typeof THEMES)[number]['id'];

const isTheme = (v: unknown): v is ThemeId => THEMES.some((t) => t.id === v);
const isAccent = (v: unknown): v is string | null => v === null || (typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v));

export const theme = persisted<ThemeId>('malice.theme', 'dark', isTheme);
export const accent = persisted<string | null>('malice.accent', null, isAccent);

if (typeof document !== 'undefined') {
  const root = document.documentElement;
  const prefersLight = window.matchMedia('(prefers-color-scheme: light)');
  let current: ThemeId = 'system';
  const apply = () => {
    root.dataset.theme = current === 'system' ? (prefersLight.matches ? 'light' : 'dark') : current;
  };
  theme.subscribe((t) => {
    current = t;
    apply();
  });
  prefersLight.addEventListener('change', apply);
  accent.subscribe((a) => {
    if (a) root.style.setProperty('--accent', a);
    else root.style.removeProperty('--accent');
  });
}
