// Copyright (c) Meta Platforms, Inc. and affiliates.

import {render, screen} from '@testing-library/react';
import {describe, expect, it, vi} from 'vitest';
import {LineClamp} from './LineClamp';

function withHorizontalOverflow() {
  const proto = window.HTMLElement.prototype;
  const scrollWidth = Object.getOwnPropertyDescriptor(proto, 'scrollWidth');
  const offsetWidth = Object.getOwnPropertyDescriptor(proto, 'offsetWidth');
  Object.defineProperty(proto, 'scrollWidth', {
    configurable: true,
    get: () => 400,
  });
  Object.defineProperty(proto, 'offsetWidth', {
    configurable: true,
    get: () => 100,
  });
  return () => {
    if (scrollWidth) Object.defineProperty(proto, 'scrollWidth', scrollWidth);
    if (offsetWidth) Object.defineProperty(proto, 'offsetWidth', offsetWidth);
  };
}

describe('LineClamp review regressions', () => {
  it('shows one tooltip rather than native title plus Tooltip', () => {
    const restore = withHorizontalOverflow();
    try {
      render(<LineClamp maxLines={1}>A long clamped label</LineClamp>);
      expect(screen.getByText('A long clamped label')).not.toHaveAttribute(
        'title',
      );
    } finally {
      restore();
    }
  });

  it('keeps a forwarded ref attached across rerenders', () => {
    const ref = vi.fn();
    const {rerender} = render(
      <LineClamp ref={ref} maxLines={2}>
        Before
      </LineClamp>,
    );
    const element = screen.getByText('Before');
    expect(ref).toHaveBeenLastCalledWith(element);
    ref.mockClear();

    rerender(
      <LineClamp ref={ref} maxLines={2}>
        After
      </LineClamp>,
    );

    expect(ref).not.toHaveBeenCalled();
    expect(screen.getByText('After')).toBe(element);
  });
});
