// DOM要素の取得
const input = document.getElementById('image-input'); // 画像アップロード用のinput要素
const imageContainer = document.getElementById('image-container'); // 画像表示用のコンテナ
const heightInput = document.getElementById('height-input'); // 身長入力用のinput要素
const nameInput = document.getElementById('name-input'); // 名前入力用のinput要素

// 画像ラッパー（画像とそのラベルを含む要素）を作成する関数
const createImageWrapper = (file, height, name) => {
	const reader = new FileReader();
	reader.onload = e => {

	// 画像のラッパー、画像、身長を表示する要素を作成
	const wrapper = document.createElement('div');
	const img = document.createElement('img');
	const heightLabel = document.createElement('div');
	const nameLabel = document.createElement('div');

	img.src = e.target.result; // 画像を読み込んで表示

	// 身長ラベルの内容を設定
	heightLabel.textContent = `${height}㎝`;
	// 名前ラベルの内容を設定（名前が入力されていれば表示）
	if (name) {
		nameLabel.textContent = name;
	} else {
		nameLabel.style.display = 'none';
	}

	// スタイルを適用
	wrapper.classList.add('image-wrapper');
	heightLabel.classList.add('height-label');
	nameLabel.classList.add('name-label');
	wrapper.append(img, nameLabel, heightLabel);

	// スタイル設定
	img.style.height = `${height}px`;

	// 画像表示時にアニメーションを追加 (CSSで管理)
	imageContainer.appendChild(wrapper);

	// 画像表示の際、CSSで設定した「show」クラスを追加
	setTimeout(() => {
		wrapper.classList.add('show');
	}, 0);

	// 画像クリックでボタン表示
	wrapper.addEventListener('click', (e) => {
		e.stopPropagation(); // クリックイベントが親要素に伝播しないようにする

		// ボタンがすでに表示されている場合は非表示にし、新しく表示
		const existingButtons = document.getElementById('edit-buttons');
		if (existingButtons) {
		existingButtons.remove(); // すでに表示されているボタンを削除
	}

		const buttons = document.createElement('div');
		buttons.id = 'edit-buttons';
		buttons.style.position = 'fixed'; // 位置を固定
		buttons.style.top = '50%'; // 画面中央に配置
		buttons.style.left = '50%';
		buttons.style.transform = 'translate(-50%, -50%)'; // 中央揃え
		buttons.style.zIndex = '1001';
		buttons.style.display = 'flex';
		buttons.style.flexDirection = 'column'; // ボタンを縦に並べる
		buttons.style.alignItems = 'center';
		buttons.style.opacity = '0'; // 最初は非表示

		// 名前変更ボタン
		const nameButton = document.createElement('button');
		nameButton.textContent = '名前の変更';
		nameButton.classList.add('cute-button');
		nameButton.addEventListener('click', () => {
			const newName = prompt("新しい名前を入力してください", nameLabel.textContent);
			if (newName !== null) {
				nameLabel.textContent = newName.trim(); // 名前ラベルを更新

				// 名前が入力されていなければ非表示
				if (nameLabel.textContent === '') {
				nameLabel.style.display = 'none';
			} else {
				nameLabel.style.display = 'block';
			}
		}
	});

	// 身長変更ボタン
	const heightButton = document.createElement('button');
	heightButton.textContent = '身長の変更';
	heightButton.classList.add('cute-button');
	heightButton.addEventListener('click', () => {
	const newHeight = prompt("新しい身長を入力してください（1～300㎝）", height);
		if (newHeight && newHeight >= 1 && newHeight <= 300) {
			heightLabel.textContent = `${newHeight}㎝`; // 身長ラベルを更新
			img.style.height = `${newHeight}px`; // 画像の高さを変更
		} else {
			alert("身長は1～300㎝で入力してください。");
		}
	});

	// 画像削除ボタン
	const deleteButton = document.createElement('button');
	deleteButton.textContent = '画像の削除';
	deleteButton.classList.add('cute-button');
	deleteButton.addEventListener('click', () => {
 		// 削除時に「remove」クラスを追加してアニメーション
		wrapper.classList.add('remove');
		setTimeout(() => {
			wrapper.remove(); // 画像ラッパーを削除
			buttons.remove(); // ボタンを削除
		}, 500); // アニメーションが終わった後に削除
	});

	buttons.append(nameButton, heightButton, deleteButton);
	document.body.appendChild(buttons); // ボタンを画面中央に追加

	// 可愛いアニメーション！
	setTimeout(() => {
		buttons.style.transition = 'opacity 0.5s ease';
		buttons.style.opacity = '1'; // アニメーションで表示
		}, 0);
	});

	// 画像をドラッグして位置を入れ替えられるようにする
	wrapper.style.cursor = 'move';

	// ドラッグ＆ドロップを有効化（PCとスマホの両方対応）
	let isDragging = false;
	let startX, startY, offsetX = 0, offsetY = 0;


};

	reader.readAsDataURL(file); // 画像ファイルを読み込む
};

