"use client";

export interface SavedMessageSnapshot {
  id: string;
  workspaceId: string;
  channelId: string;
  channelName: string | null;
  authorName: string;
  text: string;
  createdAt: string;
  savedAt: string;
}

const PREFIX = "voxi.saved.v1";
const EVENT = "voxi:saved-items";

function key(workspaceId: string) {
  return `${PREFIX}:${workspaceId}`;
}

export function getSavedMessages(workspaceId: string | null | undefined): SavedMessageSnapshot[] {
  if (!workspaceId || typeof window === "undefined") return [];
  try {
    const parsed = JSON.parse(window.localStorage.getItem(key(workspaceId)) ?? "[]") as SavedMessageSnapshot[];
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

export function isMessageSaved(workspaceId: string | null | undefined, messageId: string | number): boolean {
  return getSavedMessages(workspaceId).some((item) => String(item.id) === String(messageId));
}

export function saveMessageSnapshot(snapshot: SavedMessageSnapshot) {
  if (typeof window === "undefined") return;
  const current = getSavedMessages(snapshot.workspaceId).filter((item) => String(item.id) !== String(snapshot.id));
  const next = [snapshot, ...current].slice(0, 200);
  window.localStorage.setItem(key(snapshot.workspaceId), JSON.stringify(next));
  window.dispatchEvent(new CustomEvent(EVENT, { detail: { workspaceId: snapshot.workspaceId } }));
}

export function unsaveMessage(workspaceId: string | null | undefined, messageId: string | number) {
  if (!workspaceId || typeof window === "undefined") return;
  const next = getSavedMessages(workspaceId).filter((item) => String(item.id) !== String(messageId));
  window.localStorage.setItem(key(workspaceId), JSON.stringify(next));
  window.dispatchEvent(new CustomEvent(EVENT, { detail: { workspaceId } }));
}

export function subscribeSavedMessages(workspaceId: string, callback: () => void) {
  const onLocal = (event: Event) => {
    const detail = (event as CustomEvent<{ workspaceId?: string }>).detail;
    if (!detail?.workspaceId || detail.workspaceId === workspaceId) callback();
  };
  const onStorage = (event: StorageEvent) => {
    if (event.key === key(workspaceId)) callback();
  };
  window.addEventListener(EVENT, onLocal);
  window.addEventListener("storage", onStorage);
  return () => {
    window.removeEventListener(EVENT, onLocal);
    window.removeEventListener("storage", onStorage);
  };
}
