// Onkelfinke API-Client
// - lädt Konfig vom Server mit Hardcoded-Fallback
// - sendet Submissions an api.php
// - Admin-Login + CRUD

const API_BASE = (() => {
  // Erlaubt Override per <meta name="of-api" content="https://…/api/api.php">
  const m = document.querySelector('meta[name="of-api"]');
  if (m && m.content) return m.content;
  return 'api/api.php';
})();

async function apiCall(action, body = null, method = null) {
  const url = `${API_BASE}?action=${encodeURIComponent(action)}`;
  const opts = {
    method: method || (body ? 'POST' : 'GET'),
    credentials: 'same-origin',
    headers: { 'Accept': 'application/json' },
  };
  if (body) {
    opts.headers['Content-Type'] = 'application/json';
    opts.body = JSON.stringify(body);
  }
  const r = await fetch(url, opts);
  let json;
  try { json = await r.json(); }
  catch { throw new Error('Server-Antwort nicht lesbar (' + r.status + ')'); }
  if (!r.ok || !json.ok) throw new Error(json && json.error ? json.error : 'API-Fehler ' + r.status);
  return json;
}

// Hardcoded-Fallback (= dist/site/data.jsx Inhalt)
const FALLBACK_CONFIG = {
  anlaesse: window.SITE_DATA_FALLBACK?.ANLAESSE || [],
  bausteine: window.SITE_DATA_FALLBACK?.BAUSTEINE || {},
  anfahrt:   window.SITE_DATA_FALLBACK?.ANFAHRT   || { freikm: 30, proKm: 1.20, zonen: [] },
  timeline_bausteine: window.SITE_DATA_FALLBACK?.TIMELINE_BAUSTEINE || [],
  timeline_vorlagen:  { default: window.SITE_DATA_FALLBACK?.TIMELINE_VORLAGE || [] },
  texte: {},
};

async function loadPublicConfig() {
  try {
    const j = await apiCall('config');
    const c = j.config || {};
    // Felder absichern
    return {
      anlaesse: c.anlaesse || FALLBACK_CONFIG.anlaesse,
      bausteine: c.bausteine || FALLBACK_CONFIG.bausteine,
      anfahrt: c.anfahrt || FALLBACK_CONFIG.anfahrt,
      timeline_bausteine: c.timeline_bausteine || FALLBACK_CONFIG.timeline_bausteine,
      timeline_vorlagen: c.timeline_vorlagen || FALLBACK_CONFIG.timeline_vorlagen,
      texte: c.texte || {},
    };
  } catch (e) {
    console.warn('[Onkelfinke] Konfig-Server nicht erreichbar, nutze Fallback:', e.message);
    return FALLBACK_CONFIG;
  }
}

window.OF_API = {
  call: apiCall,
  loadPublicConfig,
  submit: (data) => apiCall('submit', data),
  // Admin
  login: (password) => apiCall('login', { password }),
  logout: () => apiCall('logout', {}),
  status: () => apiCall('status'),
  adminConfig: () => apiCall('admin_config'),
  saveConfig: (config) => apiCall('save_config', { config }),
  listSubmissions: () => apiCall('list_submissions'),
  updateSubmission: (id, status) => apiCall('update_submission', { id, status }),
  deleteSubmission: (id) => apiCall('delete_submission', { id }),
  changePassword: (oldPw, newPw) => apiCall('change_password', { old: oldPw, new: newPw }),
  listBackups: () => apiCall('list_backups'),
  restoreBackup: (name) => apiCall('restore_backup', { name }),
};
