<?php
/**
 * Post Content Scanner Renderer - UI Components
 *
 * Card rendering, cascade report, details panel with tabs.
 *
 * @package StaticQ
 * @since 3.3.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class SQMedia_Post_Content_Scanner_Renderer_Components {

    private SQMedia_Post_Content_Scanner_Renderer $renderer;
    private SQMedia_Database $db;

    public function __construct(SQMedia_Post_Content_Scanner_Renderer $renderer, SQMedia_Database $db) {
        $this->renderer = $renderer;
        $this->db = $db;
    }

    /**
     * Render the scanner card
     */
    public function render_card(array $state): void {
        $status = $state['status'];
        $subtitle = $this->get_subtitle($state);
        $badge = $this->get_status_badge_data($status);
        $show_rescan = in_array($status, [
            SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN,
            SQMedia_Post_Content_Scanner_Renderer::STATUS_ISSUES,
        ], true);

        ?>
        <div class="sqmedia-phase-card"
             id="sqmedia-pcs-card"
             data-status="<?php echo esc_attr($status); ?>"
             data-scan-id="<?php echo esc_attr($state['scan_id'] ?? ''); ?>">

            <div class="sqmedia-phase-header">
                <div class="sqmedia-phase-header-left">
                    <div class="sqmedia-phase-number <?php echo esc_attr($this->get_number_class($status)); ?>">
                        <?php echo esc_html($status === SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN ? '✓' : '📝'); ?>
                    </div>
                    <div>
                        <div class="sqmedia-phase-title"><?php esc_html_e('Post Content Scanner', 'staticq-media'); ?></div>
                        <div class="sqmedia-phase-subtitle" id="sqmedia-pcs-subtitle">
                            <?php echo esc_html($subtitle); ?>
                        </div>
                    </div>
                </div>
                <div class="sqmedia-phase-header-right">
                    <span class="sqmedia-status-badge <?php echo esc_attr($badge['class']); ?>"><?php echo esc_html($badge['label']); ?></span>
                    <?php if ($show_rescan): ?>
                        <button type="button" class="button button-secondary" id="sqmedia-pcs-rescan">
                            🔄 <?php esc_html_e('Rescan', 'staticq-media'); ?>
                        </button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="sqmedia-phase-body" id="sqmedia-pcs-body">
                <p class="sqmedia-phase-description"><?php esc_html_e('Scans post content for image references and validates domain correctness, attachment existence, and file integrity. Ensures no CDN or foreign domain URLs are baked into your database.', 'staticq-media'); ?></p>

                <?php
                switch ($status) {
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_NOT_SCANNED:
                        $this->render_not_scanned();
                        break;
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_SCANNING:
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_PAUSED:
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_FIXING:
                        // JS will replace this body content
                        $this->render_scanning_placeholder($state);
                        break;
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN:
                        $this->render_clean($state);
                        break;
                    case SQMedia_Post_Content_Scanner_Renderer::STATUS_ISSUES:
                        $this->render_issues($state);
                        break;
                }
                ?>
            </div>

            <?php $this->render_backup_section('pcs'); ?>
        </div>
        <?php
    }

    /**
     * Render not-scanned state
     */
    private function render_not_scanned(): void {
        ?>
        <div class="sqmedia-button-group" style="margin-top: 15px;">
            <button type="button" class="button button-primary button-hero" id="sqmedia-pcs-start-scan">
                🔍 <?php esc_html_e('Scan Post Content', 'staticq-media'); ?>
            </button>
        </div>
        <?php
    }

    /**
     * Render scanning placeholder (JS replaces this)
     */
    private function render_scanning_placeholder(array $state): void {
        $total = (int) ($state['total_scanned'] ?? 0);
        $processed = (int) ($state['processed'] ?? 0);
        $progress = $total > 0 ? round(($processed / $total) * 100) : 0;
        ?>
        <div class="sqmedia-progress-container">
            <div class="sqmedia-progress-bar">
                <div class="sqmedia-progress-fill" id="sqmedia-pcs-progress-fill" style="width: <?php echo (int) $progress; ?>%">
                    <?php echo (int) $progress; ?>%
                </div>
            </div>
        </div>
        <p id="sqmedia-pcs-progress-text">
            <?php echo esc_html($processed . ' / ' . $total . ' ' . __('posts', 'staticq-media')); ?>
        </p>
        <?php
    }

    /**
     * Render clean state
     */
    private function render_clean(array $state): void {
        $scanned_at = $state['scanned_at'] ?? '';
        $total = $state['total_scanned'] ?? 0;
        $duration = $state['duration'] ?? '';
        ?>
        <p class="sqmedia-last-scan">
            <?php
            echo esc_html(sprintf(
                // translators: %1$s: time ago, %2$s: number of posts, %3$s: duration or empty
                __('Last scan: %1$s • Scanned %2$s posts%3$s', 'staticq-media'),
                human_time_diff(strtotime($scanned_at), strtotime(current_time('mysql'))) . ' ' . __('ago', 'staticq-media'),
                number_format_i18n($total),
                // translators: %s: scan duration
                $duration ? ' ' . sprintf(__('in %s', 'staticq-media'), $duration) : ''
            ));
            ?>
        </p>

        <div class="sqmedia-cascade-report">
            <div class="sqmedia-cascade-container">
                <div class="sqmedia-cascade-item sqmedia-cascade-success">
                    <span class="sqmedia-cascade-icon">✓</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of posts
                            __('All %s posts passed every check', 'staticq-media'),
                            number_format_i18n($total)
                        ));
                    ?></span>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render issues state with cascade and buttons
     */
    private function render_issues(array $state): void {
        $scanned_at = $state['scanned_at'] ?? '';
        $total = $state['total_scanned'] ?? 0;
        $duration = $state['duration'] ?? '';
        $scan_id = $state['scan_id'] ?? '';
        $issue_counts = $state['issue_counts'] ?? [];
        $fixable_issues = $state['fixable_issues'] ?? 0;
        $posts_with_issues = $state['posts_with_issues'] ?? 0;

        $wrong_domain = $issue_counts[SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN] ?? 0;
        $deleted_attachment = $issue_counts[SQMedia_Post_Content_Scanner::CAT_DELETED_ATTACHMENT] ?? 0;
        $stale_size = $issue_counts[SQMedia_Post_Content_Scanner::CAT_STALE_SIZE] ?? 0;
        $broken_url = $issue_counts[SQMedia_Post_Content_Scanner::CAT_BROKEN_URL] ?? 0;
        $clean_count = max(0, $total - $posts_with_issues);
        ?>
        <p class="sqmedia-last-scan">
            <?php
            echo esc_html(sprintf(
                // translators: %1$s: time ago, %2$s: number of posts, %3$s: duration or empty
                __('Last scan: %1$s • Scanned %2$s posts%3$s', 'staticq-media'),
                human_time_diff(strtotime($scanned_at), strtotime(current_time('mysql'))) . ' ' . __('ago', 'staticq-media'),
                number_format_i18n($total),
                // translators: %s: scan duration
                $duration ? ' ' . sprintf(__('in %s', 'staticq-media'), $duration) : ''
            ));
            ?>
        </p>

        <div class="sqmedia-cascade-report">
            <div class="sqmedia-cascade-container">
                <?php if ($clean_count > 0): ?>
                <div class="sqmedia-cascade-item sqmedia-cascade-success">
                    <span class="sqmedia-cascade-icon">✓</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of clean posts
                            _n('%s post clean', '%s posts clean', $clean_count, 'staticq-media'),
                            number_format_i18n($clean_count)
                        ));
                    ?></span>
                </div>
                <?php endif; ?>

                <?php if ($wrong_domain > 0): ?>
                <div class="sqmedia-cascade-item sqmedia-cascade-warning">
                    <span class="sqmedia-cascade-icon">⚠</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of wrong domain references
                            _n('%s wrong domain reference', '%s wrong domain references', $wrong_domain, 'staticq-media'),
                            number_format_i18n($wrong_domain)
                        ));
                    ?></span>
                </div>
                <?php endif; ?>

                <?php if ($stale_size > 0): ?>
                <div class="sqmedia-cascade-item sqmedia-cascade-warning">
                    <span class="sqmedia-cascade-icon">⚠</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of stale size references
                            _n('%s stale size reference', '%s stale size references', $stale_size, 'staticq-media'),
                            number_format_i18n($stale_size)
                        ));
                    ?></span>
                </div>
                <?php endif; ?>

                <?php if ($deleted_attachment > 0): ?>
                <div class="sqmedia-cascade-item sqmedia-cascade-error">
                    <span class="sqmedia-cascade-icon">✗</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of deleted attachment references
                            _n('%s deleted attachment reference (info only)', '%s deleted attachment references (info only)', $deleted_attachment, 'staticq-media'),
                            number_format_i18n($deleted_attachment)
                        ));
                    ?></span>
                </div>
                <?php endif; ?>

                <?php if ($broken_url > 0): ?>
                <div class="sqmedia-cascade-item sqmedia-cascade-error">
                    <span class="sqmedia-cascade-icon">✗</span>
                    <span class="sqmedia-cascade-text"><?php
                        echo esc_html(sprintf(
                            // translators: %s: number of broken URLs
                            _n('%s broken URL (info only)', '%s broken URLs (info only)', $broken_url, 'staticq-media'),
                            number_format_i18n($broken_url)
                        ));
                    ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="sqmedia-button-group">
            <button type="button" class="button button-secondary" id="sqmedia-pcs-view-details">
                👁 <?php esc_html_e('View Details', 'staticq-media'); ?>
            </button>
            <?php if ($fixable_issues > 0): ?>
                <button type="button" class="button button-primary" id="sqmedia-pcs-fix-all" data-scan-id="<?php echo esc_attr($scan_id); ?>">
                    🔧 <?php echo esc_html(sprintf(
                        // translators: %d: number of posts with fixable issues
                        __('Fix All (%d)', 'staticq-media'),
                        $posts_with_issues
                    )); ?>
                </button>
            <?php endif; ?>
        </div>

        <?php $this->render_details_panel($state); ?>
        <?php
    }

    /**
     * Render table backup section
     *
     * @param string $scanner 'mls' or 'pcs'
     */
    private function render_backup_section(string $scanner): void {
        $backup = SQMedia_Database::get_backup_status($scanner);
        $ajax_action = ($scanner === 'mls') ? 'sqmedia_backup_mls_tables' : 'sqmedia_backup_pcs_tables';
        $tables_label = ($scanner === 'mls')
            ? 'wp_postmeta, wp_posts'
            : 'wp_posts';
        ?>
        <div class="sqmedia-backup-section" data-scanner="<?php echo esc_attr($scanner); ?>" style="margin-top: 14px; padding: 12px 16px; background: #f8f9fa; border: 1px solid #e2e4e7; border-radius: 4px; font-size: 13px;">
            <p style="margin: 0 0 8px; color: #50575e;">
                <?php esc_html_e('Scanning does not modify your data. The repair process may update', 'staticq-media'); ?>
                <code style="font-size: 12px;"><?php echo esc_html($tables_label); ?></code>.
                <?php echo esc_html($scanner === 'mls'
                    ? __('As an extra safety measure, you can back up these tables before applying fixes.', 'staticq-media')
                    : __('As an extra safety measure, you can back up this table before applying fixes.', 'staticq-media')
                ); ?>
            </p>
            <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                <button type="button" class="button button-secondary sqmedia-backup-tables-btn" data-action="<?php echo esc_attr($ajax_action); ?>">
                    <?php echo esc_html($scanner === 'mls'
                        ? __('Backup Tables', 'staticq-media')
                        : __('Backup Table', 'staticq-media')
                    ); ?>
                </button>
                <span class="sqmedia-backup-status" style="color: #646970; font-size: 12px;">
                    <?php if ($backup['exists']): ?>
                        <?php echo esc_html(sprintf(
                            /* translators: %s: date and time of backup */
                            __('Backup exists from %s', 'staticq-media'),
                            wp_date(get_option('date_format') . ' ' . get_option('time_format'), strtotime($backup['date']))
                        )); ?>
                    <?php else: ?>
                        <?php esc_html_e('No backup yet', 'staticq-media'); ?>
                    <?php endif; ?>
                </span>
            </div>
        </div>
        <?php
    }

    /**
     * Render the details panel (hidden by default)
     */
    private function render_details_panel(array $state): void {
        $issue_counts = $state['issue_counts'] ?? [];
        $posts_with_issues = $state['posts_with_issues'] ?? 0;
        ?>
        <div id="sqmedia-pcs-details-panel" class="sqmedia-details-panel" style="display: none; margin-top: 15px;">
            <div class="sqmedia-tab-bar" style="margin-bottom: 10px; display: flex; gap: 5px; flex-wrap: wrap;">
                <button type="button" class="button sqmedia-pcs-tab active" data-category="">
                    <?php esc_html_e('All', 'staticq-media'); ?> (<?php echo (int) $posts_with_issues; ?>)
                </button>
                <?php if (!empty($issue_counts[SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN])): ?>
                <button type="button" class="button sqmedia-pcs-tab" data-category="<?php echo esc_attr(SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN); ?>">
                    <?php esc_html_e('Wrong Domain', 'staticq-media'); ?> (<?php echo (int) $issue_counts[SQMedia_Post_Content_Scanner::CAT_WRONG_DOMAIN]; ?>)
                </button>
                <?php endif; ?>
                <?php if (!empty($issue_counts[SQMedia_Post_Content_Scanner::CAT_STALE_SIZE])): ?>
                <button type="button" class="button sqmedia-pcs-tab" data-category="<?php echo esc_attr(SQMedia_Post_Content_Scanner::CAT_STALE_SIZE); ?>">
                    <?php esc_html_e('Stale Size', 'staticq-media'); ?> (<?php echo (int) $issue_counts[SQMedia_Post_Content_Scanner::CAT_STALE_SIZE]; ?>)
                </button>
                <?php endif; ?>
                <?php if (!empty($issue_counts[SQMedia_Post_Content_Scanner::CAT_DELETED_ATTACHMENT])): ?>
                <button type="button" class="button sqmedia-pcs-tab" data-category="<?php echo esc_attr(SQMedia_Post_Content_Scanner::CAT_DELETED_ATTACHMENT); ?>">
                    <?php esc_html_e('Deleted', 'staticq-media'); ?> (<?php echo (int) $issue_counts[SQMedia_Post_Content_Scanner::CAT_DELETED_ATTACHMENT]; ?>)
                </button>
                <?php endif; ?>
                <?php if (!empty($issue_counts[SQMedia_Post_Content_Scanner::CAT_BROKEN_URL])): ?>
                <button type="button" class="button sqmedia-pcs-tab" data-category="<?php echo esc_attr(SQMedia_Post_Content_Scanner::CAT_BROKEN_URL); ?>">
                    <?php esc_html_e('Broken URL', 'staticq-media'); ?> (<?php echo (int) $issue_counts[SQMedia_Post_Content_Scanner::CAT_BROKEN_URL]; ?>)
                </button>
                <?php endif; ?>
            </div>
            <div id="sqmedia-pcs-details-list">
                <p><?php esc_html_e('Click "View Details" to load issue list.', 'staticq-media'); ?></p>
            </div>
        </div>
        <?php
    }

    /**
     * Get subtitle based on state
     */
    private function get_subtitle(array $state): string {
        switch ($state['status']) {
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_SCANNING:
                return __('Scanning...', 'staticq-media');
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_PAUSED:
                return __('Paused', 'staticq-media');
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_FIXING:
                return __('Fixing issues...', 'staticq-media');
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN:
                return __('All clean — no issues found in post content', 'staticq-media');
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_ISSUES:
                $count = $state['posts_with_issues'] ?? 0;
                return sprintf(
                    // translators: %d: number of posts with issues
                    _n('%d post with issues', '%d posts with issues', $count, 'staticq-media'),
                    $count
                );
            default:
                return __('Validates image references in post content', 'staticq-media');
        }
    }

    /**
     * Get status badge HTML
     */
    private function get_status_badge_data(string $status): array {
        $badges = [
            SQMedia_Post_Content_Scanner_Renderer::STATUS_NOT_SCANNED => ['sqmedia-status-not-scanned', __('Not Scanned', 'staticq-media')],
            SQMedia_Post_Content_Scanner_Renderer::STATUS_SCANNING => ['sqmedia-status-scanning', __('Scanning', 'staticq-media')],
            SQMedia_Post_Content_Scanner_Renderer::STATUS_PAUSED => ['sqmedia-status-issues', __('Paused', 'staticq-media')],
            SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN => ['sqmedia-status-clean', __('Clean', 'staticq-media')],
            SQMedia_Post_Content_Scanner_Renderer::STATUS_ISSUES => ['sqmedia-status-issues', __('Issues Found', 'staticq-media')],
            SQMedia_Post_Content_Scanner_Renderer::STATUS_FIXING => ['sqmedia-status-scanning', __('Fixing', 'staticq-media')],
        ];

        $badge = $badges[$status] ?? ['sqmedia-status-not-scanned', __('Unknown', 'staticq-media')];
        return ['class' => $badge[0], 'label' => $badge[1]];
    }

    /**
     * Get phase number CSS class
     */
    private function get_number_class(string $status): string {
        switch ($status) {
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_CLEAN:
                return 'complete';
            case SQMedia_Post_Content_Scanner_Renderer::STATUS_ISSUES:
                return 'warning';
            default:
                return '';
        }
    }
}
