/**
 * FormTitle — B端表单区块标题组件 (Tailwind 内联)
 *
 * 用于页面级总标题、表单区块和白卡内容区标题的统一组件，内置 5 种设计稿变体：
 * form / level-1 / level-2 / level-3 / card。
 * 描述文案与 titleSuffix 默认隐藏；仅在有板块介绍、状态展示或明确要求时分别通过 showDescription / titleSuffix 开启。
 *
 * **AI / 页面生成：层级选型（必须按场景选 variant，禁止手写 h2/h3）**
 * | 场景 | variant | 说明 |
 * |------|---------|------|
 * | 整体页面左上角总标题、工作台名、Playground 页面主标题（如 `Model Playground`） | `form` | 全页最高层级，18px 大字号，左侧**没有**绿色竖条；需要说明时描述在标题下方 |
 * | 页面内一级板块 / 列表管理页单张主白卡顶栏主标题 | `level-1` | 左侧品牌色竖条 + 16px 标题；用于页面总标题之下的大卡片/一级内容块，不用于整页左上角总标题 |
 * | `level-1` 之下的第一级分区 / 白卡内大模块标题 | `level-2` | 14px 竖条；有板块说明诉求时描述显示在标题**同行右侧** |
 * | `level-2` 再下的子分组、折叠面板头、表格上方小区域标题 | `level-3` | 与 level-2 同阶字级，用于再嵌套一层时的视觉降级（仍带竖条） |
 * | `Card` 组件标题区、统计/摘要条、表格卡片外框标题（**无竖条**、标题与描述同排） | `card` | 不要用于整页总标题或大卡片主标题 |
 *
 * 同一页面必须拉开标题层级：页面总标题用 `form`，卡片/板块标题再按 `level-1/2/3` 递进；
 * ⛔ 禁止把整页所有左上角标题都统一写成同一个 variant。
 *
 * @prop {'form'|'level-1'|'level-2'|'level-3'|'card'} [variant='form'] — 标题形态
 * @prop {string} [title] — 主标题；不传则用当前变体示例文案
 * @prop {string} [description] — 描述；不传则用当前变体示例文案
 * @prop {React.ReactNode} [titleSuffix=null] — 主标题右侧补充内容（如状态 Tag）；默认不显示，仅在有明确状态/数量/身份展示诉求时传入；align="center" 时不显示
 * @prop {boolean} [showDescription=false] — 是否展示描述；默认隐藏
 * @prop {'left'|'center'} [align='left'] — 主副文本对齐；center 适用于标题整体居于页面/卡片容器居中的场景，且不显示左侧品牌竖条
 * @prop {string} [className=''] — 额外类名
 */

function resolveAlignedLayout(config, align = 'left') {
  if (align !== 'center') {
    return {
      root: config.root,
      titleWrap: config.titleWrap,
      description: config.description,
      descriptionPlacement: config.descriptionPlacement,
    };
  }

  let root = config.root
    .replace(/\bitems-start\b/g, 'items-center')
    .replace(/\binline-flex\b/g, 'flex w-full');

  if (!/\bflex-col\b/.test(root)) {
    root = root.replace(/\bflex\b/, 'flex flex-col');
  }

  const description = config.description
    .replace(/\bmin-w-0\b/g, '')
    .replace(/\bflex-1\b/g, '')
    .replace(/\s+/g, ' ')
    .trim();

  return {
    root: `${root} w-full text-center`,
    titleWrap: `${config.titleWrap} shrink-0 justify-center`,
    description: `${description} w-full text-center`,
    descriptionPlacement: 'bottom',
  };
}

