import { describe, it, expect } from 'vitest';
import { htmlToText } from './html.js';

describe('htmlToText', () => {
  it('script と style タグを除去する', () => {
    const html = '<p>Hello</p><script>alert("x")</script><style>.a{}</style><p>World</p>';
    const result = htmlToText(html);
    expect(result).not.toContain('alert');
    expect(result).not.toContain('.a{}');
    expect(result).toContain('Hello');
    expect(result).toContain('World');
  });

  it('nav, footer, header を除去する', () => {
    const html = '<nav>Nav</nav><main>Content</main><footer>Footer</footer>';
    const result = htmlToText(html);
    expect(result).not.toContain('Nav');
    expect(result).not.toContain('Footer');
    expect(result).toContain('Content');
  });

  it('ブロック要素の前後に改行を入れる', () => {
    const html = '<p>First</p><p>Second</p>';
    const result = htmlToText(html);
    expect(result).toContain('First');
    expect(result).toContain('Second');
    expect(result).toMatch(/First\n+Second/);
  });

  it('HTML エンティティをデコードする', () => {
    const html = '<p>&amp; &lt; &gt; &quot; &#39; &nbsp;</p>';
    const result = htmlToText(html);
    expect(result).toContain('& < > "');
    expect(result).toContain("'");
  });

  it('3行以上の連続空行を2行に正規化する', () => {
    const html = '<p>A</p><br><br><br><br><br><p>B</p>';
    const result = htmlToText(html);
    expect(result).not.toMatch(/\n{3,}/);
  });

  it('10000文字超で切り捨てる', () => {
    const html = '<p>' + 'a'.repeat(15000) + '</p>';
    const result = htmlToText(html);
    const truncationSuffix = '\n... (truncated)';
    expect(result.length).toBeLessThanOrEqual(10000 + truncationSuffix.length);
    expect(result).toContain('... (truncated)');
  });

  it('空文字列を渡すと空文字列を返す', () => {
    expect(htmlToText('')).toBe('');
  });
});
