import { twMerge } from "tailwind-merge";

/**
 * Concatenates truthy classes into a space-separated string.
 *
 * @param classes - The classes to concatenate.
 * @returns The concatenated classes.
 */
export const clx = (...classes: (string | boolean | undefined)[]): string => {
  return twMerge(classes.filter(Boolean).join(" "));
};

/**
 * Detects the text direction based on the content
 *
 * @param text - The text to analyze
 * @returns 'rtl' | 'ltr' | 'auto'
 */
export const detectTextDirection = (text: string): "rtl" | "ltr" | "auto" => {
  // Remove HTML tags
  const cleanText = text.replace(/<[^>]*>/g, "").trim();
  if (!cleanText) return "auto";

  // Count RTL and LTR characters
  const rtlChars =
    cleanText.match(
      /[\u0590-\u083F\u08A0-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/g
    ) || [];
  const ltrChars = cleanText.match(/[A-Za-z]/g) || [];

  const rtlCount = rtlChars.length;
  const ltrCount = ltrChars.length;

  // If there's a significant difference, return that direction
  if (rtlCount > ltrCount * 1.5) return "rtl";
  if (ltrCount > rtlCount * 1.5) return "ltr";

  // Otherwise, use auto
  return "auto";
};
