(function (wp) {
	var el = wp.element.createElement;
	var registerPlugin = wp.plugins.registerPlugin;
	var PluginDocumentSettingPanel = wp.editor.PluginDocumentSettingPanel || wp.editPost.PluginDocumentSettingPanel;
	var useSelect = wp.data.useSelect;
	var useDispatch = wp.data.useDispatch;
	var RadioControl = wp.components.RadioControl;

	var T = HaupLocalizeTextCatRadio;

	var HaupMetaPanel = function () {
		var meta = useSelect(function (select) {
			return select('core/editor').getEditedPostAttribute('meta') || {};
		}, []);

		var currentCategories = useSelect(function (select) {
			return select('core/editor').getEditedPostAttribute('categories') || [];
		}, []);

		var { editPost } = useDispatch('core/editor');

		// 現在の選択値
		var selectedValue = meta['_haup_temp_category_id'] ? String(meta['_haup_temp_category_id']) : (currentCategories[0] ? String(currentCategories[0]) : '0');

		/*** カテゴリーを再帰的にレンダリングする関数 ***/
		var renderCategoryTree = function (items, depth = 0) {
			var nodes = [];
			items.forEach(function (item) {
				// 1行分のラジオボタン要素を作成
				nodes.push(
					el('div', {
						key: item.id,
						className: 'haup-cat-row',
						style: { marginLeft: (depth * 20) + 'px' } // ここで「行ごと」ずらす
					},
					el('input', {
						type: 'radio',
						id: 'haup-cat-' + item.id,
						name: 'haup_category_radio_group', // グループ名を統一
						value: item.id,
						checked: selectedValue === String(item.id),
						onChange: function () {
							var id = parseInt(item.id, 10);
							editPost({
								meta: { '_haup_temp_category_id': id },
								categories: [ id ]
							});
						}
					}),
						el('label', { htmlFor: 'haup-cat-' + item.id }, item.name)
					)
				);

				// 子階層があれば再帰的に追加
				if (item.children && item.children.length > 0) {
					nodes = nodes.concat(renderCategoryTree(item.children, depth + 1));
				}
			});
		return nodes;
		};

		return el( 
			PluginDocumentSettingPanel,
			{
				name: 'haup-category-radio-panel',
				title: T.title,
				icon: 'category',
				initialOpen: true,
			},
			el('div', { className: 'haup-category-tree-container' },
				renderCategoryTree(T.categories || [])
			)
		);
	};

	registerPlugin('haup-category-radio-plugin', { render: HaupMetaPanel });

/*** 標準のカテゴリーパネルを確実に削除するための監視処理 ***/
	const unsubscribe = wp.data.subscribe(function () {
	const editorSelect = wp.data.select('core/editor');
	const postType = editorSelect.getCurrentPostType();
    
	if (!postType) return;

	// PHP側で指定した投稿タイプ以外なら何もしない
	if (T.post_types && !T.post_types.includes(postType)) {
		unsubscribe();
		return;
	}

	const isCategoryPanelEnabled = wp.data.select('core/editor').isEditorPanelEnabled('taxonomy-panel-category');

	if (isCategoryPanelEnabled) {
		// パネルを削除 (dispatchも core/editor を使用)
		wp.data.dispatch('core/editor').removeEditorPanel('taxonomy-panel-category');
        
		// 削除に成功したら監視を解除
		unsubscribe();
	}
	});

})(window.wp);