/* eslint-disable no-unused-expressions */
import React, { useState, useEffect, useCallback } from 'react';
import { bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import { injectIntl, FormattedMessage } from 'react-intl';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import isNil from 'lodash/isNil';
import styled from 'styled-components';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapAlert from '@capillarytech/cap-ui-library/CapAlert';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapRadioGroup from '@capillarytech/cap-ui-library/CapRadioGroup';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
import CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapImage from '@capillarytech/cap-ui-library/CapImage';
import CapCard from '@capillarytech/cap-ui-library/CapCard';
import CapSlideBox from '@capillarytech/cap-ui-library/CapSlideBox';
import CapSelect from '@capillarytech/cap-ui-library/CapSelect';
import CapCustomCard from '@capillarytech/cap-ui-library/CapCustomCard';
import CapDropdown from '@capillarytech/cap-ui-library/CapDropdown';
import CapMenu from '@capillarytech/cap-ui-library/CapMenu';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import CapTooltipWithInfo from '@capillarytech/cap-ui-library/CapTooltipWithInfo';
import CapError from '@capillarytech/cap-ui-library/CapError';
import CapCheckbox from '@capillarytech/cap-ui-library/CapCheckbox';
import CapAskAira from '@capillarytech/cap-ui-library/CapAskAira';
import CapLink from '@capillarytech/cap-ui-library/CapLink';

import {
  CAP_G01,
  CAP_SPACE_04,
  CAP_SPACE_16,
  CAP_SPACE_24,
  CAP_SPACE_28,
  CAP_SPACE_32,
  CAP_WHITE,
  CAP_SECONDARY,
} from '@capillarytech/cap-ui-library/styled/variables';

import CapVideoUpload from '../../v2Components/CapVideoUpload';
import * as globalActions from '../Cap/actions';
import CapActionButton from '../../v2Components/CapActionButton';
import { makeSelectRcs, makeSelectAccount } from './selectors';
import { DATE_DISPLAY_FORMAT, TIME_DISPLAY_FORMAT } from '../App/constants';
import {
  isLoadingMetaEntities,
  makeSelectMetaEntities,
  setInjectedTags,
} from '../Cap/selectors';
import * as RcsActions from './actions';
import { isAiContentBotDisabled } from '../../utils/common';
import * as TemplatesActions from '../Templates/actions';
import './index.scss';
import {
  RCS,
  SMS,
  RCS_MEDIA_TYPES,
  TEMPLATE_TITLE_MAX_LENGTH,
  FALLBACK_MESSAGE_MAX_LENGTH,
  TAG,
  EMBEDDED,
  DEFAULT,
  FULL,
  ALL,
  LIBRARY,
  ALLOWED_IMAGE_EXTENSIONS_REGEX,
  RCS_IMG_SIZE,
  RCS_DLT_MODE,
  CTA,
  RCS_STATUSES,
  TITLE_TEXT,
  MESSAGE_TEXT,
  ALLOWED_EXTENSIONS_VIDEO_REGEX,
  RCS_VIDEO_SIZE,
  TEMPLATE_HEADER_MAX_LENGTH,
  TEMPLATE_MESSAGE_MAX_LENGTH,
  RCS_THUMBNAIL_MIN_SIZE,
  RCS_THUMBNAIL_MAX_SIZE,
  contentType,
  rcsVarRegex,
  rcsVarTestRegex,
  RCS_IMAGE_DIMENSIONS,
  RCS_TEXT_MESSAGE_MAX_LENGTH,
  RCS_RICH_CARD_MAX_LENGTH,
  RCS_VIDEO_THUMBNAIL_DIMENSIONS,
  MAX_BUTTONS,
  INITIAL_SUGGESTIONS_DATA_STOP,
  RCS_BUTTON_TYPES,
  titletype,
  descType,
  STANDALONE,
  VERTICAL,
  SMALL,
  MEDIUM,
  RICHCARD,
} from './constants';
import globalMessages from '../Cap/messages';
import messages from './messages';
import creativesMessages from '../CreativesContainer/messages';
import withCreatives from '../../hoc/withCreatives';
import UnifiedPreview from '../../v2Components/CommonTestAndPreview/UnifiedPreview';
import { ANDROID } from '../../v2Components/CommonTestAndPreview/constants';
import TestAndPreviewSlidebox from '../../v2Components/TestAndPreviewSlidebox';
import CapImageUpload from '../../v2Components/CapImageUpload';
import addCreativesIcon from '../Assets/images/addCreativesIllustration.svg';
import Templates from '../Templates';
import SmsTraiEdit from '../SmsTrai/Edit';
import TagList from '../TagList';
import { validateTags } from '../../utils/tagValidations';
import { getCdnUrl } from '../../utils/cdnTransformation';
import { isTagIncluded } from '../../utils/commonUtils';
import injectReducer from '../../utils/injectReducer';
import v2RcsReducer from './reducer';
import { getTemplateStatusType } from './utils';


const { Group: CapCheckboxGroup } = CapCheckbox;
export const Rcs = (props) => {
  const {
    intl,
    actions,
    isFullMode,
    onCreateComplete,
    params,
    templateData = {},
    rcsData = {},
    thumbnailData = {}, // Add separate thumbnail data
    templatesActions,
    globalActions,
    location,
    handleClose,
    getDefaultTags,
    supportedTags,
    metaEntities,
    injectedTags,
    loadingTags,
    getFormData,
    isDltEnabled,
    smsRegister,
    selectedOfferDetails,
    eventContextTags,
    waitEventContextTags,
    accountData = {},
    // TestAndPreviewSlidebox props
    showTestAndPreviewSlidebox: propsShowTestAndPreviewSlidebox,
    handleTestAndPreview: propsHandleTestAndPreview,
    handleCloseTestAndPreview: propsHandleCloseTestAndPreview,
  } = props || {};
  const { formatMessage } = intl;
  const { TextArea } = CapInput;
  const { CapCustomCardList } = CapCustomCard;
  const [isEditFlow, setEditFlow] = useState(false);
  const [tags, updateTags] = useState([]);
  const [spin, setSpin] = useState(false);
  //template
  const [templateName, setTemplateName] = useState('');
  const [templateNameError, setTemplateNameError] = useState(false);
  const [templateMediaType, setTemplateMediaType] = useState(
    RCS_MEDIA_TYPES.NONE,
  );
  const [templateRejectionReason, setTemplateRejectionReason] = useState(null);
  const [templateTitle, setTemplateTitle] = useState('');
  const [templateDesc, setTemplateDesc] = useState('');
  const [templateDescError, setTemplateDescError] = useState(false);
  const [templateStatus, setTemplateStatus] = useState('');
  const [templateDate, setTemplateDate] = useState('');
  //fallback
  const [fallbackMessage, setFallbackMessage] = useState('');
  const [fallbackMessageError, setFallbackMessageError] = useState(false);
  //fallback dlt
  const [showDltContainer, setShowDltContainer] = useState(false);
  const [dltMode, setDltMode] = useState('');
  const [dltEditData, setDltEditData] = useState({});
  const [showDltCard, setShowDltCard] = useState(false);
  const [fallbackPreviewmode, setFallbackPreviewmode] = useState(false);
  const [dltPreviewData, setDltPreviewData] = useState('');
  const [suggestions, setSuggestions] = useState(INITIAL_SUGGESTIONS_DATA_STOP);
  const [buttonType, setButtonType] = useState(RCS_BUTTON_TYPES.NONE);
  const [suggestionError, setSuggestionError] = useState(true);
  const [templateType, setTemplateType] = useState('text_message');
  const [templateHeader, setTemplateHeader] = useState('');
  const [templateMessage, setTemplateMessage] = useState('');
  const [templateHeaderError, setTemplateHeaderError] = useState('');
  const [templateMessageError, setTemplateMessageError] = useState('');
  const validVarRegex = /\{\{(\d+)\}\}/g;
  const [updatedTitleData, setUpdatedTitleData] = useState([]);
  const [updatedDescData, setUpdatedDescData] = useState([]);
  const [titleVarMappedData, setTitleVarMappedData] = useState({});
  const [descVarMappedData, setDescVarMappedData] = useState({});
  const [titleTextAreaId, setTitleTextAreaId] = useState();
  const [descTextAreaId, setDescTextAreaId] = useState();
  const [assetList, setAssetList] = useState({});
  const [assetListImage, setAssetListImage] = useState('');
  const [rcsImageSrc, updateRcsImageSrc] = useState('');
  const [rcsVideoSrc, setRcsVideoSrc] = useState({});
  const [rcsThumbnailSrc, setRcsThumbnailSrc] = useState('');
  const [selectedDimension, setSelectedDimension] = useState(RCS_IMAGE_DIMENSIONS.MEDIUM_HEIGHT.type);
  const [imageError, setImageError] = useState(null);
  const [templateTitleError, setTemplateTitleError] = useState(false);
  const [cardVarMapped, setCardVarMapped] = useState({});

  // TestAndPreviewSlidebox state
  const [showTestAndPreviewSlidebox, setShowTestAndPreviewSlidebox] = useState(false);
  const [isTestAndPreviewMode, setIsTestAndPreviewMode] = useState(false);

  const tempMsg = dltPreviewData === '' ? fallbackMessage : dltPreviewData;

  // Get template content for TestAndPreviewSlidebox
  // Reference: Based on getRcsPreview() function (lines 2087-2111) which prepares content for TemplatePreview
  // getRcsPreview ALWAYS uses templateTitle and templateDesc for ALL template types (text_message, rich_card, carousel)
  // renderTextComponent (lines 1317-1485) also uses templateTitle and templateDesc
  // Note: templateHeader and templateMessage are defined but NOT used in the component
  const getTemplateContent = useCallback(() => {
    const isMediaTypeImage = templateMediaType === RCS_MEDIA_TYPES.IMAGE;
    const isMediaTypeVideo = templateMediaType === RCS_MEDIA_TYPES.VIDEO;
    const isMediaTypeText = templateMediaType === RCS_MEDIA_TYPES.NONE;

    // Build media preview object (same pattern as getRcsPreview)
    const mediaPreview = {};
    if (isMediaTypeImage && rcsImageSrc) {
      mediaPreview.rcsImageSrc = rcsImageSrc;
    }
    if (isMediaTypeVideo && !isMediaTypeText) {
      // For video, use thumbnailSrc as rcsVideoSrc (same as getRcsPreview line 2104)
      if (rcsThumbnailSrc) {
        mediaPreview.rcsVideoSrc = rcsThumbnailSrc;
      } else if (rcsVideoSrc?.videoSrc) {
        mediaPreview.rcsVideoSrc = rcsVideoSrc.videoSrc;
      }
      // Also include thumbnailSrc separately if available
      if (rcsThumbnailSrc) {
        mediaPreview.rcsThumbnailSrc = rcsThumbnailSrc;
      }
    }

    // Build content object
    // Reference: getRcsPreview (line 2091-2092) uses templateTitle and templateDesc for ALL cases
    // templateTitle is used for rich_card/carousel title, empty for text_message
    // templateDesc is used for ALL types (text message body or rich card description)
    // For UnifiedPreview, we map templateTitle -> templateHeader and templateDesc -> templateMessage
    const contentObj = {
      // Map templateTitle to templateHeader and templateDesc to templateMessage
      templateHeader: templateTitle,
      templateMessage: templateDesc,
      ...mediaPreview,
      ...(suggestions.length > 0 && {
        suggestions: suggestions,
      }),
    };

    return contentObj;
  }, [
    templateMediaType,
    templateTitle,
    templateDesc,
    rcsImageSrc,
    rcsVideoSrc,
    rcsThumbnailSrc,
    suggestions,
    selectedDimension,
  ]);

  // Handle Test and Preview button click
  const handleTestAndPreview = useCallback(() => {
    setShowTestAndPreviewSlidebox(true);
    setIsTestAndPreviewMode(true);
    if (propsHandleTestAndPreview) {
      propsHandleTestAndPreview();
    }
  }, [propsHandleTestAndPreview]);

  // Handle close Test and Preview slidebox
  const handleCloseTestAndPreview = useCallback(() => {
    setShowTestAndPreviewSlidebox(false);
    setIsTestAndPreviewMode(false);
    if (propsHandleCloseTestAndPreview) {
      propsHandleCloseTestAndPreview();
    }
  }, [propsHandleCloseTestAndPreview]);

  // Helper to get RCS orientation from selectedDimension
  const getRcsOrientation = () => {
    const isMediaTypeImage = templateMediaType === RCS_MEDIA_TYPES.IMAGE;
    if (isMediaTypeImage) {
      return RCS_IMAGE_DIMENSIONS[selectedDimension]?.orientation || VERTICAL;
    }
    // For video
    return RCS_VIDEO_THUMBNAIL_DIMENSIONS[selectedDimension]?.orientation || VERTICAL;
  };

  const [accountId, setAccountId] = useState('');
  const [accessToken, setAccessToken] = useState('');
  const [hostName, setHostName] = useState('');
  const [accountName, setAccountName] = useState('');
  const [rcsAccount, setRcsAccount] = useState('');
  useEffect(() => {
    const accountObj = accountData.selectedRcsAccount || {};
    if (!isEmpty(accountObj)) {
      const {
        sourceAccountIdentifier = '',
        configs = {},
      } = accountObj;
      
      setAccountId(sourceAccountIdentifier);
      setAccessToken(configs.accessToken || '');
      setHostName(accountObj.hostName || '');
      setAccountName(accountObj.name || '');
      setRcsAccount(accountObj.id || '');
    }
  }, [accountData.selectedRcsAccount]);

  const isMediaTypeText = templateMediaType === RCS_MEDIA_TYPES.NONE;
  const isMediaTypeImage = templateMediaType === RCS_MEDIA_TYPES.IMAGE;
  const isMediaTypeVideo = templateMediaType === RCS_MEDIA_TYPES.VIDEO;

  const mediaRadioOptions = [
    {
      value: RCS_MEDIA_TYPES.IMAGE,
      label: formatMessage(messages.mediaImage),
    },
    {
      value: RCS_MEDIA_TYPES.VIDEO,
      label: formatMessage(messages.mediaVideo),
    },
  ];
  const aiContentBotDisabled = isAiContentBotDisabled();

  const updateButtonChange = (data, index) => {
    if (data && data.text) {
      const forbiddenError = forbiddenCharactersValidation(data.text);
      if (forbiddenError) {
        setSuggestionError(forbiddenError);
        return;
      } else {
        setSuggestionError(false);
      }
    }
    
    if(index==MAX_BUTTONS)
    {
      setSuggestions(data);
    }else {   
      setSuggestions(prev => {
        const updated = [...prev];
        updated[index] = data;
        return updated;
      });
    }
  };

  const deleteButtonHandler = (index) => {
    setSuggestions((prevState) => {
      const clonedCta = cloneDeep(prevState);
      const filteredCta = clonedCta.filter((i) => i.index !== index);
      const updatedIndex = filteredCta.map((i, idx) => ({...i, index: idx}));
      return updatedIndex;
    });
  };

  const validateResolvedTagsForType = (type) => {
    if (isFullMode) return;
    if (loadingTags || !tags || tags.length === 0) return;
    const templateStr = type === TITLE_TEXT ? templateTitle : templateDesc;
    const resolved = resolveTemplateWithMap(templateStr); // placeholders -> mapped value (or '')
    if (!resolved) {
      if (type === TITLE_TEXT) setTemplateTitleError(false);
      if (type === MESSAGE_TEXT) setTemplateDescError(false);
      return;
    }

    let contentForValidation = resolved;
    const placeholderTokens = templateStr.match(rcsVarRegex) || [];
    placeholderTokens.forEach((t) => {
      const escaped = t.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      contentForValidation = contentForValidation.replace(new RegExp(escaped, 'g'), '');
    });
    if (!contentForValidation.trim()) {
      if (type === TITLE_TEXT) setTemplateTitleError(false);
      if (type === MESSAGE_TEXT) setTemplateDescError(false);
      return;
    }

    const validationResponse =
      validateTags({
        content: contentForValidation,
        tagsParam: tags,
        location,
        tagModule: getDefaultTags,
        isFullMode,
      }) || {};
    const errorMsg =
      (validationResponse?.isBraceError &&
        formatMessage(globalMessages.unbalanacedCurlyBraces)) ||
      false;
    if (type === TITLE_TEXT) setTemplateTitleError(errorMsg);
    if (type === MESSAGE_TEXT) setTemplateDescError(errorMsg);
  };

  useEffect(() => {
    validateResolvedTagsForType(TITLE_TEXT);
  }, [cardVarMapped, templateTitle, tags, injectedTags, loadingTags]);

  useEffect(() => {
    validateResolvedTagsForType(MESSAGE_TEXT);
  }, [cardVarMapped, templateDesc, tags, injectedTags, loadingTags]);

  const getVarNameFromToken = (token = '') => token.replace(/^\{\{|\}\}$/g, '');

  const resolveTemplateWithMap = (str = '') => {
    if (!str) return '';
    const arr = splitTemplateVarString(str);
    return arr.map((elem) => {
      if (rcsVarTestRegex.test(elem)) {
        const key = getVarNameFromToken(elem);
        const v = cardVarMapped?.[key];
        if (isNil(v) || String(v)?.trim?.() === '') return elem;
        return String(v);
      }
      return elem;
    }).join('');
  };


  useEffect(() => {
    if (isFullMode || isEditFlow) return;
    const tokens = [
      ...(templateTitle ? (templateTitle.match(rcsVarRegex) || []) : []),
      ...(templateDesc ? (templateDesc.match(rcsVarRegex) || []) : []),
    ];
    if (!tokens.length) return;
    setCardVarMapped((prev) => {
      const next = { ...(prev || {}) };
      let changed = false;
      tokens.forEach((t) => {
        const name = getVarNameFromToken(t);
        if (name && !Object.prototype.hasOwnProperty.call(next, name)) {
          next[name] = '';
          changed = true;
        }
      });
      return changed ? next : prev;
    });
  }, [isFullMode, templateTitle, templateDesc]);


  const RcsLabel = styled.div`
    display: flex;
    margin-top: 20px;
  `;
  const paramObj = params || {};
  useEffect(() => {
  const { id } = paramObj;
  if (id && isFullMode) {
    setSpin(true);
    actions.getTemplateDetails(id, setSpin);
  }
  return () => {
    actions.clearEditResponse();
  };
  }, [paramObj.id]);

  useEffect(() => {
      if (!(isEditFlow || !isFullMode)) return;

      const initField = (targetString, currentVarMap, setVarMap, setUpdated) => {
        const arr = splitTemplateVarString(targetString);
        if (!arr?.length) {
          setVarMap({});
          setUpdated([]);
          return;
        }
        const nextVarMap = {};
        const nextUpdated = [...arr];
        arr.forEach((elem, idx) => {
          // RCS placeholders are alphanumeric/underscore (e.g. {{user_name}}), not numeric-only
          if (rcsVarTestRegex.test(elem)) {
            const id = `${elem}_${idx}`;
            const varName = getVarNameFromToken(elem);
            const mappedValue = (cardVarMapped?.[varName] ?? '').toString();
            nextVarMap[id] = mappedValue;
            if (mappedValue !== '') {
              nextUpdated[idx] = mappedValue;
            } else {
              nextUpdated[idx] = elem;
            }
          }
        });
        setVarMap(nextVarMap);
        setUpdated(nextUpdated);
      };

      initField(templateTitle, titleVarMappedData, setTitleVarMappedData, setUpdatedTitleData);
      initField(templateDesc, descVarMappedData, setDescVarMappedData, setUpdatedDescData);
    }, [templateTitle, templateDesc, cardVarMapped, isEditFlow, isFullMode]);
    
    useEffect(() => {
      if(!isEditFlow && isFullMode){
      setRcsVideoSrc({});
      updateRcsImageSrc('');
      setUpdateRcsImageSrc('');
      updateRcsThumbnailSrc('');
      setAssetList({});
      }
     }, [templateMediaType]);
  
    const templateStatusHelper = (details) => {
      const status = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].Status', '');
      switch (status) {
        case RCS_STATUSES.approved:
          setTemplateStatus(RCS_STATUSES.approved);
          break;
        case RCS_STATUSES.pending:
          setTemplateStatus(RCS_STATUSES.pending);
          break;
        case RCS_STATUSES.awaitingApproval:
          setTemplateStatus(RCS_STATUSES.awaitingApproval);
          break;
        case RCS_STATUSES.unavailable:
          setTemplateStatus(RCS_STATUSES.unavailable);
          break;
        case RCS_STATUSES.rejected:
          setTemplateStatus(RCS_STATUSES.rejected);
          break;
        default:
          setTemplateStatus(status);
          break;
      }
    };
  
    const setMediaData = (mediaData, mediaType, cardSettings ) => {
      if (mediaType) {
      setTemplateMediaType(mediaType);
    }
    const tempOrientation = cardSettings.cardOrientation;
    const tempAlignment = cardSettings.mediaAlignment;
    const tempHeight = mediaData.height;
    
    // Map to actual RCS_IMAGE_DIMENSIONS keys
    let tempDimension;
    if (tempAlignment) {
      // For horizontal orientations with alignment
      tempDimension = `HORIZONTAL_${tempAlignment}`;
    } else {
      // For vertical orientations with height
      if (tempHeight === 'SHORT') {
        tempDimension = 'SHORT_HEIGHT';
      } else if (tempHeight === 'MEDIUM') {
        tempDimension = 'MEDIUM_HEIGHT';
      } else {
        // Default fallback
        tempDimension = 'MEDIUM_HEIGHT';
      }
    }
    
    setSelectedDimension(tempDimension);
    if (mediaData) {
      if (mediaType === RCS_MEDIA_TYPES.IMAGE && mediaData.mediaUrl) {
        updateRcsImageSrc(mediaData.mediaUrl);
      } else if (mediaType === RCS_MEDIA_TYPES.VIDEO) {
        const videoData = {
          videoSrc: mediaData.mediaUrl || '',
          videoThumbnail: mediaData.thumbnailUrl || '',
          videoName: mediaData.videoName || '',
          videoHeight: mediaData.videoHeight,
          videoWidth: mediaData.videoWidth,
          videoId: mediaData.videoId,
          fileHandle: mediaData.fileHandle,
          videoDuration: mediaData.videoDuration,
        };
        setRcsVideoSrc(videoData);
        setRcsThumbnailSrc(videoData.videoThumbnail || '');
      }
    }
  };
  
  useEffect(() => {
    const details = isFullMode ? rcsData?.templateDetails : templateData;
    if (details && Object.keys(details).length > 0) {
      if (!isFullMode) {
        const tempCardVarMapped = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].cardVarMapped', {});
        setCardVarMapped(tempCardVarMapped);
      }
      const mediaType = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].mediaType', '');
      if (mediaType === RCS_MEDIA_TYPES.NONE) {
        setTemplateType(contentType.text_message);
      } else {
        setTemplateType(contentType.rich_card);
      }
      setEditFlow(true);
      setTemplateName(details.name || '');
      const loadedTitle = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].title', '');
      const loadedDesc = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].description', '');
      const loadedMap = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].cardVarMapped', {});
      const normalizedTitle = (!isFullMode && !isEmpty(loadedMap)) ? getUnmappedDesc(loadedTitle, loadedMap) : loadedTitle;
      const normalizedDesc = (!isFullMode && !isEmpty(loadedMap)) ? getUnmappedDesc(loadedDesc, loadedMap) : loadedDesc;
      setTemplateTitle(normalizedTitle);
      setTemplateDesc(normalizedDesc);
      setSuggestions(get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].suggestions', []));
      templateStatusHelper(details);
      const mediaData = get(details, 'versions.base.content.RCS.rcsContent.cardContent[0].media', '');
      const cardSettings = get(details, 'versions.base.content.RCS.rcsContent.cardSettings', '');
      setMediaData(mediaData, mediaType, cardSettings);
      if (details?.edit) {
        const rcsAccountId = get(details, 'versions.base.content.RCS.rcsContent.accountId', '');
        setRcsAccount(rcsAccountId);
      }
    }
  }, [rcsData, templateData, isFullMode, isEditFlow]);
  

  useEffect(() => {
    if (templateType === contentType.text_message) {
      setTemplateMediaType(RCS_MEDIA_TYPES.NONE);
      setTemplateTitle('');
      setTemplateTitleError('');
      if (!isEditFlow && isFullMode) {
        setUpdateRcsImageSrc('');
        setUpdateRcsVideoSrc({});
        setRcsVideoSrc({});
        setSelectedDimension(RCS_IMAGE_DIMENSIONS.MEDIUM_HEIGHT.type);
      }
    }
    if (!isFullMode && templateType === contentType.rich_card) {
      if (!rcsThumbnailSrc) {
        setTemplateMediaType(RCS_MEDIA_TYPES.IMAGE);
      } else {
        setTemplateMediaType(RCS_MEDIA_TYPES.VIDEO);
      }
    }
    if (templateType === contentType.rich_card && !isEditFlow && isFullMode) {
      setTemplateMediaType(RCS_MEDIA_TYPES.IMAGE);
      setRcsVideoSrc({});
      updateRcsImageSrc('');
      setRcsThumbnailSrc('');
    }
    if(isFullMode) {
      onTemplateDescChange({ target: { value: templateDesc } });
    }
  }, [templateType, isEditFlow, isFullMode]);
  
  useEffect(() => {
    if (!showDltContainer) {
      const { type, module } = location.query || {};
      const isEmbedded = type === EMBEDDED;
      const context = isEmbedded ? module : DEFAULT;
      const embedded = isEmbedded ? type : FULL;
      const query = {
        layout: SMS,
        type: TAG,
        context,
        embedded,
      };
      if (getDefaultTags) {
        query.context = getDefaultTags;
      }
      globalActions.fetchSchemaForEntity(query);
    }
  }, [showDltContainer]);

  useEffect(() => {
    let tag = get(metaEntities, `tags.standard`, []);
    const { type, module } = location.query || {};
    if (type === EMBEDDED && module === LIBRARY && !getDefaultTags) {
      tag = supportedTags;
    }
    updateTags(tag);
  }, [metaEntities]);

  const handleOnTagsContextChange = (data) => {
    const { type } = location.query || {};
    const tempData = (data || '').toLowerCase();
    const isEmbedded = type === EMBEDDED;
    const embedded = isEmbedded ? type : FULL;
    const context = tempData === ALL ? DEFAULT : tempData;
    const query = {
      layout: SMS,
      type: TAG,
      context,
      embedded,
    };
    globalActions.fetchSchemaForEntity(query);
  };

  const onTagSelect = (data, areaId) => {
    if (!areaId) return;
    const sep = areaId.lastIndexOf('_');
    if (sep === -1) return;
    const numId = Number(areaId.slice(sep + 1));
    if (isNaN(numId)) return;
    const token = areaId.slice(0, sep);
    const variableName = getVarNameFromToken(token);
    if (!variableName) return;
    setCardVarMapped((prev) => {
      const base = (prev?.[variableName] ?? '').toString();
      const nextVal = `${base}{{${data}}}`;
      return {
        ...(prev || {}),
        [variableName]: nextVal,
      };
    });
  };

  const onTitleTagSelect = (data) => onTagSelect(data, titleTextAreaId);

  const onDescTagSelect = (data) => onTagSelect(data, descTextAreaId);

  const onTagSelectFallback = (data) => {
    const tempMsg = `${fallbackMessage}{{${data}}}`;
    const error = fallbackMessageErrorHandler(tempMsg);
    setFallbackMessage(tempMsg);
    setFallbackMessageError(error);
  };


  //removing optout tag for rcs
  const getRcsTags = () => {
    const tempTags = cloneDeep(tags);
    // eslint-disable-next-line no-undef
    if (tempTags?.length > 0 && tempTags[0]?.definition?.value === 'optout') {
      tempTags.shift();
    }
    return tempTags;
  };
  // tag Code end

  const renderLabel = (value, showLabel, desc) => {
    const isTemplateApproved = (templateStatus === RCS_STATUSES.approved);
    return (
      <>
        <RcsLabel>
          <CapHeading type="h4">{formatMessage(messages[value])}</CapHeading>
        </RcsLabel>
        {desc && (
          <CapLabel type="label3" style={{ marginBottom: '17px' }}>
            {formatMessage(messages[desc])}
          </CapLabel>
        )}
      </>
    );
  };

  const TEMPLATE_TYPE_OPTIONS = [
    {
      value: contentType.text_message,
      label: formatMessage(messages.text_message),
    },
    {
      value: contentType.rich_card,
      label: formatMessage(messages.richCard),
    },
    {
      value: contentType.carousel,
      label: (
        <CapTooltip title={formatMessage(messages.disabledCarouselTooltip)}>
          {formatMessage(messages.carousel)}
        </CapTooltip>
      ),
      disabled: true,
    },
  ];

  const onTemplateNameChange = ({ target: { value } }) => {
    setTemplateName(value);
    templateNameErrorHandler(value);
  };


  const onTemplateTypeChange = ({ target: { value } }) => {
    setTemplateType(value);
  };


  const templateNameErrorHandler = (value) => {
    let errorMessage = false;
    if (value === '') {
      errorMessage = formatMessage(
        globalMessages.emptyTemplateNameErrorMessage,
      );
    } else if (value.length > 20) {
      errorMessage = formatMessage(messages.templateNameLengthError);
    } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      errorMessage = formatMessage(messages.templateNameFormatError);
    }
    setTemplateNameError(errorMessage);
  };

  const onTemplateMediaTypeChange = ({ target: { value } }) => {
    setTemplateMediaType(value);
  };


  const onTemplateTitleChange = ({ target: { value } }) => {
    let errorMessage = false;
    if (templateType === contentType.rich_card && !value.trim()) {
      errorMessage = formatMessage(messages.emptyTemplateTitleErrorMessage);
    } else if (value.length > TEMPLATE_TITLE_MAX_LENGTH) {
      errorMessage = formatMessage(messages.templateHeaderLengthError);
    } else {
      errorMessage = variableErrorHandling(value);
    }
    setTemplateTitle(value);
    setTemplateTitleError(errorMessage);
  };

  const onTemplateDescChange = ({ target: { value } }) => {
    let errorMessage = false;
    if(templateType === contentType.text_message && value?.length > RCS_TEXT_MESSAGE_MAX_LENGTH){
      errorMessage = formatMessage(messages.templateMessageLengthError);
     } else if(templateType === contentType.rich_card && value?.length > RCS_RICH_CARD_MAX_LENGTH){
      errorMessage = formatMessage(messages.templateMessageLengthError);
     } else {
      errorMessage = false;
    }
    const varError = variableErrorHandling(value);
    const error = errorMessage || varError;
    setTemplateDesc(value);
    setTemplateDescError(error);
  };


  const templateDescErrorHandler = (value) => {
    let errorMessage = false;
    const { isBraceError } = validateTags({
      content: value,
      tagsParam: tags,
      location,
      tagModule: getDefaultTags,
      isFullMode,
    }) || {};
    
    const maxLength = templateType === contentType.text_message 
      ? RCS_TEXT_MESSAGE_MAX_LENGTH 
      : RCS_RICH_CARD_MAX_LENGTH;
  
    if (value === '' && isMediaTypeText) {
      errorMessage = formatMessage(messages.emptyTemplateDescErrorMessage);
    } else if (value?.length > maxLength) {
      errorMessage = formatMessage(messages.templateMessageLengthError);
    }
    
    if (isBraceError) {
      errorMessage = formatMessage(globalMessages.unbalanacedCurlyBraces);
    }
    return errorMessage;
  };


  const onFallbackMessageChange = ({ target: { value } }) => {
    const error = fallbackMessageErrorHandler(value);
    setFallbackMessage(value);
    setFallbackMessageError(error);
  };

  const fallbackMessageErrorHandler = (value) => {
    if (value?.length > FALLBACK_MESSAGE_MAX_LENGTH) {
      return formatMessage(messages.fallbackMsgLenError);
    }
    return false;
  };

  // Check for forbidden characters: square brackets [] and single curly braces {}
  const forbiddenCharactersValidation = (value) => {
    if (!value) return false;
    
    // Check for square brackets
    if (value.includes('[') || value.includes(']')) {
      return formatMessage(messages.forbiddenCharactersError);
    }
    
    // Check for single curly braces (not part of {{variable}} format)
    // Remove valid {{variable}} patterns first, then check for remaining single braces
    const withoutValidVariables = value.replace(/\{\{[^}]*\}\}/g, '');
    if (withoutValidVariables.includes('{') || withoutValidVariables.includes('}')) {
      return formatMessage(messages.forbiddenCharactersError);
    }
    
    return false;
  };

  const variableErrorHandling = (value) => {
    if (!value) return false;
    
    // First check for forbidden characters
    const forbiddenError = forbiddenCharactersValidation(value);
    if (forbiddenError) {
      return forbiddenError;
    }
    
    // Check for unbalanced curly braces
    const openBraces = (value.match(/\{/g) || []).length;
    const closeBraces = (value.match(/\}/g) || []).length;
    if (openBraces !== closeBraces) {
      return formatMessage(messages.incompleteBracketsError);
    }
    const customParamRegex = /\{\{([^}]*)\}\}/g;
    let match;
    while ((match = customParamRegex.exec(value)) !== null) {
      const paramName = match[1];
      if (!paramName) {
        return formatMessage(messages.emptyVariableError);
      }
      if(!isFullMode){
        return false;
      }
      if (!/^\w+$/.test(paramName)) {
        return formatMessage(messages.unknownCharactersError);
      }
    }
    return false;
  };
  
  const templateHeaderErrorHandler = (value) => {
    let errorMessage = false;
    if (value?.length > TEMPLATE_HEADER_MAX_LENGTH) {
      errorMessage = formatMessage(messages.templateHeaderLengthError);
    } else {
      errorMessage = variableErrorHandling(value);
    }
    return errorMessage;
  };


  const templateMessageErrorHandler = (value) => {
    let errorMessage = false;
    if (value === '') {
      errorMessage = formatMessage(messages.emptyTemplateMessageErrorMessage);
    } else if (
      value?.length
      > TEMPLATE_MESSAGE_MAX_LENGTH
    ) {
      errorMessage = formatMessage(messages.templateMessageLengthError);
    } else {
      errorMessage = variableErrorHandling(value);
    }
    return errorMessage;
  };


  const onMessageAddVar = () => {
  onAddVar(MESSAGE_TEXT, templateDesc, rcsVarRegex);
};

