<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class IntegratePalace_Properties_Dashboard {

    public function display() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'integrate-palace-properties' ) );
        }

        // ─── Gather Data ────────────────────────────────────────────
        $status_html    = get_option( 'integrate_palace_properties_webhook_status', '' );
        $is_connected   = strpos( $status_html, 'wh_connected' ) !== false;
        $template       = get_option( 'ipp_select_template', 'palace-property' );
        $last_sync      = get_option( 'ipp_last_sync_time', '' );
        $last_sync_count = get_option( 'ipp_last_sync_count', 0 );
        $webhook_url    = get_option( 'integrate_palace_properties_webhook_url', '' );
        $blog_id        = get_option( 'integrate_palace-palace-unique-id', '' );
        $sub_key        = get_option( 'integrate_palace_properties_subscription_key', '' );
        $slug           = get_option( 'integrate_palace_properties_slug', 'palace-property' );
        $default_fields = IntegratePalace_Properties_Settings::get_default_display_fields();
        $display_fields = get_option( 'ipp_display_fields', $default_fields );
        if ( empty( $display_fields ) ) $display_fields = $default_fields; // treat empty as "all defaults"
        $sync_archived  = get_option( 'ipp_sync_archived', 'no' );

        // Property counts
        $counts    = wp_count_posts( 'palace-properties' );
        $published = $counts->publish ?? 0;
        $draft     = $counts->draft ?? 0;
        $trash     = $counts->trash ?? 0;
        $hidden    = 0;
        $locked    = 0;

        // Count hidden/locked
        $hidden_q = new WP_Query( array( 'post_type' => 'palace-properties', 'meta_key' => 'ipp_hide_property', 'meta_value' => '1', 'posts_per_page' => -1, 'fields' => 'ids' ) );
        $hidden = $hidden_q->found_posts;
        $locked_q = new WP_Query( array( 'post_type' => 'palace-properties', 'meta_key' => 'ipp_lock_updates', 'meta_value' => '1', 'posts_per_page' => -1, 'fields' => 'ids' ) );
        $locked = $locked_q->found_posts;

        // Gallery stats
        $with_images = 0;
        $total_images = 0;
        $gallery_posts = get_posts( array( 'post_type' => 'palace-properties', 'posts_per_page' => -1, 'fields' => 'ids', 'meta_query' => array( array( 'key' => 'integrate_palace_gallery', 'compare' => 'EXISTS' ) ) ) );
        foreach ( $gallery_posts as $gp_id ) {
            $gallery = get_post_meta( $gp_id, 'integrate_palace_gallery', true );
            if ( is_array( $gallery ) && count( $gallery ) > 0 ) {
                $with_images++;
                $total_images += count( $gallery );
            }
        }

        // Taxonomy stats
        $status_terms  = get_terms( array( 'taxonomy' => 'palace-property-status', 'hide_empty' => false ) );
        $type_terms    = get_terms( array( 'taxonomy' => 'palace-property-type', 'hide_empty' => false ) );
        $region_terms  = get_terms( array( 'taxonomy' => 'palace-property-region', 'hide_empty' => true ) );
        $mgmt_terms    = get_terms( array( 'taxonomy' => 'palace-property-management', 'hide_empty' => true ) );

        // Recent properties
        $recent_props = get_posts( array( 'post_type' => 'palace-properties', 'posts_per_page' => 5, 'orderby' => 'modified', 'order' => 'DESC' ) );

        // Plugin info
        $plugin_version = defined( 'INTEGRATE_PALACE_P_VERSION' ) ? INTEGRATE_PALACE_P_VERSION : '?';
        $archive_url    = get_post_type_archive_link( 'palace-properties' );
        $rest_url       = rest_url( 'palace-properties/v1/properties' );
        $api_base       = defined( 'IPP_API_URL' ) ? IPP_API_URL : 'https://wp-palace.kiwibrain.co.nz';

        // Count pending gallery cron events (lightweight — no cleanup on page load)
        $pending_gallery = 0;
        $crons = _get_cron_array();
        if ( is_array( $crons ) ) {
            foreach ( $crons as $ts => $hooks ) {
                if ( isset( $hooks['update_integrate_palace_gallery'] ) ) {
                    $pending_gallery += count( $hooks['update_integrate_palace_gallery'] );
                }
            }
        }
        ?>

        <style>
            .ippd { max-width: 1200px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
            .ippd-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px; flex-wrap: wrap; gap: 12px; }
            .ippd-header h1 { font-size: 24px; font-weight: 700; margin: 0; display: flex; align-items: center; gap: 10px; }
            .ippd-header h1 .dashicons { font-size: 28px; width: 28px; height: 28px; color: #2563eb; }
            .ippd-version { font-size: 12px; color: #94a3b8; background: #f1f5f9; padding: 3px 10px; border-radius: 20px; font-weight: 500; }
            .ippd-actions { display: flex; gap: 8px; }
            .ippd-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; margin-bottom: 24px; }
            .ippd-grid--wide { grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); }
            .ippd-grid--2 { grid-template-columns: 1fr 1fr; }
            @media (max-width: 782px) { .ippd-grid--2 { grid-template-columns: 1fr; } }

            .ippd-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden; }
            .ippd-card__head { padding: 14px 18px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; }
            .ippd-card__head h3 { margin: 0; font-size: 13px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: .04em; }
            .ippd-card__head .dashicons { color: #94a3b8; font-size: 18px; width: 18px; height: 18px; }
            .ippd-card__body { padding: 18px; }

            /* Stat cards */
            .ippd-stat { text-align: center; padding: 24px 18px; }
            .ippd-stat__number { font-size: 36px; font-weight: 800; color: #1e293b; line-height: 1; margin-bottom: 6px; }
            .ippd-stat__number--accent { color: #2563eb; }
            .ippd-stat__number--success { color: #059669; }
            .ippd-stat__number--warning { color: #d97706; }
            .ippd-stat__number--danger { color: #dc2626; }
            .ippd-stat__label { font-size: 13px; color: #64748b; font-weight: 500; }
            .ippd-stat__sub { font-size: 11px; color: #94a3b8; margin-top: 4px; }

            /* KV rows */
            .ippd-kv { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid #f8fafc; font-size: 13px; }
            .ippd-kv:last-child { border-bottom: none; }
            .ippd-kv__label { color: #64748b; display: flex; align-items: center; gap: 6px; }
            .ippd-kv__label .dashicons { font-size: 14px; width: 14px; height: 14px; color: #94a3b8; }
            .ippd-kv__value { font-weight: 600; color: #1e293b; max-width: 55%; text-align: right; word-break: break-all; }
            .ippd-kv__value code { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 12px; font-weight: 500; }
            .ippd-kv__value a { color: #2563eb; text-decoration: none; }
            .ippd-kv__value a:hover { text-decoration: underline; }

            /* Badges */
            .ippd-badge { display: inline-flex; align-items: center; gap: 5px; padding: 3px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; }
            .ippd-badge--green { background: #dcfce7; color: #166534; }
            .ippd-badge--red { background: #fee2e2; color: #991b1b; }
            .ippd-badge--yellow { background: #fef3c7; color: #92400e; }
            .ippd-badge--blue { background: #dbeafe; color: #1e40af; }
            .ippd-badge--gray { background: #f1f5f9; color: #475569; }
            .ippd-dot { width: 7px; height: 7px; border-radius: 50%; display: inline-block; }
            .ippd-dot--green { background: #22c55e; }
            .ippd-dot--red { background: #ef4444; }

            /* Breakdown bars */
            .ippd-bar { margin-bottom: 10px; }
            .ippd-bar__header { display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px; }
            .ippd-bar__label { color: #374151; font-weight: 500; }
            .ippd-bar__count { color: #64748b; font-weight: 600; }
            .ippd-bar__track { height: 6px; background: #f1f5f9; border-radius: 3px; overflow: hidden; }
            .ippd-bar__fill { height: 100%; border-radius: 3px; transition: width .3s ease; }
            .ippd-bar__fill--blue { background: #3b82f6; }
            .ippd-bar__fill--green { background: #22c55e; }
            .ippd-bar__fill--purple { background: #8b5cf6; }
            .ippd-bar__fill--orange { background: #f59e0b; }

            /* Recent list */
            .ippd-recent { list-style: none; margin: 0; padding: 0; }
            .ippd-recent li { display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f8fafc; font-size: 13px; }
            .ippd-recent li:last-child { border-bottom: none; }
            .ippd-recent__title { color: #1e293b; font-weight: 500; max-width: 60%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
            .ippd-recent__title a { color: #1e293b; text-decoration: none; }
            .ippd-recent__title a:hover { color: #2563eb; }
            .ippd-recent__meta { font-size: 11px; color: #94a3b8; }

            /* Sync button */
            #ipp-sync-now .dashicons { vertical-align: middle; margin-top: -1px; }
            #ipp-sync-now.syncing .dashicons { animation: ippd-spin 1s linear infinite; }
            @keyframes ippd-spin { to { transform: rotate(360deg); } }
            .ippd-sync-msg { font-size: 13px; color: #64748b; margin-left: 8px; }
            .ippd-sync-msg.success { color: #166534; }
            .ippd-sync-msg.error { color: #991b1b; }
        </style>

        <div class="wrap ippd">

            <!-- Header -->
            <div class="ippd-header">
                <h1>
                    <span class="dashicons dashicons-admin-home"></span>
                    <?php esc_html_e( 'Palace Properties', 'integrate-palace-properties' ); ?>
                    <span class="ippd-version">v<?php echo esc_html( $plugin_version ); ?></span>
                </h1>
                <div class="ippd-actions">
                    <button type="button" id="ipp-sync-now" class="button button-primary" <?php echo $is_connected ? '' : 'disabled'; ?>>
                        <span class="dashicons dashicons-update"></span> <?php esc_html_e( 'Sync Now', 'integrate-palace-properties' ); ?>
                    </button>
                    <button type="button" id="ipp-resync-galleries" class="button">
                        <span class="dashicons dashicons-format-gallery" style="margin-top:3px;"></span> <?php esc_html_e( 'Resync Galleries', 'integrate-palace-properties' ); ?>
                    </button>
                    <a href="<?php echo esc_url( $archive_url ); ?>" class="button" target="_blank">
                        <span class="dashicons dashicons-external" style="margin-top:3px;"></span> <?php esc_html_e( 'View Listings', 'integrate-palace-properties' ); ?>
                    </a>
                    <span id="ipp-sync-status" class="ippd-sync-msg"></span>
                </div>
            </div>

            <?php
            // Compute what's visible on frontend
            $active_count = 0;
            $inactive_count = 0;
            if ( ! empty( $status_terms ) && ! is_wp_error( $status_terms ) ) {
                foreach ( $status_terms as $st ) {
                    if ( strtolower( $st->name ) === 'active' ) $active_count = $st->count;
                    if ( strtolower( $st->name ) === 'inactive' ) $inactive_count = $st->count;
                }
            }
            $visible_on_frontend = ( $sync_archived === 'yes' ) ? ( $published - $hidden ) : ( $active_count - $hidden );
            if ( $visible_on_frontend < 0 ) $visible_on_frontend = 0;
            ?>
            <!-- Row 1: Key Stats -->
            <div class="ippd-grid">
                <div class="ippd-card">
                    <div class="ippd-stat">
                        <div class="ippd-stat__number ippd-stat__number--accent"><?php echo esc_html( $visible_on_frontend ); ?></div>
                        <div class="ippd-stat__label"><?php esc_html_e( 'Visible on Frontend', 'integrate-palace-properties' ); ?></div>
                        <div class="ippd-stat__sub">
                            <?php echo esc_html( $published ); ?> total
                            · <?php echo esc_html( $active_count ); ?> active
                            · <?php echo esc_html( $inactive_count ); ?> inactive
                            <?php if ( $hidden > 0 ) : ?>
                                · <?php echo esc_html( $hidden ); ?> hidden
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="ippd-card">
                    <div class="ippd-stat">
                        <div class="ippd-stat__number ippd-stat__number--success"><?php echo esc_html( $with_images ); ?></div>
                        <div class="ippd-stat__label"><?php esc_html_e( 'With Gallery Images', 'integrate-palace-properties' ); ?></div>
                        <div class="ippd-stat__sub"><?php echo esc_html( $total_images ); ?> total images</div>
                    </div>
                </div>
                <div class="ippd-card">
                    <div class="ippd-stat">
                        <div class="ippd-stat__number <?php echo $locked > 0 ? 'ippd-stat__number--warning' : ''; ?>"><?php echo esc_html( $locked ); ?></div>
                        <div class="ippd-stat__label"><?php esc_html_e( 'Locked Properties', 'integrate-palace-properties' ); ?></div>
                        <div class="ippd-stat__sub">Protected from sync updates</div>
                    </div>
                </div>
                <div class="ippd-card">
                    <div class="ippd-stat">
                        <div class="ippd-stat__number <?php echo $pending_gallery > 0 ? 'ippd-stat__number--warning' : 'ippd-stat__number--success'; ?>"><?php echo esc_html( $pending_gallery ); ?></div>
                        <div class="ippd-stat__label"><?php esc_html_e( 'Pending Gallery Syncs', 'integrate-palace-properties' ); ?></div>
                        <div class="ippd-stat__sub">Cron events queued</div>
                    </div>
                </div>
            </div>

            <!-- Row 2: Connection + Sync Info -->
            <div class="ippd-grid ippd-grid--2">

                <!-- Connection & Webhook -->
                <div class="ippd-card">
                    <div class="ippd-card__head">
                        <h3><span class="dashicons dashicons-cloud"></span> <?php esc_html_e( 'Connection & Webhook', 'integrate-palace-properties' ); ?></h3>
                        <span class="ippd-badge <?php echo $is_connected ? 'ippd-badge--green' : 'ippd-badge--red'; ?>">
                            <span class="ippd-dot <?php echo $is_connected ? 'ippd-dot--green' : 'ippd-dot--red'; ?>"></span>
                            <?php echo $is_connected ? esc_html__( 'Connected', 'integrate-palace-properties' ) : esc_html__( 'Disconnected', 'integrate-palace-properties' ); ?>
                        </span>
                    </div>
                    <div class="ippd-card__body">
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-admin-links"></span> API Endpoint</span>
                            <span class="ippd-kv__value"><code><?php echo esc_html( parse_url( $api_base, PHP_URL_HOST ) ?: $api_base ); ?></code></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-admin-site"></span> Webhook URL</span>
                            <span class="ippd-kv__value" title="<?php echo esc_attr( $webhook_url ); ?>"><?php echo $webhook_url ? '<code>' . esc_html( wp_parse_url( $webhook_url, PHP_URL_PATH ) ) . '</code>' : '<em>Not set</em>'; ?></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-nametag"></span> Blog ID</span>
                            <span class="ippd-kv__value"><code><?php echo esc_html( substr( $blog_id, 0, 8 ) . '...' ); ?></code></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-lock"></span> Subscription Key</span>
                            <span class="ippd-kv__value"><?php echo $sub_key ? '<span class="ippd-badge ippd-badge--green">Configured</span>' : '<span class="ippd-badge ippd-badge--red">Missing</span>'; ?></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-shield"></span> Webhook Auth</span>
                            <span class="ippd-kv__value"><?php echo get_option( 'integrate_palace_webhook_secret' ) ? '<span class="ippd-badge ippd-badge--green">HMAC Enabled</span>' : '<span class="ippd-badge ippd-badge--yellow">Open</span>'; ?></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-rest-api"></span> REST API</span>
                            <span class="ippd-kv__value"><a href="<?php echo esc_url( $rest_url ); ?>" target="_blank">palace-properties/v1</a></span>
                        </div>
                    </div>
                </div>

                <!-- Sync & Configuration -->
                <div class="ippd-card">
                    <div class="ippd-card__head">
                        <h3><span class="dashicons dashicons-update"></span> <?php esc_html_e( 'Sync & Configuration', 'integrate-palace-properties' ); ?></h3>
                    </div>
                    <div class="ippd-card__body">
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-clock"></span> Last Property Received</span>
                            <span class="ippd-kv__value"><?php echo $last_sync ? esc_html( human_time_diff( strtotime( $last_sync ), current_time( 'timestamp' ) ) ) . ' ago' : '<em>Never</em>'; ?></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-database"></span> Total in Database</span>
                            <span class="ippd-kv__value">
                                <?php echo esc_html( $published ); ?> published
                                <br><small style="color:#64748b;"><?php echo esc_html( $active_count ); ?> active · <?php echo esc_html( $inactive_count ); ?> inactive<?php
                                    $unclassified = $published - $active_count - $inactive_count;
                                    if ( $unclassified > 0 ) echo ' · ' . esc_html( $unclassified ) . ' unclassified';
                                ?></small>
                            </span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-archive"></span> Show on Frontend</span>
                            <span class="ippd-kv__value">
                                <?php if ( $sync_archived === 'yes' ) : ?>
                                    <span class="ippd-badge ippd-badge--blue">All (Active + Archived)</span>
                                <?php else : ?>
                                    <span class="ippd-badge ippd-badge--green">Active Only</span>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-layout"></span> Active Template</span>
                            <span class="ippd-kv__value"><span class="ippd-badge ippd-badge--blue"><?php echo esc_html( ucwords( str_replace( '-', ' ', $template ) ) ); ?></span></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-admin-links"></span> Property Slug</span>
                            <span class="ippd-kv__value"><code>/<?php echo esc_html( $slug ); ?>/</code></span>
                        </div>
                        <div class="ippd-kv">
                            <span class="ippd-kv__label"><span class="dashicons dashicons-visibility"></span> Display Fields</span>
                            <span class="ippd-kv__value"><?php echo esc_html( count( $display_fields ) ); ?> of <?php echo esc_html( count( $default_fields ) ); ?> enabled</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Gallery Sync Progress -->
            <div class="ippd-card" id="ipp-gallery-progress-card" style="margin-bottom:24px;">
                <div class="ippd-card__head">
                    <h3><span class="dashicons dashicons-format-gallery"></span> <?php esc_html_e( 'Gallery Sync Progress', 'integrate-palace-properties' ); ?></h3>
                    <div style="display:flex;align-items:center;gap:10px;">
                        <span id="ipp-gsp-summary" style="font-size:12px;color:#64748b;"></span>
                        <button type="button" id="ipp-gsp-run" class="button button-primary button-small" style="display:none;">
                            <span class="dashicons dashicons-controls-play" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span> Process Now
                        </button>
                        <button type="button" id="ipp-gsp-refresh" class="button button-small" title="Refresh">
                            <span class="dashicons dashicons-update" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span>
                        </button>
                    </div>
                </div>
                <div class="ippd-card__body" style="padding:0;">
                    <div id="ipp-gsp-loading" style="padding:24px;text-align:center;color:#94a3b8;">
                        <span class="dashicons dashicons-update" style="animation:ippd-spin 1s linear infinite;"></span> Loading...
                    </div>
                    <div id="ipp-gsp-empty" style="padding:24px;text-align:center;color:#94a3b8;display:none;">
                        <span class="dashicons dashicons-yes-alt" style="font-size:32px;width:32px;height:32px;color:#059669;display:block;margin:0 auto 8px;"></span>
                        No gallery syncs in progress. All caught up!
                    </div>
                    <table id="ipp-gsp-table" style="width:100%;border-collapse:collapse;font-size:13px;display:none;">
                        <thead>
                            <tr style="background:#f8fafc;border-bottom:1px solid #e2e8f0;">
                                <th style="padding:10px 18px;text-align:left;font-weight:600;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.05em;">Property</th>
                                <th style="padding:10px 14px;text-align:left;font-weight:600;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.05em;">Status</th>
                                <th style="padding:10px 14px;text-align:left;font-weight:600;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.05em;">Progress</th>
                                <th style="padding:10px 14px;text-align:left;font-weight:600;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.05em;">Message</th>
                                <th style="padding:10px 18px;text-align:right;font-weight:600;color:#64748b;font-size:11px;text-transform:uppercase;letter-spacing:.05em;">Time</th>
                            </tr>
                        </thead>
                        <tbody id="ipp-gsp-body"></tbody>
                    </table>
                </div>
            </div>

            <!-- Row 3: Breakdown + Recent -->
            <div class="ippd-grid ippd-grid--2">

                <!-- Breakdown -->
                <div class="ippd-card">
                    <div class="ippd-card__head">
                        <h3><span class="dashicons dashicons-chart-bar"></span> <?php esc_html_e( 'Property Breakdown', 'integrate-palace-properties' ); ?></h3>
                    </div>
                    <div class="ippd-card__body">
                        <?php if ( ! empty( $status_terms ) && ! is_wp_error( $status_terms ) ) : ?>
                            <h4 style="margin:0 0 10px;font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;">By Status</h4>
                            <?php foreach ( $status_terms as $term ) :
                                $pct = $published > 0 ? round( ( $term->count / $published ) * 100 ) : 0;
                                $color = strtolower( $term->name ) === 'active' ? 'green' : 'blue';
                            ?>
                                <div class="ippd-bar">
                                    <div class="ippd-bar__header">
                                        <span class="ippd-bar__label"><?php echo esc_html( $term->name ); ?></span>
                                        <span class="ippd-bar__count"><?php echo esc_html( $term->count ); ?></span>
                                    </div>
                                    <div class="ippd-bar__track"><div class="ippd-bar__fill ippd-bar__fill--<?php echo esc_attr( $color ); ?>" style="width:<?php echo esc_attr( $pct ); ?>%"></div></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>

                        <?php if ( ! empty( $type_terms ) && ! is_wp_error( $type_terms ) ) : ?>
                            <h4 style="margin:16px 0 10px;font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;">By Type</h4>
                            <?php foreach ( $type_terms as $term ) :
                                $pct = $published > 0 ? round( ( $term->count / $published ) * 100 ) : 0;
                            ?>
                                <div class="ippd-bar">
                                    <div class="ippd-bar__header">
                                        <span class="ippd-bar__label"><?php echo esc_html( $term->name ); ?></span>
                                        <span class="ippd-bar__count"><?php echo esc_html( $term->count ); ?></span>
                                    </div>
                                    <div class="ippd-bar__track"><div class="ippd-bar__fill ippd-bar__fill--purple" style="width:<?php echo esc_attr( $pct ); ?>%"></div></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>

                        <?php if ( ! empty( $region_terms ) && ! is_wp_error( $region_terms ) ) : ?>
                            <h4 style="margin:16px 0 10px;font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;">By Region</h4>
                            <?php foreach ( array_slice( $region_terms, 0, 6 ) as $term ) :
                                $pct = $published > 0 ? round( ( $term->count / $published ) * 100 ) : 0;
                            ?>
                                <div class="ippd-bar">
                                    <div class="ippd-bar__header">
                                        <span class="ippd-bar__label"><?php echo esc_html( $term->name ); ?></span>
                                        <span class="ippd-bar__count"><?php echo esc_html( $term->count ); ?></span>
                                    </div>
                                    <div class="ippd-bar__track"><div class="ippd-bar__fill ippd-bar__fill--orange" style="width:<?php echo esc_attr( $pct ); ?>%"></div></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>

                        <?php if ( ! empty( $mgmt_terms ) && ! is_wp_error( $mgmt_terms ) ) : ?>
                            <h4 style="margin:16px 0 10px;font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8;">By Management</h4>
                            <?php foreach ( $mgmt_terms as $term ) :
                                $pct = $published > 0 ? round( ( $term->count / $published ) * 100 ) : 0;
                            ?>
                                <div class="ippd-bar">
                                    <div class="ippd-bar__header">
                                        <span class="ippd-bar__label"><?php echo esc_html( $term->name ); ?></span>
                                        <span class="ippd-bar__count"><?php echo esc_html( $term->count ); ?></span>
                                    </div>
                                    <div class="ippd-bar__track"><div class="ippd-bar__fill ippd-bar__fill--blue" style="width:<?php echo esc_attr( $pct ); ?>%"></div></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent + Quick Links -->
                <div>
                    <!-- Recently Updated -->
                    <div class="ippd-card" style="margin-bottom:16px;">
                        <div class="ippd-card__head">
                            <h3><span class="dashicons dashicons-backup"></span> <?php esc_html_e( 'Recently Updated', 'integrate-palace-properties' ); ?></h3>
                            <a href="<?php echo esc_url( admin_url( 'edit.php?post_type=palace-properties' ) ); ?>" style="font-size:12px;text-decoration:none;color:#2563eb;">View All &rarr;</a>
                        </div>
                        <div class="ippd-card__body" style="padding:12px 18px;">
                            <ul class="ippd-recent">
                                <?php foreach ( $recent_props as $rp ) :
                                    $rp_code = get_post_meta( $rp->ID, 'ipp_property_code', true );
                                    $rp_rent = get_post_meta( $rp->ID, 'ipp_rent_amount', true );
                                    $rp_locked = get_post_meta( $rp->ID, 'ipp_lock_updates', true ) === '1';
                                    $rp_hidden = get_post_meta( $rp->ID, 'ipp_hide_property', true ) === '1';
                                ?>
                                    <li>
                                        <span class="ippd-recent__title">
                                            <a href="<?php echo esc_url( get_edit_post_link( $rp->ID ) ); ?>"><?php echo esc_html( $rp->post_title ); ?></a>
                                            <?php if ( $rp_locked ) : ?><span class="dashicons dashicons-lock" style="font-size:12px;width:12px;height:12px;color:#d97706;" title="Locked"></span><?php endif; ?>
                                            <?php if ( $rp_hidden ) : ?><span class="dashicons dashicons-hidden" style="font-size:12px;width:12px;height:12px;color:#ef4444;" title="Hidden"></span><?php endif; ?>
                                        </span>
                                        <span class="ippd-recent__meta">
                                            <?php if ( $rp_rent ) echo '$' . esc_html( number_format( (float) $rp_rent ) ); ?>
                                            · <?php echo esc_html( human_time_diff( strtotime( $rp->post_modified ), current_time( 'timestamp' ) ) ); ?> ago
                                        </span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>

                    <!-- Quick Links -->
                    <div class="ippd-card">
                        <div class="ippd-card__head">
                            <h3><span class="dashicons dashicons-admin-links"></span> <?php esc_html_e( 'Quick Links', 'integrate-palace-properties' ); ?></h3>
                        </div>
                        <div class="ippd-card__body" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                            <?php
                            $links = array(
                                array( 'dashicons-admin-home',     __( 'All Properties', 'integrate-palace-properties' ),  admin_url( 'edit.php?post_type=palace-properties' ) ),
                                array( 'dashicons-admin-settings', __( 'Settings', 'integrate-palace-properties' ),        admin_url( 'admin.php?page=integrate-palace-properties-configs' ) ),
                                array( 'dashicons-layout',         __( 'Templates', 'integrate-palace-properties' ),       admin_url( 'admin.php?page=palace-property_templates' ) ),
                                array( 'dashicons-art',            __( 'Appearance', 'integrate-palace-properties' ),      admin_url( 'customize.php?autofocus[panel]=ipp_panel&url=' . urlencode( $archive_url ) ) ),
                                array( 'dashicons-editor-code',    __( 'Developer Docs', 'integrate-palace-properties' ), admin_url( 'admin.php?page=ipp-developer-docs' ) ),
                                array( 'dashicons-external',       __( 'View Listings', 'integrate-palace-properties' ),  $archive_url ),
                            );
                            foreach ( $links as $link ) : ?>
                                <a href="<?php echo esc_url( $link[2] ); ?>" style="display:flex;align-items:center;gap:8px;padding:10px 12px;background:#f8fafc;border-radius:6px;text-decoration:none;color:#1e293b;font-size:13px;font-weight:500;transition:all .15s;"
                                   onmouseover="this.style.background='#2563eb';this.style.color='#fff';"
                                   onmouseout="this.style.background='#f8fafc';this.style.color='#1e293b';"
                                   <?php echo $link[0] === 'dashicons-external' ? 'target="_blank"' : ''; ?>>
                                    <span class="dashicons <?php echo esc_attr( $link[0] ); ?>" style="font-size:16px;width:16px;height:16px;"></span>
                                    <?php echo esc_html( $link[1] ); ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <script>
        jQuery(function($) {
            var $btn = $('#ipp-sync-now'), $status = $('#ipp-sync-status');
            $btn.on('click', function() {
                if ($btn.hasClass('syncing')) return;
                $btn.addClass('syncing').prop('disabled', true);
                $status.text('Triggering sync...').removeClass('success error');
                $.post(ajaxurl, {
                    action: 'ipp_trigger_sync',
                    nonce: '<?php echo esc_js( wp_create_nonce( 'ipp_admin_nonce' ) ); ?>'
                }, function(r) {
                    $btn.removeClass('syncing').prop('disabled', false);
                    if (r.success) {
                        $status.text(r.data.message).addClass('success');
                    } else {
                        $status.text(r.data || 'Sync failed').addClass('error');
                    }
                }).fail(function() {
                    $btn.removeClass('syncing').prop('disabled', false);
                    $status.text('Request failed').addClass('error');
                });
            });

            // ── Gallery Sync Progress ──────────────────────────────
            var gspNonce = '<?php echo esc_js( wp_create_nonce( 'ipp_admin_nonce' ) ); ?>';
            var gspTimer = null;
            var gspHasActive = false;
            var gspRunning = false;
            var gspProcessed = 0;

            function ippStatusBadge(status) {
                var spin = '<span class="dashicons dashicons-update" style="font-size:12px;width:12px;height:12px;animation:ippd-spin 1s linear infinite;"></span> ';
                var map = { syncing: 'ippd-badge--blue', queued: 'ippd-badge--yellow', failed: 'ippd-badge--red' };
                var labels = { syncing: spin + 'Syncing', queued: 'Queued', failed: 'Failed' };
                return '<span class="ippd-badge ' + (map[status] || 'ippd-badge--gray') + '">' + (labels[status] || status) + '</span>';
            }

            function ippProgressBar(processed, total) {
                if (!total) return '<span style="color:#94a3b8;">—</span>';
                var pct = Math.round((processed / total) * 100);
                return '<div style="display:flex;align-items:center;gap:8px;min-width:120px;">' +
                    '<div class="ippd-bar__track" style="flex:1;height:6px;">' +
                        '<div class="ippd-bar__fill ippd-bar__fill--blue" style="width:' + pct + '%;transition:width .3s;"></div>' +
                    '</div>' +
                    '<span style="font-size:11px;color:#64748b;white-space:nowrap;">' + processed + '/' + total + '</span>' +
                '</div>';
            }

            function ippLoadProgress() {
                $.post(ajaxurl, { action: 'ipp_gallery_sync_progress', nonce: gspNonce }, function(r) {
                    var $loading = $('#ipp-gsp-loading'),
                        $empty   = $('#ipp-gsp-empty'),
                        $table   = $('#ipp-gsp-table'),
                        $body    = $('#ipp-gsp-body'),
                        $summary = $('#ipp-gsp-summary');

                    $loading.hide();

                    if (!r.success || !r.data.items.length) {
                        $table.hide();
                        $empty.show();
                        $summary.text('');
                        gspHasActive = false;
                        $('#ipp-gsp-run').hide();
                        return;
                    }

                    var d = r.data, s = d.summary;
                    var parts = [];
                    if (s.syncing)   parts.push(s.syncing + ' syncing');
                    if (s.queued)    parts.push(s.queued + ' queued');
                    if (s.failed)    parts.push(s.failed + ' failed');
                    if (s.completed) parts.push(s.completed + ' done');
                    $summary.text(parts.join(' · '));

                    gspHasActive = ((s.syncing || 0) + (s.queued || 0)) > 0;

                    // Show/hide Process Now button
                    if (((s.queued || 0) + (s.syncing || 0)) > 0 && !gspRunning) {
                        $('#ipp-gsp-run').show();
                    } else if (!gspRunning) {
                        $('#ipp-gsp-run').hide();
                    }

                    // Show max 20 rows, prioritize active items
                    var rows = d.items.slice(0, 20);
                    var html = '';
                    $.each(rows, function(i, item) {
                        var rowBg = item.status === 'failed' ? 'background:#fef2f2;' : (item.status === 'syncing' ? 'background:#eff6ff;' : '');
                        html += '<tr style="border-bottom:1px solid #f1f5f9;' + rowBg + '">';
                        html += '<td style="padding:10px 18px;"><a href="' + item.edit_url + '" style="color:#1e293b;text-decoration:none;font-weight:500;" title="Post #' + item.post_id + '">' + $('<span>').text(item.title).html() + '</a></td>';
                        html += '<td style="padding:10px 14px;">' + ippStatusBadge(item.status) + '</td>';
                        html += '<td style="padding:10px 14px;">' + ippProgressBar(item.processed, item.total) + '</td>';
                        html += '<td style="padding:10px 14px;color:#64748b;max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + $('<span>').text(item.message).html() + '">' + $('<span>').text(item.message).html() + '</td>';
                        html += '<td style="padding:10px 18px;text-align:right;color:#94a3b8;white-space:nowrap;font-size:12px;">' + (item.status === 'completed' || item.status === 'failed' ? item.completed_at : item.started_at) + '</td>';
                        html += '</tr>';
                    });

                    if (d.items.length > 20) {
                        html += '<tr><td colspan="5" style="padding:10px 18px;text-align:center;color:#94a3b8;font-size:12px;">...and ' + (d.items.length - 20) + ' more</td></tr>';
                    }

                    $body.html(html);
                    $empty.hide();
                    $table.show();

                    // Auto-refresh while syncs are active
                    if (gspHasActive) {
                        clearTimeout(gspTimer);
                        gspTimer = setTimeout(ippLoadProgress, 10000);
                    }
                });
            }

            // Initial load
            ippLoadProgress();

            // Manual refresh button
            $('#ipp-gsp-refresh').on('click', function() {
                var $icon = $(this).find('.dashicons');
                $icon.css('animation', 'ippd-spin 1s linear infinite');
                ippLoadProgress();
                setTimeout(function() { $icon.css('animation', ''); }, 1000);
            });

            // Process Now — runs queued syncs one by one via AJAX
            function ippRunNext() {
                $.post(ajaxurl, { action: 'ipp_gallery_sync_run', nonce: gspNonce }, function(r) {
                    if (!r.success || r.data.done) {
                        // All done
                        gspRunning = false;
                        $('#ipp-gsp-run').html('<span class="dashicons dashicons-yes" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span> Done').prop('disabled', true);
                        setTimeout(function() {
                            $('#ipp-gsp-run').hide().html('<span class="dashicons dashicons-controls-play" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span> Process Now').prop('disabled', false);
                        }, 3000);
                        ippLoadProgress();
                        return;
                    }

                    gspProcessed++;
                    $('#ipp-gsp-run').html('<span class="dashicons dashicons-update" style="font-size:14px;width:14px;height:14px;margin-top:3px;animation:ippd-spin 1s linear infinite;"></span> Processing... (' + gspProcessed + ' done)');

                    // Refresh the table to show updated statuses
                    ippLoadProgress();

                    // Throttle: 2s gap between API calls to avoid hammering Palace API
                    setTimeout(ippRunNext, 2000);
                }).fail(function() {
                    gspRunning = false;
                    $('#ipp-gsp-run').html('<span class="dashicons dashicons-controls-play" style="font-size:14px;width:14px;height:14px;margin-top:3px;"></span> Process Now').prop('disabled', false).removeClass('syncing');
                    ippLoadProgress();
                });
            }

            $('#ipp-gsp-run').on('click', function() {
                if (gspRunning) return;
                gspRunning = true;
                gspProcessed = 0;
                $(this).html('<span class="dashicons dashicons-update" style="font-size:14px;width:14px;height:14px;margin-top:3px;animation:ippd-spin 1s linear infinite;"></span> Starting...').prop('disabled', true);
                ippRunNext();
            });

            // Resync Galleries button
            $('#ipp-resync-galleries').on('click', function() {
                var $btn = $(this), $status = $('#ipp-sync-status');
                if ($btn.prop('disabled')) return;
                $btn.prop('disabled', true).find('.dashicons').css('animation', 'ippd-spin 1s linear infinite');
                $status.text('Queuing gallery resyncs...').removeClass('success error');
                $.post(ajaxurl, {
                    action: 'ipp_resync_galleries',
                    nonce: gspNonce
                }, function(r) {
                    $btn.prop('disabled', false).find('.dashicons').css('animation', '');
                    if (r.success) {
                        $status.text(r.data.message).addClass('success');
                        ippLoadProgress();
                    } else {
                        $status.text(r.data || 'Failed').addClass('error');
                    }
                }).fail(function() {
                    $btn.prop('disabled', false).find('.dashicons').css('animation', '');
                    $status.text('Request failed').addClass('error');
                });
            });
        });
        </script>
        <?php
    }
}
