import { pagesConfig } from '../services/pagesConfig.js';
import { icons } from '../services/icons.js';

const modules = import.meta.glob('./*Page.js', { eager: true });
const knownFiles = new Set(pagesConfig.map(p => p._file).filter(Boolean));

function toRoute(path) {
  return path.replace('./', '').replace('Page.js', '')
    .replace(/([A-Z])/g, (c, l, i) => (i ? '-' : '') + l.toLowerCase());
}

function toName(path) {
  return path.replace('./', '').replace('Page.js', '')
    .replace(/([A-Z])/g, (c, l, i) => (i ? ' ' : '') + l).trim();
}

const autoPages = Object.entries(modules)
  .filter(([path]) => {
    const file = path.replace('./', '').replace('.js', '');
    return !knownFiles.has(file);
  })
  .map(([path, mod]) => {
    const render = mod.render ?? mod.default
      ?? Object.values(mod).find(v => typeof v === 'function')
      ?? (() => document.createElement('div'));
    return {
      route:         mod.route         ?? toRoute(path),
      name:          mod.name          ?? toName(path),
      order:         mod.order         ?? 99,
      icon:          mod.icon          ?? icons.dashboard,
      voicePatterns: mod.voicePatterns ?? [],
      requiresAuth:  mod.requiresAuth  ?? true,
      showInSidebar: mod.showInSidebar ?? true,
      render,
    };
  });

export const pagesRegistry = [...pagesConfig, ...autoPages]
  .sort((a, b) => (a.order ?? 99) - (b.order ?? 99));

export function getAvailablePages(isAuthenticated) {
  if (!isAuthenticated) return [];
  return pagesRegistry.filter(p => p.showInSidebar && (!p.requiresAuth || isAuthenticated));
}

export function getPageByRoute(route) {
  return pagesRegistry.find(p => p.route === route);
}
