/**
 * Integration tests for TestAndPreviewSlidebox in WebPushCreate
 *
 * Tests:
 * - Test & Preview button renders and opens the slidebox
 * - handleTestAndPreview sets showTestAndPreviewSlidebox=true
 * - handleCloseTestAndPreview sets showTestAndPreviewSlidebox=false
 * - TestAndPreviewSlidebox receives correct props (currentChannel, accountId, content)
 *
 * Note: all relative mock paths are resolved from THIS test file's location
 * (app/v2Containers/WebPush/Create/tests/), not from the component.
 */

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

// ── Infrastructure / HOC mocks ──────────────────────────────────────────────
jest.mock('../../../../hoc/withCreatives', () => ({
  __esModule: true,
  default: ({ WrappedComponent }) => WrappedComponent,
}));

jest.mock('@capillarytech/vulcan-react-sdk/utils', () => ({
  injectReducer: () => (Component) => Component,
  injectSaga: () => (Component) => Component,
}));
jest.mock('@capillarytech/vulcan-react-sdk/utils/sagaInjectorTypes', () => ({
  DAEMON: 'DAEMON',
}));

// ── Redux slices (paths relative to this test file) ─────────────────────────
jest.mock('../../../Templates/selectors', () => ({
  makeSelectTemplates: () => () => {},
}));
jest.mock('../../../Templates/actions', () => ({}));
jest.mock('../../selectors', () => ({
  makeSelectWebPush: () => () => ({}),
  makeSelectCreateError: () => () => null,
  makeSelectCreateTemplateInProgress: () => () => false,
  makeSelectEditTemplateInProgress: () => () => false,
  makeSelectEditError: () => () => null,
}));
jest.mock('../../actions', () => ({}));
jest.mock('../../reducer', () => () => ({}));
jest.mock('../../sagas', () => ({}));
jest.mock('../../../Templates/sagas', () => ({ v2TemplateSaga: {} }));
jest.mock('../../../Cap/selectors', () => ({
  makeSelectMetaEntities: () => () => [],
  setInjectedTags: () => () => [],
}));
jest.mock('../../../CreativesContainer/constants', () => ({
  WEBPUSH: 'WEBPUSH',
}));
jest.mock('../../../CreativesContainer/messages', () => ({
  testAndPreview: { id: 'testAndPreview', defaultMessage: 'Test & Preview' },
}));
jest.mock('../../../../utils/common', () => ({
  isAiContentBotDisabled: () => false,
}));

// ── Form section components ──────────────────────────────────────────────────
jest.mock('../components/TemplateNameSection', () => ({
  __esModule: true,
  default: () => <div data-testid="template-name-section" />,
}));
jest.mock('../components/NotificationTitleSection', () => ({
  __esModule: true,
  default: () => <div data-testid="notification-title-section" />,
}));
jest.mock('../components/MessageSection', () => ({
  __esModule: true,
  default: () => <div data-testid="message-section" />,
}));
jest.mock('../components/MediaSection', () => ({
  __esModule: true,
  default: () => <div data-testid="media-section" />,
}));
jest.mock('../components/BrandIconSection', () => ({
  __esModule: true,
  default: () => <div data-testid="brand-icon-section" />,
}));
jest.mock('../components/ButtonsLinksSection', () => ({
  __esModule: true,
  default: () => <div data-testid="buttons-links-section" />,
}));
jest.mock('../components/FormActions', () => ({
  __esModule: true,
  default: () => <div data-testid="form-actions" />,
}));
jest.mock('../preview/WebPushPreview', () => ({
  __esModule: true,
  default: () => <div data-testid="webpush-preview" />,
}));
jest.mock('../../../TagList', () => ({
  __esModule: true,
  default: () => <div data-testid="tag-list" />,
}));

// ── Hooks ────────────────────────────────────────────────────────────────────
jest.mock('../hooks/useCharacterCount', () => ({
  useCharacterCount: () => ({ updateCharacterCount: jest.fn() }),
}));
jest.mock('../hooks/useButtonManagement', () => ({
  useButtonManagement: () => ({ buttons: [], setButtons: jest.fn() }),
}));
jest.mock('../hooks/useImageUpload', () => ({
  useImageUpload: () => ({
    imageSrc: '',
    imageUrl: '',
    isValidating: false,
    isUploading: false,
    setImageSrc: jest.fn(),
    setImageUrl: jest.fn(),
  }),
}));
jest.mock('../hooks/useTagManagement', () => ({
  useTagManagement: () => ({ tags: [], extractTags: jest.fn() }),
}));

// ── Capture TestAndPreviewSlidebox props ─────────────────────────────────────
let capturedSlideboxProps = {};
jest.mock('../../../../v2Components/TestAndPreviewSlidebox', () => ({
  __esModule: true,
  default: (props) => {
    capturedSlideboxProps = props;
    return (
      <div data-testid="test-and-preview-slidebox" data-show={props.show ? 'true' : 'false'}>
        {props.show && <div data-testid="slidebox-open">Slidebox Open</div>}
        <button data-testid="slidebox-close-btn" onClick={props.onClose}>
          Close
        </button>
      </div>
    );
  },
}));

