import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import TemplatesV2 from '../TemplatesV2';
import TemplatePreview from '../../v2Components/TemplatePreview';
import SmsWrapper from '../SmsWrapper';
import Email from '../Email';
import EmailWrapper from '../EmailWrapper';
import MobilepushWrapper from '../MobilepushWrapper';
import InAppWrapper from '../InAppWrapper';
import EmailPreviewV2 from '../../v2Components/EmailPreviewV2';
import MobilePushPreview from '../../v2Components/MobilePushPreviewV2';
import WechatWrapper from '../WeChat/Wrapper';
import Facebook from '../Facebook';
import { RICH_MEDIA, MAP_TEMPLATE, CREATE } from '../WeChat/Wrapper/constants';
import CallTask from '../CallTask';
import MobliPushEdit from '../MobilePush/Edit';
import * as constants from './constants';
import LineContainer from '../Line/Container';
import FTP from '../FTP';
import Viber from '../Viber';
import Whatsapp from '../Whatsapp';
import InApp from '../InApp';
import Rcs from '../Rcs';
import { getWhatsappContent } from '../Whatsapp/utils';
import * as commonUtil from '../../utils/common';
import Zalo from '../Zalo';
import MobilePushNew from '../MobilePushNew';
import WebPush from '../WebPush';
import DevicePreviewContent from '../WebPush/Create/preview/DevicePreviewContent';
import { LAYOUT_MODE } from '../WebPush/Create/preview/constants';
import { WEBPUSH_CONTENT_FIELDS, WEBPUSH_TEMPLATE_PATHS } from '../WebPush/constants';
const CreativesWrapper = styled.div`
  .ant-popover,
  .ant-notification,
  .ant-modal-wrap {
    z-index: 10003;
  }
`;

function getWechatTemplateType(mode, templateData, weChatTemplateType = '') {
  if (mode !== CREATE) {
    return get(templateData, 'definition.msgcontent', '') === "RICH_MEDIA_WECHAT" ? RICH_MEDIA : MAP_TEMPLATE;
  }
  return weChatTemplateType;
}
const getLineType = ({
  slidBoxContent,
  channel,
  isFullMode,
  templateData,
}) => {
  if ((channel === constants.LINE || (slidBoxContent === 'editTemplate' && templateData && templateData.type === constants.LINE)) && slidBoxContent !== 'templates') {
    const isCreate = slidBoxContent === 'createTemplate';
    const isEdit = slidBoxContent === 'editTemplate';
    if (isFullMode) {
      return {
        isCreate,
        isEdit,
      };
    } else {
      if (templateData) {
        const { isDefault, _id } = templateData;
        const messageBody = get(templateData, "versions.base.content.messages[0]");
        if (_id || messageBody) {
          return {
            isEdit: true,
          };
        } else if (isDefault) {
          return {
            isCreate: true,
          };
        }
        return {};
      }
      return {
        isCreate,
        isEdit,
      };
    }
  }
  return {};
};
const getViber = ({
  slidBoxContent,
  channel,
  isFullMode,
  templateData,
}) => {
  if ((channel === constants.VIBER || (slidBoxContent === 'editTemplate' && templateData && templateData.type === constants.VIBER)) && slidBoxContent !== 'templates') {
    const isCreate = slidBoxContent === 'createTemplate';
    const isEdit = slidBoxContent === 'editTemplate';
    return {
      isCreate,
      isEdit,
    };
  }
  return {};
};

