/*
  STORAGE — resume points, kept in localStorage (survives restarts, no size
  worries like cookies, no per-request overhead).

  A "record" looks like:
    {
      key:      "m:603" | "t:1396:s1:e2",
      type:     "movie" | "tv",
      tmdbId:   1396,
      season:   1,          // tv only
      episode:  2,          // tv only
      show:     "Show name",
      title:    "Episode name", // tv only
      poster:   "https://…/w342/…",
      t:        934.2,      // seconds played
      d:        2710.5,     // duration seconds
      at:       1712345678901,
      provider: "cineby"
    }

  One record per (movie) or (show, season, episode). The home page collapses
  to the most recent record per show.
*/
(function () {
  'use strict';

  const KEY = 'streamreverse.resume.v1';
  const MAX_RECORDS = 200;

  function readAll() {
    try {
      const parsed = JSON.parse(localStorage.getItem(KEY) || '{}');
      return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
    } catch (e) {
      return {};
    }
  }

  function writeAll(all) {
    try {
      localStorage.setItem(KEY, JSON.stringify(all));
    } catch (e) {
      /* storage full/blocked — resume just won't persist */
    }
  }

  function keyFor({ type, tmdbId, season, episode }) {
    return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
  }

  function get(key) {
    return readAll()[key] || null;
  }

  function save(record) {
    const all = readAll();
    all[record.key] = record;
    const keys = Object.keys(all).sort((a, b) => (all[a].at || 0) - (all[b].at || 0));
    while (keys.length > MAX_RECORDS) delete all[keys.shift()];
    writeAll(all);
  }

  function remove(key) {
    const all = readAll();
    if (all[key]) {
      delete all[key];
      writeAll(all);
    }
  }

  function clear() {
    writeAll({});
  }

  function list() {
    return Object.values(readAll());
  }

  // one entry per movie/show: the most recently watched record wins
  function latestPerShow() {
    const byShow = new Map();
    for (const rec of list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
      const showKey = rec.type === 'tv' ? `t:${rec.tmdbId}` : `m:${rec.tmdbId}`;
      byShow.set(showKey, rec);
    }
    return [...byShow.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
  }

  window.SR = window.SR || {};
  SR.storage = { KEY, keyFor, get, save, remove, clear, list, latestPerShow };
})();
