
"use client";

import { forwardRef } from "react";
import type { ButtonHTMLAttributes, ReactNode } from "react";
import { twMerge } from "tailwind-merge";

type ButtonVariant = "primary" | "secondary" | "ghost" | "outline" | "destructive";
type ButtonSize = "sm" | "md" | "lg" | "icon";

export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: ButtonVariant;
  size?: ButtonSize;
  icon?: ReactNode;
  iconRight?: ReactNode;
  fullWidth?: boolean;
}

function variantClass(variant: ButtonVariant) {
  if (variant === "secondary") return "ks-button ks-button-secondary";
  if (variant === "ghost") return "ks-button ks-button-ghost";
  if (variant === "outline")
    return "ks-button border-[var(--ks-color-border-strong)] bg-transparent text-[var(--ks-color-text-primary)] hover:bg-[var(--ks-color-bg-hover)]";
  if (variant === "destructive")
    return "ks-button bg-[var(--ks-color-status-danger)] text-white border-[var(--ks-color-status-danger)] hover:brightness-95";
  return "ks-button ks-button-primary";
}

function sizeClass(size: ButtonSize) {
  if (size === "sm") return "ks-button-sm";
  if (size === "lg") return "ks-button-lg";
  if (size === "icon") return "ks-button-icon";
  return "";
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
  { className, variant = "primary", size = "md", icon, iconRight, fullWidth, children, ...props },
  ref
) {
  return (
    <button
      ref={ref}
      className={twMerge(
        "inline-flex items-center justify-center gap-1.5 font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50",
        variantClass(variant),
        sizeClass(size),
        fullWidth ? "w-full" : "",
        className
      )}
      {...props}
    >
      {icon ? <span className="shrink-0">{icon}</span> : null}
      {children ? <span className="truncate">{children}</span> : null}
      {iconRight ? <span className="shrink-0">{iconRight}</span> : null}
    </button>
  );
});
