import { addFilter } from '@wordpress/hooks';
import { useFormContext, useWatch } from 'react-hook-form';

import { AdSenseAccountOverview } from '../components/AdSenseAccountOverview';

/**
 * Reads this field's live value from react-hook-form and parses it as the
 * JSON payload `modules/gadsense/class-settings.php`'s value_callback
 * produces (see account_overview_data() there for the shape).
 *
 * @param {Object} props
 * @param {string} props.fieldId The field's schema id, used as the form key.
 */
function AdSenseAccountOverviewField( { fieldId, hasToken } ) {
	const { control } = useFormContext();
	const value = useWatch( { name: fieldId, control } );

	let data;
	try {
		data = JSON.parse( value || '{}' );
	} catch {
		return null;
	}

	return <AdSenseAccountOverview data={ data } hasToken={ hasToken } />;
}

/**
 * The AdSense tab's account card is registered server-side as a `raw`
 * field whose value is JSON, not HTML — mount the real component instead
 * of FieldRenderer's default (RawField's `dangerouslySetInnerHTML`).
 */
addFilter(
	'advancedAds.settingsField',
	'advanced-ads/adsense-account-overview',
	( element, field, context ) => {
		if ( 'adsense-account-overview' !== field.id ) {
			return element;
		}

		return (
			<AdSenseAccountOverviewField
				fieldId={ field.id }
				hasToken={ context.adsenseHasToken }
			/>
		);
	}
);
