/** Fallback so client-side image URLs resolve when NEXT_PUBLIC_STRAPI_URL is unset */
const STRAPI_URL_FALLBACK = "https://cms.navana-realestate.com";

/**
 * Get Strapi CMS URL - set NEXT_PUBLIC_STRAPI_URL env variable
 */
export const getStrapiUrl = (): string => {
    return process.env.NEXT_PUBLIC_STRAPI_URL || STRAPI_URL_FALLBACK;
};

/**
 * Get full image URL from Strapi
 * Handles both absolute URLs (starts with http) and relative URLs
 * This is the function you should use everywhere for image URLs
 */
export const getStrapiImageUrl = (url: string | undefined | null): string => {
  if (!url) return "";

  // If already absolute URL, return as is
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // If relative URL, prepend Strapi URL
  const strapiUrl = getStrapiUrl();
  if (!strapiUrl) {
    console.error("NEXT_PUBLIC_STRAPI_URL is not set. Cannot construct image URL.");
    return url; // Return the relative URL as fallback
  }
  
  // Ensure URL starts with / if it's relative
  const relativeUrl = url.startsWith("/") ? url : `/${url}`;
  return `${strapiUrl}${relativeUrl}`;
};

/**
 * Legacy helper - use getStrapiImageUrl instead
 * But this maintains backward compatibility
 */
export const getStrapiUrlForImages = (): string => {
  return getStrapiUrl();
};

/**
 * Normalize link href so external URLs from CMS (e.g. "youtube.com/@nrelltd")
 * are not treated as relative paths. Ensures protocol is present for external URLs.
 */
export function normalizeLinkHref(link: string | undefined | null): string {
  if (!link || typeof link !== "string") return "/";
  const trimmed = link.trim();
  if (!trimmed) return "/";
  // Already has a protocol or is a special scheme
  if (
    trimmed.startsWith("http://") ||
    trimmed.startsWith("https://") ||
    trimmed.startsWith("mailto:") ||
    trimmed.startsWith("tel:") ||
    trimmed.startsWith("#")
  ) {
    return trimmed;
  }
  // Internal path
  if (trimmed.startsWith("/")) return trimmed;
  // Looks like an external URL without protocol (e.g. "youtube.com/@nrelltd" or "www.example.com")
  if (trimmed.includes(".") && !trimmed.includes(" ")) {
    return `https://${trimmed}`;
  }
  return trimmed;
}
