// CSS用のサニタイズ関数（基本的な危険な文字列のみを除去）
function sanitizeCSS(css) {
	if (typeof css !== 'string') {
		return '';
	}
	
	// 危険なJavaScript関連のコードを除去
	return css
		.replace(/<script[^>]*>.*?<\/script>/gi, '') // script タグを除去
		.replace(/javascript:/gi, '') // javascript: プロトコルを除去
		.replace(/on\w+\s*=/gi, '') // onload, onclick などのイベントハンドラを除去
		.replace(/expression\s*\(/gi, '') // IE expression() を除去
		.replace(/@import[^;]*;?/gi, '') // @import を除去（外部ファイル読み込み防止）
		.replace(/url\s*\(\s*['"]?javascript:/gi, 'url('); // URL内のjavascriptを除去
}

// 安全なCSS設定関数
function setSafeCSS(element, cssContent) {
	if (!element) return;
	
	// CSS内容をサニタイズ
	var safeCss = sanitizeCSS(cssContent);
	
	// style要素を作成して設定
	var styleElement = document.createElement('style');
	styleElement.type = 'text/css';
	
	// textContentを使用してCSSを設定（HTMLエスケープを回避）
	if (styleElement.styleSheet) {
		// IE対応
		styleElement.styleSheet.cssText = safeCss;
	} else {
		// 標準ブラウザ
		styleElement.textContent = safeCss;
	}
	
	// 既存のstyle要素をクリアして新しいものを追加
	element.innerHTML = '';
	element.appendChild(styleElement);
}

// XSS対策用のユーティリティ関数
function escapeHtml(unsafe) {
	if (typeof unsafe !== 'string') {
		return '';
	}
	return unsafe
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;")
		.replace(/"/g, "&quot;")
		.replace(/'/g, "&#039;");
}

// 安全なテキスト設定関数
function setTextContentSafely(element, text) {
	if (!element) return;
	
	// textContentを使用してXSSを防止
	if (typeof text === 'string' && text.trim() !== '') {
		element.textContent = text;
	} else {
		element.textContent = '見出し';
	}
}

// 色の形式が有効かチェックする関数
function isValidColor(color) {
	if (typeof color !== 'string') return false;
	
	// HEX形式（#RGB, #RRGGBB）
	if (/^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/.test(color)) {
		return true;
	}
	
	// RGB/RGBA形式
	if (/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[01]?\.?\d*)?\s*\)$/.test(color)) {
		return true;
	}
	
	// CSS色名（基本的なもののみ）
	const validColorNames = [
		'transparent', 'black', 'white', 'red', 'green', 'blue', 'yellow', 
		'orange', 'purple', 'pink', 'gray', 'grey', 'brown', 'cyan', 'magenta'
	];
	
	return validColorNames.includes(color.toLowerCase());
}

document.addEventListener('DOMContentLoaded', function(){
	var block_styles = document.querySelectorAll('.nishiki-pro-heading-style-wrap li');

	if( !! block_styles ){

		// Codemirror を初期設定
		let editor = codemirror_init();

		// 入力内容をプレビュー
		if( !! editor ){
			preview( editor );

			document.body.addEventListener('input',function(e){
				preview( editor );
			});
		}

	}

	function codemirror_init(){
		var code_textarea = document.getElementById('wp-nishiki-codemirror');

		if( !! code_textarea ){
			//console.log(code_textarea);

			// エディターを Codemirror に置き換え
			return wp.codeEditor.initialize( code_textarea, cm_settings );
		}
	}

	function preview( editor ){
		//ajaxで送信するデータを作成
		let update_data = {};

		// 更新用ボタン
		let update_button = document.getElementById( 'nishiki-pro-update-button' );

		// 追加 CSS
		var update_code = editor.codemirror.getValue();
		update_data.code = update_code;

		//カスタムCSS - 安全なCSS設定を使用
		var code_preview = document.body.querySelector('.custom-style');
		if (code_preview) {
			setSafeCSS(code_preview, update_code);
		}

		// カスタム CSS をリアルタイムで反映
		document.body.addEventListener('keyup',function(){
			headingCodePreview( code_preview, editor, update_data, update_button );
		});

		//名前
		var block_style_name_element = document.body.querySelector('.block-style-name');
		var block_style_name = block_style_name_element ? block_style_name_element.value : '';

		//ラベル
		var block_style_label_element = document.body.querySelector('.block-style-label');
		var block_style_label = block_style_label_element ? block_style_label_element.value : '';

		// JSON データ作成 - サニタイズ
		update_data.name = escapeHtml(block_style_name);
		update_data.label = escapeHtml(block_style_label);

		//見出しのデータh1-h6 まで全部設定する
		for ( let i = 1; i <= 6; i++ ) {
			update_heading = document.getElementById('heading-h' + i ).children[0];

			// class付与 - 安全なクラス名設定
			var safeClassName = 'is-style-' + escapeHtml(block_style_name).replace(/[^a-zA-Z0-9_-]/g, '');
			update_heading.setAttribute('class', safeClassName);

			// プレビューテキスト入力反映 - XSS対策（innerHTML → textContent）
			let livepreview_text_element = document.body.querySelector('.heading-livepreview-text');
			let livepreview_text = livepreview_text_element ? livepreview_text_element.value : '見出し';
			setTextContentSafely(update_heading, livepreview_text);

			// font-size - 数値検証
			let input_font_size_element = document.getElementById('heading-h' + i + '-font-size');
			let input_font_size = input_font_size_element ? parseFloat(input_font_size_element.value) || '' : '';

			let input_font_size_unit_element = document.getElementById('heading-h' + i + '-font-unit');
			let input_font_size_unit = input_font_size_unit_element ? input_font_size_unit_element.value : 'rem';

			// 許可された単位のホワイトリスト
			const allowedUnits = ['px', 'em', 'rem', '%', 'vw', 'vh'];
			if (!allowedUnits.includes(input_font_size_unit)) {
				input_font_size_unit = 'rem';
			}

			if (input_font_size && !isNaN(input_font_size)) {
				update_heading.style.fontSize = input_font_size + input_font_size_unit;
			}

			// font-color - 色の検証
			let input_font_color_element = document.getElementById('heading-h' + i + '-font-color');
			let input_font_color = input_font_color_element ? input_font_color_element.value : '';
			
			// 基本的な色の形式チェック（hex, rgb, rgba, 色名）
			if (input_font_color && isValidColor(input_font_color)) {
				update_heading.style.color = input_font_color;
			}

			// font-background-color - 色の検証
			let input_background_color_element = document.getElementById('heading-h' + i + '-font-background-color');
			let input_background_color = input_background_color_element ? input_background_color_element.value : '';
			
			if (input_background_color && isValidColor(input_background_color)) {
				update_heading.style.backgroundColor = input_background_color;
			}

			// line-height - 数値検証
			let input_line_height_element = document.getElementById('heading-h' + i + '-font-line-height');
			let input_line_height = input_line_height_element ? parseFloat(input_line_height_element.value) || '' : '';
			
			if (input_line_height && !isNaN(input_line_height) && input_line_height > 0) {
				update_heading.style.lineHeight = input_line_height;
			} else {
				update_heading.style.lineHeight = '';
			}

			// margin - 安全な値設定
			setMarginPaddingStyles(update_heading, 'margin', i);

			// padding - 安全な値設定
			setMarginPaddingStyles(update_heading, 'padding', i);

			// border - 安全な値設定
			setBorderStyles(update_heading, i);

			// カラーピッカーのイベントハンドラー（既存のjQueryコード）
			setupColorPickers(i, update_heading, update_data, update_button);

			// JSON 追加 - 安全なデータ作成
			update_data['h' + i] = createSafeHeadingData(i);
		}

		// 反映確認
//		console.log(update_heading);
//		console.log(update_data);

		//ぜんぶまとめてJSONにする
		update_button.setAttribute("data-heading-code", JSON.stringify( update_data ) );

	}

	// マージン・パディングスタイルの安全な設定
	function setMarginPaddingStyles(element, property, headingNum) {
		const positions = ['top', 'right', 'bottom', 'left'];
		const allowedUnits = ['px', 'em', 'rem', '%'];
		
		positions.forEach(function(position) {
			let valueElement = document.getElementById('heading-h' + headingNum + '-' + property + '-' + position);
			let unitElement = document.getElementById('heading-h' + headingNum + '-' + property + '-' + position + '-unit');
			
			if (!valueElement || !unitElement) return;
			
			let value = parseFloat(valueElement.value);
			let unit = unitElement.value;
			
			if (!allowedUnits.includes(unit)) {
				unit = 'rem';
			}
			
			if (!isNaN(value) && value !== '') {
				element.style[property + position.charAt(0).toUpperCase() + position.slice(1)] = value + unit;
			} else {
				element.style[property + position.charAt(0).toUpperCase() + position.slice(1)] = '';
			}
		});
	}

	// ボーダースタイルの安全な設定
	function setBorderStyles(element, headingNum) {
		const positions = ['top', 'right', 'bottom', 'left'];
		const allowedUnits = ['px', 'em', 'rem'];
		const allowedStyles = ['none', 'solid', 'dashed', 'dotted', 'double', 'groove', 'ridge', 'inset', 'outset'];
		
		positions.forEach(function(position) {
			let widthElement = document.getElementById('heading-h' + headingNum + '-border-' + position);
			let unitElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-unit');
			let styleElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-style');
			let colorElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-color');
			
			if (!widthElement || !unitElement || !styleElement || !colorElement) return;
			
			let width = parseFloat(widthElement.value);
			let unit = unitElement.value;
			let style = styleElement.value;
			let color = colorElement.value;
			
			// 値の検証
			if (!allowedUnits.includes(unit)) unit = 'px';
			if (!allowedStyles.includes(style)) style = 'solid';
			
			if (!isNaN(width) && width !== '') {
				let borderProperty = 'border' + position.charAt(0).toUpperCase() + position.slice(1);
				element.style[borderProperty + 'Width'] = width + unit;
				element.style[borderProperty + 'Style'] = style;
				
				if (color && isValidColor(color)) {
					element.style[borderProperty + 'Color'] = color;
				}
			} else {
				let borderProperty = 'border' + position.charAt(0).toUpperCase() + position.slice(1);
				element.style[borderProperty + 'Width'] = '';
				element.style[borderProperty + 'Style'] = '';
				element.style[borderProperty + 'Color'] = '';
			}
		});
	}

	// 安全な見出しデータ作成
	function createSafeHeadingData(headingNum) {
		// 各要素の安全な取得と検証
		let fontSizeElement = document.getElementById('heading-h' + headingNum + '-font-size');
		let fontUnitElement = document.getElementById('heading-h' + headingNum + '-font-unit');
		let fontColorElement = document.getElementById('heading-h' + headingNum + '-font-color');
		let backgroundColorElement = document.getElementById('heading-h' + headingNum + '-font-background-color');
		let lineHeightElement = document.getElementById('heading-h' + headingNum + '-font-line-height');
		
		return {
			font: {
				size: fontSizeElement ? parseFloat(fontSizeElement.value) || '' : '',
				unit: fontUnitElement ? fontUnitElement.value : 'rem',
				color: fontColorElement && isValidColor(fontColorElement.value) ? fontColorElement.value : '',
				backgroundColor: backgroundColorElement && isValidColor(backgroundColorElement.value) ? backgroundColorElement.value : '',
				lineHeight: lineHeightElement ? parseFloat(lineHeightElement.value) || '' : '',
			},
			margin: createSafeSpacingData('margin', headingNum),
			padding: createSafeSpacingData('padding', headingNum),
			border: createSafeBorderData(headingNum),
		};
	}

	// 安全なスペーシングデータ作成
	function createSafeSpacingData(property, headingNum) {
		const positions = ['top', 'right', 'bottom', 'left'];
		const result = {};
		
		positions.forEach(function(position) {
			let valueElement = document.getElementById('heading-h' + headingNum + '-' + property + '-' + position);
			let unitElement = document.getElementById('heading-h' + headingNum + '-' + property + '-' + position + '-unit');
			
			let value = valueElement ? parseFloat(valueElement.value) || '' : '';
			let unit = unitElement ? unitElement.value : 'rem';
			
			result[position] = [value, unit];
		});
		
		return result;
	}

	// 安全なボーダーデータ作成
	function createSafeBorderData(headingNum) {
		const positions = ['top', 'right', 'bottom', 'left'];
		const result = {};
		
		positions.forEach(function(position) {
			let widthElement = document.getElementById('heading-h' + headingNum + '-border-' + position);
			let unitElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-unit');
			let styleElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-style');
			let colorElement = document.getElementById('heading-h' + headingNum + '-border-' + position + '-color');
			
			let width = widthElement ? parseFloat(widthElement.value) || '' : '';
			let unit = unitElement ? unitElement.value : 'px';
			let style = styleElement ? styleElement.value : 'solid';
			let color = colorElement && isValidColor(colorElement.value) ? colorElement.value : '';
			
			result[position] = [width, unit, style, color];
		});
		
		return result;
	}

	// カラーピッカーのセットアップ（XSS対策強化版）
	function setupColorPickers(headingNum, element, updateData, updateButton) {
		if (!headingNum || !element || !updateData || !updateButton) {
			return;
		}

		// font-color
		jQuery('#heading-h' + headingNum + '-font-color').wpColorPicker({
			change: function (event, ui) {
				if (!ui || !ui.color) return;
				
				var colorValue = ui.color.toString();
				if (!isValidColor(colorValue)) return;
				
				// 見出し要素を安全に取得
				var changeColorElement = document.getElementById('heading-h' + headingNum);
				if (changeColorElement && changeColorElement.children[0]) {
					changeColorElement.children[0].style.color = colorValue;
				}
				
				// updateDataの安全な更新
				if (updateData['h' + headingNum] && updateData['h' + headingNum].font) {
					updateData['h' + headingNum].font.color = colorValue;
					updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
				}
			},
			clear: function (event) {
				// 見出し要素を安全に取得
				var changeColorElement = document.getElementById('heading-h' + headingNum);
				if (changeColorElement && changeColorElement.children[0]) {
					changeColorElement.children[0].style.color = '';
				}
				
				// updateDataの安全な更新
				if (updateData['h' + headingNum] && updateData['h' + headingNum].font) {
					updateData['h' + headingNum].font.color = '';
					updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
				}
			}
		});

		// font-background-color
		jQuery('#heading-h' + headingNum + '-font-background-color').wpColorPicker({
			change: function (event, ui) {
				if (!ui || !ui.color) return;
				
				var colorValue = ui.color.toString();
				if (!isValidColor(colorValue)) return;
				
				// 見出し要素を安全に取得
				var changeColorElement = document.getElementById('heading-h' + headingNum);
				if (changeColorElement && changeColorElement.children[0]) {
					changeColorElement.children[0].style.backgroundColor = colorValue;
				}
				
				// 入力要素の値も更新
				var inputElement = jQuery(event.target).siblings('.wp-color-picker')[0];
				if (inputElement) {
					inputElement.value = colorValue;
					inputElement.setAttribute("data-bgcolor", colorValue);
				}
				
				// updateDataの安全な更新
				if (updateData['h' + headingNum] && updateData['h' + headingNum].font) {
					updateData['h' + headingNum].font.backgroundColor = colorValue;
					updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
				}
			},
			clear: function (event) {
				// 見出し要素を安全に取得
				var changeColorElement = document.getElementById('heading-h' + headingNum);
				if (changeColorElement && changeColorElement.children[0]) {
					changeColorElement.children[0].style.backgroundColor = '';
				}
				
				// updateDataの安全な更新
				if (updateData['h' + headingNum] && updateData['h' + headingNum].font) {
					updateData['h' + headingNum].font.backgroundColor = '';
					updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
				}
			}
		});

		// ボーダーカラーピッカー（4方向すべて）
		var borderPositions = ['top', 'right', 'bottom', 'left'];
		
		borderPositions.forEach(function(position) {
			var selectorId = '#heading-h' + headingNum + '-border-' + position + '-color';
			
			jQuery(selectorId).wpColorPicker({
				change: function (event, ui) {
					if (!ui || !ui.color) return;
					
					var colorValue = ui.color.toString();
					if (!isValidColor(colorValue)) return;
					
					// 見出し要素を安全に取得
					var changeColorElement = document.getElementById('heading-h' + headingNum);
					if (changeColorElement && changeColorElement.children[0]) {
						var targetElement = changeColorElement.children[0];
						
						// ボーダーカラーの適用
						switch(position) {
							case 'top':
								targetElement.style.borderTopColor = colorValue;
								break;
							case 'right':
								targetElement.style.borderRightColor = colorValue;
								break;
							case 'bottom':
								targetElement.style.borderBottomColor = colorValue;
								break;
							case 'left':
								targetElement.style.borderLeftColor = colorValue;
								break;
						}
					}
					
					// updateDataの安全な更新
					if (updateData['h' + headingNum] && 
						updateData['h' + headingNum].border && 
						updateData['h' + headingNum].border[position]) {
						updateData['h' + headingNum].border[position][3] = colorValue;
						updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
					}
				},
				clear: function (event) {
					// 見出し要素を安全に取得
					var changeColorElement = document.getElementById('heading-h' + headingNum);
					if (changeColorElement && changeColorElement.children[0]) {
						var targetElement = changeColorElement.children[0];
						
						// ボーダーカラーのクリア
						switch(position) {
							case 'top':
								targetElement.style.borderTopColor = '';
								break;
							case 'right':
								targetElement.style.borderRightColor = '';
								break;
							case 'bottom':
								targetElement.style.borderBottomColor = '';
								break;
							case 'left':
								targetElement.style.borderLeftColor = '';
								break;
						}
					}
					
					// updateDataの安全な更新
					if (updateData['h' + headingNum] && 
						updateData['h' + headingNum].border && 
						updateData['h' + headingNum].border[position]) {
						updateData['h' + headingNum].border[position][3] = '';
						updateButton.setAttribute("data-heading-code", JSON.stringify(updateData));
					}
				}
			});
		});
	}

	// コードプレビュー
	function headingCodePreview( code_preview, editor, update_data, update_button ){
		if (!code_preview || !editor || !update_data || !update_button) return;

		var update_code = editor.codemirror.getValue();
		//console.log(editor.codemirror.getValue());

		// CSSコードを安全に設定（エスケープしない）
		setSafeCSS(code_preview, update_code);

		update_data.code = update_code;

		update_button.setAttribute("data-heading-code", JSON.stringify( update_data ) );

	}

	// フォームの入力プレビュー（XSS対策強化版）
	function headingFormPreview( block_style, index ){
		//console.log(index);

		// 更新用ボタン
		var update_button = block_style.querySelector('.nishiki-pro-update-heading');

		var post_data = {};
		post_data.border = [];

		//h1-h6に付与するクラス（ラベル）
		var block_style_name = block_style.querySelector('.block-style-name').value;

		// h1-h6に入力した値をインラインstyleで出力
		for ( let i = 1; i <= 6; i++ ) {
			let heading_element = block_style.querySelector('h' + i);

			// class付与 - 安全なクラス名設定
			var safeClassName = 'is-style-' + escapeHtml(block_style_name).replace(/[^a-zA-Z0-9_-]/g, '');
			heading_element.setAttribute('class', safeClassName);

			// プレビューテキスト入力反映 - XSS対策（innerHTML → textContent）
			let livepreview_text_element = block_style.querySelector('.heading-livepreview-text-' + index);
			let livepreview_text = livepreview_text_element ? livepreview_text_element.value : '見出し';
			setTextContentSafely(heading_element, livepreview_text);

			// font-size
			let input_font_size = block_style.querySelector('.heading-h' + i + '-font-size').value;
			let input_font_size_unit = block_style.querySelector('.heading-h' + i + '-font-unit').value;

			heading_element.style.fontSize = input_font_size + input_font_size_unit;

			// font-color
			let input_font_color = block_style.querySelector('.heading-' + index + '-h' + i + '-font-color').value;
			if ( !! input_font_color ) {
				heading_element.style.color = input_font_color;
			}

			// background-color
			let input_background_color = block_style.querySelector('.heading-' + index + '-h' + i + '-font-background-color').value;
			if ( !! input_background_color ) {
				heading_element.style.backgroundColor = input_background_color;
			}

			// line-height
			let input_line_height = block_style.querySelector('.heading-h' + i + '-font-line-height').value;
			if ( !! input_line_height ) {
				heading_element.style.lineHeight = input_line_height;
			} else {
				heading_element.style.lineHeight = '';
			}

			// margin
			let input_margin_top = block_style.querySelector('.heading-h' + i + '-margin-top').value;
			let input_margin_top_unit = block_style.querySelector('.heading-h' + i + '-margin-top-unit').value;
			let input_margin_right = block_style.querySelector('.heading-h' + i + '-margin-right').value;
			let input_margin_right_unit = block_style.querySelector('.heading-h' + i + '-margin-right-unit').value;
			let input_margin_bottom = block_style.querySelector('.heading-h' + i + '-margin-bottom').value;
			let input_margin_bottom_unit = block_style.querySelector('.heading-h' + i + '-margin-bottom-unit').value;
			let input_margin_left = block_style.querySelector('.heading-h' + i + '-margin-left').value;
			let input_margin_left_unit = block_style.querySelector('.heading-h' + i + '-margin-left-unit').value;

			if( !! input_margin_top ){
				heading_element.style.marginTop = input_margin_top + input_margin_top_unit;
			} else {
				heading_element.style.marginTop = '';
			}

			if( !! input_margin_right ){
				heading_element.style.marginRight = input_margin_right + input_margin_right_unit;
			} else {
				heading_element.style.marginRight = '';
			}

			if( !! input_margin_bottom ){
				heading_element.style.marginBottom = input_margin_bottom + input_margin_bottom_unit;
			} else {
				heading_element.style.marginBottom = '';
			}

			if( !! input_margin_left ){
				heading_element.style.marginLeft = input_margin_left + input_margin_left_unit;
			} else {
				heading_element.style.marginLeft = '';
			}

			// padding
			let input_padding_top = block_style.querySelector('.heading-h' + i + '-padding-top').value;
			let input_padding_top_unit = block_style.querySelector('.heading-h' + i + '-padding-top-unit').value;
			let input_padding_right = block_style.querySelector('.heading-h' + i + '-padding-right').value;
			let input_padding_right_unit = block_style.querySelector('.heading-h' + i + '-padding-right-unit').value;
			let input_padding_bottom = block_style.querySelector('.heading-h' + i + '-padding-bottom').value;
			let input_padding_bottom_unit = block_style.querySelector('.heading-h' + i + '-padding-bottom-unit').value;
			let input_padding_left = block_style.querySelector('.heading-h' + i + '-padding-left').value;
			let input_padding_left_unit = block_style.querySelector('.heading-h' + i + '-padding-left-unit').value;

			if( !! input_padding_top ){
				heading_element.style.paddingTop = input_padding_top + input_padding_top_unit;
			} else {
				heading_element.style.paddingTop = '';
			}

			if( !! input_padding_right ){
				heading_element.style.paddingRight = input_padding_right + input_padding_right_unit;
			} else {
				heading_element.style.paddingRight = '';
			}

			if( !! input_padding_bottom ){
				heading_element.style.paddingBottom = input_padding_bottom + input_padding_bottom_unit;
			} else {
				heading_element.style.paddingBottom = '';
			}

			if( !! input_padding_left ){
				heading_element.style.paddingLeft = input_padding_left + input_padding_left_unit;
			} else {
				heading_element.style.paddingLeft = '';
			}

			// font-color
			jQuery('.heading-' + index + '-h' + i + '-font-color').wpColorPicker({
				change: function (event, ui) {
					var element = event.target;

					//変更したカラーをh1-h6に反映
					heading_element.style.color = ui.color.toString();
				},
				clear : function (event) {
					var element = jQuery(event.target).siblings('.wp-color-picker')[0];
					var color = '';

					heading_element.style.color = '';
				}
			});

			// font-background-color
			jQuery('.heading-' + index + '-h' + i + '-font-background-color').wpColorPicker({
				change: function (event, ui) {
					var element = event.target;

					//変更したカラーをh1-h6に反映
					heading_element.style.backgroundColor = ui.color.toString();
				},
				clear : function (event) {
					var element = jQuery(event.target).siblings('.wp-color-picker')[0];
					var color = '';

					heading_element.style.backgroundColor = '';
				}
			});

			// border
			let input_border_top = block_style.querySelector('.heading-h' + i + '-border-top').value;
			let input_border_top_unit = block_style.querySelector('.heading-h' + i + '-border-top-unit').value;
			let input_border_top_style = block_style.querySelector('.heading-h' + i + '-border-top-style').value;
			let input_border_top_color = block_style.querySelector('.heading-' + index + '-h' + i + '-border-top-color').value;

			let input_border_right = block_style.querySelector('.heading-h' + i + '-border-right').value;
			let input_border_right_unit = block_style.querySelector('.heading-h' + i + '-border-right-unit').value;
			let input_border_right_style = block_style.querySelector('.heading-h' + i + '-border-right-style').value;
			let input_border_right_color = block_style.querySelector('.heading-' + index + '-h' + i + '-border-right-color').value;

			let input_border_bottom = block_style.querySelector('.heading-h' + i + '-border-bottom').value;
			let input_border_bottom_unit = block_style.querySelector('.heading-h' + i + '-border-bottom-unit').value;
			let input_border_bottom_style = block_style.querySelector('.heading-h' + i + '-border-bottom-style').value;
			let input_border_bottom_color = block_style.querySelector('.heading-' + index + '-h' + i + '-border-bottom-color').value;

			let input_border_left = block_style.querySelector('.heading-h' + i + '-border-left').value;
			let input_border_left_unit = block_style.querySelector('.heading-h' + i + '-border-left-unit').value;
			let input_border_left_style = block_style.querySelector('.heading-h' + i + '-border-left-style').value;
			let input_border_left_color = block_style.querySelector('.heading-' + index + '-h' + i + '-border-left-color').value;

			if( !! input_border_top ){
				heading_element.style.borderTopWidth = input_border_top + input_border_top_unit;
				heading_element.style.borderTopStyle = input_border_top_style;
				heading_element.style.borderTopColor = input_border_top_color;
			} else {
				heading_element.style.borderTopWidth = '';
				heading_element.style.borderTopStyle = '';
				heading_element.style.borderTopColor = '';
			}

			if( !! input_border_right ){
				heading_element.style.borderRightWidth = input_border_right + input_border_right_unit;
				heading_element.style.borderRightStyle = input_border_right_style;
				heading_element.style.borderRightColor = input_border_right_color;
			} else {
				heading_element.style.borderRightWidth = '';
				heading_element.style.borderRightStyle = '';
				heading_element.style.borderRightColor = '';
			}

			if( !! input_border_bottom ){
				heading_element.style.borderBottomWidth = input_border_bottom + input_border_bottom_unit;
				heading_element.style.borderBottomStyle = input_border_bottom_style;
				heading_element.style.borderBottomColor = input_border_bottom_color;
			} else {
				heading_element.style.borderBottomWidth = '';
				heading_element.style.borderBottomStyle = '';
				heading_element.style.borderBottomColor = '';
			}

			if( !! input_border_left ){
				heading_element.style.borderLeftWidth = input_border_left + input_border_left_unit;
				heading_element.style.borderLeftStyle = input_border_left_style;
				heading_element.style.borderLeftColor = input_border_left_color;
			} else {
				heading_element.style.borderLeftWidth = '';
				heading_element.style.borderLeftStyle = '';
				heading_element.style.borderLeftColor = '';
			}

			let font_border_align_array = ['top', 'right', 'bottom', 'left'];

			font_border_align_array.forEach(function ( align, align_index ) {
				// font-border-color
				jQuery('.heading-' + index + '-h' + i + '-border-' + align + '-color').wpColorPicker({
					change: function ( event, ui ) {

						//変更したカラーをh1-h6に反映
						if (align === 'top') {
							heading_element.style.borderTopColor = ui.color.toString();
						}

						if (align === 'right') {
							heading_element.style.borderRightColor = ui.color.toString();
						}

						if (align === 'bottom') {
							heading_element.style.borderBottomColor = ui.color.toString();
						}

						if (align === 'left') {
							heading_element.style.borderLeftColor = ui.color.toString();
						}
					},
					clear : function (event) {
						var element = jQuery(event.target).siblings('.wp-color-picker')[0];

						if (align === 'top') {
							heading_element.style.borderTopColor = '';
						}

						if (align === 'right') {
							heading_element.style.borderRightColor = '';
						}

						if (align === 'bottom') {
							heading_element.style.borderBottomColor = '';
						}

						if (align === 'left') {
							heading_element.style.borderLeftColor = '';
						}

					}
				});

			});
		}
	}

	//タブコンテンツ
	const tabs = document.querySelectorAll('.heading-tabs');
	//const tab_contents = document.querySelectorAll( 'heading-tab-contents' );

	tabs.forEach( function ( tab, i ) {
		let tab_buttons = tab.querySelectorAll( 'button' );
		tab_buttons.forEach( function ( tab_button, tab_button_index ) {
			tab_button.addEventListener('click', function(e) {
				e.preventDefault();

				//全部のis-activeを削除
				tab_buttons.forEach( function ( tab_button, i ) {
					if( tab_button.classList.contains( 'is-active' ) ){
						tab_button.classList.remove('is-active');
					}
				});

				//クリックしたタブが何番目かを取得
				let index = [].slice.call(tab_buttons).indexOf(tab_button);
				//console.log( [].slice.call(tab_buttons).indexOf(tab_button) );

				//現在のタブにis-activeを追加
				tab_button.classList.add( 'is-active' );

				//タブコンテンツの全部のis-showを削除
				let tab_contents = this.parentNode.nextElementSibling.querySelectorAll( '.heading-wrap' );
				//console.log(tab_contents);

				tab_contents.forEach( function ( tab_content, i ) {
					if( tab_content.classList.contains( 'is-show' ) ){
						tab_content.classList.remove('is-show');
					}
				});

				//現在のコンテンツにis-showを追加
				tab_contents[index].classList.add( 'is-show' );

				//見出しプレビューの全てのis-selectedを削除
				let livepreview_heading = tab_button.parentNode.parentNode.nextElementSibling.querySelector( '.livepreview-heading' ).children;

				//foreachできるようにsliceする
				livepreview_heading = [].slice.call(livepreview_heading);

				livepreview_heading.forEach( function ( heading, i ) {
					if( heading.classList.contains( 'is-selected' ) ){
						heading.classList.remove('is-selected');
					}
				});

				//選択している見出しにis-selectedを追加
				livepreview_heading[tab_button_index].classList.add( 'is-selected' );

			}, false );
		});
	});

});