// admin-data.jsx — Google Sheets-backed data overlay for FENIX UNIFORM.
// Fetches remote data on load, caches to localStorage for 5 minutes, and
// exposes `window.useAdminData(key)` so components re-render when data lands.
// If the endpoint is unset or fetch fails, components fall through to
// hardcoded fallbacks in app.jsx / i18n.jsx — the site never breaks.

(function () {
  const CACHE_KEY = 'fenix-admin-cache-v1';
  const TTL_MS = 5 * 60 * 1000; // 5 minutes

  // Apps Script Web App — same URL that serves doPost for the quote form.
  // GET ?type=all returns { prices, faq, contact } read from the FENIX Admin Sheet.
  const ENDPOINT = 'https://script.google.com/macros/s/AKfycbyDBgqPrHb9JEW9NYM0ZBPr4vKeQ7vvc92_c46KfeZ86WADEDzLQ7b01P1oJpxcJyKn/exec';

  let store = null;
  const listeners = new Set();

  function notify() { listeners.forEach((fn) => fn()); }

  function readCache() {
    try {
      const raw = localStorage.getItem(CACHE_KEY);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (!parsed || (Date.now() - parsed.ts) > TTL_MS) return null;
      return parsed.data;
    } catch (e) { return null; }
  }

  function writeCache(data) {
    try {
      localStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data }));
    } catch (e) { /* quota / privacy mode — ignore */ }
  }

  async function fetchRemote() {
    if (!ENDPOINT || ENDPOINT.startsWith('PLACEHOLDER')) return null;
    try {
      const res = await fetch(`${ENDPOINT}?type=all&t=${Date.now()}`);
      if (!res.ok) throw new Error('http ' + res.status);
      const json = await res.json();
      if (!json || json.error) return null;
      return json;
    } catch (e) {
      // eslint-disable-next-line no-console
      console.warn('[adminData] fetch failed, using fallback:', e.message || e);
      return null;
    }
  }

  async function init() {
    const cached = readCache();
    if (cached) { store = cached; notify(); }
    const fresh = await fetchRemote();
    if (fresh) { store = fresh; writeCache(fresh); notify(); }
  }

  function get(key) {
    if (!store) return null;
    return store[key] != null ? store[key] : null;
  }

  function subscribe(fn) {
    listeners.add(fn);
    return () => listeners.delete(fn);
  }

  window.adminData = {
    init,
    get,
    subscribe,
    refresh: async () => {
      const fresh = await fetchRemote();
      if (fresh) { store = fresh; writeCache(fresh); notify(); }
      return !!fresh;
    },
  };

  // React hook — components use this like `useAdminData('prices')` and
  // get a re-render when the remote data arrives.
  window.useAdminData = function (key) {
    const [, setTick] = React.useState(0);
    React.useEffect(() => subscribe(() => setTick((t) => t + 1)), []);
    return get(key);
  };

  // Kick off the initial load.
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    // Defer so React has a chance to mount and register listeners.
    setTimeout(init, 0);
  }
})();
