import { get, writable } from 'svelte/store';
import { getAccountData, setAccountData } from './api';
import { MAX_QUICK_REACTIONS } from './types';
import type { QuickReaction } from './types';

const EVENT_TYPE = 'dev.malice.quick_reactions';

export const DEFAULT_QUICK_REACTIONS: QuickReaction[] = [
  { key: '👍', shortcode: 'thumbsup' },
  { key: '❤️', shortcode: 'heart' },
  { key: '😂', shortcode: 'joy' },
  { key: '🎉', shortcode: 'tada' },
  { key: '😮', shortcode: 'open_mouth' },
  { key: '😢', shortcode: 'cry' }
];

export const quickReactions = writable<QuickReaction[]>(DEFAULT_QUICK_REACTIONS);

function parse(raw: unknown): QuickReaction[] | null {
  if (typeof raw !== 'object' || raw === null) return null;
  const list = (raw as Record<string, unknown>)['reactions'];
  if (!Array.isArray(list)) return null;
  const seen = new Set<string>();
  const out: QuickReaction[] = [];
  for (const item of list) {
    if (typeof item !== 'object' || item === null) continue;
    const { key, shortcode } = item as Record<string, unknown>;
    if (typeof key !== 'string' || !key || seen.has(key)) continue;
    seen.add(key);
    out.push({ key, shortcode: typeof shortcode === 'string' ? shortcode : null });
  }
  return out.slice(0, MAX_QUICK_REACTIONS);
}

export async function loadQuickReactions(): Promise<void> {
  try {
    quickReactions.set(parse(await getAccountData(EVENT_TYPE)) ?? DEFAULT_QUICK_REACTIONS);
  } catch {
    quickReactions.set(DEFAULT_QUICK_REACTIONS);
  }
}

export async function saveQuickReactions(list: QuickReaction[]): Promise<void> {
  const reactions = list.slice(0, MAX_QUICK_REACTIONS);
  const previous = get(quickReactions);
  quickReactions.set(reactions);
  try {
    await setAccountData(EVENT_TYPE, { reactions });
  } catch (e) {
    if (get(quickReactions) === reactions) quickReactions.set(previous);
    throw e;
  }
}

export function resetQuickReactions(): void {
  quickReactions.set(DEFAULT_QUICK_REACTIONS);
}
