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

/**
 * 一般設定タブ のレンダリング
 *
 * 元 admin/class-aiap-admin-view.php から分離。
 * 共通基盤 (resolve_dynamic_key, log_message 等) は親クラス AIAP_Admin_View にあるため直接参照する。
 */
class AIAP_Admin_View_Settings {

    public static function render_settings( $s ) {
        $tasks  = AIAP_Prompts::get_all();
        $active = array_filter( $tasks, function( $t ) { return ! empty( $t['enabled'] ); } );
        $users  = get_users( array( 'capability' => 'edit_posts' ) );
        $cats   = get_categories( array( 'hide_empty' => false ) );

        $plan_is_pro    = AIAP_License::is_pro();
        $plan_is_trial  = AIAP_License::is_trial();
        $plan_count     = AIAP_License::monthly_post_count();
        $plan_limit     = AIAP_License::FREE_MONTHLY_LIMIT;
        $plan_remaining = AIAP_License::remaining_posts();
        $plan_pct       = $plan_is_pro ? 0 : min( 100, max( 0, ( $plan_count / max( 1, $plan_limit ) ) * 100 ) );
        $usage_class    = '';
        if ( ! $plan_is_pro ) {
            if ( $plan_remaining === 0 ) $usage_class = 'aiap-usage-fill-full';
            elseif ( $plan_pct >= 70 )   $usage_class = 'aiap-usage-fill-warn';
        }
        $is_pro = $plan_is_pro;
        ?>
        <?php // Phase X: 設定タブはアコーディオンごとに独立フォーム化。
              // 大外の form は廃止し、各セクション内で個別保存する。 ?>

        <?php
        // ============================================================
        // Phase 1 Live Dashboard - 「今、何が動いているか」を最初に表示
        // ============================================================
        $active_count    = count( $active );
        // Phase 12: 本日の投稿予定数 (固定スケジュール + ランダムタスクの今日の乱数決定値の合算)。
        // 旧実装は「今日スケジュールのあるタスク数」を数えていたが、ランダム 6〜10 回の
        // タスクが「今日 1 件」のように表示されて誤解を招いていた。実際の投稿予定件数を出す。
        $today_planned   = AIAP_Prompts::count_today_planned_posts();
        $next_run        = AIAP_Scheduler::get_next_scheduled_run();
        $queue_count     = AIAP_Scheduler::get_queue_count();
        $daily_counts    = AIAP_License::daily_post_counts( 7 );
        $week_max        = max( 1, max( $daily_counts ) );
        $is_enabled      = ! empty( $s['enabled'] );

        // 次の予定の表示文字列を組み立て
        $now             = new DateTimeImmutable( 'now', wp_timezone() );
        $next_label      = '';
        $next_relative   = '';
        if ( $next_run ) {
            if ( $next_run['is_today'] ) {
                $next_label = $next_run['time'];
                // 残り時間を分単位で計算
                $target = new DateTimeImmutable( $next_run['date'] . ' ' . $next_run['time'], wp_timezone() );
                $diff   = $target->getTimestamp() - $now->getTimestamp();
                if ( $diff > 0 ) {
                    $hours   = floor( $diff / 3600 );
                    $minutes = floor( ( $diff % 3600 ) / 60 );
                    if ( $hours > 0 ) {
                        /* translators: 1: hours remaining, 2: minutes remaining */
                        $next_relative = sprintf( __( 'in %1$dh %2$dm', 'ai-auto-poster' ), $hours, $minutes );
                    } else {
                        /* translators: %d = minutes remaining */
                        $next_relative = sprintf( __( 'in %d min', 'ai-auto-poster' ), max( 1, $minutes ) );
                    }
                }
            } else {
                $next_label    = mysql2date( 'M j', $next_run['date'] ) . ' ' . $next_run['time'];
                $next_relative = '';
            }
        }
        ?>
        <div class="aiap-dash">
            <div class="aiap-dash-header">
                <h2 class="aiap-dash-title"><?php echo esc_html( __( 'Live status', 'ai-auto-poster' ) ); ?></h2>
                <?php if ( $is_enabled ) : ?>
                    <span class="aiap-dash-pill aiap-dash-pill-on"><?php echo esc_html( __( 'Active', 'ai-auto-poster' ) ); ?></span>
                <?php else : ?>
                    <span class="aiap-dash-pill aiap-dash-pill-off"><?php echo esc_html( __( 'Paused', 'ai-auto-poster' ) ); ?></span>
                <?php endif; ?>
            </div>

            <div class="aiap-dash-grid">
                <div class="aiap-dash-card">
                    <div class="aiap-dash-card-label"><?php echo esc_html( __( 'Posts this month', 'ai-auto-poster' ) ); ?></div>
                    <div class="aiap-dash-card-value">
                        <?php echo esc_html( $plan_count ); ?>
                        <?php if ( ! $plan_is_pro ) : ?>
                            <span class="aiap-dash-card-sub">/ <?php echo esc_html( $plan_limit ); ?></span>
                        <?php endif; ?>
                    </div>
                    <?php if ( ! $plan_is_pro ) : ?>
                        <div class="aiap-dash-bar"><div class="aiap-dash-bar-fill <?php echo esc_attr( $usage_class ); ?>" style="width: <?php echo (int) $plan_pct; ?>%"></div></div>
                    <?php endif; ?>
                </div>

                <div class="aiap-dash-card">
                    <div class="aiap-dash-card-label"><?php echo esc_html( __( 'Active tasks', 'ai-auto-poster' ) ); ?></div>
                    <div class="aiap-dash-card-value"><?php echo esc_html( $active_count ); ?></div>
                </div>

                <?php
                // Phase 12: 本日の投稿カード。
                // 自動 (cron) と 手動 (Quick Post) を分けて表示。
                //   自動: 完了 (今日の自動投稿数) / 予定 (固定スケジュール + ランダム今日分)
                //   手動: 完了 (今日の手動投稿数のみ。手動には「予定」概念がないため X のみ)
                $tp_total       = (int) $today_planned['total'];
                $today_breakdown = AIAP_License::today_post_breakdown();
                $today_auto     = (int) $today_breakdown['auto'];
                $today_manual   = (int) $today_breakdown['manual'];
                ?>
                <div class="aiap-dash-card">
                    <div class="aiap-dash-card-label"><?php echo esc_html( __( 'Today', 'ai-auto-poster' ) ); ?></div>
                    <div class="aiap-dash-card-rows">
                        <div class="aiap-dash-card-row">
                            <span class="aiap-dash-card-row-label"><?php echo esc_html( _x( 'Auto', 'dashboard short label', 'ai-auto-poster' ) ); ?></span>
                            <span class="aiap-dash-card-row-value"><?php echo esc_html( $today_auto ); ?> / <?php echo esc_html( $tp_total ); ?></span>
                        </div>
                        <div class="aiap-dash-card-row">
                            <span class="aiap-dash-card-row-label"><?php echo esc_html( _x( 'Manual', 'dashboard short label', 'ai-auto-poster' ) ); ?></span>
                            <span class="aiap-dash-card-row-value"><?php echo esc_html( $today_manual ); ?></span>
                        </div>
                    </div>
                </div>

                <div class="aiap-dash-card">
                    <div class="aiap-dash-card-label"><?php echo esc_html( __( 'Next post', 'ai-auto-poster' ) ); ?></div>
                    <?php if ( $next_label ) : ?>
                        <div class="aiap-dash-card-value"><?php echo esc_html( $next_label ); ?></div>
                        <?php if ( $next_relative ) : ?>
                            <div class="aiap-dash-card-foot"><?php echo esc_html( $next_relative ); ?></div>
                        <?php endif; ?>
                    <?php else : ?>
                        <div class="aiap-dash-card-value aiap-dash-card-value-muted">—</div>
                        <div class="aiap-dash-card-foot"><?php echo esc_html( __( 'No upcoming runs', 'ai-auto-poster' ) ); ?></div>
                    <?php endif; ?>
                </div>

                <div class="aiap-dash-card">
                    <div class="aiap-dash-card-label"><?php echo esc_html( __( 'Recovery queue', 'ai-auto-poster' ) ); ?></div>
                    <div class="aiap-dash-card-value <?php echo $queue_count > 0 ? 'aiap-dash-card-value-warn' : ''; ?>"><?php echo esc_html( $queue_count ); ?></div>
                    <div class="aiap-dash-card-foot">
                        <?php
                        if ( $queue_count === 0 ) {
                            echo esc_html( __( 'All caught up', 'ai-auto-poster' ) );
                        } else {
                            /* translators: %d = number of pending recovery items */
                            echo esc_html( sprintf( _n( '%d pending', '%d pending', $queue_count, 'ai-auto-poster' ), $queue_count ) );
                        }
                        ?>
                    </div>
                </div>
            </div>

            <?php
            // 直近 7 日のミニグラフ
            $has_data = array_sum( $daily_counts ) > 0;
            ?>
            <div class="aiap-dash-chart">
                <div class="aiap-dash-chart-title"><?php echo esc_html( __( 'Last 7 days', 'ai-auto-poster' ) ); ?></div>
                <div class="aiap-dash-chart-bars" role="img" aria-label="<?php echo esc_attr( __( 'Posts per day for the last 7 days', 'ai-auto-poster' ) ); ?>">
                    <?php foreach ( $daily_counts as $date => $count ) :
                        $h_pct = (int) round( ( $count / $week_max ) * 100 );
                        $is_today_bar = ( $date === $now->format( 'Y-m-d' ) );
                    ?>
                        <div class="aiap-dash-chart-bar <?php echo $is_today_bar ? 'is-today' : ''; ?>" title="<?php echo esc_attr( $date . ': ' . $count ); ?>">
                            <div class="aiap-dash-chart-bar-count"><?php echo esc_html( $count ); ?></div>
                            <div class="aiap-dash-chart-bar-track">
                                <div class="aiap-dash-chart-bar-fill" style="height: <?php echo (int) max( 4, $h_pct ); ?>%"></div>
                            </div>
                            <div class="aiap-dash-chart-bar-label"><?php echo esc_html( mysql2date( 'D', $date ) ); ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <?php if ( ! $has_data ) : ?>
                    <div class="aiap-dash-chart-empty"><?php echo esc_html( __( 'No posts generated in the last 7 days yet.', 'ai-auto-poster' ) ); ?></div>
                <?php endif; ?>
            </div>
        </div>

        <?php /* Phase 2: ヒーロー (How should auto-posting behave?) は削除。ダッシュボード見出しで代替。 */ ?>

        <?php // ===== Plan card ===== ?>
        <div class="aiap-plan-card-v2 aiap-plan-card-v2-<?php echo esc_attr( $plan_is_pro ? 'pro' : ( $plan_is_trial ? 'trial' : 'free' ) ); ?>">
            <div class="aiap-plan-card-v2-row">
                <div class="aiap-plan-card-v2-name">
                    <?php if ( $plan_is_trial ) : ?>
                        <span class="aiap-plan-card-v2-label"><?php echo esc_html( __( 'Pro Trial', 'ai-auto-poster' ) ); ?></span>
                        <span class="aiap-plan-card-v2-badge aiap-plan-card-v2-badge-trial"><?php echo esc_html( __( 'TRIAL', 'ai-auto-poster' ) ); ?></span>
                    <?php elseif ( $plan_is_pro ) : ?>
                        <span class="aiap-plan-card-v2-label"><?php echo esc_html( __( 'Pro Plan', 'ai-auto-poster' ) ); ?></span>
                        <span class="aiap-plan-card-v2-badge aiap-plan-card-v2-badge-pro"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                    <?php else : ?>
                        <span class="aiap-plan-card-v2-label"><?php echo esc_html( __( 'Free Plan', 'ai-auto-poster' ) ); ?></span>
                    <?php endif; ?>
                </div>
                <div class="aiap-plan-card-v2-info">
                    <?php if ( $plan_is_trial ) :
                        $remain_days = AIAP_License::trial_days_remaining();
                        if ( $remain_days > 0 ) : ?>
                            <span class="aiap-plan-card-v2-stat"><?php
                                /* translators: %d = number of trial days remaining */
                                echo esc_html( sprintf( _n( '%d day remaining', '%d days remaining', $remain_days, 'ai-auto-poster' ), $remain_days ) );
                            ?></span>
                        <?php endif;
                    elseif ( $plan_is_pro ) : ?>
                        <span class="aiap-plan-card-v2-stat"><?php echo esc_html( __( 'Unlimited posting', 'ai-auto-poster' ) ); ?></span>
                    <?php else : ?>
                        <span class="aiap-plan-card-v2-stat">
                            <strong><?php echo esc_html( $plan_count ); ?></strong>
                            <span class="aiap-plan-card-v2-stat-sep">/</span>
                            <span class="aiap-plan-card-v2-stat-limit"><?php echo esc_html( $plan_limit ); ?></span>
                            <span class="aiap-plan-card-v2-stat-unit"><?php echo esc_html( __( 'posts this month', 'ai-auto-poster' ) ); ?></span>
                        </span>
                        <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-plan-card-v2-cta">
                            <span class="dashicons dashicons-star-filled" aria-hidden="true"></span>
                            <?php echo esc_html( __( 'Upgrade to Pro', 'ai-auto-poster' ) ); ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php if ( ! $plan_is_pro && ! $plan_is_trial ) : ?>
                <div class="aiap-plan-card-v2-bar">
                    <div class="aiap-plan-card-v2-bar-fill <?php echo esc_attr( $usage_class ); ?>" style="--aiap-bar-pct: <?php echo (int) $plan_pct; ?>%;"></div>
                </div>
                <?php if ( $plan_remaining === 0 ) : ?>
                    <p class="aiap-plan-card-v2-warning"><?php echo esc_html( __( 'Monthly limit reached. New posts will resume on the 1st of next month.', 'ai-auto-poster' ) ); ?></p>
                <?php elseif ( $plan_remaining <= 3 ) : ?>
                    <p class="aiap-plan-card-v2-warning"><?php
                        /* translators: %d = posts remaining */
                        echo esc_html( sprintf( _n( '%d post remaining this month.', '%d posts remaining this month.', $plan_remaining, 'ai-auto-poster' ), $plan_remaining ) );
                    ?></p>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <?php // ===== Status card (Phase 2: アコーディオン化, デフォルト展開) ===== ?>
        <details class="aiap-section aiap-section-status" open>
            <summary class="aiap-section-header">
                <h3 class="aiap-section-title"><?php echo esc_html( __( 'Status', 'ai-auto-poster' ) ); ?></h3>
            </summary>
            <div class="aiap-section-body">
                <div class="aiap-row-flex">
                    <div class="aiap-row-flex-text">
                        <strong class="aiap-row-flex-title"><?php echo esc_html( __( 'Auto Posting', 'ai-auto-poster' ) ); ?></strong>
                        <span class="aiap-row-flex-sub"><?php
                            /* translators: %d = number of tasks scheduled today */
                            // Bug fix: 旧実装の count( $today ) は固定スケジュールのタスクしか数えず、
                            // ランダムモードのタスクが除外されていたため「稼働中タスク」数と食い違っていた。
                            // count_tasks_scheduled_today() はランダムタスクも含めて本日実行されるタスクを数える。
                            echo esc_html( sprintf( __( 'Tasks scheduled today: %d', 'ai-auto-poster' ), AIAP_Prompts::count_tasks_scheduled_today() ) );
                        ?></span>
                    </div>
                    <label class="aiap-toggle-switch aiap-toggle-switch-large">
                        <input type="checkbox" id="js-aiap-toggle-enabled" <?php checked( ! empty( $s['enabled'] ) ); ?> data-nonce="<?php echo esc_attr( wp_create_nonce( AIAP_Admin::NONCE ) ); ?>">
                        <span class="aiap-toggle-slider"></span>
                        <span class="aiap-toggle-label" id="js-aiap-toggle-label"><strong><?php echo esc_html( AIAP_Admin_View::resolve_dynamic_key( ! empty( $s['enabled'] ) ? 'enabled' : 'disabled' ) ); ?></strong></span>
                    </label>
                </div>
                <span id="js-aiap-toggle-status" class="aiap-toggle-status" aria-live="polite"></span>
            </div>
        </details>

        <?php // ===== Missed posts recovery (Phase 2: アコーディオン化) ===== ?>
        <details class="aiap-section">
            <summary class="aiap-section-header">
                <h3 class="aiap-section-title"><?php echo esc_html( __( 'When a post gets missed', 'ai-auto-poster' ) ); ?></h3>
                <p class="aiap-section-sub"><?php echo esc_html( __( 'If a scheduled run is skipped (server, WP issue), what to do.', 'ai-auto-poster' ) ); ?></p>
            </summary>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-settings-form">
            <input type="hidden" name="action" value="aiap_save_recover"><?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
            <div class="aiap-section-body">
                <div class="aiap-field">
                    <label class="aiap-checkbox-row">
                        <input type="checkbox" name="cron_recover_missed" value="1" <?php checked( ! empty( $s['cron_recover_missed'] ) ); ?>>
                        <span>
                            <strong><?php echo esc_html( __( 'Run missed posts later', 'ai-auto-poster' ) ); ?></strong>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Skipped posts are queued and posted one-by-one on the next cron run.', 'ai-auto-poster' ) ); ?></span>
                        </span>
                    </label>
                </div>
                <div class="aiap-field">
                    <label class="aiap-field-label" for="aiap-cron-recover-max">
                        <?php echo esc_html( __( 'Max items to process', 'ai-auto-poster' ) ); ?>
                        <?php if ( ! $is_pro ) : ?>
                            <span class="aiap-pro-pill"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                        <?php endif; ?>
                    </label>
                    <?php $cur_max = $is_pro ? max( 1, min( 5, (int) ( $s['cron_recover_max'] ?? 3 ) ) ) : 1; ?>
                    <div class="aiap-field-row">
                        <input type="number" id="aiap-cron-recover-max" class="aiap-input-text aiap-input-narrow" name="cron_recover_max" value="<?php echo esc_attr( $cur_max ); ?>" min="1" max="5" <?php echo $is_pro ? '' : 'disabled'; ?>>
                        <span class="aiap-field-unit"><?php echo esc_html( __( 'items', 'ai-auto-poster' ) ); ?></span>
                    </div>
                    <?php if ( $is_pro ) : ?>
                        <span class="aiap-field-hint"><?php echo esc_html( __( 'Range 1–5. Older missed schedules beyond this are skipped.', 'ai-auto-poster' ) ); ?></span>
                    <?php else : ?>
                        <span class="aiap-field-hint">
                            <?php echo esc_html( __( 'Free plan: 1 item only. Upgrade to process up to 5.', 'ai-auto-poster' ) ); ?>
                            <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-field-link aiap-field-link-pro">
                                <?php echo esc_html( __( 'Upgrade to Pro', 'ai-auto-poster' ) ); ?> →
                            </a>
                        </span>
                    <?php endif; ?>
                </div>
                <p class="aiap-field-note"><?php echo esc_html( __( 'Recovered posts use the original scheduled date/time, not the actual run time.', 'ai-auto-poster' ) ); ?></p>
                <p class="submit aiap-section-submit"><button type="submit" class="button button-primary aiap-btn-primary"><span class="dashicons dashicons-saved" aria-hidden="true"></span> <?php echo esc_html( __( 'Save', 'ai-auto-poster' ) ); ?></button></p>
            </div>
            </form>
        </details>

        <?php // ===== Post Output Settings (Phase 2: アコーディオン化) ===== ?>
        <details class="aiap-section">
            <summary class="aiap-section-header">
                <h3 class="aiap-section-title"><?php echo esc_html( __( 'Post output', 'ai-auto-poster' ) ); ?></h3>
                <p class="aiap-section-sub"><?php echo esc_html( __( 'How generated posts appear on your site.', 'ai-auto-poster' ) ); ?></p>
            </summary>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-settings-form">
            <input type="hidden" name="action" value="aiap_save_output"><?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
            <div class="aiap-section-body">
                <div class="aiap-grid-2">
                    <div class="aiap-field">
                        <label class="aiap-field-label" for="aiap-post-status"><?php echo esc_html( __( 'Post Status', 'ai-auto-poster' ) ); ?></label>
                        <select id="aiap-post-status" class="aiap-select" name="post_status">
                            <?php foreach ( array('draft','pending','publish') as $v ) : ?>
                                <option value="<?php echo esc_attr( $v ); ?>" <?php selected( $s['post_status'], $v ); ?>><?php echo esc_html( AIAP_Admin_View::resolve_dynamic_key( $v ) ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="aiap-field">
                        <label class="aiap-field-label" for="aiap-post-category"><?php echo esc_html( __( 'Category', 'ai-auto-poster' ) ); ?></label>
                        <select id="aiap-post-category" class="aiap-select" name="post_category">
                            <option value="0"><?php echo esc_html( __( 'None', 'ai-auto-poster' ) ); ?></option>
                            <?php foreach ( $cats as $c ) : ?>
                                <option value="<?php echo esc_attr( $c->term_id ); ?>" <?php selected( $s['post_category'], $c->term_id ); ?>><?php echo esc_html( $c->name ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="aiap-field aiap-field-fullspan">
                        <label class="aiap-field-label" for="aiap-post-author"><?php echo esc_html( __( 'Author', 'ai-auto-poster' ) ); ?></label>
                        <select id="aiap-post-author" class="aiap-select" name="post_author">
                            <?php foreach ( $users as $u ) : ?>
                                <option value="<?php echo esc_attr( $u->ID ); ?>" <?php selected( $s['post_author'], $u->ID ); ?>><?php echo esc_html( $u->display_name ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <p class="submit aiap-section-submit"><button type="submit" class="button button-primary aiap-btn-primary"><span class="dashicons dashicons-saved" aria-hidden="true"></span> <?php echo esc_html( __( 'Save', 'ai-auto-poster' ) ); ?></button></p>
            </div>
            </form>
        </details>

        <?php // ===== Dedup ===== ?>
        <?php
        $dis = $is_pro ? '' : 'disabled';
        $dd_enabled = $is_pro && ! empty( $s['dedup_enabled'] );
        $dd_step1   = $is_pro ? ! empty( $s['dedup_step1'] ) : true;
        $dd_step2   = $is_pro ? ! empty( $s['dedup_step2'] ) : true;
        $dd_sens    = $is_pro && isset( $s['dedup_sensitivity'] ) ? $s['dedup_sensitivity'] : 'medium';
        $dd_retry   = $is_pro ? (int) ( $s['dedup_max_retry'] ?? 3 ) : 3;
        ?>
        <details class="aiap-section aiap-section-pro">
            <summary class="aiap-section-header">
                <div class="aiap-section-title-row">
                    <h3 class="aiap-section-title"><?php echo esc_html( __( 'Prevent duplicate articles', 'ai-auto-poster' ) ); ?></h3>
                    <span class="aiap-pro-pill"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                    <?php if ( ! $is_pro ) : ?>
                        <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-section-cta">
                            <?php echo esc_html( __( 'Upgrade to unlock', 'ai-auto-poster' ) ); ?> →
                        </a>
                    <?php endif; ?>
                </div>
            </summary>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-settings-form">
            <input type="hidden" name="action" value="aiap_save_dedup"><?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
            <div class="aiap-section-body <?php echo $is_pro ? '' : 'aiap-section-locked'; ?>">
                <div class="aiap-field">
                    <label class="aiap-checkbox-row">
                        <input type="checkbox" name="dedup_enabled" value="1" <?php checked( $dd_enabled ); ?> <?php echo esc_attr( $dis ); ?>>
                        <span>
                            <strong><?php echo esc_html( __( 'Avoid overlap with past posts', 'ai-auto-poster' ) ); ?></strong>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Compares new articles with the 20 most recent posts and rewrites if similar.', 'ai-auto-poster' ) ); ?></span>
                        </span>
                    </label>
                </div>

                <div class="aiap-field">
                    <span class="aiap-field-label"><?php echo esc_html( __( 'Detection method', 'ai-auto-poster' ) ); ?></span>
                    <label class="aiap-checkbox-row">
                        <input type="checkbox" name="dedup_step1" value="1" <?php checked( $dd_step1 ); ?> <?php echo esc_attr( $dis ); ?>>
                        <span>
                            <strong><?php echo esc_html( __( 'Method 1: Compare keywords', 'ai-auto-poster' ) ); ?></strong>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Compares keywords in titles and content.', 'ai-auto-poster' ) ); ?></span>
                        </span>
                    </label>
                    <label class="aiap-checkbox-row aiap-dedup-step2-row">
                        <input type="checkbox" name="dedup_step2" value="1" <?php checked( $dd_step2 ); ?> <?php echo esc_attr( $dis ); ?>>
                        <span>
                            <strong><?php echo esc_html( __( 'Method 2: Let AI judge', 'ai-auto-poster' ) ); ?></strong>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'AI scores similarity. More accurate but uses more API credits.', 'ai-auto-poster' ) ); ?></span>
                        </span>
                    </label>
                </div>

                <div class="aiap-field">
                    <span class="aiap-field-label"><?php echo esc_html( __( 'Sensitivity', 'ai-auto-poster' ) ); ?></span>
                    <div class="aiap-segment" role="radiogroup">
                        <?php foreach ( array( 'low', 'medium', 'high' ) as $sv ) : ?>
                            <label class="aiap-segment-option<?php echo $dd_sens === $sv ? ' is-active' : ''; ?>">
                                <input type="radio" name="dedup_sensitivity" value="<?php echo esc_attr( $sv ); ?>" <?php checked( $dd_sens, $sv ); ?> <?php echo esc_attr( $dis ); ?>>
                                <span><?php echo esc_html( AIAP_Admin_View::resolve_dynamic_key( 'dedup_sens_' . $sv ) ); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    <span class="aiap-field-hint"><?php echo esc_html( __( 'Applies to both methods. When both are ON, an article is regenerated only if both flag it.', 'ai-auto-poster' ) ); ?></span>
                </div>

                <div class="aiap-field">
                    <label class="aiap-field-label" for="aiap-dedup-retry"><?php echo esc_html( __( 'Max retries', 'ai-auto-poster' ) ); ?></label>
                    <div class="aiap-field-row">
                        <input type="number" id="aiap-dedup-retry" class="aiap-input-text aiap-input-narrow" name="dedup_max_retry" value="<?php echo esc_attr( $dd_retry ); ?>" min="1" max="10" <?php echo esc_attr( $dis ); ?>>
                        <span class="aiap-field-unit"><?php echo esc_html( __( 'retries', 'ai-auto-poster' ) ); ?></span>
                    </div>
                </div>
                <?php if ( $is_pro ) : ?>
                <p class="submit aiap-section-submit"><button type="submit" class="button button-primary aiap-btn-primary"><span class="dashicons dashicons-saved" aria-hidden="true"></span> <?php echo esc_html( __( 'Save', 'ai-auto-poster' ) ); ?></button></p>
                <?php endif; ?>
            </div>
            </form>
        </details>

        <?php // ===== SEO (Phase 2: アコーディオン化) ===== ?>
        <?php
        // Phase 12: 画像設定タブの「SEO セクションへ」リンクから来た場合は ?open=seo が付くので、
        // <details> を開いた状態で描画する。直接 #aiap-seo-section へスクロールしても、
        // アコーディオンが閉じたままだとユーザーは何も見えないので、open 属性を強制する。
        $aiap_open_seo = isset( $_GET['open'] ) && sanitize_key( wp_unslash( $_GET['open'] ) ) === 'seo';
        ?>
        <details class="aiap-section aiap-section-pro" id="aiap-seo-section" data-aiap-anchor="seo"<?php echo $aiap_open_seo ? ' open' : ''; ?>>
            <summary class="aiap-section-header">
                <div class="aiap-section-title-row">
                    <h3 class="aiap-section-title"><?php echo esc_html( __( 'SEO optimization', 'ai-auto-poster' ) ); ?></h3>
                    <span class="aiap-pro-pill"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                    <?php if ( ! $is_pro ) : ?>
                        <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-section-cta">
                            <?php echo esc_html( __( 'Upgrade to unlock', 'ai-auto-poster' ) ); ?> →
                        </a>
                    <?php endif; ?>
                </div>
            </summary>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-settings-form">
            <input type="hidden" name="action" value="aiap_save_seo"><?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
            <div class="aiap-section-body <?php echo $is_pro ? '' : 'aiap-section-locked'; ?>">
                <div class="aiap-field">
                    <label class="aiap-checkbox-row">
                        <input type="checkbox" name="seo_enabled" value="1" <?php checked( $is_pro && ! empty( $s['seo_enabled'] ) ); ?> id="aiap-seo-switch" <?php echo $is_pro ? '' : 'disabled'; ?>>
                        <span>
                            <strong><?php echo esc_html( __( 'Enable SEO optimization', 'ai-auto-poster' ) ); ?></strong>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Automatically applies search engine optimization to generated articles.', 'ai-auto-poster' ) ); ?></span>
                        </span>
                    </label>
                </div>
                <p class="aiap-toggle-row">
                    <button type="button" class="aiap-btn js-aiap-toggle" data-target="aiap-seo-detail" <?php echo $is_pro ? '' : 'disabled'; ?>>
                        <span class="dashicons dashicons-admin-generic" aria-hidden="true"></span>
                        <?php echo esc_html( __( 'SEO options', 'ai-auto-poster' ) ); ?>
                    </button>
                </p>
                <div id="aiap-seo-detail" class="aiap-seo-detail" hidden>
                    <?php
                    $seo_groups = array(
                        'seo_content_group'   => array( 'seo_meta_desc','seo_heading','seo_focus_kw','seo_faq','seo_toc','seo_template' ),
                        'seo_image_group'     => array( 'seo_img_alt','seo_img_webp' ),
                        'seo_structure_group' => array( 'seo_internal_link','seo_auto_tag','seo_related' ),
                        'seo_meta_group'      => array( 'seo_schema','seo_ogp','seo_canonical','seo_plugin_link' ),
                        'seo_other_group'     => array( 'seo_reading_time','seo_sitemap_ping','seo_llms_txt' ),
                    );
                    $seo_standard = array(
                        'seo_meta_desc'     => 1,
                        'seo_heading'       => 1,
                        'seo_focus_kw'      => 1,
                        'seo_img_alt'       => 1,
                        'seo_internal_link' => 1,
                        'seo_auto_tag'      => 1,
                        'seo_schema'        => 1,
                    );
                    $disabled_attr = $is_pro ? '' : ' disabled';
                    foreach ( $seo_groups as $group_key => $fields ) :
                        echo '<span class="aiap-seo-group-label">' . esc_html( AIAP_Admin_View::resolve_dynamic_key( $group_key ) ) . '</span>';
                        foreach ( $fields as $f ) :
                            $checked_state = $is_pro ? ! empty( $s[ $f ] ) : ! empty( $seo_standard[ $f ] );
                            echo '<label class="aiap-seo-check"><input type="checkbox" name="' . esc_attr( $f ) . '" value="1" ' . checked( $checked_state, true, false ) . esc_attr( $disabled_attr ) . '> <span>' . esc_html( AIAP_Admin_View::resolve_dynamic_key( $f ) ) . '</span></label>';
                        endforeach;
                    endforeach;
                    ?>
                </div>
                <?php if ( $is_pro ) : ?>
                <p class="submit aiap-section-submit"><button type="submit" class="button button-primary aiap-btn-primary"><span class="dashicons dashicons-saved" aria-hidden="true"></span> <?php echo esc_html( __( 'Save', 'ai-auto-poster' ) ); ?></button></p>
                <?php endif; ?>
            </div>
            </form>
        </details>

        <?php
    }

}
