// Simple localStorage-based notification store
export type Notification = {
  id: string;
  module: string;
  message: string;
  timestamp: string;
  read: boolean;
  link: string;
};

const KEY = 'usfloral-notifications';

export function getNotifications(): Notification[] {
  if (typeof window === 'undefined') return [];
  try {
    return JSON.parse(localStorage.getItem(KEY) || '[]');
  } catch {
    return [];
  }
}

export function addNotification(notif: Pick<Notification, 'module' | 'message' | 'link'>) {
  const existing = getNotifications();
  const newNotif: Notification = {
    ...notif,
    id: Date.now().toString(),
    timestamp: new Date().toISOString(),
    read: false,
  };
  const updated = [newNotif, ...existing].slice(0, 25);
  localStorage.setItem(KEY, JSON.stringify(updated));
  window.dispatchEvent(new CustomEvent('usfloral-notification'));
}

export function markAllRead() {
  const notifs = getNotifications().map(n => ({ ...n, read: true }));
  localStorage.setItem(KEY, JSON.stringify(notifs));
  window.dispatchEvent(new CustomEvent('usfloral-notification'));
}

export function clearNotifications() {
  localStorage.setItem(KEY, '[]');
  window.dispatchEvent(new CustomEvent('usfloral-notification'));
}

export function formatRelative(timestamp: string): string {
  const diff = Date.now() - new Date(timestamp).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Ahora mismo';
  if (mins < 60) return `Hace ${mins} min`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `Hace ${hrs}h`;
  return `Hace ${Math.floor(hrs / 24)}d`;
}
