/*
	https://jonathanbossenger.com/developing-wordpress-blocks-without-react/
	https://developer.wordpress.org/block-editor/getting-started/tutorial/
	https://developer.wordpress.org/resource/dashicons/#shortcode
*/

( function( blocks, element, components, blockEditor ) {

	if (blocks) {
		/**
		* Load WordPress dependencies
		* This is the same as importing the dependencies in an ES2015+ environment
		*/

		const __					= wp.i18n.__;

		const el					= element.createElement;

		const InspectorControls		= blockEditor.InspectorControls;

		const CheckboxControl		= components.CheckboxControl;
		const ComboboxControl		= components.ComboboxControl;
		const RadioControl			= components.RadioControl;
		const RangeControl			= components.RangeControl;
		const SelectControl			= components.SelectControl;
		const TextControl			= components.TextControl;
		const ToggleControl			= components.ToggleControl;
		const Panel					= components.Panel;
		const PanelBody				= components.PanelBody;
		const PanelRow				= components.PanelRow;

		const Fragment				= element.Fragment;
		const registerBlockType		= blocks.registerBlockType;

		const iconEl = el("svg", { viewBox: "0 0 30 30", preserveAspectRatio: "xMidYMid meet" },
			el("path", { fill: "#567fbd", d: "M18.3916 13.1621C17.6084 12 16.32 11.2926 14.9053 11.2926C13.4905 11.2926 12.2021 12 11.4189 13.1621L8.53895 17.4821C7.68 18.7958 7.57895 20.3874 8.33684 21.7768C9.06947 23.1663 10.4589 24 12.0253 24L17.7853 24C19.3516 24 20.7411 23.1663 21.4737 21.7768C22.2063 20.3874 22.1305 18.7958 21.2716 17.4821L18.3916 13.1621ZM13.1368 4.04211C13.1368 1.81895 11.6716 0 9.85263 0C8.03368 0 6.56842 1.81895 6.56842 4.04211C6.56842 6.26526 8.03368 8.08421 9.85263 8.08421C11.6716 8.08421 13.1368 6.26526 13.1368 4.04211ZM3.28421 8.58947C1.46526 8.58947 0 10.4084 0 12.6316C0 14.8547 1.46526 16.6737 3.28421 16.6737C5.10316 16.6737 6.56842 14.8547 6.56842 12.6316C6.56842 10.4084 5.10316 8.58947 3.28421 8.58947ZM26.5263 8.58947C24.7074 8.58947 23.2421 10.4084 23.2421 12.6316C23.2421 14.8547 24.7074 16.6737 26.5263 16.6737C28.3453 16.6737 29.8105 14.8547 29.8105 12.6316C29.8105 10.4084 28.3453 8.58947 26.5263 8.58947ZM19.9579 0C18.1389 0 16.6737 1.81895 16.6737 4.04211C16.6737 6.26526 18.1389 8.08421 19.9579 8.08421C21.7768 8.08421 23.2421 6.26526 23.2421 4.04211C23.2421 1.81895 21.7768 0 19.9579 0Z" } ),
			);

		function IDXShortcodeListings(attributes) {
			var p				= [];
			Object.keys(attributes).forEach(function(key) {
				var attr	= attributes[key];

					// Skip internal attributes
					if (key == "content" ||
						key == "area_autocomplete_options" ||
						key == "overall_layout" ||  // This might also be causing issues
						key == "full_page_layout") {
						return;
						}

					// Handle the area autocomplete specially
					if (key == "area_autocomplete_val" && attr.length) {
						var areaKey = attributes.area_autocomplete_key || "subdivision";
						p.push(areaKey + "=\"" + attr + "\"");  // Output as key="val"
						return;
						}

					// Skip the key field (we handled it above)
					if (key == "area_autocomplete_key") {
						return;
						}

					if (typeof attr == "number")	{
						if (attr > 0) {
							p.push(key + "=\"" + attr + "\"");
							}
						}
					else
						{
						if (attr.length) {
							p.push(key + "=\"" + attr + "\"");
							}
						}

				});

			return "[rover_idx_listings " + p.join(" ") + "]";
			}

		registerBlockType(
			"rover-idx/listings",
			{
			title: "Rover IDX Listings",

			icon: {
				background: "#0000",
				foreground: "#fff",
				src: iconEl
				},

			category: "rover-idx-data-blocks",

			edit: function( props ) {

				// For vanilla JS blocks, we don't use useBlockProps hook
				var blockProps = {
					className: "rover-idx-shortcode-form-wrap"
				};

				var city_checkboxes				= [];
				var prop_type_checkboxes		= [];
				var search_panel_layout_options	= [];
				var price_options				= [];
				var bed_options					= [];
				var bath_options				= [];
				var listing_layout_options		= [];
				var listing_per_page_options	= [];
				var area_autocomplete_options	= [];

				if ( "pt" in window.ridx_block_data ) {
					Object.keys(window.ridx_block_data.pt).forEach(function(key) {
						var label	= window.ridx_block_data.pt[key];
						prop_type_checkboxes.push(
							el( CheckboxControl, {
								label: label,
								name: "prop_types",
								value: key,
								onChange: function( val ) {
									props.attributes.prop_types		= ridx.el_join("input[name=prop_types]");
									onContentRefresh();
									}
								})
							);
						});
					}

				if ( "cities" in window.ridx_block_data ) {
					Object.keys(window.ridx_block_data.cities).forEach(function(key) {
						var label	= window.ridx_block_data.cities[key];
						city_checkboxes.push(
							el( CheckboxControl, {
								label: label,
								name: "cities",
								value: label,
								onChange: function( val ) {
									props.attributes.cities			= ridx.el_join("input[name=cities]");
									onContentRefresh();
									}
								})
							);
						});
					}

				if ( "search_panel_layouts" in window.ridx_block_data ) {
					Object.keys(window.ridx_block_data.search_panel_layouts).forEach(function(key) {
						var label	= window.ridx_block_data.search_panel_layouts[key];
						search_panel_layout_options.push({
								label: label,
								value: label,
								}
							);
						});
					}

				for (let z = 0; z < 64; z++)
					{
					listing_per_page_options.push({
							label: z,
							value: z,
							}
						);
					}

				if ( "listing_layouts" in window.ridx_block_data ) {
					Object.keys(window.ridx_block_data.listing_layouts).forEach(function(key) {
						var label	= window.ridx_block_data.listing_layouts[key];
						listing_layout_options.push({
								label: label,
								value: label,
								}
							);
						});
					}

				price_options.push({label: "No Preference", value: 0});
				[
				50000,100000,150000,200000,250000,300000,350000,400000,450000,500000,600000,700000,800000,900000,
				1000000,1250000,1500000,2000000,2500000,3000000,4000000,5000000,6000000,7000000,8000000,9000000,10000000,
				15000000,20000000,25000000,30000000,35000000,40000000
				].forEach(function(val) {
					price_options.push({
							label: formatNumber(val),
							value: val,
							}
						);
					});

				bed_options.push({label: "No Preference", value: 0});
				[
				1,2,3,4,5,6,7,8,9,10
				].forEach(function(val) {
					bed_options.push({
							label: val,
							value: val,
							}
						);
					});

				bath_options.push({label: "No Preference", value: 0});
				[
				1,2,3,4,5,6,7,8,9,10
				].forEach(function(val) {
					bath_options.push({
							label: val,
							value: val,
							}
						);
					});

				function onChangeFullPageComponents() {

					var sfw				= document.querySelector(".rover-idx-shortcode-form-wrap");
					if (sfw) {
						sfw.classList.remove("full","search","grid","map");
						}

					onContentRefresh();
					}

				function onContentRefresh() {

					if ("attributes" in props) {

						function getPreviewElement() {
							// Try in current document first
							var el = document.querySelector(".rover-idx-shortcode-form-wrap");
							if (el) return el;

							// Try in iframes (WordPress.com block editor)
							var iframes = document.querySelectorAll('iframe');
							for (var i = 0; i < iframes.length; i++) {
								try {
									var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow.document;
									el = iframeDoc.querySelector(".rover-idx-shortcode-form-wrap");
									if (el) return el;
								} catch(e) {
									// Cross-origin iframe, skip
									console.log('Cannot access iframe:', e);
								}
							}
							return null;
						}


						// Check if we have the necessary dependencies for live preview
						if (typeof window.ridx_security !== 'undefined' &&
							typeof ajaxurl !== 'undefined' &&
							typeof ridx !== 'undefined') {

							var shortcode_data = {
								action: "rover_idx_block_refresh",
								security: window.ridx_security,
								roveridx_debug: 1,
								...props.attributes
							};

							fetch(ajaxurl, {
								method: "POST",
								body: new URLSearchParams(shortcode_data),
								credentials: "same-origin"
							})
							.then(function(response) {
								if (response.ok) {
									return response.clone().text().then(function(text) {

										try {
											var data = JSON.parse(text);
											return data;
										} catch(e) {
											console.error('JSON parse error:', e);
											console.error('Failed to parse:', text);
											throw new Error('Invalid JSON response');
										}
									});
								}
								throw new Error('Network response was not ok');
							})
							.then(function(data) {
								if (data && data.html) {

									var previewElement = getPreviewElement();
									if (previewElement) {
										previewElement.innerHTML = data.html;

										// Copy styles into the iframe
										var iframeDoc = previewElement.ownerDocument;
										if (iframeDoc !== document) {
											// We're in an iframe, copy styles

											// Copy all <style> elements with class starting with "idx-"
											var idxStyles = document.querySelectorAll('style[class^="idx-"]');
											idxStyles.forEach(function(styleElement) {
												// Check if this style is already in the iframe
												var className = styleElement.className;
												var existingStyle = iframeDoc.querySelector('style.' + className);

												if (!existingStyle) {
													var clone = styleElement.cloneNode(true);
													iframeDoc.head.appendChild(clone);
													}
												});

											// Also copy any <link> stylesheets with href containing "rover-idx"
											var roverLinks = document.querySelectorAll('link[rel="stylesheet"][href*="rover-idx"]');
											roverLinks.forEach(function(linkElement) {
												var existingLink = iframeDoc.querySelector('link[href="' + linkElement.href + '"]');

												if (!existingLink) {
													var clone = linkElement.cloneNode(true);
													iframeDoc.head.appendChild(clone);
													}
												});
											}
										}
									else {
										console.error('Could not find .rover-idx-shortcode-form-wrap element');
										}


									if (typeof ridx.load_js === 'function') {
										ridx.load_js(["rover_ui_search.js"], function(){
											if (typeof ridx.load_js_on_demand === 'function') {
												ridx.load_js_on_demand("after");
											}
										});
									}
								}
								else
									{
									console.error('No HTML in response data');
									}
							})
							.catch(function(error) {
								console.log('Preview refresh failed:', error);
								// Fallback to showing shortcode
								var previewElement = document.querySelector(".rover-idx-shortcode-form-wrap");
								if (previewElement) {
									previewElement.innerHTML = '<div style="padding: 20px; background: #f0f0f0; border: 1px dashed #ccc; text-align: center;">' +
										'<strong>Rover IDX Listings Preview</strong><br>' +
										'<code>' + IDXShortcodeListings(props.attributes) + '</code><br>' +
										'<small>Live preview will be available on the frontend</small>' +
										'</div>';
								}
							});
						} else {
							// Show a better preview when AJAX dependencies aren't available
							var previewElement = document.querySelector(".rover-idx-shortcode-form-wrap");
							if (previewElement) {
								previewElement.innerHTML = '<div style="padding: 20px; background: #f0f0f0; border: 1px dashed #ccc; text-align: center;">' +
									'<strong>Rover IDX Listings Preview</strong><br>' +
									'<code>' + IDXShortcodeListings(props.attributes) + '</code><br>' +
									'<small>Live preview will be available on the frontend</small>' +
									'</div>';
							}
						}
					}
				}


				function onAreaAutocompleteRefresh(searchTerm, props) {
					ridx.request(
							"typeahead/listing_block_autocomplete.php",
							{
							cities:		props.attributes.cities,
							prop_types:	props.attributes.prop_types,
							q:			searchTerm,
							msg:		false
							},
							function(data) {
								if (data && data.areas) {
									// Update the ComboboxControl options
									var options = data.areas.map(function(area) {
										return {
											label: area.name,
											value: JSON.stringify({
												key: area.key,  // development, subdivision, community
												val: area.name
											})
										};
									});

								// Force re-render by updating attributes

								props.setAttributes({ area_autocomplete_options: options });
								}
							}
						);

				}


				// Initialize preview on block load
				setTimeout(() => {
					onContentRefresh();
				}, 100);

				return (

						el( Fragment, blockProps,
							el( InspectorControls, {},
								el(
									PanelBody,
									{ title: "Display these elements", initialOpen: true },
									el( PanelRow, {},
										el( RadioControl,
											{
											name: "format",
											selected: props.attributes.overall_layout,
											options : [
												{ label: "Search + Grid", value: "search-grid" },
												{ label: "Search + Map", value: "search-map" },
												{ label: "Map + Search + Grid", value: "full" },
												{ label: "Grid", value: "grid" },
												{ label: "Map + Grid", value: "map_and_listings" },
												{ label: "Map", value: "map" },
												{ label: "Carousel", value: "carousel" },
												],
											onChange: function( content ) {
												props.attributes.overall_layout				= content;

												if (content === "search-grid") {
													props.attributes.format					= "full";
													props.attributes.full_page_layout		= "top";
													}
												else if (content === "search-map") {
													props.attributes.format					= "full";
													props.attributes.full_page_layout		= "search-map";
													}
												else {
													props.attributes.format					= content;
													}
												onContentRefresh();
												},
											}
										)
									)
								),
								el(
									PanelBody,
									{ title: "Filters", initialOpen: false },

									el(
										"p",
										{ className: "panel-intro" },
										"Any combination of filters can be used to further filter the displayed listings"
									),
									el(
										PanelBody,
										{ title: "Cities", initialOpen: false },
										city_checkboxes
									),
									el(
										PanelBody,
										{ title: "Property Types", initialOpen: false },
										prop_type_checkboxes
									),
									el(
										PanelBody,
										{ title: "Price", initialOpen: false },
										el( SelectControl,
											{
												label: 'Min Price',
												options : price_options,
												value: props.attributes.min_price,
												onChange: function( v ) {
													props.attributes.min_price		= v;
													onContentRefresh();
												},
											},
										),
										el( SelectControl,
											{
												label: 'Max Price',
												options : price_options,
												value: props.attributes.max_price,
												onChange: function( v ) {
													props.attributes.max_price		= v;
													onContentRefresh();
												},
											},
										),
									),

									el(
										PanelBody,
										{ title: "Bedrooms", initialOpen: false },
										el( SelectControl,
											{
												label: 'Min Beds',
												options : bed_options,
												value: props.attributes.min_beds,
												onChange: function( v ) {
													props.attributes.min_beds		= v;
													onContentRefresh();
												},
											},
										),
									),

									el(
										PanelBody,
										{ title: "Bathrooms", initialOpen: false },
										el( SelectControl,
											{
												label: 'Min Baths',
												options : bath_options,
												value: props.attributes.min_baths,
												onChange: function( v ) {
													props.attributes.min_baths		= v;
													onContentRefresh();
												},
											},
										),
									),

									el(
										PanelBody,
										{ title: "Subdivision/Community", initialOpen: false },
										el( ComboboxControl,
											{
												label: 'Search Subdivision/Community',
												value: props.attributes.area_autocomplete,
												options: props.attributes.area_autocomplete_options,
												onChange: function( value ) {
													try {
														var parsed = JSON.parse(value);
														props.setAttributes({
															area_autocomplete_key: parsed.key,  //	Store key
															area_autocomplete_val: parsed.val   //	Store val
														});
														onContentRefresh();
													} catch(e) {
														// Fallback if value isn't JSON
														props.setAttributes({
															area_autocomplete_val: value,
															area_autocomplete_key: ""
														});
														onContentRefresh();
													}
												},
												onFilterValueChange: function( inputValue ) {
													// This fires as the user types
													if (inputValue.length >= 2) {
														onAreaAutocompleteRefresh(inputValue, props);
													}
												},
												help: "Type at least 2 characters to search"
											},
										)
									),

									el(
										PanelBody,
										{ title: "Display Only Our Listings", initialOpen: false },
										el( RadioControl,
											{
											name: "listing_office_mlsid",
											selected: props.attributes.listing_office_mlsid,
											options : [
												{ label: "No Preference", value: "" },
												{ label: "Only Our Listings", value: "*" },
												],
											help: "Only our listings will be displayed.",
											onChange: function( content ) {
												if (content !== "") {
													props.attributes.listing_office_mlsid	= content;
													}
												onContentRefresh();
												},
											})
										),

									el(
										PanelBody,
										{ title: "Prioritize Our Listings", initialOpen: false },
										el( RadioControl,
											{
											name: "prioritize_office_listings",
											selected: props.attributes.prioritize_office_listings,
											options : [
												{ label: "No Preference", value: "" },
												{ label: "Prioritize Our Listings", value: "true" },
												],
											help: "Our listings will appears at top of listings displayed, regardless of sort order",
											onChange: function( content ) {
												if (content !== "") {
													props.attributes.prioritize_office_listings	= content;
													}
												onContentRefresh();
												},
											})
										),

									el(
										PanelBody,
										{ title: "Display Only New Listings", initialOpen: false },
										el( RadioControl,
											{
											name: "listing_date",
											selected: props.attributes.listing_date,
											options : [
												{ label: "No Preference", value: "" },
												{ label: "7 days", value: "7days" },
												{ label: "14 days", value: "14days" },
												{ label: "30 days", value: "30days" },
												],
											help: "Only new listings will be displayed.",
											onChange: function( content ) {
												if (content !== "") {
													props.attributes.listing_date			= content;
													}
												onContentRefresh();
												},
											})
										),

									el(
										PanelBody,
										{ title: "Status", initialOpen: false },
										el( RadioControl,
											{
											name: "status",
											selected: props.attributes.status,
											options : [
												{ label: "Active", value: "active" },
												{ label: "Active + Pending", value: "active,pending" },
												{ label: "Active + Pending + Sold", value: "active,pending,sold" },
												{ label: "Active + Sold", value: "active,sold" },
												{ label: "Sold", value: "sold" },
												],
											help: "If not specified, Active listings are displayed.",
											onChange: function( content ) {
												if (content !== "") {
													props.attributes.status	= content;
													}
												onContentRefresh();
												},
											})
										),
								),
							el(
								PanelBody,
								{ title: "Sort Order", initialOpen: false },
								el( RadioControl,
									{
									name: "sort_by",
									selected: props.attributes.sort_by,
									options : [
										{ label: "No Preference", value: "" },
										{ label: "Price - Highest to Lowest", value: "SortPrice" },
										{ label: "Price - Lowest to Highest", value: "SortPriceASC" },
										{ label: "Sort by Newest", value: "SortNewest" },

										{ label: "Sort by Acres", value: "SortAcres" },
										{ label: "Sort by Bedrooms", value: "SortBedrooms" },
										{ label: "Sort by City", value: "SortCity" },
										{ label: "Sort by Price per SqFt", value: "SortPricePerSqFt" },
										{ label: "Sort by SqFt", value: "SortSqFt" },
										],
									onChange: function( content ) {
										if (content !== "") {
											props.attributes.sort_by			= content;
											}
										onContentRefresh();
										},
									})
								),
								el(
									PanelBody,
									{ title: "Layouts", initialOpen: false },

									el( PanelRow, {},
										el( SelectControl,
											{
												label: 'Search Panel Layout',
												options : search_panel_layout_options,
												value: props.attributes.search_panel_layout,
												onChange: function( content ) {
													props.attributes.search_panel_layout	= content;
													onContentRefresh();
												},
											},
										),
									),

									el( PanelRow, {},
										el( SelectControl,
											{
												label: 'Listing Layout',
												options : listing_layout_options,
												value: props.attributes.listing_layout,
												onChange: function( content ) {
													props.attributes.listing_layout		= content;
													onContentRefresh();
												},
											},
										),
									),

									el( PanelRow, {},
										el( SelectControl,
											{
												label: 'Listings per Page',
												options : listing_per_page_options,
												value: props.attributes.listings_per_page,
												help: "Listings per Page directly affects page load speed",
												onChange: function( content ) {
													props.attributes.listings_per_page	= content;
													onContentRefresh();
												},
											},
										),
									),

								)
							),

							el( "div", blockProps, IDXShortcodeListings(props.attributes) )

						)
					);
				},

			save: function( { attributes } ) {

				//	For vanilla JS blocks, we don't use useBlockProps.save() hook

				//	Match the structure from edit - need a container element
/*
				return el( "div", { className: "rover-idx-shortcode-form-wrap" },
					IDXShortcodeListings(attributes)
					);
*/
				return null;		//	rendering happens server-side
				}
			});
		}

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


Number.prototype.toThousands = function(d){
	return this.toFixed(d).replace(/(\d)(?=(\d{3})+\b)/g,'$1,');
	};

function formatNumber(n, c) {
	var prec = 0;
	var factor = '';
	n = parseFloat(n);
	c = (!!c) ? c : '';
	if (c === false)
		{return n;}

	if (n >= 1000000)	{
		n = (n / 1000000);
		prec = 2;
		factor = "M";
		}

	if (n >= 40000)	{
		n = (n / 1000);
		factor = "K";
		}

	if (n > 0)			{
		n = n.toThousands(prec);
		}

	return (c + n.toString() + factor);
	}