// Centralized route registry — single source of truth for every page on the site.
// Pages read SEO + nav from here. Endpoint routes are derived from endpoint data,
// so adding/removing endpoints flows through automatically.
//
// Route shape: { path, file, title, description, type, group? }
//   type: 'home' | 'docs-hub' | 'docs-static' | 'endpoint' | 'group-hub'
//       | 'use-cases-hub' | 'use-case' | 'pricing' | 'dashboard' | 'sitemap'

const STATIC_ROUTES = [
  { path:'/',                 file:'index.html',                          title:'MomentIQ — Video, Audio & Timeline APIs for AI media apps',                description:'AI-ready video, audio, and timeline APIs. One key. Usage-only pricing. Find the moments that matter — frames, laughter, speakers, silence, cuts, clips.', type:'home' },

  { path:'/docs',             file:'docs.html',                           title:'MomentIQ Docs — API reference, quickstart, and SDKs',                       description:'Reference docs for every MomentIQ video, audio, and timeline API. Quickstart, authentication, errors, async jobs, common workflows.', type:'docs-hub' },
  { path:'/docs/quickstart',  file:'docs-quickstart.html',                title:'Quickstart — your first MomentIQ API call in under 60 seconds',             description:'Run your first MomentIQ call in cURL, JavaScript, or Python. Includes best-frames, detect-laughter, chained-endpoint, and async-job examples.', type:'docs-static' },
  { path:'/docs/authentication', file:'docs-authentication.html',         title:'Authentication — using your MomentIQ API key',                              description:'Bearer auth, key rotation, test vs live keys, spending caps, usage logs. Same key works on every endpoint.', type:'docs-static' },
  { path:'/docs/errors',      file:'docs-errors.html',                    title:'Errors — standard error envelope and reference codes',                      description:'MomentIQ error envelope, HTTP status codes, and the full list of error codes including invalid_media_url, insufficient_credits, and processing_timeout.', type:'docs-static' },
  { path:'/docs/async-jobs',  file:'docs-async-jobs.html',                title:'Async jobs — process long media without timeouts',                          description:'POST /v1/jobs and GET /v1/jobs/{job_id}. Pending, completed, and failed responses. Webhooks. For media longer than 5 minutes.', type:'docs-static' },

  { path:'/use-cases',        file:'use-cases.html',                      title:'Use cases — what to build with MomentIQ',                                   description:'Podcast clipping, AI meeting memory, lecture study tools, field documentation, creator thumbnails, AI summarizers, media search, call analysis.', type:'use-cases-hub' },
  { path:'/use-cases/podcast-clipping',     file:'use-case-podcast-clipping.html',     title:'Podcast clipping — auto-cut shareable clips with MomentIQ',          description:'Detect laughter, find natural cut points, render clips. Endpoint chain, sample request flow, pricing example.',                              type:'use-case' },
  { path:'/use-cases/ai-meeting-memory',    file:'use-case-ai-meeting-memory.html',    title:'AI meeting memory — speaker-aware recall with MomentIQ',             description:'Diarize speakers, chunk by topic, merge into a queryable timeline. Endpoint chain, sample flow, pricing example.',                          type:'use-case' },
  { path:'/use-cases/lecture-study-tools',  file:'use-case-lecture-study-tools.html',  title:'Lecture study tools — slide-aware notes from any video',            description:'Pull slide frames with OCR, chunk by topic, build a study index. Endpoint chain, sample flow, pricing example.',                            type:'use-case' },
  { path:'/use-cases/field-documentation',  file:'use-case-field-documentation.html',  title:'Field documentation — turn site walks into searchable records',     description:'Detect cuts, score frames, isolate speech. Endpoint chain, sample flow, pricing example.',                                                  type:'use-case' },

  { path:'/pricing',          file:'pricing.html',                        title:'Pricing — usage-only, per-minute, no monthly fee',                          description:'Pay only for media you process. Per-minute pricing for every endpoint. $20 free credits. Hard spending caps and usage alerts.', type:'pricing' },

  { path:'/dashboard',                       file:'dashboard.html',                       title:'Dashboard — MomentIQ',                                  description:'Recent jobs, usage, estimated monthly spend, errors.', type:'dashboard' },
  { path:'/dashboard/api-keys',              file:'dashboard-api-keys.html',              title:'API keys — MomentIQ Dashboard',                          description:'Manage API keys. Rotate, revoke, scope.',             type:'dashboard' },
  { path:'/dashboard/usage',                 file:'dashboard-usage.html',                 title:'Usage — MomentIQ Dashboard',                             description:'Usage by endpoint. Estimated monthly spend.',         type:'dashboard' },
  { path:'/dashboard/jobs',                  file:'dashboard-jobs.html',                  title:'Jobs — MomentIQ Dashboard',                              description:'Queued, processing, completed, and failed jobs. Retry and cancel.', type:'dashboard' },
  { path:'/dashboard/billing',               file:'dashboard-billing.html',               title:'Billing — MomentIQ Dashboard',                           description:'Billing history. Spending cap. Invoices.',            type:'dashboard' },
  { path:'/dashboard/settings',              file:'dashboard-settings.html',              title:'Settings — MomentIQ Dashboard',                          description:'Org profile, webhook URL, default quality, alerts.',  type:'dashboard' },
  { path:'/dashboard/playground-history',    file:'dashboard-playground-history.html',    title:'Playground history — MomentIQ Dashboard',                description:'Replay every Playground request. Copy as code.',      type:'dashboard' },

  { path:'/sitemap',          file:'sitemap.html',                        title:'Sitemap — MomentIQ',                                                       description:'All MomentIQ pages.',                                                                                                                                                                                                       type:'sitemap' },
];

