/**
 * CargoHub Frontend JS
 * Adds copy-to-clipboard for tracking numbers
 */
(function($){
	'use strict';

	function copyTextToClipboard(text){
		if (navigator.clipboard && window.isSecureContext) {
			return navigator.clipboard.writeText(text);
		}
		// Fallback for non-secure contexts
		return new Promise(function(resolve, reject){
			try{
				var textarea = document.createElement('textarea');
				textarea.value = text;
				textarea.setAttribute('readonly', '');
				textarea.style.position = 'absolute';
				textarea.style.left = '-9999px';
				document.body.appendChild(textarea);
				textarea.select();
				document.execCommand('copy');
				document.body.removeChild(textarea);
				resolve();
			}catch(err){
				reject(err);
			}
		});
	}

	$(document).on('click', '.cargohub-copy-btn', function(e){
		e.preventDefault();
		var $btn = $(this);
		var text = $btn.data('track') || '';
		if (!text) {
			var fromSibling = $btn.siblings('.cargohub-free-tracking-number, .tracking-code').first().text();
			text = $.trim(fromSibling);
		}
		if (!text) return;
		copyTextToClipboard(text).then(function(){
			var original = $btn.text();
			$btn.addClass('copied').text('Kopyalandı ✓');
			setTimeout(function(){
				$btn.removeClass('copied').text(original);
			}, 1500);
		}).catch(function(){
			var original = $btn.text();
			$btn.addClass('copy-error').text('Kopyalanamadı');
			setTimeout(function(){
				$btn.removeClass('copy-error').text(original);
			}, 1500);
		});
	});
})(jQuery);


