//import renderHTML from "react-render-html";
import { RawHTML } from '@wordpress/element';

import allowedBlocks from "../common/component/compatibility/allowedBlocks";

import _merge from "lodash.merge";
import Board from "../comment/board";
import { createRoot } from 'react-dom/client';
import { showNotice } from '../common/utils';

const { __ } = wp.i18n;
const { Fragment, useEffect } = wp.element;
const { registerPlugin } = wp.plugins;
if (cfIsVersionCheck(multicollab_wp_version.wp_version, "6.6", "lt")) {
    var { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost;  // For versions less than 6.6
} else {
    var { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editor;  // For versions 6.6 and above, use wp.editor
}
const { PanelBody, TabPanel, ToggleControl } =
	wp.components;

import icons from "../common/component/icons";
import ActivitySummary from "./component/activitySummary";
import MarkedResolved from "./component/markedResolved";
import AssignedTo from "./component/assignedTo";
import UserDataHeader from "./component/userDataHeader"; 
import tabs from "./component/tabs.json";
import SidebarSettings from "./component/sidebarSettings";

const $ = jQuery; // eslint-disable-line
let suggestionBoardToggle;
let commentBoardToggle;
let realTimeMode;
let isCommentor = false; // To check is user commentor @author - Mayank / since 3.6
const { sprintf } = wp.i18n;
const { displayShortcut, isKeyboardEvent } = wp.keycodes;
const { addFilter, removeFilter } = wp.hooks;

class Comments extends React.Component {
	constructor(props) {
		super(props);
		
		const { select } = wp.data;
		const showActivities = select("mdstore").getShowActivities();
		const showComments = select("mdstore").getShowComments();
		const suggestionBoardsEnable = select("core/editor").getEditedPostAttribute("meta")?._sb_show_suggestion_boards;
		const enableCoEditing = select("core/editor").getEditedPostAttribute("meta")?._is_real_time_mode;
		let suggestionEnable = select('mdstore').getSuggestionMode();

		this.state = {
			threads: [],
			isLoading: false,
			showActivities,
			showComments,
			collapseLimit: 50,
			hasAccordian: false,
			hasAccordianSuggestions: false,
			hasAccordionReviewSugesstions: false,
			suggestionEnable,
			suggestionBoardsEnable,
			enableCoEditing,
			usersWithAccess: [],
		};


		// Get the Page ID.
		this.postID = wp.data.select("core/editor").getCurrentPostId(); // eslint-disable-line

		// Binding Methods.
		this.edit = this.edit.bind(this);
		this.reply = this.reply.bind(this);
		this.delete = this.delete.bind(this);
		this.toggleCollapseLink = this.toggleCollapseLink.bind(this);
		this.resolveThread = this.resolveThread.bind(this);
		this.handleShowComments = this.handleShowComments.bind(this);
		this.getComments = this.getComments.bind(this);

		// Grab the current user id.
		this.currentUserID = multicollabActivityL10n.currentUserID;
		this.setUserFlag;
		this.enableshowActivitiesToggleUpdate = this.enableshowActivitiesToggleUpdate.bind(this);
	}
	/**
	 * Collapse Comment Board in mobile on load.
	 */
	collapseBoardOnMobile() {
		const iframe = cfGetIframe();
      	const iframeDocument = iframe ? iframe.contentWindow.document : null;
		const checkWidth = window.innerWidth;
		if (checkWidth <= 768) {
			this.setState({
				showComments: wp.data.dispatch("mdstore").setShowComments(false),
			});
			
			// Use classList for adding/removing classes
			const body = document.body;
			body.classList.add('hide-comments');
			body.classList.remove('commentOn');
			if(iframe){
			  	iframe.contentDocument?.body.classList.add('hide-comments');
			  	iframe.contentDocument?.body.classList.remove('commentOn');
			}
			
			// Trigger a custom event
			const event = new CustomEvent('editorLayoutUpdate');
			document.dispatchEvent(event);
		}
	}
	

	/**
	 * Collapse Selected Text.
	 */
	collapseText(str) {
		let text = str;
	
		const collapseLimit = this.state.collapseLimit;
	
		if (collapseLimit !== null && text && collapseLimit <= text.replace(/<\/?[^>]+(>|$)/g, "").length) {
			text = text.slice(0, collapseLimit) + (text.length > collapseLimit ? "..." : "");
		}
	
		return __(text, "commenting-feature");
	}

	selectedTextStripLength(selectedText) {
		if (null == selectedText || selectedText === "") {
			return 0;
		}
		return String(selectedText).replace(/<\/?[^>]+(>|$)/g, "").length;
	}

	shouldCollapseCommentedOn(selectedText) {
		return this.state.collapseLimit <= this.selectedTextStripLength(selectedText);
	}

	/**
	 * Changing collapse link text.
	 */
	toggleCollapseLink(e) {
		const targetID = e.target.dataset.id;
		const linkElement = e.target;
		const showAllEl = document.getElementById(`show-all-${targetID}`);
		const showLessEl = document.getElementById(`show-less-${targetID}`);
		if (!showAllEl || !showLessEl) {
			return;
		}

		const showMoreText = __("Show more", "commenting-feature");
		const showLessText = __("Show less", "commenting-feature");

		if (linkElement.innerHTML === showMoreText) {
			linkElement.innerHTML = showLessText;
			showAllEl.classList.remove("js-hide");
			showLessEl.classList.add("js-hide");
		} else {
			linkElement.innerHTML = showMoreText;
			showAllEl.classList.add("js-hide");
			showLessEl.classList.remove("js-hide");
		}
	}
	/**
	 * Get All Comments Related to this Post.
	 */
	getComments() {
		// Set loading to true (assuming this is done somewhere before this method)	
		if (wp.data.select("mdstore").getShowActivities()) {
			const isFallback = multicollabActivityL10n.apiUrl.includes('rest_route=');
			const baseUrl = multicollabActivityL10n.apiUrl.replace(/\/+$/, ''); // remove trailing slash
			const route = '/multicollab/v2/activities'; // always has leading slash

			const url = isFallback
			  ? `${baseUrl}${route}&postID=${this.postID}` // NO slash between baseUrl and route
			  : `${baseUrl}${route}?postID=${this.postID}`; // regular format
			
			fetch(url, {
				method: 'GET',
				headers: {
					"X-WP-Nonce": multicollabActivityL10n.nonce,
				},
			})
			.then(response => {
				if (!response.ok) {
					throw new Error('Network response was not ok');
				}
				return response.json();
			})
			.then(res => {
				const threads = res.threads.length > 0 ? res.threads : null;
				wp.data.dispatch("mdstore").setAllCommentCount(res.threads);
				this.setState({
					threads,
					isLoading: false,
				});
			})
			.catch(error => {
				console.error(error);
				this.setState({ isLoading: false }); // Handle loading state in case of error
			});
		} else {
			this.setState({ isLoading: false }); // Ensure loading state is set if activities are not shown
		}		
	}
	

	/**
	 * Get all comments boards related to this Post.
	 * @author: Nirav Soni @since-4.0
	 */
	getCommentsBoard() {
		var referenceNode = document.getElementById("cf-comment-board-wrapper");
		var selectedTexts = [];

		// get editor datatext value
		const elementsByDatatext = document.querySelectorAll('[datatext]');
		const elementsByDatatextArr = Array.prototype.map.call(elementsByDatatext, el => el.getAttribute("datatext"));
		const uniqueDatatextArr = elementsByDatatextArr.filter((element, index) => {
			return elementsByDatatextArr.indexOf(element) === index;
		});


		const {
			threads
		} = this.state;

		if (threads !== null && threads !== undefined) {
			threads.forEach((th) => {
				if (th.resolved === "true") {
					var resolvedId = document.getElementById(th.elID);
					if (resolvedId) {
						resolvedId.remove();
					}
					if (uniqueDatatextArr.includes(th.elID)) {
						const blockType = document.querySelector(`[datatext="${th.elID}"]`)?.getAttribute('data-type');
						const dataBlocks = Array.from(document.querySelectorAll(`[datatext="${th.elID}"]`)).map(function (el) {
							return el.getAttribute('data-block');
						});
					
						if (blockType !== undefined && dataBlocks.length > 0) {
							dataBlocks.forEach(function (clientId) {
								wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, { datatext: '' });
							});
						} else {
							// Remove Tag.
							document.querySelectorAll(`[datatext="${th.elID}"]`).forEach(function (element) {
								removeTag(th.elID); // Call the removeTag function
								const elementById = document.getElementById(th.elID);
								if (elementById) {
									elementById.remove(); // Remove the element by ID
								}
							});
						}
					}					
				}
			});
		}
		
		const selectedNontextblock = wp.data.select('mdstore').getBoardIds();
		selectedTexts = selectedNontextblock.filter(Boolean);

		if (selectedTexts.length === 0) {
			const commentBoardWrapper = document.getElementById('cf-comment-board-wrapper');
			if (commentBoardWrapper) {
				commentBoardWrapper.innerHTML = ''; // Clear all child elements
			}
		}

		selectedTexts.forEach((selectedText) => {
			if (typeof selectedText !== "undefined" && selectedText.match(/^el/m) !== null) {
				let getSelectedText = document.getElementById(selectedText);

				if (getSelectedText) {
					let hasClassList = getSelectedText.classList;
					if (hasClassList.contains('is-open') && hasClassList.contains('focus')) {
						return;
					}
					getSelectedText.remove();
				}

				let newNode = document.createElement("div");
				newNode.setAttribute("id", selectedText);
				newNode.setAttribute("class", "cls-board-outer cm-board");
				referenceNode.appendChild(newNode);

				const container = document.getElementById(selectedText);
				const root = createRoot(container);
				root.render(
					<Board datatext={selectedText} onLoadFetch={1} />
				);
			}
		});
	}

	/**
	 * Setup active activity board.
	 */
	setActiveBoard(elID) {

		var findMdSpan = document.querySelectorAll('.mdspan-comment');
	
		findMdSpan?.forEach(function (mdSpan) {
			var datatext = mdSpan.getAttribute('datatext');
			if (elID === datatext) {
				var userDataRows = document.querySelectorAll('.js-activity-centre .user-data-row');
				userDataRows.forEach(function (row) {
					row.classList.remove('is-active');
				});
				document.getElementById('cf-' + elID)?.classList.add('is-active');
				var selectedElement = document.querySelector('[datatext="' + elID + '"]');
				if (selectedElement) {
					selectedElement.classList.remove('is-selected');
				}
			}
		});
	
		var commentIconElement = document.querySelector('[datatext="' + elID + '"]');
		if (commentIconElement && commentIconElement.classList.contains('commentIcon')) {
			commentIconElement.classList.add('is-selected');
		}
	}
	
	/**
	 * Highlight Selected Text From Editor.
	 */
	highlightSelectedText(elID) {
		var findMdSpan = document.querySelectorAll('.mdspan-comment');
	
		findMdSpan?.forEach(function (mdSpan) {
			mdSpan.setAttribute('data-rich-text-format-boundary', 'false');
		});
	
		findMdSpan.forEach(function (mdSpan) {
			var datatext = mdSpan.getAttribute('datatext');
			if (elID === datatext) {
				mdSpan.setAttribute('data-rich-text-format-boundary', 'true');
			}
		});
	
		var selectedElement = document.getElementById(elID);
		if (selectedElement && selectedElement.classList.contains('sg-board')) {
			var sid = selectedElement.getAttribute('data-sid');
			var sidElement = document.getElementById(sid);
			if (sidElement) {
				sidElement.setAttribute('data-rich-text-format-boundary', 'true');
			}
		}
	}

	/**
	 * CLosing Sidebar On Mobile.
	 */
	closingSidebarOnMobile() {
		var checkWidth = window.innerWidth;
		if (768 >= checkWidth) {
			wp.data.dispatch("core/edit-post").closeGeneralSidebar();
		}
	}

	/**
	 * Add active class on activity center thread on post status change.
	 */
	addActiveClassOnPostStatusChange() {
		const addActiveClass = setInterval(() => {
			var activeBoard = document.querySelector('.cls-board-outer.focus')?.id;
	
			if (activeBoard !== undefined) {
				var activeElement = document.getElementById('cf-' + activeBoard);
				if (activeElement && activeElement.classList.contains('is-active')) {
					clearInterval(addActiveClass);
				}
	
				var userDataRows = document.querySelectorAll('.cf-activity-centre .user-data-row');
				userDataRows.forEach(function (row) {
					row.classList.remove('is-active');
				});
	
				if (activeElement) {
					activeElement.classList.add('is-active');
				}
			} else {
				clearInterval(addActiveClass);
			}
		}, 1000);
	}	

	/**
	 * Resolving Thread.
	 */
	async resolveThread(e) {
		// Open comment if not opened.
		if (!wp.data.select("mdstore").getShowComments()) {
			this.handleShowComments();
		}
		var elID = e.target.dataset.elid;
		elID = elID.replace("cf-", "");

		if( elID.includes('el') ) {
			await new Promise((resolve) => {
				wp.data.dispatch("core/edit-post").openGeneralSidebar("edit-post/cf-collab-sidebar");
				resolve();
			});
		}
		
		// Closing Sidebar On Mobile.
		this.closingSidebarOnMobile();
	}

	/**
	 * Reply on a thread.
	 */
	async reply(e) {
		// Reset all reply comment textareas.
		const cancelComments = document.querySelectorAll(".js-cancel-comment");
		cancelComments.forEach(comment => comment.click());
	
		// Open comments if not already opened.
		if (!wp.data.select("mdstore").getShowComments()) {
			this.handleShowComments();
		}
		let elID = '';
		if( undefined === e.target.dataset.elid ) {
			elID = e.target.parentElement.dataset.elid.replace("cf-", "");
		} else {
			elID = e.target.dataset.elid.replace("cf-", "");
		}

		let selectedElement;
		await new Promise((resolve) => {
			wp.data.dispatch("core/edit-post").openGeneralSidebar("edit-post/cf-collab-sidebar");
			resolve();
		});
		if( elID.includes('sg') ) {
			var elIDwithSg = elID;
			elID = elID.replace('sg', '');
			selectedElement = document.getElementById(elIDwithSg);
		} else {
			selectedElement = returnCommntTextElement( elID );
		}

		if (selectedElement) {
			selectedElement.click();
		}
	
		// Highlight the selected text in the editor.
		this.highlightSelectedText(elID);
	
		// Set the active class in the activity center.
		this.setActiveBoard(elID);
	
		// Close sidebar on mobile.
		this.closingSidebarOnMobile();
	}

	/**
	 * Edit a message.
	 */
	async edit(e) {
		e.preventDefault();
	
		// Open comments if not already opened.
		if (!wp.data.select("mdstore").getShowComments()) {
			this.handleShowComments();
		}
	
		let elID = e.target.dataset.elid.replace("cf-", "");
		let editID = e.target.dataset.editid.replace("cf-", "");
		let elIDSelector = '';
		let selectedElement;
		// Reset all reply comment textareas.
		jQuery(".js-cancel-comment").trigger("click");
		// Resetting before triggering.
		jQuery(".cls-board-outer").removeClass("focus").css({ opacity: 0.2, top: 0 }); // Resetting before trigger.
		
		await new Promise((resolve) => {
			wp.data.dispatch("core/edit-post").openGeneralSidebar("edit-post/cf-collab-sidebar");
			resolve();
		});

		if( elID.includes('sg') ) {
			let elIDSg = elID;
			elID   = elID.replace('sg', '');
			selectedElement = document.getElementById(elID);
			elIDSelector = elIDSg;
		} else {
			selectedElement = returnCommntTextElement( elID );
			editID = editID.replace('sg', '');
			elIDSelector = elID;
		}

		if (selectedElement) {
			selectedElement.click();
		}
	
		// Highlight the selected text in the editor.
		this.highlightSelectedText(elID);
	
		// Set the active class.
		this.setActiveBoard(elID);
	
		// Close sidebar on mobile.
		this.closingSidebarOnMobile();
	}

	/**
	 * Delete a message.
	 */
	async delete(e) {
		e.preventDefault();
	
		// Open comments if not already opened.
		if (!wp.data.select("mdstore").getShowComments()) {
			this.handleShowComments();
		}
	
		let elID = e.target.dataset.elid.replace("cf-", "");
		let deleteID = e.target.dataset.deleteid.replace("cf-", "");
		let selectedElement;
		await new Promise((resolve) => {
			wp.data.dispatch("core/edit-post").openGeneralSidebar("edit-post/cf-collab-sidebar");
			resolve();
		});

		if( elID.includes('sg') ) {
			let elIDSg = elID;
			elIDSg   = elIDSg.replace('sg', '');
			selectedElement = document.getElementById(elIDSg);
		} else {
			selectedElement = returnCommntTextElement( elID );
		}

		if (selectedElement) {
			selectedElement.click();
		}
		// Highlight the selected text in the editor.
		this.highlightSelectedText(elID);
	
		// Set the active class.
		this.setActiveBoard(elID);
	
		// Close sidebar on mobile.
		this.closingSidebarOnMobile();
	}

	/**
	 * Track if post updated or published.
	 */
	isPostUpdated() {
		const _this = this;
		//set flag to restrict multiple call
		var checked = true;


		wp.data.subscribe(function () {

			let select = wp.data.select("core/editor");
			var isSavingPost = select.isSavingPost();
			var isAutosavingPost = select.isAutosavingPost();
			var didPostSaveRequestSucceed = select.didPostSaveRequestSucceed();
			var status = wp.data
				.select("core/editor")
				.getEditedPostAttribute("status");

			if (isSavingPost) {
				checked = false;
			} else {
				if (!checked && !isAutosavingPost) {
					if (didPostSaveRequestSucceed) {
						_this.addActiveClassOnPostStatusChange();
					}
					checked = true;
				}
			}
		});
	}

	/**
	 * Comment toggle for whole block
	 */
	hideBlockLevelComment(isHideComment) {
		// Resolved hide comment issue for whole block #584 @author - Mayank / since 3.6
		if (isHideComment) {
			const cfIcons = document.querySelectorAll(".cf-icon-wholeblock__comment[data-suggestion_id]");
			cfIcons.forEach(cfIcon => {
				const suggestionId = cfIcon.dataset.suggestion_id;
				const matchedElements = document.querySelectorAll(`[suggestion_id="${suggestionId}"]`);
	
				// Add classes based on the presence of specific classes on the matched elements
				matchedElements.forEach(matchedElement => {
					if (matchedElement.classList.contains("blockAdded")) {
						cfIcon.classList.add("cf-icon__addBlocks");
					} else if (matchedElement.classList.contains("blockremove")) {
						cfIcon.classList.add("cf-icon__removeBlocks");
					}
					cfIcon.classList.remove("cf-icon-wholeblock__comment");
				});
			});
		} else {
			const cfIcons = document.querySelectorAll(".cf-icon__addBlocks[datatext], .cf-icon__removeBlocks[datatext]");
			cfIcons.forEach(cfIcon => {
				const datatextId = cfIcon.getAttribute("datatext");
				const matchedElements = document.querySelectorAll(`[datatext="${datatextId}"]`);
	
				matchedElements.forEach(() => {
					cfIcon.classList.add("cf-icon-wholeblock__comment");
				});
				cfIcon.classList.remove("cf-icon__addBlocks", "cf-icon__removeBlocks");
			});
		}
	}	

	/**
	 * Handle Show Comments
	 */
	handleShowComments(value) {

		const iframe = cfGetIframe();
      	const iframeDocument = iframe ? iframe.contentWindow.document : null;

		const openBoards = document.querySelectorAll(".cls-board-outer").length;
	
		wp.data.dispatch("mdstore").setAllCommentCount(0);
	
		// Set the value in the store to hide/show comment option.
		wp.data.dispatch("core/editor").editPost({
			meta: { _sb_show_comment_boards: value },
		});
	
		this.setState({
			showComments: wp.data.dispatch("mdstore").setShowComments(value),
		});
	
		if (
			true === wp.data.select("mdstore").getShowComments() ||
			"1" === multicollabRolePermissions.hide_comment
		) {
			document.body.classList.add("hide-comments");
			document.body.classList.remove('commentOn');
			if(iframe){
			  	iframe.contentDocument?.body.classList.add('hide-comments');
			  	iframe.contentDocument?.body.classList.remove('commentOn');
			}
			//jQuery.event.trigger({ type: "editorLayoutUpdate" });
			const eventEditorLayoutUpdate = new CustomEvent("editorLayoutUpdate");
			document.dispatchEvent(eventEditorLayoutUpdate);
	
			if (document.querySelectorAll(".cls-board-outer.cm-board.focus").length > 0) {
				wp.data.dispatch("mdstore").setDataText("");
			}
	
			const boards = document.querySelectorAll("#cf-comment-board-wrapper .cls-board-outer.cm-board");
			boards.forEach(board => {
				board.classList.remove("focus");
				board.classList.remove("is-open");
				board.removeAttribute("style");
			});
			document.querySelectorAll("mdspan").forEach(el => el.removeAttribute("data-rich-text-format-boundary"));
	
			multicollab_removeAllNotices();
			if ("1" !== multicollabRolePermissions.hide_comment) {
				wp.data.dispatch("core/notices").createNotice(
					"success",
					__("Comments are Hidden", "commenting-feature"),
					{
						id: "hideComments",
						type: "snackbar",
						isDismissible: true,
					}
				);
			}
			this.hideBlockLevelComment(true); 
		} else {
			document.body.classList.remove("hide-comments");
			if(iframe){
			  	iframe.contentDocument?.body.classList.remove('hide-comments');
			}
			if (openBoards === 0) {
				document.body.classList.remove('commentOn');
				if(iframe){
				  	iframe.contentDocument?.body.classList.remove('commentOn');
				}
			} else {
				document.body.classList.add('commentOn');
				
				if(iframe){
				  	iframe.contentDocument?.body.classList.add('commentOn');
				}
				document.querySelector(".comment-toggle .components-form-toggle")?.classList.remove("is-checked");
			}
			const eventEditorLayoutUpdate = new CustomEvent("editorLayoutUpdate");
			document.dispatchEvent(eventEditorLayoutUpdate);

			multicollab_removeAllNotices();
			wp.data.dispatch("core/notices").createNotice(
				"success",
				__("Comments are Visible", "commenting-feature"),
				{
					id: "showComments",
					type: "snackbar",
					isDismissible: true,
				}
			);
			this.hideBlockLevelComment(false);
		}

		const nonFocusBoards = document.querySelectorAll("#cf-comment-board-wrapper .cls-board-outer:not(.focus)");

		if (document.querySelectorAll(".cls-board-outer.focus").length === 0) {
		  nonFocusBoards.forEach(board => board.style.top = "auto");
		}
	}	

	/**
	 * Appned Counter on Activity Center.
	 */

	appendCounter() {
		this.appendCounterFunction(); // Call once initially
	
		wp.data.subscribe(function () {
			this.appendCounterFunction();  // This will now work because of binding
		}.bind(this));  // Explicitly bind `this` to the correct context
	}

	appendCounterFunction() {
		const isPluginSidebarOpen = wp.data
			.select("core/edit-post")
			.isPluginSidebarOpened();
		const isEditorSidebarOpen = wp.data
			.select("core/edit-post")
			.isEditorSidebarOpened();

		if (isPluginSidebarOpen && !isEditorSidebarOpen) {
			let openBoards = wp.data.select('mdstore').getBoardIds().length;

			setTimeout(function () {
				if (document.getElementById("history-toggle") === null) {

					const notificationCounter = document.createElement("span");
					notificationCounter.id = "history-toggle";
					notificationCounter.setAttribute("data-count", openBoards);
					//notificationCounter.setAttribute("data-test", "testing");
					const activitiesTab = document.querySelector(".cf-multicollab-sidebar__activities-tab");
					activitiesTab?.appendChild(notificationCounter);
				}
			}, 300);

			if (document.getElementById("history-toggle") !== null) {
				document.getElementById("history-toggle").setAttribute("data-count", openBoards);
			}
		}
	}

	/**
	 * Add active class in activities thread on selected text click.
	 */
	activeBoardOnSelectedText() {
		document.body.addEventListener("click", function (event) {
			if (event.target.classList.contains("mdspan-comment")) {
				const queryString = window.location.search;
				const urlParams = new URLSearchParams(queryString);
				const currentUrl = urlParams.get("current_url");
				if (currentUrl) {
					urlParams.delete("current_url");
					window.history.replaceState(
						{},
						"",
						`${location.pathname}?${urlParams}`
					);
				}
	
				const datatext = event.target.getAttribute("datatext");
				const userDataRows = document.querySelectorAll(".cf-activity-centre .user-data-row");
				userDataRows.forEach(row => row.classList.remove("is-active"));
				const selectedRow = document.getElementById(`cf-${datatext}`);
				if (selectedRow) {
					selectedRow.classList.add("is-active");
				}
				wp.data.dispatch("mdstore").setDataText(datatext);
			}
		});
	}	

	componentDidMount() {
		this.collapseBoardOnMobile();
		this.getComments(); // Calling getComments() to get the comments related to this post.
		this.isPostUpdated(); // Calling isPostUpdated() when the post saving status chagned.
		this.appendCounter(); // Appending counter.
		this.activeBoardOnSelectedText(); // Add active class in activities thread on selected text click.
	
		// set state for hidecomments
		if ("1" === multicollabRolePermissions.hide_comment) {
			this.handleShowComments();
		}
	
	}

	componentDidUpdate() {

		// keyboard shortcut for hide/show comments toggle.
		const thisFunctions = this;
		$(document).on("click keydown", ".is-selected", function (e) {
			if (isKeyboardEvent.shiftAlt(e, "j")) {
			  e.stopImmediatePropagation();
	  
			  $(".comment-toggle").trigger("click");
	  
			  var commentBoardToggle = wp.data
				.select("core/editor")
				.getEditedPostAttribute("meta")?._sb_show_comment_boards;
	  
			  var updateValue = false;
	  
			  if (commentBoardToggle === true) {
				updateValue = false;
			  } else {
				updateValue = true;
			  }
	  
			  thisFunctions.handleShowComments(updateValue);
	  
			}
		  });
	  
	}



	enableshowActivitiesToggleUpdate = ( value ) => {
		wp.data.dispatch("mdstore").setShowActivities( value );
		this.setState({ showActivities: value });
		this.setState({ isLoading: value });
		this.getComments();
	}


	render() {
		const iframe = cfGetIframe();
      	const iframeDocument = iframe ? iframe.contentWindow.document : null;
		const isTemplate = wp.data.select('core/editor').getCurrentPostType();
        const isEditingTemplate = isTemplate === 'wp_template';
		const seenIds = new Set();  // Define seenIds set	
		const allCommentBoards = wp.data.select('mdstore').getAllCommentCount();
		//check Editingtemplate mode
		if (isEditingTemplate) {
			return null;
		} else {
			const {
				threads,
				isLoading,
				collapseLimit,
				hasAccordian,
				showActivities,
			} = this.state;
			
			this.postStatus = wp.data.select("core/editor").getCurrentPost().status;
			//check thread id is available in editor?
			let newThreads = [];
			function sgIdsBlockLevelSuggestions(selectedText) {
				if (selectedText) {
					let obj = { elID: ["sg", selectedText].join("") };
					newThreads.push(obj);
				}
			}
			const iframe = cfGetIframe();
			if (isEditingTemplate || (iframe && iframe.contentDocument)) {
				const contents = iframe.contentDocument;

				// First block of elements
				const elements = contents.querySelectorAll(
					".wp-block mdspan, .commentIcon, .cf-onwhole-block__comment"
				);

				elements.forEach(function (element) {
					const selectedText = element.getAttribute("datatext");
					if (selectedText) {
						newThreads.push({ elID: selectedText });
					}
				});

				const additionalElements = contents.querySelectorAll(
					".commentIcon, .cf-onwhole-block__comment"
				);

				additionalElements.forEach(function (element) {
					let selectedText = element.getAttribute("id");
					if (selectedText) {
						newThreads.push({ elID: `sg${selectedText}` });
					}
				});

			} else {
				
				const commentElements = document.querySelectorAll(".commentIcon, .cf-onwhole-block__comment, .wp-block mdspan");

				commentElements.forEach(function (element) {
					const selectedText = element.getAttribute("datatext");
					if (selectedText) {
						newThreads.push({ elID: selectedText });
					}
				});
			}
			let threadsId = [],
				newThreadsId = [],
				commentAutoDrafts = 0;

			if (newThreads !== null && threads !== null && threads !== undefined) {
				threads.forEach((th) => {
					if (th.resolved === "false") {
						threadsId.push(th.elID);
					}
				});

				newThreads.forEach((newTh) => {
					newThreadsId.push(newTh.elID);
				});

				const newThreadsIdSet = new Set(newThreadsId);
				var setDifference = threadsId.filter((x) => !newThreadsIdSet.has(x));
				
				setDifference.forEach((setDiff) => {
					if (setDiff.match(/el/g)) {
						commentAutoDrafts++;
					}
				});
			}
			// Add toggle functionality to show/hide comment board on page load.
			commentBoardToggle = wp.data
				.select("core/editor")
				.getEditedPostAttribute("meta")?._sb_show_comment_boards;

				if ("1" !== multicollabRolePermissions.hide_comment) {
					const body = document.body;
				
					if (!commentBoardToggle && body.classList.contains("hide-comments")) {
						body.classList.remove("hide-comments");
						if(iframe){
						  	iframe.contentDocument?.body.classList.remove('hide-comments');
						}
					} else if (commentBoardToggle && !body.classList.contains("hide-comments") && "1" !== multicollabRolePermissions.hide_comment) {
						body.classList.add("hide-comments");
						if(iframe){
						  	iframe.contentDocument?.body.classList.add('hide-comments');
						}
				
						const boards = document.querySelectorAll("#cf-comment-board-wrapper .cls-board-outer.cm-board");
						boards.forEach(board => {
							board.classList.remove("focus");
							board.classList.remove("is-open");
							board.removeAttribute("style");
						});
				
						const mdspanElements = document.querySelectorAll("mdspan");
						mdspanElements.forEach(mdspan => {
							mdspan.removeAttribute("data-rich-text-format-boundary");
						});
					}
				}				

			
			//Remove active class from activity center when board is not on focus @Minal Diwan version -4.5
			const sidebarName = wp.data.select("core/edit-post").getActiveGeneralSidebarName();
			if (sidebarName === "cf-activity-center/cf-activity-center") {
				let boardOuterElements = 'cf-comment-board-wrapper';
				
				setTimeout(function () {
					if( iframeDocument ) {
						var SuggestionActive = iframeDocument.querySelector('[data-rich-text-format-boundary="true"]');
					} else {
						var SuggestionActive = document.querySelector('[data-rich-text-format-boundary="true"]');
					}
					if (!SuggestionActive) {
						document.querySelectorAll('.js-activity-centre .user-data-row').forEach(function (element) {
							element.classList.remove('is-active');
						});
					}
				}, 200);
			}

			if ( document.body.classList.contains("hide-sg")) {
				document.body.classList.remove("hide-sg");
				if(iframe){
				  	iframe.contentDocument?.body.classList.remove('hide-sg');
				}
			} else if ( !document.body.classList.contains("hide-sg")) {
				const focusedBoard = document.querySelector(".cls-board-outer.sg-board.focus");
				
				if (focusedBoard) {
					const id = focusedBoard.getAttribute("data-sid");
					const targetElement = document.getElementById(id);
					
					if (targetElement) {
						targetElement.removeAttribute("data-rich-text-format-boundary");
					}
					
					wp.data.dispatch("mdstore").setDataText("");
				}
			
				document.body.classList.add("hide-sg");
				if(iframe){
				  	iframe.contentDocument?.body.classList.add('hide-sg');
				}
				
				const boards = document.querySelectorAll("#cf-comment-board-wrapper .cls-board-outer.sg-board");
				boards.forEach(board => {
					board.classList.remove("focus");
					board.classList.remove("is-open");
				});
			}			
					

			if (multicollab_fs.is_plan_free) {
				document.body.classList.remove("hide-sg");
				if(iframe){
			  		iframe.contentDocument?.body.classList.remove('hide-sg');
			  	}
			}			
			const nonFocusBoards = document.querySelectorAll("#cf-comment-board-wrapper .cls-board-outer:not(.focus)");
			if (document.querySelectorAll(".cls-board-outer.focus").length === 0) {
			  nonFocusBoards.forEach(board => board.style.top = "auto");
			}
			
			// Triggering the custom event
			const event = new Event("editorLayoutUpdate");
			document.dispatchEvent(event);			
		// Fix github issue: 889.
				setTimeout(() => {
					var emptyActivityThreads = false;
					if (null === allCommentBoards || 0 === allCommentBoards?.length) {
						emptyActivityThreads = true;
					}
					var emptyActivityThreadsMsg = document.querySelector('.cf_no_activity_found');
					if (true === emptyActivityThreads && emptyActivityThreadsMsg && true === showActivities) {
						emptyActivityThreadsMsg.innerHTML = '<strong>No recent activities found!</strong>';
					}

				}, 200);

				/* edited the new tab for summary. */
				return (
					<PanelBody
						className="cf-multicollab-sidebar-panel"
					>
							
						<TabPanel
							className="cf-multicollab-sidebar__tab-panel"
							tabs={tabs.map(tab => ({
								name: tab.name,
								title: (
									<span className={`${tab.className}-title`}>
										{__(tab.title, "commenting-feature")}
									</span>
								),
								className: tab.className,
							}))}
						>
							{(tab) => {
								if (
									"cf-activity-centre" === tab.name &&
									$(".cf-activity-center__tab-title").css(
										"display",
										"block"
									)
								) {
									return (
										<div className="cf-activity-centre js-activity-centre">
											<PanelBody>
												<ToggleControl
													label={__(
														"Show Activities",
														"commenting-feature"
													)}
													className="comment-toggle"
													help={__(
														"Toggle recent activities",
														"commenting-feature"
													)}
													checked={wp.data
														.select("mdstore")
														.getShowActivities()}
													
													onChange={(value) => {
														this.enableshowActivitiesToggleUpdate( value );
													}}
												/>
											</PanelBody>

											{true === isLoading && true === showActivities && (
												<div className="user-data-row">
													<strong>
													{__(
														"Loading...",
														"commenting-feature"
													)}
													</strong>
												</div>
											)}

											{(null === allCommentBoards || allCommentBoards?.length === 0) && true !== isLoading && true === showActivities && (
											<div className="user-data-row cf_no_activity_found">
												<strong>
												{__(
													"No recent activities found!",
													"commenting-feature"
												)}
												</strong>
											</div>
											)}

											{undefined !== threads &&
											null !== threads &&
											true === showActivities &&
											threads.map((th) => {
												// Check if id already exists in the set (for uniqueness)
												if (seenIds.has(th.elID)) {
													return;  // Return duplicate id or handle it accordingly
												} else {
													seenIds.add(th.elID);  // Add id to set if it's unique
												}
												//check thread id is available in editor?
												var removedItem =
												newThreads.filter((x) => x.elID === th.elID)
													.length > 0
													? false
													: true;
												if (th.resolved === "true") {
												removedItem = false;
												}
					
												if (removedItem) {
												return;
												}
												var boardId = wp.data
												.select("mdstore")
												.getDataText();
												
												var SuggestionActiveID = "";      											
												if( iframeDocument ) {
													var SuggestionActive = iframeDocument.querySelector('[data-rich-text-format-boundary="true"]');
												} else {
													var SuggestionActive = document.querySelector('[data-rich-text-format-boundary="true"]');
												}

												if ( SuggestionActive && SuggestionActive?.className !== 'mdspan-comment' ) {
													SuggestionActiveID = SuggestionActive.id;
												} else if( SuggestionActive && SuggestionActive?.className === 'mdspan-comment' ) {
													SuggestionActiveID = SuggestionActive.getAttribute('datatext');
												}
												if (th.resolved === "true") {
													return (
													<div
														className={
														("true" === th.resolved
															? "user-data-row cf-thread-resolved"
															: "user-data-row") +
														((th.elID === boardId ||
															th.elID === SuggestionActiveID) &&
															"true" !== th.resolved
															? " active"
															: "") +
														(removedItem ? " unknownThread" : "") +
														(th.type === "sg" ? " sglog" : th.type === "el" ? " cmlog" : " cblog")
														}
														id={`cf-${`${th.elID}`}`}
														key={`cf-${`${th.elID}`}`}
													>
														{th.activities?.map((c, index) => {
														return (
															<div
															className={
																0 < index
																? "user-data-box user-reply"
																: "user-data-box"
															}
															key={index}
															style={{
																display:
																index >= getCommentsLimit()
																	? "none"
																	: "",
															}}
															>
															<div className="user-data">
																<UserDataHeader
																	c={c}
																	th={th}
																/>
																<div className="user-data-wrapper">
																<div className="user-commented-on">
																	{0 >= index && (
																	<Fragment>
																		<blockquote
																		className={
																			"user-commented-icon" +
																			(th.blockType
																			? "-" + th.blockType
																			: "") +
																			(th.action &&
																			th.action.toLowerCase() ===
																			"delete"
																			? " delete"
																			: " add")
																		}
																		>
																		{"deleted" === c.status ||
																			"true" === th.resolved ? (
																			<Fragment>
																			{th.type === "sg" ? (
																				this.shouldCollapseCommentedOn(th.selectedText) ? (
																				<Fragment>
																				<span
																					id={`show-all-${c.id}`}
																					class="user-commented-on show-all js-hide "
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																						{sprintf(
																							"<strong>%s</strong> : %s",
																							__(
																							th.action,
																							"commenting-feature"
																							),
																							__(
																							translateStringFormat(
																								th.selectedText
																							),
																							"commenting-feature"
																							)
																						)}
																					</RawHTML>
																				</span>
																				<span
																					id={`show-less-${c.id}`}
																					class="user-commented-on show-less"
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																					{this.collapseText(
																						sprintf(
																						"<strong>%s</strong> : %s",
																						__(
																							th.action,
																							"commenting-feature"
																						),
																						__(
																							translateStringFormat(
																							th.selectedText
																							),
																							"commenting-feature"
																						)
																						)
																					)}
																					</RawHTML>
																				</span>
																				</Fragment>
																				) : (
																				<span
																					className="user-commented-on"
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																						{sprintf(
																							"<strong>%s</strong> : %s",
																							__(
																								th.action,
																								"commenting-feature"
																							),
																							__(
																								translateStringFormat(
																									th.selectedText
																								),
																								"commenting-feature"
																							)
																						)}
																					</RawHTML>
																				</span>
																				)
																			) : (
																				this.shouldCollapseCommentedOn(th.selectedText) ? (
																				<Fragment>
																				<span
																					id={`show-all-${c.id}`}
																					class="user-commented-on show-all js-hide "
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																					{translateStringFormat(
																						th.selectedText
																					)}
																					</RawHTML>
																				</span>
																				<span
																					id={`show-less-${c.id}`}
																					class="user-commented-on show-less"
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																					{this.collapseText(
																						translateStringFormat(
																						th.selectedText
																						)
																					)}
																					</RawHTML>
																				</span>
																				</Fragment>
																				) : (
																				<span
																					className="user-commented-on"
																					data-id={`cf-${th.elID}`}
																				>
																					<RawHTML>
																						{translateStringFormat(
																							th.selectedText
																						)}
																					</RawHTML>
																				</span>
																				)
																			)}
						
																			{null !==
																				th.selectedText &&
																				this.shouldCollapseCommentedOn(th.selectedText) && (
																				<a
																					href="javascript:void(0)"
																					className="cf-show-more"
																					data-id={c.id}
																					onClick={this.toggleCollapseLink.bind(
																					this
																					)}
																				>
																					{__(
																					"Show more",
																					"commenting-feature"
																					)}
																				</a>
																				)}
																			</Fragment>
																		) : (
																			<Fragment>
																			{th.type === "sg" ? (
																				this.shouldCollapseCommentedOn(th.selectedText) ? (
																				<Fragment>
																				<a
																					id={`show-all-${c.id}`}
																					class="user-commented-on show-all js-hide "
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																					this
																					)}
																				>
																					<RawHTML>
																					{sprintf(
																						"<strong>%s</strong> : %s",
																						__(
																						th.action,
																						"commenting-feature"
																						),
																						__(
																						translateStringFormat(
																							th.selectedText
																						),
																						"commenting-feature"
																						)
																					)}
																					</RawHTML>
																				</a>
																				<a
																					id={`show-less-${c.id}`}
																					class="user-commented-on show-less"
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																					this
																					)}
																				>
																					<RawHTML>
																					{this.collapseText(
																						sprintf(
																						"<strong>%s</strong> : %s",
																						__(
																							th.action,
																							"commenting-feature"
																						),
																						__(
																							translateStringFormat(
																							th.selectedText
																							),
																							"commenting-feature"
																						)
																						)
																					)}
																					</RawHTML>
																				</a>
																				</Fragment>
																				) : (
																				<a
																					className="user-commented-on"
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																						this
																					)}
																				>
																					<RawHTML>
																						{sprintf(
																							"<strong>%s</strong> : %s",
																							__(
																								th.action,
																								"commenting-feature"
																							),
																							__(
																								translateStringFormat(
																									th.selectedText
																								),
																								"commenting-feature"
																							)
																						)}
																					</RawHTML>
																				</a>
																				)
																			) : (
																				this.shouldCollapseCommentedOn(th.selectedText) ? (
																				<Fragment>
																				<a
																					id={`show-all-${c.id}`}
																					class="user-commented-on show-all js-hide "
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																					this
																					)}
																				>
																					<RawHTML>
																					{translateStringFormat(
																						th.selectedText
																					)}
																					</RawHTML>
																				</a>
																				<a
																					id={`show-less-${c.id}`}
																					class="user-commented-on show-less"
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																					this
																					)}
																				>
																					<RawHTML>
																					{this.collapseText(
																						translateStringFormat(
																						th.selectedText
																						)
																					)}
																					</RawHTML>
																				</a>
																				</Fragment>
																				) : (
																				<a
																					className="user-commented-on"
																					data-elid={`cf-${th.elID}`}
																					href="javascript:void(0)"
																					onClick={this.reply.bind(
																						this
																					)}
																				>
																					<RawHTML>
																						{translateStringFormat(
																							th.selectedText
																						)}
																					</RawHTML>
																				</a>
																				)
																			)}
						
																			{null !==
																				th.selectedText &&
																				this.shouldCollapseCommentedOn(th.selectedText) && (
																				<a
																					href="javascript:void(0)"
																					className="cf-show-more"
																					data-id={c.id}
																					onClick={this.toggleCollapseLink.bind(
																					this
																					)}
																				>
																					{__(
																					"Show more",
																					"commenting-feature"
																					)}
																				</a>
																				)}
																			</Fragment>
																		)}
																		</blockquote>
																	</Fragment>
																	)}
																</div>
																<div class="user-comment">
																	{0 < index &&
																	"deleted" === c.status ? (
																	<del><RawHTML>{c.thread}</RawHTML></del> // phpcs:ignore
																	) : (
																	<span>
																		<RawHTML>
																			{c.thread}
																		</RawHTML>
																	</span> // phpcs:ignore
																	)}
																</div>
						
																{c.editedTime &&
																	c.editedTime.length > 0 &&
																	"deleted" !== c.status &&
																	th.type === "el" && (
																	<time class="user-commented-date user-inner-box-time">
																		{" "}
																		{sprintf(
																		__(
																			"edited %s",
																			"commenting-feature"
																		),
																		timeAgo(c.editedTimestamp)
																		)}{" "}
																		<span className="tooltip">
																		{convertedDatetime(
																			c.editedTimestamp.toString()
																		)}
																		</span>
																	</time>
																	)}
																{0 >= index &&
																	th.assignedTo &&
																	th.assignedTo.username && (
																	<AssignedTo
																		th={th}	
																	/>
																	)}
															{"true" !== th.resolved && "deleted" !== c.status && ( // Add deleted status condition to resolve Github issue: 755
											<div className="user-action">
											{0 >= index && (
												<Fragment>
												<a
													href="javascript:void(0)"
													className="user-cmnt-reply last-cmt-text"
													data-elid={`cf-${th.elID}`}
													onClick={this.reply.bind(
													this
													)}
												>
													{__(
													"Reply",
													"commenting-feature"
													)}
													<span className="tooltip">
													{__(
														"Reply to this comment",
														"commenting-feature"
													)}
													</span>
												</a>
												{th.type !== "sg" &&
													(
													<a
														href="javascript:void(0)"
														className="user-thread-resolve js-resolve-comment last-cmt-text"
														onClick={this.resolveThread.bind(
														this
														)}
														data-elid={`cf-${th.elID}`}
													>
														{__(
														"Resolve",
														"commenting-feature"
														)}
														<span className="tooltip">
														{" "}
														{__(
															"Mark as Resolved",
															"commenting-feature"
														)}
														</span>
													</a>
													)}
												</Fragment>
											)}
											{0 < index &&
												parseInt(
												this.currentUserID,
												10
												) === c.userData.id && (
												<Fragment>
													<a
													href="javascript:void(0)"
													className="user-cmnt-reply"
													data-elid={`cf-${th.elID}`}
													data-editid={c.id}
													onClick={this.edit.bind(
														this
													)}
													
													>
													{__(
														"Edit",
														"commenting-feature"
													)}
													<span className="tooltip">
														{__(
														"Edit",
														"commenting-feature"
														)}
													</span>
													</a>

													<a
													href="javascript:void(0)"
													className="user-cmnt-delete"
													data-elid={`cf-${th.elID}`}
													data-deleteid={c.id}
													onClick={this.delete.bind(
														this
													)}
													
													>
													{__(
														"Delete",
														"commenting-feature"
													)}
													<span className="tooltip">
														{__(
														"Delete",
														"commenting-feature"
														)}
													</span>
													</a>
												</Fragment>
												)}{" "}
											</div>
										)}
																</div>
															</div>
															</div>
														);
														})}
														{th.activities.length > getCommentsLimit() && (
														<div className="show-all-comments">
															{" "}
															{sprintf(
															__("Show all %d replies"),
															th.activities.length - 1
															)}{" "}
														</div>
														)}
														{"true" === th.resolved &&
														undefined !== th.resolvedBy && (
															<MarkedResolved
																th={th}
															/>
														)}
													</div>
													);
												} else {
													const boardId = th.elID;

													if (boardId && boardId.startsWith("el")) {
														return (
															<div id={boardId} className="user-data-row cls-board-outer cm-board">
																{th.activities?.map((c, index) => {
																	return(
																		<div className="user-commented-on">
																					{0 >= index && (
																					<Fragment>
																						<blockquote
																						className={
																							"user-commented-icon" +
																							(th.blockType
																							? "-" + th.blockType
																							: "") +
																							(th.action &&
																							th.action.toLowerCase() ===
																							"delete"
																							? " delete"
																							: " add")
																						}
																						>
																						{"deleted" === c.status ||
																							"true" === th.resolved ? (
																							<Fragment>
																							{th.type === "sg" ? (
																								this.shouldCollapseCommentedOn(th.selectedText) ? (
																								<Fragment>
																								<span
																									id={`show-all-${c.id}`}
																									class="user-commented-on show-all js-hide "
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																										{sprintf(
																											"<strong>%s</strong> : %s",
																											__(
																											th.action,
																											"commenting-feature"
																											),
																											__(
																											translateStringFormat(
																												th.selectedText
																											),
																											"commenting-feature"
																											)
																										)}
																									</RawHTML>
																								</span>
																								<span
																									id={`show-less-${c.id}`}
																									class="user-commented-on show-less"
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																									{this.collapseText(
																										sprintf(
																										"<strong>%s</strong> : %s",
																										__(
																											th.action,
																											"commenting-feature"
																										),
																										__(
																											translateStringFormat(
																											th.selectedText
																											),
																											"commenting-feature"
																										)
																										)
																									)}
																									</RawHTML>
																								</span>
																								</Fragment>
																								) : (
																								<span
																									className="user-commented-on"
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																										{sprintf(
																											"<strong>%s</strong> : %s",
																											__(
																												th.action,
																												"commenting-feature"
																											),
																											__(
																												translateStringFormat(
																													th.selectedText
																												),
																												"commenting-feature"
																											)
																										)}
																									</RawHTML>
																								</span>
																								)
																							) : (
																								this.shouldCollapseCommentedOn(th.selectedText) ? (
																								<Fragment>
																								<span
																									id={`show-all-${c.id}`}
																									class="user-commented-on show-all js-hide "
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																									{translateStringFormat(
																										th.selectedText
																									)}
																									</RawHTML>
																								</span>
																								<span
																									id={`show-less-${c.id}`}
																									class="user-commented-on show-less"
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																									{this.collapseText(
																										translateStringFormat(
																										th.selectedText
																										)
																									)}
																									</RawHTML>
																								</span>
																								</Fragment>
																								) : (
																								<span
																									className="user-commented-on"
																									data-id={`cf-${th.elID}`}
																								>
																									<RawHTML>
																										{translateStringFormat(
																											th.selectedText
																										)}
																									</RawHTML>
																								</span>
																								)
																							)}
										
																							{null !==
																								th.selectedText &&
																								this.shouldCollapseCommentedOn(th.selectedText) && (
																								<a
																									href="javascript:void(0)"
																									className="cf-show-more"
																									data-id={c.id}
																									onClick={this.toggleCollapseLink.bind(
																									this
																									)}
																								>
																									{__(
																									"Show more",
																									"commenting-feature"
																									)}
																								</a>
																								)}
																							</Fragment>
																						) : (
																							<Fragment>
																							{th.type === "sg" ? (
																								this.shouldCollapseCommentedOn(th.selectedText) ? (
																								<Fragment>
																								<a
																									id={`show-all-${c.id}`}
																									class="user-commented-on show-all js-hide "
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																									{sprintf(
																										"<strong>%s</strong> : %s",
																										__(
																										th.action,
																										"commenting-feature"
																										),
																										__(
																										translateStringFormat(
																											th.selectedText
																										),
																										"commenting-feature"
																										)
																									)}
																									</RawHTML>
																								</a>
																								<a
																									id={`show-less-${c.id}`}
																									class="user-commented-on show-less"
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																									{this.collapseText(
																										sprintf(
																										"<strong>%s</strong> : %s",
																										__(
																											th.action,
																											"commenting-feature"
																										),
																										__(
																											translateStringFormat(
																											th.selectedText
																											),
																											"commenting-feature"
																										)
																										)
																									)}
																									</RawHTML>
																								</a>
																								</Fragment>
																								) : (
																								<a
																									className="user-commented-on"
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																										{sprintf(
																											"<strong>%s</strong> : %s",
																											__(
																												th.action,
																												"commenting-feature"
																											),
																											__(
																												translateStringFormat(
																													th.selectedText
																												),
																												"commenting-feature"
																											)
																										)}
																									</RawHTML>
																								</a>
																								)
																							) : (
																								this.shouldCollapseCommentedOn(th.selectedText) ? (
																								<Fragment>
																								<a
																									id={`show-all-${c.id}`}
																									class="user-commented-on show-all js-hide "
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																									{translateStringFormat(
																										th.selectedText
																									)}
																									</RawHTML>
																								</a>
																								<a
																									id={`show-less-${c.id}`}
																									class="user-commented-on show-less"
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																									{this.collapseText(
																										translateStringFormat(
																										th.selectedText
																										)
																									)}
																									</RawHTML>
																								</a>
																								</Fragment>
																								) : (
																								<a
																									className="user-commented-on"
																									data-elid={`cf-${th.elID}`}
																									href="#"
																								>
																									<RawHTML>
																										{translateStringFormat(
																											th.selectedText
																										)}
																									</RawHTML>
																								</a>
																								)
																							)}
										
																							{null !==
																								th.selectedText &&
																								this.shouldCollapseCommentedOn(th.selectedText) && (
																								<a
																									href="javascript:void(0)"
																									className="cf-show-more"
																									data-id={c.id}
																									onClick={this.toggleCollapseLink.bind(
																									this
																									)}
																								>
																									{__(
																									"Show more",
																									"commenting-feature"
																									)}
																								</a>
																								)}
																							</Fragment>
																						)}
																						</blockquote>
																					</Fragment>
																					)}
																				</div>
																	);
																})}
																<Board datatext={boardId} onLoadFetch={1} />
															</div>
														);
													} else {
														return null;
													}
												}
											})}
										</div>
									);
								}
								if (
									"cf-settings" === tab.name &&
									$(".cf-settings-tab-title").css("display", "block")
								) {
									seenIds.clear();
									return (
										<SidebarSettings
											handleShowComments={this.handleShowComments}
											enableCoEditing={this.enableCoEditing}
											postStatus={this.postStatus}
											commentBoardToggle={commentBoardToggle}
										/>
									);
								}
								if (
									"cf-comment-summary" === tab.name &&
									$(".cf-comment-summary-tab-title").css("display", "block")
								) {
									seenIds.clear();
									return (
										<>
										{true === isLoading && (
											<div className="comment-summary-row-loading">
												<strong>
												{__(
													"Loading...",
													"commenting-feature"
												)}
												</strong>
											</div>
										)}
										
										{false === isLoading && (
											<ActivitySummary 
												// threads={ threads }
												commentAutoDrafts = { commentAutoDrafts }
						
												setDifference = { setDifference }
											/>
										)}
										</>
									)
								}
							}}
						</TabPanel>
						<Fragment>
							<div
								className="cf-feedback-post-wrap__outer"
								style={{ display: "none" }}
							>
								<div className="cf-feedback-post-wrap__inner">
									<button className="cf-feedback-post-wrap__button">
										{icons.fbcommentIcon}
									</button>
								</div>
							</div>
						</Fragment>
					</PanelBody>
				);
			
		}
	}
}

