import type React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { HighlightsPanel } from '../src/platform/features/record/components/HighlightsPanel';
import { RecordLink } from '../src/platform/components/RecordLink';
import { UIRegistry, type FieldRendererProps } from '../src/platform/registries/FieldUiRegistry';
import type { PageLayout, SObject, SObjectField } from '../src/platform/types';
import { createCrmUiFieldComponents, type CrmUiFieldHost } from '../src/ui-field-components';

// The highlights panel and the Details form show the same fields. A lookup that
// is a link in the form must also be a link in the highlights panel — otherwise
// the same field looks clickable in one place and inert in another. The panel
// only renders lookups as links when it is given an onNavigate callback.

const host: CrmUiFieldHost = {
  SearchableLookup: () => null,
  RecordLink,
  decodeHtmlEntities: value => value,
  formatCurrency: value => String(value),
  formatDate: value => value,
  formatDateTime: value => value,
  getRecordValue: (record, fieldName) => record?.[fieldName],
  parseMultipicklistSelections: value => (Array.isArray(value) ? value.map(String) : []),
  joinMultipicklistSelections: values => values.join(';'),
};

const { fieldRenderers } = createCrmUiFieldComponents(host);

const opportunityField: SObjectField = {
  name: 'OpportunityId',
  label: 'Opportunity',
  type: 'reference',
  referenceTo: ['Opportunity'],
  custom: false,
  readable: true,
  createable: true,
  updateable: true,
  nillable: true,
};

const record: SObject = {
  Id: '0Q0000000000001',
  OpportunityId: '006000000000001',
  OpportunityId_Name: 'Big Expansion Deal',
};

const layout = { compactLayout: ['OpportunityId'] } as unknown as PageLayout;

beforeEach(() => {
  UIRegistry.registerFieldRenderer(
    'reference',
    fieldRenderers.reference as unknown as React.FC<FieldRendererProps>,
  );
});

afterEach(() => {
  UIRegistry.clear();
});

describe('HighlightsPanel lookup link consistency', () => {
  it('renders a lookup as a navigable anchor (matching the Details form) when onNavigate is provided', () => {
    const onNavigate = vi.fn();
    render(
      <HighlightsPanel
        record={record}
        layout={layout}
        fields={[opportunityField]}
        objectApiName="Quote"
        onNavigate={onNavigate}
      />,
    );

    const link = screen.getByRole('link', { name: 'Big Expansion Deal' });
    expect(link).toHaveAttribute('href', '/object/Opportunity/006000000000001');

    // The lookup renderer emits a block <div>; the highlights value wrapper must
    // therefore be a <div>, not a <span> (a <div> inside a <span> is invalid DOM
    // nesting). Assert the link's nearest value wrapper is a div, not a span.
    const valueWrapper = link.closest('.text-sm');
    expect(valueWrapper?.tagName).toBe('DIV');
    expect(link.closest('span.text-sm')).toBeNull();

    fireEvent.click(link);
    expect(onNavigate).toHaveBeenCalledWith('Opportunity', '006000000000001');
  });

  it('falls back to plain text when no onNavigate is provided', () => {
    render(
      <HighlightsPanel
        record={record}
        layout={layout}
        fields={[opportunityField]}
        objectApiName="Quote"
      />,
    );

    expect(screen.getByText('Big Expansion Deal')).toBeInTheDocument();
    expect(screen.queryByRole('link')).toBeNull();
    expect(screen.queryByRole('button')).toBeNull();
  });
});
