(function () {
	function copyText(text) {
		if (!text) return Promise.resolve(false);

		// Secure context: Clipboard API
		if (navigator.clipboard && window.isSecureContext) {
			return navigator.clipboard
				.writeText(text)
				.then(function () { return true; })
				.catch(function () { return false; });
		}

		// Fallback: execCommand
		return new Promise(function (resolve) {
			var ta = document.createElement('textarea');
			ta.value = text;

			// iOS / Safari 対策で viewport 外に固定
			ta.style.position = 'fixed';
			ta.style.top = '-1000px';
			ta.style.left = '-1000px';

			document.body.appendChild(ta);
			ta.focus();
			ta.select();

			var ok = false;
			try {
				ok = document.execCommand('copy');
			} catch (e) {
				ok = false;
			}

			document.body.removeChild(ta);
			resolve(ok);
		});
	}

	document.addEventListener('click', function (e) {
		var btn = e.target.closest('button.rllm-copy-btn');
		if (!btn) return;

		var sel = btn.getAttribute('data-copy');
		var el = sel ? document.querySelector(sel) : null;
		var text = el ? String(el.textContent || '').trim() : '';

		var prev = btn.innerHTML;

		copyText(text).then(function (ok) {
			btn.innerHTML = ok ? 'コピーしました' : 'コピー失敗';
			setTimeout(function () { btn.innerHTML = prev; }, 1200);
		});
	});
})();