// Tiny localStorage-backed store for admin-created content.
// NOTE: this is a client-side prototype — no real security, no server sync.
const STORAGE_KEY = 'umbmpc_content_v1';
const AUTH_KEY = 'umbmpc_auth_v1';

// Seeded "accounts" — prototype only. Passwords live in-page; anyone can read them.
// Swap for a real backend before you ship.
const ACCOUNTS = {
  admin: { password: 'umb-admin-2026', role: 'admin', name: 'Mia (Admin)' },
  board: { password: 'board-2026',     role: 'board', name: 'Board Member' },
};

function loadContent() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { events: [], posts: [] };
    const parsed = JSON.parse(raw);
    return { events: parsed.events || [], posts: parsed.posts || [] };
  } catch {
    return { events: [], posts: [] };
  }
}
function saveContent(data) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}

function loadAuth() {
  try {
    const raw = localStorage.getItem(AUTH_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch { return null; }
}
function saveAuth(session) {
  if (session) localStorage.setItem(AUTH_KEY, JSON.stringify(session));
  else localStorage.removeItem(AUTH_KEY);
}

// Simple event bus so components react to updates.
const listeners = new Set();
function notify() { listeners.forEach(fn => fn()); }

const Store = {
  ACCOUNTS,
  get content() { return loadContent(); },
  get session() { return loadAuth(); },
  subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },

  login(username, password) {
    const u = (username || '').trim().toLowerCase();
    const acc = ACCOUNTS[u];
    if (!acc || acc.password !== password) return { ok: false, error: 'Wrong username or password.' };
    const session = { username: u, role: acc.role, name: acc.name, at: Date.now() };
    saveAuth(session);
    notify();
    return { ok: true, session };
  },
  logout() { saveAuth(null); notify(); },

  addEvent(evt) {
    const data = loadContent();
    data.events.unshift({ ...evt, id: 'ev_' + Date.now(), custom: true });
    saveContent(data);
    notify();
  },
  removeEvent(id) {
    const data = loadContent();
    data.events = data.events.filter(e => e.id !== id);
    saveContent(data);
    notify();
  },
  addPost(post) {
    const data = loadContent();
    data.posts.unshift({ ...post, id: 'po_' + Date.now(), custom: true });
    saveContent(data);
    notify();
  },
  removePost(id) {
    const data = loadContent();
    data.posts = data.posts.filter(p => p.id !== id);
    saveContent(data);
    notify();
  },
  clearAll() {
    saveContent({ events: [], posts: [] });
    notify();
  },
};

function useStoreSlice(selector) {
  const [val, setVal] = React.useState(selector());
  React.useEffect(() => Store.subscribe(() => setVal(selector())), []);
  return val;
}

window.Store = Store;
window.useStoreSlice = useStoreSlice;
