// 1. Declare the global object used throughout the project
window.popstore = {};

// 2. Set your public project token (get it from admin.popstore.com.br)
popstore.token = 'pk_abc123';

// 3. Load your project config from the Popstore API
popstore.config = await (await fetch('https://api.popstore.com.br/v1/config', {
  headers: { Authorization: 'Bearer ' + popstore.token }
})).json();

// 4. Define dynamic import functions using auto versioning (for cache busting)
popstore.load = async (path) => import(path + '?v=' + popstore.config.version);
popstore.loadCDN = async (path) => import('https://cdn.popstore.com.br' + path + '?v=' + popstore.config.versionCDN);

// 5. Define your custom router to dynamically load local page modules
popstore.route = async function (path = location.pathname) {
  popstore.loading();
  const page = await popstore.router(path);
  try {
    const module = await popstore.load('/js/' + page + '.page.js');
    await module.render();
  } catch {
    const fallback = await popstore.load('/js/home.page.js');
    await fallback.render();
  }
};

// 6. Define your auth method for protected routes
popstore.auth = function (token_name = 'token') {
  const token = localStorage.getItem(token_name);
  if (!token) {
    popstore.route('login');
    return false;
  }
  return true;
};

// 7. Load the core Popstore framework from CDN (session, geo, listeners, etc)
await popstore.loadCDN('/main.js');
await popstore.init(); 

// 8. Load your base layout shell
await popstore.load('/js/layout.js');

// 9. Load the initial page based on current URL
await popstore.route();

// 10. Load optional modules (WebSocket, GPT, notifications) after login
if (popstore.auth()) {
  const ws = await popstore.loadCDN('/ws.js');
  popstore.ws = ws.default;

  const gpt = await popstore.loadCDN('/gpt.js');
  gpt.render();

  popstore.ws.emit('ping', { teste: true });
  popstore.ws.on('pong', (payload) => console.log('Pong received:', payload));

  const PopNotifications = await popstore.loadCDN('/notifications.js');
  PopNotifications.render('pop-notifications-placeholder');
}