const onAddVar = (type, messageContent, regex) => {
  // Always append the next variable at the end, like WhatsApp
  const existingVars = messageContent.match(/\{\{(\d+)\}\}/g) || [];
  const existingNumbers = existingVars.map(v => parseInt(v.match(/\d+/)[0], 10));
  let nextNumber = 1;
  while (existingNumbers.includes(nextNumber)) {
    nextNumber++;
  }
  if (nextNumber > 19) {
    return;
  }
  const nextVar = `{{${nextNumber}}}`;
  const tempMsg = messageContent + nextVar;
  const error = variableErrorHandling(tempMsg);

    setTemplateDesc(tempMsg);
    setTemplateDescError(error);
};

const onTitleAddVar = () => {
  // Always append the next variable at the end, like WhatsApp
  const messageContent = templateTitle;
  const existingVars = messageContent.match(/\{\{(\d+)\}\}/g) || [];
  const existingNumbers = existingVars.map(v => parseInt(v.match(/\d+/)[0], 10));
  let nextNumber = 1;
  while (existingNumbers.includes(nextNumber)) {
    nextNumber++;
  }
  if (nextNumber > 19) {
    return;
  }
  const nextVar = `{{${nextNumber}}}`;
  const tempTitle = messageContent + nextVar;

  const error = variableErrorHandling(tempTitle);

  setTemplateTitle(tempTitle);
  setTemplateTitleError(error);
};

  
const splitTemplateVarString = (str) => {
  if (!str) return [];
  const validVarArr = str.match(rcsVarRegex) || [];
  const templateVarArray = [];
  let content = str;
  while (content?.length !== 0) {
    const index = content.indexOf(validVarArr?.[0]);
    if (index !== -1) {
      templateVarArray.push(content.substring(0, index));
      templateVarArray.push(validVarArr?.[0]);
      content = content.substring(index + validVarArr?.[0]?.length, content?.length);
      validVarArr?.shift();
    } else {
      templateVarArray.push(content);
      break;
    }
  }
  return templateVarArray.filter(Boolean);
};

  const textAreaValue = (idValue, type) => {
    if (idValue >= 0) {
      const templateStr = type === TITLE_TEXT ? templateTitle : templateDesc;
      const templateArr = splitTemplateVarString(templateStr);
      const token = templateArr?.[idValue] || "";
      if (token && rcsVarTestRegex.test(token)) {
        const varName = getVarNameFromToken(token);
        return (cardVarMapped?.[varName] ?? '').toString();
      }
      return "";
    }
    return "";
  };

  const textAreaValueChange = (e, type) => {
    const value = e?.target?.value ?? '';
    const id = e?.target?.id || e?.currentTarget?.id || '';
    if (!id) return;
    const sep = id.lastIndexOf('_');
    if (sep === -1) return;
    const isInvalidValue = value?.trim() === "";
    const token = id.slice(0, sep);
    const variableName = getVarNameFromToken(token);

    if (variableName) {
      setCardVarMapped((prev) => ({
        ...prev,
        [variableName]: isInvalidValue ? "" : value,
      }));
    }
  };

  const setTextAreaId = (e, type) => {
    const id = e?.target?.id || e?.currentTarget?.id || '';
    if (!id) return;
    if (type === TITLE_TEXT) setTitleTextAreaId(id);
    else setDescTextAreaId(id);
  };

  const renderButtonComponent = () => {
    return (
      <>
        <CapHeader
          className="rcs-button-cta"
          title={
            <CapRow type="flex">
              <CapHeading type="h4">
                {formatMessage(messages.btnLabel)}
              </CapHeading>
            </CapRow>
          }
          description={
            <CapLabel type="label3">{formatMessage(messages.btnDesc)}</CapLabel>
          }
        />
        
        <CapActionButton
                        buttonType={buttonType}
                        updateButtonChange={updateButtonChange}
                        deleteButtonHandler={deleteButtonHandler}
                        suggestions={suggestions}
                        isEditFlow={isEditFlow}
                        isFullMode={isFullMode}
                        maxButtons={MAX_BUTTONS}
            />
      </>
    );
  };
  
  const renderedRCSEditMessage = (descArray, type) => {
    const renderArray = [];
    if (descArray?.length) {
      descArray.forEach((elem, index) => {
        if (rcsVarTestRegex.test(elem)) {
          // Variable input
          renderArray.push(
            <TextArea
              id={`${elem}_${index}`}
              key={`${elem}_${index}`}
              placeholder={`enter the value for ${elem}`}
              autosize={{ minRows: 1, maxRows: 3 }}
              onChange={e => textAreaValueChange(e, type)}
              value={textAreaValue(index, type)}
              onFocus={(e) => setTextAreaId(e, type)}
            />
          );
        } else if (elem) {
          // Static text
          renderArray.push(
            <TextArea
              key={`static_${index}`}
              value={elem}
              autosize={{ minRows: 1, maxRows: 3 }}
              disabled
              className="rcs-edit-template-message-static-textarea"
              style={{ background: '#fafafa', color: '#888' }}
            />
          );
        }
      });
    }
    return renderArray;
  };

  const renderTextComponent = () => {
    const isTemplateApproved = (templateStatus === RCS_STATUSES.approved);
    return (
      <>
      {templateType !== contentType.text_message && (
      <>
      <CapHeader
        className="rcs-template-title-label"
        title={
          <CapRow type="flex">
            <CapHeading type="h4">
              {formatMessage(messages.templateTitleLabel)}
            </CapHeading>
          </CapRow>
        }
        suffix={
          <>
            {(isEditFlow || !isFullMode) ? (
              <TagList
                label={formatMessage(globalMessages.addLabels)}
                onTagSelect={onTitleTagSelect}
                location={location}
                tags={getRcsTags()}
                onContextChange={handleOnTagsContextChange}
                injectedTags={injectedTags || {}}
                selectedOfferDetails={selectedOfferDetails}
              />
            ) : (
              <CapButton
                data-testid="suffix-button"
                type="flat"
                isAddBtn
                onClick={onTitleAddVar}
                disabled={!!templateTitleError}
              >
                {formatMessage(messages.addVar)}
              </CapButton>
            )}
          </>
        }
      />
   <div className="rcs_text_area_wrapper">
  {(isEditFlow || !isFullMode) ? (
      renderedRCSEditMessage(splitTemplateVarString(templateTitle), TITLE_TEXT)
  ) : (
    <CapInput
      className={`rcs-template-title-input ${
        !isTemplateApproved ? "rcs-edit-disabled" : ""
      }`}
      onChange={onTemplateTitleChange}
      placeholder={formatMessage(messages.templateTitlePlaceholder)}
      value={templateTitle || ""}
      size="default"
      data-testid="template_title"
      errorMessage={templateTitleError}
      disabled={isEditFlow || !isFullMode}
    />
  )}
</div>
{(isEditFlow || !isFullMode) && templateTitleError && (
  <CapError className="rcs-template-title-error">
    {templateTitleError}
  </CapError>
)}
{!isEditFlow && isFullMode && renderTitleCharacterCount()}
    </>
  )}

{/* Template Message */}
       <CapRow id="rcs-template-message-label">
         <CapHeader
            title={(
              <CapRow type="flex">
                <CapHeading type="h4">
                  {formatMessage(messages.templateDescLabel)}
                </CapHeading>
              </CapRow>
            )}
            suffix={
              (isEditFlow || !isFullMode) ? (
                <TagList
                  label={formatMessage(globalMessages.addLabels)}
                  onTagSelect={onDescTagSelect}
                  location={location}
                  tags={getRcsTags()}
                  onContextChange={handleOnTagsContextChange}
                  injectedTags={injectedTags || {}}
                  selectedOfferDetails={selectedOfferDetails}
                />
              ) : (
                <CapButton
                  data-testid="suffix-button"
                  type="flat"
                  isAddBtn
                  onClick={onMessageAddVar}
                  disabled={templateDescError && templateDesc}
                >
                  {formatMessage(messages.addVar)}
                </CapButton>
              )
            }
          />
        </CapRow>
        <CapRow className="rcs-create-template-message-input">
          <div className="rcs_text_area_wrapper">
            {(isEditFlow || !isFullMode)
              ? renderedRCSEditMessage(splitTemplateVarString(templateDesc), MESSAGE_TEXT)
              : (
                <>
                  <TextArea
                    id="rcs_template_message_textarea"
                    autosize={{ minRows: 3, maxRows: 5 }}
                    placeholder={formatMessage(messages.templateDescPlaceholder)}
                    onChange={onTemplateDescChange}
                    errorMessage={
                      templateDescError && (
                        <CapError className="rcs-template-message-error">
                          {templateDescError}
                        </CapError>
                      )
                    }
                    value={templateDesc || ""}
                    // maxLength={templateType === contentType.text_message 
                    //   ? RCS_TEXT_MESSAGE_MAX_LENGTH 
                    //   : RCS_RICH_CARD_MAX_LENGTH}
                    data-testid="rcs_text_area"
                    disabled={(isEditFlow || !isFullMode)}
                  />
                  {!aiContentBotDisabled && !isEditFlow && (
                    <CapAskAira.ContentGenerationBot
                      text={templateDesc || ""}
                      setText={(text) => onTemplateDescChange({ target: { value: text } })}
                      iconPlacement="float-br"
                      iconSize="1.6rem"
                      rootStyle={{
                        bottom: "0.5rem",
                        right: "1.2rem",
                        left: "auto",
                      }}
                    />
                  )}
                </>
              )
            }
          </div>
          {(isEditFlow || !isFullMode) && templateDescError && (
            <CapError className="rcs-template-message-error">
              {templateDescError}
            </CapError>
          )}
          {!isEditFlow && isFullMode && renderDescriptionCharacterCount()}
          {!isFullMode && hasTag() && (
            <CapAlert
              message={
                <CapLabel type="label2">
                  <CapIcon type="warning" className="alert-icon-rcs" />
                  {formatMessage(messages.tagLengthWarning)}
                </CapLabel>
              }
              type="warning"
              className="rcs-warning-message"
            />
          )}
        </CapRow>
        {renderButtonComponent()}
      </>

    );
  };

 
  const fallbackSmsLength = () => (
    <CapLabel type="label1" className="fallback-sms-length">
      {formatMessage(messages.totalCharacters, {
        smsCount: Math.ceil(
          fallbackMessage?.length / FALLBACK_MESSAGE_MAX_LENGTH,
        ),
        number: fallbackMessage?.length,
      })}
    </CapLabel>
  );

  // Get character count for title (rich card only)
  const getTitleCharacterCount = () => {
    if (templateType === contentType.text_message) return 0;
    return templateTitle ? templateTitle.length : 0;
  };

  // Get character count for description/message
  const getDescriptionCharacterCount = () => {
    return templateDesc ? templateDesc.length : 0;
  };

  // Get max length for description based on template type
  const getDescriptionMaxLength = () => {
    return templateType === contentType.text_message 
      ? RCS_TEXT_MESSAGE_MAX_LENGTH  // 160 for text message
      : RCS_RICH_CARD_MAX_LENGTH;    // 2000 for rich card description
  };

  // Get max length for title (rich card only)
  const getTitleMaxLength = () => {
    return TEMPLATE_TITLE_MAX_LENGTH; // 200 for rich card title
  };

  // Render character count for title (rich card only)
  const renderTitleCharacterCount = (className = "rcs-character-count") => {
    if (templateType === contentType.text_message) return null;
    
    const currentLength = getTitleCharacterCount();
    const maxLength = getTitleMaxLength();
    
    return (
      <CapLabel type="label1" className={className}>
        {formatMessage(messages.templateMessageLength, {
          currentLength,
          maxLength,
        })}
      </CapLabel>
    );
  };

  // Render character count for description/message
  const renderDescriptionCharacterCount = (className = "rcs-character-count") => {
    const currentLength = getDescriptionCharacterCount();
    const maxLength = getDescriptionMaxLength();
    
    return (
      <CapLabel type="label1" className={className}>
        {formatMessage(messages.templateMessageLength, {
          currentLength,
          maxLength,
        })}
      </CapLabel>
    );
  };

  // Check if any RCS variables contain tags (similar to Zalo hasTag logic)
  const hasTag = () => {
    // Check cardVarMapped values for tags
    if (cardVarMapped && Object.keys(cardVarMapped).length > 0) {
      const hasTagInMapped = Object.values(cardVarMapped).some(value => 
        isTagIncluded(value)
      );
      if (hasTagInMapped) return true;
    }
    
    if (titleVarMappedData && Object.keys(titleVarMappedData).length > 0) {
      const hasTagInTitle = Object.values(titleVarMappedData).some((value) => isTagIncluded(value));
      if (hasTagInTitle) return true;
    }
    if (descVarMappedData && Object.keys(descVarMappedData).length > 0) {
      const hasTagInDesc = Object.values(descVarMappedData).some((value) => isTagIncluded(value));
      if (hasTagInDesc) return true;
    }
    
    return false;
  };

  //adding creative dlt fallback sms handlers
  const addDltMsgHandler = () => {
    setShowDltContainer(true);
    setDltMode(RCS_DLT_MODE.TEMPLATES);
    setDltEditData({});
    setFallbackMessage('');
  };

  const closeDltContainerHandler = () => {
    setShowDltContainer(false);
    setDltMode('');
    templatesActions.getAllTemplates('Rcs', { page: 1, perPage: 25 });
  };

  const rcsDltEditSelectHandler = (data) => {
    setShowDltContainer(true);
    setDltMode(RCS_DLT_MODE.EDIT);
    setDltEditData(data);
  };

  const rcsDltEditCompletionHandler = (data) => {
    const tempData = {
      versions: {
        // eslint-disable-next-line no-undef
        base: data?.value?.base || {},
      },
    };
    const fallMsg = get(tempData, `versions.base.updated-sms-editor`, []).join(
      '',
    );
    closeDltContainerHandler();
    setDltEditData(tempData);
    setFallbackMessage(fallMsg);
    setFallbackMessageError(fallMsg?.length > FALLBACK_MESSAGE_MAX_LENGTH);
    setShowDltCard(true);
  };

  const rcsDltCardDeleteHandler = () => {
    closeDltContainerHandler();
    setDltEditData({});
    setFallbackMessage('');
    setFallbackMessageError(false);
    setShowDltCard(false);
  };

  const dltFallbackListingPreviewhandler = (data) => {
    const {
      'updated-sms-editor': updatedSmsEditor = [],
      'sms-editor': smsEditor = '',
    } = data.versions.base || {};
    setFallbackPreviewmode(true);
    setDltPreviewData(
      updatedSmsEditor === '' ? smsEditor : updatedSmsEditor.join(''),
    );
  };

  const getDltContentCardList = (content, channel) => {
    const extra = [
      <CapIcon
        type="edit"
        style={{ marginRight: '8px' }}
        onClick={() => rcsDltEditSelectHandler(dltEditData)}
      />,
      <CapDropdown
        overlay={(
          <CapMenu>
            <>
              <CapMenu.Item
                className="ant-dropdown-menu-item"
                onClick={() => setFallbackPreviewmode(true)}
              >
                {formatMessage(globalMessages.preview)}
              </CapMenu.Item>
              <CapMenu.Item
                className="ant-dropdown-menu-item"
                onClick={rcsDltCardDeleteHandler}
              >
                {formatMessage(globalMessages.delete)}
              </CapMenu.Item>
            </>
          </CapMenu>
        )}
      >
        <CapIcon type="more" />
      </CapDropdown>,
    ];
    return {
      title: channel,
      content,
      cardType: channel,
      extra,
    };
  };

  const getDltSlideBoxContent = () => {
    const loc = {
      pathname: `/sms/edit`,
      query: { type: EMBEDDED, module: LIBRARY },
      search: '',
    };
    const route = { name: SMS.toLowerCase() };
    let dltHeader = '';
    let dltContent = '';
    if (dltMode === RCS_DLT_MODE.TEMPLATES) {
      dltHeader = (
        <CapHeader
          title={formatMessage(messages.rcsDltTitle)}
          description={formatMessage(messages.rcsDltDesc)}
        />
      );
      dltContent = (
        <Templates
          location={loc}
          route={route}
          smsRegister={smsRegister}
          isFullMode={isFullMode}
          isDltFromRcs
          onSelectTemplate={rcsDltEditSelectHandler}
          handlePeviewTemplate={dltFallbackListingPreviewhandler}
        />
      );
    } else if (dltMode === RCS_DLT_MODE.EDIT) {
      dltHeader = formatMessage(messages.dltEditHeader);
      dltContent = (
        <SmsTraiEdit
          location={loc}
          route={route}
          getDefaultTags="outbound"
          handleClose={closeDltContainerHandler}
          templateData={dltEditData}
          getFormSubscriptionData={rcsDltEditCompletionHandler}
          isFullMode={false}
          selectedOfferDetails={selectedOfferDetails}
        />
      );
    }
    return { dltHeader, dltContent };
  };

  const renderFallBackSmsComponent = () => {
    // Completely disable fallback functionality when DLT is disabled
   return null;
    
    // const contentArr = [];
    // const showAddCreativeBtnForDlt = isDltEnabled && !showDltCard;
    // const showCardForDlt = isDltEnabled && showDltCard;
    // const showNonDltFallbackComp = !showAddCreativeBtnForDlt && !showCardForDlt;
    // //pushing common fallback sms headings
    // contentArr.push(
    //   <CapRow
    //     style={{
    //       marginBottom: isDltEnabled ? '20px' : '10px',
    //     }}
    //   >
    //     <CapHeader
    //       title={(
    //         <CapRow type="flex">
    //           <CapHeading type="h4">
    //             {formatMessage(messages.fallbackLabel)}
    //           </CapHeading>
    //           <CapTooltipWithInfo
    //             placement="right"
    //             infoIconProps={{
    //               style: { marginLeft: '4px', marginTop: '3px' },
    //             }}
    //             title={formatMessage(messages.fallbackToolTip)}
    //           />
    //         </CapRow>
    //       )}
    //       description={formatMessage(messages.fallbackDesc)}
    //       suffix={
    //         isDltEnabled ? null : (
    //           <CapButton
    //             type="flat"
    //             className="fallback-preview-btn"
    //             prefix={<CapIcon type="eye" />}
    //             style={{ color: CAP_SECONDARY.base }}
    //             onClick={() => setFallbackPreviewmode(true)}
    //             disabled={fallbackMessage === '' || fallbackMessageError}
    //           >
    //             {formatMessage(globalMessages.preview)}
    //           </CapButton>
    //         )
    //       }
    //     />
    //   </CapRow>,
    // );

    //dlt is enabled, and dlt content is not yet added, show button to add dlt creative
    // showAddCreativeBtnForDlt
    //   && contentArr.push(
    //     <CapCard className="rcs-dlt-fallback-card">
    //       <CapRow type="flex" justify="center" align="middle">
    //         <CapColumn span={10}>
    //           <CapImage src={addCreativesIcon} />
    //         </CapColumn>
    //         <CapColumn span={14}>
    //           <CapButton
    //             className="add-dlt-btn"
    //             type="secondary"
    //             onClick={addDltMsgHandler}
    //           >
    //             {formatMessage(messages.addSmsCreative)}
    //           </CapButton>
    //         </CapColumn>
    //       </CapRow>
    //     </CapCard>,
    //   );

    // //dlt is enabled and dlt content is added, show it in a card
    // showCardForDlt
    //   && contentArr.push(
    //     <CapCustomCardList
    //       cardList={[getDltContentCardList(fallbackMessage, SMS)]}
    //       className="rcs-dlt-card"
    //     />,
    //     fallbackMessageError && (
    //       <CapError className="rcs-fallback-len-error">
    //         {formatMessage(messages.fallbackMsgLenError)}
    //       </CapError>
    //     ),
    //   );

    // //dlt is not enabled, show non dlt text area
    // showNonDltFallbackComp
    //   && contentArr.push(
    //     <>
    //       <CapRow>
    //         <CapHeader
    //           title={(
    //             <CapHeading type="h4">
    //               {formatMessage(messages.fallbackTextAreaLabel)}
    //             </CapHeading>
    //           )}
    //           suffix={(
    //             <TagList
    //               label={formatMessage(globalMessages.addLabels)}
    //               onTagSelect={onTagSelectFallback}
    //               location={location}
    //               tags={tags || []}
    //               onContextChange={handleOnTagsContextChange}
    //               injectedTags={injectedTags || {}}
    //               selectedOfferDetails={selectedOfferDetails}
    //             />
    //           )}
    //         />
    //       </CapRow>
    //       <div className="rcs_fallback_msg_textarea_wrapper">
    //         <TextArea
    //           id="rcs_fallback_message_textarea"
    //           autosize={{ minRows: 3, maxRows: 5 }}
    //           placeholder={formatMessage(messages.fallbackMsgPlaceholder)}
    //           onChange={onFallbackMessageChange}
    //           errorMessage={fallbackMessageError}
    //           value={fallbackMessage || ""}
    //         />
    //         {!aiContentBotDisabled && (
    //           <CapAskAira.ContentGenerationBot
    //             text={fallbackMessage || ""}
    //             setText={(text) => {
    //               onFallbackMessageChange({ target: { value: text } });
    //             }}
    //             iconPlacement="float-br"
    //             rootStyle={{
    //               bottom: "0.5rem",
    //               right: "0.5rem",
    //               position: "absolute",
    //             }}
    //           />
    //         )}
    //       </div>
    //       <CapRow>{fallbackSmsLength()}</CapRow>
    //     </>
    //   );

    // return <>{contentArr}</>;
  };

  const uploadRcsImage = useCallback((file, type, fileParams, index) => {
    setImageError(null);
    const isRcsThumbnail = index === 1;
    actions.uploadRcsAsset(file, type, {
      isRcsThumbnail,
      ...fileParams,
      dimensionType: selectedDimension,
      orientation: RCS_IMAGE_DIMENSIONS[selectedDimension].orientation,
    }, index); // Pass the index parameter
  }, [selectedDimension]);

  const setUpdateRcsImageSrc = useCallback(
    (val) => {
      setAssetListImage(val);
      updateRcsImageSrc(val);
      actions.clearRcsMediaAsset(0); 
    },
    [rcsImageSrc],
  );

    useEffect(() => {
    if (!isEditFlow && isFullMode) {
      setUpdateRcsImageSrc('');
      setRcsThumbnailSrc('');
    }
  }, [selectedDimension]);

  useEffect(() => {
    const thumbnailDataObj = rcsData[`uploadedAssetData1`];
    if (thumbnailDataObj && thumbnailDataObj.metaInfo) {
      const imageUrl = thumbnailDataObj.metaInfo.secure_file_path || thumbnailDataObj.metaInfo.public_url;
      if (imageUrl) {
        setRcsThumbnailSrc(imageUrl);
      }
    }
  }, [rcsData[`uploadedAssetData1`]]);

  const updateOnRcsImageReUpload = useCallback(() => {
    setUpdateRcsImageSrc('');
  }, []);


  const uploadRcsVideo = (file, type, fileParams) => { 
    setImageError(null);
    actions.uploadRcsAsset(file, type, {
      ...fileParams,
      type: 'video',
      channel: RCS,
      isGenerateVideoThumbnail: false,
    });  
  };

  const updateRcsVideoSrc = (val) => {
    setRcsVideoSrc(val);
  };
  const setUpdateRcsVideoSrc = useCallback((index, val) => {
    setRcsVideoSrc(val);
    setAssetList(val); 
    if (!val) {
      setRcsVideoSrc({}); 
      setAssetList({}); 
    }
    actions.clearRcsMediaAsset(0); 
  }, []);

  const updateRcsThumbnailSrc = useCallback(
    (val) => {
      setRcsThumbnailSrc(val);
      actions.clearRcsMediaAsset(1); 
    },
    [thumbnailData],
  );

  const updateOnRcsThumbnailReUpload=() => {
    updateRcsThumbnailSrc('');
  };

  const renderThumbnailComponent = () => {
    const currentDimension = selectedDimension || Object.keys(RCS_VIDEO_THUMBNAIL_DIMENSIONS)[0];
    return !isEditFlow && (
    <>
       <CapHeading type="h4" className="rcs-image-dimensions-label">Upload Thumbnail</CapHeading>
       <CapImageUpload
         style={{ paddingTop: '20px' }}
         allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX}
         imgWidth={RCS_VIDEO_THUMBNAIL_DIMENSIONS[currentDimension].width}
         imgHeight={RCS_VIDEO_THUMBNAIL_DIMENSIONS[currentDimension].height}
         imgSize={RCS_THUMBNAIL_MAX_SIZE}
         uploadAsset={uploadRcsImage}
         isFullMode={isFullMode}
         imageSrc={rcsThumbnailSrc}
         updateImageSrc={updateRcsThumbnailSrc}
         updateOnReUpload={updateOnRcsThumbnailReUpload}
         minImgSize={RCS_THUMBNAIL_MIN_SIZE}
         index={1}
         className="cap-custom-image-upload"
         key={`rcs-uploaded-image-${currentDimension}`}
         imageData={thumbnailData}
         channel={RCS}
         channelSpecificStyle={!isFullMode}
         skipDimensionValidation={true}
       />
    </>
    )
  }

  const renderImageComponent = () => {
          
          return (
            <>
              {!isEditFlow && (
                <>
                  <CapHeading type="h4" className="rcs-image-dimensions-label">Image and Card Orientation</CapHeading>
                  <CapSelect
                    id="rcs-dimension-select"
                        value={selectedDimension}
                    onChange={(value) => {
                      setSelectedDimension(value);
                      if (rcsImageSrc) {
                        updateRcsImageSrc('');
                      }
                    }}
                    options={Object.values(RCS_IMAGE_DIMENSIONS).map(dim => ({
                      value: dim.type,
                      label: `${dim.label}`
                    }))}
                    style={{ marginBottom: '20px' }}
                  />
                </>
              )}
                  {(isEditFlow || !isFullMode) ? (
                    <div className="rcs-image-preview">
                      <CapImage
                        src={rcsImageSrc}
                        alt="RCS Image"
                        className="rcs-preview-image"
                      />
                    </div>
                  ) : (
                <CapImageUpload
                  style={{ paddingTop: '20px' }}
                  allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX}
                  imgWidth={RCS_IMAGE_DIMENSIONS[selectedDimension].width}
                  imgHeight={RCS_IMAGE_DIMENSIONS[selectedDimension].height}
                  imgSize={RCS_IMG_SIZE}
                  uploadAsset={uploadRcsImage}
                  isFullMode={isFullMode}
                  imageSrc={rcsImageSrc}
                  updateImageSrc={setUpdateRcsImageSrc}
                  updateOnReUpload={updateOnRcsImageReUpload}
                  index={0}
                  className="cap-custom-image-upload"
                  key={`rcs-uploaded-image-${selectedDimension}`}
                  imageData={rcsData}
                  channel={RCS}
                  channelSpecificStyle={!isFullMode}
                  skipDimensionValidation={true}
                />
              )}
              
            </>
          );
        }
  
  const renderVideoComponent = () => {
    const currentDimension =selectedDimension || Object.keys(RCS_VIDEO_THUMBNAIL_DIMENSIONS)[0];
          return (
            <>
            {isFullMode && renderLabel('cardOrientationLabel')}
            {!isEditFlow && isFullMode && (
            <CapSelect
              id="rcs-dimension-select"
              value={currentDimension}
              onChange={(value) => {
                setSelectedDimension(value);
                updateRcsThumbnailSrc('');
              }}
              options={Object.values(RCS_VIDEO_THUMBNAIL_DIMENSIONS).map(dim => ({
                value: dim.type,
                label: `${dim.label}`
              }))}
              style={{ marginBottom: '20px' }}
            />
            )}
              {(isEditFlow || !isFullMode) ? (
                <div className="rcs-video-preview">
                  <CapImage
                    src={rcsVideoSrc.videoThumbnail || ''}
                    className="rcs-preview-video"
                  />
                </div>
              ) : (
                <>
                  <CapHeading type="h4" className="rcs-image-dimensions-label">Upload Video</CapHeading>
                  <CapVideoUpload
                    index={0}
                    allowedExtensionsRegex={ALLOWED_EXTENSIONS_VIDEO_REGEX}
                    videoSize={RCS_VIDEO_SIZE}
                    isFullMode={isFullMode}
                    uploadAsset={uploadRcsVideo}
                    uploadedAssetList={assetList}
                    onVideoUploadUpdateAssestList={setUpdateRcsVideoSrc}
                    videoData={rcsData}
                    className="cap-custom-video-upload"
                    formClassName={"rcs-video-upload"}
                    channel={RCS}
                    errorMessage={formatMessage(messages.videoErrorMessage)}
                    showVideoNameAndDuration={false}
                    channelSpecificStyle={!isFullMode}
                  />
                </>
              )}
            </>
          );   
  }

  const getMediaBasedComponent = () => {
    
    if (!templateType || !templateMediaType) {
      return null;
    }
  
    if (templateType === contentType.rich_card || templateType === contentType.carousel) {
      if (templateMediaType === RCS_MEDIA_TYPES.IMAGE) {
        return renderImageComponent();
      }
      if (templateMediaType === RCS_MEDIA_TYPES.VIDEO) {
        return (
          <>
            {renderVideoComponent()}
            {renderThumbnailComponent()}
          </>
        );
      }
    }
    return renderTextComponent();
  };

  const getRcsPreview = () => {
    
    const dimensionObj = RCS_IMAGE_DIMENSIONS[selectedDimension];
    const resolvedTitle = !isFullMode ? resolveTemplateWithMap(templateTitle) : templateTitle;
    const resolvedDesc = !isFullMode ? resolveTemplateWithMap(templateDesc) : templateDesc;
    return (
      <UnifiedPreview
        channel={RCS}
        content={{
          rcsTitle: resolvedTitle,
          rcsDesc: resolvedDesc,
          ...(!isMediaTypeText && {
            rcsImageSrc,
            rcsVideoSrc: rcsThumbnailSrc,
          }),
          suggestions,
          rcsType: dimensionObj?.type,
          rcsOrientation: dimensionObj?.orientation,
        }}
        device={ANDROID}
        showDeviceToggle={false}
        showHeader={false}
        formatMessage={formatMessage}
      />
    );
  };
  
  const getUnmappedDesc = (str, mapping) => {
    if (!str) return '';
    if (!mapping || Object.keys(mapping).length === 0) return str;
    let result = str;
    const replacements = [];
    Object.entries(mapping).forEach(([key, value]) => {
      const raw = (value ?? '').toString();
      if (!raw || raw?.trim?.() === '') return;
      const braced = /^\{\{[\s\S]*\}\}$/.test(raw) ? raw : `{{${raw}}}`;
      replacements.push({ key, needle: raw });
      if (braced !== raw) replacements.push({ key, needle: braced });
    });
    const seen = new Set();
    const uniq = replacements
      .filter(({ key, needle }) => {
        const id = `${key}::${needle}`;
        if (seen.has(id)) return false;
        seen.add(id);
        return true;
      })
      .sort((a, b) => (b.needle.length - a.needle.length));

    uniq.forEach(({ key, needle }) => {
      if (!needle) return;
      const escaped = needle.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      const regex = new RegExp(escaped, 'g');
      result = result.replace(regex, `{{${key}}}`);
    });
    return result;
  };

  const createPayload = () => {
    const base = get(dltEditData, `versions.base`, {});
    const {
      template_id: templateId = '',
      template_name = '',
      'sms-editor': template = '',
      header: registeredSenderIds = [],
    } = base;
    const resolvedTitle = !isFullMode ? resolveTemplateWithMap(templateTitle) : templateTitle;
    const resolvedDesc = !isFullMode ? resolveTemplateWithMap(templateDesc) : templateDesc;
    const alignment = isMediaTypeImage
      ? RCS_IMAGE_DIMENSIONS[selectedDimension]?.alignment
      : RCS_VIDEO_THUMBNAIL_DIMENSIONS[selectedDimension]?.alignment;

    const payload = {
      name: templateName,
      versions: {
        base: {
          content: {
            RCS: {
              rcsContent: {
                ...(rcsAccount && !isFullMode && { accountId: rcsAccount }),
                cardType: STANDALONE,
                cardSettings: {
                  cardOrientation: isMediaTypeImage ? RCS_IMAGE_DIMENSIONS[selectedDimension]?.orientation || VERTICAL : RCS_VIDEO_THUMBNAIL_DIMENSIONS[selectedDimension]?.orientation || VERTICAL,
                  ...(alignment && { mediaAlignment: alignment }),
                  cardWidth: SMALL,
                },
                cardContent: [
                  {
                    title: resolvedTitle,
                    description: resolvedDesc,
                    mediaType: templateMediaType,
                    ...(!isMediaTypeText && {media: {
                      mediaUrl: rcsImageSrc || rcsVideoSrc.videoSrc || '',
                      thumbnailUrl: rcsThumbnailSrc || '',
                      height: isMediaTypeImage
                        ? RCS_IMAGE_DIMENSIONS[selectedDimension]?.heightType || MEDIUM
                        : RCS_VIDEO_THUMBNAIL_DIMENSIONS[selectedDimension]?.heightType || MEDIUM,
                    }}),
                    ...(!isFullMode && (() => {
                      const tokens = [
                        ...(templateTitle ? (templateTitle.match(rcsVarRegex) || []) : []),
                        ...(templateDesc ? (templateDesc.match(rcsVarRegex) || []) : []),
                      ];
                      const allowedKeys = tokens
                        .map((t) => getVarNameFromToken(t))
                        .filter(Boolean);
                      const nextMap = {};
                      allowedKeys.forEach((k) => {
                        if (Object.prototype.hasOwnProperty.call(cardVarMapped || {}, k)) {
                          nextMap[k] = cardVarMapped[k];
                        } else {
                          nextMap[k] = '';
                        }
                      });
                      return { cardVarMapped: nextMap };
                    })()),
                    ...(suggestions.length > 0 && { suggestions }),
                  }
                ],
                contentType: isFullMode ? templateType : RICHCARD,
                ...(isFullMode && {accountId:accountId, accessToken: accessToken, accountName: accountName, hostName: hostName}),
              },
              smsFallBackContent: {
                message: fallbackMessage,
                ...(isDltEnabled && {
                  templateConfigs: {
                    templateId,
                    templateName: template_name,
                    template,
                    registeredSenderIds,
                  },
                }),
              },
            },
          },
        },
      },
      type: RCS,
    };
    return payload;
  };

  const actionCallback = ({ errorMessage, resp }, isEdit) => {
    // eslint-disable-next-line no-undef
    const error = errorMessage?.message || errorMessage;
    if (!error) {
      CapNotification.success({
        message: isEdit
          ? formatMessage(messages.rcsEditNotification)
          : formatMessage(messages.rcsCreateNotification),
      });
      if (isEdit) {
        actions.clearEditResponse();
      } else {
        actions.clearCreateResponse();
      }
    } else {
      CapNotification.error({
        message: error,
      });
    }
  };

 
  const onEditRcs = () => {
    const payload = createPayload();
    const formDataParams = {
      value: payload,
      _id: params?.id,
      validity: true,
      type: RCS,
    };
    getFormData(formDataParams);
  };

  const createApprovalHandler = () => {
    setSpin(true);
    const payload = createPayload();
    actions.createRcsTemplate(payload, (resp, errorMessage) => {
      if (!resp && !errorMessage) {
      }
      actionCallback({ resp, errorMessage });
      setSpin(false); // Always turn off spinner
      if (!errorMessage) {
        onCreateComplete();
      }
    });
  };

  const onDoneCallback = () => {
    if (isFullMode) {
      return createApprovalHandler;
    }
  };

  const isDisableDone = () => {
    if(isEditFlow){
      return false;
    }
    if (isFullMode) {
      if (templateName.trim() === '' || templateNameError) {
        return true;
      }
    }

    if(!isFullMode){
      const titleVars = splitTemplateVarString(templateTitle).filter(elem => rcsVarTestRegex.test(elem)).map(v => v.replace(/^\{\{|\}\}$/g, ''));
      const descVars = splitTemplateVarString(templateDesc).filter(elem => rcsVarTestRegex.test(elem)).map(v => v.replace(/^\{\{|\}\}$/g, ''));
      const allVars = Array.from(new Set([ ...titleVars, ...descVars ]));

      if (allVars.length > 0 && isEmpty(cardVarMapped)) {
        return true;
      }

      const hasEmptyMapping =
        cardVarMapped &&
        Object.keys(cardVarMapped).length > 0 &&
        Object.entries(cardVarMapped).some(([_, v]) => {
          if (typeof v !== 'string') return !v; // null/undefined
          return v.trim() === ''; // empty string
        });

      if (hasEmptyMapping) {
        return true;
      }

      const anyMissing = allVars.some(name => {
        const v = cardVarMapped?.[name];
        if (typeof v !== 'string') return !v;
        return v.trim() === '';
      });
      if (anyMissing) {
        return true;
      }
    }

      if (isMediaTypeText && templateDesc.trim() === '') {
      return true;

    }
    if (isMediaTypeImage && (rcsImageSrc === '' || templateTitle === '' || templateDesc === '' )) {
      return true;
    }

    if (isMediaTypeVideo && (rcsVideoSrc.videoSrc === '' || rcsThumbnailSrc === '' || templateTitle === '' || templateDesc === '' )) {
     return true;
    }
    if (buttonType.includes(CTA)) {

      const hasValidButtons = suggestions.every(suggestion => 
        suggestion.text && suggestion.url && !suggestionError && !forbiddenCharactersValidation(suggestion.text)
      );
      if (!hasValidButtons) {
        return true;
      }
    }
    if (templateDescError || templateTitleError || fallbackMessageError) {
      return true;
    }
    return false;
  };

  const isEditDisableDone = () => {
    
    if (templateStatus !== RCS_STATUSES.approved) {
      return true;
    }

    if (!isFullMode) {
      if (templateName.trim() === '' || templateNameError) {
        return true;
      }
    }
    if(!isFullMode){
      const titleVars = splitTemplateVarString(templateTitle).filter(elem => rcsVarTestRegex.test(elem)).map(v => v.replace(/^\{\{|\}\}$/g, ''));
      const descVars = splitTemplateVarString(templateDesc).filter(elem => rcsVarTestRegex.test(elem)).map(v => v.replace(/^\{\{|\}\}$/g, ''));
      const allVars = Array.from(new Set([ ...titleVars, ...descVars ]));

      if (allVars.length > 0 && isEmpty(cardVarMapped)) {
        return true;
      }

      const hasEmptyMapping =
        cardVarMapped &&
        Object.keys(cardVarMapped).length > 0 &&
        Object.entries(cardVarMapped).some(([_, v]) => {
          if (typeof v !== 'string') return !v; // null/undefined
          return v.trim() === ''; // empty string
        });

      if (hasEmptyMapping) {
        return true;
      }

      const anyMissing = allVars.some(name => {
        const v = cardVarMapped?.[name];
        if (typeof v !== 'string') return !v;
        return v.trim() === '';
      });
      if (anyMissing) {
        return true;
      }
    }
    if (isMediaTypeText && templateDesc.trim() === '') {
      return true;
    }
    if (isMediaTypeImage && rcsImageSrc === '') {
      return true;
    }
    if(isMediaTypeVideo && (rcsThumbnailSrc === '' || rcsVideoSrc.videoSrc === '')) {
      return true;
    }

    if (buttonType.includes(CTA)) {
      const hasValidButtons = suggestions.every(suggestion => 
        suggestion.text && suggestion.url && !suggestionError && !forbiddenCharactersValidation(suggestion.text)
      );
      if (!hasValidButtons) {
        return true;
      }
    }
    if (templateTitleError || templateDescError || fallbackMessageError) {
      return true;
    }
    return false;
  };

  const getTemplateStatusMessage = () => {
    switch (templateStatus) {
      case RCS_STATUSES.approved:
        return (
          <CapLabel type="label2">
            {formatMessage(messages.approvedStatusMsg)}
          </CapLabel>
        );
      case RCS_STATUSES.rejected:
        return (
          <>
            <CapLabel type="label2" className="rcs-status-label">
              {formatMessage(messages.rejectedStatusMsg)}
            </CapLabel>
          </>
        );
      case RCS_STATUSES.unavailable:
        return (
          <>
            <CapLabel type="label2" className="rcs-status-label">
              {formatMessage(messages.unavailableStatusMsg)}
            </CapLabel>
          </>
        );
      case RCS_STATUSES.pending:
        return (
          <>
            <CapLabel type="label2" className="rcs-status-label">
              {formatMessage(messages.awaitingStatusMsg)}
            </CapLabel>
          </>
        );
      default:
        return (
          <>
            <CapLabel type="label2" className="rcs-status-label">
              {formatMessage(messages.templateStatusGeneric, { templateStatus })}
            </CapLabel>
          </>
        );
    }
  };

  const getMainContent = () => {
    if (showDltContainer && !fallbackPreviewmode) {
      const dltSlideBoxContent = showDltContainer && getDltSlideBoxContent();
      const { dltHeader = '', dltContent = '' } = dltSlideBoxContent;
      return (
        <CapSlideBox
          show={showDltContainer}
          header={dltHeader}
          content={dltContent}
          handleClose={closeDltContainerHandler}
          size="size-xl"
        />
      );
    }

    return (
      <>
        {templateStatus !== '' && (<CapRow className="template-status-container">
          <CapLabel type="label2">
            {formatMessage(messages.templateStatusLabel)}
          </CapLabel>

          {templateStatus && (
            <CapAlert
              message={getTemplateStatusMessage()}
              type={getTemplateStatusType(templateStatus)}
            />
          )}
        </CapRow>
        )}
        <CapRow className="cap-rcs-creatives">
          <CapColumn span={14}>
            {/* template name */}
            {isFullMode && (
              <CapInput
                id="rcs_template_name_input"
                data-testid="template_name"
                onChange={onTemplateNameChange}
                errorMessage={templateNameError}
                placeholder={formatMessage(
                  globalMessages.templateNamePlaceholder,
                )}
                value={templateName || ''}
                size="default"
                label={formatMessage(globalMessages.creativeNameLabel)}
                disabled={(isEditFlow || !isFullMode)}
              />
            )}
            {renderLabel('templateTypeLabel')}
            <CapRadioGroup
              id="select-rcs-template-type"
              options={TEMPLATE_TYPE_OPTIONS}
              onChange={onTemplateTypeChange}
              value={templateType}
              disabled={(isEditFlow || !isFullMode)}
            />

            {/* Show media only for rich_card or carousel */}
            {(templateType === contentType.rich_card || templateType === contentType.carousel) && (
              <>
                {renderLabel('mediaLabel')}
                  <CapRadioGroup
                    options={mediaRadioOptions || []}
                    value={templateMediaType}
                    onChange={onTemplateMediaTypeChange}
                    disabled={(isEditFlow || !isFullMode)}
                    className="rcs-radio"
                  />
                <div className="rcs-container-image">
                  {getMediaBasedComponent()}
                </div>
              </>
            )}
            {renderTextComponent()}
            <CapDivider style={{ margin: `${CAP_SPACE_28} 0` }} />
            {renderFallBackSmsComponent()}
            <div className="rcs-scroll-div" />
          </CapColumn>
          <CapColumn span={8} offset={2}>
            {getRcsPreview()}
          </CapColumn>
        </CapRow>


       
        <div className="rcs-footer">
          {!isEditFlow && (
          <>
              <div className="button-disabled-tooltip-wrapper">
                <CapButton
                  onClick={onDoneCallback()}
                  disabled={isDisableDone()}
                  className="rcs-done-btn"
                >
                  <FormattedMessage {...messages.sendForApprovalButtonLabel} />
                </CapButton>
              </div>
              <CapTooltip
                title={formatMessage(messages.rcsTestPreviewDisabledTooltip)}
                placement={"top"}
              >
                <div className="button-disabled-tooltip-wrapper">
                  <CapButton
                    onClick={handleTestAndPreview}
                    className="rcs-test-preview-btn"
                    type="secondary"
                    disabled={true}
                    style={{ marginLeft: "8px" }}
                  >
                    <FormattedMessage {...creativesMessages.testAndPreview} />
                  </CapButton>
                </div>
              </CapTooltip>
          </>
          )}
          {(!isFullMode || isEditFlow) &&  (
          <>
               <div className="button-disabled-tooltip-wrapper">
                <CapButton
                  onClick={onEditRcs}
                  disabled={isEditDisableDone()}
                  className="rcs-done-btn"
                >
                  <FormattedMessage {...messages.doneButtonLabel} />
                </CapButton>
              </div>
          </>
          )}
          {isEditFlow && templateStatus === RCS_STATUSES.approved && (
            <>
              <CapButton
                onClick={handleTestAndPreview}
                className="rcs-test-preview-btn"
                type="secondary"
              >
                <FormattedMessage {...creativesMessages.testAndPreview} />
              </CapButton>
            </>
          )}
        </div>


        {fallbackPreviewmode && (
          <CapSlideBox
            className="rcs-fallback-preview"
            show={fallbackPreviewmode}
            header={(
              <CapHeading type="h7" style={{ color: CAP_G01 }}>
                {formatMessage(messages.fallbackPreviewtitle)}
              </CapHeading>
            )}
            content={(
              <>
                <UnifiedPreview
                  channel={RCS}
                  content={{
                    rcsPreviewContent: {
                      rcsDesc: tempMsg,
                    },
                  }}
                  device={ANDROID}
                  showDeviceToggle={false}
                  showHeader={false}
                  formatMessage={formatMessage}
                />
                <CapHeading
                  type="h3"
                  style={{ textAlign: 'center' }}
                  className="margin-t-16"
                >
                  {formatMessage(messages.totalCharacters, {
                    smsCount: Math.ceil(
                      tempMsg?.length / FALLBACK_MESSAGE_MAX_LENGTH,
                    ),
                    number: tempMsg.length,
                  })}
                </CapHeading>
              </>
            )}
            handleClose={() => {
              setFallbackPreviewmode(false);
              setDltPreviewData('');
            }}
          />
        )}
      </>
    );
  };
  return (
    <>
      <CapSpin spinning={loadingTags || spin}>
        {getMainContent()}
      </CapSpin>
      <TestAndPreviewSlidebox
        show={propsShowTestAndPreviewSlidebox || showTestAndPreviewSlidebox}
        onClose={handleCloseTestAndPreview}
        formData={null} // RCS doesn't use formData structure like SMS
        content={getTemplateContent()}
        currentChannel={RCS}
      />
    </>
  );
};

const mapStateToProps = createStructuredSelector({
  rcsData: makeSelectRcs(),
  accountData: makeSelectAccount(),
  metaEntities: makeSelectMetaEntities(),
  loadingTags: isLoadingMetaEntities(),
  injectedTags: setInjectedTags(),
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(RcsActions, dispatch),
  globalActions: bindActionCreators(globalActions, dispatch),
  templatesActions: bindActionCreators(TemplatesActions, dispatch),
});

const withReducer = injectReducer({ key: 'rcs', reducer: v2RcsReducer });

export default withCreatives({
  WrappedComponent: Rcs,
  mapStateToProps,
  mapDispatchToProps,
  userAuth: true,
  reducers: [withReducer],
});
