// Reactive history, shared across the home feed (which RECORDS opens/replaces)
// and the account page (which DISPLAYS + manages). Device-local always; synced to
// the account when signed in. Only deliberate events live here — opened or
// replaced-away articles — never everything merely shown.
import { auth } from './auth.svelte.js';
import { getJSON, delJSON } from './api.js';

const KEY = 'goodnews:history';
const CAP = 200;

function load() {
  try {
    const v = JSON.parse(localStorage.getItem(KEY));
    return Array.isArray(v) ? v : [];
  } catch {
    return [];
  }
}
function save(arr) {
  try {
    localStorage.setItem(KEY, JSON.stringify(arr.slice(0, CAP)));
  } catch {
    /* private mode / quota */
  }
}

export const history = $state({ device: [], server: [], ready: false });

export function initHistory() {
  if (history.ready) return;
  history.device = load();
  history.ready = true;
}

export function deviceIds() {
  return history.device.map((a) => a.id);
}

export function record(article) {
  if (!article) return;
  if (!history.device.some((h) => h.id === article.id)) {
    history.device = [article, ...history.device].slice(0, CAP);
    save(history.device);
  }
  if (auth.user) {
    if (!history.server.some((h) => h.id === article.id)) {
      history.server = [article, ...history.server];
    }
    // keepalive: this often fires on a click that navigates to /a, so it must
    // survive the page transition.
    fetch('/api/history', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ids: [article.id] }),
      credentials: 'same-origin',
      keepalive: true,
    }).catch(() => {});
  }
}

export function removeOne(id) {
  history.device = history.device.filter((h) => h.id !== id);
  history.server = history.server.filter((h) => h.id !== id);
  save(history.device);
  if (auth.user) delJSON(`/api/history/${id}`).catch(() => {});
}

export function clearAll() {
  history.device = [];
  history.server = [];
  save([]);
  if (auth.user) delJSON('/api/history').catch(() => {});
}

export async function loadServerHistory() {
  if (!auth.user) {
    history.server = [];
    return;
  }
  try {
    history.server = (await getJSON('/api/history')).items;
  } catch {
    /* leave as-is */
  }
}