// Endpoint routes — derived from endpoint data, never hand-maintained.
const endpointRoutes = () =>
  (window.endpointIds ? window.endpointIds() : []).map(id => ({
    path:        '/docs/' + id,
    file:        window.docsHrefFor(id),
    title:       window.seoTitle(id),
    description: window.seoDescription(id),
    type:        'endpoint',
    group:       window.ENDPOINTS[id].group,
    endpointId:  id,
  }));

// Group hubs (e.g. /docs/video) — derived from GROUPS.
const groupRoutes = () =>
  Object.values(window.GROUPS || {}).map(g => ({
    path:        '/docs/' + g.id,
    file:        'docs.html#' + g.id,
    title:       g.name + ' API — MomentIQ',
    description: g.desc,
    type:        'group-hub',
    group:       g.id,
  }));

const allRoutes      = () => [...STATIC_ROUTES, ...groupRoutes(), ...endpointRoutes()];
const routeByFile    = (file) => allRoutes().find(r => r.file === file);
const routeByPath    = (path) => allRoutes().find(r => r.path === path);

// Apply <title> + <meta description> from a route. Pages opt in by calling:
//   applyRouteMeta('docs-quickstart.html');
// or rely on EndpointPage which uses ep.seoTitle / ep.seoDescription directly.
//
// Also: drive analytics from the same call. Every page already invokes
// applyRouteMeta on mount, so this is how we centrally get page_view + safe
// metadata into PostHog without editing 40+ HTML files individually.
const applyRouteMeta = (file) => {
  const r = routeByFile(file);
  if (!r) return;
  if (r.title) document.title = r.title;
  if (r.description) {
    let m = document.querySelector('meta[name="description"]');
    if (!m) { m = document.createElement('meta'); m.name = 'description'; document.head.appendChild(m); }
    m.setAttribute('content', r.description);
  }
  ensureAnalyticsLoaded();
  capturePageViewFor(r, file);
};

// Build the page-view metadata for a route. Keep this conservative — we
// never include URLs, key prefixes, request bodies, user PII, etc. The
// path is the canonical site path, NOT the file name on disk.
const pageMetaFor = (r, file) => {
  const meta = { path: r.path, page_type: r.type };
  if (r.endpointId) {
    meta.endpoint_id    = r.endpointId;
    meta.endpoint_group = r.group;
  }
  if (r.group && !meta.endpoint_group) meta.endpoint_group = r.group;
  if (r.type === 'use-case') {
    // /use-cases/podcast-clipping → "podcast-clipping"
    const seg = r.path.split('/').filter(Boolean).pop();
    if (seg) meta.use_case_id = seg;
  }
  return meta;
};

const capturePageViewFor = (r, file) => {
  const meta = pageMetaFor(r, file);
  const fire = () => {
    if (window.MIQAnalytics) {
      window.MIQAnalytics.capturePageView(r.path, meta);
    }
  };
  if (window.MIQAnalytics) fire();
  else window.addEventListener('miq-analytics-ready', fire, { once: true });
};

// Inject analytics.js (+ optional env loader) exactly once, on first call.
// Pages don't need to add the <script> tag themselves — pulling this in
// from routes.jsx keeps the HTML files untouched.
const ensureAnalyticsLoaded = () => {
  if (window.__miqAnalyticsLoading || window.MIQAnalytics) return;
  window.__miqAnalyticsLoading = true;

  // env.local.js is optional. If it's missing we silently move on; in
  // that case analytics.js falls back to no-op mode (or localStorage).
  // Setting onerror prevents the 404 from looking like a real failure.
  const env = document.createElement('script');
  env.src = 'env.local.js';
  env.async = false;
  env.onerror = () => { /* expected when running without a local env file */ };
  env.onload = injectMain;
  env.addEventListener('error', injectMain);   // even on 404, continue
  document.head.appendChild(env);

  function injectMain() {
    if (document.querySelector('script[data-miq-analytics]')) return;
    const s = document.createElement('script');
    s.src = 'analytics.js';
    s.async = false;
    s.dataset.miqAnalytics = '1';
    s.onload = () => {
      try { window.dispatchEvent(new Event('miq-analytics-ready')); }
      catch (e) {}
    };
    document.head.appendChild(s);
  }
};

// Tiny helper exposed for ad-hoc tracking outside this file — e.g. inline
// scripts that want to fire a custom event but need MIQAnalytics queueing.
const onAnalyticsReady = (fn) => {
  if (window.MIQAnalytics) fn(window.MIQAnalytics);
  else window.addEventListener('miq-analytics-ready', () => fn(window.MIQAnalytics), { once: true });
};

Object.assign(window, {
  STATIC_ROUTES, allRoutes, routeByFile, routeByPath,
  endpointRoutes, groupRoutes, applyRouteMeta,
  pageMetaFor, ensureAnalyticsLoaded, onAnalyticsReady,
});
