<?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

global $wpdb;

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

$group = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->prepare( 'SELECT * FROM %i WHERE group_id = %d', SCHOLAR_SYNC_DB_GROUPS, $group_id ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- %i is the WordPress identifier placeholder (WP 6.2+)
);
if ( ! $group ) {
    wp_die( esc_html__( 'Group not found.', 'scholar-sync' ) );
}

$shortcode        = '[scholar-sync-group id="' . $group_id . '"]';
$existing_page_links = ScholarSync_Admin::get_tracked_page_links( ScholarSync_Admin::group_page_option_name( $group_id ) );
$existing_page_html  = ScholarSync_Admin::render_tracked_page_links_html( $existing_page_links );
$create_page_nonce = wp_create_nonce( 'scholar_sync_create_page' );
$ajax_url          = admin_url( 'admin-ajax.php' );
$back_url   = admin_url( 'admin.php?page=scholar-sync-groups-slug&group-id=' . $group_id );

$public_css_url = SCHOLAR_SYNC_PLUGIN_URL . 'public/css/scholar-sync-public.css';
$admin_css_url  = SCHOLAR_SYNC_PLUGIN_URL . 'admin/css/scholar-sync-admin.css';
$groups_js_url  = SCHOLAR_SYNC_PLUGIN_URL . 'admin/js/scholar-sync-groups.js';
$create_page_js_url = SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-create-page.js';
$author_js_url  = SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-author-display.js';
$admin_js_url   = SCHOLAR_SYNC_PLUGIN_URL . 'admin/js/scholar-sync-admin.js';
$card_js_url    = SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-article-card.js';
$group_public_js_url = SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-group-public.js';
$pagination_js_url = SCHOLAR_SYNC_PLUGIN_URL . 'public/js/scholar-sync-pagination.js';
$rest_url       = rest_url( 'sclr/v1/' );
$rest_nonce     = wp_create_nonce( 'wp_rest' );
$is_feed        = ( $group->view_type === 'feed' );

// Persisted group settings — the group's actual saved settings (group_edit_view.php /
// save_group.php), not a separate/disconnected store. Previously this page read grid options
// from standalone wp_options keys that nothing else ever wrote to, so they always fell back to
// hardcoded defaults; seeding directly from the group's real settings fixes that.
$group_settings = $group->settings ? json_decode( $group->settings, true ) : array();
if ( ! is_array( $group_settings ) ) {
    $group_settings = array();
}
$show_article_image = ! empty( $group_settings['show_article_image'] );
$columns             = isset( $group_settings['columns'] )     ? (int) $group_settings['columns']     : 3;
$image_shape         = isset( $group_settings['image_shape'] ) ? $group_settings['image_shape']       : 'circle';
$show_shadow         = ! array_key_exists( 'shadow', $group_settings ) || ! empty( $group_settings['shadow'] );
$show_position       = ! array_key_exists( 'show_position', $group_settings )      || ! empty( $group_settings['show_position'] );
$show_institution    = ! array_key_exists( 'show_institution', $group_settings )   || ! empty( $group_settings['show_institution'] );
$show_tags           = ! array_key_exists( 'show_tags', $group_settings )          || ! empty( $group_settings['show_tags'] );
$max_tags            = isset( $group_settings['max_tags'] ) ? (int) $group_settings['max_tags'] : 3;
$show_publications   = ! array_key_exists( 'show_publications', $group_settings )  || ! empty( $group_settings['show_publications'] );
$show_profile_link   = ! array_key_exists( 'show_profile_link', $group_settings )  || ! empty( $group_settings['show_profile_link'] );

// Enqueue all page assets via the WordPress API before any HTML is output.
// wp_print_styles()/wp_print_scripts() below will output them in the correct positions.
wp_enqueue_style( 'scholar-sync-public',  $public_css_url,                                          array(), SCHOLAR_SYNC_VERSION );
wp_enqueue_style( 'scholar-sync-admin',   $admin_css_url,                                           array(), SCHOLAR_SYNC_VERSION );
wp_enqueue_style( 'scholar-sync-preview', plugin_dir_url( __FILE__ ) . 'css/scholar-sync-preview.css', array(), SCHOLAR_SYNC_VERSION );

wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'scholar-sync',              $admin_js_url,      array( 'jquery' ),                          SCHOLAR_SYNC_VERSION, true );
wp_enqueue_script( 'scholar-sync-pagination',   $pagination_js_url, array( 'jquery' ),                          SCHOLAR_SYNC_VERSION, true );
wp_enqueue_script( 'scholar-sync-article-card', $card_js_url,       array( 'jquery' ),                          SCHOLAR_SYNC_VERSION, true );
wp_enqueue_script( 'scholar-sync-group-public', $group_public_js_url, array( 'jquery' ),                        SCHOLAR_SYNC_VERSION, true );
if ( $is_feed ) {
    wp_enqueue_script( 'scholar-sync-author-display', $author_js_url, array( 'jquery' ), SCHOLAR_SYNC_VERSION, true );
}
// Depends on scholar-sync-group-public for the shared scholarSyncRenderGroupCard() renderer
// (same function the live public grid uses), so the preview panel never drifts from reality.
wp_enqueue_script( 'scholar-sync-groups', $groups_js_url, array( 'scholar-sync', 'scholar-sync-group-public' ), SCHOLAR_SYNC_VERSION, true );
// Shared Create Page handler; reads the scholarSync* globals (defined inline on
// scholar-sync-groups below) at click time, so no dependency ordering is required.
wp_enqueue_script( 'scholar-sync-create-page', $create_page_js_url, array(), SCHOLAR_SYNC_VERSION, true );

// scholar_sync_public_object must be defined before scholar-sync-author-display.js runs,
// so attach it inline to that handle. All other vars go before scholar-sync-groups.
if ( $is_feed ) {
    wp_add_inline_script(
        'scholar-sync-author-display',
        'var scholar_sync_public_object = ' . wp_json_encode( array(
            'site_url'   => SCHOLAR_SYNC_SITE_URL,
            'rest_nonce' => $rest_nonce,
            'plugin_url' => SCHOLAR_SYNC_PLUGIN_URL,
        ) ) . ';',
        'before'
    );
}

$inline_data  = 'var scholar_sync_ajax_object = ' . wp_json_encode( array(
    'rest'       => $rest_url,
    'rest_nonce' => $rest_nonce,
    'url'        => site_url(),
    'plugin_url' => SCHOLAR_SYNC_PLUGIN_URL,
) ) . ';';
if ( ! $is_feed ) {
    $inline_data .= 'var scholar_sync_public_object = ' . wp_json_encode( array(
        'site_url'   => SCHOLAR_SYNC_SITE_URL,
        'rest_nonce' => $rest_nonce,
        'plugin_url' => SCHOLAR_SYNC_PLUGIN_URL,
    ) ) . ';';
}
$inline_data .= 'var scholarSyncGroupId = ' . (int) $group_id . ';';
$inline_data .= 'var scholarSyncViewType = ' . wp_json_encode( $group->view_type ) . ';';
$inline_data .= 'var scholarSyncAjaxUrl = ' . wp_json_encode( $ajax_url ) . ';';
$inline_data .= 'var scholarSyncCreatePageNonce = ' . wp_json_encode( $create_page_nonce ) . ';';
wp_add_inline_script( 'scholar-sync-groups', $inline_data, 'before' );

// Panel toggle IIFE (pure DOM, no jQuery dependency).
$panel_toggle_js = '(function(){var panel=document.getElementById("wps-panel");var toggle=document.getElementById("wps-toggle");var closeBtn=document.getElementById("wps-panel-close");function openPanel(){panel.classList.remove("is-closed");toggle.classList.remove("is-visible");}function closePanel(){panel.classList.add("is-closed");toggle.classList.add("is-visible");}if(closeBtn){closeBtn.addEventListener("click",closePanel);}if(toggle){toggle.addEventListener("click",openPanel);}})();';
wp_add_inline_script( 'scholar-sync-groups', $panel_toggle_js, 'after' );
?>
<!DOCTYPE html>
<html class="scholar-sync-author-preview-html">
<head>
    <title><?php echo esc_html( $group->name ); ?> — Preview</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_print_styles(); ?>
