/**
 * @vitest-environment happy-dom
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import BuildManagerPage, {
  fmtSize,
  platformColor,
  platformLabel,
  truncateUrl,
  truncateWallet,
} from './BuildManagerPage';
import { api } from '../api/client';
import { routerFuture } from '../routerFuture';

vi.mock('../components/Fleet/LanDownloadQR', () => ({
  LanDownloadQR: () => <div data-testid="lan-qr-mock" />,
}));

describe('BuildManagerPage helpers', () => {
  it('truncateWallet shortens long addresses', () => {
    const w = '4' + 'A'.repeat(94);
    expect(truncateWallet(w)).toMatch(/^4AAAAA…AAAAAA$/);
    expect(truncateWallet('short')).toBe('short');
    expect(truncateWallet('')).toBe('—');
  });

  it('truncateUrl returns host for valid URLs', () => {
    expect(truncateUrl('https://pool.example.com:3333/path')).toBe('pool.example.com:3333');
    expect(truncateUrl('not-a-url-but-long-enough-to-truncate-xyz')).toMatch(/…$/);
  });

  it('fmtSize formats bytes to KB and MB', () => {
    expect(fmtSize(0)).toBe('—');
    expect(fmtSize(512)).toBe('1 KB');
    expect(fmtSize(2 * 1024 * 1024)).toBe('2.0 MB');
  });

  it('platformLabel and platformColor map known platforms', () => {
    expect(platformLabel('linux')).toBe('Linux');
    expect(platformLabel()).toBe('Win');
    expect(platformColor('darwin')).toBe('#f0abfc');
    expect(platformColor('unknown-os')).toBe('#aaa');
  });
});

describe('BuildManagerPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.spyOn(api, 'listBuilds').mockResolvedValue([
      {
        id: 'build-1',
        worker_name: 'office-worker',
        server_url: 'https://c2.example.com',
        wallet: '4' + 'A'.repeat(94),
        threads: 4,
        file_size: 1024 * 1024,
        file_path: 'builds/agent.exe',
        file_name: 'agent.exe',
        created_at: '2026-05-30T12:00:00.000Z',
        pool_host: 'pool.example.com',
        pool_port: 3333,
        pool_tls: false,
        pool_pass: 'x',
        platform: 'windows',
        download_url: '/api/v1/builds/build-1/download',
      },
    ]);
    vi.spyOn(api, 'getServerInfo').mockResolvedValue({
      port: 8989,
      host: '0.0.0.0',
      local_ips: [],
      suggested_url: 'http://localhost:8989',
      dashboard_url: 'http://localhost:8989/dashboard',
      websocket_url: 'ws://localhost:8989/ws/dashboard',
    });
  });

  afterEach(() => {
    cleanup();
  });

  it('renders build list after load', async () => {
    render(
      <MemoryRouter future={routerFuture}>
        <BuildManagerPage />
      </MemoryRouter>
    );
    await waitFor(() => {
      expect(screen.getByText('office-worker')).toBeTruthy();
    });
  });
});
