import api from './api.js';

// Site settings + header/footer menus change rarely (an admin editing the CMS) but are needed
// on every single page render. Without caching, every request — including static-feeling pages —
// makes a synchronous round trip to the backend before it can even start rendering. A short TTL
// cache keeps pages fast under load while still picking up CMS edits within a few seconds.
const TTL_MS = 60 * 1000;

let cache = null; // { data, fetchedAt }
let inFlight = null; // dedupes concurrent refreshes so a traffic spike doesn't fan out N requests

const fetchLayout = async () => {
  const { data } = await api.get('/public/layout');
  return {
    settings: data.settings || {},
    headerMenus: data.headerMenus || [],
    footerMenus: data.footerMenus || []
  };
};

export const getLayoutData = async () => {
  const isFresh = cache && Date.now() - cache.fetchedAt < TTL_MS;
  if (isFresh) return cache.data;

  if (!inFlight) {
    inFlight = fetchLayout()
      .then((data) => {
        cache = { data, fetchedAt: Date.now() };
        return data;
      })
      .catch((err) => {
        console.error('Failed to load layout data from API:', err.message);
        // Serve stale data rather than an empty header/footer if the backend hiccups.
        if (cache) return cache.data;
        return { settings: {}, headerMenus: [], footerMenus: [] };
      })
      .finally(() => {
        inFlight = null;
      });
  }

  return inFlight;
};
