( function( blocks, element, components, blockEditor, i18n ) {
  if ( ! blocks || ! element || ! components || ! blockEditor || ! i18n ) {
    return;
  }

  var __ = i18n.__;
  var el = element.createElement;
  var Fragment = element.Fragment;
  var useState = element.useState;
  var useEffect = element.useEffect;
  var InspectorControls = blockEditor.InspectorControls;
  var useBlockProps = blockEditor.useBlockProps;
  var PanelBody = components.PanelBody;
  var TextControl = components.TextControl;
  var ToggleControl = components.ToggleControl;
  var SelectControl = components.SelectControl;
  var RangeControl = components.RangeControl;
  var Spinner = components.Spinner;

  // Block API v3 requires the edit() root element to carry the props returned
  // by useBlockProps(), otherwise the block is not selectable inside the
  // iframed editor. useBlockProps has shipped since WP 5.6 and the plugin
  // floor is 6.0, so the fallback below is belt-and-braces only; it resolves
  // once at module scope, so hook call order stays stable across renders.
  function buildPreview( title, description ) {
    var previewProps = useBlockProps
      ? useBlockProps( { className: 'bookaro-block-preview' } )
      : { className: 'bookaro-block-preview' };

    return el(
      'div',
      previewProps,
      el( 'strong', null, title ),
      el( 'div', { style: { marginTop: '6px', color: '#555' } }, description )
    );
  }

  function useProviderServices( providerId ) {
    var initialState = { items: [], loading: false, error: '' };
    var _a = useState( initialState );
    var state = _a[0];
    var setState = _a[1];

    useEffect( function() {
      var id = parseInt( providerId, 10 ) || 0;
      if ( ! id ) {
        setState( initialState );
        return;
      }

      var data = window.BookaroBlocksData || {};
      var baseUrl = data.restUrl || '';
      if ( ! baseUrl ) {
        setState( { items: [], loading: false, error: __( 'REST API unavailable.', 'bookaro' ) } );
        return;
      }

      var url = baseUrl.replace( /\/$/, '' ) + '/providers/' + id + '/services';
      var headers = {};
      if ( data.restNonce ) {
        headers[ 'X-WP-Nonce' ] = data.restNonce;
      }

      var cancelled = false;
      setState( { items: [], loading: true, error: '' } );

      window.fetch( url, { method: 'GET', credentials: 'same-origin', headers: headers } )
        .then( function( response ) {
          return response.json().then( function( body ) {
            if ( ! response.ok ) {
              var msg = body && body.message ? body.message : __( 'Unable to load services.', 'bookaro' );
              throw new Error( msg );
            }
            return body;
          } );
        } )
        .then( function( body ) {
          if ( cancelled ) {
            return;
          }
          var items = Array.isArray( body ) ? body : [];
          setState( { items: items, loading: false, error: '' } );
        } )
        .catch( function( error ) {
          if ( cancelled ) {
            return;
          }
          setState( { items: [], loading: false, error: error && error.message ? error.message : __( 'Unable to load services.', 'bookaro' ) } );
        } );

      return function() {
        cancelled = true;
      };
    }, [ providerId ] );

    return state;
  }

  function BookingControls( props ) {
    var attrs = props.attributes;
    var includeAutoOpen = !!props.includeAutoOpen;
    var providerId = parseInt( attrs.providerId, 10 ) || 0;
    var listingLabel = providerId > 0
      ? __( 'Listing ID (optional)', 'bookaro' )
      : __( 'Listing ID (required)', 'bookaro' );
    var providerLabel = providerId > 0
      ? __( 'Provider ID (required for Generic mode)', 'bookaro' )
      : __( 'Provider ID (optional)', 'bookaro' );
    var servicesState = useProviderServices( providerId );
    var serviceOptions = [ { label: __( 'Select a service', 'bookaro' ), value: 0 } ];
    if ( servicesState.items && servicesState.items.length ) {
      servicesState.items.forEach( function( service ) {
        var label = service.title || __( 'Untitled service', 'bookaro' );
        if ( service.price_formatted ) {
          label += ' · ' + service.price_formatted;
        } else if ( typeof service.price !== 'undefined' && service.price !== '' ) {
          label += ' · ' + service.price;
        }
        if ( service.duration ) {
          label += ' · ' + service.duration + 'm';
        }
        serviceOptions.push( { label: label, value: service.id } );
      } );
    }

    return el(
      InspectorControls,
      null,
      el(
        PanelBody,
        { title: __( 'Booking Settings', 'bookaro' ), initialOpen: true },
        el( TextControl, {
          label: listingLabel,
          value: attrs.listingId || '',
          onChange: function( value ) {
            props.setAttributes( { listingId: parseInt( value, 10 ) || 0 } );
          }
        } ),
        el( TextControl, {
          label: providerLabel,
          value: attrs.providerId || '',
          onChange: function( value ) {
            props.setAttributes( { providerId: parseInt( value, 10 ) || 0 } );
          }
        } ),
        providerId > 0
          ? el(
              Fragment,
              null,
              servicesState.loading
                ? el( 'div', { className: 'bookaro-block-service-loading' }, el( Spinner ), ' ', __( 'Loading services…', 'bookaro' ) )
                : null,
              ( ! servicesState.loading && serviceOptions.length > 1 )
                ? el( SelectControl, {
                    label: __( 'Service', 'bookaro' ),
                    value: attrs.serviceId || 0,
                    options: serviceOptions,
                    onChange: function( value ) {
                      var serviceId = parseInt( value, 10 ) || 0;
                      if ( ! serviceId ) {
                        props.setAttributes( { serviceId: 0 } );
                        return;
                      }
                      var selected = null;
                      servicesState.items.forEach( function( service ) {
                        if ( parseInt( service.id, 10 ) === serviceId ) {
                          selected = service;
                        }
                      } );
                      if ( ! selected ) {
                        props.setAttributes( { serviceId: serviceId } );
                        return;
                      }
                      var nextAttrs = {
                        serviceId: serviceId,
                        serviceLabel: selected.title || attrs.serviceLabel || '',
                        price: typeof selected.price !== 'undefined' ? String( selected.price ) : attrs.price || '',
                        serviceDuration: selected.duration ? parseInt( selected.duration, 10 ) || 0 : attrs.serviceDuration || 0
                      };
                      if ( selected.listing_id && ( ! attrs.listingId || attrs.listingId !== selected.listing_id ) ) {
                        nextAttrs.listingId = parseInt( selected.listing_id, 10 ) || attrs.listingId || 0;
                      }
                      props.setAttributes( nextAttrs );
                    }
                  } )
                : null,
              ( ! servicesState.loading && providerId > 0 && serviceOptions.length <= 1 )
                ? el( 'p', { className: 'description' }, __( 'No provider services found yet.', 'bookaro' ) )
                : null,
              ( servicesState.error )
                ? el( 'p', { className: 'description' }, servicesState.error )
                : null
            )
          : null,
        el( TextControl, {
          label: __( 'Service ID (optional)', 'bookaro' ),
          value: attrs.serviceId || '',
          onChange: function( value ) {
            props.setAttributes( { serviceId: parseInt( value, 10 ) || 0 } );
          }
        } ),
        el( TextControl, {
          label: __( 'Service Label (optional)', 'bookaro' ),
          value: attrs.serviceLabel || '',
          onChange: function( value ) {
            props.setAttributes( { serviceLabel: value } );
          }
        } ),
        el( TextControl, {
          label: __( 'Price (optional)', 'bookaro' ),
          value: attrs.price || '',
          onChange: function( value ) {
            props.setAttributes( { price: value } );
          }
        } ),
        el( TextControl, {
          label: __( 'Duration (minutes, optional)', 'bookaro' ),
          value: attrs.serviceDuration || '',
          onChange: function( value ) {
            props.setAttributes( { serviceDuration: parseInt( value, 10 ) || 0 } );
          }
        } ),
        el( TextControl, {
          label: __( 'Button Label (optional)', 'bookaro' ),
          value: attrs.buttonLabel || '',
          onChange: function( value ) {
            props.setAttributes( { buttonLabel: value } );
          }
        } ),
        el( TextControl, {
          label: __( 'Extra CSS class (optional)', 'bookaro' ),
          value: attrs.className || '',
          onChange: function( value ) {
            props.setAttributes( { className: value } );
          }
        } ),
        includeAutoOpen
          ? el( ToggleControl, {
              label: __( 'Auto open booking modal', 'bookaro' ),
              checked: !!attrs.autoOpen,
              onChange: function( value ) {
                props.setAttributes( { autoOpen: value } );
              }
            } )
          : null
      )
    );
  }

  function servicesCardsControls( props ) {
    var attrs = props.attributes;
    if ( attrs.source && ( !attrs.mode || attrs.mode === 'auto' ) && attrs.source !== 'auto' && attrs.source !== 'provider' ) {
      var migratedMode = attrs.source === 'bookaro' ? 'generic' : attrs.source;
      if ( migratedMode !== attrs.mode ) {
        props.setAttributes( { mode: migratedMode } );
      }
    }
    return el(
      InspectorControls,
      null,
      el(
        PanelBody,
        { title: __( 'Services Cards Settings', 'bookaro' ), initialOpen: true },
        (function() {
          var listingSource = attrs.listingSource || ( attrs.listingId ? 'manual' : 'current' );
          useEffect( function() {
            if ( ! attrs.listingSource ) {
              props.setAttributes( { listingSource: listingSource } );
            }
          }, [ attrs.listingSource, attrs.listingId ] );
          return el(
            Fragment,
            null,
            el( SelectControl, {
              label: __( 'Listing source', 'bookaro' ),
              value: listingSource,
              options: [
                { label: __( 'Current post (default)', 'bookaro' ), value: 'current' },
                { label: __( 'Manual listing ID', 'bookaro' ), value: 'manual' }
              ],
              onChange: function( value ) {
                var next = value === 'manual' ? 'manual' : 'current';
                var updates = { listingSource: next };
                if ( next !== 'manual' ) {
                  updates.listingId = 0;
                }
                props.setAttributes( updates );
              }
            } ),
            listingSource === 'manual'
              ? el( TextControl, {
                  label: __( 'Listing ID (required when manual)', 'bookaro' ),
                  value: attrs.listingId || '',
                  onChange: function( value ) {
                    props.setAttributes( { listingId: parseInt( value, 10 ) || 0 } );
                  }
                } )
              : null
          );
        })(),
        el( TextControl, {
          label: __( 'Provider ID (optional)', 'bookaro' ),
          value: attrs.providerId || '',
          onChange: function( value ) {
            props.setAttributes( { providerId: parseInt( value, 10 ) || 0 } );
          }
        } ),
        el( SelectControl, {
          label: __( 'Mode', 'bookaro' ),
          value: attrs.mode || 'auto',
          options: [
            { label: __( 'Auto', 'bookaro' ), value: 'auto' },
            { label: __( 'MyListing', 'bookaro' ), value: 'mylisting' },
            { label: __( 'Generic', 'bookaro' ), value: 'generic' }
          ],
          onChange: function( value ) {
            props.setAttributes( { mode: value, source: value === 'auto' ? 'auto' : '' } );
          }
        } ),
        el( SelectControl, {
          label: __( 'Layout', 'bookaro' ),
          value: attrs.layout || 'grid',
          options: [
            { label: __( 'Grid', 'bookaro' ), value: 'grid' },
            { label: __( 'List', 'bookaro' ), value: 'list' }
          ],
          onChange: function( value ) {
            props.setAttributes( { layout: value } );
          }
        } ),
        el( RangeControl, {
          label: __( 'Columns (grid only)', 'bookaro' ),
          value: attrs.columns || 3,
          min: 1,
          max: 6,
          onChange: function( value ) {
            props.setAttributes( { columns: parseInt( value, 10 ) || 3 } );
          }
        } ),
        el( ToggleControl, {
          label: __( 'Show price', 'bookaro' ),
          checked: !!attrs.showPrice,
          onChange: function( value ) {
            props.setAttributes( { showPrice: value } );
          }
        } ),
        el( ToggleControl, {
          label: __( 'Show duration', 'bookaro' ),
          checked: !!attrs.showDuration,
          onChange: function( value ) {
            props.setAttributes( { showDuration: value } );
          }
        } ),
        null
      )
    );
  }

  blocks.registerBlockType( 'bookaro/booking-button', {
    apiVersion: 3,
    title: __( 'MyBookaro Booking Button', 'bookaro' ),
    icon: 'calendar',
    category: 'bookaro',
    attributes: {
      listingId: { type: 'number', default: 0 },
      providerId: { type: 'number', default: 0 },
      serviceId: { type: 'number', default: 0 },
      serviceLabel: { type: 'string', default: '' },
      price: { type: 'string', default: '' },
      serviceDuration: { type: 'number', default: 0 },
      buttonLabel: { type: 'string', default: '' },
      className: { type: 'string', default: '' }
    },
    edit: function( props ) {
      return el(
        Fragment,
        null,
        el( BookingControls, { attributes: props.attributes, setAttributes: props.setAttributes, includeAutoOpen: false } ),
        buildPreview(
          __( 'MyBookaro Booking Button', 'bookaro' ),
          __( 'Displays a Book Now button for the selected listing.', 'bookaro' )
        )
      );
    },
    save: function() {
      return null;
    }
  } );

  blocks.registerBlockType( 'bookaro/booking-form', {
    apiVersion: 3,
    title: __( 'MyBookaro Booking Form', 'bookaro' ),
    icon: 'feedback',
    category: 'bookaro',
    attributes: {
      listingId: { type: 'number', default: 0 },
      providerId: { type: 'number', default: 0 },
      serviceId: { type: 'number', default: 0 },
      serviceLabel: { type: 'string', default: '' },
      price: { type: 'string', default: '' },
      serviceDuration: { type: 'number', default: 0 },
      buttonLabel: { type: 'string', default: '' },
      className: { type: 'string', default: '' },
      autoOpen: { type: 'boolean', default: true }
    },
    edit: function( props ) {
      return el(
        Fragment,
        null,
        el( BookingControls, { attributes: props.attributes, setAttributes: props.setAttributes, includeAutoOpen: true } ),
        buildPreview(
          __( 'MyBookaro Booking Form', 'bookaro' ),
          __( 'Embeds the MyBookaro booking form for the selected listing.', 'bookaro' )
        )
      );
    },
    save: function() {
      return null;
    }
  } );

  blocks.registerBlockType( 'bookaro/provider-dashboard', {
    apiVersion: 3,
    title: __( 'MyBookaro Provider Dashboard', 'bookaro' ),
    icon: 'groups',
    category: 'bookaro',
    edit: function() {
      return buildPreview(
        __( 'MyBookaro Provider Dashboard', 'bookaro' ),
        __( 'Shows the provider dashboard on the frontend.', 'bookaro' )
      );
    },
    save: function() {
      return null;
    }
  } );

  blocks.registerBlockType( 'bookaro/customer-dashboard', {
    apiVersion: 3,
    title: __( 'MyBookaro Customer Dashboard', 'bookaro' ),
    icon: 'admin-users',
    category: 'bookaro',
    edit: function() {
      return buildPreview(
        __( 'MyBookaro Customer Dashboard', 'bookaro' ),
        __( 'Shows the customer dashboard on the frontend.', 'bookaro' )
      );
    },
    save: function() {
      return null;
    }
  } );

  blocks.registerBlockType( 'bookaro/services-cards', {
    apiVersion: 3,
    title: __( 'MyBookaro Services Cards', 'bookaro' ),
    icon: 'grid-view',
    category: 'bookaro',
    attributes: {
      listingId: { type: 'number', default: 0 },
      providerId: { type: 'number', default: 0 },
      listingSource: { type: 'string', default: 'current' },
      mode: { type: 'string', default: 'auto' },
      layout: { type: 'string', default: 'grid' },
      columns: { type: 'number', default: 3 },
      showPrice: { type: 'boolean', default: true },
      showDuration: { type: 'boolean', default: true },
      source: { type: 'string', default: 'auto' }
    },
    edit: function( props ) {
      return el(
        Fragment,
        null,
        servicesCardsControls( props ),
        buildPreview(
          __( 'MyBookaro Services Cards', 'bookaro' ),
          __( 'Displays services with booking buttons.', 'bookaro' )
        )
      );
    },
    save: function() {
      return null;
    }
  } );

  if ( blocks.registerBlockVariation ) {
    blocks.registerBlockVariation( 'bookaro/booking-button', {
      name: 'bookaro-provider-booking-button',
      title: __( 'Book Now Button (Provider)', 'bookaro' ),
      description: __( 'Generic mode preset that requires a provider ID.', 'bookaro' ),
      attributes: {
        listingId: 0,
        providerId: 0
      },
      scope: [ 'inserter' ],
      keywords: [ __( 'provider', 'bookaro' ), __( 'generic', 'bookaro' ) ]
    } );

    blocks.registerBlockVariation( 'bookaro/services-cards', {
      name: 'bookaro-provider-services-cards',
      title: __( 'Services Cards (Provider)', 'bookaro' ),
      description: __( 'Show provider-defined services for a specific provider.', 'bookaro' ),
      attributes: {
        providerId: 0,
        listingSource: 'current',
        mode: 'generic',
        source: 'provider',
        columns: 3,
        layout: 'grid',
        showPrice: true,
        showDuration: true
      },
      scope: [ 'inserter' ],
      keywords: [ __( 'provider', 'bookaro' ), __( 'generic', 'bookaro' ) ]
    } );
  }
} )( window.wp && window.wp.blocks,
  window.wp && window.wp.element,
  window.wp && window.wp.components,
  window.wp && window.wp.blockEditor,
  window.wp && window.wp.i18n );
