/* Club FRESH — live wiring layer.
   Loaded after cf-data: persistence, real dates, and the chat backend.
   Keeps the design files close to their Claude Design source. */

(function () {
  const CHAT_URL = 'https://club-fresh-chat.karl-5fb.workers.dev/api/messages';

  const todayKey = () => new Date().toISOString().slice(0, 10);
  const read = (k, fb) => { try { const v = JSON.parse(localStorage.getItem(k)); return v == null ? fb : v; } catch { return fb; } };
  const write = (k, v) => localStorage.setItem(k, JSON.stringify(v));

  /* ---- sweep persistence (Daily Five marks, keyed per date) ---- */
  const sweepKey = 'cf_sweep_' + todayKey();
  const EMPTY_SWEEP = { fitness: 'none', relationships: 'none', environment: 'none', self: 'none', hustle: 'none' };

  window.CFLive = {
    chatUrl: CHAT_URL,
    todayKey,

    loadSweep() { return Object.assign({}, EMPTY_SWEEP, read(sweepKey, {})); },
    saveSweep(s) { write(sweepKey, s); },

    loadTracks(defaults) { return read('cf_tracks', null) || JSON.parse(JSON.stringify(defaults)); },
    saveTracks(t) { write('cf_tracks', t); },

    deckRevealedToday() { return read('cf_deck_' + todayKey(), false); },
    revealDeck(prompt) {
      write('cf_deck_' + todayKey(), true);
      const drawn = read('cf_deck_drawn', []);
      if (!drawn.includes(prompt)) { drawn.push(prompt); write('cf_deck_drawn', drawn); }
    },

    /* chat */
    async fetchMessages(since) {
      const r = await fetch(`${CHAT_URL}?since=${since || 0}`);
      const d = await r.json();
      return d.messages || [];
    },
    async post(who, text) {
      await fetch(CHAT_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ who, text }) });
    },

    /* wins wall */
    loadWins() { return read('cf_wins', []); },
    addWin(text) {
      const wins = read('cf_wins', []);
      wins.unshift({ who: window.CF_ME.name, anchor: window.CF_ME.anchor, text, react: [{ e: '🙌', n: 1 }], time: 'Just now' });
      write('cf_wins', wins);
      return wins;
    },
  };

  /* ---- real-date layer over the demo Rhythm data ---- */
  // Current week's cluster (Mon-Fri) built from stored sweeps; days with no
  // record stay empty, the freedom day rests, today is ringed.
  try {
    const now = new Date();
    const dow = (now.getDay() + 6) % 7; // Mon=0
    const monday = new Date(now); monday.setDate(now.getDate() - dow);
    const cluster = [];
    for (let i = 0; i < 5; i++) {
      const d = new Date(monday); d.setDate(monday.getDate() + i);
      const key = 'cf_sweep_' + d.toISOString().slice(0, 10);
      const s = read(key, null);
      const isToday = d.toDateString() === now.toDateString();
      if (i === 4) { cluster.push({ freedom: true, today: isToday }); continue; }
      const marks = [];
      if (s) for (const a of ['fitness', 'relationships', 'environment', 'self', 'hustle']) {
        if (s[a] === 'min') marks.push({ a });
        else if (s[a] === 'max') marks.push({ a, max: true });
      }
      cluster.push(isToday ? { today: true, marks } : { marks });
    }
    window.CF_RHYTHM.cluster = cluster;

    // deck library reflects real draws on top of the demo baseline
    const drawn = read('cf_deck_drawn', []);
    window.CF_RHYTHM.deckCount = Math.min(window.CF_RHYTHM.deckTotal, 12 + drawn.length);
  } catch (e) { /* demo data stands if anything goes wrong */ }
})();