export function SlideBoxContent(props) {
  const {
      slidBoxContent,
      onSelectTemplate,
      onPreviewTemplate,
      templateData,
      location,
      isGetFormData,
      getFormData,
      getLiquidTags,
      onCreateComplete,
      messageDetails = {},
      onCreateNew,
      currentChannel,
      onChannelChange,
      onEmailModeChange,
      emailCreateMode,
      onMobilepushModeChange,
      mobilePushCreateMode,
      onInAppEditorTypeChange,
      inAppEditorType,
      templateStep,
      inAppCreateMode,
      onInAppModeChange,
      onEnterTemplateName,
      onRemoveTemplateName,
      onCreateNextStep,
      cap,
      onResetStep,
      isFullMode,
      editor,
      onCallTaskSubmit,
      setIsLoadingContent,
      showTemplateName,
      onValidationFail,
      channelsToHide,
      forwardedTags,
      supportedTags = [],
      selectedOfferDetails,
      channelsToDisable,
      weChatTemplateType,
      onWechatTemplateChange,
      selectedWeChatAccount,
      weChatMaptemplateStep,
      onWeChatMaptemplateStepChange,
      onTestContentClicked,
      onPreviewContentClicked,
      onFacebookSubmit,
      saveMessage,
      selectedAccount,
      onShowTemplates,
      handleClose,
      onFTPSubmit,
      campaignSettings,
      messageStrategy,
      fbAdManager,
      showDisabledFBInfo,
      orgUnitId,
      smsRegister,
      enableNewChannels,
      hideTestAndPreviewBtn,
      getCmsTemplatesInProgress = false,
      moduleType,
      showLiquidErrorInFooter,
      creativesMode,
      hostName = '',
      eventContextTags,
      waitEventContextTags = {},
      isLoyaltyModule,
      loyaltyMetaData = {},
      showTestAndPreviewSlidebox,
      handleTestAndPreview,
      handleCloseTestAndPreview,
      restrictPersonalization = false,
      isAnonymousType = false,
      onPersonalizationTokensChange,
      isTestAndPreviewMode,
      onHtmlEditorValidationStateChange,
    } = props;
  const type = (messageDetails.type || '').toLowerCase(); // type is context in get tags values : outbound | dvs | referral | loyalty | coupons
  const query = { type: !isFullMode && 'embedded', module: isFullMode ? 'default' : 'library', isEditFromCampaigns: (templateData || {}).isEditFromCampaigns};
  const creativesLocationProps = {
    pathname: `/sms/edit`,
    query,
    search: '',
  };
  let channel = currentChannel || '';//for create mode
  const {
    isCreate: isCreateLine = false,
    isEdit: isEditLine = false,
  } = getLineType({
    slidBoxContent,
    channel,
    isFullMode,
    templateData,
  });
  const {isCreate: isCreateViber = false,
    isEdit: isEditViber = false } = getViber({
      slidBoxContent,
      channel,
      isFullMode,
      templateData,
    });


  const isCreate = slidBoxContent === 'createTemplate';
  const isEdit = slidBoxContent === 'editTemplate';
  const isCreateSms = isCreate && channel === constants.SMS;
  const isCreateFacebook = isCreate && channel === constants.FACEBOOK;
  const isCreateWhatsapp = isCreate && channel === constants.WHATSAPP;
  const isCreateInApp = isCreate && channel === constants.INAPP;
  const isCreateRcs = isCreate && channel === constants.RCS;
  const isCreateMPush = isCreate && channel === constants.MOBILE_PUSH;
  const isCreateCallTask = isCreate && channel === constants.CALL_TASK;
  const isCreateWebPush = isCreate && channel === constants.WEBPUSH;
  let isEditSms = false;
  let isEditEmailWithId = false;
  let isEmailEditWithContent = false;
  let isPreview = false;
  let isEmailPreview = false;
  let isMpushPreview = false;
  let isInappPreview = false;
  let isWebPushPreview = false;
  let isEditCallTask = false;
  let isEditMPush = false;
  let isEditFacebook = false;
  let isEditFTP = false;
  let isEditWhatsapp = false;
  let isEditInApp = false;
  let isEditWebPush = false;
  let isEditRcs = false;
  let isEditZalo = false;
  const isEmailCreate = isCreate && channel === constants.EMAIL;
  if (templateData && channel) {
    channel = templateData.type;// for edit mode with template data
    isEditSms = isEdit && channel === constants.SMS;
    isEditCallTask = isEdit && channel === constants.CALL_TASK;
    isEditMPush = isEdit && channel === constants.MOBILE_PUSH;
    isEditEmailWithId = isEdit && channel === constants.EMAIL && templateData._id;
    isEmailEditWithContent = isEdit && channel === constants.EMAIL && !templateData._id;
    isEditFacebook = isEdit && channel === constants.FACEBOOK;
    isEditWhatsapp = isEdit && channel === constants.WHATSAPP;
    isEditRcs = isEdit && channel === constants.RCS;
    isEditWebPush = isEdit && channel === constants.WEBPUSH;
    isPreview = slidBoxContent === 'preview' && [constants.SMS, constants.LINE, constants.WHATSAPP, constants.FACEBOOK, constants.VIBER, constants.RCS].includes(channel);
    isEmailPreview = slidBoxContent === 'preview' && channel === constants.EMAIL;
    isMpushPreview = slidBoxContent === 'preview' && channel === constants.MOBILE_PUSH;
    isInappPreview = slidBoxContent === 'preview' && channel === constants.INAPP;
    isWebPushPreview = slidBoxContent === 'preview' && channel === constants.WEBPUSH;
    isEditFTP = isEdit && [constants.NO_COMMUNICATION, constants.FTP].includes(channel);
    isEditZalo = isEdit && channel?.toUpperCase() === constants.ZALO;
    isEditInApp = isEdit && channel === constants.INAPP;
  }
  const isDltEnabled = commonUtil.isTraiDLTEnable(isFullMode, smsRegister);
  const hasJPLocaleHideFeatureEnabled = commonUtil?.hasJPLocaleHideFeatureEnabled();

  const getChannelPreviewContent = (templateDataObject) => {
    switch (templateDataObject.type.toUpperCase()) {
      case constants.SMS: {
        const updatedSmsEditor = get(
          templateDataObject,
          `versions.base['updated-sms-editor']`,
          '',
        );
        if (!isDltEnabled || updatedSmsEditor === '') {
          return get(templateDataObject, `versions.base['sms-editor']`);
        }
        return updatedSmsEditor.join('');
      }
      case constants.LINE: {
        const lineContents = get(templateDataObject, `versions.base.content.messages`, [{}]);
        const previewContent = [];
        return lineContents.map(({
          text,
          previewImageUrl,
          selectedSticker,
          stickerUrl,
          animatedStickerUrl,
          stickerId,
          packageId,
          baseUrl,
          video,
          template,
          contents = {},
          type = '',
        }) => {
          const isNewLineFormat = type === 'flex';
          const {
            originalContentUrl,
            externalLink: {
              linkUri,
            } = {},
          } = video || {};
          const previewContent = {};
          previewContent.messageContent = text;
          previewContent.previewImageUrl = previewImageUrl;
          previewContent.selectedSticker = selectedSticker || {
            stickerUrl,
            animatedStickerUrl,
            stickerId,
            packageId,
          };
          previewContent.baseUrl = baseUrl;
          previewContent.video = originalContentUrl;
          previewContent.actionUrl = linkUri;
          if (isNewLineFormat) {
            const { contents: flexContent = [] } = contents;
            previewContent.imageCarousel = flexContent.map((data) => ({
              imageUrl: get(data, "hero.url", ""),
              actionLabel: get(data, "footer.contents[0].action.label", ""),
            }));
          } else {
            previewContent.imageCarousel = get(template, 'columns', [{}]).map(({ imageUrl, action: { label: actionLabel } = {} }) => ({ imageUrl, actionLabel }) );
          }
          const getType = () => {
            if (text) {
              return 'text';
            }
            if (previewImageUrl) {
              return 'image';
            }
            if (selectedSticker || stickerUrl) {
              return 'sticker';
            }
            if (baseUrl) {
              return 'imagemap';
            }
            if (template || contents) {
              return 'image_carousel';
            }
            if (video) {
              return 'video';
            }
          };
          previewContent.type = getType();
          return previewContent;
        });
      }
      case constants.VIBER: {
        const template = cloneDeep(templateDataObject);
        const { text = "", button = {}, image = {}, video = {} } = get(template, 'versions.base.content.content', {});
        const { url: viberVideoUrl = "", thumbnailUrl = '' } = video;
        const { url: viberImageUrl = "" } = image;
        template.content = {
          viberPreviewContent: {
            ...(!isEmpty(image) && { imageURL: viberImageUrl }),
            ...(!isEmpty(video) && { videoParams: { viberVideoSrc: viberVideoUrl, viberVideoPreviewImg: thumbnailUrl }}),
            buttonText: button?.text,
            messageContent: text,
          },
        };
        return template.content;
      }
      case constants.FACEBOOK: {
        const template = cloneDeep(templateDataObject.versions.base) || {};
        const {FacebookAd = [], pageOrgUnitId} = template.content || {};
        const {
          type: fbType = "",
          primaryText = "",
          callToAction = "",
          displayLink = "",
        } = FacebookAd[0] || {};
        const previewData = Object.values(template.content.FacebookAd).map((obj) => ({
          imageData: obj.imgSrc ? {imageSrc: obj.imgSrc} : {},
          linkDesc: obj.linkDesc,
          linkHeadLine: obj.linkHeadLine,
          subType: obj.subType,
          videoData: obj.video ? { videoSrc: obj.video.originalContentUrl,
            videoName: obj.video.videoName,
            previewUrl: obj.video.previewImageUrl,
            videoId: obj.video.videoId,

          } : {},
          webSiteLink: obj.webSiteLink,
        }));
        const facebookAccountSettings = get(campaignSettings, 'accountSettings.socialAccountSettings.facebookAccountSettings', []);
        const {accountId, employeeAccessToken: accessToken, orgUnitFacebookPageSettingsMap = {}} = facebookAccountSettings[0] || {};
        const {pageAccessToken, pageId} = orgUnitFacebookPageSettingsMap[pageOrgUnitId];
        const fbContent = {
          selectedAd: fbType,
          previewData,
          primaryText,
          callToAction,
          displayLink,
          pageAccessToken,
          pageId,
          accountId,
          accessToken,
        };
        return fbContent;
      }
      case constants.WHATSAPP: {
        return {
          ...getWhatsappContent(templateDataObject, true),
        };
      }
      case constants.RCS: {
        const template = cloneDeep(templateDataObject);
        const { description = "", media: { mediaUrl = "" } = {}, title = "", suggestions = [] } = get(template, 'versions.base.content.RCS.rcsContent.cardContent[0]', {});
        return {
          rcsPreviewContent: {
            rcsImageSrc: mediaUrl,
            rcsTitle: title,
            rcsDesc: description,
            ...(suggestions.length > 0 && {
              buttonText: suggestions[0]?.text,
            }),
          },
        };
      }
      default:
        return get(templateDataObject, `versions.base.content`);
    }
  };

  const rcsCommonProps = {
    isFullMode,
    isDltEnabled,
    smsRegister,
    getDefaultTags: type,
    onCreateComplete,
    selectedOfferDetails,
    getFormData,
    eventContextTags,
    waitEventContextTags,
  };

  return (
    <CreativesWrapper>
      {!isFullMode && slidBoxContent === 'templates' && (
      <TemplatesV2
        isFullMode={isFullMode}
        onSelectTemplate={onSelectTemplate}
        handlePeviewTemplate={onPreviewTemplate}
        location={location}
        createNew={onCreateNew}
        channel={(channel || '').toLowerCase()}
        onChannelChange={onChannelChange}
        onCallTaskSubmit={onCallTaskSubmit}
        cap={cap}
        channelsToHide={channelsToHide}
        forwardedTags={forwardedTags}
        channelsToDisable={channelsToDisable}
        messageDetails={messageDetails}
        onFacebookSubmit={onFacebookSubmit}
        onCreateComplete={onCreateComplete}
        getFormSubscriptionData={getFormData}
        handleClose={handleClose}
        onFTPSubmit={onFTPSubmit}
        slidBoxContent={slidBoxContent}
        FTPMode="create"
        selectedOfferDetails={selectedOfferDetails}
        messageStrategy={messageStrategy}
        showDisabledFBInfo={showDisabledFBInfo}
        orgUnitId={orgUnitId}
        smsRegister={smsRegister}
        enableNewChannels={enableNewChannels}
        hideTestAndPreviewBtn={hideTestAndPreviewBtn}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        loyaltyMetaData={loyaltyMetaData}
        isLoyaltyModule={isLoyaltyModule}
        />
      )}
      {isPreview && (
      <TemplatePreview
        content={getChannelPreviewContent(templateData)}
        viberBrandName={selectedAccount || ""}
        viberAccountName={(selectedAccount || "")[0]}
        whatsappAccountName={selectedAccount}
        unicodeEnabled={get(templateData, `versions.base['unicode-validity']`)}
        channel={(templateData.type || '').toLowerCase()}
        charCounterEnabled={channel === constants.SMS}
        templateData={templateData}
        showCount
        forwardedTags={forwardedTags}
        hasJPLocaleHideFeatureEnabled={hasJPLocaleHideFeatureEnabled}
      />
        )}
      {isEmailPreview && (
        <EmailPreviewV2
          templateData={templateData}
          forwardedTags={forwardedTags}
        />
      )
      }
      {isInappPreview && (
        <MobilePushPreview
          templateData={templateData}
          channel={channel}
          forwardedTags={forwardedTags}
      />
      )}
      {isMpushPreview && (
        <MobilePushPreview
          templateData={templateData}
          channel={channel}
          forwardedTags={forwardedTags}
      />
      )}
      {isWebPushPreview && (() => {
        const webpushContent = get(templateData, WEBPUSH_TEMPLATE_PATHS.CONTENT, {});
        const notificationTitle = webpushContent?.[WEBPUSH_CONTENT_FIELDS.TITLE] || '';
        const notificationBody = webpushContent?.[WEBPUSH_CONTENT_FIELDS.MESSAGE] || '';
        const imageSrc = webpushContent?.[WEBPUSH_CONTENT_FIELDS.IMAGE] || '';
        const brandIconSrc = webpushContent?.[WEBPUSH_CONTENT_FIELDS.BRAND_ICON] || '';
        // Extract URL from onClickAction or use empty string
        const url = webpushContent?.[WEBPUSH_CONTENT_FIELDS.ON_CLICK_ACTION]?.url || '';
        
        return (
          <div className="webpush-preview-container">
            <DevicePreviewContent
              notificationTitle={notificationTitle}
              notificationBody={notificationBody}
              url={url}
              imageSrc={imageSrc}
              brandIconSrc={brandIconSrc}
              layoutMode={LAYOUT_MODE.COMPACT}
            />
          </div>
        );
      })()}

      {
        (currentChannel === constants.WECHAT && !!slidBoxContent) && <WechatWrapper
          mode={slidBoxContent}
          templateData={templateData}
          templateType={getWechatTemplateType(slidBoxContent, templateData, weChatTemplateType)}
          onWechatTemplateChange={onWechatTemplateChange}
          templateStep={templateStep}
          query={query}
          selectedWeChatAccount={selectedWeChatAccount}
          isGetFormData={isGetFormData}
          getFormData={getFormData}
          isFullMode={isFullMode}
          onValidationFail={onValidationFail}
          onWeChatMaptemplateStepChange={onWeChatMaptemplateStepChange}
          weChatMaptemplateStep={weChatMaptemplateStep}
          forwardedTags={forwardedTags}
          setIsLoadingContent={setIsLoadingContent}
        />
      }
      {isEditSms && (
        <SmsWrapper
          showLiquidErrorInFooter={showLiquidErrorInFooter}
          setIsLoadingContent={setIsLoadingContent}
          isEditSms={isEditSms}
          location={creativesLocationProps}
          isFullMode={isFullMode}
          route={{ name: 'sms' }}
          params={{id: templateData._id}}
          isGetFormData={isGetFormData}
          getFormSubscriptionData={getFormData}
          getDefaultTags={type}
          templateData={templateData}
          forwardedTags={forwardedTags}
          selectedOfferDetails={selectedOfferDetails}
          onPreviewContentClicked={onPreviewContentClicked}
          onTestContentClicked={onTestContentClicked}
          handleClose={handleClose}
          onCreateComplete={onCreateComplete}
          smsRegister={smsRegister}
          eventContextTags={eventContextTags}
          waitEventContextTags={waitEventContextTags}
          getLiquidTags={getLiquidTags}
          showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
          handleTestAndPreview={handleTestAndPreview}
          handleCloseTestAndPreview={handleCloseTestAndPreview}
          isTestAndPreviewMode={isTestAndPreviewMode}
          onValidationFail={onValidationFail}
        />
      )}
      {isEditFTP && (
        <FTP
          mode="edit"
          onFTPSubmit={onFTPSubmit}
          messageDetails={messageDetails}
          selectedOfferDetails={selectedOfferDetails}
        />
      )}
      {
        isEditCallTask &&
          <CallTask
            mode={'edit'}
            templateData={templateData}
            onCallTaskSubmit={onCallTaskSubmit}
            forwardedTags={forwardedTags}
            selectedOfferDetails={selectedOfferDetails}
            messageDetails={messageDetails}
          />
      }
      {
        isEditZalo &&
        <Zalo
          isFullMode={isFullMode}
          templateData={templateData}
          getFormData={getFormData}
          getDefaultTags={type}
          forwardedTags={forwardedTags}
          selectedOfferDetails={selectedOfferDetails}
          location={{
            pathname: `/zalo/edit`,
            query,
            search: '',
          }}
          hostName={hostName}
          eventContextTags={eventContextTags}
          waitEventContextTags={waitEventContextTags}
          showLiquidErrorInFooter={showLiquidErrorInFooter}
          showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
          handleTestAndPreview={handleTestAndPreview}
          handleCloseTestAndPreview={handleCloseTestAndPreview}
        />
      }
      {
         isCreateCallTask &&
         <CallTask
           mode={'create'}
           onCallTaskSubmit={onCallTaskSubmit}
           forwardedTags={forwardedTags}
           selectedOfferDetails={selectedOfferDetails}
           messageDetails={messageDetails}
        />
       }
      {isCreateSms && (
      <SmsWrapper
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        setIsLoadingContent={setIsLoadingContent}
        location={creativesLocationProps}
        route={{ name: 'sms' }}
        isCreateSms={isCreateSms}
        isComponent
        isGetFormData={isGetFormData}
        getFormSubscriptionData={getFormData}
        getLiquidTags={getLiquidTags}
        getDefaultTags={type}
        isFullMode={isFullMode}
        onValidationFail={onValidationFail}
        forwardedTags={forwardedTags}
        selectedOfferDetails={selectedOfferDetails}
        onPreviewContentClicked={onPreviewContentClicked}
        onTestContentClicked={onTestContentClicked}
        onCreateComplete={onCreateComplete}
        smsRegister={smsRegister}
        onShowTemplates={onShowTemplates}
        eventContextTags={eventContextTags}
        restrictPersonalization={restrictPersonalization}
        isAnonymousType={isAnonymousType}
        waitEventContextTags={waitEventContextTags}
      />
        )}

            {isEmailCreate && (
      <EmailWrapper
        key="creatives-email-wrapper"
        isEditEmail={false}
        date={new Date().getMilliseconds()}
        setIsLoadingContent={setIsLoadingContent}
        onEmailModeChange={onEmailModeChange}
        emailCreateMode={emailCreateMode}
        isGetFormData={isGetFormData}
        getFormdata={getFormData}
        templateData={templateData}
        type={type}
        step={templateStep}
        showNextStep={onCreateNextStep}
        isFullMode={isFullMode}
        editor={editor}
        cap={cap}
        onResetStep={onResetStep}
        showTemplateName={showTemplateName}
        onEnterTemplateName={onEnterTemplateName}
        onRemoveTemplateName={onRemoveTemplateName}
        onValidationFail={onValidationFail}
        forwardedTags={forwardedTags}
        selectedOfferDetails={selectedOfferDetails}
        onPreviewContentClicked={onPreviewContentClicked}
        onTestContentClicked={onTestContentClicked}
        getCmsTemplatesInProgress={getCmsTemplatesInProgress}
        moduleType={moduleType}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        isLoyaltyModule={isLoyaltyModule}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        isTestAndPreviewMode={isTestAndPreviewMode}
        location={location}
        onHtmlEditorValidationStateChange={onHtmlEditorValidationStateChange}
        restrictPersonalization={restrictPersonalization}
        isAnonymousType={isAnonymousType}
      />
        )}
      {(isEditEmailWithId || isEmailEditWithContent) && (
        (() => {
          const supportCKEditor = commonUtil.hasSupportCKEditor();
          // BEE templates always use the <Email> component directly (the same
          // path the SUPPORT_CK_EDITOR=true branch uses). EmailWrapper's
          // useEmailWrapper strips templateData from props, so library-mode
          // pencil-edit on a BEE template would never reach startTemplateCreation
          // and getDetails?type=BEE_PLUGIN would never fire. Routing BEE
          // templates through the direct <Email> path — which is already
          // battle-tested for the CKEditor flow — sidesteps that entirely.
          const isBEETemplate = templateData?.base?.is_drag_drop === true
            || templateData?.base?.is_drag_drop === 1;
          if (supportCKEditor || isBEETemplate) {
            return (
              <Email
                key="cretives-container-email-edit"
                setIsLoadingContent={setIsLoadingContent}
                location={{
                  pathname: `/email/edit`,
                  query: { type: 'embedded', module: 'library'},
                }}
                route={{ name: 'email' }}
                isGetFormData={isGetFormData}
                getFormdata={getFormData}
                params={{ id: templateData._id }}
                templateData={templateData}
                getFormSubscriptionData={getFormData}
                getDefaultTags={type}
                isFullMode={isFullMode}
                editor={editor}
                cap={cap}
                showTemplateName={showTemplateName}
                onValidationFail={onValidationFail}
                forwardedTags={forwardedTags}
                selectedOfferDetails={selectedOfferDetails}
                onPreviewContentClicked={onPreviewContentClicked}
                onTestContentClicked={onTestContentClicked}
                moduleType={moduleType}
                showLiquidErrorInFooter={showLiquidErrorInFooter}
                eventContextTags={eventContextTags}
                waitEventContextTags={waitEventContextTags}
              isLoyaltyModule={isLoyaltyModule}
              showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
              handleTestAndPreview={handleTestAndPreview}
              handleCloseTestAndPreview={handleCloseTestAndPreview}
              isTestAndPreviewMode={isTestAndPreviewMode}
              onHtmlEditorValidationStateChange={onHtmlEditorValidationStateChange}
            />
            );
          }     
          // HTML template: Use EmailWrapper component (which uses EmailWithoutSaga)
          return (
            <EmailWrapper
              key="cretives-container-email-edit-wrapper"
              isEditEmail
              setIsLoadingContent={setIsLoadingContent}
              onEmailModeChange={onEmailModeChange}
              emailCreateMode="editor"
              isGetFormData={isGetFormData}
              getFormdata={getFormData}
              templateData={templateData}
              type={type}
              step="createTemplateContent"
              showNextStep={onCreateNextStep}
              isFullMode={isFullMode}
              editor={editor}
              cap={cap}
              onResetStep={onResetStep}
              showTemplateName={showTemplateName}
              onEnterTemplateName={onEnterTemplateName}
              onRemoveTemplateName={onRemoveTemplateName}
              onValidationFail={onValidationFail}
              forwardedTags={forwardedTags}
              selectedOfferDetails={selectedOfferDetails}
              onPreviewContentClicked={onPreviewContentClicked}
              onTestContentClicked={onTestContentClicked}
              getCmsTemplatesInProgress={getCmsTemplatesInProgress}
              moduleType={moduleType}
              showLiquidErrorInFooter={showLiquidErrorInFooter}
              eventContextTags={eventContextTags}
              waitEventContextTags={waitEventContextTags}
              isLoyaltyModule={isLoyaltyModule}
              showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
              handleTestAndPreview={handleTestAndPreview}
              handleCloseTestAndPreview={handleCloseTestAndPreview}
              isTestAndPreviewMode={isTestAndPreviewMode}
              onHtmlEditorValidationStateChange={onHtmlEditorValidationStateChange}
              location={{
                pathname: `/email/edit/${templateData._id || ''}`,
                query: {
                  type: 'embedded',
                  module: 'library',
                  ...(templateData._id ? { id: templateData._id } : {}),
                },
              }}
              params={{ id: templateData._id }}
            />
          );
        })()
      )}
      {isEditMPush && (
        (isFullMode && !commonUtil.hasNewMobilePushFeatureEnabled()) || 
        (!isFullMode && isLoyaltyModule) || 
        (!isFullMode && !isLoyaltyModule && !commonUtil.hasNewMobilePushFeatureEnabled()) ? (
          <MobliPushEdit
            getFormLibraryData={getFormData}
            setIsLoadingContent={setIsLoadingContent}
            getLiquidTags={getLiquidTags}
            location={{
              pathname: `/mobilepush/edit/`,
              query,
            }}
            params={{ id: templateData._id }}
            isFullMode={isFullMode}
            isGetFormData={isGetFormData}
            route={{ name: 'mobilepush' }}
            templateData={templateData}
            showTemplateName={showTemplateName}
            getDefaultTags={type}
            onValidationFail={onValidationFail}
            forwardedTags={forwardedTags}
            selectedOfferDetails={selectedOfferDetails}
            onPreviewContentClicked={onPreviewContentClicked}
            onTestContentClicked={onTestContentClicked}
            type={type}
            hideTestAndPreviewBtn={hideTestAndPreviewBtn}
            creativesMode={creativesMode}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
            showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
            handleTestAndPreview={handleTestAndPreview}
            handleCloseTestAndPreview={handleCloseTestAndPreview}
            restrictPersonalization={restrictPersonalization}
            isAnonymousType={isAnonymousType}
            onPersonalizationTokensChange={onPersonalizationTokensChange}
          />
        ) : (
          <MobilePushNew
            getFormLibraryData={getFormData}
            setIsLoadingContent={setIsLoadingContent}
            location={{
              pathname: `/mobilepush/edit/`,
              query,
            }}
            params={{ id: templateData._id }}
            isFullMode={isFullMode}
            isGetFormData={isGetFormData}
            route={{ name: 'mobilepush' }}
            templateData={templateData}
            showTemplateName={showTemplateName}
            getDefaultTags={type}
            onValidationFail={onValidationFail}
            forwardedTags={forwardedTags}
            selectedOfferDetails={selectedOfferDetails}
            onPreviewContentClicked={onPreviewContentClicked}
            onTestContentClicked={onTestContentClicked}
            type={type}
            hideTestAndPreviewBtn={hideTestAndPreviewBtn}
            creativesMode={creativesMode}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
            handleClose={handleClose}
            restrictPersonalization={restrictPersonalization}
            isAnonymousType={isAnonymousType}
            onPersonalizationTokensChange={onPersonalizationTokensChange}
          />
        )
      )}
      {isCreateMPush && (
        (isFullMode && !commonUtil.hasNewMobilePushFeatureEnabled()) || 
        (!isFullMode && isLoyaltyModule) || 
        (!isFullMode && !isLoyaltyModule && !commonUtil.hasNewMobilePushFeatureEnabled()) ? (
          <MobilepushWrapper
            key="creatives-mobilepush-wrapper"
            date={new Date().getMilliseconds()}
            setIsLoadingContent={setIsLoadingContent}
            onMobilepushModeChange={onMobilepushModeChange}
            mobilePushCreateMode={mobilePushCreateMode}
            isGetFormData={isGetFormData}
            getFormData={getFormData}
            getLiquidTags={getLiquidTags}
            templateData={templateData}
            type={type}
            step={templateStep}
            showNextStep={onCreateNextStep}
            isFullMode={isFullMode}
            onEnterTemplateName={onEnterTemplateName}
            onRemoveTemplateName={onRemoveTemplateName}
            cap={cap}
            onResetStep={onResetStep}
            showTemplateName={showTemplateName}
            query={query}
            forwardedTags={forwardedTags}
            onValidationFail={onValidationFail}
            selectedOfferDetails={selectedOfferDetails}
            onPreviewContentClicked={onPreviewContentClicked}
            hideTestAndPreviewBtn={hideTestAndPreviewBtn}
            onTestContentClicked={onTestContentClicked}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
            showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
            handleTestAndPreview={handleTestAndPreview}
            handleCloseTestAndPreview={handleCloseTestAndPreview}
            restrictPersonalization={restrictPersonalization}
            isAnonymousType={isAnonymousType}
            onPersonalizationTokensChange={onPersonalizationTokensChange}
          />
        ) : (
          <MobilePushNew
            key="creatives-mobilepush-create-new"
            date={new Date().getMilliseconds()}
            setIsLoadingContent={setIsLoadingContent}
            onMobilepushModeChange={onMobilepushModeChange}
            mobilePushCreateMode={mobilePushCreateMode}
            isGetFormData={isGetFormData}
            getFormLibraryData={getFormData}
            location={location}
            getDefaultTags={type}
            templateData={templateData}
            type={type}
            handleClose={handleClose}
            step={templateStep}
            showNextStep={onCreateNextStep}
            isFullMode={isFullMode}
            onEnterTemplateName={onEnterTemplateName}
            onRemoveTemplateName={onRemoveTemplateName}
            cap={cap}
            onResetStep={onResetStep}
            showTemplateName={showTemplateName}
            query={query}
            forwardedTags={forwardedTags}
            onValidationFail={onValidationFail}
            selectedOfferDetails={selectedOfferDetails}
            onPreviewContentClicked={onPreviewContentClicked}
            hideTestAndPreviewBtn={hideTestAndPreviewBtn}
            onTestContentClicked={onTestContentClicked}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
            onCreateComplete={onCreateComplete}
            creativesMode={creativesMode}
            restrictPersonalization={restrictPersonalization}
            isAnonymousType={isAnonymousType}
          />
        )
      )}
      {
        isCreateFacebook && (
          <Facebook
            templateData={templateData}
            messageDetails={messageDetails}
            cap={cap}
            onFacebookSubmit={onFacebookSubmit}
            onCreateComplete={onCreateComplete}
            setIsLoadingContent={setIsLoadingContent}
            isFullMode={isFullMode}
            createNew
            getFormSubscriptionData={getFormData}
            messageStrategy={messageStrategy}
            fbAdManager={fbAdManager}
            onSelectTemplate={onSelectTemplate}
            orgUnitId={orgUnitId}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
          />
        )
      }
      {
        isEditFacebook && (
          <Facebook
            templateData={templateData}
            messageDetails={messageDetails}
            cap={cap}
            createNew={onCreateNew}
            onFacebookSubmit={onFacebookSubmit}
            onCreateComplete={onCreateComplete}
            isFullMode={isFullMode}
            params={{
              id: templateData._id,
            }}
            getFormSubscriptionData={getFormData}
            fbAdManager={fbAdManager}
            onSelectTemplate={onSelectTemplate}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
          />
        )
      }
      {
        isEditLine && (
          <LineContainer
            location={creativesLocationProps}
            params={{
              id: templateData._id,
              mode: templateData.modeType || (templateData.definition && templateData.definition.mode),
            }}
            route={{ name: (templateData.modeType || (templateData.definition && templateData.definition.mode)) === 'image' ? 'edit_image' : 'edit_text' }}
            onCreateComplete={onCreateComplete}
            isFullMode={isFullMode}
            saveMessage={saveMessage}
            getFormSubscriptionData={getFormData}
            isGetFormData={isGetFormData}
            templateData={templateData}
            selectedAccount={selectedAccount}
            handleClose={handleClose}
            selectedOfferDetails={selectedOfferDetails}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
          />
        )
      }
      {
        isCreateLine && (
          <LineContainer
            location={creativesLocationProps}
            onCreateComplete={onCreateComplete}
            isFullMode={isFullMode}
            isGetFormData={isGetFormData}
            saveMessage={saveMessage}
            selectedAccount={selectedAccount}
            templateData={templateData}
            getFormSubscriptionData={getFormData}
            onShowTemplates={onShowTemplates}
            createNew
            handleClose={handleClose}
            selectedOfferDetails={selectedOfferDetails}
            eventContextTags={eventContextTags}
            waitEventContextTags={waitEventContextTags}
            showLiquidErrorInFooter={showLiquidErrorInFooter}
          />
        )
      }
      {isCreateViber && (
        <Viber
          location={creativesLocationProps}
          onCreateComplete={onCreateComplete}
          isFullMode={isFullMode}
          handleClose={handleClose}
          isGetFormData={isGetFormData}
          getFormSubscriptionData={getFormData}
          onShowTemplates={onShowTemplates}
          templateData={templateData}
          selectedOfferDetails={selectedOfferDetails}
          eventContextTags={eventContextTags}
          waitEventContextTags={waitEventContextTags}
          showLiquidErrorInFooter={showLiquidErrorInFooter}
          showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
          handleTestAndPreview={handleTestAndPreview}
          handleCloseTestAndPreview={handleCloseTestAndPreview}
          createNew/>
      )}

      {isEditViber && <Viber
        location={creativesLocationProps}
        params={{
          id: templateData._id,
        }}
        onCreateComplete={onCreateComplete}
        isFullMode={isFullMode}
        handleClose={handleClose}
        isGetFormData={isGetFormData}
        getFormSubscriptionData={getFormData}
        onShowTemplates={onShowTemplates}
        templateData={templateData}
        selectedOfferDetails={selectedOfferDetails}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        createNew/> }

      {isCreateWhatsapp && (<Whatsapp
        isFullMode={isFullMode}
        onCreateComplete={onCreateComplete}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        handleClose={handleClose}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        isTestAndPreviewMode={isTestAndPreviewMode}
        />
      )}

      {isEditWhatsapp && (<Whatsapp
        isFullMode={isFullMode}
        templateData={templateData}
        getFormData={getFormData}
        getDefaultTags={type}
        forwardedTags={forwardedTags}
        selectedOfferDetails={selectedOfferDetails}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        isTestAndPreviewMode={isTestAndPreviewMode}
        params={{
          id: templateData._id,
        }}
        location={{
          pathname: `/whatsapp/edit`,
          query,
          search: '',
        }}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        />
      )}

      {isCreateInApp && (
  (isFullMode && !commonUtil.hasNewEditorFlowInAppEnabled()) ||
  (!isFullMode && isLoyaltyModule) ||
  (!isFullMode && !isLoyaltyModule && !commonUtil.hasNewEditorFlowInAppEnabled()) ? (
    <InApp
      key="creatives-inapp-create"
      location={{ pathname: '/inapp/create', query, search: '' }}
      setIsLoadingContent={setIsLoadingContent}
      isGetFormData={isGetFormData}
      getFormData={getFormData}
      getDefaultTags={type}
      isFullMode={isFullMode}
      templateData={templateData}
      cap={cap}
      showTemplateName={showTemplateName}
      showLiquidErrorInFooter={showLiquidErrorInFooter}
      onValidationFail={onValidationFail}
      forwardedTags={forwardedTags}
      selectedOfferDetails={selectedOfferDetails}
      onPreviewContentClicked={onPreviewContentClicked}
      onTestContentClicked={onTestContentClicked}
      eventContextTags={eventContextTags}
      waitEventContextTags={waitEventContextTags}
      onCreateComplete={onCreateComplete}
      handleClose={handleClose}
      moduleType={moduleType}
      showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
      handleTestAndPreview={handleTestAndPreview}
      handleCloseTestAndPreview={handleCloseTestAndPreview}
      isTestAndPreviewMode={isTestAndPreviewMode}
    />
  ) : (
    <InAppWrapper
      key="creatives-inapp-wrapper"
          date={new Date().getMilliseconds()}
          setIsLoadingContent={setIsLoadingContent}
          onInAppEditorTypeChange={onInAppEditorTypeChange}
          inAppEditorType={inAppEditorType}
          isGetFormData={isGetFormData}
          getFormdata={getFormData}
          templateData={templateData}
          type={type}
          step={templateStep}
          showNextStep={onCreateNextStep}
          isFullMode={isFullMode}
          cap={cap}
          onResetStep={onResetStep}
          showTemplateName={showTemplateName}
          onEnterTemplateName={onEnterTemplateName}
          onRemoveTemplateName={onRemoveTemplateName}
          onValidationFail={onValidationFail}
          forwardedTags={forwardedTags}
          selectedOfferDetails={selectedOfferDetails}
          onPreviewContentClicked={onPreviewContentClicked}
          onTestContentClicked={onTestContentClicked}
          moduleType={moduleType}
          showLiquidErrorInFooter={showLiquidErrorInFooter}
          eventContextTags={eventContextTags}
          waitEventContextTags={waitEventContextTags}
          onCreateComplete={onCreateComplete}
          handleClose={handleClose}
          getDefaultTags={type}
          onInAppModeChange={onInAppModeChange}
          inAppCreateMode={inAppCreateMode}
          showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        isTestAndPreviewMode={isTestAndPreviewMode}
      />
      )
      )}
  
      {isEditInApp && (<InApp
        isFullMode={isFullMode}
        isLoyaltyModule={isLoyaltyModule}
        templateData={templateData}
        getFormData={getFormData}
        getDefaultTags={type}
        forwardedTags={forwardedTags}
        onCreateComplete={onCreateComplete}
        selectedOfferDetails={selectedOfferDetails}
        eventContextTags={eventContextTags}
        waitEventContextTags={waitEventContextTags}
        params={{
          id: templateData._id,
        }}
        location={{
          pathname: `/inapp/edit`,
          query,
          search: '',
        }}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        isTestAndPreviewMode={isTestAndPreviewMode}
      />
      )}

      {(isCreateWebPush || isEditWebPush) && (
        <WebPush
          isFullMode={isFullMode}
          handleClose={handleClose}
          onCreateComplete={onCreateComplete}
          getFormData={getFormData}
          isGetFormData={isGetFormData}
          templateData={isEditWebPush ? templateData : undefined}
          creativesMode={creativesMode}
          params={isEditWebPush && templateData ? { id: templateData._id } : undefined}
          location={{
            pathname: isEditWebPush ? '/webpush/edit' : '/webpush/create',
            query,
            search: '',
          }}
          getDefaultTags={type}
          forwardedTags={forwardedTags}
          supportedTags={supportedTags}
          selectedOfferDetails={selectedOfferDetails}
          eventContextTags={eventContextTags}
          restrictPersonalization={restrictPersonalization}
          isAnonymousType={isAnonymousType}
          waitEventContextTags={waitEventContextTags}
        />
      )}
      {isCreateRcs && (<Rcs
        {...rcsCommonProps}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        location={{
          pathname: `/rcs/create`,
          query,
          search: '',
        }} />
      )}
      {isEditRcs && (<Rcs
        {...rcsCommonProps}
        showLiquidErrorInFooter={showLiquidErrorInFooter}
        showTestAndPreviewSlidebox={showTestAndPreviewSlidebox}
        handleTestAndPreview={handleTestAndPreview}
        handleCloseTestAndPreview={handleCloseTestAndPreview}
        templateData={templateData}
        params={{
          id: templateData._id,
        }}
        location={{
          pathname: `/rcs/edit`,
          query,
          search: '',
        }} />
      )}

    </CreativesWrapper>
  );
}
SlideBoxContent.propTypes = {
  slidBoxContent: PropTypes.node,
  onSelectTemplate: PropTypes.func,
  onPreviewTemplate: PropTypes.func,
  templateData: PropTypes.object,
  onInAppEditorTypeChange: PropTypes.func,
  inAppEditorType: PropTypes.object,
  location: PropTypes.object,
  isGetFormData: PropTypes.bool,
  getFormData: PropTypes.func,
  messageDetails: PropTypes.object,
  onCreateNew: PropTypes.func,
  onChannelChange: PropTypes.func,
  currentChannel: PropTypes.string,
  onEmailModeChange: PropTypes.func,
  onFacebookAdModeChange: PropTypes.func,
  emailCreateMode: PropTypes.string,
  templateStep: PropTypes.string,
  onCreateNextStep: PropTypes.func,
  onEnterTemplateName: PropTypes.func,
  onRemoveTemplateName: PropTypes.func,
  cap: PropTypes.object,
  onResetStep: PropTypes.func,
  onCallTaskSubmit: PropTypes.func,
  isFullMode: PropTypes.bool,
  setIsLoadingContent: PropTypes.func,
  onMobilepushModeChange: PropTypes.func,
  mobilePushCreateMode: PropTypes.string,
  showTemplateName: PropTypes.func,
  onValidationFail: PropTypes.func,
  channelsToHide: PropTypes.array,
  forwardedTags: PropTypes.object,
  supportedTags: PropTypes.array,
  selectedOfferDetails: PropTypes.array,
  channelsToDisable: PropTypes.array,
  weChatTemplateType: PropTypes.string,
  onWechatTemplateChange: PropTypes.func,
  selectedWeChatAccount: PropTypes.object,
  loyaltyMetaData: PropTypes.object,
  onWeChatMaptemplateStepChange: PropTypes.func,
  weChatMaptemplateStep: PropTypes.string,
  onFacebookSubmit: PropTypes.func,
  onCreateComplete: PropTypes.func,
  saveMessage: PropTypes.func,
  selectedAccount: PropTypes.object,
  onFTPSubmit: PropTypes.func,
  messageStrategy: PropTypes.string,
  fbAdManager: PropTypes.string,
  showDisabledFBInfo: PropTypes.bool,
  orgUnitId: PropTypes.any,
  smsRegister: PropTypes.any,
  getCmsTemplatesInProgress: PropTypes.bool,
  moduleType: PropTypes.string,
  showLiquidErrorInFooter: PropTypes.bool,
  creativesMode: PropTypes.string,
  hostName: PropTypes.string,
  showTestAndPreviewSlidebox: PropTypes.bool,
  handleTestAndPreview: PropTypes.func,
  handleCloseTestAndPreview: PropTypes.func,
  isTestAndPreviewMode: PropTypes.bool,
  waitEventContextTags: PropTypes.object,
  eventContextTags: PropTypes.array,
};
export default SlideBoxContent;
