/*
 * Icon Panel Changes Indicator
 */

import { useEffect } from 'react';
import blockConfig from '../icon-block/block.json';

// Get default values from block.json
const defaultSettings = Object.fromEntries(
	Object.entries( blockConfig.attributes ).map( ( [ key, { default: defaultValue } ] ) => [ key, defaultValue ] )
);

// Deep comparison for nested objects
const deepEqual = ( obj1, obj2 ) => {
	return JSON.stringify( obj1 ) === JSON.stringify( obj2 );
};

// Check if any attribute has changed for a particular device or global state
const hasChanged = ( currentAttributes = {}, attributeKey, deviceType ) => {
	const attributeValue = currentAttributes[ attributeKey ];
	const defaultValue = defaultSettings[ attributeKey ];

	if ( typeof attributeValue === 'object' && attributeValue !== null ) {
		return !deepEqual( attributeValue, defaultValue );
	}

	return attributeValue !== defaultValue;
};

// Function to update the panel toggle class
const updateIconPanelToggleClass = ( isChanged, panelTitle ) => {
	const panelToggles = document.querySelectorAll( '.components-panel__body-title' );

	panelToggles.forEach( ( panelToggle ) => {
		const buttonText = panelToggle.innerText || panelToggle.textContent;

		if ( buttonText.includes( panelTitle ) ) {
			const alreadyHasChangedClass = panelToggle.classList.contains( 'ssmb-panel-changed' );

			// Add or remove class based on changes
			if ( isChanged && !alreadyHasChangedClass ) {
				panelToggle.classList.add( 'ssmb-panel-changed' );
			} else if ( !isChanged && alreadyHasChangedClass ) {
				panelToggle.classList.remove( 'ssmb-panel-changed' );
			}
		}
	} );
};

// Function to reapply the class after opening or closing the panel
const reapplyClassOnPanelToggle = ( panelTitle, isChanged ) => {
	const panelBodies = document.querySelectorAll( '.components-panel__body' );

	panelBodies.forEach( ( panelBody ) => {
		const titleElement = panelBody.querySelector( '.components-panel__body-title' );

		if ( titleElement && titleElement.innerText.includes( panelTitle ) ) {
			// Reapply class to toggle button after the panel is toggled open/closed
			const panelToggle = panelBody.querySelector( '.components-panel__body-title' );
			if ( panelToggle ) {
				const alreadyHasChangedClass = panelToggle.classList.contains( 'ssmb-panel-changed' );
				if ( isChanged && !alreadyHasChangedClass ) {
					panelToggle.classList.add( 'ssmb-panel-changed' );
				} else if ( !isChanged && alreadyHasChangedClass ) {
					panelToggle.classList.remove( 'ssmb-panel-changed' );
				}
			}
		}
	} );
};

// Custom hook for monitoring changes and updating panel toggle button
export const useIconPanelBodyClass = ( attributes, attributeKeys, deviceType, panelTitle ) => {
	useEffect( () => {
		const isChanged = attributeKeys.some( ( key ) => hasChanged( attributes, key, deviceType ) );

		// Update the panel toggle button class
		updateIconPanelToggleClass( isChanged, panelTitle );

		// Reapply class when panel is opened/closed
		const panelBodies = document.querySelectorAll( '.components-panel__body' );
		panelBodies.forEach( ( panelBody ) => {
			const toggleButton = panelBody.querySelector( '.components-panel__body-title' );

			// Detect when the 'is-opened' class is added or removed
			const observer = new MutationObserver( () => {
				reapplyClassOnPanelToggle( panelTitle, isChanged );
			} );

			// Observe for class changes on the panel body
			observer.observe( panelBody, { attributes: true, attributeFilter: [ 'class' ] } );

			return () => observer.disconnect(); // Cleanup on component unmount
		} );
	}, [ JSON.stringify( attributes ), attributeKeys, deviceType, panelTitle] );
};
