"use client";
import { create } from "zustand";
import { persist } from "zustand/middleware";

function generateSessionId(): string {
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  // Fallback for environments without crypto.randomUUID
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
  });
}

interface NotificationStore {
  /** Stable browser session ID — generated once, persisted forever */
  sessionId:   string;
  unreadCount: number;
  setUnreadCount: (n: number) => void;
  incrementUnread: () => void;
}

export const useNotificationStore = create<NotificationStore>()(
  persist(
    (set) => ({
      sessionId:   generateSessionId(),
      unreadCount: 0,
      setUnreadCount:  (n) => set({ unreadCount: n }),
      incrementUnread: ()  => set((s) => ({ unreadCount: s.unreadCount + 1 })),
    }),
    { name: "drivehub-notif-session" }
  )
);
