// --- Personal engagement stats --------------------------------------------
// Three simple action counters - messages read (detail view opened), echoed,
// and let go - stored only in localStorage on this device. Like trail.js,
// this is purely local: never sent to Firestore, never attached to a
// message, never shared. It's a private mirror of how THIS device has moved
// through the app (read vs. acted), shown as a summary line on the archive
// page.

const STATS_KEY = 'overheard_stats';

const DEFAULT_STATS = { read: 0, echoed: 0, letGo: 0 };

// Reads the stats object from localStorage, merged over the all-zero
// defaults so older/partial stored objects (or a first-ever read with
// nothing stored yet) still have all three keys. Falls back to defaults
// entirely if localStorage is unavailable (SSR) or the value can't be parsed.
export function getStats() {
    if (typeof localStorage === 'undefined') return { ...DEFAULT_STATS };

    try {
        const raw = localStorage.getItem(STATS_KEY);
        return raw ? { ...DEFAULT_STATS, ...JSON.parse(raw) } : { ...DEFAULT_STATS };
    } catch {
        return { ...DEFAULT_STATS };
    }
}

// Increments one counter by 1 and persists the whole stats object back to
// localStorage. Internal helper - see the three named exports below.
function incrementStat(key) {
    const stats = getStats();
    stats[key] = (stats[key] ?? 0) + 1;

    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem(STATS_KEY, JSON.stringify(stats));
        } catch {
            // localStorage unavailable/full - nothing more we can do here
        }
    }

    return stats;
}

// called when a message detail view is opened (BottomSheet/SidePanel)
export const incrementRead = () => incrementStat('read');
// called when the Echo button is pressed
export const incrementEchoed = () => incrementStat('echoed');
// called when the Let go button is pressed
export const incrementLetGo = () => incrementStat('letGo');

// --- "last chance" one-time prompt tracking --------------------------------
// Tracks which message IDs have already shown the "last chance" prompt (see
// BottomSheet.svelte / SidePanel.svelte) so it appears at most once per
// message, per device - reopening the same message later (while it's still
// on its last day) won't show it again.

const LAST_CHANCE_SEEN_KEY = 'overheard_last_chance_seen';

function getSeenLastChanceIds() {
    if (typeof localStorage === 'undefined') return [];

    try {
        const raw = localStorage.getItem(LAST_CHANCE_SEEN_KEY);
        return raw ? JSON.parse(raw) : [];
    } catch {
        return [];
    }
}

// has this message ID already shown the "last chance" prompt?
export function hasSeenLastChancePrompt(messageId) {
    return getSeenLastChanceIds().includes(messageId);
}

// marks a message ID as having shown the prompt, so it won't show again
export function markLastChancePromptSeen(messageId) {
    const seen = getSeenLastChanceIds();
    if (seen.includes(messageId)) return;

    seen.push(messageId);

    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem(LAST_CHANCE_SEEN_KEY, JSON.stringify(seen));
        } catch {
            // localStorage unavailable/full - worst case the prompt could
            // reappear once more for this message, which is harmless
        }
    }
}
