jQuery(function($){
	
	var ua = navigator.userAgent;
	if($(window).width() < 748  ||  ua.indexOf('iPhone') > 0 || ua.indexOf('Android') > 0 ) {
		
		$('#wp-extend-toolbar-window').css({'display':'none'});
	
	} else {
		
		var title       = $("title").text();
		var description = $("meta[name='description']").attr("content");
		var keyword     = $("meta[name='keywords']").attr("content");
		
		// XSS対策のため、text()メソッドを使用して出力
		$("#wp-extend-toolbar-window__title .value").text( title );
		$("#wp-extend-toolbar-window__desc .value").text( description );
		$("#wp-extend-toolbar-window__keyword .value").text( keyword );

	}
});

// Cookieの操作関数
function setCookie(name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		expires = "; expires=" + date.toUTCString();
	}
	document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// ウィンドウ
jQuery(document).ready(function($) {
	var $dragWindow = $('#wp-extend-toolbar-window');
	var $reopenBtn  = $('#wp-extend-toolbar-window__reopen');
	let $closeBtn   = $('#wp-extend-toolbar-window__close');

	// 右下リサイズハンドルの追加
	var $resizeHandle = $('<div id="wp-extend-toolbar-window__resize-handle"></div>');
	$dragWindow.append($resizeHandle);
	$dragWindow.css('position', 'fixed');
	$dragWindow.css('min-width', '120px');
	$dragWindow.css('min-height', '80px');

	// ドラッグ時にはleft/topだけ明示的にセットし、right/bottomを解除
	function setDragWindowPosition(left, top) {
		$dragWindow.css({
			left: left + "px",
			top: top + "px",
			right: '',
			bottom: ''
		});
	}

	// ウィンドウ位置・サイズの復元
	function restoreWindowPosition() {
		var pos = getCookie('wp_extend_toolbar_position');
		var size = getCookie('wp_extend_toolbar_size');
		if (pos) {
			try {
				var position = JSON.parse(pos);
				if (
					typeof position.left === "number" && 
					typeof position.top === "number"
				) {
					var left = position.left;
					var top = position.top;
					var maxLeft = $(window).width() - $dragWindow.outerWidth();
					var maxTop = $(window).height() - $dragWindow.outerHeight();
					if (left < 0) left = 0;
					if (top < 0) top = 0;
					if (left > maxLeft) left = maxLeft;
					if (top > maxTop) top = maxTop;
					setDragWindowPosition(left, top);
				}
			} catch(e) {}
		}
		if (size) {
			try {
				var s = JSON.parse(size);
				if (typeof s.width === "number" && typeof s.height === "number") {
					var newWidth = Math.max(s.width, 120);
					var newHeight = Math.max(s.height, 80);
					var posLeft = parseInt($dragWindow.css('left'), 10) || 0;
					var posTop = parseInt($dragWindow.css('top'), 10) || 0;
					var maxWidth = $(window).width() - posLeft;
					var maxHeight = $(window).height() - posTop;
					if (newWidth > maxWidth) newWidth = maxWidth;
					if (newHeight > maxHeight) newHeight = maxHeight;
					$dragWindow.css({ width: newWidth + "px", height: newHeight + "px" });
				}
			} catch(e) {}
		}
	}

	// Cookieを見て表示状態を決定
	var toolbarDisplay = getCookie('wp_extend_toolbar_display');
	if(toolbarDisplay === 'hidden') {
		$dragWindow.hide();
		$reopenBtn.show();
	} else {
		$dragWindow.show();
		$reopenBtn.hide();
		restoreWindowPosition();
	}

	$closeBtn.on('click', function() {
		$dragWindow.fadeOut(function(){
			$reopenBtn.fadeIn();
			setCookie('wp_extend_toolbar_display', 'hidden', 1);
		});
	});

	$reopenBtn.on('click', function() {
		$dragWindow.fadeIn(function(){
			setCookie('wp_extend_toolbar_display', 'visible', 1);
			restoreWindowPosition();
		});
		$reopenBtn.fadeOut();
	});

	// ドラッグ＆ドロップ機能
	var isDragging = false;
	var dragOffsetX, dragOffsetY;
	var dragStartWidth, dragStartHeight;

	$dragWindow.on('mousedown', function(e) {
		// 右クリックや閉じるボタンやリサイズハンドルは無視
		if ($(e.target).is('button,button *,a,a *,#wp-extend-toolbar-window__resize-handle')) return;
		
		// スクロールバーのクリックを除外
		// ウィンドウの内側の要素（.window-info-inner）の幅と比較
		var windowWidth = $dragWindow.width();
		var innerWidth = $dragWindow.find('.window-info-inner').width();
		var scrollbarWidth = windowWidth - innerWidth;
		var clickX = e.pageX - $dragWindow.offset().left;
		var clickY = e.pageY - $dragWindow.offset().top;
		
		// スクロールバー領域のクリックは無視
		if (clickX > windowWidth - scrollbarWidth || clickY > $dragWindow.height() - scrollbarWidth) {
			return;
		}
		
		isDragging = true;
		var offset = $dragWindow.offset();
		var currentLeft = parseInt($dragWindow.css('left'), 10);
		var currentTop = parseInt($dragWindow.css('top'), 10);
		var left = isNaN(currentLeft) ? offset.left : currentLeft;
		var top = isNaN(currentTop) ? offset.top : currentTop;
		
		// 移動開始時に現在のサイズを保持（outerではなくinnerサイズ）
		dragStartWidth = $dragWindow.width();
		dragStartHeight = $dragWindow.height();
		
		// 明示的にサイズを固定
		$dragWindow.css({
			width: dragStartWidth + 'px',
			height: dragStartHeight + 'px'
		});
		
		setDragWindowPosition(left, top);
		dragOffsetX = e.clientX - left;
		dragOffsetY = e.clientY - top;
		$dragWindow.css({ 'user-select': 'none' });
		e.preventDefault();
	});

	$(document).on('mousemove', function(e) {
		if (isDragging) {
			var left = e.clientX - dragOffsetX;
			var top = e.clientY - dragOffsetY;

			// 0 より小さくならないように制限
			if (left < 0) left = 0;
			if (top < 0) top = 0;

			// 画面外に出ないように制限（outerWidthで計算）
			var maxLeft = $(window).width() - $dragWindow.outerWidth();
			var maxTop = $(window).height() - $dragWindow.outerHeight();
			if (left > maxLeft) left = maxLeft;
			if (top > maxTop) top = maxTop;

			// 移動中もサイズを維持
			$dragWindow.css({
				left: left + "px",
				top: top + "px",
				right: '',
				bottom: '',
				width: dragStartWidth + 'px',
				height: dragStartHeight + 'px'
			});
		}
		if (isResizing) {
			var minWidth = 120;
			var minHeight = 80;
			var offset = $dragWindow.offset();
			var left = parseInt($dragWindow.css('left'), 10) || offset.left;
			var top = parseInt($dragWindow.css('top'), 10) || offset.top;
			var maxWidth = $(window).width() - left;
			var maxHeight = $(window).height() - top;
			var width = e.clientX - left;
			var height = e.clientY - top;
			if (width < minWidth) width = minWidth;
			if (height < minHeight) height = minHeight;
			if (width > maxWidth) width = maxWidth;
			if (height > maxHeight) height = maxHeight;
			$dragWindow.css({ width: width + 'px', height: height + 'px' });
		}
	});

	$(document).on('mouseup', function(e) {
		if (isDragging) {
			isDragging = false;
			$dragWindow.css({ 'user-select':'auto' });
			var left = parseInt($dragWindow.css('left'),10);
			var top = parseInt($dragWindow.css('top'),10);
			var pos = JSON.stringify({left:left, top:top});
			setCookie('wp_extend_toolbar_position', pos, 7);
		}
		if (isResizing) {
			isResizing = false;
			$dragWindow.css({ 'user-select':'auto' });
			var width = $dragWindow.outerWidth();
			var height = $dragWindow.outerHeight();
			var size = JSON.stringify({width: width, height: height});
			setCookie('wp_extend_toolbar_size', size, 7);
		}
	});

	// リサイズ機能
	var isResizing = false;
	var startX, startY, startWidth, startHeight;

	$resizeHandle.on('mousedown', function(e) {
		isResizing = true;
		startX = e.clientX;
		startY = e.clientY;
		startWidth = $dragWindow.outerWidth();
		startHeight = $dragWindow.outerHeight();
		$dragWindow.css({ 'user-select': 'none' });
		e.preventDefault();
		e.stopPropagation(); // ドラッグと重複しないように
	});

	// ウィンドウリサイズ時もはみ出し防止＋位置とサイズの修正
	$(window).on('resize', function() {
		restoreWindowPosition();
	});
});