/* API client — bridges browser localStorage ↔ Express/SQLite backend.
 *
 * Strategy:
 *   READ  → always from localStorage (instant, no flash)
 *   WRITE → localStorage first (instant UI), then server in background
 *   SYNC  → on every page load, fetch server data and refresh localStorage
 *            so changes from admin appear on the main site and vice-versa.
 */

const ALZ_API = {

  /* ── Sync server → localStorage on page load ── */
  async sync() {
    try {
      const res = await fetch('/api/all');
      if (!res.ok) return;
      const { cars, media, content } = await res.json();

      if (Array.isArray(cars)) {
        try { localStorage.setItem('alz_cars_v1', JSON.stringify(cars)); } catch {}
        window.dispatchEvent(new CustomEvent('alz-cars-updated', { detail: cars }));
      }
      if (media && typeof media === 'object') {
        try { localStorage.setItem('alz_media_v1', JSON.stringify(media)); } catch {}
        window.dispatchEvent(new CustomEvent('alz-media-updated', { detail: media }));
      }
      if (content) {
        if (content.phone)    try { localStorage.setItem('alz_phone',    content.phone);    } catch {}
        if (content.whatsapp) try { localStorage.setItem('alz_whatsapp', content.whatsapp); } catch {}
      }
    } catch {
      /* Server not reachable — site still works from localStorage cache */
    }
  },

  /* ── Persist cars to server ── */
  async saveCars(cars) {
    try {
      await fetch('/api/cars', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(cars),
      });
    } catch (e) {
      console.warn('[ALZ] saveCars failed:', e.message);
    }
  },

  /* ── Persist media to server ── */
  async saveMedia(media) {
    try {
      await fetch('/api/media', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(media),
      });
    } catch (e) {
      console.warn('[ALZ] saveMedia failed:', e.message);
    }
  },

  /* ── Persist contact info to server ── */
  async saveContent(phone, whatsapp) {
    try {
      await fetch('/api/content', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, whatsapp }),
      });
    } catch (e) {
      console.warn('[ALZ] saveContent failed:', e.message);
    }
  },
};

window.ALZ_API = ALZ_API;

// Kick off background sync immediately when script loads
ALZ_API.sync();
