/**
 * Frontend admin bar, Generate Featured Image button.
 * Injected on single post pages for manage_options users only.
 */
( function () {
    'use strict';

    var cfg     = window.csdtFrontAdmin || {};
    var ajaxUrl = cfg.ajaxUrl || '';
    var nonce   = cfg.nonce   || '';

    /* ── Pill button + modal CSS ─────────────────────────────────────────── */
    var css = [
        /* pill */
        '.csdt-gen-bar{display:block!important;text-align:right!important;padding:0 0 20px!important;width:100%!important;box-sizing:border-box!important;}',
        '.csdt-gen-img-pill{display:inline-flex;align-items:center;gap:6px;background:#2271b1;color:#fff;border:none;border-radius:3px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;line-height:1.5;transition:background .15s;}',
        '.csdt-gen-img-pill:hover{background:#135e96;}',
        '.csdt-gen-img-pill:disabled{opacity:.55;cursor:not-allowed;}',
        /* overlay */
        '.csdt-gen-modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:999999;}',
        /* modal card, WP admin style */
        '.csdt-gen-modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);background:#fff;border-radius:4px;width:calc(100% - 40px);max-width:500px;box-shadow:0 4px 32px rgba(0,0,0,.35);font-size:13px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#3c434a;max-height:calc(100vh - 40px);overflow-y:auto;}',
        /* header */
        '.csdt-gen-modal-hdr{padding:14px 16px;border-bottom:1px solid #dcdcde;background:#f6f7f7;border-radius:4px 4px 0 0;display:flex;align-items:center;justify-content:space-between;cursor:move;user-select:none;}',
        '.csdt-gen-modal-hdr h3{margin:0;font-size:14px;font-weight:600;color:#1d2327;}',
        '.csdt-gen-modal-hdr button{background:none;border:none;cursor:pointer;padding:2px 6px;color:#787c82;font-size:22px;line-height:1;border-radius:3px;}',
        /* body */
        '.csdt-gen-modal-body{padding:20px 24px;}',
        /* grid rows: fixed label col + fluid control col */
        '.csdt-gen-row{display:grid;grid-template-columns:120px 1fr;align-items:center;gap:0 12px;margin-bottom:12px;}',
        '.csdt-gen-row label{font-size:13px;font-weight:600;color:#3c434a;text-align:right;}',
        '.csdt-gen-row select{width:100%;padding:5px 8px;font-size:13px;border:1px solid #8c8f94;border-radius:3px;background:#fff;color:#3c434a;line-height:1.8;}',
        '.csdt-gen-row .csdt-sel-pair{display:flex;gap:8px;align-items:center;}',
        '.csdt-gen-row .csdt-sel-pair select:first-child{flex:1;}',
        '.csdt-gen-row .csdt-sel-pair select:last-child{width:100px;}',
        /* status + images, indent to align with controls */
        '.csdt-gen-modal-msg{font-size:12px;color:#00a32a;font-weight:600;min-height:18px;text-align:right;}',
        '.csdt-gen-modal-imgs{margin-left:132px;display:flex;gap:10px;flex-wrap:wrap;margin-bottom:4px;}',
        '.csdt-gen-img-opt{flex:1 1 200px;border-radius:4px;overflow:hidden;cursor:pointer;border:3px solid transparent;transition:border-color .15s;}',
        '.csdt-gen-img-opt.selected{border-color:#2271b1;}',
        '.csdt-gen-img-opt img{width:100%;display:block;height:auto;}',
        /* directive row */
        '.csdt-gen-directive-row{display:grid;grid-template-columns:120px 1fr;align-items:start;gap:0 12px;margin-bottom:12px;}',
        '.csdt-gen-directive-row label{font-size:13px;font-weight:600;color:#3c434a;text-align:right;padding-top:6px;}',
        '.csdt-gen-directive-wrap{display:flex;flex-direction:column;gap:3px;}',
        '.csdt-gen-directive-wrap textarea{width:100%;padding:5px 8px;font-size:12px;border:1px solid #8c8f94;border-radius:3px;background:#fff;color:#3c434a;line-height:1.5;resize:vertical;min-height:56px;box-sizing:border-box;font-family:inherit;}',
        '.csdt-gen-directive-hint{font-size:11px;color:#787c82;}',
        /* prompt toggle */
        '.csdt-gen-prompt-row{margin:0 0 8px 132px;}',
        '.csdt-gen-prompt-toggle{font-size:11px;color:#787c82;background:none;border:none;cursor:pointer;padding:0;text-decoration:underline;}',
        '.csdt-gen-prompt-text{display:none;margin-top:6px;padding:8px 10px;background:#f6f7f7;border:1px solid #dcdcde;border-radius:3px;font-size:11px;color:#3c434a;line-height:1.5;white-space:pre-wrap;word-break:break-word;}',
        /* footer */
        '.csdt-gen-modal-actions{padding:12px 16px;border-top:1px solid #dcdcde;background:#f6f7f7;border-radius:0 0 4px 4px;display:flex;align-items:flex-end;gap:8px;}',
        '.csdt-gen-footer-right{display:flex;flex-direction:column;align-items:flex-end;gap:5px;}',
        '.csdt-gen-footer-btns{display:flex;gap:8px;}',
        '.csdt-gen-btn-regen{background:#2271b1;color:#fff;border:1px solid #135e96;border-radius:3px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;}',
        '.csdt-gen-btn-regen:hover{background:#135e96;}',
        '.csdt-gen-btn-regen:disabled{opacity:.5;cursor:not-allowed;}',
        '.csdt-gen-btn-cancel{background:#fff;color:#3c434a;border:1px solid #c3c4c7;border-radius:3px;padding:6px 14px;font-size:13px;cursor:pointer;font-family:inherit;}',
        '.csdt-gen-btn-cancel:disabled{opacity:.5;cursor:not-allowed;}',
        '.csdt-gen-btn-spacer{flex:1;}',
        '.csdt-gen-btn-save{background:#00a32a;color:#fff;border:1px solid #00a32a;border-radius:3px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;}',
        '.csdt-gen-btn-save:hover{background:#007017;}',
        '.csdt-gen-btn-save:disabled{opacity:.35;cursor:not-allowed;}',
    ].join( '' );

    var style = document.createElement( 'style' );
    style.textContent = css;
    document.head.appendChild( style );

    /* ── Modal DOM ───────────────────────────────────────────────────────── */
    var styleOptHtml = ( csdtFrontAdmin.styleOptions || [] ).map( function( s ) {
        return '<option value="' + s.val + '">' + s.label + '</option>';
    } ).join( '' );

    var articleStyleOptHtml = ( csdtFrontAdmin.articleStyleOptions || [] ).map( function( s ) {
        return '<option value="' + s.val + '">' + s.label + '</option>';
    } ).join( '' );

    var bg = document.createElement( 'div' );
    bg.className = 'csdt-gen-modal-bg';
    bg.innerHTML = [
        '<div class="csdt-gen-modal">',
        '  <div class="csdt-gen-modal-hdr">',
        '    <h3>🎨 Generate Featured Image</h3>',
        '    <button type="button" id="csdt-gen-close" title="Close">&times;</button>',
        '  </div>',
        '  <div class="csdt-gen-modal-body">',
        '    <div class="csdt-gen-row">',
        '      <label for="csdt-gen-article-style">Article style</label>',
        '      <select id="csdt-gen-article-style">' + articleStyleOptHtml + '</select>',
        '    </div>',
        '    <div class="csdt-gen-row">',
        '      <label for="csdt-gen-bg-color">Background</label>',
        '      <select id="csdt-gen-bg-color">',
        '        <option value="auto">Auto (match style)</option>',
        '        <option value="light_grey">⬜ Light grey / off-white</option>',
        '        <option value="warm_cream">🟡 Warm cream / golden</option>',
        '        <option value="white">◻ Clean white</option>',
        '        <option value="sky_blue">🔵 Sky blue / outdoor</option>',
        '        <option value="gradient">🌅 Soft gradient</option>',
        '        <option value="dark">⬛ Dark / dramatic</option>',
        '      </select>',
        '    </div>',
        '    <div class="csdt-gen-row">',
        '      <label for="csdt-gen-style">Image style</label>',
        '      <select id="csdt-gen-style">' + styleOptHtml + '</select>',
        '    </div>',
        '    <div class="csdt-gen-row">',
        '      <label for="csdt-gen-quality">Quality</label>',
        '      <select id="csdt-gen-quality">',
        '        <option value="standard" selected>Standard</option>',
        '        <option value="hd">HD</option>',
        '      </select>',
        '    </div>',
        '    <div class="csdt-gen-row">',
        '      <label>Post title</label>',
        '      <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;color:#3c434a;font-weight:400;">',
        '        <input type="checkbox" id="csdt-gen-overlay" style="width:16px;height:16px;cursor:pointer">',
        '        Include Post Title in image',
        '      </label>',
        '    </div>',
        '    <div class="csdt-gen-directive-row">',
        '      <label for="csdt-gen-directive">Directive</label>',
        '      <div class="csdt-gen-directive-wrap">',
        '        <textarea id="csdt-gen-directive" maxlength="1000" placeholder="Optional, give the AI a specific direction, e.g. &quot;use a chess metaphor&quot; or &quot;focus on the human cost&quot;"></textarea>',
        '        <span class="csdt-gen-directive-hint"><span id="csdt-gen-directive-count">0</span> / 1000</span>',
        '      </div>',
        '    </div>',
        '    <div class="csdt-gen-prompt-row" id="csdt-gen-prompt-row" style="display:none;">',
        '      <button type="button" class="csdt-gen-prompt-toggle" id="csdt-gen-prompt-toggle">▶ View prompt</button>',
        '      <div class="csdt-gen-prompt-text" id="csdt-gen-prompt-text"></div>',
        '    </div>',
        '    <div class="csdt-gen-modal-imgs" id="csdt-gen-imgs"></div>',
        '  </div>',
        '  <div class="csdt-gen-modal-actions">',
        '    <button type="button" class="csdt-gen-btn-save" id="csdt-gen-save" disabled>✔ Save as Featured Image</button>',
        '    <span class="csdt-gen-btn-spacer"></span>',
        '    <div class="csdt-gen-footer-right">',
        '      <div class="csdt-gen-modal-msg" id="csdt-gen-msg"></div>',
        '      <div class="csdt-gen-footer-btns">',
        '        <button type="button" class="csdt-gen-btn-regen" id="csdt-gen-regen">⚙ Generate</button>',
        '        <button type="button" class="csdt-gen-btn-cancel" id="csdt-gen-cancel">Cancel</button>',
        '      </div>',
        '    </div>',
        '  </div>',
        '</div>',
    ].join( '' );
    document.body.appendChild( bg );

    var msgEl         = document.getElementById( 'csdt-gen-msg' );
    var imgsEl        = document.getElementById( 'csdt-gen-imgs' );
    var saveBtn       = document.getElementById( 'csdt-gen-save' );
    var regenBtn      = document.getElementById( 'csdt-gen-regen' );
    var cancelBtn     = document.getElementById( 'csdt-gen-cancel' );
    var closeBtn      = document.getElementById( 'csdt-gen-close' );
    var styleEl       = document.getElementById( 'csdt-gen-style' );
    var qualEl        = document.getElementById( 'csdt-gen-quality' );
    var promptRow     = document.getElementById( 'csdt-gen-prompt-row' );
    var promptToggle  = document.getElementById( 'csdt-gen-prompt-toggle' );
    var promptText    = document.getElementById( 'csdt-gen-prompt-text' );

    if ( promptToggle ) {
        promptToggle.addEventListener( 'click', function () {
            var open = promptText.style.display !== 'none';
            promptText.style.display = open ? 'none' : 'block';
            promptToggle.textContent = ( open ? '▶' : '▼' ) + ' View prompt';
        } );
    }

    var articleStyleEl  = document.getElementById( 'csdt-gen-article-style' );
    var bgColorEl       = document.getElementById( 'csdt-gen-bg-color' );
    var overlayEl       = document.getElementById( 'csdt-gen-overlay' );
    var directiveEl     = document.getElementById( 'csdt-gen-directive' );
    var directiveCount  = document.getElementById( 'csdt-gen-directive-count' );

    var LS_STYLE_KEY = 'csdt_img_style_last';

    // Default to last used style; first-time default is strong_metaphor
    if ( styleEl ) {
        var savedStyle = localStorage.getItem( LS_STYLE_KEY ) || 'strong_metaphor';
        styleEl.value = savedStyle;
        styleEl.addEventListener( 'change', function () {
            localStorage.setItem( LS_STYLE_KEY, styleEl.value );
        } );
    }

    if ( directiveEl && directiveCount ) {
        directiveEl.addEventListener( 'input', function () {
            directiveCount.textContent = directiveEl.value.length;
        } );
    }

    var currentPostId = 0;
    var pendingIds    = [];
    var selectedId    = 0;

    /* ── Helpers ─────────────────────────────────────────────────────────── */
    function setMsg( txt ) {
        if ( ! msgEl ) { return; }
        msgEl.textContent = txt;
        var lead = txt.charAt( 0 );
        // Colour by state so failures read as failures, not as green "success" text.
        msgEl.style.color = lead === '✕' ? '#d63638' : ( lead === '✔' ? '#00a32a' : '#787c82' );
    }

    function setBusy( busy ) {
        if ( regenBtn  ) regenBtn.disabled  = busy;
        if ( cancelBtn ) cancelBtn.disabled = busy;
        if ( saveBtn   ) saveBtn.disabled   = busy || ! selectedId;
    }

    function post( action, extra, cb ) {
        var fd = new FormData();
        fd.append( 'action', action );
        fd.append( 'nonce',  nonce );
        Object.keys( extra ).forEach( function ( k ) { fd.append( k, extra[ k ] ); } );
        fetch( ajaxUrl, { method: 'POST', body: fd } )
            .then( function ( r ) { return r.json(); } )
            .then( cb )
            .catch( function () { cb( { success: false, data: { message: 'Network error.' } } ); } );
    }

    /* ── Generate ────────────────────────────────────────────────────────── */
    function generate() {
        if ( ! currentPostId ) return;
        imgsEl.innerHTML = '';
        selectedId = 0;
        saveBtn.disabled = true;
        setBusy( true );
        setMsg( '⏳ Writing prompt…' );

        var style        = styleEl        ? styleEl.value        : ( localStorage.getItem( LS_STYLE_KEY ) || 'strong_metaphor' );
        var quality      = qualEl         ? qualEl.value         : 'standard';
        var articleStyle = articleStyleEl ? articleStyleEl.value : 'general';
        var bgColor      = bgColorEl      ? bgColorEl.value      : 'auto';
        var directive    = directiveEl    ? directiveEl.value.trim().substring( 0, 1000 ) : '';

        if ( styleEl ) { localStorage.setItem( LS_STYLE_KEY, style ); }

        post( 'csdt_devtools_ai_image_generate', {
            post_id:         currentPostId,
            quality:         quality,
            prompt_vendor:   cfg.promptVendor || 'openai',
            prompt_model:    cfg.promptModel  || 'gpt-4o-mini',
            prompt_style:    style,
            article_style:   articleStyle,
            bg_color:        bgColor,
            include_overlay: overlayEl && overlayEl.checked ? '1' : '0',
            user_directive:  directive,
        }, function ( startResp ) {
            if ( ! startResp.success || ! startResp.data || ! startResp.data.job_id ) {
                setBusy( false );
                setMsg( '✕ ' + ( ( startResp.data && startResp.data.message ) || 'Failed to start generation.' ) );
                return;
            }
            var jobId      = startResp.data.job_id;
            var elapsed    = 0;
            var MAX_POLL_S = 300;
            setMsg( '⏳ Generating… (0s)' );
            var pollTimer = setInterval( function () {
                elapsed += 4;
                if ( elapsed > MAX_POLL_S ) {
                    clearInterval( pollTimer );
                    setBusy( false );
                    setMsg( '✕ Timed out after 5 min, check server error logs' );
                    return;
                }
                var m = Math.floor( elapsed / 60 ), s = elapsed % 60;
                setMsg( '⏳ Generating… (' + ( m > 0 ? m + 'm ' : '' ) + s + 's)' );
                post( 'csdt_devtools_ai_image_poll', { job_id: jobId }, function ( pollResp ) {
                    var st = pollResp.data && pollResp.data.status;
                    if ( st === 'pending' || st === 'processing' ) return;
                    clearInterval( pollTimer );
                    setBusy( false );
                    if ( ! pollResp.success ) {
                        var expMsg = st === 'expired' ? 'Job expired, server may have timed out' : ( ( pollResp.data && ( pollResp.data.error || pollResp.data.message ) ) || 'Request failed' );
                        setMsg( '✕ ' + expMsg );
                        return;
                    }
                    if ( st === 'error' ) {
                        setMsg( '✕ ' + ( ( pollResp.data && pollResp.data.error ) || 'Generation failed (no error detail, check PHP error log)' ) );
                        return;
                    }
                    var result  = pollResp.data.result || {};
                    var options = result.options || [];
                    if ( ! options.length ) {
                        setMsg( '✕ Generation failed, no images returned' );
                        return;
                    }
                    if ( result.prompt && promptRow && promptText ) {
                        promptText.textContent = result.prompt;
                        promptRow.style.display = 'block';
                        promptText.style.display = 'none';
                        if ( promptToggle ) { promptToggle.textContent = '▶ View prompt'; }
                    }
                    pendingIds = options.map( function ( o ) { return o.attach_id; } );
                    setMsg( options.length > 1 ? 'Click an image to select it, then save.' : 'Review the image and save or regenerate.' );
                    imgsEl.innerHTML = '';
                    options.forEach( function ( opt ) {
                        var wrap = document.createElement( 'div' );
                        wrap.className = 'csdt-gen-img-opt' + ( options.length === 1 ? ' selected' : '' );
                        wrap.dataset.attachId = opt.attach_id;
                        var img = document.createElement( 'img' );
                        img.src = opt.thumb_url || opt.full_url;
                        img.alt = 'Generated option';
                        wrap.appendChild( img );
                        wrap.addEventListener( 'click', function () {
                            imgsEl.querySelectorAll( '.csdt-gen-img-opt' ).forEach( function ( el ) { el.classList.remove( 'selected' ); } );
                            wrap.classList.add( 'selected' );
                            selectedId = opt.attach_id;
                            saveBtn.disabled = false;
                        } );
                        imgsEl.appendChild( wrap );
                    } );
                    if ( options.length === 1 ) {
                        selectedId = options[0].attach_id;
                        saveBtn.disabled = false;
                    }
                } );
            }, 4000 );
        } );
    }

    /* ── Save ────────────────────────────────────────────────────────────── */
    function save() {
        if ( ! selectedId || ! currentPostId ) return;
        setBusy( true );
        setMsg( '⏳ Saving as featured image…' );
        var discardIds = pendingIds.filter( function ( id ) { return id !== selectedId; } );
        post( 'csdt_devtools_ai_image_pick', {
            post_id:   currentPostId,
            attach_id: selectedId,
            discard:   discardIds.join( ',' ),
        }, function ( resp ) {
            setBusy( false );
            if ( resp.success ) {
                setMsg( '✔ Saved! Refreshing page…' );
                // Update the featured image on the page without full reload
                var newUrl = resp.data && resp.data.thumb_url ? resp.data.thumb_url : '';
                if ( newUrl ) {
                    var heroImg = document.querySelector( '.wp-post-image' );
                    if ( heroImg ) { heroImg.src = newUrl; }
                }
                pendingIds = [];
                selectedId = 0;
                setTimeout( function () { window.location.reload(); }, 800 );
            } else {
                setMsg( '✕ ' + ( ( resp.data && resp.data.message ) || 'Save failed.' ) );
            }
        } );
    }

    /* ── Discard (cancel) ────────────────────────────────────────────────── */
    function discard() {
        if ( pendingIds.length ) {
            post( 'csdt_devtools_ai_image_discard', { attach_ids: pendingIds.join( ',' ) }, function () {} );
            pendingIds = [];
        }
        selectedId = 0;
        bg.style.display = 'none';
        if ( modalEl ) { modalEl.style.left = ''; modalEl.style.top = ''; modalEl.style.transform = ''; }
        imgsEl.innerHTML = '';
        setMsg( '' );
        setBusy( false );
        saveBtn.disabled = true;
        if ( promptRow )  { promptRow.style.display = 'none'; }
        if ( promptText ) { promptText.style.display = 'none'; promptText.textContent = ''; }
    }

    /* ── Wire up buttons ─────────────────────────────────────────────────── */
    if ( regenBtn  ) { regenBtn.addEventListener(  'click', generate ); }
    if ( saveBtn   ) { saveBtn.addEventListener(   'click', save ); }
    if ( cancelBtn ) { cancelBtn.addEventListener( 'click', discard ); }
    if ( closeBtn  ) { closeBtn.addEventListener(  'click', discard ); }

    document.addEventListener( 'keydown', function ( e ) {
        if ( e.key === 'Escape' && bg.style.display !== 'none' ) discard();
    } );

    /* ── Drag to move ────────────────────────────────────────────────────── */
    var modalEl  = bg.querySelector( '.csdt-gen-modal' );
    var hdrEl    = bg.querySelector( '.csdt-gen-modal-hdr' );
    var dragging = false, dragOffX = 0, dragOffY = 0;

    hdrEl.addEventListener( 'mousedown', function ( e ) {
        if ( e.button !== 0 || e.target.tagName === 'BUTTON' ) return;
        var rect = modalEl.getBoundingClientRect();
        modalEl.style.left      = rect.left + 'px';
        modalEl.style.top       = rect.top  + 'px';
        modalEl.style.transform = 'none';
        dragOffX = e.clientX - rect.left;
        dragOffY = e.clientY - rect.top;
        dragging = true;
        e.preventDefault();
    } );

    document.addEventListener( 'mousemove', function ( e ) {
        if ( ! dragging ) return;
        var x = Math.max( 0, Math.min( e.clientX - dragOffX, window.innerWidth  - modalEl.offsetWidth  ) );
        var y = Math.max( 0, Math.min( e.clientY - dragOffY, window.innerHeight - modalEl.offsetHeight ) );
        modalEl.style.left = x + 'px';
        modalEl.style.top  = y + 'px';
    } );

    document.addEventListener( 'mouseup', function () { dragging = false; } );

    /* ── Position bar above category/tags section ───────────────────────── */
    function positionBar( bar ) {
        // Prefer entry footer (cats/tags), then footer meta, then end of content
        var anchor = document.querySelector( '.entry-footer' )
                  || document.querySelector( '.cat-links' )
                  || document.querySelector( '.tags-links' )
                  || document.querySelector( '.post-categories' )
                  || document.querySelector( '.entry-meta' )
                  || document.querySelector( '.entry-content' )
                  || document.querySelector( 'article' );
        if ( anchor ) {
            anchor.parentNode.insertBefore( bar, anchor );
        } else {
            document.body.insertBefore( bar, document.body.firstChild );
        }
        bar.style.display = 'block';
    }

    /* ── Wire up pill button ─────────────────────────────────────────────── */
    function bindBar() {
        var bar = document.getElementById( 'csdt-gen-bar' );
        if ( ! bar || bar._csdtBound ) return;
        bar._csdtBound = true;
        positionBar( bar );
        var pid = parseInt( bar.dataset.postId, 10 );
        bar.querySelectorAll( '.csdt-gen-img-pill' ).forEach( function ( btn ) {
            btn.addEventListener( 'click', function () {
                currentPostId = pid;
                selectedId    = 0;
                pendingIds    = [];
                imgsEl.innerHTML = '';
                saveBtn.disabled = true;
                setMsg( 'Click Generate to create an image for this post.' );
                bg.style.display = 'block';
            } );
        } );
    }

    /* ── Add CTR pill styles alongside the generate pill ────────────────── */
    var style = document.querySelector( 'style[data-csdt-frontend]' ) || ( function () {
        var s = document.createElement( 'style' );
        s.setAttribute( 'data-csdt-frontend', '1' );
        document.head.appendChild( s );
        return s;
    } )();
    style.textContent += '.csdt-ctr-pill{display:inline-flex;align-items:center;gap:6px;background:#1a7a34;color:#fff;border:none;border-radius:3px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;line-height:1.5;transition:background .15s;margin-left:8px;}'
        + '.csdt-ctr-pill:hover{background:#145c27;}'
        + '.csdt-ctr-pill:disabled{opacity:.55;cursor:not-allowed;}';

    if ( document.readyState === 'loading' ) {
        document.addEventListener( 'DOMContentLoaded', bindBar );
    } else {
        bindBar();
    }

} )();

