/**
 * Tag — 标签组件（Tailwind 内联）
 * @prop {'brand'|'red'|'orange'|'yellow'|'green'|'cyan'|'blue'|'purple'|'pink'|'teal'|'grey'|'white'|'ai'} [variant='brand'] — 颜色变体
 * @prop {'s'|'m'|'l'} [size='m'] — 尺寸档位
 * @prop {'md'|'square'|'full'} [radius='md'] — 圆角样式
 * @prop {'regular'|'bold'} [fontWeight='bold'] — 字体粗细
 * @prop {boolean} [showIcon=false] — 是否显示左侧图标
 * @prop {string} [iconName='tag-01-stroked'] — 图标名称
 * @prop {boolean} [closable=false] — 是否显示关闭按钮
 * @prop {function|null} [onClose=null] — 关闭回调
 * @prop {string} [className=''] — 附加类名
 *
 * 白色标签用于业务卡片、筛选标签等中性场景；
 * `square` 圆角使用 3px，和 Avatar 方形 / Card 内置标签保持同一套细圆角语言。
 */

import Icon from './Icon';

/* ── 基础样式（所有变体 / 尺寸共用） ── */
const BASE = [
  'inline-flex items-center justify-center',
  '[font-family:inherit]',
  'cursor-default select-none',
  'transition-colors tfds-motion-ui-fast leading-none whitespace-nowrap',
].join(' ');

/* ── 变体 → Tailwind 类名（按色相排序） ── */
const VARIANT_CLASS = {
  red: [
    'bg-red-50 text-red-600',
  ].join(' '),
  orange: [
    'bg-orange-50 text-orange-600',
  ].join(' '),
  yellow: [
    'bg-yellow-100 text-yellow-700',
  ].join(' '),
  green: [
    'bg-green-50 text-green-600',
  ].join(' '),
  cyan: [
    'bg-cyan-50 text-cyan-600',
  ].join(' '),
  blue: [
    'bg-blue-50 text-blue-600',
  ].join(' '),
  purple: [
    'bg-purple-50 text-purple-600',
  ].join(' '),
  pink: [
    'bg-pink-50 text-pink-600',
  ].join(' '),
  teal: [
    'bg-brand-50 text-brand-800',
  ].join(' '),
  grey: [
    'bg-fill text-blueGrey-700',
  ].join(' '),
  white: [
    'bg-white text-foreground border border-border-default',
  ].join(' '),
  brand: [
    'bg-brand-50 text-brand-500',
  ].join(' '),
  ai: [
    'text-brand-500',
  ].join(' '),
};

/* ── 尺寸 → 间距配置（参考 Figma 截图） ── */
const SIZE_CONFIG = {
  s: {
    height: 'h-[16px]',
    fontSize: 'text-xs [font-size:var(--text-xs)] leading-[var(--leading-4)]',
    paddingLeft: 'pl-1',
    paddingRight: 'pr-1',
    iconToTextGap: '[&>.tag-icon]:mr-1',
    textToCloseGap: '[&>.tag-text]:mr-1',
  },
  m: {
    height: 'h-[20px]',
    fontSize: 'text-xs [font-size:var(--text-xs)] leading-[var(--leading-4)]',
    paddingLeft: 'pl-2',
    paddingRight: 'pr-2',
    iconToTextGap: '[&>.tag-icon]:mr-1',
    textToCloseGap: '[&>.tag-text]:mr-1',
  },
  l: {
    height: 'h-[24px]',
    fontSize: 'text-xs [font-size:var(--text-xs)] leading-[var(--leading-4)]',
    paddingLeft: 'pl-2',
    paddingRight: 'pr-2',
    iconToTextGap: '[&>.tag-icon]:mr-1',
    textToCloseGap: '[&>.tag-text]:mr-1',
  },
};

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

const FONT_WEIGHT_CLASS = {
  regular: '[font-weight:400]',
  bold: '[font-weight:var(--font-bold)]',
};

const CLOSE_ICON = (
  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M9 3L3 9M3 3L9 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
  </svg>
);

export default function Tag({
  variant = 'brand',
  size = 'm',
  radius = 'md',
  fontWeight = 'bold',
  showIcon = false,
  iconName = 'tag-01-stroked',
  closable = false,
  onClose,
  className = '',
  style,
  children,
  ...rest
}) {
  const config = SIZE_CONFIG[size];
  const aiStyle = variant === 'ai'
    ? {
        background: 'var(--bg-chat-outgoing-ai)',
      }
    : undefined;
  const mergedStyle = {
    ...(aiStyle || null),
    ...(style || null),
  };
  
  const cls = [
    BASE,
    VARIANT_CLASS[variant],
    config.height,
    config.fontSize,
    config.paddingLeft,
    config.paddingRight,
    RADIUS_CLASS[radius],
    showIcon ? config.iconToTextGap : '',
    closable ? config.textToCloseGap : '',
    className,
  ].filter(Boolean).join(' ');
  const textClassName = [
    'tag-text whitespace-nowrap',
    FONT_WEIGHT_CLASS[fontWeight] || FONT_WEIGHT_CLASS.bold,
  ].join(' ');

  const handleClose = (e) => {
    e.stopPropagation();
    if (onClose) {
      onClose();
    }
  };

  const iconSize = 'xs';

  return (
    <span className={[`tfds-tag`, cls].filter(Boolean).join(' ')} style={mergedStyle} {...rest} data-tfds-component="Tag">
      {showIcon && (
        <span className="tag-icon inline-flex items-center justify-center">
          <Icon name={iconName} size={iconSize} />
        </span>
      )}
      <span
        className={textClassName}
        style={variant === 'ai'
          ? {
              background: 'var(--gradient-ai-fill-text)',
              WebkitBackgroundClip: 'text',
              backgroundClip: 'text',
              color: 'transparent',
            }
          : undefined}
      >
        {children}
      </span>
      {closable && (
        <button
          type="button"
          className="inline-flex items-center justify-center"
          onClick={handleClose}
          aria-label="关闭"
        >
          {CLOSE_ICON}
        </button>
      )}
    </span>
  );
}
