import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { AboutModal } from './AboutModal';

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

let container: HTMLDivElement;
let root: Root;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
  root = createRoot(container);
  act(() => root.render(<AboutModal />));
});

afterEach(() => {
  act(() => root.unmount());
  container.remove();
});

describe('AboutModal', () => {
  test('renders the app name', () => {
    expect(container.textContent).toContain('Astrolabe');
  });

  test('renders the app version from __APP_VERSION__', () => {
    // __APP_VERSION__ is injected by vite.config.ts `define` (shared with Vitest).
    expect(container.textContent).toContain(__APP_VERSION__);
  });

  test('renders all five keyboard shortcuts from spec §01D', () => {
    // Platform-specific modifier (Cmd on Mac, Ctrl elsewhere) + the five actions.
    const text = container.textContent ?? '';
    // Key combinations — platform-aware modifier is either ⌘ or Ctrl
    expect(text).toMatch(/(?:⌘|Ctrl)\+Shift\+N/);
    expect(text).toMatch(/(?:⌘|Ctrl)\+K/);
    expect(text).toMatch(/(?:⌘|Ctrl)\+S/);
    expect(text).toMatch(/(?:⌘|Ctrl)\+,/);
    expect(text).toContain('Esc');
  });

  test('shortcuts are in an accessible table with an aria-label', () => {
    const table = container.querySelector('table[aria-label]');
    expect(table).not.toBeNull();
    expect(table!.getAttribute('aria-label')).toBe('Keyboard shortcuts');
  });

  test('renders a Privacy section that mentions local-first posture', () => {
    const text = container.textContent ?? '';
    // Core privacy claims from SOUL.md / spec §10
    expect(text).toMatch(/no account/i);
    expect(text).toMatch(/no telemetry|no analytics|no tracking/i);
    expect(text).toMatch(/offline/i);
  });

  test('has three labelled sections: identity, shortcuts, privacy', () => {
    const headings = Array.from(container.querySelectorAll('h3')).map(
      (h) => h.textContent?.toLowerCase() ?? '',
    );
    expect(headings.some((h) => h.includes('astrolabe'))).toBe(true);
    expect(headings.some((h) => h.includes('keyboard'))).toBe(true);
    expect(headings.some((h) => h.includes('privacy'))).toBe(true);
  });
});
