import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function getWsUrl() {
  const envUrl = import.meta.env.VITE_WS_URL;
  if (envUrl && !envUrl.includes('localhost')) return envUrl;
  
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const host = window.location.host;
  
  // Try to derive path prefix from VITE_API_URL if it's a relative-looking path on the same host
  // or a full URL on the same host.
  const apiUrl = import.meta.env.VITE_API_URL || "";
  let pathPrefix = "";
  
  try {
    if (apiUrl.startsWith('http')) {
      const url = new URL(apiUrl);
      if (url.host === host) {
        pathPrefix = url.pathname.replace(/\/$/, '');
      }
    } else if (apiUrl.startsWith('/')) {
      pathPrefix = apiUrl.replace(/\/$/, '');
    }
  } catch (e) {}

  return `${protocol}//${host}${pathPrefix}`;
}
