// --- Personal location trail ---------------------------------------------
// A private, on-device-only record of every place this device has ever
// opened Overheard. Stored solely in localStorage - this never gets sent to
// Firestore, attached to a message, or shared with anyone else in any way.
// Unlike the public messages (which decay after 30 days, see messages.js),
// this history is kept forever with no pruning or size limit - it's a
// permanent personal map of presence, for this device/browser only.

const STORAGE_KEY = 'overheard_location_trail';

// Reads the full trail array ([{ lat, lng, timestamp }, ...], oldest first)
// from localStorage. Returns [] if nothing has been recorded yet, if
// localStorage isn't available (e.g. during SSR), or if the stored value
// can't be parsed - any of those just means "no trail to draw" rather than
// an error worth surfacing.
export function getTrail() {
    if (typeof localStorage === 'undefined') return [];

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

// Appends a new { lat, lng, timestamp } point to the trail and writes the
// whole array back to localStorage, then returns the updated array so the
// caller can render it immediately without a second read. Intentionally
// has no size cap/pruning - every visit is kept. Called unconditionally on
// every successful geolocation fetch, regardless of whether the trail is
// currently shown - logging the visit and displaying it are independent.
export function addTrailPoint(lat, lng) {
    const trail = getTrail();
    trail.push({ lat, lng, timestamp: Date.now() });

    if (typeof localStorage !== 'undefined') {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(trail));
        } catch {
            // localStorage unavailable/full - still return the in-memory
            // array below so the trail renders for this session at least
        }
    }

    return trail;
}
