/**
 * Linked placements follow My Block content + Design (one-way). Customize forks
 * this placement into an independent copy — never writes back to My Blocks.
 */
import { Button } from '@wordpress/components';
import {
	createElement,
	createPortal,
	Fragment,
	useEffect,
	useState,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Admin URL for the My Block builder (`#/editor/{id}`).
 *
 * @param {number|string} userBlockId
 * @return {string}
 */
export function myBlockEditorUrl( userBlockId ) {
	const id = Number( userBlockId );
	if ( ! id || typeof window === 'undefined' ) {
		return '';
	}
	const cfg =
		window.jocbmEditor ||
		window.jocbmFront ||
		window.jocbmAdmin ||
		{};
	const base = String( cfg.adminUrl || '' )
		.trim()
		.replace( /#.*$/, '' );
	if ( ! base ) {
		return '';
	}
	return `${ base }#/editor/${ id }`;
}

/**
 * Lightweight confirm overlay (works in Gutenberg + FE editor without admin UI).
 *
 * @param {object}   props
 * @param {boolean}  props.open
 * @param {string}   props.title
 * @param {string}   props.description
 * @param {string}   props.confirmLabel
 * @param {Function} props.onConfirm
 * @param {Function} props.onCancel
 */
function ScopeConfirmDialog( {
	open,
	title,
	description,
	confirmLabel,
	onConfirm,
	onCancel,
} ) {
	useEffect( () => {
		if ( ! open ) {
			return undefined;
		}
		const onKey = ( event ) => {
			if ( event.key === 'Escape' ) {
				event.stopPropagation();
				onCancel?.();
			}
		};
		window.addEventListener( 'keydown', onKey, true );
		return () => window.removeEventListener( 'keydown', onKey, true );
	}, [ open, onCancel ] );

	if ( ! open || typeof document === 'undefined' ) {
		return null;
	}

	return createPortal(
		createElement(
			'div',
			{
				className: 'bm-scope-confirm bm-scope-confirm--warning',
				role: 'alertdialog',
				'aria-modal': 'true',
				'aria-labelledby': 'bm-scope-confirm-title',
				'aria-describedby': 'bm-scope-confirm-desc',
			},
			createElement( 'div', {
				className: 'bm-scope-confirm__backdrop',
				onClick: onCancel,
			} ),
			createElement(
				'div',
				{ className: 'bm-scope-confirm__card' },
				createElement(
					'div',
					{
						className: 'bm-scope-confirm__notice',
						role: 'status',
					},
					createElement( 'span', {
						className:
							'dashicons dashicons-warning bm-scope-confirm__notice-icon',
						'aria-hidden': 'true',
					} ),
					createElement(
						'strong',
						{ className: 'bm-scope-confirm__notice-text' },
						__( 'Please read carefully', 'joc-blockora-morph' )
					)
				),
				createElement(
					'strong',
					{
						id: 'bm-scope-confirm-title',
						className: 'bm-scope-confirm__title',
					},
					title
				),
				createElement(
					'p',
					{
						id: 'bm-scope-confirm-desc',
						className: 'bm-scope-confirm__desc',
					},
					description
				),
				createElement(
					'div',
					{ className: 'bm-scope-confirm__actions' },
					createElement(
						Button,
						{
							variant: 'tertiary',
							onClick: onCancel,
							className: 'bm-scope-confirm__btn',
						},
						__( 'Cancel', 'joc-blockora-morph' )
					),
					createElement(
						Button,
						{
							variant: 'primary',
							isDestructive: true,
							onClick: onConfirm,
							className: 'bm-scope-confirm__btn',
						},
						confirmLabel
					)
				)
			)
		),
		document.body
	);
}

/**
 * @param {object}   props
 * @param {Function} props.onCustomizeInstance
 * @param {string}   [props.editMyBlockUrl]
 */
export default function StyleScopeGate( {
	onCustomizeInstance,
	editMyBlockUrl = '',
} ) {
	const [ pending, setPending ] = useState( false );

	const title = __( 'This block is wired to My Blocks', 'joc-blockora-morph' );
	const description = __(
		'Content and design stay in sync with your My Block. Customize this instance to fork an independent copy — after that, My Block updates will no longer apply here.',
		'joc-blockora-morph'
	);
	const editUrl = String( editMyBlockUrl || '' ).trim();

	return createElement(
		Fragment,
		null,
		createElement(
			'div',
			{
				className: 'bm-style-scope-gate bm-style-scope-gate--full',
				role: 'dialog',
				'aria-label': title,
			},
			createElement(
				'div',
				{ className: 'bm-style-scope-gate__card' },
				createElement(
					'strong',
					{ className: 'bm-style-scope-gate__title' },
					title
				),
				createElement(
					'p',
					{ className: 'bm-style-scope-gate__desc' },
					description
				),
				createElement(
					'div',
					{ className: 'bm-style-scope-gate__actions' },
					createElement(
						Button,
						{
							variant: 'primary',
							onClick: () => setPending( true ),
							className: 'bm-style-scope-gate__btn',
						},
						__( 'Customize this instance', 'joc-blockora-morph' )
					),
					editUrl
						? createElement(
								Button,
								{
									variant: 'secondary',
									href: editUrl,
									target: '_blank',
									rel: 'noopener noreferrer',
									className:
										'bm-style-scope-gate__btn bm-style-scope-gate__btn--edit',
								},
								createElement( 'span', {
									className:
										'dashicons dashicons-external bm-style-scope-gate__btn-icon',
									'aria-hidden': 'true',
								} ),
								__( 'Edit My Block', 'joc-blockora-morph' )
						  )
						: null
				)
			)
		),
		createElement( ScopeConfirmDialog, {
			open: pending,
			title: __( 'Make this its own block?', 'joc-blockora-morph' ),
			description: __(
				'This placement will become an isolated copy with its own content and design. It will no longer use your My Block, so future My Block updates will not apply here.',
				'joc-blockora-morph'
			),
			confirmLabel: __( 'Customize this instance', 'joc-blockora-morph' ),
			onConfirm: () => {
				setPending( false );
				onCustomizeInstance?.();
			},
			onCancel: () => setPending( false ),
		} )
	);
}
