// router.jsx — Roteamento centralizado baseado em URL

// Páginas acessíveis por usuário normal
const USER_PAGES = ['dashboard', 'sync', 'logs', 'billing', 'settings', 'notifications', 'onboarding'];

// Páginas acessíveis no contexto de impersonação de tenant pelo admin
const ADMIN_TENANT_PAGES = ['dashboard', 'sync', 'logs', 'billing', 'settings', 'notifications'];

// Metadados de rota → breadcrumbs
const ROUTE_META = {
  '/':                     { crumbs: [] },
  '/dashboard':            { crumbs: ['Dashboard'] },
  '/sync':                 { crumbs: ['Sincronizações'] },
  '/logs':                 { crumbs: ['Logs de execução'] },
  '/billing':              { crumbs: ['Plano & cobrança'] },
  '/settings':             { crumbs: ['Conexões'] },
  '/notifications':        { crumbs: ['Central de notificações'] },
  '/onboarding':           { crumbs: ['Configuração inicial'] },
  '/admin':                { crumbs: ['Plataforma', 'Visão geral'] },
  '/admin/tenants':        { crumbs: ['Plataforma', 'Tenants'] },
  '/admin/plans':          { crumbs: ['Plataforma', 'Planos'] },
  '/admin/coupons':        { crumbs: ['Plataforma', 'Cupons'] },
  '/admin/notifications':  { crumbs: ['Plataforma', 'Notificações'] },
  '/admin/invite-links':   { crumbs: ['Plataforma', 'Links de convite'] },
  '/admin/popups':         { crumbs: ['Plataforma', 'Popups'] },
};

// Labels das páginas de tenant (para breadcrumbs na impersonação)
const ADMIN_PAGE_LABELS = {
  dashboard:     'Dashboard',
  sync:          'Sincronizações',
  logs:          'Logs de execução',
  billing:       'Plano & cobrança',
  settings:      'Conexões',
  notifications: 'Central de notificações',
};

// ── parsePathname ─────────────────────────────────────────────────────────────
// Retorna um objeto routeInfo com type, page, path, valid e (para admin-tenant) tenantId
function parsePathname(pathname) {
  const path = (!pathname || pathname === '')
    ? '/'
    : (pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname);

  // /admin/tenant/:tenantId[/:page]
  const tenantMatch = path.match(/^\/admin\/tenant\/([^\/]+)(?:\/([^\/]+))?$/);
  if (tenantMatch) {
    const tenantId = tenantMatch[1];
    const page     = tenantMatch[2] || 'dashboard';
    return {
      type:     'admin-tenant',
      tenantId,
      page,
      path,
      valid: ADMIN_TENANT_PAGES.includes(page),
    };
  }

  // Rotas de admin puro
  if (path === '/admin')                return { type: 'admin', page: 'overview',      path, valid: true };
  if (path === '/admin/tenants')        return { type: 'admin', page: 'tenants',       path, valid: true };
  if (path === '/admin/plans')          return { type: 'admin', page: 'plans',         path, valid: true };
  if (path === '/admin/coupons')        return { type: 'admin', page: 'coupons',       path, valid: true };
  if (path === '/admin/notifications')  return { type: 'admin', page: 'notifications', path, valid: true };
  if (path === '/admin/invite-links')   return { type: 'admin', page: 'invite-links',  path, valid: true };
  if (path === '/admin/popups')         return { type: 'admin', page: 'popups',        path, valid: true };

  // Raiz
  if (path === '/') return { type: 'root', page: 'root', path, valid: true };

  // Rotas de usuário normal
  const pageSlug = path.startsWith('/') ? path.slice(1) : path;
  if (USER_PAGES.includes(pageSlug)) {
    return { type: 'user', page: pageSlug, path, valid: true };
  }

  return { type: 'notfound', page: 'notfound', path, valid: false };
}

// ── parseQuery ────────────────────────────────────────────────────────────────
function parseQuery(search) {
  const params = new URLSearchParams(search || '');
  const result = {};
  for (const [k, v] of params.entries()) result[k] = v;
  return result;
}

// ── buildPath ─────────────────────────────────────────────────────────────────
// Monta URL a partir de pathname + query object (filtra vazios)
function buildPath(pathname, query) {
  if (!query) return pathname;
  const entries = Object.entries(query).filter(([, v]) => v !== undefined && v !== null && v !== '');
  if (entries.length === 0) return pathname;
  return `${pathname}?${new URLSearchParams(entries).toString()}`;
}

// ── navigate ──────────────────────────────────────────────────────────────────
// Troca de página: pushState + dispara re-render via popstate
function navigate(pathname, query) {
  history.pushState(null, '', buildPath(pathname, query || {}));
  window.dispatchEvent(new PopStateEvent('popstate'));
}

// ── replace ───────────────────────────────────────────────────────────────────
// Atualiza URL silenciosamente (sem re-render — para sincronizar filtros dentro de uma página)
function replace(pathname, query) {
  history.replaceState(null, '', buildPath(pathname, query || {}));
}

// ── adminTenantPath ───────────────────────────────────────────────────────────
// Monta caminho de impersonação: /admin/tenant/:id/:page[?query]
function adminTenantPath(tenantId, page, query) {
  return buildPath(`/admin/tenant/${tenantId}/${page || 'dashboard'}`, query || {});
}

const Router = {
  ROUTE_META,
  ADMIN_PAGE_LABELS,
  USER_PAGES,
  ADMIN_TENANT_PAGES,
  parsePathname,
  parseQuery,
  buildPath,
  navigate,
  replace,
  adminTenantPath,
};

Object.assign(window, { Router });
