/**
 * Ornate  Separator Block
 * Place ornate or animated separators with Gutenberg editor.
 * 
 */
( function( blocks, editor, i18n, element, components, underscore) {
	var el = element.createElement,
    Fragment = element.Fragment
    registerBlockType = blocks.registerBlockType,
    RichText = wp.blockEditor.RichText,
    BlockControls = wp.blockEditor.BlockControls,
		InspectorControls = wp.blockEditor.InspectorControls,//wp.blockEditor.InspectorControls
    AlignmentToolbar = wp.blockEditor.AlignmentToolbar;//editor.AlignmentToolbar;
		ResizableBox = components.ResizableBox;
		PanelBody = components.PanelBody;
		BaseControl = components.BaseControl;
		ButtonGroup = components.ButtonGroup;
		Button = components.Button;
	var __ = i18n.__;
	var useRef = element.useRef;
	var useEffect = element.useEffect;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var doingdrag = false;
	var getShadowStr = function( ss ) {
						sa = Math.abs(ss);
						shadowstr = '0px 0px 1px rgba(68, 68, 68, 0.9),'
						if(ss==0)
							shadowstr ="none";
						else if (ss>0)
							shadowstr += ss+'px '+ss+'px '+ss+'px rgba(68, 68, 68, 0.9)';
						else if (ss<0)
							shadowstr += sa+'px '+sa+'px '+sa+'px inset rgba(68, 68, 68, 0.9)';
            return shadowstr;
        		};
	var blockStyle = {
		backgroundColor: '#900',
		color: '#fff',
		padding: '20px',
	};
const iconEl = el('svg', { width: 20, height: 20 },
  el('path', { d: "M14.2-1.3c-0.1,0-0.3,0-0.4,0.1c-0.1,0-0.1,0.1-0.2,0.2s-0.1,0.2-0.1,0.3s0.1,0.6,0.2,1.3 C13.9,1.3,14,2,14,2.7c-0.2-0.3-0.4-0.6-0.6-0.8c-0.8-0.8-3-1.4-3-1.4L7.8,1.9c0.4-0.3,1.6,0.3,2.4,0.6c0.6,0.3,1.2,0.7,1.7,1.1 c0.6,0.4,0.8,1,0.8,1.7s-0.3,1.3-0.8,1.8c-0.1,0.1-0.2,0.2-0.4,0.3l2,1.2c0.1-0.1,0.2-0.1,0.2-0.2c0.3-0.3,0.5-0.5,0.7-0.8 s0.4-0.6,0.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El,
		category: 'layout',
		description: __( 'Highlight pull quotes, separate sections or add texture to page, 1000 variations', 'genolve-toolkit' ),
		//                                                A T T R I B U T E S
		attributes: {
				id: {
						type: 'string',
						default:  'sep'+Math.floor(100000 * Math.random())
						},
				isPreview: {
					type: 'boolean',
					default: false
					},
				background: {
						type: 'string',
						default:'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB2aWV3Qm94PSIwIDAgMjAwIDIwMCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ieE1pbllNaW4gbWVldCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6aHRtbD0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCIgaWQ9Im15c2VsZWN0ZWRzdmciPjxkZXNjPmV2b2x2ZWQgYXQgd3d3Lmdlbm9sdmUuY29tPC9kZXNjPjxnIGlkPSJBMHgyMDE5MDIyNTEwMTMwNjA1MzNjMDU4Yjk4MzkxODExOCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZ3JvdXBfcGliXzFfIj48c3R5bGU+dGV4dC5zdHlsZV9waTdfMV97IGZpbGw6dmFyKC0tZ190ZXh0XzEsI0FEOUNEMCk7IGZvbnQtZmFtaWx5OmluaGVyaXQ7fTwvc3R5bGU+PC9kZWZzPjxzdHlsZSBpZD0iZ19rdWxhcyI+ICAgOnJvb3R7IC0tZ19ncmFkaWVudHNfMTogIzhCMDAwMDstLWdfZ3JhZGllbnRzXzFfY29tcDE6ICMwMDhiMDA7LS1nX2dyYWRpZW50c18xX3Njb21wMTogIzAwOGI4YjstLWdfZ3JhZGllbnRzXzFfc2NvbXAyOiAjNDY4YjAwOy0tZ19ncmFkaWVudHNfMV9zaW1pMTogIzhiMjMwMDstLWdfZ3JhZGll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M3OTdkNzk7LS1nX3RleHRfMV90ZXRyYWQyOiAjNzk3OTdkOy0tZ190ZXh0XzFfdGV0cmFkMzogIzdkN2I3OTstLWdfdGV4dF8xX2Nocm9tMTogIzk2NzM3MzstLWdfdGV4dF8xX2Nocm9tMjogIzhhNzE3MTstLWdfdGV4dF8xX2Nocm9tMzogIzk2NjQ2NDstLWdfdGV4dF8xX2Nocm9tNDogI2EzNTQ1NDstLWdfdGV4dF8xX2xpZ2h0MTogIzg5ODU4NTstLWdfdGV4dF8xX2xpZ2h0MjogIzk1OTI5MjstLWdfdGV4dF8xX2xpZ2h0MzogI0ExOUU5RTstLWdfdGV4dF8xX2xpZ2h0NDogI0FFQUJBQjstLWdfdGV4dF8xX2RhcmsxOiAjNzE2RDZEOy0tZ190ZXh0XzFfZGFyazI6ICM2NDYxNjE7LS1nX3RleHRfMV9kYXJrMzogIzU3NTU1NTstLWdfdGV4dF8xX2Rhcms0OiAjNEI0OTQ5OyB9PC9zdHlsZT48dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB4PSIwIiB5PSI3MCIgY2xhc3M9InN0eWxlX3BpN18xXyIgZm9udC1zaXplPSI1OCI+PHRzcGFuIHg9IjAiIGR5PSIwIj5jbGlja21lPC90c3Bhbj48L3RleHQ+IDwvZz48L3N2Zz4='
						},
					alignment: {
						type: 'string',
						default:'center'
						},
					height: {
						type: 'number',
						default: 20
					}, 
					width: {
						type: 'number',
						default: 500
					},
					rounding: {
						type: 'number',
						default: 8
					},
					margin: {
						type: 'number',
						default: 8
					},
					shadow: {
						type: 'number',
						default: 0
					},
					pwidth:{
						type:'number',
						default: 100
					}
				}, // end attributes
		example: {
			attributes: {
				isPreview: true
				}
			},
		edit: function(props) {
				var outerRef = useRef(null);
				useEffect(function() {
					if (outerRef.current) {
						var doc = outerRef.current.ownerDocument;
						var myidA = doc.querySelectorAll('div[id="' + props.attributes.id + '"]');
						if (myidA.length > 1) {
							console.log("X X X separator dupe ids!" + myidA.length + " resetting:" + props.attributes.id);
							props.setAttributes({ id: 'sep' + Math.floor(100000 * Math.random()) });
						}
					}
				}, []);
				if ( props.attributes.isPreview ) {
					return el( 'div', { style: { padding: '0' } },
						el( 'img', {
							src: genolveToolkitBseparator.pluginUrl + 'img/blockpreview-separator.jpg',
							alt: __( 'Ornate Separator', 'genolve-toolkit' ),
							style: { width: '100%', height: 'auto' }
						})
					);
				}
			 	isSelected = props.isSelected,
        toggleSelection = props.toggleSelection,
        instanceId = props.instanceId;
				/* background not used siphon bg off eloop*/
				var background 	= props.attributes.background;
				var alignment 	= props.attributes.alignment;
				var height 			= props.attributes.height;
				var width 			= props.attributes.width;
				var pwidth 			= props.attributes.pwidth;
				var rounding    = props.attributes.rounding;
				var margin      = props.attributes.margin;
				var shadow      = props.attributes.shadow;
				//20190330 keep original rand id but make sure unique
				//20200214 moved dupe check to useEffect with ref for iframe compat
				//put defaults above ^^^    if(background==null) background = '';// some default background
				//if(alignment==null)alignment="center";
				function setBackground( newBg ) {
						console.log("separatorblock^^^^ setBackground^^^have props?"+props+"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
						console.log("separatorblock^^^^ setBackground(blockid:"+newBg.blockid+" =? myid:"+props.attributes.id+":");
						if(newBg.blockid==props.attributes.id){
							console.log("separatorblock^^^^ setBackground to:"+newBg.message);
							props.setAttributes( { background: newBg.message } );
							}
						}
				
				/* alignment */
        function onChangeAlignment( newAlignment ) {
            props.setAttributes( { alignment: newAlignment } );
        		}
				/* rounding */
        function onChangeRounding( newRound ) {
            props.setAttributes( { rounding: newRound } );
        		}
				/* margin */
        function onChangemargin( newPad ) {
            props.setAttributes( { margin: newPad } );
        		}
				/* shadow */
        function onChangeshadow( ss ) {
            props.setAttributes( { shadow: ss } );
        		}
				
				/* background : watch for when ready */
				function onLinkClick(){
					if(genolve_customize){// this is null: this.parentElement.getAttribute('data-block')
						// events must target parent window where genolve-customize.js triggers them
						jQuery(window).off('eloopsvgready');
						jQuery(window).on('eloopsvgready',setBackground);
						console.log('genolve_customize startup! for separatorblock id:' +props.attributes.id);
						genolve_customize.startupGenolve('block-separator',props.attributes.id);
						}
					else
						console.log('separatorblock found no genolve_customize!');
					}
				
			
		return (
		  el(Fragment,
				null,
				el(BlockControls,
						null,
						el(AlignmentToolbar,
								{
										value: alignment,
										onChange: onChangeAlignment,
								}
						)// end align
				), // end Block
				el('div',  // < OUTER DIV
					useBlockProps({
					id:props.attributes.id,
					ref: outerRef,
					className: 'gnlv-separator',
					style: { width: '100%',height:'auto' }
					}),
					el('div', { // < INNER DIV
							id: 'gnlv-inner-div',
							style: { display:'grid',
												justifyItems: alignment,}
							},
							/* 
							ref https://github.com/bokuweb/re-resizable
							https://wordpress.org/gutenberg/handbook/designers-developers/developers/components/resizable-box/
							*/
						el(ResizableBox,// < SIZER DIV
								{ 
								id:'resize_'+props.attributes.id,
								className: 'components-resizable-box__container block-library-spacer__resize-container is-resizing',//20220417 is-selected->is-resizing to block application of style that blocks resizing
								size: {
									height:height,
									width:pwidth+'%'
									},
									/* this shows a grey box but that is kind of a nice feed back on the margin size
									and moving the resize dot up gets rid of annoying conflict with add block control */
								style:{					
																'margin-bottom':margin+"px"
																			},
								minHeight:10,
								//minWidth:10,
								lockAspectRatio:false,
								/* ooops cant do height very good : bounds:'parent', */
								enable: {
										top: false,
										right: false,
										bottom: true,
										left: false,
										topRight: false,
										bottomRight: false,
										bottomLeft: false,
										topLeft: false,
								} ,
							onResizeStop:function ( event, direction, elt, delta )  {
										/*											width  		= parseInt( width + delta.width, 10 );*/
										stemp ="";
										for(key in elt) stemp+="["+key+"]="+elt[key]+ " " ;
										centw     = parseInt(width/pwidth*100)+'%';
										doingdrag = false;
										console.log("separatorblock resize stop id["+props.attributes.id+"] percent width:"+pwidth+" h:"+height+" delta.height:"+delta.height+": direction:"+direction+" elt:"+stemp);
										
										props.setAttributes( {
												height: parseInt( height + delta.height, 10 ),
												width: pwidth+'%',// edit mode this wraps BG div
												} );
										toggleSelection( true );
								} ,
							onResizeStart:function ()  {
									/**/
									pixwidth = outerRef.current ? outerRef.current.querySelector('#gnlv-final-div').offsetWidth : 0;
									doingdrag=true;
									console.log("separatorblock resize start id["+props.attributes.id+"] pixwidth:"+pixwidth);
									props.setAttributes( {
												width: pwidth+'%',
												} );
									toggleSelection( false );
									} 
									 
									},
								
								el('div', // < BACKGROUND DIV - EDIT mode
									{id: 'gnlv-final-div',
									style:{ height: height,  // changes? one more below
													width: '100%', // for editmode this is 100%
													borderRadius:rounding+"px",
													margin:margin+"px 0px",
													'box-shadow': getShadowStr(shadow),
													border:'thin red dashed',
													backgroundImage:"url('"+background+"')" 
													},
									onClick:onLinkClick}
									)
								)	// end sizer div
							) // end inner div
				) // end outer div
			
			// vvv INSPECTOR
		,el(InspectorControls, 
			null, 
			el(PanelBody, 
				{
      	title: __('More Settings')
    		}, 
				// start                       SHADOW
				el(BaseControl, 
						{
						label: __('shadow'),
						id: 'dummyids'
						}, 
						el("input", 
								{
								type: "number",
								id: 'dummyidss',
								value: shadow,
								max: "10",
								min: "-10",
								step: "1",
								onChange: function onChange(event) {
									props.setAttributes({		shadow: parseInt(event.target.value, 10)	});
									console.log("separatorblock shadow now:"+event.target.value);
									}// end onChange
								}// end input el props
						)// end input
				),// end BaseControl
				// start                       MARGIN
				el(BaseControl, 
						{
						label: __('margin'),
						id: 'dummyidm'
						}, 
						el("input", 
								{
								type: "number",
								id: 'dummyidmm',
								value: margin,
								max: "100",
								step: "1",
								onChange: function onChange(event) {
									props.setAttributes({		margin: parseInt(event.target.value, 10)	});
									console.log("separatorblock margin now:"+event.target.value);
									}// end onChange
								}// end input el props
						)// end input
				),// end BaseControl
				// start                       ROUNDING
				el(BaseControl, 
						{
						label: __('rounding'),
						id: 'dummyid'
						}, 
						el("input", 
								{
								type: "number",
								id: 'dummyid2',
								value: rounding,
								max: "100",
								min: "0",
								step: "1",
								onChange: function onChange(event) {
									//setAttributes({		rounding: parseInt(event.target.value, 10)	});
									props.setAttributes({		rounding: parseInt(event.target.value, 10)	});
									console.log("separatorblock rounding now:"+event.target.value);
									}// end onChange
								}// end input el props
						)// end input
				),// end BaseControl
				// start                       PERCENT    WIDTH
				el(BaseControl, 
						{
						label: __('width'),
						id: 'dummyid'
						}, 
				el(ButtonGroup, {
          "aria-label": __('Percent Width')
        }, [25, 50, 75, 100].map(function (scale) {
          var scaledWidth = scale ;
          var isCurrent = pwidth === scaledWidth;
          return el(Button, {
								key: scale,
								isSmall: true,
								isPrimary: isCurrent,
								"aria-pressed": isCurrent,
								onClick: function(event){
									props.setAttributes({	pwidth:scaledWidth});
									console.log("separatorblock pwidth ev:"+event.target.value+" var:"+scaledWidth+ " id:"+props.attributes.id);
									//update resizer div
									if (outerRef.current) {
										var resizer = outerRef.current.querySelector('.components-resizable-box__container');
										if (resizer) resizer.style.width = scaledWidth + '%';
									}
									}
							}, scale, "%");
        }))// end ButtonGroup
				)//end BaseControl2
		)// end PanelBody
  ) // end InspectorControls
	// ^^^ End INSPECTOR
		) // end frag
		);// end return
    }, // end edit
		// SAVE
		// render_callback handles frontend output; save is for block validation only
    save: function( props ) {
        var pwidth 		= props.attributes.pwidth,
						height 		= props.attributes.height,
            alignment = props.attributes.alignment,
						margin    = props.attributes.margin,
						shadow    = props.attributes.shadow,
						rounding  = props.attributes.rounding,
						bg 				= props.attributes.background;

        var blockProps = useBlockProps.save({
						className: 'gnlv-separator',
						style: { width: '100%', height:'auto' }
				});

        return el( 'div', blockProps,
										el('div', {
												id: 'gnlv-inner-div',
												style: {display:'grid',
												justifyItems: alignment,
												 }
											},
												el('div', {
													id: 'gnlv-final-div',
													style: { height: height,
																	width: pwidth+"%",
																	borderRadius: rounding +"px",
																	'box-shadow': getShadowStr(shadow),
																	margin:margin+"px 0px",
																	backgroundImage:"url('"+bg+"')"
																	}
												})
										) // end inner
						);// end div outer
    },
	} );

} )(	
// adding stuff? index.php file too!
	window.wp.blocks,
	window.wp.editor,
	window.wp.i18n,
	window.wp.element,
	window.wp.components,
	window._
);
