/**
 * PreviewModeGroup Tests
 *
 * Tests for the PreviewModeGroup component
 */

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import { IntlProvider } from 'react-intl';
import PreviewModeGroup from '../PreviewModeGroup';
import { PREVIEW_MODES } from '../../../constants';

// Mock Cap UI components
jest.mock('@capillarytech/cap-ui-library/CapButton', () => {
  return function MockCapButton({ children, onClick, disabled, className, type, value, 'aria-label': ariaLabel, 'aria-pressed': ariaPressed, ...rest }) {
    return (
      <button
        onClick={onClick}
        disabled={disabled}
        className={className}
        data-type={type}
        value={value}
        aria-label={ariaLabel}
        aria-pressed={ariaPressed}
        {...rest}
      >
        {children}
      </button>
    );
  };
});

jest.mock('@capillarytech/cap-ui-library/CapIcon', () => {
  return function MockCapIcon({ type, size }) {
    return <span data-testid={`icon-${type}`} data-size={size}>{type}</span>;
  };
});

// Test wrapper with IntlProvider
const renderWithIntl = (component) => {
  return render(
    <IntlProvider locale="en" messages={{}}>
      {component}
    </IntlProvider>
  );
};

describe('PreviewModeGroup', () => {
  const mockOnChange = jest.fn();

  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('Basic Rendering', () => {
    it('renders without crashing', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      expect(screen.getByTestId('icon-desktop')).toBeInTheDocument();
      expect(screen.getByTestId('icon-mobile')).toBeInTheDocument();
    });

    it('renders both desktop and mobile buttons', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
    });

    it('renders desktop icon', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const desktopIcon = screen.getByTestId('icon-desktop');
      expect(desktopIcon).toBeInTheDocument();
      expect(desktopIcon).toHaveAttribute('data-size', 'm');
    });

    it('renders mobile icon', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const mobileIcon = screen.getByTestId('icon-mobile');
      expect(mobileIcon).toBeInTheDocument();
      expect(mobileIcon).toHaveAttribute('data-size', 'm');
    });

    it('renders with correct container structure', () => {
      const { container } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const previewGroup = container.querySelector('.preview-mode-group');
      expect(previewGroup).toBeInTheDocument();
      expect(previewGroup).toHaveClass('preview-mode-group');
    });
  });

  describe('Active State', () => {
    it('marks desktop button as active when desktop mode is selected', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];

      expect(desktopButton).toHaveClass('preview-mode-group__btn--active');
    });

    it('marks mobile button as active when mobile mode is selected', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.MOBILE}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      expect(mobileButton).toHaveClass('preview-mode-group__btn--active');
    });

    it('only one button is active at a time', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const activeButtons = buttons.filter(btn =>
        btn.className.includes('preview-mode-group__btn--active')
      );

      expect(activeButtons).toHaveLength(1);
    });

    it('applies base class to all buttons', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toHaveClass('preview-mode-group__btn');
      });
    });
  });

  describe('User Interactions', () => {
    it('calls onChange with DESKTOP when desktop button is clicked', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.MOBILE}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];

      fireEvent.click(desktopButton);

      expect(mockOnChange).toHaveBeenCalledTimes(1);
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.DESKTOP);
    });

    it('calls onChange with MOBILE when mobile button is clicked', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      fireEvent.click(mobileButton);

      expect(mockOnChange).toHaveBeenCalledTimes(1);
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });

    it('allows clicking the already active button', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];

      fireEvent.click(desktopButton);

      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.DESKTOP);
    });

    it('handles multiple clicks', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];
      const mobileButton = buttons[1];

      fireEvent.click(mobileButton);
      fireEvent.click(desktopButton);
      fireEvent.click(mobileButton);

      expect(mockOnChange).toHaveBeenCalledTimes(3);
      expect(mockOnChange).toHaveBeenNthCalledWith(1, PREVIEW_MODES.MOBILE);
      expect(mockOnChange).toHaveBeenNthCalledWith(2, PREVIEW_MODES.DESKTOP);
      expect(mockOnChange).toHaveBeenNthCalledWith(3, PREVIEW_MODES.MOBILE);
    });
  });

  describe('Disabled State', () => {
    it('disables both buttons when disabled prop is true', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toBeDisabled();
      });
    });

    it('does not call onChange when disabled button is clicked', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      fireEvent.click(mobileButton);

      expect(mockOnChange).not.toHaveBeenCalled();
    });

    it('enables buttons when disabled prop is false', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={false}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).not.toBeDisabled();
      });
    });

    it('enables buttons by default when disabled prop is not provided', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).not.toBeDisabled();
      });
    });

    it('can transition from disabled to enabled', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[0]).toBeDisabled();

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
            disabled={false}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).not.toBeDisabled();
    });
  });

  describe('Button Types', () => {
    it('renders buttons with flat type', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toHaveAttribute('data-type', 'link');
      });
    });
  });

  describe('Value Updates', () => {
    it('updates active state when value prop changes', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
      expect(buttons[1]).not.toHaveClass('preview-mode-group__btn--active');

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).not.toHaveClass('preview-mode-group__btn--active');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
    });

    it('maintains correct state through multiple value changes', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Change to mobile
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');

      // Change back to desktop
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
    });
  });

  describe('PropTypes and Validation', () => {
    it('accepts valid PREVIEW_MODES values', () => {
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        );
      }).not.toThrow();

      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        );
      }).not.toThrow();
    });

    it('accepts onChange function', () => {
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={jest.fn()}
          />
        );
      }).not.toThrow();
    });

    it('accepts disabled boolean', () => {
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
            disabled={true}
          />
        );
      }).not.toThrow();
    });
  });

  describe('Integration with IntlProvider', () => {
    it('renders correctly within IntlProvider', () => {
      const { container } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      expect(container.firstChild).toBeInTheDocument();
    });

    it('works with different locales', () => {
      const { container: enContainer } = render(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      expect(enContainer.firstChild).toBeInTheDocument();

      const { container: jaContainer } = render(
        <IntlProvider locale="ja" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      expect(jaContainer.firstChild).toBeInTheDocument();
    });
  });

  describe('Edge Cases', () => {
    it('handles rapid successive clicks', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      // Deterministic rapid clicks - each click is processed immediately
      for (let i = 0; i < 5; i++) {
        fireEvent.click(mobileButton);
      }

      // All clicks should be processed synchronously
      expect(mockOnChange).toHaveBeenCalledTimes(5);
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });

    it('handles onChange being replaced', () => {
      const firstOnChange = jest.fn();
      const secondOnChange = jest.fn();

      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={firstOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      fireEvent.click(buttons[1]);
      expect(firstOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={secondOnChange}
          />
        </IntlProvider>
      );

      fireEvent.click(buttons[1]);
      expect(secondOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
      expect(firstOnChange).toHaveBeenCalledTimes(1);
    });
  });

  describe('Accessibility', () => {
    it('renders buttons with proper role', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
    });

    it('disabled buttons are not clickable', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toBeDisabled();
        fireEvent.click(button);
      });

      expect(mockOnChange).not.toHaveBeenCalled();
    });

    it('maintains focus management', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];

      desktopButton.focus();
      expect(document.activeElement).toBe(desktopButton);
    });

    it('supports keyboard navigation', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      // Tab through buttons
      buttons.forEach(button => {
        button.focus();
        expect(document.activeElement).toBe(button);
      });
    });
  });

  describe('Performance and Memory', () => {
    it('handles frequent re-renders efficiently', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Multiple re-renders
      for (let i = 0; i < 20; i++) {
        const value = i % 2 === 0 ? PREVIEW_MODES.DESKTOP : PREVIEW_MODES.MOBILE;
        rerender(
          <IntlProvider locale="en" messages={{}}>
            <PreviewModeGroup
              value={value}
              onChange={mockOnChange}
            />
          </IntlProvider>
        );
      }

      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
    });

    it('maintains consistent button references', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const initialButtons = screen.getAllByRole('button');

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      const updatedButtons = screen.getAllByRole('button');
      expect(updatedButtons).toHaveLength(initialButtons.length);
    });

    it('handles rapid prop changes without memory leaks', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Rapid prop changes
      for (let i = 0; i < 50; i++) {
        rerender(
          <IntlProvider locale="en" messages={{}}>
            <PreviewModeGroup
              value={i % 2 === 0 ? PREVIEW_MODES.DESKTOP : PREVIEW_MODES.MOBILE}
              onChange={mockOnChange}
              disabled={i % 3 === 0}
            />
          </IntlProvider>
        );
      }

      expect(screen.getAllByRole('button')).toHaveLength(2);
    });
  });

  describe('Component Lifecycle', () => {
    it('initializes with correct state', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
      expect(buttons[1]).not.toHaveClass('preview-mode-group__btn--active');
    });

    it('cleans up properly on unmount', () => {
      const { unmount } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      expect(() => unmount()).not.toThrow();
    });

    it('handles component updates correctly', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={false}
        />
      );

      // Update multiple props
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={jest.fn()}
            disabled={true}
          />
        </IntlProvider>
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
      expect(buttons[0]).toBeDisabled();
      expect(buttons[1]).toBeDisabled();
    });
  });

  describe('Error Handling and Edge Cases', () => {
    it('handles null onChange gracefully', () => {
      // This should not crash the component
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={null}
          />
        );
      }).not.toThrow();
    });

    it('handles undefined value gracefully', () => {
      // Component should still render even with undefined value
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={undefined}
            onChange={mockOnChange}
          />
        );
      }).not.toThrow();
    });

    it('maintains functionality with concurrent clicks', () => {
      // Use fake timers for deterministic behavior
      jest.useFakeTimers();

      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      // Simulate deterministic "concurrent" clicks using fake timers
      for (let i = 0; i < 10; i++) {
        setTimeout(() => {
          fireEvent.click(buttons[i % 2]);
        }, i * 10); // Deterministic delays: 0ms, 10ms, 20ms, etc.
      }

      // Advance timers to execute all scheduled clicks
      jest.advanceTimersByTime(100); // Advance past all scheduled timeouts

      expect(mockOnChange).toHaveBeenCalledTimes(10);

      // Restore real timers
      jest.useRealTimers();
    });

    it('handles extreme prop combinations', () => {
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
            disabled={true}
          />
        );
      }).not.toThrow();

      const buttons = screen.getAllByRole('button');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
      expect(buttons[1]).toBeDisabled();
    });
  });

  describe('Constants Integration', () => {
    it('uses PREVIEW_MODES constants correctly', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      fireEvent.click(buttons[1]);

      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });

    it('handles all valid PREVIEW_MODES values', () => {
      const modes = Object.values(PREVIEW_MODES);

      modes.forEach(mode => {
        const { unmount } = renderWithIntl(
          <PreviewModeGroup
            value={mode}
            onChange={mockOnChange}
          />
        );

        expect(screen.getAllByRole('button')).toHaveLength(2);
        unmount();
      });
    });

    it('maintains consistency with PREVIEW_MODES enum', () => {
      expect(PREVIEW_MODES.DESKTOP).toBeDefined();
      expect(PREVIEW_MODES.MOBILE).toBeDefined();
      expect(typeof PREVIEW_MODES.DESKTOP).toBe('string');
      expect(typeof PREVIEW_MODES.MOBILE).toBe('string');
    });
  });

  describe('Cap UI Integration', () => {
    it('passes correct props to CapButton components', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toHaveAttribute('data-type', 'link');
        expect(button).toBeDisabled();
      });
    });

    it('passes correct props to CapIcon components', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const desktopIcon = screen.getByTestId('icon-desktop');
      const mobileIcon = screen.getByTestId('icon-mobile');

      expect(desktopIcon).toHaveAttribute('data-size', 'm');
      expect(mobileIcon).toHaveAttribute('data-size', 'm');
      expect(desktopIcon).toHaveTextContent('desktop');
      expect(mobileIcon).toHaveTextContent('mobile');
    });

    it('maintains Cap UI component structure', () => {
      const { container } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Should have the preview-mode-group container
      expect(container.querySelector('.preview-mode-group')).toBeInTheDocument();

      // Should have buttons with Cap UI structure
      const buttons = container.querySelectorAll('button');
      expect(buttons).toHaveLength(2);
    });
  });

  describe('Styling and Layout', () => {
    it('applies correct container styles', () => {
      const { container } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const previewGroup = container.querySelector('.preview-mode-group');
      expect(previewGroup).toHaveClass('preview-mode-group');

      // Verify the container has the expected structure for CSS styling
      expect(previewGroup.tagName.toLowerCase()).toBe('div');
    });

    it('applies correct button classes based on state', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn', 'preview-mode-group__btn--active');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn');
      expect(buttons[1]).not.toHaveClass('preview-mode-group__btn--active');

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn');
      expect(buttons[0]).not.toHaveClass('preview-mode-group__btn--active');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn', 'preview-mode-group__btn--active');
    });

    it('maintains consistent layout structure', () => {
      const { container } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const previewGroup = container.querySelector('.preview-mode-group');
      const buttons = previewGroup.querySelectorAll('button');

      expect(buttons).toHaveLength(2);
      expect(previewGroup.children).toHaveLength(2);
    });
  });

  describe('Accessibility and ARIA Attributes', () => {
    it('sets correct aria-label attributes for desktop button', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const desktopButton = buttons[0];

      expect(desktopButton).toHaveAttribute('aria-label');
      expect(desktopButton).toHaveAttribute('aria-pressed', 'true');
    });

    it('sets correct aria-label attributes for mobile button', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.MOBILE}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      expect(mobileButton).toHaveAttribute('aria-label');
      expect(mobileButton).toHaveAttribute('aria-pressed', 'true');
    });

    it('updates aria-pressed attributes correctly when value changes', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveAttribute('aria-pressed', 'true');
      expect(buttons[1]).toHaveAttribute('aria-pressed', 'false');

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveAttribute('aria-pressed', 'false');
      expect(buttons[1]).toHaveAttribute('aria-pressed', 'true');
    });

    it('maintains aria attributes when disabled', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      const buttons = screen.getAllByRole('button');

      buttons.forEach(button => {
        expect(button).toHaveAttribute('aria-label');
        expect(button).toHaveAttribute('aria-pressed');
      });
    });
  });

  describe('Internationalization (i18n)', () => {
    it('formats desktop message using intl', () => {
      const customMessages = {
        'app.components.HtmlEditor.desktop': 'Desktop View',
        'app.components.HtmlEditor.mobile': 'Mobile View'
      };

      render(
        <IntlProvider locale="en" messages={customMessages}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      const buttons = screen.getAllByRole('button');
      // The aria-label should be formatted by intl
      expect(buttons[0]).toHaveAttribute('aria-label');
    });

    it('formats mobile message using intl', () => {
      const customMessages = {
        'app.components.HtmlEditor.desktop': 'Desktop View',
        'app.components.HtmlEditor.mobile': 'Mobile View'
      };

      render(
        <IntlProvider locale="en" messages={customMessages}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      const buttons = screen.getAllByRole('button');
      // The aria-label should be formatted by intl
      expect(buttons[1]).toHaveAttribute('aria-label');
    });

    it('handles missing message keys gracefully', () => {
      render(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      // Should still render without crashing even with missing messages
      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
    });

    it('works with different locale formats', () => {
      const frenchMessages = {
        'app.components.HtmlEditor.desktop': 'Vue Bureau',
        'app.components.HtmlEditor.mobile': 'Vue Mobile'
      };

      render(
        <IntlProvider locale="fr" messages={frenchMessages}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
      expect(buttons[0]).toHaveAttribute('aria-label');
    });
  });

  describe('Component Internal Functions', () => {
    it('handleChange function exists and can be called', () => {
      // Test the internal handleChange function by creating a scenario where it might be used
      const TestComponent = () => {
        const [value, setValue] = React.useState(PREVIEW_MODES.DESKTOP);

        const handleChange = (newValue) => {
          setValue(newValue);
        };

        return (
          <PreviewModeGroup
            value={value}
            onChange={handleChange}
          />
        );
      };

      render(
        <IntlProvider locale="en" messages={{}}>
          <TestComponent />
        </IntlProvider>
      );

      const buttons = screen.getAllByRole('button');
      fireEvent.click(buttons[1]);

      // Should update the state through the handleChange function
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
    });

    it('handles button click to change mode from desktop to mobile', () => {
      // Test button click interaction to change preview mode
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1]; // Second button is mobile

      fireEvent.click(mobileButton);

      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });

    it('changes preview mode through user interaction with mobile button', () => {
      // Test real component interaction - user clicking mobile button
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Find the mobile button (second button in the group)
      const buttons = screen.getAllByRole('button');
      const mobileButton = buttons[1];

      // Verify initial state - desktop should be active
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
      expect(mobileButton).not.toHaveClass('preview-mode-group__btn--active');

      // Simulate user clicking the mobile button
      fireEvent.click(mobileButton);

      // Assert that onChange was called with the correct mode
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
      expect(mockOnChange).toHaveBeenCalledTimes(1);
    });

    it('mock CapButton forwards value prop and other props to DOM button elements', () => {
      // Test that our mock CapButton properly forwards props
      const MockCapButton = jest.requireMock('@capillarytech/cap-ui-library/CapButton');

      const TestComponent = () => (
        <MockCapButton
          value={PREVIEW_MODES.DESKTOP}
          onClick={mockOnChange}
          data-testid="test-button"
          custom-attribute="test-value"
        >
          Test Button
        </MockCapButton>
      );

      render(<TestComponent />);

      const button = screen.getByTestId('test-button');

      // Check that value and custom attributes are forwarded via ...rest
      expect(button).toHaveAttribute('value', PREVIEW_MODES.DESKTOP);
      expect(button).toHaveAttribute('custom-attribute', 'test-value');
    });

    it('enables event.target.value access in event handlers', () => {
      const handleChangeWithEvent = jest.fn((e) => {
        // This test verifies that e.target.value is available
        expect(e.target.value).toBeDefined();
        mockOnChange(e.target.value);
      });

      const TestComponent = () => {
        return (
          <div>
            <button
              value={PREVIEW_MODES.MOBILE}
              onClick={handleChangeWithEvent}
              data-testid="test-button"
            >
              Test Button
            </button>
          </div>
        );
      };

      renderWithIntl(<TestComponent />);

      const testButton = screen.getByTestId('test-button');
      fireEvent.click(testButton);

      expect(handleChangeWithEvent).toHaveBeenCalled();
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });
  });

  describe('Branch Coverage Tests', () => {
    it('covers all conditional branches for desktop active state', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      let buttons = screen.getAllByRole('button');
      // Desktop button should have active class
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
      // Mobile button should not have active class
      expect(buttons[1]).not.toHaveClass('preview-mode-group__btn--active');

      // Test the opposite condition
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      // Desktop button should not have active class
      expect(buttons[0]).not.toHaveClass('preview-mode-group__btn--active');
      // Mobile button should have active class
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
    });

    it('covers all conditional branches for mobile active state', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.MOBILE}
          onChange={mockOnChange}
        />
      );

      let buttons = screen.getAllByRole('button');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
      expect(buttons[0]).not.toHaveClass('preview-mode-group__btn--active');

      // Test aria-pressed attributes
      expect(buttons[1]).toHaveAttribute('aria-pressed', 'true');
      expect(buttons[0]).toHaveAttribute('aria-pressed', 'false');

      // Switch to desktop to test the other branch
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveAttribute('aria-pressed', 'true');
      expect(buttons[1]).toHaveAttribute('aria-pressed', 'false');
    });

    it('covers disabled prop branches', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
          disabled={true}
        />
      );

      let buttons = screen.getAllByRole('button');
      buttons.forEach(button => {
        expect(button).toBeDisabled();
      });

      // Test enabled state
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={mockOnChange}
            disabled={false}
          />
        </IntlProvider>
      );

      buttons = screen.getAllByRole('button');
      buttons.forEach(button => {
        expect(button).not.toBeDisabled();
      });
    });

    it('covers className conditional branches thoroughly', () => {
      // Test all combinations of active states and class assignments
      const testCases = [
        { value: PREVIEW_MODES.DESKTOP, expectedActiveIndex: 0 },
        { value: PREVIEW_MODES.MOBILE, expectedActiveIndex: 1 }
      ];

      testCases.forEach(({ value, expectedActiveIndex }) => {
        const { unmount } = renderWithIntl(
          <PreviewModeGroup
            value={value}
            onChange={mockOnChange}
          />
        );

        const buttons = screen.getAllByRole('button');

        buttons.forEach((button, index) => {
          expect(button).toHaveClass('preview-mode-group__btn');

          if (index === expectedActiveIndex) {
            expect(button).toHaveClass('preview-mode-group__btn--active');
          } else {
            expect(button).not.toHaveClass('preview-mode-group__btn--active');
          }
        });

        unmount();
      });
    });
  });

  describe('Advanced Edge Cases', () => {
    it('handles component re-mounting', () => {
      const { unmount } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      unmount();

      // Re-mount with new render call
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.MOBILE}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');
      expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
    });

    it('handles invalid PREVIEW_MODES values gracefully', () => {
      // Test with an invalid value
      expect(() => {
        renderWithIntl(
          <PreviewModeGroup
            value="invalid-mode"
            onChange={mockOnChange}
          />
        );
      }).not.toThrow();

      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);
    });

    it('maintains functionality with complex prop combinations', () => {
      const complexProps = {
        value: PREVIEW_MODES.DESKTOP,
        onChange: mockOnChange,
        disabled: false
      };

      renderWithIntl(<PreviewModeGroup {...complexProps} />);

      const buttons = screen.getAllByRole('button');
      fireEvent.click(buttons[1]);

      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });

    it('handles onChange function replacement during lifecycle', () => {
      const firstHandler = jest.fn();
      const secondHandler = jest.fn();

      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={firstHandler}
        />
      );

      const buttons = screen.getAllByRole('button');
      fireEvent.click(buttons[1]);
      expect(firstHandler).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);

      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.DESKTOP}
            onChange={secondHandler}
          />
        </IntlProvider>
      );

      fireEvent.click(buttons[1]);
      expect(secondHandler).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
      expect(firstHandler).toHaveBeenCalledTimes(1);
    });
  });

  describe('Component State Management', () => {
    it('maintains consistent state across re-renders', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Multiple re-renders with same props
      for (let i = 0; i < 5; i++) {
        rerender(
          <IntlProvider locale="en" messages={{}}>
            <PreviewModeGroup
              value={PREVIEW_MODES.DESKTOP}
              onChange={mockOnChange}
            />
          </IntlProvider>
        );
      }

      const buttons = screen.getAllByRole('button');
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
    });

    it('handles state transitions correctly', () => {
      const states = [
        PREVIEW_MODES.DESKTOP,
        PREVIEW_MODES.MOBILE,
        PREVIEW_MODES.DESKTOP,
        PREVIEW_MODES.MOBILE
      ];

      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={states[0]}
          onChange={mockOnChange}
        />
      );

      states.forEach((state, index) => {
        rerender(
          <IntlProvider locale="en" messages={{}}>
            <PreviewModeGroup
              value={state}
              onChange={mockOnChange}
            />
          </IntlProvider>
        );

        const buttons = screen.getAllByRole('button');
        if (state === PREVIEW_MODES.DESKTOP) {
          expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');
        } else {
          expect(buttons[1]).toHaveClass('preview-mode-group__btn--active');
        }
      });
    });
  });

  describe('Real-world Usage Scenarios', () => {
    it('supports typical preview mode switching workflow', () => {
      const { rerender } = renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      const buttons = screen.getAllByRole('button');

      // User starts with desktop, switches to mobile
      expect(buttons[0]).toHaveClass('preview-mode-group__btn--active');

      fireEvent.click(buttons[1]);
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);

      // Simulate parent updating value to mobile
      rerender(
        <IntlProvider locale="en" messages={{}}>
          <PreviewModeGroup
            value={PREVIEW_MODES.MOBILE}
            onChange={mockOnChange}
          />
        </IntlProvider>
      );

      const updatedButtons = screen.getAllByRole('button');
      expect(updatedButtons[1]).toHaveClass('preview-mode-group__btn--active');
      expect(updatedButtons[0]).not.toHaveClass('preview-mode-group__btn--active');
    });

    it('supports editor toolbar integration', () => {
      // Simulate being used within a larger toolbar
      const { container } = render(
        <IntlProvider locale="en" messages={{}}>
          <div className="editor-toolbar">
            <div className="toolbar-section">
              <PreviewModeGroup
                value={PREVIEW_MODES.DESKTOP}
                onChange={mockOnChange}
              />
            </div>
          </div>
        </IntlProvider>
      );

      expect(container.querySelector('.editor-toolbar')).toBeInTheDocument();
      expect(container.querySelector('.preview-mode-group')).toBeInTheDocument();
    });

    it('supports responsive design scenarios', () => {
      renderWithIntl(
        <PreviewModeGroup
          value={PREVIEW_MODES.DESKTOP}
          onChange={mockOnChange}
        />
      );

      // Component should maintain functionality regardless of container size
      const buttons = screen.getAllByRole('button');
      expect(buttons).toHaveLength(2);

      // Should work in different viewport scenarios
      fireEvent.click(buttons[1]);
      expect(mockOnChange).toHaveBeenCalledWith(PREVIEW_MODES.MOBILE);
    });
  });
});


