import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import MonacoEditor from './MonacoEditor';

const storeState = vi.hoisted(() => ({
  fontSize: 14,
    appearance: {
      enabled: true,
      opacity: 1,
      blur: 0,
      uiVersion: 'v2' as 'legacy' | 'v2',
      customUIFontFamily: null as string | null,
      customMonoFontFamily: null as string | null,
      showDataTableVerticalBorders: false,
      dataTableDensity: 'comfortable' as const,
      dataTableFontSize: null as number | null,
    dataTableFontSizeFollowGlobal: true,
    sidebarTreeFontSize: null as number | null,
    sidebarTreeFontSizeFollowGlobal: true,
  },
}));

vi.mock('../store', () => ({
  useStore: (selector: (state: typeof storeState) => any) => selector(storeState),
}));

vi.mock('@monaco-editor/react', () => ({
  loader: { config: vi.fn() },
  default: ({ options }: { options?: Record<string, unknown> }) => (
    <div data-monaco-options={JSON.stringify(options || {})} />
  ),
}));

describe('MonacoEditor typography', () => {
  beforeEach(() => {
    storeState.fontSize = 14;
    storeState.appearance = {
      enabled: true,
      opacity: 1,
      blur: 0,
      uiVersion: 'v2',
      customUIFontFamily: null,
      customMonoFontFamily: null,
      showDataTableVerticalBorders: false,
      dataTableDensity: 'comfortable',
      dataTableFontSize: null,
      dataTableFontSizeFollowGlobal: true,
      sidebarTreeFontSize: null,
      sidebarTreeFontSizeFollowGlobal: true,
    };
  });

  it('injects v2 code-editor typography when font settings are not explicitly provided', () => {
    const markup = renderToStaticMarkup(
      <MonacoEditor options={{ minimap: { enabled: false } }} />,
    );

    expect(markup).toContain('JetBrains Mono');
    expect(markup).toContain('ui-monospace');
    expect(markup).toContain('&quot;fontSize&quot;:13');
    expect(markup).toContain('&quot;lineHeight&quot;:21');
  });

  it('uses data-table font size for data-oriented editors in v2', () => {
    storeState.fontSize = 16;
    storeState.appearance.dataTableFontSizeFollowGlobal = false;
    storeState.appearance.dataTableFontSize = 15;

    const markup = renderToStaticMarkup(
      <MonacoEditor gonaviTypography="data" options={{ lineNumbers: 'off' }} />,
    );

    expect(markup).toContain('&quot;fontSize&quot;:15');
    expect(markup).toContain('&quot;lineHeight&quot;:24');
  });

  it('keeps legacy editors on their explicit font settings', () => {
    storeState.appearance.uiVersion = 'legacy';

    const markup = renderToStaticMarkup(
      <MonacoEditor options={{ fontFamily: 'Consolas', fontSize: 18 }} />,
    );

    expect(markup).toContain('&quot;fontFamily&quot;:&quot;Consolas&quot;');
    expect(markup).toContain('&quot;fontSize&quot;:18');
    expect(markup).not.toContain('JetBrains Mono');
  });
});
