/**
 * List — editor render (port of Smart Team Pro's block).
 *
 * Markup twin of Team_List::render_block(): the Grid's `__items` / `__cell`
 * wrappers (so the ajax runtime drives it unchanged) around the shared
 * MemberCard in one of the three list designs. Zig Zag Orientation is Pro, so
 * no `--zigzag` class is rendered whatever `zigZag` holds.
 */

import { __ } from '@wordpress/i18n';
import { useMemo } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';
import { Spinner } from '@wordpress/components';

import { BlockInspectorTabs } from '../../components';
import { AIRefineControl } from '../shared/ai-builder';
import useUniqueId from '../../hooks/useUniqueId';
import useTeamChildBlocks from '../../hooks/useTeamChildBlocks';
import useMembers from '../../hooks/useMembers';
import ExtraIdWrapper from '../../shared/ExtraIdWrapper.jsx';
import DemoMembersNotice from '../shared/DemoMembersNotice.jsx';
import dynamicCss from './dynamicCss';
import { extractGoogleFontImports } from '../../utils/googleFonts.js';
import Inspector from './inspect';
import MemberCard, { MetaIconSprite } from '../shared/MemberCard';
import useCardSettings from '../shared/useCardSettings';
import { TogglePanelBodyProvider } from '../../hooks/togglePanelBodyContext';
import { resolveDesign } from './styles';

// Twin of Team_List::root_classes().
export const rootClasses = ({ cardDesign, imagePosition }) =>
	[
		'sp-smart-team-grid',
		'sp-smart-team-list',
		`sp-smart-team-list--${resolveDesign(cardDesign)}`,
		imagePosition === 'right' ? 'sp-smart-team-list--image-right' : '',
	].filter(Boolean);

export default function Edit({ clientId, attributes, setAttributes }) {
	const { uniqueId } = attributes;

	useUniqueId(clientId, uniqueId, setAttributes, 'sp-smart-team-list-', 'sptp/');

	// Wrap with team-group + manage the addon child blocks from the Display Settings toggles.
	useTeamChildBlocks(clientId, attributes);

	const design = resolveDesign(attributes.cardDesign);
	const resolved = useMemo(() => ({ ...attributes, cardDesign: design }), [attributes, design]);

	const blockStyling = useMemo(
		() => extractGoogleFontImports(resolved) + dynamicCss(resolved),
		[resolved]
	);

	const { members, loading, error, isDemoMembers } = useMembers(attributes);

	const blockProps = useBlockProps({ className: 'sp-smart-team-wrapper' });
	const settings = useCardSettings(resolved);
	const { meta } = settings;

	return (
		<div {...blockProps}>
			{/* Refine only: the List always has a design, and the AI never builds one. */}
			<AIRefineControl clientId={clientId} blockName="sptp/team-list" isConfigured />
			<style dangerouslySetInnerHTML={{ __html: blockStyling }} />

			<TogglePanelBodyProvider>
				<BlockInspectorTabs
					attributes={{ ...resolved, blockName: 'team-list' }}
					setAttributes={setAttributes}
					General={Inspector}
					documentLink="https://docs.getwpteam.com/guide/blocks/list"
				/>

				{isDemoMembers && <DemoMembersNotice />}

				<ExtraIdWrapper id={attributes.additionalId}>
					<div
						id={uniqueId}
						className={[...rootClasses(attributes), attributes.additionalCssClass || '']
							.filter(Boolean)
							.join(' ')}
					>
						{loading ? (
							<div className="sp-smart-team-grid__loading">
								<Spinner />
								{__('Loading team members…', 'team-free')}
							</div>
						) : error ? (
							<p className="sp-smart-team-grid__empty">{error}</p>
						) : members.length === 0 ? (
							<p className="sp-smart-team-grid__empty">
								{__('No team members found.', 'team-free')}
							</p>
						) : (
							<div className="sp-smart-team-grid__items">
								<MetaIconSprite iconSet={meta.iconSet} />
								{members.map((member) => (
									<div key={member.id} className="sp-smart-team-grid__cell">
										<MemberCard
											member={member}
											{...settings}
											cardDesign={design}
										/>
									</div>
								))}
							</div>
						)}
					</div>
				</ExtraIdWrapper>
			</TogglePanelBodyProvider>
		</div>
	);
}
