import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { format, getTime, formatDistanceToNow } from 'date-fns';


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

export function nl2br(text: string) {
  return text?.replace(/\n/g, '<br />');
}

export function parseMessage(message: string) {
  let parts = [];

  // Bold: *text*
  message = message?.replace(/\*(.*?)\*/g, '<b>$1</b>');
  // Italic: _text_
  message = message?.replace(/_(.*?)_/g, '<i>$1</i>');
  // Strikethrough: ~text~
  message = message?.replace(/~(.*?)~/g, '<s>$1</s>');
  // Monospace: `text`
  message = message?.replace(/`(.*?)`/g, '<code>$1</code>');

  // Replace URLs in the message with anchor tags
  message = message?.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" class="text-emerald-600 break-all dark:text-emerald-400 hover:underline hover:text-emerald-800" rel="noopener noreferrer">$1</a>');
  message = message?.replace(/^[-*]\s+/gm, "• ");

  return message;
}

export function fLimitation(string:string, start:number, limit:number) {
  if (typeof string === 'undefined' || string === null) {
      return '';
  }
  return string.slice(start,limit) + (string.length > limit ? '...' : '')
}

export function dashToPoint(text:string) {
  // ganti setiap baris yang dimulai dengan - atau * jadi •
  return text?.replace(/^[-*]\s+/gm, "• ");
}

export function fToNow(date: string) {
  return formatDistanceToNow(new Date(date), {
    addSuffix: true,
  });
}

export function formatPreview(text: string, samples: string[]): string {
  if (!text) return "";
  let result = text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");

  const matches = result.match(/{{(\d+)}}/g);
  if (matches) {
      matches.forEach((match, idx) => {
          const sample = samples && samples[idx] ? samples[idx] : match;
          result = result.replace(match, `${sample}`);
      });
  }

  result = result.replace(/\*(.*?)\*/g, '<b>$1</b>');
  result = result.replace(/_(.*?)_/g, '<i>$1</i>');
  result = result.replace(/~(.*?)~/g, '<s>$1</s>');
  result = result.replace(/`(.*?)`/g, '<code class="bg-gray-100 dark:bg-gray-800 p-0.5 rounded text-xs">$1</code>');

  return result;
}
export function formatResponseTime(totalMinutes: number): string {
    if (typeof totalMinutes !== 'number' || isNaN(totalMinutes)) return "";
    
    if (totalMinutes < 1) {
        return `${Math.round(totalMinutes * 60)} detik`;
    }
    
    const h = Math.floor(totalMinutes / 60);
    const m = Math.floor(totalMinutes % 60);
    const s = Math.round((totalMinutes - Math.floor(totalMinutes)) * 60);
    
    let result = [];
    if (h > 0) result.push(`${h} jam`);
    if (m > 0) result.push(`${m} menit`);
    
    if (h > 0) {
        return result.join(' ');
    } else {
        if (s > 0) result.push(`${s} detik`);
        return result.join(' ');
    }
}
