// components/__tests__/DealerScripts.test.tsx
import { render } from '@testing-library/react';
import { DealerScripts } from '../DealerScripts';

// Mock next/script since it has special behavior in tests
jest.mock('next/script', () => {
  return function MockScript({
    id,
    src,
    strategy,
    onLoad,
    onError,
    dangerouslySetInnerHTML,
    ...props
  }: {
    id: string;
    src?: string;
    strategy?: string;
    onLoad?: () => void;
    onError?: () => void;
    dangerouslySetInnerHTML?: { __html: string };
    [key: string]: unknown;
  }) {
    return (
      <script
        data-testid={`mock-script-${id}`}
        data-src={src}
        data-strategy={strategy}
        data-has-inline={dangerouslySetInnerHTML ? 'true' : 'false'}
        {...props}
      />
    );
  };
});

describe('DealerScripts', () => {
  it('renders nothing when no scripts provided', () => {
    const { container } = render(<DealerScripts />);
    expect(container.querySelectorAll('script')).toHaveLength(0);
  });

  it('renders nothing for null scripts', () => {
    const { container } = render(
      <DealerScripts headScripts={null} bodyScripts={null} />
    );
    expect(container.querySelectorAll('script')).toHaveLength(0);
  });

  it('renders external script with afterInteractive strategy', () => {
    const { container } = render(
      <DealerScripts
        headScripts='<script src="https://example.com/script.js"></script>'
      />
    );

    const script = container.querySelector('script');
    expect(script).toBeTruthy();
    expect(script?.getAttribute('data-src')).toBe('https://example.com/script.js');
    expect(script?.getAttribute('data-strategy')).toBe('afterInteractive');
  });

  it('renders inline script with dangerouslySetInnerHTML', () => {
    const { container } = render(
      <DealerScripts
        headScripts='<script>console.log("test");</script>'
      />
    );

    const script = container.querySelector('script');
    expect(script).toBeTruthy();
    expect(script?.getAttribute('data-has-inline')).toBe('true');
  });

  it('renders multiple scripts from both head and body', () => {
    const { container } = render(
      <DealerScripts
        headScripts='<script src="https://head.com/a.js"></script>'
        bodyScripts='<script src="https://body.com/b.js"></script>'
      />
    );

    const scripts = container.querySelectorAll('script');
    expect(scripts).toHaveLength(2);
  });

  it('passes data attributes through to script', () => {
    const { container } = render(
      <DealerScripts
        headScripts='<script src="https://example.com/script.js" data-api-key="abc123"></script>'
      />
    );

    const script = container.querySelector('script');
    expect(script?.getAttribute('data-api-key')).toBe('abc123');
  });
});
