<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Inserisci un Bottone Parse&Render </title>
        <script type="text/javascript" src="{{home_url}}/wp/wp-includes/js/tinymce/tiny_mce_popup.js"></script>
        <script type="text/javascript" src="{{base_url}}/lib/AmazonLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/EbayLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/AwinLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/TradeTrackerLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/PartnerizeLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/PrimeVideoLink.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/LinkPreview.js?{{renewcache}}"></script>
        <script type="text/javascript" src="{{base_url}}/lib/ImpactLink.js?{{renewcache}}"></script>
        <link rel="stylesheet" href="{{base_url}}/css/forms.css">
        <link rel="stylesheet" href="{{base_url}}/css/grid.css">
		<style>
			.status-card { padding:12px 14px; border-radius:8px; margin:16px 5%; border:1px solid #e3e3e3; background:#fafafa }
			.status-card.success { background:#f0fff4; border-color:#c6f6d5 }
			.status-card.error { background:#fff5f5; border-color:#fed7d7 }
			.status-card .title { font-weight:bold; font-size:14px; margin-bottom:4px }
			.status-card .subtitle { color:#555; font-size:12px; margin-bottom:6px }
			.status-card .message { font-size:13px }
			#submit[disabled] { opacity:.5; cursor:not-allowed }
		</style>

        <script>
            const formatProvider   = '{{ApiFormatProvider}}';
            const renderingManager = '{{ApiRenderingManager}}';
            const linksProvider    = '{{ApiLinkProvider}}';

            class FieldsManager {

                constructor() {

                    this.data = {};
                    
                    this.cta = document.getElementById('cta');

                    this.submitConditions = [];

                    this.marketplaceLink = null;

                    this.initDataShow();

                    this.initLanding();

                    this.submit = this.submit.bind( this );

                    document.getElementById('submit').addEventListener( 'click', this.submit );
                }


                setSubmitCondition( callback ) {

                    this.submitConditions.push( callback );
                }


                initDataShow() {
                    this.dataShow = document.getElementById('data_show');
                    this.dataShow.style.display = 'none';
                }


                initLanding() {

                    this.landingUrl    = document.getElementById('landing_url');
                    this.landingLoader = document.getElementById('landing_loader');

                    //this.landingSubmit = document.getElementById('landing_submit');

                    this.checkLanding = this.checkLanding.bind(this);

                    // this.landingSubmit.addEventListener('click', this.checkLanding );      
                    this.landingUrl.addEventListener('change', this.checkLanding );                    
                }


				async checkLanding( evt ) {

					try {
						this.showLoader();

						const encodedUrl = encodeURIComponent( encodeURIComponent( this.landingUrl.value ) );
						const apiUrl = `${renderingManager}v2/link-parser/check?url=${encodedUrl}`;
						const response = await fetch(apiUrl);
						const result = await response.json();

						this.data    = result;
						this.link    = result.url || this.landingUrl.value;
						this.program = (result.parser_info && result.parser_info.platform) || (result.platform || '');

						this.loaderFound();
						this.showData();
						return;

					} catch (e) {
						tinyMCEPopup.alert("Errore durante il controllo del link. Riprova.");
						return;
					}
				}


				

               
                showLoader() {
                    this.landingLoader.innerHTML = "<span style=\"bigger\">⏱🤔 cerco...</span>";                    
                }

                loaderFound() {
                    this.landingLoader.innerHTML = "<span style=\"bigger\">🤓👍 trovato!</span>";                    
                }

				showData() {

					let linkInput  = document.getElementById('link');
					let card       = document.getElementById('status_card');
					let submitBtn  = document.getElementById('submit');
					let ctaWrap    = document.getElementById('cta_container');
					let preview    = document.getElementById('preview');

					const handled = !!(this.data && this.data.is_handled);
					const platformFull = (this.data && this.data.parser_info && this.data.parser_info.platform) ? this.data.parser_info.platform : (this.program || '—');
					const platformCode = this.data && this.data.parser_info ? (this.data.parser_info.platform_code || this.data.parser_info.platform_slug || '') : '';

					card.className = 'status-card ' + (handled ? 'success' : 'error');
					card.innerHTML = handled
						? `<div class=\"title\">Link riconosciuto</div><div class=\"subtitle\">Piattaforma: ${platformFull}${platformCode?` · ${platformCode}`:''}</div><div class=\"message\">Puoi inserire lo shortcode.</div>`
						: `<div class=\"title\">Link non gestito</div><div class=\"subtitle\">${platformFull ? `Piattaforma: ${platformFull}` : ''}</div><div class=\"message\">Non puoi inserire lo shortcode per questo link.</div>`;

					linkInput.value = this.link;

					// Toggle interactions
					submitBtn.disabled = !handled;
					ctaWrap.style.display = handled ? 'block' : 'none';
					preview.style.display = handled ? 'block' : 'none';

					this.dataShow.style.display = 'block';
				}

                submit( event ) {

                    let content = this.cta.value; // tinymce.activeEditor.selection.getContent();

                    /// caso di uscita
                    if ( content.trim()  == '') { 

                        tinyMCEPopup.alert("Inserire un testo (CTA)" );
                        return;
                    }

                    /// verifica che non ci siano condizioni di errore
                    if( this.verifyErrors() ) return;
                
                    /// inserisce lo shortcode
                    let shortcode = `[parse_button link="${this.link}" program="${this.program}" format_id="{{formatId}}"]${content}[/parse_button]`;

                    tinyMCE.activeEditor.execCommand( 'mceInsertContent', 0, shortcode );

                    tinyMCEPopup.close();
                }
                

                /**
                 * verifica che non ci siano condizioni di errore
                 * 
                 * @return {boolean} true se ci sono errori, false altrimenti
                 */
                verifyErrors() {
                    
                    let errors = this.submitConditions.filter( item => !item.condition() );

                    if( errors.length ) {
                        tinyMCEPopup.alert( errors.shift().message );
                        return true;
                    }

                    return false;
                }
            }


            window.addEventListener( 'DOMContentLoaded', function() { 
                                
                const fieldsManager = new FieldsManager();                

                const preview = new LinkPreview('#preview', document.querySelector( '#link' ) );

                /*
                fieldsManager.setSubmitCondition( { 
                    condition : () => preview.clicked,
                    message   : 'Cliccare prima sul pulsante "preview"'
                });
                */

            }.bind(this));

        </script>
    </head>

    <body onload="tinyMCEPopup.executeOnLoad('init();')">
        
        <div class="landing_url_container">
            <div class="col1">
                <legend for="landing_url">Inserisci la URL della landing page dell'offerta e premi invio</legend>
            </div>
            <div class="col2"></div>
            <div class="col1">                
                <input type="text" id="landing_url">
            </div>    
            <div class="col2">
                <span id="landing_loader"></span>
            </div>
            <!--div class="col2">
                <button id="landing_submit">Elabora</button>
            </div-->    
        </div>

        <input type="hidden" id="link">

		<div id="data_show">

			<div id="status_card" class="status-card"></div>

			<div id="cta_container">
				<legend>Inserisci il testo (CTA) del bottone</legend>
				<input type="text" id="cta">
			</div>

            <div id="preview" class="btn-container">
                <a class="btn" href="javascript:void(0)">Preview</a>
                <small>Abilitare le popup sul sito per visualizzare la preview</small>
            </div>

            <input type="button" id="submit" value="Inserisci"/>   

        </div>
        
    
        <!--button>Usa una chiave di ricerca ( sconsigliato )</button>

            <span id="container_non_custom">

                <legend>keyword</legend>
                <input type="text" id="keyword">

                <legend>Min Price (Inserire un valore intero senza valuta, se omesso il default è 20 euro)</legend>
                <input type="text" id="min_price" placeholder="20">

            </span>

        </div--> 
    
        
        
    </body>
</html>