// 画像が選択されたときの処理
input.addEventListener('change', e => {
	const height = parseInt(heightInput.value);
	const name = nameInput.value.trim();

	// 身長が無効な場合、警告を表示
	if (isNaN(height) || height <= 0) {
		alert("身長（㎝）を正しく入力してください。");
	return;
	}

	// 身長が300㎝を超えた場合の警告
	if (height > 300) {
		alert("入力できる身長は300㎝までです。\n怪獣ですか？");
		return;
	}

	// 選択されたすべての画像ファイルに対して処理を行う
	[...e.target.files].forEach(file => createImageWrapper(file, height, name));
});

// 画像ラッパー以外をクリックした場合にボタンを非表示にする処理
document.addEventListener('click', (e) => {
	const buttons = document.getElementById('edit-buttons');
	if (!e.target.closest('.image-wrapper') && buttons) {
		buttons.style.transition = 'opacity 0.5s ease';
		buttons.style.opacity = '0';
		setTimeout(() => {
		buttons.remove();
		}, 500);
	}
});


// Sortableを使って画像コンテナを並び替え可能にする
document.addEventListener("DOMContentLoaded", () => {
	// 画像コンテナをSortable対象にする
	new Sortable(imageContainer, {
		handle: '.image-wrapper',
		animation: 1,
		onStart(evt) {
			// 並び替え開始時の処理 (オプション)
			console.log('Sorting started');
		},
		onEnd(evt) {
			// 並び替え終了時の処理 (オプション)
			console.log('Sorting ended');
		}
	});
});





// アリクイの画像を取得
const spaceImage = document.getElementById('space-image');

// 右上の画像クリック時の処理
spaceImage.addEventListener('click', () => {
	// メッセージのリスト
	const messages = [
		"おい！このおれ様に触るな！",
		"いてっ！やめろ！",
		"こらっ！なにすんだ！",
		"やめろ！舐めるぞ！",
		"今……何かしたか？",
		"やる気か？かかってこいよッ！",
		"宇宙の藻屑になりたいようだな……",
		"もっと優しく触れ！",
		"画面の向こうから……卑怯だぞッ！",
		"時間は有効に使え……",
		"何の真似だッ！！",
		"おれはスペース・オオアリクイ様だぞ！",
		"こらこら……やめなさい",
		"あまりおれ様を怒らせるな……",
		"ちょっと！やめて！",
		"なにがたのしいの！？",
		"ぎゃっ！やめろって！",
		"ちょっと！やめて！",
		"ひゃあ！",
		"ひえっ！",
		"むっ！やめろ！",
	];

	// ランダムにメッセージを選択
	const randomMessage = messages[Math.floor(Math.random() * messages.length)];

	// アニメーション停止
	spaceImage.style.animation = 'none'; 

	// メッセージ要素を作成
	const message = document.createElement('div');
	message.textContent = randomMessage;
	message.style.position = 'absolute';
	message.style.top = '40px';
	message.style.right = 'auto';
	message.style.color = '#FF0000';
	message.style.fontSize = '20px';
	message.style.fontWeight = 'bold';
	message.style.zIndex = '1001';
	message.style.textShadow = '2px 2px 5px white'; // 白い縁取りを追加
	document.body.appendChild(message);

	// メッセージを1秒後に非表示
	setTimeout(() => {
		message.style.display = 'none';
		// アニメーションを元に戻す
		spaceImage.style.animation = 'spin 8s linear infinite';
	}, 1000);
});





// スクリーンショットボタン
document.addEventListener("DOMContentLoaded", () => {
	const screenshotBtn = document.getElementById('screenshot-btn');
	const imageContainer = document.getElementById('image-container');
	if (screenshotBtn && imageContainer) {
		screenshotBtn.addEventListener('click', () => {
			const allImages = document.querySelectorAll('.image-wrapper');
			allImages.forEach(image => {
				image.style.animation = 'none';
			});
			html2canvas(imageContainer, {
				scale: 10, 
				useCORS: true, 
				allowTaint: true 
			}).then((canvas) => {
				const screenshotImg = canvas.toDataURL("image/png");
				const downloadLink = document.createElement('a');
				downloadLink.href = screenshotImg;
				downloadLink.download = 'screenshot.png';
				downloadLink.click();
			}).catch((error) => {
				console.error("エラーが発生しました:", error);
			});
			setTimeout(() => {
				allImages.forEach(image => {
					image.style.animation = ''; 
				});
			}, 1000);
		});
	}
});