/**
 * Renders a custom sidebar for the Gutenberg editor.
 * 
 * This function creates a sidebar named "cf-activity-center" which is intended
 * for displaying comments related to the current post or page being edited.
 * It includes a menu item in the more options menu (the three dots menu in the
 * top right of the editor) that, when clicked, opens this custom sidebar.
 * 
 * The sidebar is populated with the content from the <Comments /> component,
 * which presumably handles the display and management of comments.
 */
function cfCommentsSidebar() {

	/**
	 * Subscribes to changes in the active general sidebar in the Gutenberg editor
	 * and opens the "cf-collab-sidebar" sidebar if no active sidebar is detected.
	 * This ensures that the custom "cf-activity-center" sidebar is displayed when
	 * the editor is loaded.
	 */
	useEffect(() => {
		const unsubscribe = wp.data.subscribe(() => {
			const sidebarName = wp.data.select("core/edit-post").getActiveGeneralSidebarName();
			if ( ! sidebarName ) {
				// Check if open board count is 0 then not open the sidebar.
				const selectedNontextblock = wp.data.select('mdstore').getBoardIds();

				if (selectedNontextblock.length > 0) {
					const meta = wp.data.select("core/editor").getEditedPostAttribute("meta");
					
					const startsWithEl = selectedNontextblock.filter(item => item.startsWith("el"));
					const doesNotStartWithEl = selectedNontextblock.filter(item => !item.startsWith("el"));				
					// Check the conditions using these separated values
					if ( startsWithEl.length > 0 || doesNotStartWithEl.length > 0 ) {
						wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/cf-collab-sidebar');
					}
				
				}
			}
		});

		return () => {
			unsubscribe();
		};
	}, []);

	return (
		<Fragment>
			<PluginSidebarMoreMenuItem target="cf-activity-center">
				{__("Multicollab", "cf-activity-center")}
			</PluginSidebarMoreMenuItem>
			<PluginSidebar
				name="cf-activity-center"
				title={__(`Multicollab`, "cf-activity-center")}
			>
				<Comments />
			</PluginSidebar>
		</Fragment>
	);
}

registerPlugin("cf-activity-center", {
	icon: icons.multicollab,
	render: cfCommentsSidebar,
});
