export function isMobileHost(hostname = window.location.hostname) {
  return hostname === "m.localhost" || hostname.startsWith("m.");
}

export function isMobileDevice() {
  if (typeof window === "undefined" || !window.navigator) return false;
  const ua = window.navigator.userAgent;
  const isMobileUA = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
  const isSmallScreen = window.innerWidth < 768;
  return isMobileUA || isSmallScreen;
}

export function getMobilePath(path: string): string {
  if (path === "/" || path === "") {
    return "/m";
  }
  if (path === "/m" || path.startsWith("/m/") || path.startsWith("/admin")) {
    return path;
  }
  
  if (path === "/listings" || path.startsWith("/listings/")) {
    return `/m${path}`;
  }
  if (path === "/orders" || path.startsWith("/orders/")) {
    return `/m${path}`;
  }
  if (path === "/realname") return "/m/realname";
  if (path === "/login") return "/m/login";
  if (path === "/register") return "/m/register";
  
  if (path === "/seller/listings/create") {
    return "/m/seller/listings/create";
  }
  if (path === "/messages" || path.startsWith("/messages/")) {
    return "/m/messages";
  }
  
  // PC-only views that don't have mobile counterparts go to mobile profile as fallback
  if (path === "/wallet" || path === "/notifications" || path.startsWith("/seller")) {
    return "/m/profile";
  }
  
  return `/m${path}`;
}

export function getPcPath(path: string): string {
  if ((path !== "/m" && !path.startsWith("/m/")) || path.startsWith("/admin")) {
    return path;
  }
  
  if (path === "/m" || path === "/m/") {
    return "/";
  }
  
  const subPath = path.substring(2);
  
  if (subPath === "/listings" || subPath.startsWith("/listings/")) {
    return subPath;
  }
  if (subPath === "/orders" || subPath.startsWith("/orders/")) {
    return subPath;
  }
  if (subPath === "/login") return "/login";
  if (subPath === "/register") return "/login"; // PC uses /login for both auth actions
  if (subPath === "/realname") return "/realname";
  if (subPath === "/seller/listings/create") return "/seller/listings/create";
  
  if (subPath === "/messages") return "/messages";
  if (subPath.startsWith("/chats/")) return "/messages/" + subPath.substring(7);
  if (subPath === "/profile") return "/wallet";
  
  return subPath || "/";
}

export function toMobilePath(path: string) {
  return getMobilePath(path);
}
