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

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

/**
 * Converts HTTP image URLs to use Next.js image proxy when the site is served over HTTPS.
 * This prevents Mixed Content errors when accessing the site through ngrok or HTTPS.
 * The proxy route fetches images from HTTP Strapi server-side and serves them over HTTPS.
 * 
 * @param url - The image URL (can be relative, HTTP, or HTTPS)
 * @param baseUrl - Optional base URL from environment variable
 * @returns The URL using the image proxy if on HTTPS, or direct URL if on HTTP
 */
export function ensureHttpsImageUrl(url: string, baseUrl?: string): string {
  if (!url || typeof url !== "string") {
    console.warn("ensureHttpsImageUrl: Invalid URL provided", url)
    return ""
  }
  
  // Trim whitespace
  url = url.trim()
  
  // Check if we're in browser and on HTTPS
  const isHttps = typeof window !== "undefined" && window.location.protocol === "https:"
  
  // If not on HTTPS, return the URL as-is (no proxy needed)
  if (!isHttps) {
    // Construct absolute URL if relative
    if (!url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("//")) {
      const strapiBaseUrl = baseUrl || process.env.NEXT_PUBLIC_STRAPI_BASE_URL || "http://160.187.167.213"
      const normalizedBaseUrl = strapiBaseUrl.replace(/\/+$/, "")
      const normalizedUrl = url.startsWith("/") ? url : `/${url}`
      return `${normalizedBaseUrl}${normalizedUrl}`
    }
    return url
  }
  
  // On HTTPS - use image proxy to avoid Mixed Content issues
  // Extract the relative path from the URL
  let imagePath: string
  
  if (url.startsWith("http://") || url.startsWith("https://")) {
    // Extract path from absolute URL
    try {
      const urlObj = new URL(url)
      imagePath = urlObj.pathname
    } catch {
      // If URL parsing fails, try to extract path manually
      const match = url.match(/\/uploads\/.*$/)
      imagePath = match ? match[0] : url
    }
  } else if (url.startsWith("//")) {
    // Protocol-relative URL
    imagePath = url.substring(2).replace(/^[^/]+/, "")
  } else {
    // Relative URL
    imagePath = url.startsWith("/") ? url : `/${url}`
  }
  
  // Use Next.js image proxy route
  const proxyUrl = `/api/image-proxy?url=${encodeURIComponent(imagePath)}`
  return proxyUrl
}
