/**
 * Build an iframe-compatible URL for a platform service.
 *
 * All URLs route through nginx which strips X-Frame-Options headers:
 * - Real domain (app.cmlite.org) → //db.cmlite.org (subdomain via nginx port 80)
 * - Localhost/IP dev → //hostname:EMBED_PORT (dedicated nginx proxy ports)
 */
export function buildServiceUrl(
  subdomain: string,
  domain: string,
  embedPort: number,
): string {
  const hostname = window.location.hostname;
  // Use subdomain routing only when accessing via the configured domain
  // (avoids IP addresses like 0.0.0.0/127.0.0.1 triggering subdomain logic)
  if (hostname.endsWith(domain)) {
    return `//${subdomain}.${domain}`;
  }
  // Localhost or IP access — use dedicated nginx embed proxy port
  return `//${hostname}:${embedPort}`;
}

/**
 * Build the "Home" URL pointing to the MkDocs static site.
 *
 * - Real domain (app.cmlite.org) → //cmlite.org (root domain serves MkDocs)
 * - Localhost/IP dev → //hostname:MKDOCS_SITE_SERVER_PORT (default 4004)
 *
 * Uses VITE_DOMAIN env var (set by docker-compose) to detect whether the
 * browser is on a real domain. This avoids needing an API call in every layout.
 */
export function buildHomeUrl(): string {
  const hostname = window.location.hostname;
  const domain = import.meta.env.VITE_DOMAIN as string | undefined;

  if (domain && hostname.endsWith(domain)) {
    return `//${domain}`;
  }
  // Localhost or IP access — use the MkDocs site server port
  const sitePort = import.meta.env.VITE_MKDOCS_SITE_PORT || '4004';
  return `//${hostname}:${sitePort}`;
}

/**
 * Resolve special `$token` nav paths to environment-aware URLs.
 *
 * - `$landing` → MkDocs root (buildHomeUrl())
 * - `$docs`    → MkDocs /docs/ section
 * - anything else → passthrough unchanged
 */
export function resolveNavUrl(path: string): string {
  if (path === '$landing') return buildHomeUrl();
  if (path === '$docs') return buildHomeUrl() + '/docs/';
  return path;
}
