( function ( blocks, blockEditor, components, element, i18n, apiFetch ) {
	'use strict';

	var __               = i18n.__;
	var el               = element.createElement;
	var useState         = element.useState;
	var useEffect        = element.useEffect;
	var registerBlockType = blocks.registerBlockType;
	var InspectorControls = blockEditor.InspectorControls;
	var PanelColorSettings = blockEditor.PanelColorSettings || null;
	var useBlockProps    = blockEditor.useBlockProps;
	var PanelBody        = components.PanelBody;
	var RangeControl     = components.RangeControl;
	var ToggleControl    = components.ToggleControl;
	var SelectControl    = components.SelectControl;
	var TextControl      = components.TextControl;
	var Spinner          = components.Spinner;

	// ── Style maps (mirror render.php) ───────────────────────────────────────────
	var RADIUS_MAP  = { none: '0px',  soft: '14px',  round: '22px' };
	var IMG_PB_MAP  = { short: '42%', medium: '58%', tall: '78%' };
	var SPACING_PAD = { compact: '12px 14px', normal: '16px 18px', spacious: '24px 28px' };
	var SPACING_GAP = { compact: '4px',        normal: '8px',       spacious: '14px' };

	var BTN_STYLE = {
		primary: { background: '#0F172A', color: '#fff',    border: 'none'                },
		accent:  { background: '#3B82F6', color: '#fff',    border: 'none'                },
		outline: { background: 'transparent', color: '#0F172A', border: '2px solid #0F172A' },
	};

	var MOCK_FIELDS = [
		{ id:'m1', name:'Football Field A', sports:['Football','Soccer'],  description:'Full-size grass pitch with floodlights.',   base_price:30 },
		{ id:'m2', name:'Badminton Court 1', sports:['Badminton'],          description:'Indoor court with professional nets.',       base_price:15 },
		{ id:'m3', name:'Cricket Ground',    sports:['Cricket'],            description:'Standard cricket ground with pavilion.',     base_price:50 },
	];

	// ── Derived preview styles from attributes ───────────────────────────────────
	function previewStyles( attrs ) {
		return {
			radius:      RADIUS_MAP[ attrs.cardRadius ]  || RADIUS_MAP.soft,
			imgPb:       IMG_PB_MAP[ attrs.imgHeight ]   || IMG_PB_MAP.medium,
			bodyPadding: SPACING_PAD[ attrs.spacing ]    || SPACING_PAD.normal,
			bodyGap:     SPACING_GAP[ attrs.spacing ]    || SPACING_GAP.normal,
			cardBg:      attrs.cardBg    || '#FFFFFF',
			titleColor:  attrs.titleColor || '#0F172A',
			priceColor:  attrs.priceColor || '#3B82F6',
			badgeBg:     attrs.badgeBg   || '#EFF6FF',
			badgeColor:  attrs.badgeColor || '#1E40AF',
			titleSize:   attrs.titleSize > 0 ? attrs.titleSize + 'px' : '17px',
			btn:         BTN_STYLE[ attrs.buttonStyle ] || BTN_STYLE.primary,
		};
	}

	// ── renderCard (editor canvas preview) ───────────────────────────────────────
	function renderCard( field, idx, attrs ) {
		var s      = previewStyles( attrs );
		var isList = attrs.cardStyle === 'list';
		var sports = Array.isArray( field.sports ) ? field.sports : [];
		var price  = parseFloat( field.base_price ) || 0;
		var btnLabel = attrs.buttonText || 'Book Now';

		// ── List row ──────────────────────────────────────────────────────────
		if ( isList ) {
			return el( 'div', { key: field.id || idx, style: {
				display:'flex', alignItems:'center', gap:'16px',
				padding: s.bodyPadding,
				background: s.cardBg,
				border: '1px solid #E2E8F0',
				borderRadius: s.radius,
			} },
				el( 'div', { style: { width:10, height:10, borderRadius:'50%', background: s.priceColor, flexShrink:0 } } ),
				el( 'div', { style: { flex:1, minWidth:0 } },
					el( 'p', { style: { margin:0, fontWeight:700, fontSize: s.titleSize, color: s.titleColor } }, field.name || 'Field ' + (idx+1) ),
					attrs.showSports && sports.length
						? el( 'p', { style: { margin:'3px 0 0', fontSize:'12px', color:'#64748B' } }, sports.join(' · ') )
						: null,
					attrs.showDescription && field.description
						? el( 'p', { style: { margin:'3px 0 0', fontSize:'12px', color:'#64748B' } }, field.description.slice(0,80) )
						: null
				),
				el( 'div', { style: { display:'flex', alignItems:'center', gap:'12px', flexShrink:0 } },
					attrs.showPrice && price > 0
						? el( 'p', { style: { margin:0, fontSize:'16px', fontWeight:800, color: s.priceColor, whiteSpace:'nowrap' } },
							'$' + price.toFixed(0),
							el( 'span', { style: { fontSize:'11px', fontWeight:500, color:'#94A3B8' } }, ' / slot' )
						)
						: null,
					attrs.showButton
						? el( 'div', { style: {
							padding:'8px 18px', borderRadius:'8px', fontSize:'13px', fontWeight:600,
							background: s.btn.background, color: s.btn.color, border: s.btn.border || 'none',
							whiteSpace:'nowrap',
						} }, btnLabel )
						: null
				)
			);
		}

		// ── Card ─────────────────────────────────────────────────────────────
		return el( 'article', { key: field.id || idx, style: {
			background: s.cardBg,
			border: 'none',
			borderRadius: s.radius,
			overflow:'hidden',
			display:'flex',
			flexDirection:'column',
		} },
			attrs.showPhoto
				? el( 'div', { style: { position:'relative', width:'100%', paddingBottom: s.imgPb, background:'linear-gradient(135deg,#F1F5F9,#E2E8F0)', flexShrink:0 } },
					el( 'div', { style: { position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', gap:'8px' } },
						el( 'svg', { width:36, height:36, fill:'none', viewBox:'0 0 24 24', stroke:'#CBD5E1', strokeWidth:1.2, style:{opacity:.5} },
							el('rect', { x:3, y:3, width:18, height:18, rx:2 }),
							el('circle', { cx:8.5, cy:8.5, r:1.5 }),
							el('path', { d:'m21 15-5-5L5 21' })
						),
						el( 'span', { style: { fontSize:'10px', fontWeight:600, color:'#94A3B8', textTransform:'uppercase', letterSpacing:'.5px' } }, 'Photo' )
					)
				)
				: null,

			el( 'div', { style: { padding: s.bodyPadding, flex:1, display:'flex', flexDirection:'column', gap: s.bodyGap } },
				el( 'h3', { style: { margin:0, fontSize: s.titleSize, fontWeight:700, color: s.titleColor, lineHeight:1.25 } }, field.name || 'Field ' + (idx+1) ),

				attrs.showDescription && field.description
					? el( 'p', { style: { margin:0, fontSize:'13px', color:'#64748B', lineHeight:1.5 } },
						field.description.slice(0,80) + ( field.description.length > 80 ? '…' : '' )
					)
					: null,

				attrs.showSports && sports.length
					? el( 'div', { style: { display:'flex', flexWrap:'wrap', gap:'4px' } },
						sports.slice(0,4).map( function(s2, i) {
							return el( 'span', { key:i, style: {
								fontSize:'11px', fontWeight:600, padding:'3px 9px', borderRadius:'99px',
								background: s.badgeBg, color: s.badgeColor, letterSpacing:'.2px',
							} }, s2 );
						} )
					)
					: null,

				attrs.showPrice && price > 0
					? el( 'div', { style: { display:'flex', alignItems:'baseline', gap:'4px' } },
						el( 'span', { style: { fontSize:'20px', fontWeight:800, color: s.priceColor, lineHeight:1 } }, '$' + price.toFixed(0) ),
						el( 'span', { style: { fontSize:'12px', fontWeight:500, color:'#94A3B8' } }, '/ slot' )
					)
					: null
			),

			attrs.showButton
				? el( 'div', { style: { padding: s.bodyPadding.replace(/^(\S+)\s/, '$1 ').split(' ').map(function(v,i){ return i===0?'0':v; }).join(' ') + '; padding-top:0' } },
					el( 'div', { style: {
						display:'block', textAlign:'center',
						padding:'11px 0', borderRadius:'9px',
						fontSize:'14px', fontWeight:600,
						background: s.btn.background, color: s.btn.color,
						border: s.btn.border || 'none',
					} }, btnLabel )
				)
				: null
		);
	}

	function Edit( props ) {
		var attributes    = props.attributes;
		var setAttributes = props.setAttributes;
		var blockProps    = useBlockProps();

		var _f = useState( [] );
		var fields    = _f[0];
		var setFields = _f[1];

		var _l = useState( true );
		var loading    = _l[0];
		var setLoading = _l[1];

		var _e = useState( false );
		var apiEmpty   = _e[0];
		var setApiEmpty = _e[1];

		useEffect( function () {
			apiFetch( { path: '/playard/v1/admin/fields' } )
				.then( function ( res ) {
					var list = Array.isArray( res ) ? res : ( res && Array.isArray( res.data ) ? res.data : [] );
					var active = list.filter( function (f) {
						var st = f.status;
						return st === 'active' || st === 'Active' || st === true || st === 1;
					} );
					if ( active.length > 0 ) setFields( active );
					else setApiEmpty( true );
					setLoading( false );
				} )
				.catch( function () { setApiEmpty( true ); setLoading( false ); } );
		}, [] );

		var isList        = attributes.cardStyle === 'list';
		var displayFields = fields.length > 0 ? fields : ( apiEmpty ? MOCK_FIELDS : [] );
		var s             = previewStyles( attributes );

		var gridStyle = isList
			? { display:'flex', flexDirection:'column', gap:'10px' }
			: { display:'grid', gridTemplateColumns:'repeat(' + attributes.columns + ', 1fr)', gap:'20px' };

		// ── Sidebar color panel ──────────────────────────────────────────────────
		var colorPanel = PanelColorSettings
			? el( PanelColorSettings, {
				title: __( 'Colors', 'playard' ),
				initialOpen: true,
				colorSettings: [
					{ label: __( 'Card background',  'playard' ), value: attributes.cardBg,          onChange: function(v){ setAttributes({ cardBg: v || '' }); } },
					{ label: __( 'Card border',      'playard' ), value: attributes.cardBorderColor,  onChange: function(v){ setAttributes({ cardBorderColor: v || '' }); } },
					{ label: __( 'Title color',      'playard' ), value: attributes.titleColor,       onChange: function(v){ setAttributes({ titleColor: v || '' }); } },
					{ label: __( 'Price color',      'playard' ), value: attributes.priceColor,       onChange: function(v){ setAttributes({ priceColor: v || '' }); } },
					{ label: __( 'Badge background', 'playard' ), value: attributes.badgeBg,          onChange: function(v){ setAttributes({ badgeBg: v || '' }); } },
					{ label: __( 'Badge text',       'playard' ), value: attributes.badgeColor,       onChange: function(v){ setAttributes({ badgeColor: v || '' }); } },
				],
			} )
			: null;

		return el(
			'div', blockProps,

			el( InspectorControls, {},

				// ── Layout ──────────────────────────────────────────────────────
				el( PanelBody, { title: __( 'Layout', 'playard' ), initialOpen: true },
					el( SelectControl, {
						label:    __( 'Card style', 'playard' ),
						value:    attributes.cardStyle,
						options:  [
							{ label: __( 'Grid cards', 'playard' ), value: 'card' },
							{ label: __( 'List rows',  'playard' ), value: 'list' },
						],
						onChange: function(v){ setAttributes({ cardStyle: v }); },
					} ),
					! isList ? el( RangeControl, {
						label:    __( 'Columns', 'playard' ),
						value:    attributes.columns,
						onChange: function(v){ setAttributes({ columns: v }); },
						min: 1, max: 4,
					} ) : null,
					! isList ? el( SelectControl, {
						label:    __( 'Image height', 'playard' ),
						value:    attributes.imgHeight,
						options:  [
							{ label: __( 'Short',  'playard' ), value: 'short'  },
							{ label: __( 'Medium', 'playard' ), value: 'medium' },
							{ label: __( 'Tall',   'playard' ), value: 'tall'   },
						],
						onChange: function(v){ setAttributes({ imgHeight: v }); },
					} ) : null
				),

				// ── Card design ─────────────────────────────────────────────────
				el( PanelBody, { title: __( 'Card Design', 'playard' ), initialOpen: true },
					el( SelectControl, {
						label:    __( 'Corner radius', 'playard' ),
						value:    attributes.cardRadius,
						options:  [
							{ label: __( 'Square',  'playard' ), value: 'none'  },
							{ label: __( 'Rounded', 'playard' ), value: 'soft'  },
							{ label: __( 'Pill',    'playard' ), value: 'round' },
						],
						onChange: function(v){ setAttributes({ cardRadius: v }); },
					} ),
					el( SelectControl, {
						label:    __( 'Spacing', 'playard' ),
						value:    attributes.spacing,
						options:  [
							{ label: __( 'Compact',  'playard' ), value: 'compact'  },
							{ label: __( 'Normal',   'playard' ), value: 'normal'   },
							{ label: __( 'Spacious', 'playard' ), value: 'spacious' },
						],
						onChange: function(v){ setAttributes({ spacing: v }); },
					} ),
					el( SelectControl, {
						label:    __( 'Title size', 'playard' ),
						value:    attributes.titleSize,
						options:  [
							{ label: __( 'Default (17px)', 'playard' ), value: 0  },
							{ label: __( 'Small (14px)',   'playard' ), value: 14 },
							{ label: __( 'Medium (18px)',  'playard' ), value: 18 },
							{ label: __( 'Large (20px)',   'playard' ), value: 20 },
							{ label: __( 'XL (24px)',      'playard' ), value: 24 },
						],
						onChange: function(v){ setAttributes({ titleSize: parseInt( v, 10 ) }); },
					} )
				),

				// ── Card content ─────────────────────────────────────────────────
				el( PanelBody, { title: __( 'Card Content', 'playard' ), initialOpen: false },
					! isList ? el( ToggleControl, {
						label:    __( 'Show photo', 'playard' ),
						checked:  attributes.showPhoto,
						onChange: function(v){ setAttributes({ showPhoto: v }); },
					} ) : null,
					el( ToggleControl, {
						label:    __( 'Show description', 'playard' ),
						checked:  attributes.showDescription,
						onChange: function(v){ setAttributes({ showDescription: v }); },
					} ),
					el( ToggleControl, {
						label:    __( 'Show sports', 'playard' ),
						checked:  attributes.showSports,
						onChange: function(v){ setAttributes({ showSports: v }); },
					} ),
					el( ToggleControl, {
						label:    __( 'Show price', 'playard' ),
						checked:  attributes.showPrice,
						onChange: function(v){ setAttributes({ showPrice: v }); },
					} )
				),

				// ── Button ───────────────────────────────────────────────────────
				el( PanelBody, { title: __( 'Button', 'playard' ), initialOpen: false },
					el( ToggleControl, {
						label:    __( 'Show button', 'playard' ),
						checked:  attributes.showButton,
						onChange: function(v){ setAttributes({ showButton: v }); },
					} ),
					attributes.showButton ? el( TextControl, {
						label:    __( 'Button label', 'playard' ),
						value:    attributes.buttonText,
						onChange: function(v){ setAttributes({ buttonText: v }); },
					} ) : null,
					attributes.showButton ? el( SelectControl, {
						label:    __( 'Button style', 'playard' ),
						value:    attributes.buttonStyle,
						options:  [
							{ label: __( 'Primary (dark)', 'playard' ), value: 'primary' },
							{ label: __( 'Accent (blue)',  'playard' ), value: 'accent'  },
							{ label: __( 'Outline',        'playard' ), value: 'outline' },
						],
						onChange: function(v){ setAttributes({ buttonStyle: v }); },
					} ) : null,
					attributes.showButton ? el( SelectControl, {
						label:    __( 'Button action', 'playard' ),
						help:     attributes.buttonAction === 'modal'
							? __( 'Opens the booking modal pre-filtered to that field.', 'playard' )
							: __( 'Navigates to the booking page URL.', 'playard' ),
						value:    attributes.buttonAction,
						options:  [
							{ label: __( 'Open booking modal', 'playard' ), value: 'modal' },
							{ label: __( 'Go to booking page', 'playard' ), value: 'link'  },
						],
						onChange: function(v){ setAttributes({ buttonAction: v }); },
					} ) : null,
					attributes.showButton && attributes.buttonAction === 'link' ? el( TextControl, {
						label:    __( 'Booking page URL', 'playard' ),
						help:     __( 'Leave blank to use the current page URL.', 'playard' ),
						value:    attributes.bookingPage,
						onChange: function(v){ setAttributes({ bookingPage: v }); },
					} ) : null
				),

				colorPanel
			),

			// ── Canvas preview ───────────────────────────────────────────────────
			el( 'div', {},
				loading
					? el( Spinner )
					: el( 'div', {},
						apiEmpty
							? el( 'p', { style: { fontSize:'11px', color:'#94A3B8', margin:'0 0 12px', fontStyle:'italic' } },
								__( 'Preview — add real fields in Playard → Fields', 'playard' )
							)
							: null,
						el( 'div', { style: gridStyle },
							displayFields.map( function(f, i){ return renderCard( f, i, attributes ); } )
						)
					)
			)
		);
	}

	registerBlockType( 'playard/field-list', {
		edit: Edit,
		save: function(){ return null; },
	} );

} (
	window.wp.blocks,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.element,
	window.wp.i18n,
	window.wp.apiFetch
) );
