import { afterEach, describe, expect, it } from 'vitest';
import { colorToHex, buildFloatingUiConfig } from '../src/services/automation/floatingUiConfig';
import { lightTheme, darkTheme } from '../src/theme/presets';
import { setLocale, t } from '../src/i18n';

// 共享 i18n 单例：无论断言是否失败都还原 locale，避免泄漏给后续测试文件
afterEach(() => setLocale('zh'));

describe('colorToHex', () => {
  it("'#RRGGBB' 原样返回", () => {
    expect(colorToHex('#111318')).toBe('#111318');
    expect(colorToHex('#E5E7EB')).toBe('#E5E7EB');
  });

  it("'rgba(r,g,b,a)' → '#AARRGGBB'（alpha 四舍五入）", () => {
    expect(colorToHex('rgba(255,255,255,0.08)')).toBe('#14FFFFFF');
    expect(colorToHex('rgba(17,19,24,0.4)')).toBe('#66111318');
    expect(colorToHex('rgba(0,0,0,0.7)')).toBe('#B3000000');
  });

  it('其它格式原样返回', () => {
    expect(colorToHex('red')).toBe('red');
    expect(colorToHex('rgb(1,2,3)')).toBe('rgb(1,2,3)');
  });
});

describe('buildFloatingUiConfig', () => {
  it('lightTheme colors 映射正确', () => {
    setLocale('zh');
    const config = buildFloatingUiConfig(lightTheme, t);
    expect(config.colors.accent).toBe('#111318');
    expect(config.colors.accentFg).toBe('#FFFFFF');
    expect(config.colors.cardBg).toBe('#FFFFFF');
    expect(config.colors.inputBg).toBe('#EFF1F4');
    expect(config.colors.fgPrimary).toBe('#111318');
    expect(config.colors.fgSecondary).toBe('#565F6D');
    expect(config.colors.border).toBe('#E5E7EB');
    expect(config.colors.income).toBe('#10B981');
    expect(config.colors.expense).toBe('#EF4444');
    expect(config.colors.transfer).toBe('#3B82F6');
  });

  it('darkTheme 的 rgba border 转换为 #AARRGGBB', () => {
    const config = buildFloatingUiConfig(darkTheme, t);
    expect(config.colors.border).toBe('#14FFFFFF');
    expect(config.colors.accent).toBe('#F3F4F6');
  });

  it('labels 使用 floating.* 文案且所有契约字段非空', () => {
    setLocale('zh');
    const config = buildFloatingUiConfig(lightTheme, t);
    expect(config.labels.billTitle).toBe('调整交易草稿');
    expect(config.labels.confirm).toBe('确认入账');
    expect(config.labels.ballOcr).toBe('识别账单');
    for (const [key, value] of Object.entries(config.labels)) {
      expect(typeof value, `labels.${key} 应为字符串`).toBe('string');
      expect(value.length, `labels.${key} 不应为空`).toBeGreaterThan(0);
      expect(value, `labels.${key} 不应是 missing 标记`).not.toContain('[missing');
    }
    for (const [key, value] of Object.entries(config.colors)) {
      expect(value, `colors.${key} 应为 hex`).toMatch(/^#[0-9A-F]{6,8}$/);
    }
  });

  it('英文 locale 下 labels 为英文', () => {
    setLocale('en');
    const config = buildFloatingUiConfig(lightTheme, t);
    expect(config.labels.billTitle).toBe('Adjust Draft');
    expect(config.labels.ballOcr).toBe('Scan Bill');
  });
});
