<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- admin view partial; local variables are not global
// phpcs:disable WordPress.Security.NonceVerification -- read-only admin preview; capability check handled by admin menu registration
// phpcs:disable WordPress.Security.ValidatedSanitizedInput -- GET params sanitized with absint/sanitize_key/esc_url_raw

function scholar_sync_display_instruction_step3() {
    $option_name = 'scholar-sync-add-author-step3';
    if ( get_option( $option_name, false ) === false ) {
        $title   = wp_json_encode( __( 'Step 3/3 — Preview', 'scholar-sync' ) );
        $message = wp_json_encode(
            '<ul style="margin:8px 0 0 16px;padding:0;list-style:disc;">' .
            '<li>' . sprintf(
                /* translators: %1$s and %2$s are opening/closing <b> tags around "Display Options". */
                esc_html__( 'Use the %1$sDisplay Options%2$s on the left to configure the layout.', 'scholar-sync' ),
                '<b>',
                '</b>'
            ) . '</li>' .
            '<li>' . sprintf(
                /* translators: %1$s and %2$s are opening/closing <b> tags around "Create Page". */
                esc_html__( 'Click %1$sCreate Page%2$s to generate a page with the shortcode embedded, or copy and paste the shortcode manually into any page.', 'scholar-sync' ),
                '<b>',
                '</b>'
            ) . '</li>' .
            '<li>' . esc_html__( 'Click the back arrow at the top left to return to the author settings.', 'scholar-sync' ) . '</li>' .
            '</ul>'
        );
        $point   = wp_json_encode( array( 'x' => '80%', 'y' => '5%' ) );
        $key     = wp_json_encode( $option_name );
        $rest    = wp_json_encode( esc_url_raw( rest_url( 'sclr/v1/' ) ) );
        $nonce   = wp_json_encode( wp_create_nonce( 'wp_rest' ) );

        $instruction_js = '(function(){
    var title=' . $title . ', msg=' . $message . ', point=' . $point . ', key=' . $key . ', rest=' . $rest . ', nonce=' . $nonce . ';
    if (typeof openInstructions === "function") {
        openInstructions(title, msg, point, key);
        return;
    }
    var isMobile = window.innerWidth < 782;
    var win = document.createElement("div");
    win.id = "instruction-window";
    var hdr = document.createElement("div");
    hdr.id = "instruction-header";
    var ttl = document.createElement("span");
    ttl.id = "instruction-title";
    ttl.textContent = title;
    var closeBtn = document.createElement("button");
    closeBtn.id = "close-btn";
    closeBtn.textContent = "×";
    hdr.appendChild(ttl);
    hdr.appendChild(closeBtn);
    var bdy = document.createElement("div");
    bdy.id = "instruction-body";
    bdy.innerHTML = msg;
    var ftr = document.createElement("div");
    ftr.id = "instruction-footer";
    ftr.style.cssText = "padding:10px;display:flex;align-items:center;";
    var lbl = document.createElement("label");
    lbl.style.cssText = "display:flex;align-items:center;color:gray;font-size:12px;";
    var chk = document.createElement("input");
    chk.type = "checkbox";
    chk.id = "do-not-show";
    chk.style.marginRight = "5px";
    lbl.appendChild(chk);
    lbl.appendChild(document.createTextNode("Don’t show this message again"));
    ftr.appendChild(lbl);
    win.appendChild(hdr);
    win.appendChild(bdy);
    win.appendChild(ftr);
    if (isMobile) {
        win.style.cssText = "position:relative;top:auto;left:auto;width:100%;box-sizing:border-box;margin-top:12px;";
        document.body.appendChild(win);
    } else {
        win.style.position = "absolute";
        document.body.appendChild(win);
        var calcPos = function(value, maxSize, offset) {
            if (typeof value === "string" && value.slice(-1) === "%") {
                return Math.min((parseFloat(value) / 100) * maxSize, maxSize - offset);
            }
            return Math.min(parseInt(value, 10), maxSize - offset);
        };
        win.style.left = calcPos(point.x, window.innerWidth,  win.offsetWidth)  + "px";
        win.style.top  = calcPos(point.y, window.innerHeight, win.offsetHeight) + "px";
        var isDragging = false, dragX, dragY;
        hdr.addEventListener("mousedown", function(e) {
            isDragging = true;
            dragX = e.clientX - win.offsetLeft;
            dragY = e.clientY - win.offsetTop;
            document.body.style.userSelect = "none";
        });
        document.addEventListener("mousemove", function(e) {
            if (isDragging) {
                win.style.left = (e.clientX - dragX) + "px";
                win.style.top  = (e.clientY - dragY)  + "px";
            }
        });
        document.addEventListener("mouseup", function() {
            isDragging = false;
            document.body.style.userSelect = "";
        });
    }
    closeBtn.addEventListener("click", function() {
        if (chk.checked) {
            fetch(rest + "add-option?option=" + encodeURIComponent(key) + "&value=1",
                  {headers:{"X-WP-Nonce":nonce}}).catch(function(){});
        }
        win.style.display = "none";
    });
})();';
        wp_print_inline_script_tag( $instruction_js );
    }
}

// single author
if ( ! current_user_can( 'edit_others_posts' ) ) {
    wp_die( esc_html__( 'You do not have permission to access this page.', 'scholar-sync' ) );
}
check_admin_referer( 'scholar_sync_preview' );

$author_id = isset( $_GET['author-id'] ) ? (int) $_GET['author-id'] : 0;
if ( ! $author_id ) {
    wp_die( esc_html__( 'Author ID is required.', 'scholar-sync' ) );
}

require_once SCHOLAR_SYNC_PLUGIN_DIR . '/includes/class-scholar-sync-author-display.php';

// All display options start as true; sidebar JS toggles them live.
// The constructor signature is: __construct( $author_id, $display_header, $display_search, $display_cited_by, $display_co_authors, $image_shape, $image_shadow, $display_article_image, $display_co_author_photos )
$image_shape    = isset( $_GET['image_shape'] ) ? sanitize_key( $_GET['image_shape'] ) : 'circle';
$image_shadow   = ! ( isset( $_GET['shadow'] ) && $_GET['shadow'] === '0' );
$author_preview = new ScholarSync_Author_Display( $author_id, true, true, true, true, $image_shape, $image_shadow );
$page_title     = __( 'Preview', 'scholar-sync' );

$show_step3 = isset( $_GET['is-new'] );

// Enqueue admin CSS here (admin_enqueue_scripts fires after load-{hook}, so the
// normal enqueue_styles() callback never runs for this standalone page).
wp_enqueue_style( 'scholar-sync', plugin_dir_url( __FILE__ ) . 'css/scholar-sync-admin.css', array(), SCHOLAR_SYNC_VERSION, 'all' );

// Call display() before outputting any HTML so that wp_enqueue_*() calls inside the
// display class register their assets before wp_print_styles()/wp_print_scripts() fire.
$author_preview->setPreviewMode( true );
$display_html = $author_preview->display(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted plugin-generated HTML

// Output the standalone page structure with assets going through the WordPress enqueue API.
echo '<!DOCTYPE html><html class="scholar-sync-author-preview-html"><head>';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<title>' . esc_html( $page_title ) . '</title>';
wp_print_styles();
echo '</head><body class="scholar-sync-author-preview-body">';
echo $display_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted plugin-generated HTML
wp_print_scripts();
if ( ! empty( $show_step3 ) ) {
    scholar_sync_display_instruction_step3();
}
echo '</body></html>';
