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

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

    public static function render_quick_post() {
        $uid         = get_current_user_id();
        $last_prompt = get_user_meta( $uid, AIAP_Admin::USER_META_LAST_MANUAL_PROMPT, true );
        $s           = AIAP_AI_Client::get_settings();
        $langs       = AIAP_AI_Client::get_language_options();
        $last_lang   = get_user_meta( $uid, AIAP_Admin::USER_META_LAST_MANUAL_LANGUAGE, true );
        $last_length = get_user_meta( $uid, AIAP_Admin::USER_META_LAST_MANUAL_LENGTH, true );
        $last_img_mode = get_user_meta( $uid, AIAP_Admin::USER_META_LAST_MANUAL_IMAGE_MODE, true );
        $init_lang   = ( $last_lang && isset( $langs[ $last_lang ] ) ) ? $last_lang : $s['content_language'];
        $init_length = $last_length ? (int) $last_length : (int) ( $s['content_length'] ?? 0 );
        $init_img_mode = AIAP_Prompts::sanitize_image_mode( $last_img_mode );

        $qp_is_pro    = AIAP_License::is_pro();
        $qp_at_limit  = ( ! $qp_is_pro ) && ! AIAP_License::can_post_more();
        $qp_count     = AIAP_License::monthly_post_count();
        $qp_limit     = AIAP_License::FREE_MONTHLY_LIMIT;
        $qp_remaining = AIAP_License::remaining_posts();
        ?>
        <div class="aiap-quickpost">
            <header class="aiap-provider-hero">
                <span class="aiap-provider-hero-eyebrow"><?php echo esc_html( __( 'Quick Post', 'ai-auto-poster' ) ); ?></span>
                <h2 class="aiap-provider-hero-title"><?php echo esc_html( __( 'Write a post right now', 'ai-auto-poster' ) ); ?></h2>
                <p class="aiap-provider-hero-sub"><?php echo esc_html( __( 'Type a prompt and one post is created immediately. Leave blank to use the next scheduled task.', 'ai-auto-poster' ) ); ?></p>
            </header>

            <?php if ( $qp_at_limit ) : ?>
                <div class="aiap-banner aiap-banner-error">
                    <span class="dashicons dashicons-warning" aria-hidden="true"></span>
                    <span class="aiap-banner-text">
                        <strong><?php echo esc_html( __( 'Free plan monthly limit reached (10 posts).', 'ai-auto-poster' ) ); ?></strong>
                        <span><?php echo esc_html( __( 'Upgrade to Pro for unlimited posting.', '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 elseif ( ! $qp_is_pro && $qp_remaining <= 3 ) : ?>
                <div class="aiap-banner aiap-banner-warning">
                    <span class="aiap-banner-text">
                        <?php
                        /* translators: 1: posts used, 2: monthly limit */
                        echo esc_html( sprintf( __( 'This month: %1$d / %2$d posts', 'ai-auto-poster' ), $qp_count, $qp_limit ) );
                        ?>
                    </span>
                </div>
            <?php endif; ?>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
                  class="aiap-run-now-form aiap-quickpost-form"
                  data-label-run="<?php echo esc_attr( __( 'Run Now', 'ai-auto-poster' ) ); ?>"
                  data-label-running="<?php echo esc_attr( __( 'Running…', 'ai-auto-poster' ) ); ?>"
                  data-label-ai="<?php echo esc_attr( __( 'Generating article with AI…', 'ai-auto-poster' ) ); ?>"
                  data-label-post="<?php echo esc_attr( __( 'Creating post…', 'ai-auto-poster' ) ); ?>"
                  data-label-image="<?php echo esc_attr( __( 'Generating featured image…', 'ai-auto-poster' ) ); ?>"
                  data-label-seo="<?php echo esc_attr( __( 'Applying SEO settings…', 'ai-auto-poster' ) ); ?>"
                  data-label-done="<?php echo esc_attr( __( 'Completed', 'ai-auto-poster' ) ); ?>"
                  data-label-error="<?php echo esc_attr( __( 'Error', 'ai-auto-poster' ) ); ?>"
                  data-label-prompt-required="<?php echo esc_attr( __( 'Prompt is required.', 'ai-auto-poster' ) ); ?>"
                  data-label-retry-ai="<?php
                    /* translators: %d = number of AI retries (legacy) */
                    echo esc_attr( __( 'AI retries: %d', 'ai-auto-poster' ) );
                  ?>"
                  data-label-retry-dedup="<?php
                    /* translators: %d = number of dedup retries (legacy) */
                    echo esc_attr( __( 'Dedup retries: %d', 'ai-auto-poster' ) );
                  ?>"
                  data-label-server-retry="<?php
                    /* translators: 1: current retry, 2: max retries (e.g. "Recovering from server error 2/3") */
                    echo esc_attr( __( 'Recovering from server error %1$d/%2$d', 'ai-auto-poster' ) );
                  ?>"
                  data-label-dedup-retry="<?php
                    /* translators: 1: current retry, 2: max retries (e.g. "Resolving similar content 2/3") */
                    echo esc_attr( __( 'Resolving similar content %1$d/%2$d', 'ai-auto-poster' ) );
                  ?>"
                  data-max-retry-ai="<?php echo esc_attr( (string) AIAP_AI_Client::GENERATE_MAX_RETRY ); ?>"
                  data-max-retry-dedup="<?php echo esc_attr( (string) max( 1, (int) ( $s['dedup_max_retry'] ?? 3 ) ) ); ?>"
                  data-label-server-error="<?php
                    /* translators: %d = HTTP status code */
                    echo esc_attr( __( 'Server error (HTTP %d)', 'ai-auto-poster' ) );
                  ?>"
                  data-label-upgrade="<?php echo esc_attr( __( 'Upgrade to Pro', 'ai-auto-poster' ) ); ?>">
                <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                <input type="hidden" name="manual_rss_form_submitted" value="1">

                <?php
                $qp_all_tasks = class_exists( 'AIAP_Prompts' ) ? AIAP_Prompts::get_all() : array();
                ?>
                <div class="aiap-editor aiap-quickpost-editor">
                    <div class="aiap-quickpost-editor-head">
                        <label for="js-aiap-manual-prompt" class="aiap-editor-label"><?php echo esc_html( __( 'What do you want to write about?', 'ai-auto-poster' ) ); ?></label>
                        <?php if ( ! empty( $qp_all_tasks ) ) : ?>
                            <select id="js-aiap-manual-task"
                                    name="manual_selected_task_id"
                                    class="aiap-select aiap-quickpost-task-select"
                                    data-aiap-task-select
                                    data-confirm="<?php echo esc_attr( __( 'Replace current input with the selected task settings?', 'ai-auto-poster' ) ); ?>"
                                    <?php disabled( $qp_at_limit ); ?>>
                                <option value=""><?php echo esc_html( __( '— Select a task (optional) —', 'ai-auto-poster' ) ); ?></option>
                                <?php foreach ( $qp_all_tasks as $qp_t ) :
                                    $qp_t_id = isset( $qp_t['id'] ) ? (string) $qp_t['id'] : '';
                                    if ( $qp_t_id === '' ) { continue; }
                                    $qp_t_enabled = ! empty( $qp_t['enabled'] );
                                    $qp_t_label   = isset( $qp_t['name'] ) && (string) $qp_t['name'] !== ''
                                        ? (string) $qp_t['name']
                                        /* translators: %s: task ID */
                                        : sprintf( __( 'Task #%s', 'ai-auto-poster' ), $qp_t_id );
                                    if ( ! $qp_t_enabled ) {
                                        $qp_t_label .= ' ' . __( '(disabled)', 'ai-auto-poster' );
                                    }
                                    $qp_t_rss        = AIAP_Prompts::get_rss_settings( $qp_t );
                                    $qp_t_image_mode = AIAP_Prompts::sanitize_image_mode( isset( $qp_t['featured_image_mode'] ) ? $qp_t['featured_image_mode'] : 'on' );
                                ?>
                                    <option value="<?php echo esc_attr( $qp_t_id ); ?>"
                                            data-prompt="<?php echo esc_attr( (string) ( $qp_t['prompt'] ?? '' ) ); ?>"
                                            data-lang="<?php echo esc_attr( (string) ( $qp_t['content_language'] ?? '' ) ); ?>"
                                            data-length="<?php echo esc_attr( (string) (int) ( $qp_t['content_length'] ?? 0 ) ); ?>"
                                            data-image-mode="<?php echo esc_attr( $qp_t_image_mode ); ?>"
                                            data-rss-enabled="<?php echo esc_attr( (string) (int) $qp_t_rss['rss_enabled'] ); ?>"
                                            data-rss-feed-ids="<?php echo esc_attr( implode( ',', (array) $qp_t_rss['rss_feed_ids'] ) ); ?>"
                                            data-rss-count="<?php echo esc_attr( (string) (int) $qp_t_rss['rss_count'] ); ?>"
                                            data-rss-mode="<?php echo esc_attr( (string) $qp_t_rss['rss_mode'] ); ?>"
                                            data-rss-fallback="<?php echo esc_attr( (string) $qp_t_rss['rss_fallback'] ); ?>"
                                            <?php disabled( ! $qp_t_enabled ); ?>>
                                        <?php echo esc_html( $qp_t_label ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        <?php endif; ?>
                        <span class="aiap-quickpost-charcount" data-aiap-charcount>0</span>
                    </div>
                    <textarea name="manual_prompt" id="js-aiap-manual-prompt" rows="6" class="aiap-editor-textarea aiap-quickpost-textarea" placeholder="<?php echo esc_attr( __( 'e.g. Write about three quick tips for staying focused while working from home, in a friendly tone.', 'ai-auto-poster' ) ); ?>" <?php echo $qp_at_limit ? 'disabled' : ''; ?>><?php echo esc_textarea( $last_prompt ); ?></textarea>
                    <p class="aiap-editor-hint aiap-manual-empty-hint"><?php echo esc_html( __( 'Type a prompt or pick a task above.', 'ai-auto-poster' ) ); ?></p>
                </div>

                <div class="aiap-quickpost-options aiap-quickpost-options-grid" id="js-aiap-manual-options">
                    <div class="aiap-quickpost-option-card">
                        <div class="aiap-quickpost-option-label">
                            <span class="dashicons dashicons-translation" aria-hidden="true"></span>
                            <?php echo esc_html( __( 'Language', 'ai-auto-poster' ) ); ?>
                        </div>
                        <select id="aiap-manual-lang" class="aiap-select" name="manual_content_language">
                            <?php foreach ( $langs as $v => $l ) : ?>
                                <option value="<?php echo esc_attr( $v ); ?>" <?php selected( $init_lang, $v ); ?>><?php echo esc_html( $l ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="aiap-quickpost-option-card">
                        <div class="aiap-quickpost-option-label">
                            <span class="dashicons dashicons-editor-alignleft" aria-hidden="true"></span>
                            <?php echo esc_html( __( 'Length', 'ai-auto-poster' ) ); ?>
                        </div>
                        <div class="aiap-field-row">
                            <input type="number" id="aiap-manual-length" class="aiap-input-text aiap-input-narrow" name="manual_content_length" value="<?php echo esc_attr( $init_length > 0 ? $init_length : '' ); ?>" min="0" max="10000" placeholder="<?php echo esc_attr( __( 'Default', 'ai-auto-poster' ) ); ?>">
                            <span class="aiap-field-unit"><?php echo esc_html( __( 'chars', 'ai-auto-poster' ) ); ?></span>
                        </div>
                    </div>
                    <div class="aiap-quickpost-option-card aiap-quickpost-option-image">
                        <div class="aiap-quickpost-option-label">
                            <span class="dashicons dashicons-format-image" aria-hidden="true"></span>
                            <?php echo esc_html( __( 'Featured image', 'ai-auto-poster' ) ); ?>
                        </div>
                        <div class="aiap-quickpost-pill-group">
                            <label class="aiap-quickpost-pill"><input type="radio" name="manual_featured_image_mode" value="on" <?php checked( $init_img_mode !== 'off' ); ?> <?php disabled( $qp_at_limit ); ?>><span><?php echo esc_html( __( 'Yes', 'ai-auto-poster' ) ); ?></span></label>
                            <label class="aiap-quickpost-pill"><input type="radio" name="manual_featured_image_mode" value="off" <?php checked( $init_img_mode === 'off' ); ?> <?php disabled( $qp_at_limit ); ?>><span><?php echo esc_html( __( 'No', 'ai-auto-poster' ) ); ?></span></label>
                        </div>
                    </div>
                </div>

                <?php
                $qp_is_pro_for_rss = class_exists( 'AIAP_License' ) && AIAP_License::is_pro();
                $qp_rss_all_feeds  = class_exists( 'AIAP_RSS_Feeds' ) ? AIAP_RSS_Feeds::get_all() : array();
                // user_meta から最後の RSS 設定を復元
                $qp_uid = get_current_user_id();
                $qp_rss_defaults = array(
                    'rss_enabled'  => (int) get_user_meta( $qp_uid, AIAP_Admin::USER_META_LAST_MANUAL_RSS_ENABLED, true ),
                    'rss_feed_ids' => array_filter( array_map( 'sanitize_key', (array) get_user_meta( $qp_uid, AIAP_Admin::USER_META_LAST_MANUAL_RSS_FEED_IDS, true ) ) ),
                    'rss_count'    => max( 1, (int) ( get_user_meta( $qp_uid, AIAP_Admin::USER_META_LAST_MANUAL_RSS_COUNT, true ) ?: 5 ) ),
                    'rss_mode'     => get_user_meta( $qp_uid, AIAP_Admin::USER_META_LAST_MANUAL_RSS_MODE, true ) ?: 'pick',
                    'rss_fallback' => get_user_meta( $qp_uid, AIAP_Admin::USER_META_LAST_MANUAL_RSS_FALLBACK, true ) ?: 'generate',
                );
                $qp_rss = AIAP_Prompts::get_rss_settings( $qp_rss_defaults );
                ?>
                <details class="aiap-task-section aiap-task-section--rss aiap-quickpost-rss" data-aiap-section="rss" data-aiap-configured-label="<?php echo esc_attr__( 'Configured', 'ai-auto-poster' ); ?>">
                    <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 ( AIAP_Admin_View_Tasks::is_section_configured( 'rss', $qp_rss ) ) : ?>
                            <span class="aiap-task-section__configured-badge"><?php echo esc_html__( 'Configured', 'ai-auto-poster' ); ?></span>
                        <?php endif; ?>
                        <?php $qp_rss_summary = AIAP_Admin_View_Tasks::build_rss_section_summary( array( 'rss_enabled' => $qp_rss['rss_enabled'], 'rss_feed_ids' => $qp_rss['rss_feed_ids'], 'rss_count' => $qp_rss['rss_count'], 'rss_mode' => $qp_rss['rss_mode'], 'rss_fallback' => $qp_rss['rss_fallback'] ) ); if ( $qp_rss_summary !== '' ) : ?>
                            <span class="aiap-task-section__summary-text"><?php echo esc_html( $qp_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 ( ! $qp_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 $qp_is_pro_for_rss ? '' : 'disabled'; ?>>
                        <p>
                            <label>
                                <input type="checkbox" name="manual_rss_enabled" value="1" class="js-aiap-task-rss-enable" <?php checked( 1, (int) $qp_rss['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( $qp_rss_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 ( $qp_rss_all_feeds as $qp_feed ) :
                                        $qp_fid = isset( $qp_feed['id'] )   ? $qp_feed['id']   : '';
                                        $qp_fnm = isset( $qp_feed['name'] ) ? $qp_feed['name'] : '';
                                        $qp_chk = in_array( $qp_fid, $qp_rss['rss_feed_ids'], true );
                                    ?>
                                        <label class="aiap-task-rss-feed">
                                            <input type="checkbox" name="manual_rss_feed_ids[]" value="<?php echo esc_attr( $qp_fid ); ?>" <?php checked( $qp_chk ); ?> />
                                            <?php echo esc_html( $qp_fnm ); ?>
                                        </label><br/>
                                    <?php endforeach; ?>
                                </p>

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

                                <p>
                                    <strong><?php echo esc_html__( 'Mode', 'ai-auto-poster' ); ?></strong><br/>
                                    <label><input type="radio" name="manual_rss_mode" value="pick"   <?php checked( 'pick',   $qp_rss['rss_mode'] ); ?> /> <?php echo esc_html__( 'Pickup (AI picks one)', 'ai-auto-poster' ); ?></label><br/>
                                    <label><input type="radio" name="manual_rss_mode" value="digest" <?php checked( 'digest', $qp_rss['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="manual_rss_fallback" value="skip"     <?php checked( 'skip',     $qp_rss['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Skip post', 'ai-auto-poster' ); ?></label><br/>
                                    <label><input type="radio" name="manual_rss_fallback" value="generate" <?php checked( 'generate', $qp_rss['rss_fallback'] ); ?> /> <?php echo esc_html__( 'Generate without RSS', 'ai-auto-poster' ); ?></label>
                                </p>
                            <?php endif; ?>
                        </div>
                    </fieldset>
                    </div>
                </details>

                <div class="aiap-quickpost-action">
                    <button type="submit" class="button button-primary aiap-run-now-btn aiap-btn-primary aiap-btn-large aiap-quickpost-cta" <?php disabled( $qp_at_limit ); ?>>
                        <span class="dashicons dashicons-controls-play" aria-hidden="true"></span>
                        <?php echo esc_html( __( 'Generate now', 'ai-auto-poster' ) ); ?>
                    </button>
                </div>

                <div class="aiap-progress" aria-live="polite" hidden>
                    <div class="aiap-progress-main">
                        <div class="aiap-progress-step" data-step="ai"></div>
                        <div class="aiap-progress-step" data-step="post"></div>
                        <div class="aiap-progress-step" data-step="image"></div>
                        <div class="aiap-progress-step" data-step="seo"></div>
                        <div class="aiap-progress-result"></div>
                    </div>
                    <div class="aiap-progress-media" aria-hidden="true">
                        <video class="aiap-progress-video"
                               src="<?php echo esc_url( AIAP_PLUGIN_URL . 'assets/video/Robot.mp4' ); ?>"
                               muted
                               loop
                               playsinline
                               preload="metadata"></video>
                    </div>
                </div>
            </form>
        </div>
        <?php
    }

}
