import { get, writable, type Writable } from 'svelte/store';
import { THEME_COLOURS, isCustomTheme, type CustomTheme, type ThemeDocument } from './custom-themes';

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 SIDE_WIDTH = { min: 200, max: 480, default: 260 };
export const MEMBERS_WIDTH = { min: 200, max: 420, default: 240 };
export const THREAD_WIDTH = { min: 300, max: 720, default: 400 };
const widthIn = (range: { min: number; max: number }) => (v: unknown): v is number =>
  typeof v === 'number' && Number.isFinite(v) && v >= range.min && v <= range.max;
export const sideWidth = persisted('malice.sideWidth', SIDE_WIDTH.default, widthIn(SIDE_WIDTH));
export const membersWidth = persisted('malice.membersWidth', MEMBERS_WIDTH.default, widthIn(MEMBERS_WIDTH));
export const threadWidth = persisted('malice.threadWidth', THREAD_WIDTH.default, widthIn(THREAD_WIDTH));
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' },
  { id: 'malicious', label: 'Malicious' }
] as const;

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

const isCustomThemeList = (v: unknown): v is CustomTheme[] => Array.isArray(v) && v.every(isCustomTheme);
export const customThemes = persisted<CustomTheme[]>('malice.customThemes', [], isCustomThemeList);
export const themePreview = writable<ThemeDocument | null>(null);

const isTheme = (v: unknown): v is ThemeId => THEMES.some((t) => t.id === v) || get(customThemes).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)');
  const themeColor = document.querySelector('meta[name="theme-color"]');
  const apply = () => {
    const current = get(theme);
    const custom = get(themePreview) ?? get(customThemes).find((t) => t.id === current);
    const base = current === 'system' ? (prefersLight.matches ? 'light' : 'dark') : current;
    root.dataset.theme = custom?.scheme ?? (current.startsWith('custom:') ? 'dark' : base);
    for (const [key] of THEME_COLOURS) {
      if (custom) root.style.setProperty(`--${key}`, custom.colours[key]);
      else root.style.removeProperty(`--${key}`);
    }
    if (custom) {
      root.style.setProperty('--name-lightness', `${custom.nameLightness}%`);
      root.style.colorScheme = custom.scheme;
    } else {
      root.style.removeProperty('--name-lightness');
      root.style.removeProperty('color-scheme');
    }
    const override = get(accent);
    if (override && !get(themePreview)) root.style.setProperty('--accent', override);
    const bar = getComputedStyle(root).getPropertyValue('--rail-bg').trim();
    if (bar) themeColor?.setAttribute('content', bar);
  };
  theme.subscribe(apply);
  customThemes.subscribe(apply);
  themePreview.subscribe(apply);
  prefersLight.addEventListener('change', apply);
  accent.subscribe(apply);
}