/* ── CTR Optimisation pill handler ──────────────────────────────────────── */
( function () {
    'use strict';

    var ajaxUrl   = ( window.csdtFrontAdmin || {} ).ajaxUrl || '';
    var CACHE_TTL     = 48 * 60 * 60 * 1000; // 48 h
    var CACHE_VERSION = 3; // bump to auto-purge old format entries

    /* CSS for CTR result modal */
    var s = document.createElement( 'style' );
    s.textContent = [
        '.csdt-ctr-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:1000000;}',
        '.csdt-ctr-modal{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);background:#fff;border-radius:4px;width:calc(100% - 32px);max-width:560px;box-shadow:0 4px 32px rgba(0,0,0,.35);font-size:13px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#3c434a;max-height:calc(100vh - 40px);overflow-y:auto;}',
        '.csdt-ctr-hdr{padding:12px 16px;border-bottom:1px solid #dcdcde;background:#f6f7f7;border-radius:4px 4px 0 0;display:flex;align-items:center;justify-content:space-between;}',
        '.csdt-ctr-hdr h3{margin:0;font-size:14px;font-weight:600;color:#1d2327;}',
        '.csdt-ctr-hdr button{background:none;border:none;cursor:pointer;padding:2px 6px;color:#787c82;font-size:22px;line-height:1;border-radius:3px;}',
        '.csdt-ctr-body{padding:16px 20px;}',
        '.csdt-ctr-scores{display:flex;align-items:center;gap:12px;margin-bottom:16px;padding-bottom:14px;border-bottom:1px solid #f0f0f0;}',
        '.csdt-ctr-score-col{flex:1;text-align:center;}',
        '.csdt-ctr-score-lbl{display:block;font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:4px;}',
        '.csdt-ctr-badge{display:inline-block;padding:4px 14px;border-radius:20px;font-size:18px;font-weight:700;color:#fff;background:#888;min-width:60px;text-align:center;}',
        '.csdt-ctr-arrow{font-size:22px;color:#aaa;flex-shrink:0;}',
        '.csdt-ctr-section{margin-bottom:14px;}',
        '.csdt-ctr-section-lbl{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#888;margin-bottom:5px;display:flex;align-items:center;gap:6px;}',
        '.csdt-ctr-field-score{font-size:10px;font-weight:700;padding:1px 6px;border-radius:10px;color:#fff;}',
        '.csdt-ctr-row{display:flex;align-items:flex-start;gap:7px;margin-bottom:5px;}',
        '.csdt-ctr-tag{flex-shrink:0;font-size:10px;font-weight:700;padding:1px 6px;border-radius:3px;line-height:1.6;margin-top:1px;}',
        '.csdt-ctr-tag-cur{background:#fff3e0;color:#b45309;}',
        '.csdt-ctr-tag-new{background:#dbeafe;color:#1d4ed8;}',
        '.csdt-ctr-old{font-size:12px;color:#b45309;line-height:1.45;}',
        '.csdt-ctr-new{font-size:13px;color:#1d4ed8;font-weight:600;line-height:1.45;}',
        '.csdt-ctr-apply{background:#1a7a34;color:#fff;border:none;border-radius:3px;padding:4px 12px;font-size:12px;font-weight:600;cursor:pointer;font-family:inherit;}',
        '.csdt-ctr-apply:disabled{opacity:.55;cursor:not-allowed;}',
        '.csdt-ctr-reanalyse{background:none;border:none;padding:0;font-size:11px;color:#2271b1;text-decoration:underline;cursor:pointer;font-family:inherit;margin-left:8px;}',
        '.csdt-ctr-reasoning{font-size:12px;color:#555;font-style:italic;border-top:1px solid #f0f0f0;padding-top:10px;margin-top:4px;line-height:1.5;}',
        '.csdt-ctr-status{font-size:12px;margin-top:8px;min-height:16px;}',
    ].join( '' );
    document.head.appendChild( s );

    /* Build modal DOM once */
    var bg = document.createElement( 'div' );
    bg.className = 'csdt-ctr-bg';
    bg.innerHTML = '<div class="csdt-ctr-modal">'
        + '<div class="csdt-ctr-hdr"><h3>↑ CTR Optimisation</h3><button id="csdt-ctr-close">✕</button></div>'
        + '<div class="csdt-ctr-body">'
        +   '<div class="csdt-ctr-scores">'
        +     '<div class="csdt-ctr-score-col"><span class="csdt-ctr-score-lbl">Before</span><span class="csdt-ctr-badge" id="csdt-ctr-before">—</span></div>'
        +     '<div class="csdt-ctr-arrow">→</div>'
        +     '<div class="csdt-ctr-score-col"><span class="csdt-ctr-score-lbl">After</span><span class="csdt-ctr-badge" id="csdt-ctr-after">—</span></div>'
        +   '</div>'
        +   '<div class="csdt-ctr-section"><div class="csdt-ctr-section-lbl">Title<span class="csdt-ctr-field-score" id="csdt-ctr-title-score" style="display:none;"></span></div><div class="csdt-ctr-row"><span class="csdt-ctr-tag csdt-ctr-tag-cur">Current</span><div class="csdt-ctr-old" id="csdt-ctr-old-title"></div></div><div class="csdt-ctr-row"><span class="csdt-ctr-tag csdt-ctr-tag-new">New</span><div class="csdt-ctr-new" id="csdt-ctr-new-title"></div></div><button class="csdt-ctr-apply" id="csdt-ctr-apply-title" style="margin-top:4px;">Apply title</button></div>'
        +   '<div class="csdt-ctr-section"><div class="csdt-ctr-section-lbl">Meta description<span class="csdt-ctr-field-score" id="csdt-ctr-desc-score" style="display:none;"></span></div><div class="csdt-ctr-row"><span class="csdt-ctr-tag csdt-ctr-tag-cur">Current</span><div class="csdt-ctr-old" id="csdt-ctr-old-desc"></div></div><div class="csdt-ctr-row"><span class="csdt-ctr-tag csdt-ctr-tag-new">New</span><div class="csdt-ctr-new" id="csdt-ctr-new-desc"></div></div><button class="csdt-ctr-apply" id="csdt-ctr-apply-desc" style="margin-top:4px;">Apply meta</button></div>'
        +   '<p class="csdt-ctr-reasoning" id="csdt-ctr-reasoning"></p>'
        +   '<div class="csdt-ctr-status" id="csdt-ctr-apply-status"></div>'
        + '</div></div>';
    document.body.appendChild( bg );

    /* Reload-on-close state — set when title apply changes the slug */
    var pendingReloadUrl = '';

    function closeModal() {
        bg.style.display = 'none';
        if ( pendingReloadUrl ) {
            window.location.href = pendingReloadUrl;
        }
    }

    var closeBtn = document.getElementById( 'csdt-ctr-close' );
    closeBtn.addEventListener( 'click', closeModal );
    bg.addEventListener( 'click', function ( e ) { if ( e.target === bg ) closeModal(); } );

    function scoreColour( n ) {
        return n >= 70 ? '#1a7a34' : n >= 45 ? '#e67e00' : '#c3372b';
    }

    /* localStorage cache keyed by post ID */
    function cacheKey( pid ) { return 'csdt_ctr_' + pid; }

    function loadCache( pid ) {
        try {
            var c = JSON.parse( localStorage.getItem( cacheKey( pid ) ) || 'null' );
            if ( ! c || ! c.d ) return null;
            if ( c.v !== CACHE_VERSION ) { localStorage.removeItem( cacheKey( pid ) ); return null; }
            if ( c.d.titleApplied ) { localStorage.removeItem( cacheKey( pid ) ); return null; }
            if ( ( Date.now() - ( c.ts || 0 ) ) < CACHE_TTL ) return c.d;
        } catch ( e ) {}
        return null;
    }

    function saveCache( pid, d ) {
        try { localStorage.setItem( cacheKey( pid ), JSON.stringify( { v: CACHE_VERSION, d: d, ts: Date.now() } ) ); } catch ( e ) {}
    }

    function clearCache( pid ) {
        try { localStorage.removeItem( cacheKey( pid ) ); } catch ( e ) {}
    }

    function showResult( d, pid, ctrNonce, fromCache, runFresh ) {
        pendingReloadUrl = '';

        document.getElementById( 'csdt-ctr-before' ).textContent      = d.ctr_before + '%';
        document.getElementById( 'csdt-ctr-before' ).style.background  = scoreColour( d.ctr_before );
        document.getElementById( 'csdt-ctr-after' ).textContent        = d.ctr_after + '%';
        document.getElementById( 'csdt-ctr-after' ).style.background   = scoreColour( d.ctr_after );
        document.getElementById( 'csdt-ctr-old-title' ).textContent    = d.old_title || '(post title)';
        document.getElementById( 'csdt-ctr-new-title' ).textContent    = d.new_title;
        document.getElementById( 'csdt-ctr-old-desc' ).textContent     = d.old_desc || '(none set)';
        document.getElementById( 'csdt-ctr-new-desc' ).textContent     = d.new_desc;
        document.getElementById( 'csdt-ctr-reasoning' ).textContent    = d.reasoning;

        /* Per-field score chips */
        function setFieldScore( elId, score ) {
            var el = document.getElementById( elId );
            if ( ! el || score === null || score === undefined ) { return; }
            el.textContent        = score + '%';
            el.style.background   = scoreColour( score );
            el.style.display      = 'inline-block';
        }
        setFieldScore( 'csdt-ctr-title-score', d.title_score );
        setFieldScore( 'csdt-ctr-desc-score',  d.desc_score );

        var statusEl = document.getElementById( 'csdt-ctr-apply-status' );
        if ( fromCache ) {
            statusEl.style.color = '#888';
            statusEl.innerHTML   = 'Cached result. <button class="csdt-ctr-reanalyse" id="csdt-ctr-reanalyse-btn">Re-analyse</button>';
            document.getElementById( 'csdt-ctr-reanalyse-btn' ).addEventListener( 'click', function () {
                clearCache( pid );
                bg.style.display = 'none';
                runFresh();
            } );
        } else {
            statusEl.textContent = '';
        }

        var applyTitleBtn  = document.getElementById( 'csdt-ctr-apply-title' );
        var applyDescBtn   = document.getElementById( 'csdt-ctr-apply-desc' );
        var titleOptimised = d.new_title && d.old_title && d.new_title.trim() === d.old_title.trim();
        var descOptimised  = d.new_desc  && d.old_desc  && d.new_desc.trim()  === d.old_desc.trim();
        applyTitleBtn.disabled    = titleOptimised;
        applyTitleBtn.textContent = titleOptimised ? '✓ Already optimised' : 'Apply title';
        applyDescBtn.disabled     = descOptimised;
        applyDescBtn.textContent  = descOptimised  ? '✓ Already optimised' : 'Apply meta';

        /* Rescore after an apply — updates all DOM including button states */
        function rescore( onDone ) {
            statusEl.textContent = '⟳ Rescoring…';
            statusEl.style.color = '#888';
            fetch( ajaxUrl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    new URLSearchParams( { action: 'cs_seo_ctr_optimise', post_id: pid, nonce: ctrNonce } ),
            } )
            .then( function ( r ) { return r.json(); } )
            .then( function ( data ) {
                if ( data.success ) {
                    var nd = data.data;
                    /* Call onDone FIRST so it can override nd fields (e.g. lock new_title = appliedTitle)
                       before we update d and the DOM. Without this, d.new_desc gets overwritten by the
                       AI rescore value, causing the next Apply click to send the wrong (or empty) value. */
                    if ( onDone ) onDone( nd );
                    /* Sync d from nd (already patched by onDone) */
                    d.ctr_before = nd.ctr_before; d.ctr_after = nd.ctr_after;
                    d.old_title  = nd.old_title;  d.old_desc  = nd.old_desc;
                    d.new_title  = nd.new_title;  d.new_desc  = nd.new_desc;
                    /* Update scores */
                    var bb = document.getElementById( 'csdt-ctr-before' );
                    bb.textContent      = nd.ctr_before + '%';
                    bb.style.background = scoreColour( nd.ctr_before );
                    var ab = document.getElementById( 'csdt-ctr-after' );
                    ab.textContent      = nd.ctr_after + '%';
                    ab.style.background = scoreColour( nd.ctr_after );
                    /* Update current + new text */
                    document.getElementById( 'csdt-ctr-old-title' ).textContent = nd.old_title || '';
                    document.getElementById( 'csdt-ctr-old-desc' ).textContent  = nd.old_desc  || '';
                    document.getElementById( 'csdt-ctr-new-title' ).textContent = nd.new_title || '';
                    document.getElementById( 'csdt-ctr-new-desc' ).textContent  = nd.new_desc  || '';
                    /* Re-evaluate already-optimised state; preserve any ✓ state already shown */
                    var tOpt = nd.new_title && nd.old_title && nd.new_title.trim() === nd.old_title.trim();
                    var dOpt = nd.new_desc  && nd.old_desc  && nd.new_desc.trim()  === nd.old_desc.trim();
                    var tBtn = document.getElementById( 'csdt-ctr-apply-title' );
                    var dBtn = document.getElementById( 'csdt-ctr-apply-desc' );
                    if ( tBtn && ! tBtn.textContent.startsWith( '✓' ) ) {
                        tBtn.disabled    = tOpt;
                        tBtn.textContent = tOpt ? '✓ Already optimised' : 'Apply title';
                    }
                    if ( dBtn && ! dBtn.textContent.startsWith( '✓' ) ) {
                        dBtn.disabled    = dOpt;
                        dBtn.textContent = dOpt ? '✓ Already optimised' : 'Apply meta';
                    }
                }
            } )
            .catch( function () {} );
        }

        /* Replace listeners by cloning to drop any previous bindings */
        var newApplyTitle = applyTitleBtn.cloneNode( true );
        applyTitleBtn.parentNode.replaceChild( newApplyTitle, applyTitleBtn );
        newApplyTitle.addEventListener( 'click', function () {
            newApplyTitle.disabled    = true;
            newApplyTitle.textContent = '⟳ Applying…';
            clearCache( pid ); // clear immediately so close+reopen before response triggers fresh analysis
            fetch( ajaxUrl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    new URLSearchParams( { action: 'cs_seo_ctr_apply_title', post_id: pid, new_title: d.new_title, nonce: ctrNonce } ),
            } )
            .then( function ( r ) { return r.json(); } )
            .then( function ( res ) {
                if ( res.success ) {
                    newApplyTitle.textContent = '✓ Applied';
                    pendingReloadUrl = res.data.new_url || window.location.href;
                    var msg = res.data.redirected
                        ? '✓ Title + slug updated, 301 redirect added'
                        : '✓ Title updated';
                    var appliedTitle = d.new_title; // capture before rescore overwrites d
                    rescore( function ( nd ) {
                        /* Lock nd so DOM + d reflect the applied state, not the AI's next suggestion.
                           rescore() reads nd AFTER this callback returns, so these values win. */
                        nd.old_title = appliedTitle;
                        nd.new_title = appliedTitle;
                        saveCache( pid, nd );
                        statusEl.textContent = msg + ' — score: ' + nd.ctr_before + '% → ' + nd.ctr_after + '% — apply meta or close to reload';
                        statusEl.style.color = '#1a7a34';
                    } );
                } else {
                    newApplyTitle.disabled    = false;
                    newApplyTitle.textContent = 'Apply title';
                    statusEl.textContent      = '✗ ' + ( res.data || 'Error' );
                    statusEl.style.color      = '#c3372b';
                }
            } )
            .catch( function ( e ) {
                newApplyTitle.disabled    = false;
                newApplyTitle.textContent = 'Apply title';
                statusEl.textContent      = '✗ ' + e.message;
                statusEl.style.color      = '#c3372b';
            } );
        } );

        var newApplyDesc = applyDescBtn.cloneNode( true );
        applyDescBtn.parentNode.replaceChild( newApplyDesc, applyDescBtn );
        newApplyDesc.addEventListener( 'click', function () {
            if ( ! d.new_desc || ! d.new_desc.trim() ) {
                statusEl.textContent = '✗ New description is empty — re-run analysis';
                statusEl.style.color = '#c3372b';
                return;
            }
            newApplyDesc.disabled    = true;
            newApplyDesc.textContent = '⟳ Saving…';
            clearCache( pid ); // clear immediately so close+reopen before response triggers fresh analysis
            fetch( ajaxUrl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    new URLSearchParams( { action: 'cs_seo_save_desc', post_id: pid, desc: d.new_desc, nonce: ctrNonce } ),
            } )
            .then( function ( r ) { return r.json(); } )
            .then( function ( res ) {
                if ( res.success ) {
                    newApplyDesc.textContent = '✓ Saved';
                    var appliedDesc = d.new_desc; // capture before rescore overwrites d
                    rescore( function ( nd ) {
                        /* Lock nd so DOM + d reflect the applied state, not the AI's next suggestion.
                           rescore() reads nd AFTER this callback returns, so these values win. */
                        nd.old_desc = appliedDesc;
                        nd.new_desc = appliedDesc;
                        saveCache( pid, nd );
                        if ( pendingReloadUrl ) {
                            statusEl.textContent = '✓ All changes applied — close to reload';
                        } else {
                            statusEl.textContent = '✓ Meta saved — score: ' + nd.ctr_before + '% → ' + nd.ctr_after + '%';
                        }
                        statusEl.style.color = '#1a7a34';
                    } );
                } else {
                    newApplyDesc.disabled    = false;
                    newApplyDesc.textContent = 'Apply meta';
                    statusEl.textContent     = '✗ ' + ( res.data || 'Error' );
                    statusEl.style.color     = '#c3372b';
                }
            } )
            .catch( function ( e ) {
                newApplyDesc.disabled    = false;
                newApplyDesc.textContent = 'Apply meta';
                statusEl.textContent     = '✗ ' + e.message;
                statusEl.style.color     = '#c3372b';
            } );
        } );

        bg.style.display = 'block';
    }

    function bindCtrPill( bar ) {
        var pill = bar.querySelector( '.csdt-ctr-pill' );
        if ( ! pill || pill._ctrBound ) return;
        pill._ctrBound = true;
        var pid      = parseInt( bar.dataset.postId, 10 );
        var ctrNonce = bar.dataset.ctrNonce || '';

        function runAnalysis() {
            pill.disabled    = true;
            pill.textContent = '⟳ Analysing…';
            fetch( ajaxUrl, {
                method:  'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:    new URLSearchParams( { action: 'cs_seo_ctr_optimise', post_id: pid, nonce: ctrNonce } ),
            } )
            .then( function ( r ) { return r.json(); } )
            .then( function ( data ) {
                pill.disabled    = false;
                pill.textContent = '↑ Optimise for CTR';
                if ( ! data.success ) {
                    alert( 'CTR Optimise error: ' + ( data.data || 'Unknown error' ) );
                    return;
                }
                var d = data.data;
                saveCache( pid, d );
                showResult( d, pid, ctrNonce, false, runAnalysis );
            } )
            .catch( function ( e ) {
                pill.disabled    = false;
                pill.textContent = '↑ Optimise for CTR';
                alert( 'CTR Optimise error: ' + e.message );
            } );
        }

        pill.addEventListener( 'click', function () {
            var cached = loadCache( pid );
            if ( cached ) {
                showResult( cached, pid, ctrNonce, true, runAnalysis );
                return;
            }
            runAnalysis();
        } );
    }

    /* Bind when the bar is available, polling briefly since bindBar() runs async */
    function tryCtrBind() {
        var bar = document.getElementById( 'csdt-gen-bar' );
        if ( bar ) { bindCtrPill( bar ); return; }
        var attempts = 0;
        var t = setInterval( function () {
            bar = document.getElementById( 'csdt-gen-bar' );
            if ( bar || ++attempts > 20 ) { clearInterval( t ); if ( bar ) bindCtrPill( bar ); }
        }, 100 );
    }

    if ( document.readyState === 'loading' ) {
        document.addEventListener( 'DOMContentLoaded', tryCtrBind );
    } else {
        tryCtrBind();
    }

} )();
