/**
 * Shared "My Saved Spots" favourites system.
 *
 * A single localStorage-backed favourites list shared across the whole site -
 * locations (explore.html), walks (routes.html / walks_*.html), and workshops
 * (workshops.html) all write into the same store, and the navbar reads from
 * it to show a unified panel. Loaded early (right after 00-icons.jsx) so
 * every subsequent page script and the navbar itself can use it directly.
 *
 * Each saved entry stores enough info to render the panel immediately
 * (id, category, name, url, and a short subtitle) rather than just an id -
 * that avoids every page needing to re-fetch locations.json/walks.json/
 * workshops.json just to show the saved list.
 */

const FAVOURITES_KEY = 'np_favourites';
const FAVOURITES_EVENT = 'np-favourites-changed';

const getFavourites = () => {
    try {
        const raw = localStorage.getItem(FAVOURITES_KEY);
        const parsed = raw ? JSON.parse(raw) : [];
        return Array.isArray(parsed) ? parsed : [];
    } catch (e) {
        return [];
    }
};

const saveFavourites = (list) => {
    try {
        localStorage.setItem(FAVOURITES_KEY, JSON.stringify(list));
    } catch (e) {
        console.warn('Could not save favourites (localStorage unavailable):', e.message);
    }
    // Lets the navbar (and any other listener) update its badge/panel
    // immediately, even though it lives in a totally separate component.
    window.dispatchEvent(new Event(FAVOURITES_EVENT));
};

const isFavourited = (category, id) => {
    return getFavourites().some((f) => f.category === category && f.id === id);
};

// entry: { category: 'location'|'walk'|'workshop', id, name, subtitle, url }
const toggleFavourite = (entry) => {
    const list = getFavourites();
    const idx = list.findIndex((f) => f.category === entry.category && f.id === entry.id);
    if (idx >= 0) {
        list.splice(idx, 1);
    } else {
        list.unshift({ ...entry, savedAt: Date.now() });
    }
    saveFavourites(list);
    return idx < 0; // true if it was just added, false if just removed
};

const removeFavourite = (category, id) => {
    const list = getFavourites().filter((f) => !(f.category === category && f.id === id));
    saveFavourites(list);
};