// ── CapUI library ─────────────────────────────────────────────────────────────
jest.mock('@capillarytech/cap-ui-library/CapRow', () => ({
  __esModule: true,
  default: ({ children, className }) => <div className={className}>{children}</div>,
}));
jest.mock('@capillarytech/cap-ui-library/CapColumn', () => ({
  __esModule: true,
  default: ({ children, className }) => <div className={className}>{children}</div>,
}));
jest.mock('@capillarytech/cap-ui-library/CapButton', () => ({
  __esModule: true,
  default: ({ children, onClick, className, type }) => (
    <button className={className} onClick={onClick} data-type={type}>
      {children}
    </button>
  ),
}));

// ── Import component AFTER mocks ─────────────────────────────────────────────
// eslint-disable-next-line import/first
import WebPushCreateDefault from '../index';

const baseProps = {
  isFullMode: false,
  handleClose: jest.fn(),
  webPushActions: {
    createTemplate: jest.fn(),
    editTemplate: jest.fn(),
    uploadImage: jest.fn(),
    clearCreateError: jest.fn(),
    clearEditError: jest.fn(),
    clearCreateResponse: jest.fn(),
    clearEditResponse: jest.fn(),
    setSelectedAccount: jest.fn(),
    clearState: jest.fn(),
  },
  createTemplateInProgress: false,
  createTemplateError: null,
  editTemplateInProgress: false,
  editTemplateError: null,
  accountData: null,
  webPush: {},
  onCreateComplete: jest.fn(),
  getFormData: jest.fn(),
  isGetFormData: false,
  templateData: null,
  creativesMode: 'create',
  params: {},
  globalActions: { getMetaEntities: jest.fn() },
  location: { pathname: '/webpush', query: {}, search: '', state: {} },
  metaEntities: [],
  injectedTags: [],
  getDefaultTags: jest.fn(),
  supportedTags: [],
  forwardedTags: [],
  selectedOfferDetails: [],
  eventContextTags: [],
  waitEventContextTags: {},
  templateActions: {},
  Templates: { templates: [] },
  restrictPersonalization: false,
};

const TestWrapper = ({ children }) => (
  <IntlProvider locale="en" messages={{ testAndPreview: 'Test & Preview' }}>
    {children}
  </IntlProvider>
);

describe('WebPushCreate - Test & Preview integration', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    capturedSlideboxProps = {};
  });

  it('should render the Test & Preview button', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(screen.getByText('Test & Preview')).toBeTruthy();
  });

  it('should render TestAndPreviewSlidebox with show=false initially', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    const slidebox = screen.getByTestId('test-and-preview-slidebox');
    expect(slidebox.getAttribute('data-show')).toBe('false');
  });

  it('should open TestAndPreviewSlidebox when Test & Preview button is clicked', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    fireEvent.click(screen.getByText('Test & Preview'));

    const slidebox = screen.getByTestId('test-and-preview-slidebox');
    expect(slidebox.getAttribute('data-show')).toBe('true');
    expect(screen.getByTestId('slidebox-open')).toBeTruthy();
  });

  it('should close TestAndPreviewSlidebox when onClose is called', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    // Open it
    fireEvent.click(screen.getByText('Test & Preview'));
    expect(screen.getByTestId('test-and-preview-slidebox').getAttribute('data-show')).toBe('true');

    // Close it
    fireEvent.click(screen.getByTestId('slidebox-close-btn'));
    expect(screen.getByTestId('test-and-preview-slidebox').getAttribute('data-show')).toBe('false');
  });

  it('should pass currentChannel="WEBPUSH" to TestAndPreviewSlidebox', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(capturedSlideboxProps.currentChannel).toBe('WEBPUSH');
  });

  it('should pass null accountId when accountData is null', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} accountData={null} />
      </TestWrapper>
    );

    expect(capturedSlideboxProps.accountId).toBeNull();
  });

  it('should pass content object with channel WEBPUSH to TestAndPreviewSlidebox', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(capturedSlideboxProps.content).toBeDefined();
    expect(capturedSlideboxProps.content.channel).toBe('WEBPUSH');
  });

  it('should pass content with offers array to TestAndPreviewSlidebox', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(capturedSlideboxProps.content.offers).toEqual([]);
  });

  it('should pass onClose handler to TestAndPreviewSlidebox', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(typeof capturedSlideboxProps.onClose).toBe('function');
  });

  it('should pass show=false to TestAndPreviewSlidebox before button click', () => {
    render(
      <TestWrapper>
        <WebPushCreateDefault {...baseProps} />
      </TestWrapper>
    );

    expect(capturedSlideboxProps.show).toBe(false);
  });
});
