// LSMD — API & Site-Konfiguration
window.LSMD = {
  site: null,
  user: null,
  permissions: [],

  async loadSite() {
    try {
      const r = await fetch('/api/site', { credentials: 'same-origin' });
      if (!r.ok) throw new Error('site ' + r.status);
      this.site = await r.json();
      window.__LSMD_SITE__ = this.site;
      if (this.site.user) this.user = this.site.user;
      const fav = this.site.logoUrl || '/img/lsmd-logo.png';
      document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]').forEach((el) => {
        el.href = fav;
      });
      return this.site;
    } catch (e) {
      console.error('[LSMD] loadSite', e);
      this.site = { logoUrl: '/img/lsmd-logo.png', stats: {}, team: [] };
      window.__LSMD_SITE__ = this.site;
      return this.site;
    }
  },

  async loadMe() {
    try {
      const r = await fetch('/api/me', { credentials: 'same-origin', redirect: 'manual' });
      if (r.status === 401 || r.type === 'opaqueredirect' || r.status === 302) {
        this.user = null;
        this.permissions = [];
        return null;
      }
      if (!r.ok) throw new Error('me ' + r.status);
      const data = await r.json();
      this.user = data.user;
      this.permissions = data.permissions || [];
      return data;
    } catch (e) {
      console.error('[LSMD] loadMe', e);
      this.user = null;
      this.permissions = [];
      return null;
    }
  },

  hasPerm(key) {
    if (this.user?.platform_role === 'admin') return true;
    return (this.permissions || []).includes(key);
  },

  logoUrl() {
    return this.site?.logoUrl || '/img/lsmd-logo.png';
  },

  sortStaffByDienstnummer(staff) {
    const key = (m) => {
      if (m?.employee_number) {
        const parts = String(m.employee_number).match(/\d+/g);
        if (parts?.length) return parseInt(parts[parts.length - 1], 10);
      }
      for (const raw of [m?.display_name, m?.ic_name, m?.name, m?.dn]) {
        if (!raw) continue;
        const b = String(raw).match(/^\s*\[(\d+)\]/);
        if (b) return parseInt(b[1], 10);
      }
      return null;
    };
    return [...(staff || [])].sort((a, b) => {
      const na = key(a);
      const nb = key(b);
      const aMiss = na === null;
      const bMiss = nb === null;
      if (aMiss !== bMiss) return aMiss ? 1 : -1;
      if (!aMiss && na !== nb) return na - nb;
      return (a.name || '').localeCompare(b.name || '', 'de');
    });
  },

  async loadStaff(q = '') {
    const r = await fetch('/api/staff?' + new URLSearchParams(q ? { q } : {}), { credentials: 'same-origin' });
    if (r.status === 401 || r.status === 403) return { staff: [], total: 0 };
    if (!r.ok) throw new Error('staff ' + r.status);
    const data = await r.json();
    data.staff = this.sortStaffByDienstnummer(data.staff);
    return data;
  },

  async loadStaffMember(userId) {
    const r = await fetch(`/api/staff/${userId}`, { credentials: 'same-origin' });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Mitarbeiter laden fehlgeschlagen');
    return data;
  },

  async updateStaffMember(userId, body) {
    const r = await fetch(`/api/staff/${userId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Speichern fehlgeschlagen');
    return data;
  },

  async loadDepartmentsFull() {
    const r = await fetch('/api/departments?full=1', { credentials: 'same-origin' });
    if (!r.ok) return { departments: [] };
    return r.json();
  },

  async loadLogbook(type = 'ALLE') {
    const q = type && type !== 'ALLE' ? `?type=${encodeURIComponent(type)}` : '';
    const r = await fetch('/api/logbook' + q, { credentials: 'same-origin' });
    if (r.status === 401 || r.status === 403) return { entries: [], types: [] };
    if (!r.ok) throw new Error('logbook ' + r.status);
    return r.json();
  },

  async loadDiscordAdmin() {
    const r = await fetch('/api/admin/discord', { credentials: 'same-origin' });
    if (!r.ok) throw new Error('discord admin ' + r.status);
    return r.json();
  },

  async saveDiscordModules(modules) {
    const r = await fetch('/api/admin/discord-modules', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ modules }),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Speichern fehlgeschlagen');
    return data;
  },

  async syncMembers() {
    const r = await fetch('/api/admin/sync-members', { method: 'POST', credentials: 'same-origin' });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Sync fehlgeschlagen');
    return data;
  },

  async loadPatients(q = '') {
    const r = await fetch('/api/patients?' + new URLSearchParams(q ? { q } : {}), { credentials: 'same-origin' });
    if (r.status === 401 || r.status === 403) return { patients: [], total: 0 };
    if (!r.ok) throw new Error('patients ' + r.status);
    return r.json();
  },

  async loadPatient(dbId) {
    const r = await fetch(`/api/patients/${dbId}`, { credentials: 'same-origin' });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'patient ' + r.status);
    return data;
  },

  async createPatient(body) {
    const r = await fetch('/api/patients', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'create patient');
    return data;
  },

  async updatePatient(dbId, body) {
    const r = await fetch(`/api/patients/${dbId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'update patient');
    return data;
  },

  async deletePatient(dbId) {
    const r = await fetch(`/api/patients/${dbId}`, { method: 'DELETE', credentials: 'same-origin' });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'delete patient');
    return data;
  },

  async addPatientEntry(dbId, body) {
    const r = await fetch(`/api/patients/${dbId}/entries`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'add entry');
    return data;
  },

  async uploadPatientPhoto(dbId, photoBase64) {
    const r = await fetch(`/api/patients/${dbId}/photo`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ photo_base64: photoBase64 }),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'Foto speichern fehlgeschlagen');
    return data;
  },

  async deletePatientEntry(dbId, entryId) {
    const r = await fetch(`/api/patients/${dbId}/entries/${entryId}`, {
      method: 'DELETE',
      credentials: 'same-origin',
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'delete entry');
    return data;
  },

  async loadDepartments() {
    const r = await fetch('/api/departments', { credentials: 'same-origin' });
    if (!r.ok) return { departments: ['Rettungsdienst', 'Notaufnahme', 'Chirurgie', 'Verwaltung'] };
    return r.json();
  },

  async submitBewerbung(payload) {
    const r = await fetch('/api/bewerbung', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(payload),
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'Fehler beim Senden');
    return data;
  },

  async loadInsurance(q = '') {
    const r = await fetch('/api/insurance?' + new URLSearchParams(q ? { q } : {}), { credentials: 'same-origin' });
    if (!r.ok) throw new Error('insurance');
    return r.json();
  },

  async loadInsurance(id) {
    const r = await fetch(`/api/insurance/${id}`, { credentials: 'same-origin' });
    const d = await r.json();
    if (!r.ok) throw new Error(d.error || 'insurance');
    return d;
  },

  async createInsurance(body) {
    const r = await fetch('/api/insurance', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const d = await r.json();
    if (!r.ok) throw new Error(d.error || 'create');
    return d;
  },

  async addInsuranceMember(id, body) {
    const r = await fetch(`/api/insurance/${id}/members`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body),
    });
    const d = await r.json();
    if (!r.ok) throw new Error(d.error || 'member');
    return d;
  },

  async loadAdminOverview() {
    const r = await fetch('/api/admin/overview', { credentials: 'same-origin' });
    const d = await r.json();
    if (!r.ok) throw new Error(d.error || 'admin');
    return d;
  },

  async submitBeschwerde(payload) {
    const r = await fetch('/api/beschwerde', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(payload),
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(data.error || 'Fehler beim Senden');
    return data;
  },
};