</head>
<body class="scholar-sync-author-preview-body scholar-sync-group-preview-body">

    <!-- Toggle button (shown when panel is closed) -->
    <button id="wps-toggle" title="<?php esc_attr_e( 'Open display options', 'scholar-sync' ); ?>">
        <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
            <rect y="3"  width="18" height="2" rx="1" fill="currentColor"/>
            <rect y="8"  width="18" height="2" rx="1" fill="currentColor"/>
            <rect y="13" width="18" height="2" rx="1" fill="currentColor"/>
        </svg>
        <?php esc_html_e( 'Display Options', 'scholar-sync' ); ?>
    </button>

    <!-- Sliding panel -->
    <div id="wps-panel">

        <div class="wps-panel-header">
            <a href="<?php echo esc_url( $back_url ); ?>" class="wps-panel-back"
               title="<?php esc_attr_e( 'Back to group', 'scholar-sync' ); ?>">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M9 1.5L1.5 9L9 16.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <path d="M1.5 9H16.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </a>

            <span class="wps-panel-title"><?php esc_html_e( 'Display Options', 'scholar-sync' ); ?></span>

            <button class="wps-panel-close" id="wps-panel-close"
                    title="<?php esc_attr_e( 'Close panel', 'scholar-sync' ); ?>">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </button>
        </div>

        <div class="wps-panel-body">

            <?php if ( $is_feed ): ?>

                <label class="wps-checkbox-label">
                    <input type="checkbox" id="preview-show-search" class="scholar-sync-preview-control" checked>
                    <?php esc_html_e( 'Show search bar', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-cited-by" class="scholar-sync-preview-control" checked>
                    <?php esc_html_e( 'Show cited-by count', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-co-authors" class="scholar-sync-preview-control" checked>
                    <?php esc_html_e( 'Show co-authors', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label wps-checkbox-label-spaced">
                    <input type="checkbox" id="preview-show-co-author-photos" class="scholar-sync-preview-control" checked>
                    <?php esc_html_e( 'Show co-author photos', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label wps-checkbox-label-spaced">
                    <input type="checkbox" id="preview-show-article-image" class="scholar-sync-preview-control" <?php checked( $show_article_image ); ?>>
                    <?php esc_html_e( 'Show article images', 'scholar-sync' ); ?>
                </label>
                <label style="display:block;margin-top:16px;font-weight:600;color:#1d2327;font-size:13px;"><?php esc_html_e( 'Sort by', 'scholar-sync' ); ?></label>
                <select id="preview-sort-by" class="scholar-sync-preview-control" style="width:100%;margin-top:4px;">
                    <option value="year"><?php esc_html_e( 'Year', 'scholar-sync' ); ?></option>
                    <option value="cited_by"><?php esc_html_e( 'Cited by', 'scholar-sync' ); ?></option>
                </select>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-image-shadow" class="scholar-sync-preview-control" checked>
                    <?php esc_html_e( 'Show image shadow', 'scholar-sync' ); ?>
                </label>
                <label style="display:block;margin-top:16px;font-weight:600;color:#1d2327;font-size:13px;"><?php esc_html_e( 'Image Shape', 'scholar-sync' ); ?></label>
                <select id="preview-image-shape" class="scholar-sync-preview-control" style="width:100%;margin-top:4px;">
                    <option value="circle"><?php esc_html_e( 'Circle', 'scholar-sync' ); ?></option>
                    <option value="square"><?php esc_html_e( 'Square', 'scholar-sync' ); ?></option>
                </select>

            <?php else: ?>

                <label for="preview-columns"><?php esc_html_e( 'Columns', 'scholar-sync' ); ?></label>
                <div class="wps-columns-row">
                    <input type="range" id="preview-columns" class="scholar-sync-preview-control"
                           min="1" max="4" value="<?php echo (int) $columns; ?>"
                           oninput="document.getElementById('preview-columns-val').textContent=this.value">
                    <span class="wps-columns-badge" id="preview-columns-val"><?php echo (int) $columns; ?></span>
                </div>

                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-position" class="scholar-sync-preview-control"
                           <?php checked( $show_position ); ?>>
                    <?php esc_html_e( 'Show position / title', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-institution" class="scholar-sync-preview-control"
                           <?php checked( $show_institution ); ?>>
                    <?php esc_html_e( 'Show institution', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-tags" class="scholar-sync-preview-control"
                           <?php checked( $show_tags ); ?>>
                    <?php esc_html_e( 'Show research tags', 'scholar-sync' ); ?>
                </label>
                <label style="display:block;margin-top:12px;">
                    <?php esc_html_e( 'Tags before "+N more":', 'scholar-sync' ); ?>
                    <input type="number" id="preview-max-tags" class="scholar-sync-preview-control"
                           min="1" max="10" value="<?php echo (int) $max_tags; ?>" style="width:60px;">
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-publications" class="scholar-sync-preview-control"
                           <?php checked( $show_publications ); ?>>
                    <?php esc_html_e( 'Show publication count', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-show-profile-link" class="scholar-sync-preview-control"
                           <?php checked( $show_profile_link ); ?>>
                    <?php esc_html_e( 'Show "View Profile" link', 'scholar-sync' ); ?>
                </label>
                <label class="wps-checkbox-label" style="margin-top:12px;">
                    <input type="checkbox" id="preview-shadow" class="scholar-sync-preview-control"
                           <?php checked( $show_shadow ); ?>>
                    <?php esc_html_e( 'Show image shadow', 'scholar-sync' ); ?>
                </label>

                <label for="preview-image-shape" style="margin-top:14px;"><?php esc_html_e( 'Image Shape', 'scholar-sync' ); ?></label>
                <select id="preview-image-shape" class="scholar-sync-preview-control">
                    <option value="circle"    <?php selected( $image_shape, 'circle' ); ?>><?php esc_html_e( 'Circle', 'scholar-sync' ); ?></option>
                    <option value="square"    <?php selected( $image_shape, 'square' ); ?>><?php esc_html_e( 'Square', 'scholar-sync' ); ?></option>
                    <option value="rectangle" <?php selected( $image_shape, 'rectangle' ); ?>><?php esc_html_e( 'Rectangle (portrait)', 'scholar-sync' ); ?></option>
                </select>

            <?php endif; ?>

            <div class="wps-shortcode-box">
                <label><?php esc_html_e( 'Shortcode', 'scholar-sync' ); ?></label>
                <input type="text" id="group-shortcode-display" readonly
                       value="<?php echo esc_attr( $shortcode ); ?>">
                <button type="button" id="copy-group-shortcode" class="wps-copy-btn">
                    <?php esc_html_e( 'Copy Shortcode', 'scholar-sync' ); ?>
                </button>
            </div>

            <div class="wps-create-page-box">
                <label><?php esc_html_e( 'Create a page', 'scholar-sync' ); ?></label>
                <input type="text" id="wps-page-title"
                       placeholder="<?php esc_attr_e( 'Page title', 'scholar-sync' ); ?>"
                       value="<?php echo esc_attr( $group->name ); ?>">
                <button type="button" id="wps-create-page-btn" class="wps-copy-btn" style="background:#1a1f36;">
                    + <?php esc_html_e( 'Create Page', 'scholar-sync' ); ?>
                </button>
                <div id="wps-create-page-result" class="wps-create-page-result<?php echo $existing_page_html ? ' is-visible' : ''; ?>"><?php echo wp_kses_post( $existing_page_html ); ?></div>
            </div>

        </div><!-- /.wps-panel-body -->
    </div><!-- /#wps-panel -->

    <!-- Main preview area -->
    <div id="wps-main">

        <?php if ( $is_feed ): ?>

            <!-- Feed: same HTML structure as the author display page -->
            <div class="scholar-sync-container"
                 data-entity-id="<?php echo (int) $group_id; ?>"
                 data-rest-url="<?php echo esc_attr( $rest_url . 'group-display' ); ?>"
                 data-display-search="1"
                 data-display-cited-by="1"
                 data-display-co-authors="1"
                 data-display-co-author-photos="1"
                 data-display-article-image="<?php echo $show_article_image ? '1' : '0'; ?>"
                 data-image-shape="circle"
                 data-image-shadow="1">

                <div class="scholar-sync-search-row">
                    <div class="scholar-sync-search-container">
                        <input type="text" id="scholar-sync-search"
                               placeholder="<?php esc_attr_e( 'Search...', 'scholar-sync' ); ?>">
                        <button type="button" id="scholar-sync-clear-search">
                            <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M1 1L11 11M11 1L1 11" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
                        </button>
                    </div>
                    <button type="button" id="scholar-sync-search-btn">
                        <?php esc_html_e( 'Search', 'scholar-sync' ); ?>
                    </button>
                </div>

                <div class="scholar-sync-controls-bar">
                    <span class="scholar-sync-results-info"></span>
                    <div class="scholar-sync-perpage-container">
                        <?php esc_html_e( 'Per page:', 'scholar-sync' ); ?>
                        <select id="scholar-sync-per-page">
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                </div>

                <div class="wps-feed-list"></div>
                <div class="wps-author-pagination"></div>
            </div>

        <?php else: ?>

            <!-- Grid: loaded dynamically by scholar-sync-groups.js -->
            <div id="scholar-sync-group-preview-container"
                 data-group-id="<?php echo (int) $group_id; ?>"
                 data-view-type="<?php echo esc_attr( $group->view_type ); ?>">
                <p><?php esc_html_e( 'Loading preview…', 'scholar-sync' ); ?></p>
            </div>

        <?php endif; ?>
    </div>

    <?php wp_print_scripts(); ?>
</body>
</html>
