// ══════════════════════════════════════════════════════════════════
//  InPractice — useNotificationStore.js
//  Location: resources/js/Stores/useNotificationStore.js
//
//  Tracks the user's unread notification count and notification list.
//  The bell icon in AppLayout reads unreadCount from here.
//
//  The unread count is seeded from HandleInertiaRequests.php
//  on every page load — no separate API call needed.
// ══════════════════════════════════════════════════════════════════

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import axios from 'axios';

export const useNotificationStore = defineStore('notifications', () => {

    // ── State ──────────────────────────────────────────────────────
    const notifications = ref([]);
    const unreadCount   = ref(0);
    const isOpen        = ref(false);   // controls the notification dropdown

    // ── Computed ───────────────────────────────────────────────────
    const hasUnread = computed(() => unreadCount.value > 0);

    const unreadBadge = computed(() => {
        if (unreadCount.value === 0) return null;
        if (unreadCount.value > 99) return '99+';
        return String(unreadCount.value);
    });

    // ── Actions ────────────────────────────────────────────────────

    /**
     * Seed the initial unread count from Inertia shared data.
     * Called in AppLayout on mount.
     */
    function init(count) {
        unreadCount.value = count ?? 0;
    }

    /**
     * Toggle the notification panel open/closed.
     * When opening, mark all as read.
     */
    function toggle() {
        isOpen.value = !isOpen.value;
        if (isOpen.value && unreadCount.value > 0) {
            markAllRead();
        }
    }

    function close() {
        isOpen.value = false;
    }

    /**
     * Mark all notifications as read — optimistic update then server call.
     */
    function markAllRead() {
        unreadCount.value = 0;
        axios.patch(route('member.notifications.read-all'))
            .catch(() => {
                // Silent fail — count will resync on next page load
            });
    }

    /**
     * Increment count when a real-time notification arrives (future: Echo/Pusher).
     */
    function increment() {
        unreadCount.value += 1;
    }

    /**
     * Set notifications list (loaded when panel opens).
     */
    function setList(list) {
        notifications.value = list;
    }

    // ── Return ─────────────────────────────────────────────────────
    return {
        notifications,
        unreadCount,
        isOpen,
        hasUnread,
        unreadBadge,
        init,
        toggle,
        close,
        markAllRead,
        increment,
        setList,
    };
});
