import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, test } from 'vitest';
import appV2Source from './AppV2.tsx?raw';
import indexSource from '../../index.html?raw';
import mainSource from '../main.tsx?raw';

const v2Styles = readFileSync(resolve(process.cwd(), 'src/v2/styles/v2.css'), 'utf8');

describe('V2 production entry', () => {
  test('does not load the legacy Semi UI theme and global stylesheet', () => {
    expect(mainSource).not.toContain("./styles/global.css");
    expect(mainSource).toContain("./v2/styles/v2.css");
  });

  test('renders a static boot shell and recovers when the React entry never becomes ready', () => {
    expect(indexSource).toContain('id="platform-boot"');
    expect(indexSource).toContain('rel="icon" type="image/svg+xml" href="/brand-mark.svg"');
    expect(indexSource).toContain('<title>羚牛车辆数据中台</title>');
    expect(indexSource).toContain('class="platform-boot-logo" src="/brand-logo.svg"');
    expect(indexSource).toContain("window.addEventListener('error', fail, true)");
    expect(indexSource).toContain("window.addEventListener('unhandledrejection', fail)");
    expect(indexSource).toContain('window.setTimeout(fail, 10_000)');
    expect(indexSource).toContain("target.searchParams.set('__reload', String(Date.now()))");
    expect(appV2Source).toContain("export const PLATFORM_READY_EVENT = 'vehicle-platform:ready'");
    expect(appV2Source).toContain('window.dispatchEvent(new Event(PLATFORM_READY_EVENT))');
  });

  test('applies rendering containment to off-screen vehicle items instead of the visible scroller', () => {
    const ruleBody = (selector: string) => {
      const start = v2Styles.indexOf(`${selector} {`);
      expect(start).toBeGreaterThanOrEqual(0);
      const end = v2Styles.indexOf('}', start);
      expect(end).toBeGreaterThan(start);
      return v2Styles.slice(start, end);
    };
    const scrollRule = ruleBody('.v2-vehicle-scroll');
    const rowRule = ruleBody('.v2-vehicle-row');
    const mobileCardRule = ruleBody('.v2-monitor-mobile-cards > article');

    expect(scrollRule).not.toContain('content-visibility');
    expect(rowRule).toContain('content-visibility: auto');
    expect(rowRule).toContain('contain-intrinsic-size: auto 60px');
    expect(mobileCardRule).toContain('content-visibility: auto');
    expect(mobileCardRule).toContain('contain-intrinsic-size: auto 154px');
  });
});
