import React from "react";
import { render, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom";
import { IntlProvider } from "react-intl";
import PlatformContentFields from "../PlatformContentFields";
import {
  ANDROID, IOS, DEEP_LINK, EXTERNAL_LINK,
} from "../../constants";

// Simple mock components
jest.mock("@capillarytech/cap-ui-library/CapRow", () => ({ children }) => <div>{children}</div>);
jest.mock("@capillarytech/cap-ui-library/CapColumn", () => ({ children }) => <div>{children}</div>);
jest.mock("@capillarytech/cap-ui-library/CapInput", () => {
  const MockCapInput = ({
    value, onChange, errorMessage, error, ...props
  }) => (
    <div>
      <input value={value || ""} onChange={onChange} error={error} {...props} />
      {(errorMessage || error) && <div data-testid="error-message">{errorMessage || error}</div>}
    </div>
  );

  MockCapInput.TextArea = ({
    value, onChange, errorMessage, error, ...props
  }) => (
    <div>
      <textarea
        value={value || ""}
        onChange={onChange}
        data-testid="message-textarea"
        {...props}
      />
      {(errorMessage || error) && <div data-testid="error-message">{errorMessage || error}</div>}
    </div>
  );

  return MockCapInput;
});
jest.mock("@capillarytech/cap-ui-library/CapHeading", () => ({ children }) => <div>{children}</div>);
jest.mock("@capillarytech/cap-ui-library/CapError", () => ({ children }) => <div data-testid="cap-error">{children}</div>);
jest.mock("@capillarytech/cap-ui-library/CapDivider", () => () => <div data-testid="divider" />);
jest.mock("@capillarytech/cap-ui-library/CapSelect", () => ({
  CapCustomSelect: ({ value, onChange, options }) => (
    <select value={value} onChange={(e) => onChange && onChange(e.target.value)}>
      {options?.map((option) => (
        <option key={option.value} value={option.value}>
          {option.label}
        </option>
      ))}
    </select>
  ),
}));
jest.mock("@capillarytech/cap-ui-library/CapCheckbox", () => ({ checked, onChange, children }) => (
  <div>
    <input type="checkbox" checked={checked} onChange={onChange} data-testid="action-checkbox" />
    <span>{children}</span>
  </div>
));
jest.mock("@capillarytech/cap-ui-library/CapLabel", () => ({ children }) => <label>{children}</label>);
jest.mock("@capillarytech/cap-ui-library/CapInfoNote", () => ({ message }) => <div data-testid="info-note">{message}</div>);

// Mock child components
jest.mock("../../../TagList", () => ({
  onTagSelect, onContextChange, label, disabled, disableTooltipMsg, ...props
}) => (
  <div data-testid="tag-list" data-disabled={disabled || false} data-tooltip={disableTooltipMsg || ''}>
    <button
      type="button"
      onClick={() => onTagSelect && onTagSelect('test_tag')}
      data-testid="tag-select-button"
    >
      Select Tag
    </button>
    <button
      type="button"
      onClick={() => onContextChange && onContextChange('test_context')}
      data-testid="tag-context-button"
    >
      Change Context
    </button>
    <span data-testid="tag-label">{label}</span>
  </div>
));
jest.mock("../MediaUploaders", () => () => <div data-testid="media-uploaders">MediaUploaders</div>);
jest.mock("../CtaButtons", () => () => <div data-testid="cta-buttons">CtaButtons</div>);

// Mock messages
jest.mock("../../messages", () => ({
  sameContentNote: { id: "sameContentNote", defaultMessage: "Same content note" },
  title: { id: "title", defaultMessage: "Title" },
  titlePlaceholder: { id: "titlePlaceholder", defaultMessage: "Enter title" },
  message: { id: "message", defaultMessage: "Message" },
  messagePlaceholder: { id: "messagePlaceholder", defaultMessage: "Enter message" },
  mediaType: { id: "mediaType", defaultMessage: "Media Type" },
  buttonsAndLinks: { id: "buttonsAndLinks", defaultMessage: "Buttons and Links" },
  optionalText: { id: "optionalText", defaultMessage: "Optional" },
  actionOnClickBody: { id: "actionOnClickBody", defaultMessage: "Action on click" },
  actionDescription: { id: "actionDescription", defaultMessage: "Action description" },
  linkType: { id: "linkType", defaultMessage: "Link Type" },
  selectDeepLink: { id: "selectDeepLink", defaultMessage: "Select deep link" },
  deepLink: { id: "deepLink", defaultMessage: "Deep Link" },
  externalLink: { id: "externalLink", defaultMessage: "External Link" },
  enterExternalLink: { id: "enterExternalLink", defaultMessage: "Enter external link" },
  deepLinkKeys: { id: "deepLinkKeys", defaultMessage: "Deep Link Keys" },
  deepLinkKeysPlaceholder: { id: "deepLinkKeysPlaceholder", defaultMessage: "Enter {key}" },
  deepLinkKeysRequired: { id: "deepLinkKeysRequired", defaultMessage: "Deep link keys are required" },
  addLabels: { id: "addLabels", defaultMessage: "Add labels" },
  personalizationTagsErrorMessage: { id: "personalizationTagsErrorMessage", defaultMessage: "Personalization tags are not supported for anonymous customers, please remove the tags." },
  personalizationNotSupportedAnonymous: { id: "personalizationNotSupportedAnonymous", defaultMessage: "Personalization tags are not supported for anonymous customers" },
}));

// Mock constants
jest.mock("../../constants", () => ({
  ANDROID: "android",
  IOS: "ios",
  CAROUSEL: "CAROUSEL",
  MEDIA_TYPES_OPTIONS: [
    { value: "IMAGE", label: "Image" },
    { value: "VIDEO", label: "Video" },
    { value: "CAROUSEL", label: "Carousel" },
  ],
  LINK_TYPE_OPTIONS: [
    { value: "DEEP_LINK", label: "Deep Link" },
    { value: "EXTERNAL_LINK", label: "External Link" },
  ],
  DEEP_LINK: "DEEP_LINK",
  EXTERNAL_LINK: "EXTERNAL_LINK",
}));

describe("PlatformContentFields", () => {
  const defaultProps = {
    deviceType: ANDROID,
    content: {
      title: "Test Title",
      message: "Test Message",
      mediaType: "IMAGE",
      actionOnClick: false,
      linkType: DEEP_LINK,
    },
    errors: {
      title: "",
      message: "",
      externalLink: "",
      deepLinkKeys: "",
    },
    handlers: {
      handleTitleChange: jest.fn(),
      handleMessageChange: jest.fn(),
      handleMediaTypeChange: jest.fn(),
      handleActionOnClickChange: jest.fn(),
      handleLinkTypeChange: jest.fn(),
      handleDeepLinkChange: jest.fn(),
      handleDeepLinkKeysChange: jest.fn(),
      handleExternalLinkChange: jest.fn(),
      onTagSelect: jest.fn(),
      handleOnTagsContextChange: jest.fn(),
    },
    tagListProps: {
      tags: ["tag1", "tag2"],
    },
    mediaUploaderProps: {
      uploadProps: "test",
    },
    ctaButtonProps: {
      buttons: [],
    },
    linkProps: {
      deepLink: [
        { value: "link1", label: "Link 1" },
        { value: "link2", label: "Link 2" },
      ],
      deepLinkValue: "link1",
      deepLinkKeysValue: [],
      externalLinkValue: "https://example.com",
    },
    sameContent: false,
    formatMessage: jest.fn((msg) => msg.defaultMessage),
    location: { query: {} },
    tags: ["tag1", "tag2"],
    injectedTags: [],
    selectedOfferDetails: null,
    restrictPersonalization: false,
  };

  const renderComponent = (props = {}) => render(
    <IntlProvider locale="en">
      <PlatformContentFields {...defaultProps} {...props} />
    </IntlProvider>
  );

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

  describe("Basic Rendering", () => {
    it("should render without crashing", () => {
      const { container } = renderComponent();
      expect(container).toBeInTheDocument();
    });

    it("should render title input with correct value", () => {
      const { container } = renderComponent();
      const titleInput = container.querySelector('input[value="Test Title"]');
      expect(titleInput).toBeInTheDocument();
    });

    it("should render message input with correct value", () => {
      const { getByTestId } = renderComponent();
      const messageInput = getByTestId("message-textarea");
      expect(messageInput).toBeInTheDocument();
      expect(messageInput.value).toBe("Test Message");
    });

    it("should render MediaUploaders component", () => {
      const { getByTestId } = renderComponent();
      expect(getByTestId("media-uploaders")).toBeInTheDocument();
    });

    it("should render CtaButtons component", () => {
      const { getByTestId } = renderComponent();
      expect(getByTestId("cta-buttons")).toBeInTheDocument();
    });

    it("should render TagList components", () => {
      const { getAllByTestId } = renderComponent();
      const tagLists = getAllByTestId("tag-list");
      expect(tagLists).toHaveLength(2);
    });
  });

  describe("Title Field", () => {
    it("should call title change handler", () => {
      const { container } = renderComponent();
      const titleInput = container.querySelector('input[value="Test Title"]');

      fireEvent.change(titleInput, { target: { value: "New Title" } });

      expect(defaultProps.handlers.handleTitleChange).toHaveBeenCalled();
    });

    it("should display title error when present", () => {
      const { getByTestId } = renderComponent({
        errors: { ...defaultProps.errors, title: "Title is required" },
      });

      expect(getByTestId("cap-error")).toHaveTextContent("Title is required");
    });
  });

  describe("Message Field", () => {
    it("should call message change handler", () => {
      const { getByTestId } = renderComponent();
      const messageInput = getByTestId("message-textarea");

      fireEvent.change(messageInput, { target: { value: "New Message" } });

      expect(defaultProps.handlers.handleMessageChange).toHaveBeenCalled();
    });

    it("should display message error when present", () => {
      const { getByTestId } = renderComponent({
        errors: { ...defaultProps.errors, message: "Message is required" },
      });

      expect(getByTestId("cap-error")).toHaveTextContent("Message is required");
    });

    it("should show inline personalization error when restricted and tokens present", () => {
      const personalizationErrorMsg = "Personalization tags are not supported for anonymous customers";
      const formatMessageStub = jest.fn((msg) => msg?.defaultMessage ?? "");
      const { container } = renderComponent({
        restrictPersonalization: true,
        content: { ...defaultProps.content, message: "Hello {{user}}" },
        formatMessage: formatMessageStub,
      });
      expect(container.textContent).toContain(personalizationErrorMsg);
      expect(formatMessageStub).toHaveBeenCalledWith(
        expect.objectContaining({ defaultMessage: expect.stringContaining("Personalization tags") })
      );
    });
  });

  describe("Personalization restriction", () => {
    it("disables tag list and shows tooltip when restrictPersonalization true", () => {
      const formatMessageForTooltip = jest.fn((msg) => msg?.defaultMessage ?? "");
      const { getAllByTestId } = renderComponent({
        restrictPersonalization: true,
        formatMessage: formatMessageForTooltip,
      });
      const tagLists = getAllByTestId("tag-list");
      expect(tagLists.length).toBeGreaterThan(0);
      tagLists.forEach((tag) => {
        expect(tag).toHaveAttribute('data-disabled', 'true');
      });
      expect(formatMessageForTooltip).toHaveBeenCalledWith(
        expect.objectContaining({ defaultMessage: "Personalization tags are not supported for anonymous customers" })
      );
    });
  });

  describe("Media Type Selection", () => {
    it("should call media type change handler", () => {
      const { container } = renderComponent();
      const mediaSelect = container.querySelector('select');

      fireEvent.change(mediaSelect, { target: { value: "VIDEO" } });

      expect(defaultProps.handlers.handleMediaTypeChange).toHaveBeenCalled();
    });
  });

  describe("Action on Click", () => {
    it("should call action on click change handler", () => {
      const { getByTestId } = renderComponent();
      const checkbox = getByTestId("action-checkbox");

      fireEvent.click(checkbox);

      expect(defaultProps.handlers.handleActionOnClickChange).toHaveBeenCalled();
    });

    it("should show action controls when actionOnClick is true", () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: true },
      });

      expect(container.textContent).toContain("Link Type");
    });

    it("should hide action controls when actionOnClick is false", () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: false },
      });

      expect(container.textContent).not.toContain("Link Type");
    });
  });

  describe("Device Type Handling", () => {
    it("should render with Android device type", () => {
      const { container } = renderComponent({ deviceType: ANDROID });
      const titleInput = container.querySelector('#mobile-push-title-name-input-android');
      expect(titleInput).toBeInTheDocument();
    });

    it("should render with iOS device type", () => {
      const { container } = renderComponent({ deviceType: IOS });
      const titleInput = container.querySelector('#mobile-push-title-name-input-ios');
      expect(titleInput).toBeInTheDocument();
    });
  });

  describe("External Link Input", () => {
    it("should call external link change handler", () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: true, linkType: EXTERNAL_LINK },
      });

      const externalLinkInput = container.querySelector('input[value="https://example.com"]');

      if (externalLinkInput) {
        fireEvent.change(externalLinkInput, { target: { value: "https://newlink.com" } });
        expect(defaultProps.handlers.handleExternalLinkChange).toHaveBeenCalled();
      }
    });

    it("should display external link error when present", () => {
      const { getByTestId } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: true, linkType: EXTERNAL_LINK },
        errors: { ...defaultProps.errors, externalLink: "Invalid URL" },
      });

      expect(getByTestId("cap-error")).toHaveTextContent("Invalid URL");
    });
  });

  describe("Carousel Media Type", () => {
    it("should hide action controls when mediaType is CAROUSEL", () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, mediaType: "CAROUSEL" },
      });

      expect(container.textContent).not.toContain("Buttons and Links");
      expect(container.textContent).not.toContain("CtaButtons");
    });

    it("should show action controls when mediaType is not CAROUSEL", () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, mediaType: "IMAGE" },
      });

      expect(container.textContent).toContain("Buttons and Links");
    });
  });

  describe("formatMessage Integration", () => {
    it("should call formatMessage with correct arguments", () => {
      renderComponent();

      expect(defaultProps.formatMessage).toHaveBeenCalledWith(
        expect.objectContaining({
          id: "titlePlaceholder",
          defaultMessage: "Enter title",
        })
      );
    });
  });

  describe("Error Handling", () => {
    it("should handle missing linkProps gracefully", () => {
      const { container } = renderComponent({
        linkProps: {},
      });

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

    it("should handle undefined values gracefully", () => {
      const { container } = renderComponent({
        content: {
          ...defaultProps.content,
          title: undefined,
          message: undefined,
        },
      });

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

  // Deep link keys handling - covering lines 109-120, 134, 297-303
  it('should handle deep link keys with array from selection', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: ['key1', 'key2'] },
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: ['key1', 'key2'],
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { getByText, getByDisplayValue } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Check that deep link keys are displayed correctly
    expect(getByText('key1, key2')).toBeInTheDocument();
    expect(getByDisplayValue('key1, key2')).toBeInTheDocument();
  });

  it('should handle deep link keys with single key from selection', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: 'single-key' },
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: ['single-key'],
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { getByText, getByDisplayValue } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Check that single key is displayed correctly
    expect(getByText('single-key')).toBeInTheDocument();
    expect(getByDisplayValue('single-key')).toBeInTheDocument();
  });

  it('should handle deep link keys with no keys from selection but existing keys', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: [] }, // No keys from selection
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: ['existing-key1', 'existing-key2'], // But existing keys in value
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { container } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // When no keys from selection, the deep link keys section should not render at all
    expect(container.textContent).not.toContain('Deep Link Keys');
  });

  it('should handle deep link keys with no keys at all', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: [] }, // No keys from selection
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: [], // But no keys in the value
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { container } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // When no keys from selection, the deep link keys section should not render at all
    expect(container.textContent).not.toContain('Deep Link Keys');
  });

  it('should handle deep link keys with string value instead of array', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: 'single-key' },
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: 'string-key-value',
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { getByDisplayValue } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Check that string value is displayed correctly
    expect(getByDisplayValue('string-key-value')).toBeInTheDocument();
  });

  it('should handle deep link keys with undefined deepLinkKeysValue', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: ['key1', 'key2'] },
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: undefined,
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    const { getAllByDisplayValue } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Check that empty string is displayed when deepLinkKeysValue is undefined
    const emptyInputs = getAllByDisplayValue('');
    expect(emptyInputs.length).toBeGreaterThan(0);
  });

  it('should handle deep link keys placeholder with fallback', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: ['key1', 'key2'] }, // Need keys to trigger the section
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: [],
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };

    render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={{}}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Verify that formatMessage was called with the fallback placeholder
    expect(defaultProps.formatMessage).toHaveBeenCalledWith(
      expect.any(Object),
      { key: 'key1, key2' }
    );
  });

  it('should handle deep link keys error display', () => {
    const mockDeepLink = [
      { value: 'test-deep-link', keys: ['key1', 'key2'] },
    ];
    const mockLinkProps = {
      deepLink: mockDeepLink,
      deepLinkValue: 'test-deep-link',
      deepLinkKeysValue: ['key1', 'key2'],
      externalLinkValue: '',
    };
    const mockContent = {
      title: 'Test Title',
      message: 'Test Message',
      mediaType: 'IMAGE',
      actionOnClick: true,
      linkType: 'DEEP_LINK',
    };
    const mockErrors = {
      deepLinkKeys: 'Deep link keys error message',
    };

    const { getByText } = render(
      <PlatformContentFields
        deviceType="ANDROID"
        content={mockContent}
        errors={mockErrors}
        handlers={defaultProps.handlers}
        tagListProps={defaultProps.tagListProps}
        mediaUploaderProps={defaultProps.mediaUploaderProps}
        ctaButtonProps={defaultProps.ctaButtonProps}
        linkProps={mockLinkProps}
        sameContent={false}
        formatMessage={defaultProps.formatMessage}
      />
    );

    // Check that error message is displayed
    expect(getByText('Deep link keys error message')).toBeInTheDocument();
  });

  // Test cases for uncovered lines
  describe('Deep link null/undefined handling', () => {
    it('should handle null deepLink in options', () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: true, linkType: DEEP_LINK },
        linkProps: {
          deepLink: null, // This should trigger the fallback to empty array
          deepLinkValue: '',
          externalLinkValue: '',
        },
      });

      // Should render without crashing when deepLink is null
      expect(container).toBeInTheDocument();
    });

    it('should handle undefined deepLink in options', () => {
      const { container } = renderComponent({
        content: { ...defaultProps.content, actionOnClick: true, linkType: DEEP_LINK },
        linkProps: {
          deepLink: undefined, // This should trigger the fallback to empty array
          deepLinkValue: '',
          externalLinkValue: '',
        },
      });

      // Should render without crashing when deepLink is undefined
      expect(container).toBeInTheDocument();
    });
  });

  describe('Deep link query parameter handling', () => {
    it('should match deep link with query parameters', () => {
      const mockDeepLink = [
        { value: 'myapp://profile', keys: ['userId'] },
      ];
      const mockLinkProps = {
        deepLink: mockDeepLink,
        deepLinkValue: 'myapp://profile?userId=123', // Has query parameters
        deepLinkKeysValue: ['userId'],
        externalLinkValue: '',
      };
      const mockContent = {
        title: 'Test Title',
        message: 'Test Message',
        mediaType: 'IMAGE',
        actionOnClick: true,
        linkType: 'DEEP_LINK',
      };

      const { getByText } = render(
        <IntlProvider locale="en">
          <PlatformContentFields
            deviceType="ANDROID"
            content={mockContent}
            errors={{}}
            handlers={defaultProps.handlers}
            tagListProps={defaultProps.tagListProps}
            mediaUploaderProps={defaultProps.mediaUploaderProps}
            ctaButtonProps={defaultProps.ctaButtonProps}
            linkProps={mockLinkProps}
            sameContent={false}
            formatMessage={defaultProps.formatMessage}
          />
        </IntlProvider>
      );

      // Should find the base deep link and display keys
      expect(getByText('userId')).toBeInTheDocument();
    });

    it('should not match deep link when no base match exists with query parameters', () => {
      const mockDeepLink = [
        { value: 'myapp://settings', keys: ['theme'] },
      ];
      const mockLinkProps = {
        deepLink: mockDeepLink,
        deepLinkValue: 'myapp://nomatch?theme=dark', // Base doesn't match any deepLink
        deepLinkKeysValue: [],
        externalLinkValue: '',
      };
      const mockContent = {
        title: 'Test Title',
        message: 'Test Message',
        mediaType: 'IMAGE',
        actionOnClick: true,
        linkType: 'DEEP_LINK',
      };

      const { container } = render(
        <IntlProvider locale="en">
          <PlatformContentFields
            deviceType="ANDROID"
            content={mockContent}
            errors={{}}
            handlers={defaultProps.handlers}
            tagListProps={defaultProps.tagListProps}
            mediaUploaderProps={defaultProps.mediaUploaderProps}
            ctaButtonProps={defaultProps.ctaButtonProps}
            linkProps={mockLinkProps}
            sameContent={false}
            formatMessage={defaultProps.formatMessage}
          />
        </IntlProvider>
      );

      // Should render without crashing even when no match is found
      expect(container).toBeInTheDocument();
    });

    it('should handle multiple query parameters in deep link value', () => {
      const mockDeepLink = [
        { value: 'testapp://dashboard', keys: ['category', 'filter'] },
      ];
      const mockLinkProps = {
        deepLink: mockDeepLink,
        deepLinkValue: 'testapp://dashboard?category=news&filter=recent', // Multiple query parameters
        deepLinkKeysValue: ['category', 'filter'],
        externalLinkValue: '',
      };
      const mockContent = {
        title: 'Test Title',
        message: 'Test Message',
        mediaType: 'IMAGE',
        actionOnClick: true,
        linkType: 'DEEP_LINK',
      };

      const { getByText } = render(
        <IntlProvider locale="en">
          <PlatformContentFields
            deviceType="ANDROID"
            content={mockContent}
            errors={{}}
            handlers={defaultProps.handlers}
            tagListProps={defaultProps.tagListProps}
            mediaUploaderProps={defaultProps.mediaUploaderProps}
            ctaButtonProps={defaultProps.ctaButtonProps}
            linkProps={mockLinkProps}
            sameContent={false}
            formatMessage={defaultProps.formatMessage}
          />
        </IntlProvider>
      );

      // Should find the base deep link and display keys
      expect(getByText('category, filter')).toBeInTheDocument();
    });

    it('should handle empty query parameters in deep link value', () => {
      const mockDeepLink = [
        { value: 'myapp://search', keys: ['query'] },
      ];
      const mockLinkProps = {
        deepLink: mockDeepLink,
        deepLinkValue: 'myapp://search?', // Empty query parameters
        deepLinkKeysValue: ['query'],
        externalLinkValue: '',
      };
      const mockContent = {
        title: 'Test Title',
        message: 'Test Message',
        mediaType: 'IMAGE',
        actionOnClick: true,
        linkType: 'DEEP_LINK',
      };

      const { getByText } = render(
        <IntlProvider locale="en">
          <PlatformContentFields
            deviceType="ANDROID"
            content={mockContent}
            errors={{}}
            handlers={defaultProps.handlers}
            tagListProps={defaultProps.tagListProps}
            mediaUploaderProps={defaultProps.mediaUploaderProps}
            ctaButtonProps={defaultProps.ctaButtonProps}
            linkProps={mockLinkProps}
            sameContent={false}
            formatMessage={defaultProps.formatMessage}
          />
        </IntlProvider>
      );

      // Should find the base deep link and display keys
      expect(getByText('query')).toBeInTheDocument();
    });
  });

  it('should handle tag selection for external link in buttons', () => {
    const mockHandleExternalLinkChange = jest.fn();

    // Create a test that actually renders the component and triggers the useCallback
    const { container } = renderComponent({
      content: {
        ...defaultProps.content,
        actionOnClick: true,
        linkType: EXTERNAL_LINK,
      },
      linkProps: {
        ...defaultProps.linkProps,
        externalLinkValue: 'https://example.com/',
      },
      handlers: {
        ...defaultProps.handlers,
        handleExternalLinkChange: mockHandleExternalLinkChange,
      },
    });

    // Find the TagList component that's specifically for external link (there should be 3 TagLists total)
    // One for title, one for message, and one for external link
    const tagLists = container.querySelectorAll('[data-testid="tag-list"]');
    expect(tagLists).toHaveLength(3); // title, message, and external link TagLists

    // The external link TagList should be the third one (index 2)
    const externalLinkTagList = tagLists[2];
    const tagSelectButton = externalLinkTagList.querySelector('[data-testid="tag-select-button"]');
    expect(tagSelectButton).toBeTruthy();

    // Click the button to trigger the real onButtonTagSelect useCallback
    fireEvent.click(tagSelectButton);

    // Verify the handler was called with the correct parameters
    // The mock TagList calls onTagSelect with 'test_tag', so we expect that
    expect(mockHandleExternalLinkChange).toHaveBeenCalledWith(
      'https://example.com/{{test_tag}}' // newUrl with appended tag
    );
  });
});
