/**
 * Resolves an asset path (logo, favicon, uploaded media) against NEXT_PUBLIC_APP_URL.
 * Ensures the logo and static assets always resolve correctly across environments:
 * e.g., https://portal.webiletechnologies.com/meta-connector/images/logo.png
 */
export function getAppBaseUrl(): string {
  if (typeof window !== 'undefined' && window.location.origin) {
    if (window.location.pathname.startsWith('/meta-connector')) {
      return `${window.location.origin}/meta-connector`;
    }
    return window.location.origin;
  }
  const envUrl = (process.env.NEXT_PUBLIC_APP_URL || '').trim().replace(/\/+$/, '');
  if (envUrl) {
    return envUrl;
  }
  return '';
}

export function normalizeAssetUrl(url?: string | null): string {
  if (!url) return '';
  // If already a complete absolute URL or data URI, return as-is
  if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) {
    return url;
  }

  const baseUrl = getAppBaseUrl();
  const cleanPath = url.startsWith('/') ? url : `/${url}`;

  if (!baseUrl) {
    return cleanPath;
  }

  try {
    const parsedBase = new URL(baseUrl);
    const subpath = parsedBase.pathname.replace(/\/+$/, '');
    if (subpath && cleanPath.startsWith(subpath)) {
      return `${parsedBase.origin}${cleanPath}`;
    }
  } catch {}

  return `${baseUrl}${cleanPath}`;
}

/**
 * Resolves an API or page path against NEXT_PUBLIC_APP_URL or current browser origin.
 */
export function apiUrl(path?: string | null): string {
  if (!path) return '';
  if (path.startsWith('http://') || path.startsWith('https://') || path.startsWith('data:')) {
    return path;
  }
  const cleanPath = path.startsWith('/') ? path : `/${path}`;
  if (typeof window !== 'undefined') {
    const isSubpath = window.location.pathname.startsWith('/meta-connector');
    if (isSubpath) {
      if (cleanPath.startsWith('/meta-connector')) return cleanPath;
      return `/meta-connector${cleanPath}`;
    }
    return cleanPath;
  }
  return normalizeAssetUrl(path);
}

export const buildAppUrl = apiUrl;

/**
 * Resolves an in-app page route for Next.js Link/router by preserving query parameters
 * and stripping any redundant basePath prefix (since Next.js basePath='/meta-connector' automatically adds it).
 */
export function appRoute(path: string = '/', searchParams?: string | URLSearchParams | null): string {
  let clean = (path || '/').trim();
  let hash = '';
  const hashIdx = clean.indexOf('#');
  if (hashIdx !== -1) {
    hash = clean.slice(hashIdx);
    clean = clean.slice(0, hashIdx);
  }

  // Strip all repeated subpath prefixes (/meta-connector or /meta_connector)
  clean = clean.replace(/^(\/meta[-_]connector)+/i, '');
  if (!clean.startsWith('/')) clean = `/${clean}`;

  if (!searchParams) return `${clean}${hash}`;
  const qs = typeof searchParams === 'string'
    ? (searchParams.includes('=') ? searchParams.replace(/^\?/, '') : `shop=${encodeURIComponent(searchParams)}`)
    : searchParams.toString();
  if (!qs) return `${clean}${hash}`;
  const sep = clean.includes('?') ? '&' : '?';
  return `${clean}${sep}${qs}${hash}`;
}

/**
 * Returns the fully-qualified subpath route (/meta-connector/...) for window.history or external redirection.
 */
export function canonicalAppRoute(path: string = '/', searchParams?: string | URLSearchParams | null): string {
  const route = appRoute(path, searchParams);
  return `/meta-connector${route === '/' ? '' : route}`;
}