// すべての画像を削除するボタン
const deleteBtn = document.getElementById('delete-btn');
deleteBtn.addEventListener('click', () => {
	const imageWrappers = document.querySelectorAll('.image-wrapper'); 
	imageWrappers.forEach(wrapper => {
		wrapper.classList.add('remove');
		setTimeout(() => {
			wrapper.remove();
		}, 500);
	});
});



// 名前表示/非表示ボタン
const toggleNameBtn = document.getElementById('toggle-name-btn');
toggleNameBtn.addEventListener('click', () => {
	const nameLabels = document.querySelectorAll('.name-label');
	nameLabels.forEach(label => {
		// 名前ラベルの表示/非表示を切り替える
		if (label.style.display === 'none') {
			label.style.display = 'block';
		} else {
			label.style.display = 'none';
		}
	});
});

// 身長表示/非表示ボタン
const toggleHeightBtn = document.getElementById('toggle-height-btn');
toggleHeightBtn.addEventListener('click', () => {
	const heightLabels = document.querySelectorAll('.height-label');
	heightLabels.forEach(label => {
		// 身長ラベルの表示/非表示を切り替える
		if (label.style.display === 'none') {
			label.style.display = 'block';
		} else {
			label.style.display = 'none';
		}
	});
});

// 目盛り表示/非表示ボタン
const toggleScaleBtn = document.getElementById('toggle-scale-btn');
const scaleGraduations = document.getElementById('scale-graduations');

toggleScaleBtn.addEventListener('click', () => {
	// 目盛りの表示/非表示を即座に切り替える
	if (scaleGraduations.style.display === '' || scaleGraduations.style.display === 'none') {
		scaleGraduations.style.display = 'flex'; // 表示
	} else {
		scaleGraduations.style.display = 'none'; // 非表示
	}
});

// ページ読み込み時に初期状態を設定しておく
document.addEventListener("DOMContentLoaded", () => {
	if (scaleGraduations.style.display === "") {
		scaleGraduations.style.display = "flex"; // 初期状態は表示
	}
});

// 画像の右クリックを無効にする
document.addEventListener('contextmenu', (e) => {
	if (e.target.tagName.toLowerCase() === 'img') {
		e.preventDefault();
	}
});



// アリクイ召喚
const showerButton = document.getElementById('shower-btn');

showerButton.addEventListener('click', () => {
	const numImages = 40;
	const imagePath = "image/アリクイ.png";

	// 画像が飛び出す場所をランダムに
	const randomPosition = () => {
		const x = Math.random() * window.innerWidth; // ランダムなX座標
		const y = Math.random() * window.innerHeight; // ランダムなY座標
		return { x, y };
	};

	// アニメーション！虹色に輝く効果を加える
	for (let i = 0; i < numImages; i++) {
		const img = document.createElement('img');
		img.src = imagePath;
		img.style.position = 'absolute';

		// サイズ！
		const size = Math.random() * (200 - 30) + 30; // 最小30px、最大200px
		img.style.width = `${size}px`;
		img.style.height = `${(size * 1) / (img.naturalWidth / img.naturalHeight)}px`; // 縦横比を維持

		img.style.transition = 'all 1s ease-in-out'; // アニメーション設定

		// 虹色アニメーションを設定
		img.style.animation = 'rainbow 0.5s infinite';  // 5秒周期で虹色にアニメーション

		const { x, y } = randomPosition();
		img.style.left = `${x}px`;
		img.style.top = `${y}px`;
		document.body.appendChild(img);

		setTimeout(() => {
			const { x, y } = randomPosition();
			img.style.left = `${x}px`;
			img.style.top = `${y}px`;
			img.style.transform = `scale(${Math.random() * 1.5 + 0.5})`; // ランダムに拡大
		}, 0);

		setTimeout(() => {
			img.style.opacity = '0';
			setTimeout(() => {
				img.remove();
			}, 500);
		}, 1000);
	}
});

// CSSに虹色アニメーションを追加
const style = document.createElement('style');
style.innerHTML = `
	@keyframes rainbow {
		0% { filter: hue-rotate(0deg); }
		25% { filter: hue-rotate(90deg); }
		50% { filter: hue-rotate(180deg); }
		75% { filter: hue-rotate(270deg); }
		100% { filter: hue-rotate(360deg); }
	}
`;
document.head.appendChild(style);
