import 'dart:ui';

import 'locale_storage.dart';
import 'locale_registry.dart';

String get defaultLocaleCode => LocaleRegistry.fallbackLocaleCode;

String normalizeLocaleCode(String? code) {
  final supportedLocaleCodes = LocaleRegistry.supportedLocaleCodes;
  final fallbackLocaleCode = LocaleRegistry.fallbackLocaleCode;

  if (code == null || code.isEmpty) {
    return fallbackLocaleCode;
  }
  final normalized = code.toLowerCase().replaceAll('_', '-');
  if (supportedLocaleCodes.contains(normalized)) {
    return normalized;
  }
  final languageCode = normalized.split('-').first;
  if (supportedLocaleCodes.contains(languageCode)) {
    return languageCode;
  }
  return fallbackLocaleCode;
}

String resolvePreferredLocaleCode() {
  final stored = LocaleStorage.read();
  if (stored != null && stored.isNotEmpty) {
    final normalizedStored = normalizeLocaleCode(stored);
    if (LocaleRegistry.contains(normalizedStored)) {
      return normalizedStored;
    }
  }
  final deviceLocale = PlatformDispatcher.instance.locale;
  final countryCode = deviceLocale.countryCode;
  final languageTag = countryCode == null || countryCode.isEmpty
      ? deviceLocale.languageCode
      : '${deviceLocale.languageCode}-$countryCode';
  return normalizeLocaleCode(languageTag);
}

String? extractLocaleFromPath(Uri uri) {
  final supportedLocaleCodes = LocaleRegistry.supportedLocaleCodes;
  if (uri.pathSegments.isEmpty) {
    return null;
  }
  final code = uri.pathSegments.first.toLowerCase();
  if (supportedLocaleCodes.contains(code)) {
    return code;
  }
  return null;
}

String stripLocalePath(Uri uri) {
  final supportedLocaleCodes = LocaleRegistry.supportedLocaleCodes;
  final segments = uri.pathSegments;
  if (segments.isNotEmpty &&
      supportedLocaleCodes.contains(segments.first.toLowerCase())) {
    final rest = segments.skip(1).join('/');
    if (rest.isEmpty) {
      return '/';
    }
    return '/$rest';
  }
  return uri.path;
}

String buildLocalizedPath(String localeCode, Uri uri) {
  final supportedLocaleCodes = LocaleRegistry.supportedLocaleCodes;
  final segments = uri.pathSegments;
  Iterable<String> restSegments = segments;
  if (segments.isNotEmpty) {
    final head = segments.first.toLowerCase();
    if (supportedLocaleCodes.contains(head)) {
      restSegments = segments.skip(1);
    }
  }
  final newPath = '/${[localeCode, ...restSegments].join('/')}';

  // Return only the path and query part to avoid GoRouter confusion with full URLs
  final newUri = uri.replace(path: newPath);
  String result = newUri.path;
  if (newUri.hasQuery) {
    result += '?${newUri.query}';
  }
  if (newUri.hasFragment) {
    result += '#${newUri.fragment}';
  }
  return result;
}

String buildSigninRedirectPath(String localeCode, Uri uri) {
  final newPath = '/$localeCode/signin';
  final newUri = uri.replace(path: newPath);
  String result = newUri.path;
  if (newUri.hasQuery) {
    result += '?${newUri.query}';
  }
  if (newUri.hasFragment) {
    result += '#${newUri.fragment}';
  }
  return result;
}

String buildLocalizedHomePath(Uri uri, {String? preferredLocaleCode}) {
  final resolvedLocale =
      extractLocaleFromPath(uri) ??
      normalizeLocaleCode(preferredLocaleCode ?? resolvePreferredLocaleCode());
  return '/$resolvedLocale/dashboard';
}

String buildLocalizedSigninPath(Uri uri, {String? preferredLocaleCode}) {
  final resolvedLocale =
      extractLocaleFromPath(uri) ??
      normalizeLocaleCode(preferredLocaleCode ?? resolvePreferredLocaleCode());
  return '/$resolvedLocale/signin';
}
