// API-backed store — alle Methoden sind async
const API_BASE = (typeof window !== 'undefined' && window.IMMOHUB_API) || '';

const _token = {
  get:   ()  => localStorage.getItem('ih.token'),
  set:   (t) => localStorage.setItem('ih.token', t),
  clear: ()  => localStorage.removeItem('ih.token'),
};

const api = async (method, path, body) => {
  const token = _token.get();
  const res = await fetch(API_BASE + path, {
    method,
    headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: 'Bearer ' + token } : {}) },
    body: body !== undefined ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || 'Serverfehler (' + res.status + ')');
  return data;
};

const Store = {
  hasToken() { return !!_token.get(); },
  async getMe() { try { return await api('GET', '/api/auth/me'); } catch { _token.clear(); return null; } },
  async login(email, pw) { try { const d = await api('POST', '/api/auth/login', { email, pw }); _token.set(d.token); return { session: d.session }; } catch(e) { return { error: e.message }; } },
  async register({ name, email, pw, company }) { try { const d = await api('POST', '/api/auth/register', { name, email, pw, company }); _token.set(d.token); return { session: d.session }; } catch(e) { return { error: e.message }; } },
  async logout() { try { await api('POST', '/api/auth/logout'); } catch {} _token.clear(); },
  async getProperties() { try { return await api('GET', '/api/properties'); } catch { return []; } },
  async addProperty(_orgId, data) { return api('POST', '/api/properties', data); },
  async deleteProperty(propId) { return api('DELETE', '/api/properties/' + propId); },
  async getUsers() { try { return await api('GET', '/api/users'); } catch { return []; } },
  async getPendingInvites() { try { return await api('GET', '/api/invites/pending'); } catch { return []; } },
  async createInvite(data) { return api('POST', '/api/invites', data); },
  async getInvite(code) { try { return await api('GET', '/api/invites/' + code); } catch { return null; } },
  async acceptInvite(code, { name, pw }) { try { const d = await api('POST', '/api/invites/' + code + '/accept', { name, pw }); _token.set(d.token); return { session: d.session }; } catch(e) { return { error: e.message }; } },
  async getTickets() { try { return await api('GET', '/api/tickets'); } catch { return []; } },
  async createTicket(data) { return api('POST', '/api/tickets', data); },
  async updateTicket(id, data) { return api('PATCH', '/api/tickets/' + id, data); },
  async deleteTicket(id) { return api('DELETE', '/api/tickets/' + id); },

  async getUnits(propId) { try { return await api('GET', `/api/properties/${propId}/units`); } catch { return []; } },
  async createUnit(propId, data) { return api('POST', `/api/properties/${propId}/units`, data); },
  async updateUnit(id, data) { return api('PATCH', '/api/units/' + id, data); },
  async deleteUnit(id) { return api('DELETE', '/api/units/' + id); },

  async getMaintenance(propId) { try { const q = propId ? `?propId=${propId}` : ''; return await api('GET', '/api/maintenance' + q); } catch { return []; } },
  async createMaintenance(data) { return api('POST', '/api/maintenance', data); },
  async updateMaintenance(id, data) { return api('PATCH', '/api/maintenance/' + id, data); },
  async deleteMaintenance(id) { return api('DELETE', '/api/maintenance/' + id); },

  async getNews(propId) { try { const q = propId ? `?propId=${propId}` : ''; return await api('GET', '/api/news' + q); } catch { return []; } },
  async createNews(data) { return api('POST', '/api/news', data); },
  async deleteNews(id) { return api('DELETE', '/api/news/' + id); },

  async getDocuments(propId) { try { const q = propId ? `?propId=${propId}` : ''; return await api('GET', '/api/documents' + q); } catch { return []; } },
  async createDocument(data) { return api('POST', '/api/documents', data); },
  async deleteDocument(id) { return api('DELETE', '/api/documents/' + id); },
};

Object.assign(window, { Store });