/* ── 变体 → 布局与排版（颜色走语义 Token 短类） ── */
// 字重使用显式 CSS 变量，避免 Tailwind v4 将 token 解析为 font-family token。
// 所有 variant 主标题统一语义色 text-primary（--color-foreground / blueGrey-900）；Tailwind 类名用 text-foreground，勿用 text-primary（后者是品牌色）。
const TITLE_BASE = 'shrink-0 whitespace-nowrap [font-weight:var(--font-semibold)] text-foreground';
const VARIANT_CONFIG = {
  form: {
    root: 'inline-flex max-w-full min-w-0 flex-col items-start gap-1',
    titleWrap: 'flex shrink-0 items-center gap-1',
    title: `${TITLE_BASE} text-lg leading-7`,
    description: 'whitespace-pre-wrap text-sm font-normal leading-5 text-foreground-muted',
    indicator: null,
    descriptionPlacement: 'bottom',
  },
  'level-1': {
    root: 'inline-flex max-w-full min-w-0 flex-col items-start gap-1',
    titleWrap: 'flex shrink-0 items-center gap-1',
    title: `${TITLE_BASE} text-base leading-[22px]`,
    description: 'whitespace-pre-wrap text-sm font-normal leading-5 text-foreground-muted',
    indicator: 'h-4 w-[4px] shrink-0 rounded-full bg-brand-500',
    descriptionPlacement: 'bottom',
  },
  'level-2': {
    root: 'flex max-w-full min-w-0 items-start gap-1',
    titleWrap: 'flex min-w-0 flex-wrap items-center gap-x-1 gap-y-1',
    title: `${TITLE_BASE} text-sm leading-5`,
    description: 'min-w-0 flex-1 whitespace-normal break-words text-sm font-normal leading-5 text-foreground-muted',
    indicator: 'h-[14px] w-[4px] shrink-0 rounded-full bg-brand-500',
    descriptionPlacement: 'right',
  },
  'level-3': {
    root: 'flex max-w-full min-w-0 items-start gap-1',
    titleWrap: 'flex min-w-0 flex-wrap items-center gap-x-1 gap-y-1',
    title: `${TITLE_BASE} text-sm leading-5`,
    description: 'min-w-0 flex-1 whitespace-normal break-words text-sm font-normal leading-5 text-foreground-muted',
    indicator: 'h-[14px] w-[4px] shrink-0 rounded-full bg-brand-500',
    descriptionPlacement: 'right',
  },
  card: {
    root: 'flex max-w-full min-w-0 gap-1',
    titleWrap: 'flex min-w-0 flex-wrap items-center gap-x-1 gap-y-1',
    title: `${TITLE_BASE} text-sm leading-5`,
    description: 'min-w-0 flex-1 whitespace-normal break-words text-sm font-normal leading-5 text-foreground-muted',
    indicator: null,
    descriptionPlacement: 'right',
  },
};

const SAMPLE_COPY = {
  form: { title: '表单标题', description: '一级标题描述' },
  'level-1': { title: '一级标题', description: '一级标题描述' },
  'level-2': { title: '二级标题', description: '二级标题描述' },
  'level-3': { title: '三级标题', description: '二级标题描述' },
  card: { title: '卡片标题', description: '二级标题描述' },
};

export default function FormTitle({
  variant = 'form',
  title,
  description,
  titleSuffix = null,
  showDescription = false,
  align = 'left',
  className = '',
  style,
}) {
  const resolvedVariant = VARIANT_CONFIG[variant] ? variant : 'form';
  const config = VARIANT_CONFIG[resolvedVariant];
  const resolvedAlign = align === 'center' ? 'center' : 'left';
  const layout = resolveAlignedLayout(config, resolvedAlign);
  const sample = SAMPLE_COPY[resolvedVariant];
  const resolvedTitle = title ?? sample.title;
  const resolvedDescription = description ?? sample.description;
  const shouldShowDescription = (
    showDescription
    && typeof resolvedDescription === 'string'
    && resolvedDescription.trim().length > 0
  );
  const descriptionNode = shouldShowDescription ? (
    <span className={layout.description}>{resolvedDescription}</span>
  ) : null;
  const suffixNode = titleSuffix && resolvedAlign !== 'center' ? (
    <span className="inline-flex shrink-0 items-center">{titleSuffix}</span>
  ) : null;

  const descOnRight = layout.descriptionPlacement === 'right';

  return (
    <div
      className={[`tfds-form-title`, [layout.root, className].filter(Boolean).join(' ')].filter(Boolean).join(' ')}
      style={style}
      data-tfds-component="FormTitle"
      data-tfds-align={resolvedAlign}
    >
      <div className={layout.titleWrap}>
        {config.indicator && resolvedAlign !== 'center' ? (
          <span aria-hidden="true" className={config.indicator} />
        ) : null}
        <span className={config.title}>{resolvedTitle}</span>
        {suffixNode}
        {descOnRight ? descriptionNode : null}
      </div>
      {!descOnRight ? descriptionNode : null}
    </div>
  );
}
