/**
 * Button — 触发离散动作（提交、取消、打开弹窗、行内操作）
 *
 * **何时用**：改变业务状态、导航至任务、打开抽屉/对话框；与 `Tabs`（切换同容器内面板）区分。
 * **组合**：仅图标时用 `icon` + `iconOnly`，必须传 `tooltip` 说明真实操作。
 *
 * @prop {'button'|'a'|import('react').ElementType} [as='button'] — 根元素类型（链接式操作可用 `as="a"`）
 * @prop {'primary'|'outline-brand'|'outline-black'|'ghost-brand'|'ghost-black'|'text-brand'|'text-black'} [variant='primary'] — 变体（primary = 每视图唯一主操作）
 * @prop {'sm'|'md'} [size='md'] — 高度档位，md 与 Input md 对齐
 * @prop {'rounded'|'full'} [radius='rounded'] — 圆角
 * @prop {import('react').ReactNode} [icon=null] — 图标插槽（通常传 `<Icon />`）
 * @prop {boolean} [iconOnly=false] — 是否仅图标
 * @prop {import('react').ReactNode} [tooltip=null] — 仅图标按钮的操作说明，hover/focus 时通过 Tooltip 展示
 * @prop {boolean} [disabled=false]
 * @prop {boolean} [loading=false]
 */

import Tooltip from './Tooltip';

/* ── 基础样式（所有变体 / 尺寸共用） ── */
const BASE = [
  'tfds-button',
  'inline-flex items-center justify-center',
  '[font-family:inherit] [font-weight:var(--font-semibold)]',
  'border cursor-pointer select-none',
  'transition-colors transition-transform tfds-motion-ui-fast leading-none',
  '[outline:2px_solid_transparent] outline-offset-2',
  'disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none',
].join(' ');

/* ── 变体 → Tailwind 类名 ── */
const VARIANT_CLASS = {
  primary: [
    'bg-grey-950 text-white border-0',
    'hover:bg-grey-900',
    'active:bg-grey-800 active:scale-[0.97]',
    'focus-visible:outline-grey-400',
  ].join(' '),
  'outline-brand': [
    'bg-white text-brand-700 border-border-brand',
    'hover:bg-brand-50',
    'active:bg-brand-100',
    'focus-visible:outline-brand-200',
  ].join(' '),
  'outline-black': [
    'bg-white text-foreground border-border-default',
    'hover:bg-blueGrey-50 hover:border-border-strong',
    'active:bg-blueGrey-100',
    'focus-visible:outline-blueGrey-400',
  ].join(' '),
  'ghost-brand': [
    'bg-transparent text-brand-700 border-transparent',
    'hover:bg-brand-50',
    'active:bg-brand-100',
    'focus-visible:outline-brand-200',
  ].join(' '),
  'ghost-black': [
    'bg-transparent text-foreground border-transparent',
    'hover:bg-blueGrey-100',
    'active:bg-blueGrey-200',
    'focus-visible:outline-blueGrey-400',
  ].join(' '),
  'text-brand': [
    'bg-transparent text-brand-700 border-transparent',
    'hover:text-brand-800',
    'active:text-brand-900',
    'focus-visible:outline-brand-200',
  ].join(' '),
  'text-black': [
    'bg-transparent text-foreground border-transparent',
    'hover:text-blueGrey-700',
    'active:text-blueGrey-600',
    'focus-visible:outline-blueGrey-400',
  ].join(' '),
};

/* ── 尺寸 → Tailwind 类名 ── */
const SIZE_CLASS = {
  sm: 'h-[var(--size-control-sm)] py-1 px-2 text-xs [font-size:var(--text-xs)] leading-[var(--leading-4)] gap-1',
  md: 'h-[var(--size-control-md)] py-2 px-3 text-sm [font-size:var(--text-sm)] leading-[var(--leading-5)] gap-2',
};

/* ── 圆角 → Tailwind 类名 ── */
const RADIUS_CLASS = {
  rounded: 'rounded-md',
  full: 'rounded-full',
};

export default function Button({
  as = 'button',
  variant = 'primary',
  size = 'md',
  radius = 'rounded',
  icon,
  iconOnly = false,
  tooltip = null,
  disabled = false,
  loading = false,
  className = '',
  children,
  ...rest
}) {
  const cls = [
    BASE,
    VARIANT_CLASS[variant],
    SIZE_CLASS[size],
    RADIUS_CLASS[radius],
    iconOnly && '!p-0 !gap-0 aspect-square',
    loading && 'cursor-wait pointer-events-none',
    className,
  ].filter(Boolean).join(' ');

  const iconSlot = loading
    ? <span className="tfds-inline-spin w-[1em] h-[1em] shrink-0" aria-hidden="true" />
    : icon;

  const Component = as;
  const hasIconOnlyTooltip = iconOnly && tooltip !== null && tooltip !== undefined && tooltip !== '';
  const ariaLabel = rest['aria-label'] ?? (hasIconOnlyTooltip && typeof tooltip === 'string' ? tooltip : undefined);

  const buttonNode = (
    <Component
      className={cls}
      data-tfds-component="Button"
      disabled={Component === 'button' ? disabled : undefined}
      aria-busy={loading || undefined}
      {...rest}
      aria-label={ariaLabel}
    >
      {iconSlot}
      {!iconOnly && children}
    </Component>
  );

  if (!hasIconOnlyTooltip) {
    return buttonNode;
  }

  return (
    <Tooltip content={tooltip} placement="top">
      {buttonNode}
    </Tooltip>
  );
}
