/* LocalStorage helpers for recordings */
const STORAGE_KEY = "medictation.recordings.v1";

const Store = {
  load() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return [];
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed : [];
    } catch { return []; }
  },
  save(list) {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(list)); } catch {}
  },
  add(rec) {
    const list = Store.load();
    list.unshift(rec);
    Store.save(list);
    return rec;
  },
  update(id, patch) {
    const list = Store.load();
    const i = list.findIndex(r => r.id === id);
    if (i >= 0) {
      list[i] = { ...list[i], ...patch, updatedAt: Date.now() };
      Store.save(list);
      return list[i];
    }
    return null;
  },
  remove(id) {
    const list = Store.load().filter(r => r.id !== id);
    Store.save(list);
  },
  get(id) {
    return Store.load().find(r => r.id === id);
  },
};

const fmtDate = (ts) => {
  const d = new Date(ts);
  const months = ["Jan.","Feb.","März","Apr.","Mai","Juni","Juli","Aug.","Sept.","Okt.","Nov.","Dez."];
  const today = new Date();
  const sameDay = d.toDateString() === today.toDateString();
  const yest = new Date(); yest.setDate(yest.getDate() - 1);
  const sameYest = d.toDateString() === yest.toDateString();
  const hh = String(d.getHours()).padStart(2, "0");
  const mm = String(d.getMinutes()).padStart(2, "0");
  if (sameDay) return `Heute, ${hh}:${mm}`;
  if (sameYest) return `Gestern, ${hh}:${mm}`;
  return `${d.getDate()}. ${months[d.getMonth()]} ${d.getFullYear()}, ${hh}:${mm}`;
};

const fmtDuration = (sec) => {
  const m = Math.floor(sec / 60);
  const s = Math.floor(sec % 60);
  return `${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
};

const uid = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);

window.Store = Store;
window.fmtDate = fmtDate;
window.fmtDuration = fmtDuration;
window.uid = uid;
