import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
import slug from 'slug';

function slugify(text, locale = "en") {
  return slug(text, { lower: true, locale });
}
function cn(...inputs) {
  return twMerge(clsx(inputs));
}
function throttle(callback, waitMs) {
  let timerId = null;
  let lastInvokeTime = 0;
  let trailingArgs = null;
  const invoke = (args) => {
    lastInvokeTime = Date.now();
    callback(...args);
  };
  const throttled = (...args) => {
    const now = Date.now();
    const remaining = waitMs - (now - lastInvokeTime);
    if (lastInvokeTime === 0) {
      invoke(args);
      return;
    }
    if (remaining <= 0 || remaining > waitMs) {
      if (timerId) {
        clearTimeout(timerId);
        timerId = null;
      }
      invoke(args);
    } else {
      trailingArgs = args;
      if (!timerId) {
        timerId = setTimeout(() => {
          timerId = null;
          if (trailingArgs) {
            invoke(trailingArgs);
            trailingArgs = null;
          }
        }, remaining);
      }
    }
  };
  throttled.cancel = () => {
    if (timerId) {
      clearTimeout(timerId);
      timerId = null;
    }
    trailingArgs = null;
    lastInvokeTime = 0;
  };
  throttled.flush = () => {
    if (timerId && trailingArgs) {
      clearTimeout(timerId);
      timerId = null;
      invoke(trailingArgs);
      trailingArgs = null;
    }
  };
  return throttled;
}
function stripHtml(html) {
  let text = html.replace(/<[^>]*>/g, "");
  text = text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#x27;/g, "'").replace(/&#x2F;/g, "/").replace(/&nbsp;/g, " ").replace(/&hellip;/g, "...");
  return text.replace(/\s+/g, " ").trim();
}
function stripMarkdown(markdown) {
  let text = markdown;
  text = text.replace(/^#{1,6}\s+/gm, "");
  text = text.replace(/\*\*([^*]+)\*\*/g, "$1");
  text = text.replace(/\*([^*]+)\*/g, "$1");
  text = text.replace(/__([^_]+)__/g, "$1");
  text = text.replace(/_([^_]+)_/g, "$1");
  text = text.replace(/~~([^~]+)~~/g, "$1");
  text = text.replace(/`([^`]+)`/g, "$1");
  text = text.replace(/```[\s\S]*?```/g, "");
  text = text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1");
  text = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1");
  text = text.replace(/^>\s+/gm, "");
  text = text.replace(/^[-*]{3,}$/gm, "");
  text = text.replace(/^[\s]*[-*+]\s+/gm, "");
  text = text.replace(/^[\s]*\d+\.\s+/gm, "");
  return text.replace(/\n\s*\n/g, "\n").replace(/\s+/g, " ").trim();
}

export { cn, slugify, stripHtml, stripMarkdown, throttle };
