import { __ } from "@wordpress/i18n";
import { useBlockProps, InnerBlocks } from "@wordpress/block-editor";
import { useSelect } from "@wordpress/data";
import "./editor.scss";

export default function Edit({ attributes, setAttributes, clientId }) {
	const blockProps = useBlockProps({
		className: "tab-group",
	});

	const tabs = useSelect(
		(select) => {
			const block = select("core/block-editor").getBlock(clientId);
			if (!block?.innerBlocks) return [];
			return block.innerBlocks.map((innerBlock, index) => ({
				id: `tab-${index + 1}`,
				panelId: `tabpanel-${index + 1}`,
				title: innerBlock.attributes?.title || __("Sans titre", "tab-group"),
				iconUrl: innerBlock.attributes?.iconUrl || "",
			}));
		},
		[clientId],
	);

	return (
		<section {...blockProps}>
			<div className="tab-group__toolbar">
				<div role="tablist" aria-labelledby="tablist-1" className="tablist">
					{tabs.map((tab, index) => (
						<button
							key={tab.id}
							id={tab.id}
							type="button"
							role="tab"
							aria-selected={index === 0}
							aria-controls={tab.panelId}
							tabIndex={index === 0 ? 0 : -1}
							data-tab={index}
						>
							{tab.iconUrl && (
								<img src={tab.iconUrl} alt="" className="tab__icon" aria-hidden />
							)}
							<span>{tab.title}</span>
						</button>
					))}
				</div>
			</div>
			<InnerBlocks
				allowedBlocks={["carhop-blocks/tab"]}
				template={[["carhop-blocks/tab"]]}
			/>
		</section>
	);
}
