/**
 * Flipa flipbook editor metabox behaviour.
 * Values from PHP arrive on window.FLIPA_DATA (see Flipa_Admin::enqueue):
 *   FLIPA_DATA.viewer     viewer.html URL
 *   FLIPA_DATA.ver        engine cache-bust token (viewer.html mtime)
 *   FLIPA_DATA.isPro      bool — Pro tier available
 *   FLIPA_DATA.bmkey      bookmark preview key ("preview-<post id>")
 *   FLIPA_DATA.mediaTitle i18n label for the media chooser
 */
( function () {
	var FD = window.FLIPA_DATA || {};
	var FLIPA_VIEWER = FD.viewer || '';
	var FLIPA_VER    = FD.ver || '';
	/*  */

	jQuery(function($){
		// ---- PDF media picker ----
		$('#flipa_pick_pdf').on('click', function(e){
			e.preventDefault();
			var frame = wp.media({ title:'Select a PDF', library:{ type:'application/pdf' }, multiple:false, button:{ text:'Use this PDF' } });
			frame.on('select', function(){
				var att = frame.state().get('selection').first().toJSON();
				$('#flipa_pdf_url').val(att.url);
				flipaSchedulePreview();
			});
			frame.open();
		});

		// ---- background color picker ----
		if ($.fn.wpColorPicker) { $('#flipa_bg').wpColorPicker(); }

		// ---- background image picker ----
		/*  */

		// ---- copy shortcode (button + click-on-code; green flash + toast) ----
		function flipaToast(msg){ var t=$('#flipa-toast'); t.text(msg).addClass('on'); clearTimeout(t.data('tid')); t.data('tid', setTimeout(function(){ t.removeClass('on'); }, 1600)); }
		function flipaCopy(text){
			var flash=function(){ var c=$('#flipa-sc').addClass('flipa-flash'); setTimeout(function(){ c.removeClass('flipa-flash'); }, 700); flipaToast('Copied to clipboard'); };
			if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text).then(flash, flash); }
			else { var t=document.createElement('textarea'); t.value=text; document.body.appendChild(t); t.select(); try{ document.execCommand('copy'); }catch(e){} document.body.removeChild(t); flash(); }
		}
		$('#flipa-sc').on('click', function(){ flipaCopy($(this).text()); });
		$('#flipa-sc-copy').on('click', function(){ flipaCopy($('#flipa-sc').text()); });

		// ---- page-flip sound test (same synth as the viewer engine) ----
		/*  */

		// ---- TOC builder (chapter / section rows) ----
		/*  */

		// ---- live preview ----
		function flipaPreviewSrc(){
			var pdf = ($('#flipa_pdf_url').val()||'').trim();
			if(!pdf) return '';
			var q=[]; function add(k,v){ q.push(k+'='+encodeURIComponent(v)); }
			add('pdf',pdf);
				add('_v', FLIPA_VER);   // cache-bust engine file in preview / open-in-tab
			add('dir',$('#flipa_dir').val());
			add('lang',$('#flipa_lang').val());
			add('view',$('#flipa_view').val());
			add('cover','hard');
			if($('#flipa_theme').val()==='light') add('theme','light');
			if($('#flipa_autoplay_on').is(':checked')){ add('auto','1'); add('autoint', $('#flipa_autoplay_interval').val()||4); if($('input[name=flipa_autoplay_loop]').is(':checked'))add('autoloop','1'); if($('input[name=flipa_autoplay_start]').is(':checked'))add('autostart','1'); }  // preview now mirrors autostart (WYSIWYG)
			if($('#flipa_print_on').is(':checked')) add('print','1');
				/*  */
				/*  */
			if($('input[name=flipa_bg_transparent]').is(':checked')) add('bg','transparent');
			else add('bg', ($('#flipa_bg').val()||'#222a36'));
			/*  */
			/*  */
			var hide=[];
			$('.flipa-toggles input[type=checkbox]').each(function(){
				var key=this.name.replace('flipa_opt_','');
				if(key==='sidearrows'){ if(this.checked) add('arrows','1'); return; }
				if(!this.checked) hide.push(key);
			});
			/*  */
			if(hide.length) add('hide', hide.join(','));
			var parts=[];
			$('#flipa-toc tbody tr').each(function(){
				var n=($(this).find('input[name="flipa_toc_name[]"]').val()||'').trim();
				if(!n) return;
				var pv=($(this).find('input[name="flipa_toc_page[]"]').val()||'').trim();
				var p=(pv==='')?'':(parseInt(pv,10)||'');
				var sub=$(this).find('.flipa-toc-kind').val()==='section';
				parts.push(encodeURIComponent(n)+'~'+p+(sub?'~s':''));
			});
			/*  */
			/*  */
			/*  */
			/*  */
			// password gate intentionally skipped in preview so content is visible
			// "Powered by flipa" credit is a FREE feature — reflect the checkbox in the live preview (free + pro)
			if($('#flipa_credit_on').is(':checked')) add('credit','1');
			// reflect the tier: free sends none of links/qr/depth (engine defaults them OFF); Pro enables them
			/*  */
			/*  */ // editor preview: enable drag/resize of media hotspots
			var src = FLIPA_VIEWER + '?' + q.join('&');
			if(window.flipaMediaPage>0) src += '#p=' + window.flipaMediaPage;   // open preview on the hotspot's page while editing media
			return src;
		}
		function flipaRefreshPreview(){
			var s=flipaPreviewSrc(); if(!s) return;
			$('#flipa-prev-frame').attr('src', s);
		}
		var flipaPrevT;
		function flipaSchedulePreview(){ clearTimeout(flipaPrevT); flipaPrevT=setTimeout(flipaRefreshPreview, 800); }
		$('#flipa-prev-refresh').on('click', flipaRefreshPreview);
		$('#flipa-prev-open').on('click', function(){ var s=flipaPreviewSrc(); if(s) window.open(s,'_blank','noopener'); else flipaToast('Select a PDF first'); });
		// auto-refresh (debounced) on any settings change
		$('#flipa_settings').on('change', 'input, select', flipaSchedulePreview);
		$('#flipa_settings').on('input', 'input[type=text], input[type=number]', function(e){
			if(e.target.id==='flipa_pdf_url') return; // URL: wait for change/blur, not each keystroke
			flipaSchedulePreview();
		});
		// ---- tabs ----
		$('.flipa-tabs').on('click','.flipa-tab',function(){
			var t=$(this).data('tab');
			$('.flipa-tab').removeClass('active'); $(this).addClass('active');
			$('.flipa-panel').removeClass('active').filter('[data-tab="'+t+'"]').addClass('active');
		});
		// ---- TOC drag-to-reorder ----
		/*  */
		flipaRefreshPreview(); // initial
	});
} )();
