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

/**
 * タスク管理タブのレンダリング + アコーディオンセクション用ヘルパ
 *
 * 元 admin/class-aiap-admin-view.php から分離。
 * 共通基盤 (resolve_dynamic_key, tab_label, meta_label, log_message)
 * は親クラス AIAP_Admin_View にあるため、そちらを直接参照する。
 */
class AIAP_Admin_View_Tasks {

    // ================================================================
    // タスク一覧 (Phase 9: 別タブに分離 + 1 行レイアウト)
    // ================================================================
    public static function render_tasks( $s ) {
        $tasks = AIAP_Prompts::get_all();
        $days  = array( 'mon','tue','wed','thu','fri','sat','sun' );
        $langs = AIAP_AI_Client::get_language_options();
        $im    = AIAP_Image_Client::get_settings();
        ?>
        <header class="aiap-provider-hero">
            <span class="aiap-provider-hero-eyebrow"><?php echo esc_html( __( 'Tasks', 'ai-auto-poster' ) ); ?></span>
            <h2 class="aiap-provider-hero-title"><?php echo esc_html( __( 'Scheduled posting tasks', 'ai-auto-poster' ) ); ?></h2>
            <?php /* Phase 12: 旧 hero sub に「システムプロンプトは全タスク共通で使われます」が含まれていたが、
                   システムプロンプトはこの画面では編集できない別タブの機能で、ここで言及してもユーザーは
                   「で、それどこ?」となるだけ。タスクの説明だけに絞った。 */ ?>
            <p class="aiap-provider-hero-sub"><?php echo esc_html( __( 'Each task is a prompt + schedule.', 'ai-auto-poster' ) ); ?></p>
        </header>

        <?php
        if ( ! AIAP_License::is_pro() ) {
            $weekly_count = 0;
            foreach ( $tasks as $t ) {
                if ( empty( $t['enabled'] ) ) continue;
                $sched = isset( $t['schedule'] ) && is_array( $t['schedule'] ) ? $t['schedule'] : array();
                foreach ( $days as $d ) {
                    if ( ! empty( $sched[ $d ] ) && is_array( $sched[ $d ] ) ) {
                        $weekly_count += count( array_filter( $sched[ $d ], 'strlen' ) );
                    }
                }
            }
            $monthly_estimate = (int) round( $weekly_count * 4.345 );
            $free_limit = AIAP_License::FREE_MONTHLY_LIMIT;
            if ( $monthly_estimate > $free_limit ) :
                ?>
                <div class="aiap-banner aiap-banner-warning">
                    <span class="dashicons dashicons-warning" aria-hidden="true"></span>
                    <span class="aiap-banner-text">
                        <strong><?php
                            /* translators: 1: estimated monthly posts, 2: free plan limit */
                            echo esc_html( sprintf( __( 'Estimated %1$d posts/month from current schedule, but Free plan allows only %2$d.', 'ai-auto-poster' ), $monthly_estimate, $free_limit ) );
                        ?></strong>
                        <span><?php echo esc_html( __( 'Posts beyond the limit will be skipped automatically.', 'ai-auto-poster' ) ); ?></span>
                    </span>
                    <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-banner-cta">
                        <span class="dashicons dashicons-star-filled" aria-hidden="true"></span>
                        <?php echo esc_html( __( 'Upgrade', 'ai-auto-poster' ) ); ?>
                    </a>
                </div>
                <?php
            endif;
        }
        ?>

        <div class="aiap-section">
            <div class="aiap-section-header aiap-section-header-with-action">
                <?php /* Phase 12: section title「Tasks」は hero eyebrow と完全に重複していたので削除。
                       カウントバッジと CTA ボタンだけ残し、ヘッダ機能は維持する。 */ ?>
                <div class="aiap-section-title-row">
                    <span class="aiap-section-count"><?php echo esc_html( count( $tasks ) ); ?></span>
                </div>
                <button type="button" class="button button-primary js-aiap-toggle-add-task aiap-btn-primary aiap-section-header-cta">
                    <span class="dashicons dashicons-plus-alt" aria-hidden="true"></span>
                    <?php echo esc_html( __( 'Add Task', 'ai-auto-poster' ) ); ?>
                </button>
            </div>
            <div class="aiap-section-body">
                <?php if ( empty( $tasks ) ) : ?>
                    <div class="aiap-empty-state">
                        <span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
                        <p><?php echo esc_html( __( 'No tasks yet.', 'ai-auto-poster' ) ); ?></p>
                        <p class="aiap-empty-state-sub"><?php echo esc_html( __( 'Add your first task using the button above.', 'ai-auto-poster' ) ); ?></p>
                    </div>
                <?php else : ?>
                    <div class="aiap-task-list">
                        <?php $task_index = 0; foreach ( $tasks as $task ) :
                            $task_index++;
                            $is_on   = ! empty( $task['enabled'] );
                            $sched_summary = AIAP_Prompts::format_schedule_summary( $task );
                            $last_run_meta = isset( $task['last_run'] ) ? (string) $task['last_run'] : '';
                        ?>
                            <div class="aiap-task-card<?php echo $is_on ? ' is-enabled' : ' is-disabled'; ?>">
                                <div class="aiap-task-card-row aiap-task-card-row-compact">
                                    <span class="aiap-task-status-dot<?php echo $is_on ? ' is-on' : ''; ?>" aria-hidden="true"></span>
                                    <div class="aiap-task-card-main">
                                        <div class="aiap-task-name-line">
                                            <span class="aiap-task-name"><?php echo esc_html( AIAP_Prompts::get_display_name( $task, $task_index ) ); ?></span>
                                            <span class="aiap-task-id-mini"><?php
                                                /* translators: %d = sequential task number (1-based) */
                                                echo esc_html( sprintf( __( '#%d', 'ai-auto-poster' ), $task_index ) );
                                            ?></span>
                                        </div>
                                        <div class="aiap-task-card-meta-line">
                                            <span class="aiap-task-meta-item" title="<?php echo esc_attr( __( 'Schedule', 'ai-auto-poster' ) ); ?>">
                                                <span class="dashicons dashicons-clock" aria-hidden="true"></span>
                                                <?php echo esc_html( $sched_summary ); ?>
                                            </span>
                                            <span class="aiap-task-meta-item" title="<?php echo esc_attr( __( 'Run count', 'ai-auto-poster' ) ); ?>">
                                                <span class="dashicons dashicons-update" aria-hidden="true"></span>
                                                <?php
                                                /* translators: %d = times this task has been run */
                                                echo esc_html( sprintf( _n( 'Run %d time', 'Run %d times', (int) $task['used_count'], 'ai-auto-poster' ), (int) $task['used_count'] ) );
                                                ?>
                                            </span>
                                            <?php if ( $last_run_meta ) : ?>
                                                <span class="aiap-task-meta-item" title="<?php echo esc_attr( __( 'Last run', 'ai-auto-poster' ) ); ?>">
                                                    <span class="dashicons dashicons-yes-alt" aria-hidden="true"></span>
                                                    <?php echo esc_html( $last_run_meta ); ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="aiap-task-card-actions">
                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-inline-form">
                                            <input type="hidden" name="action" value="aiap_toggle_task">
                                            <input type="hidden" name="task_id" value="<?php echo esc_attr( $task['id'] ); ?>">
                                            <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                                            <label class="aiap-toggle-switch" title="<?php echo esc_attr( AIAP_Admin_View::resolve_dynamic_key( $is_on ? 'deactivate' : 'activate' ) ); ?>" aria-label="<?php echo esc_attr( AIAP_Admin_View::resolve_dynamic_key( $is_on ? 'deactivate' : 'activate' ) ); ?>">
                                                <input type="checkbox" <?php checked( $is_on ); ?> class="js-aiap-task-toggle-cb">
                                                <span class="aiap-toggle-slider"></span>
                                            </label>
                                        </form>
                                        <button type="button" class="aiap-btn aiap-btn-icon-only js-aiap-edit-task" data-target="aiap-task-edit-<?php echo esc_attr( $task['id'] ); ?>" title="<?php echo esc_attr( __( 'Edit', 'ai-auto-poster' ) ); ?>" aria-label="<?php echo esc_attr( __( 'Edit', 'ai-auto-poster' ) ); ?>">
                                            <span class="dashicons dashicons-edit" aria-hidden="true"></span>
                                        </button>
                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-inline-form js-aiap-confirm" data-confirm="<?php echo esc_attr( __( 'Delete this task?', 'ai-auto-poster' ) ); ?>">
                                            <input type="hidden" name="action" value="aiap_delete_task">
                                            <input type="hidden" name="task_id" value="<?php echo esc_attr( $task['id'] ); ?>">
                                            <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                                            <button type="submit" class="aiap-btn aiap-btn-icon-only aiap-btn-danger-icon" title="<?php echo esc_attr( __( 'Delete', 'ai-auto-poster' ) ); ?>" aria-label="<?php echo esc_attr( __( 'Delete', 'ai-auto-poster' ) ); ?>">
                                                <span class="dashicons dashicons-trash" aria-hidden="true"></span>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                                <details class="aiap-task-edit" id="aiap-task-edit-<?php echo esc_attr( $task['id'] ); ?>">
                                    <summary hidden></summary>
                                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-task-edit-form">
                                        <input type="hidden" name="action" value="aiap_edit_task">
                                        <input type="hidden" name="task_id" value="<?php echo esc_attr( $task['id'] ); ?>">
                                        <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                                        <div class="aiap-field">
                                            <label class="aiap-field-label"><?php echo esc_html( __( 'Task name', 'ai-auto-poster' ) ); ?> <span class="aiap-field-label-hint"><?php echo esc_html( __( 'optional', 'ai-auto-poster' ) ); ?></span></label>
                                            <input type="text" name="task_name" class="aiap-input-text" maxlength="60" value="<?php echo esc_attr( $task['name'] ?? '' ); ?>" placeholder="<?php echo esc_attr( __( 'e.g. Daily nature observations', 'ai-auto-poster' ) ); ?>">
                                            <span class="aiap-field-hint"><?php echo esc_html( __( 'A short label to identify this task. Leave blank to auto-generate from the prompt.', 'ai-auto-poster' ) ); ?></span>
                                        </div>
                                        <div class="aiap-field">
                                            <label class="aiap-field-label"><?php echo esc_html( __( 'Prompt', 'ai-auto-poster' ) ); ?> <span class="aiap-required" aria-hidden="true">*</span></label>
                                            <textarea name="prompt" rows="6" class="aiap-editor-textarea aiap-editor-textarea-mono" required><?php echo esc_textarea( $task['prompt'] ); ?></textarea>
                                        </div>
                                        <div class="aiap-grid-2">
                                            <div class="aiap-field">
                                                <label class="aiap-field-label"><?php echo esc_html( __( 'Content Language', 'ai-auto-poster' ) ); ?> <span class="aiap-required" aria-hidden="true">*</span></label>
                                                <?php $cur_lang = isset( $task['content_language'] ) ? $task['content_language'] : ''; ?>
                                                <select name="task_content_language" class="aiap-select" required>
                                                    <option value="" disabled <?php selected( '', $cur_lang ); ?> hidden><?php echo esc_html( __( '(Please select)', 'ai-auto-poster' ) ); ?></option>
                                                    <?php foreach ( $langs as $v => $l ) : ?>
                                                        <option value="<?php echo esc_attr( $v ); ?>" <?php selected( $cur_lang, $v ); ?>><?php echo esc_html( $l ); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="aiap-field">
                                                <label class="aiap-field-label"><?php echo esc_html( __( 'Content Length', 'ai-auto-poster' ) ); ?></label>
                                                <div class="aiap-field-row">
                                                    <input type="number" name="task_content_length" value="<?php echo esc_attr( ! empty( $task['content_length'] ) ? (int) $task['content_length'] : '' ); ?>" min="0" max="10000" class="aiap-input-text aiap-input-narrow" placeholder="0">
                                                    <span class="aiap-field-unit"><?php echo esc_html( __( 'chars', 'ai-auto-poster' ) ); ?></span>
                                                </div>
                                                <span class="aiap-field-hint"><?php echo esc_html( __( '0 = unlimited', 'ai-auto-poster' ) ); ?></span>
                                            </div>
                                        </div>
                                        <details class="aiap-task-section aiap-task-section--image" data-aiap-section="image" <?php echo self::is_section_expanded( 'image', $task ) ? 'open' : ''; ?>>
                                            <summary class="aiap-task-section__summary">
                                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                                <span class="aiap-task-section__icon dashicons dashicons-format-image" aria-hidden="true"></span>
                                                <span class="aiap-task-section__title"><?php echo esc_html( __( 'Featured image', 'ai-auto-poster' ) ); ?></span>
                                                <?php if ( self::is_section_configured( 'image', $task ) ) : ?>
                                                    <span class="aiap-task-section__configured-badge"><?php echo esc_html__( 'Configured', 'ai-auto-poster' ); ?></span>
                                                <?php endif; ?>
                                                <?php $image_summary = self::build_image_section_summary( $task ); if ( $image_summary !== '' ) : ?>
                                                    <span class="aiap-task-section__summary-text"><?php echo esc_html( $image_summary ); ?></span>
                                                <?php endif; ?>
                                            </summary>
                                            <div class="aiap-task-section__body">
                                                <?php $cur_img_mode = AIAP_Prompts::get_image_mode( $task ); ?>
                                                <label class="aiap-radio-row"><input type="radio" name="task_featured_image_mode" value="on" <?php checked( $cur_img_mode !== 'off' ); ?>> <span><?php echo esc_html( __( 'Always attach', 'ai-auto-poster' ) ); ?></span></label>
                                                <label class="aiap-radio-row"><input type="radio" name="task_featured_image_mode" value="off" <?php checked( $cur_img_mode === 'off' ); ?>> <span><?php echo esc_html( __( "Don't attach", 'ai-auto-poster' ) ); ?></span></label>
                                            </div>
                                        </details>
                                        <?php
                                        $is_pro_for_rss = class_exists( 'AIAP_License' ) && AIAP_License::is_pro();
                                        $rss_settings   = AIAP_Prompts::get_rss_settings( $task );
                                        $all_feeds      = class_exists( 'AIAP_RSS_Feeds' ) ? AIAP_RSS_Feeds::get_all() : array();
                                        ?>
                                        <details class="aiap-task-section aiap-task-section--rss" data-aiap-section="rss" data-aiap-rss-section data-aiap-configured-label="<?php echo esc_attr__( 'Configured', 'ai-auto-poster' ); ?>" <?php echo self::is_section_expanded( 'rss', $task ) ? 'open' : ''; ?>>
                                            <summary class="aiap-task-section__summary">
                                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                                <span class="aiap-task-section__icon dashicons dashicons-rss" aria-hidden="true"></span>
                                                <span class="aiap-task-section__title"><?php echo esc_html__( 'RSS Settings', 'ai-auto-poster' ); ?></span>
                                                <span class="aiap-pro-pill"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                                                <?php if ( self::is_section_configured( 'rss', $task ) ) : ?>
                                                    <span class="aiap-task-section__configured-badge"><?php echo esc_html__( 'Configured', 'ai-auto-poster' ); ?></span>
                                                <?php endif; ?>
                                                <?php $rss_summary = self::build_rss_section_summary( $task ); if ( $rss_summary !== '' ) : ?>
                                                    <span class="aiap-task-section__summary-text"><?php echo esc_html( $rss_summary ); ?></span>
                                                <?php else : ?>
                                                    <span class="aiap-task-section__summary-text"><?php echo esc_html__( '(optional)', 'ai-auto-poster' ); ?></span>
                                                <?php endif; ?>
                                            </summary>
                                            <div class="aiap-task-section__body">

                                            <?php if ( ! $is_pro_for_rss ) : ?>
                                                <p class="aiap-pro-badge"><?php echo esc_html__( 'This is a Pro feature.', 'ai-auto-poster' ); ?></p>
                                            <?php endif; ?>

                                            <fieldset <?php echo $is_pro_for_rss ? '' : 'disabled'; ?>>
                                                <p>
                                                    <label>
                                                        <input type="checkbox" name="rss_enabled" value="1" class="js-aiap-task-rss-enable" <?php checked( 1, (int) $rss_settings['rss_enabled'] ); ?> />
                                                        <?php echo esc_html__( 'Use RSS as source material', 'ai-auto-poster' ); ?>
                                                    </label>
                                                </p>

                                                <div class="aiap-task-rss-detail" data-aiap-rss-detail>
                                                    <?php if ( empty( $all_feeds ) ) : ?>
                                                        <p class="description aiap-task-rss-empty">
                                                            <?php echo esc_html__( 'Register an RSS feed first.', 'ai-auto-poster' ); ?>
                                                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=' . AIAP_Admin::MENU_SLUG . '&tab=rss_feeds' ) ); ?>">
                                                                <?php echo esc_html__( 'Open RSS Feeds tab', 'ai-auto-poster' ); ?>
                                                            </a>
                                                        </p>
                                                    <?php else : ?>
                                                        <p>
                                                            <strong><?php echo esc_html__( 'Source feeds', 'ai-auto-poster' ); ?></strong><br/>
                                                            <?php foreach ( $all_feeds as $feed ) :
                                                                $fid = isset( $feed['id'] )   ? $feed['id']   : '';
                                                                $fnm = isset( $feed['name'] ) ? $feed['name'] : '';
                                                                $chk = in_array( $fid, $rss_settings['rss_feed_ids'], true );
                                                            ?>
                                                                <label class="aiap-task-rss-feed">
                                                                    <input type="checkbox" name="rss_feed_ids[]" value="<?php echo esc_attr( $fid ); ?>" <?php checked( $chk ); ?> />
                                                                    <?php echo esc_html( $fnm ); ?>
                                                                </label><br/>
                                                            <?php endforeach; ?>
                                                        </p>

                                                        <p>
                                                            <label>
                                                                <?php echo esc_html__( 'Item count', 'ai-auto-poster' ); ?>
                                                                <input type="number" name="rss_count" min="1" max="<?php echo esc_attr( AIAP_RSS_Feeds::COUNT_MAX ); ?>" step="1" value="<?php echo esc_attr( (int) $rss_settings['rss_count'] ); ?>" />
                                                            </label>
                                                        </p>

                                                        <p>
                                                            <strong><?php echo esc_html__( 'Mode', 'ai-auto-poster' ); ?></strong><br/>
                                                            <label><input type="radio" name="rss_mode" value="pick"   <?php checked( 'pick',   $rss_settings['rss_mode'] ); ?> /> <?php echo esc_html__( 'Pickup (AI picks one)', 'ai-auto-poster' ); ?></label><br/>
                                                            <label><input type="radio" name="rss_mode" value="digest" <?php checked( 'digest', $rss_settings['rss_mode'] ); ?> /> <?php echo esc_html__( 'Digest (summarize all)', 'ai-auto-poster' ); ?></label>
                                                        </p>

                                                        <p>
                                                            <strong><?php echo esc_html__( 'When no fresh articles:', 'ai-auto-poster' ); ?></strong><br/>
                                                            <label><input type="radio" name="rss_fallback" value="skip"     <?php checked( 'skip',     $rss_settings['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Skip post', 'ai-auto-poster' ); ?></label><br/>
                                                            <label><input type="radio" name="rss_fallback" value="generate" <?php checked( 'generate', $rss_settings['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Generate without RSS', 'ai-auto-poster' ); ?></label>
                                                        </p>
                                                    <?php endif; ?>
                                                </div>
                                            </fieldset>
                                            </div>
                                        </details>
                                        <details class="aiap-task-section aiap-task-section--schedule" data-aiap-section="schedule" <?php echo self::is_section_expanded( 'schedule', $task ) ? 'open' : ''; ?>>
                                            <summary class="aiap-task-section__summary">
                                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                                <span class="aiap-task-section__icon dashicons dashicons-calendar-alt" aria-hidden="true"></span>
                                                <span class="aiap-task-section__title"><?php echo esc_html__( 'Schedule', 'ai-auto-poster' ); ?></span>
                                                <?php if ( self::is_section_configured( 'schedule', $task ) ) : ?>
                                                    <span class="aiap-task-section__configured-badge"><?php echo esc_html__( 'Configured', 'ai-auto-poster' ); ?></span>
                                                <?php endif; ?>
                                                <span class="aiap-task-section__summary-text"><?php echo esc_html( self::build_schedule_section_summary( $task ) ); ?></span>
                                            </summary>
                                            <div class="aiap-task-section__body">
                                        <div class="aiap-field">
                                            <label class="aiap-checkbox-row">
                                                <input type="checkbox" name="task_random_mode" value="1" data-aiap-random-toggle="1" <?php checked( ! empty( $task['random_mode'] ) ); ?>>
                                                <span><strong><?php echo esc_html( __( 'Random mode', 'ai-auto-poster' ) ); ?></strong></span>
                                            </label>
                                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Posts at random times and a random count per day.', 'ai-auto-poster' ) ); ?></span>
                                        </div>
                                        <?php
                                        $rm_on        = ! empty( $task['random_mode'] );
                                        $rm_min       = isset( $task['random_count_min'] ) ? (int) $task['random_count_min'] : 0;
                                        $rm_max       = isset( $task['random_count_max'] ) ? (int) $task['random_count_max'] : 0;
                                        $rm_allowed   = ( isset( $task['allowed_periods'] ) && is_array( $task['allowed_periods'] ) ) ? $task['allowed_periods'] : array();
                                        $rm_interval  = isset( $task['min_interval_minutes'] ) ? (int) $task['min_interval_minutes'] : 0;
                                        ?>
                                        <div class="aiap-random-fields<?php echo $rm_on ? '' : ' aiap-hidden'; ?>" data-aiap-random-fields>
                                            <div class="aiap-field">
                                                <label class="aiap-field-label"><?php echo esc_html( __( 'Posts per day', 'ai-auto-poster' ) ); ?></label>
                                                <div class="aiap-counts-row">
                                                    <input type="number" name="task_random_count_min" value="<?php echo esc_attr( $rm_min ); ?>" min="0" max="50" class="aiap-input-text">
                                                    <span class="aiap-counts-sep"><?php echo esc_html( __( 'to', 'ai-auto-poster' ) ); ?></span>
                                                    <input type="number" name="task_random_count_max" value="<?php echo esc_attr( $rm_max ); ?>" min="0" max="50" class="aiap-input-text">
                                                    <span class="aiap-field-unit"><?php echo esc_html( __( '/ day (0–50)', 'ai-auto-poster' ) ); ?></span>
                                                </div>
                                            </div>
                                            <div class="aiap-field">
                                                <label class="aiap-field-label"><?php echo esc_html( __( 'Allowed time ranges (post only here)', 'ai-auto-poster' ) ); ?></label>
                                                <div class="aiap-allowed-list" data-aiap-allowed-list>
                                                    <?php foreach ( $rm_allowed as $api => $ap ) : ?>
                                                        <div class="aiap-allowed-row" data-aiap-allowed-row>
                                                            <input type="time" name="task_allowed_periods[<?php echo (int) $api; ?>][start]" value="<?php echo esc_attr( $ap['start'] ?? '' ); ?>" step="60" class="aiap-input-text">
                                                            <span class="aiap-counts-sep">–</span>
                                                            <input type="time" name="task_allowed_periods[<?php echo (int) $api; ?>][end]" value="<?php echo esc_attr( $ap['end'] ?? '' ); ?>" step="60" class="aiap-input-text">
                                                            <div class="aiap-allowed-actions">
                                                                <button type="button" class="button" data-aiap-allowed-remove><?php echo esc_html( __( 'Remove', 'ai-auto-poster' ) ); ?></button>
                                                                <button type="button" class="button" data-aiap-allowed-add><?php echo esc_html( __( '+ Add', 'ai-auto-poster' ) ); ?></button>
                                                            </div>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php // 0 行のとき表示する「再追加」ボタン (行があれば JS で隠す) ?>
                                                <button type="button" class="button aiap-allowed-add-empty<?php echo ! empty( $rm_allowed ) ? ' aiap-hidden' : ''; ?>" data-aiap-allowed-add-empty><?php echo esc_html( __( '+ Add time range', 'ai-auto-poster' ) ); ?></button>
                                                <span class="aiap-field-hint"><?php echo esc_html( __( 'If empty, all 24 hours are allowed. Format: HH:MM – HH:MM. Crossing midnight (e.g. 22:00 – 07:00) is allowed.', 'ai-auto-poster' ) ); ?></span>
                                            </div>
                                            <div class="aiap-field">
                                                <label class="aiap-field-label"><?php echo esc_html( __( 'Minimum interval between posts', 'ai-auto-poster' ) ); ?></label>
                                                <div class="aiap-counts-row">
                                                    <input type="number" name="task_min_interval_minutes" value="<?php echo esc_attr( $rm_interval ); ?>" min="0" max="720" step="1" class="aiap-input-text">
                                                    <span class="aiap-field-unit"><?php echo esc_html( __( 'minutes (0 = no minimum)', 'ai-auto-poster' ) ); ?></span>
                                                </div>
                                                <span class="aiap-field-hint"><?php echo esc_html( __( 'If you cannot fit "posts per day" with this interval, fewer posts will be scheduled.', 'ai-auto-poster' ) ); ?></span>
                                            </div>
                                        </div>
                                        <div class="aiap-schedule-fields<?php echo $rm_on ? ' aiap-hidden' : ''; ?>" data-aiap-schedule-fields>
                                        <div class="aiap-field">
                                            <label class="aiap-field-label"><?php echo esc_html( __( 'Schedule', 'ai-auto-poster' ) ); ?></label>
                                            <div class="aiap-sched-grid">
                                                <?php foreach ( $days as $dk ) : $task_times = isset( $task['schedule'][ $dk ] ) && is_array( $task['schedule'][ $dk ] ) ? implode( ', ', $task['schedule'][ $dk ] ) : ''; ?>
                                                    <div class="aiap-sched-row">
                                                        <span class="aiap-sched-day"><?php echo esc_html( AIAP_Admin_View::resolve_dynamic_key( $dk ) ); ?></span>
                                                        <input type="text" name="schedule[<?php echo esc_attr( $dk ); ?>]" class="aiap-input-text" value="<?php echo esc_attr( $task_times ); ?>" placeholder="09:00, 14:00">
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Comma-separated times. Empty = skip that day.', 'ai-auto-poster' ) ); ?></span>
                                        </div>
                                        </div>
                                            </div>
                                        </details>
                                        <div class="aiap-field">
                                            <label class="aiap-checkbox-row">
                                                <input type="checkbox" name="task_enabled" value="1" <?php checked( ! empty( $task['enabled'] ) ); ?>>
                                                <span><strong><?php echo esc_html( __( 'Enable this task', 'ai-auto-poster' ) ); ?></strong></span>
                                            </label>
                                        </div>
                                        <div class="aiap-task-edit-action">
                                            <button type="button" class="aiap-btn js-aiap-cancel-edit-task"><span class="dashicons dashicons-no" aria-hidden="true"></span> <?php echo esc_html( __( 'Cancel', 'ai-auto-poster' ) ); ?></button>
                                            <button type="submit" class="aiap-btn aiap-btn-primary"><span class="dashicons dashicons-saved" aria-hidden="true"></span> <?php echo esc_html( __( 'Save', 'ai-auto-poster' ) ); ?></button>
                                        </div>
                                    </form>
                                </details>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="aiap-add-task-wrapper" data-collapsed="1">
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-add-task-form" hidden>
                <input type="hidden" name="action" value="aiap_add_task"><?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                <div class="aiap-section">
                    <div class="aiap-section-header">
                        <h3 class="aiap-section-title"><?php echo esc_html( __( 'New task', 'ai-auto-poster' ) ); ?></h3>
                    </div>
                    <div class="aiap-section-body">
                        <div class="aiap-field">
                            <label class="aiap-field-label"><?php echo esc_html( __( 'Task name', 'ai-auto-poster' ) ); ?> <span class="aiap-field-label-hint"><?php echo esc_html( __( 'optional', 'ai-auto-poster' ) ); ?></span></label>
                            <input type="text" name="task_name" class="aiap-input-text" maxlength="60" placeholder="<?php echo esc_attr( __( 'e.g. Daily nature observations', 'ai-auto-poster' ) ); ?>">
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'A short label to identify this task. Leave blank to auto-generate from the prompt.', 'ai-auto-poster' ) ); ?></span>
                        </div>
                        <div class="aiap-field">
                            <label class="aiap-field-label"><?php echo esc_html( __( 'Prompt', 'ai-auto-poster' ) ); ?> <span class="aiap-required" aria-hidden="true">*</span></label>
                            <textarea name="prompt" rows="6" class="aiap-editor-textarea aiap-editor-textarea-mono" placeholder="<?php echo esc_attr( __( 'What should this task write about?', 'ai-auto-poster' ) ); ?>" required></textarea>
                        </div>
                        <div class="aiap-grid-2">
                            <div class="aiap-field">
                                <label class="aiap-field-label"><?php echo esc_html( __( 'Content Language', 'ai-auto-poster' ) ); ?> <span class="aiap-required" aria-hidden="true">*</span></label>
                                <select name="task_content_language" class="aiap-select" required>
                                    <option value="" disabled selected hidden><?php echo esc_html( __( '(Please select)', 'ai-auto-poster' ) ); ?></option>
                                    <?php foreach ( $langs as $v => $l ) : ?>
                                        <option value="<?php echo esc_attr( $v ); ?>"><?php echo esc_html( $l ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="aiap-field">
                                <label class="aiap-field-label"><?php echo esc_html( __( 'Content Length', 'ai-auto-poster' ) ); ?></label>
                                <div class="aiap-field-row">
                                    <input type="number" name="task_content_length" value="" min="0" max="10000" class="aiap-input-text aiap-input-narrow" placeholder="0">
                                    <span class="aiap-field-unit"><?php echo esc_html( __( 'chars', 'ai-auto-poster' ) ); ?></span>
                                </div>
                            </div>
                        </div>
                        <details class="aiap-task-section aiap-task-section--image" data-aiap-section="image" <?php echo self::is_section_expanded( 'image', array(), true ) ? 'open' : ''; ?>>
                            <summary class="aiap-task-section__summary">
                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                <span class="aiap-task-section__icon dashicons dashicons-format-image" aria-hidden="true"></span>
                                <span class="aiap-task-section__title"><?php echo esc_html( __( 'Featured image', 'ai-auto-poster' ) ); ?></span>
                                <span class="aiap-task-section__summary-text"><?php echo esc_html__( '(optional)', 'ai-auto-poster' ); ?></span>
                            </summary>
                            <div class="aiap-task-section__body">
                                <label class="aiap-radio-row"><input type="radio" name="task_featured_image_mode" value="on" checked> <span><?php echo esc_html( __( 'Always attach', 'ai-auto-poster' ) ); ?></span></label>
                                <label class="aiap-radio-row"><input type="radio" name="task_featured_image_mode" value="off"> <span><?php echo esc_html( __( "Don't attach", 'ai-auto-poster' ) ); ?></span></label>
                            </div>
                        </details>
                        <?php
                        $is_pro_for_rss  = class_exists( 'AIAP_License' ) && AIAP_License::is_pro();
                        $rss_settings    = AIAP_Prompts::get_rss_settings( array() );
                        $all_feeds       = class_exists( 'AIAP_RSS_Feeds' ) ? AIAP_RSS_Feeds::get_all() : array();
                        ?>
                        <details class="aiap-task-section aiap-task-section--rss" data-aiap-section="rss" data-aiap-rss-section data-aiap-configured-label="<?php echo esc_attr__( 'Configured', 'ai-auto-poster' ); ?>" <?php echo self::is_section_expanded( 'rss', array(), true ) ? 'open' : ''; ?>>
                            <summary class="aiap-task-section__summary">
                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                <span class="aiap-task-section__icon dashicons dashicons-rss" aria-hidden="true"></span>
                                <span class="aiap-task-section__title"><?php echo esc_html__( 'RSS Settings', 'ai-auto-poster' ); ?></span>
                                <span class="aiap-pro-pill"><?php echo esc_html( __( 'PRO', 'ai-auto-poster' ) ); ?></span>
                                <span class="aiap-task-section__summary-text"><?php echo esc_html__( '(optional)', 'ai-auto-poster' ); ?></span>
                            </summary>
                            <div class="aiap-task-section__body">

                            <?php if ( ! $is_pro_for_rss ) : ?>
                                <p class="aiap-pro-badge"><?php echo esc_html__( 'This is a Pro feature.', 'ai-auto-poster' ); ?></p>
                            <?php endif; ?>

                            <fieldset <?php echo $is_pro_for_rss ? '' : 'disabled'; ?>>
                                <p>
                                    <label>
                                        <input type="checkbox" name="rss_enabled" value="1" class="js-aiap-task-rss-enable" <?php checked( 1, (int) $rss_settings['rss_enabled'] ); ?> />
                                        <?php echo esc_html__( 'Use RSS as source material', 'ai-auto-poster' ); ?>
                                    </label>
                                </p>

                                <div class="aiap-task-rss-detail" data-aiap-rss-detail>
                                    <?php if ( empty( $all_feeds ) ) : ?>
                                        <p class="description aiap-task-rss-empty">
                                            <?php echo esc_html__( 'Register an RSS feed first.', 'ai-auto-poster' ); ?>
                                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=' . AIAP_Admin::MENU_SLUG . '&tab=rss_feeds' ) ); ?>">
                                                <?php echo esc_html__( 'Open RSS Feeds tab', 'ai-auto-poster' ); ?>
                                            </a>
                                        </p>
                                    <?php else : ?>
                                        <p>
                                            <strong><?php echo esc_html__( 'Source feeds', 'ai-auto-poster' ); ?></strong><br/>
                                            <?php foreach ( $all_feeds as $feed ) :
                                                $fid = isset( $feed['id'] )   ? $feed['id']   : '';
                                                $fnm = isset( $feed['name'] ) ? $feed['name'] : '';
                                                $chk = in_array( $fid, $rss_settings['rss_feed_ids'], true );
                                            ?>
                                                <label class="aiap-task-rss-feed">
                                                    <input type="checkbox" name="rss_feed_ids[]" value="<?php echo esc_attr( $fid ); ?>" <?php checked( $chk ); ?> />
                                                    <?php echo esc_html( $fnm ); ?>
                                                </label><br/>
                                            <?php endforeach; ?>
                                        </p>

                                        <p>
                                            <label>
                                                <?php echo esc_html__( 'Item count', 'ai-auto-poster' ); ?>
                                                <input type="number" name="rss_count" min="1" max="<?php echo esc_attr( AIAP_RSS_Feeds::COUNT_MAX ); ?>" step="1" value="<?php echo esc_attr( (int) $rss_settings['rss_count'] ); ?>" />
                                            </label>
                                        </p>

                                        <p>
                                            <strong><?php echo esc_html__( 'Mode', 'ai-auto-poster' ); ?></strong><br/>
                                            <label><input type="radio" name="rss_mode" value="pick"   <?php checked( 'pick',   $rss_settings['rss_mode'] ); ?> /> <?php echo esc_html__( 'Pickup (AI picks one)', 'ai-auto-poster' ); ?></label><br/>
                                            <label><input type="radio" name="rss_mode" value="digest" <?php checked( 'digest', $rss_settings['rss_mode'] ); ?> /> <?php echo esc_html__( 'Digest (summarize all)', 'ai-auto-poster' ); ?></label>
                                        </p>

                                        <p>
                                            <strong><?php echo esc_html__( 'When no fresh articles:', 'ai-auto-poster' ); ?></strong><br/>
                                            <label><input type="radio" name="rss_fallback" value="skip"     <?php checked( 'skip',     $rss_settings['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Skip post', 'ai-auto-poster' ); ?></label><br/>
                                            <label><input type="radio" name="rss_fallback" value="generate" <?php checked( 'generate', $rss_settings['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Generate without RSS', 'ai-auto-poster' ); ?></label>
                                        </p>
                                    <?php endif; ?>
                                </div>
                            </fieldset>
                            </div>
                        </details>
                        <details class="aiap-task-section aiap-task-section--schedule" data-aiap-section="schedule" <?php echo self::is_section_expanded( 'schedule', array(), true ) ? 'open' : ''; ?>>
                            <summary class="aiap-task-section__summary">
                                <span class="aiap-task-section__toggle" aria-hidden="true"><span class="dashicons dashicons-arrow-right"></span></span>
                                <span class="aiap-task-section__icon dashicons dashicons-calendar-alt" aria-hidden="true"></span>
                                <span class="aiap-task-section__title"><?php echo esc_html__( 'Schedule', 'ai-auto-poster' ); ?></span>
                                <span class="aiap-task-section__summary-text"><?php echo esc_html( self::build_schedule_section_summary( array() ) ); ?></span>
                            </summary>
                            <div class="aiap-task-section__body">
                        <div class="aiap-field">
                            <label class="aiap-checkbox-row">
                                <input type="checkbox" name="task_random_mode" value="1" data-aiap-random-toggle="1">
                                <span><strong><?php echo esc_html( __( 'Random mode', 'ai-auto-poster' ) ); ?></strong></span>
                            </label>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Posts at random times and a random count per day.', 'ai-auto-poster' ) ); ?></span>
                        </div>
                        <div class="aiap-random-fields aiap-hidden" data-aiap-random-fields>
                            <div class="aiap-field">
                                <label class="aiap-field-label"><?php echo esc_html( __( 'Posts per day', 'ai-auto-poster' ) ); ?></label>
                                <div class="aiap-counts-row">
                                    <input type="number" name="task_random_count_min" value="" min="0" max="50" class="aiap-input-text" placeholder="0">
                                    <span class="aiap-counts-sep"><?php echo esc_html( __( 'to', 'ai-auto-poster' ) ); ?></span>
                                    <input type="number" name="task_random_count_max" value="" min="0" max="50" class="aiap-input-text" placeholder="0">
                                    <span class="aiap-field-unit"><?php echo esc_html( __( '/ day (0–50)', 'ai-auto-poster' ) ); ?></span>
                                </div>
                            </div>
                            <div class="aiap-field">
                                <label class="aiap-field-label"><?php echo esc_html( __( 'Allowed time ranges (post only here)', 'ai-auto-poster' ) ); ?></label>
                                <div class="aiap-allowed-list" data-aiap-allowed-list></div>
                                <button type="button" class="button aiap-allowed-add-empty" data-aiap-allowed-add-empty><?php echo esc_html( __( '+ Add time range', 'ai-auto-poster' ) ); ?></button>
                                <span class="aiap-field-hint"><?php echo esc_html( __( 'If empty, all 24 hours are allowed. Format: HH:MM – HH:MM. Crossing midnight (e.g. 22:00 – 07:00) is allowed.', 'ai-auto-poster' ) ); ?></span>
                            </div>
                            <div class="aiap-field">
                                <label class="aiap-field-label"><?php echo esc_html( __( 'Minimum interval between posts', 'ai-auto-poster' ) ); ?></label>
                                <div class="aiap-counts-row">
                                    <input type="number" name="task_min_interval_minutes" value="" min="0" max="720" step="1" class="aiap-input-text" placeholder="0">
                                    <span class="aiap-field-unit"><?php echo esc_html( __( 'minutes (0 = no minimum)', 'ai-auto-poster' ) ); ?></span>
                                </div>
                                <span class="aiap-field-hint"><?php echo esc_html( __( 'If you cannot fit "posts per day" with this interval, fewer posts will be scheduled.', 'ai-auto-poster' ) ); ?></span>
                            </div>
                        </div>
                        <div class="aiap-schedule-fields" data-aiap-schedule-fields>
                        <div class="aiap-field">
                            <label class="aiap-field-label"><?php echo esc_html( __( 'Schedule', 'ai-auto-poster' ) ); ?></label>
                            <div class="aiap-sched-grid">
                                <?php foreach ( $days as $dk ) : ?>
                                    <div class="aiap-sched-row">
                                        <span class="aiap-sched-day"><?php echo esc_html( AIAP_Admin_View::resolve_dynamic_key( $dk ) ); ?></span>
                                        <input type="text" name="schedule[<?php echo esc_attr( $dk ); ?>]" class="aiap-input-text" placeholder="09:00, 14:00">
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <span class="aiap-field-hint"><?php echo esc_html( __( 'Comma-separated times. Empty = skip that day.', 'ai-auto-poster' ) ); ?></span>
                        </div>
                        </div>
                            </div>
                        </details>
                        <div class="aiap-field">
                            <label class="aiap-checkbox-row">
                                <input type="checkbox" name="task_enabled" value="1" checked>
                                <span><strong><?php echo esc_html( __( 'Enable this task', 'ai-auto-poster' ) ); ?></strong></span>
                            </label>
                        </div>
                    </div>
                </div>
                <p class="submit">
                    <button type="button" class="aiap-btn js-aiap-cancel-add-task" data-confirm-message="<?php echo esc_attr( __( 'Discard changes?', 'ai-auto-poster' ) ); ?>"><span class="dashicons dashicons-no" aria-hidden="true"></span> <?php echo esc_html( __( 'Cancel', 'ai-auto-poster' ) ); ?></button>
                    <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>
            </form>
        </div>
        <?php
    }


    // ================================================================
    // ログ (unchanged)
    // ================================================================

    // ================================================================
    // タスクカードのアコーディオンセクション用 helper
    // ================================================================

    /**
     * タスク配列から画像セクションのサマリ文字列を生成する
     *
     * @param array $task
     * @return string 空文字 or 「— Always attach」「— Don't attach」等
     */
    private static function build_image_section_summary( $task ) {
        $mode = AIAP_Prompts::get_image_mode( $task );
        if ( $mode === 'on' ) {
            return '— ' . __( 'Always attach', 'ai-auto-poster' );
        }
        return '— ' . __( "Don't attach", 'ai-auto-poster' );
    }

    /**
     * タスク配列から RSS セクションのサマリ文字列を生成する
     *
     * @param array $task
     * @return string 空文字 or 「— Yahoo IT, NHK Main / 5 items / pick」
     */
    public static function build_rss_section_summary( $task ) {
        $rss = AIAP_Prompts::get_rss_settings( $task );
        if ( $rss['rss_enabled'] !== 1 ) {
            return '';
        }
        // フィード名解決（先頭 3 つまで、残りは「他 N フィード」）
        $feed_names = array();
        if ( class_exists( 'AIAP_RSS_Feeds' ) ) {
            $all_feeds = AIAP_RSS_Feeds::get_all();
            $feed_map  = array();
            foreach ( $all_feeds as $f ) {
                if ( isset( $f['id'] ) ) {
                    $feed_map[ $f['id'] ] = isset( $f['name'] ) ? (string) $f['name'] : '';
                }
            }
            foreach ( $rss['rss_feed_ids'] as $fid ) {
                if ( isset( $feed_map[ $fid ] ) && $feed_map[ $fid ] !== '' ) {
                    $feed_names[] = $feed_map[ $fid ];
                }
            }
        }
        $names_str = '';
        $total     = count( $feed_names );
        if ( $total === 0 ) {
            $names_str = '';
        } elseif ( $total <= 3 ) {
            $names_str = implode( ', ', $feed_names );
        } else {
            /* translators: 1: first feed names, 2: remaining count */
            $names_str = sprintf( __( '%1$s and %2$d more', 'ai-auto-poster' ), implode( ', ', array_slice( $feed_names, 0, 3 ) ), $total - 3 );
        }
        $mode_label = $rss['rss_mode'] === 'digest' ? __( 'digest', 'ai-auto-poster' ) : __( 'pick', 'ai-auto-poster' );
        /* translators: 1: feed names, 2: item count, 3: mode label */
        return '— ' . sprintf( __( '%1$s / %2$d items / %3$s', 'ai-auto-poster' ), $names_str, (int) $rss['rss_count'], $mode_label );
    }

    /**
     * タスク配列からスケジュールセクションのサマリ文字列を生成する
     *
     * @param array $task
     * @return string 「— Daily 09:00」等、既存の format_schedule_summary をラップ
     */
    private static function build_schedule_section_summary( $task ) {
        if ( ! is_array( $task ) ) {
            $task = array();
        }
        $summary = AIAP_Prompts::format_schedule_summary( $task );
        if ( $summary === '' || $summary === __( 'No schedule', 'ai-auto-poster' ) ) {
            return '— ' . __( 'unset', 'ai-auto-poster' );
        }
        return '— ' . $summary;
    }

    /**
     * セクションを既定で展開するかどうかを判定する
     *
     * 仕様変更（2026-05-13 UX 改善 v2）：
     * 編集モード・新規追加・Quick Post すべてで初期表示は折り畳み。
     * 設定済みかどうかは is_section_configured() で別途判定し、ヘッダに「設定済」バッジを出して区別する。
     *
     * @param string $section_key 'image' | 'rss' | 'schedule'
     * @param array  $task
     * @param bool   $is_new      新規追加フォームならtrue
     * @return bool
     */
    private static function is_section_expanded( $section_key, $task, $is_new = false ) {
        unset( $section_key, $task, $is_new ); // 引数は互換のため受け取るが現状常に false 返却
        return false;
    }

    /**
     * セクションが「設定済み」（既定値以外の値が入っている）かを判定する
     *
     * 折り畳んだ状態のヘッダに「設定済」バッジを表示するかの判定に使う。
     *
     * @param string $section_key 'image' | 'rss' | 'schedule'
     * @param array  $task
     * @return bool
     */
    public static function is_section_configured( $section_key, $task ) {
        if ( ! is_array( $task ) ) {
            $task = array();
        }
        switch ( $section_key ) {
            case 'image':
                // featured_image_mode は 'on' / 'off' の 2 値でいずれかが必ず設定されている。
                // 設定状態の概念がないので常に true (= サマリは常に表示する) とする。
                return true;
            case 'rss':
                $rss = AIAP_Prompts::get_rss_settings( $task );
                return $rss['rss_enabled'] === 1;
            case 'schedule':
                if ( ! empty( $task['random_mode'] ) ) {
                    return true;
                }
                $schedule = isset( $task['schedule'] ) && is_array( $task['schedule'] ) ? $task['schedule'] : array();
                foreach ( $schedule as $times ) {
                    if ( is_array( $times ) ) {
                        foreach ( $times as $t ) {
                            if ( trim( (string) $t ) !== '' ) {
                                return true;
                            }
                        }
                    }
                }
                return false;
        }
        return false;
    }
}
