// mariusson — saves, likes, and room posts (per-user, localStorage-backed)
//
// Three storage keys:
//   mariusson:saves    { [userId]: [workId, ...] }
//   mariusson:likes    { [userId]: [workId, ...] }
//   mariusson:posts    { [workId]: [{ id, who, when, text, userId }, ...] }
//
// Anonymous users get an `anon` bucket so a viewer who's poking around
// without an account still has *something* persist across reloads.

(() => {
  const SAVES = 'mariusson:saves';
  const LIKES = 'mariusson:likes';
  const POSTS = 'mariusson:posts';

  function readMap(key) {
    try { return JSON.parse(localStorage.getItem(key) || '{}'); }
    catch { return {}; }
  }
  function writeMap(key, obj) {
    try { localStorage.setItem(key, JSON.stringify(obj)); } catch {}
  }

  function uid() {
    const a = window.AN_AUTH ? window.AN_AUTH.currentAccount() : null;
    return a?.id || 'anon';
  }

  // ── saves ────────────────────────────────────────────────────────
  function getSaves() {
    return new Set(readMap(SAVES)[uid()] || []);
  }
  function setSaves(set) {
    const all = readMap(SAVES);
    all[uid()] = [...set];
    writeMap(SAVES, all);
    window.dispatchEvent(new Event('an-saves-changed'));
  }
  function toggleSave(workId) {
    const cur = getSaves();
    if (cur.has(workId)) cur.delete(workId); else cur.add(workId);
    setSaves(cur);
    return cur;
  }

  // ── likes ────────────────────────────────────────────────────────
  function getLikes() {
    return new Set(readMap(LIKES)[uid()] || []);
  }
  function setLikes(set) {
    const all = readMap(LIKES);
    all[uid()] = [...set];
    writeMap(LIKES, all);
    window.dispatchEvent(new Event('an-likes-changed'));
  }
  function toggleLike(workId) {
    const cur = getLikes();
    if (cur.has(workId)) cur.delete(workId); else cur.add(workId);
    setLikes(cur);
    return cur;
  }

  // ── room posts ────────────────────────────────────────────────────
  function getPosts(workId) {
    return readMap(POSTS)[workId] || [];
  }
  function addPost(workId, post) {
    const all = readMap(POSTS);
    const list = all[workId] || [];
    list.unshift({
      id: 'p_' + Math.random().toString(36).slice(2, 9),
      who: post.who || 'you',
      when: 'just now',
      text: String(post.text || '').trim(),
      userId: uid(),
      ts: Date.now(),
    });
    all[workId] = list.slice(0, 200);
    writeMap(POSTS, all);
    window.dispatchEvent(new Event('an-posts-changed'));
    return list[0];
  }

  // ── React hooks ───────────────────────────────────────────────────
  function useSavedSet() {
    const [s, setS] = React.useState(getSaves);
    React.useEffect(() => {
      const refresh = () => setS(getSaves());
      window.addEventListener('an-saves-changed', refresh);
      window.addEventListener('storage', (e) => { if (e.key === SAVES) refresh(); });
      return () => window.removeEventListener('an-saves-changed', refresh);
    }, []);
    return s;
  }
  function useLikedSet() {
    const [s, setS] = React.useState(getLikes);
    React.useEffect(() => {
      const refresh = () => setS(getLikes());
      window.addEventListener('an-likes-changed', refresh);
      window.addEventListener('storage', (e) => { if (e.key === LIKES) refresh(); });
      return () => window.removeEventListener('an-likes-changed', refresh);
    }, []);
    return s;
  }
  function useRoomPosts(workId) {
    const [p, setP] = React.useState(() => getPosts(workId));
    React.useEffect(() => {
      const refresh = () => setP(getPosts(workId));
      refresh();
      window.addEventListener('an-posts-changed', refresh);
      window.addEventListener('storage', (e) => { if (e.key === POSTS) refresh(); });
      return () => window.removeEventListener('an-posts-changed', refresh);
    }, [workId]);
    return p;
  }

  window.AN_INTERACTIONS = {
    getSaves, getLikes, getPosts,
    toggleSave, toggleLike, addPost,
    SAVES, LIKES, POSTS,
  };
  window.useSavedSet = useSavedSet;
  window.useLikedSet = useLikedSet;
  window.useRoomPosts = useRoomPosts;
})();
