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

/**
 * Reusable HTML renderers for analysis results — shared by the admin pages and the
 * post-editor metabox. All output is escaped here.
 */
class AIVT_Render {

    /**
     * Inline SVG sparkline from numeric points (0-100 assumed). Self-contained, no JS.
     *
     * @param int[]  $values  Series values, oldest → newest.
     * @param string $class   Extra CSS class (e.g. 'aivt-spark-ok').
     */
    public static function sparkline(array $values, $class = '') {
        $values = array_values(array_filter(array_map('intval', $values), function ($v) { return $v >= 0; }));
        if (count($values) < 2) {
            echo '<span class="aivt-spark-empty">' . esc_html__('Not enough data yet', 'pewit-geo-analysis-tool') . '</span>';
            return;
        }
        $w = 120; $h = 32; $pad = 2;
        $max = max($values); $min = min($values);
        $range = max(1, $max - $min);
        $n = count($values);
        $step = ($w - 2 * $pad) / max(1, $n - 1);
        $pts = [];
        foreach ($values as $i => $v) {
            $x = $pad + $i * $step;
            $y = $h - $pad - (($v - $min) / $range) * ($h - 2 * $pad);
            $pts[] = round($x, 1) . ',' . round($y, 1);
        }
        $poly = implode(' ', $pts);
        $last = end($values);
        $lastX = $pad + ($n - 1) * $step;
        $lastY = $h - $pad - (($last - $min) / $range) * ($h - 2 * $pad);
        ?>
        <span class="aivt-spark <?php echo esc_attr($class); ?>" role="img" aria-label="<?php echo esc_attr(implode(', ', $values)); ?>">
            <svg width="<?php echo (int) $w; ?>" height="<?php echo (int) $h; ?>" viewBox="0 0 <?php echo (int) $w; ?> <?php echo (int) $h; ?>" preserveAspectRatio="none" focusable="false" aria-hidden="true">
                <polyline fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" points="<?php echo esc_attr($poly); ?>" />
                <circle cx="<?php echo esc_attr(round($lastX, 1)); ?>" cy="<?php echo esc_attr(round($lastY, 1)); ?>" r="2.2" fill="currentColor" />
            </svg>
        </span>
        <?php
    }

    public static function score_donut($score, $size = 'lg') {
        $score = (int) $score;
        $class = AIVT_GEO_Score::score_class($score);
        ?>
        <div class="aivt-donut aivt-donut-<?php echo esc_attr($size); ?> aivt-<?php echo esc_attr($class); ?>" style="--aivt-score:<?php echo esc_attr($score); ?>">
            <span class="aivt-donut-value"><?php echo esc_html($score); ?></span>
        </div>
        <?php
    }

    public static function geo($data, $post_id = null) {
        if (empty($data)) {
            echo '<p class="description">' . esc_html__('Not analyzed yet.', 'pewit-geo-analysis-tool') . '</p>';
            return;
        }
        $score = (int) ($data['score'] ?? 0);
        $can_auto = true;
        $history = ($post_id && $can_auto) ? AIVT_Store::geo_history($post_id) : [];
        ?>
        <div class="aivt-result aivt-result-geo">
            <div class="aivt-result-head">
                <?php self::score_donut($score, 'lg'); ?>
                <div>
                    <div class="aivt-result-title"><?php esc_html_e('GEO Score', 'pewit-geo-analysis-tool'); ?> — <?php echo esc_html(AIVT_GEO_Score::score_label($score)); ?></div>
                    <p class="description"><?php echo esc_html($data['summary'] ?? ''); ?></p>
                    <?php if (count($history) >= 2): ?>
                        <div class="aivt-trend aivt-trend-inline">
                            <span class="aivt-trend-label"><?php esc_html_e('Trend', 'pewit-geo-analysis-tool'); ?></span>
                            <?php self::sparkline(wp_list_pluck($history, 'score'), 'aivt-' . AIVT_GEO_Score::score_class($score)); ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php if (!empty($data['breakdown'])): ?>
            <div class="aivt-bars">
                <?php foreach ($data['breakdown'] as $row): ?>
                    <div class="aivt-bar-row">
                        <span class="aivt-bar-label"><?php echo esc_html($row['label']); ?></span>
                        <span class="aivt-bar-track"><span class="aivt-bar-fill aivt-<?php echo esc_attr(AIVT_GEO_Score::score_class($row['score'])); ?>" style="width:<?php echo esc_attr((int) $row['score']); ?>%"></span></span>
                        <span class="aivt-bar-num"><?php echo esc_html((int) $row['score']); ?></span>
                    </div>
                    <?php if (!empty($row['note'])): ?>
                        <p class="aivt-bar-note"><?php echo esc_html($row['note']); ?></p>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($data['tips'])): ?>
            <h4><?php esc_html_e('Top improvements', 'pewit-geo-analysis-tool'); ?></h4>
            <ul class="aivt-tips">
                <?php foreach ($data['tips'] as $tip): ?>
                    <li><?php echo esc_html($tip); ?></li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function entities($data) {
        if (empty($data) || empty($data['entities'])) {
            echo '<p class="description">' . esc_html__('No entities detected yet.', 'pewit-geo-analysis-tool') . '</p>';
            return;
        }
        ?>
        <div class="aivt-result">
            <?php if (!empty($data['primary'])): ?>
                <p><strong><?php esc_html_e('Primary entity:', 'pewit-geo-analysis-tool'); ?></strong> <?php echo esc_html($data['primary']); ?></p>
            <?php endif; ?>
            <table class="widefat striped aivt-table">
                <thead><tr>
                    <th><?php esc_html_e('Entity', 'pewit-geo-analysis-tool'); ?></th>
                    <th><?php esc_html_e('Type', 'pewit-geo-analysis-tool'); ?></th>
                    <th><?php esc_html_e('Salience', 'pewit-geo-analysis-tool'); ?></th>
                    <th><?php esc_html_e('Knowledge link', 'pewit-geo-analysis-tool'); ?></th>
                </tr></thead>
                <tbody>
                <?php foreach ($data['entities'] as $e): ?>
                    <tr>
                        <td><?php echo esc_html($e['name']); ?>
                            <?php if (!empty($e['ambiguous'])): ?><span class="aivt-pill aivt-pill-warn"><?php esc_html_e('ambiguous', 'pewit-geo-analysis-tool'); ?></span><?php endif; ?>
                        </td>
                        <td><code><?php echo esc_html($e['type']); ?></code></td>
                        <td><?php echo esc_html((int) $e['salience']); ?></td>
                        <td><?php if (!empty($e['sameAs'])): ?><a href="<?php echo esc_url($e['sameAs']); ?>" target="_blank" rel="noopener nofollow"><?php esc_html_e('link', 'pewit-geo-analysis-tool'); ?></a><?php else: ?>—<?php endif; ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php if (!empty($data['knows_about'])): ?>
                <p><strong><?php esc_html_e('Topical authority (knowsAbout):', 'pewit-geo-analysis-tool'); ?></strong> <?php echo esc_html(implode(', ', $data['knows_about'])); ?></p>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function eeat($data) {
        if (empty($data)) {
            echo '<p class="description">' . esc_html__('Not analyzed yet.', 'pewit-geo-analysis-tool') . '</p>';
            return;
        }
        ?>
        <div class="aivt-result">
            <div class="aivt-result-head">
                <?php self::score_donut((int) ($data['overall'] ?? 0), 'md'); ?>
                <div class="aivt-result-title"><?php esc_html_e('E-E-A-T overall', 'pewit-geo-analysis-tool'); ?></div>
            </div>
            <div class="aivt-bars">
                <?php foreach (($data['pillars'] ?? []) as $row): ?>
                    <div class="aivt-bar-row">
                        <span class="aivt-bar-label"><?php echo esc_html($row['label']); ?></span>
                        <span class="aivt-bar-track"><span class="aivt-bar-fill aivt-<?php echo esc_attr(AIVT_GEO_Score::score_class($row['score'])); ?>" style="width:<?php echo esc_attr((int) $row['score']); ?>%"></span></span>
                        <span class="aivt-bar-num"><?php echo esc_html((int) $row['score']); ?></span>
                    </div>
                    <?php if (!empty($row['note'])): ?><p class="aivt-bar-note"><?php echo esc_html($row['note']); ?></p><?php endif; ?>
                <?php endforeach; ?>
            </div>
            <?php if (!empty($data['missing'])): ?>
                <h4><?php esc_html_e('Missing trust signals', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-tips"><?php foreach ($data['missing'] as $m): ?><li><?php echo esc_html($m); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
            <?php if (!empty($data['recommendations'])): ?>
                <h4><?php esc_html_e('Recommendations', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-tips"><?php foreach ($data['recommendations'] as $r): ?><li><?php echo esc_html($r); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function citability($data) {
        if (empty($data)) {
            echo '<p class="description">' . esc_html__('Not analyzed yet.', 'pewit-geo-analysis-tool') . '</p>';
            return;
        }
        ?>
        <div class="aivt-result">
            <div class="aivt-result-head">
                <?php self::score_donut((int) ($data['score'] ?? 0), 'md'); ?>
                <div>
                    <div class="aivt-result-title"><?php esc_html_e('Citability', 'pewit-geo-analysis-tool'); ?></div>
                    <p class="description"><?php echo esc_html($data['summary'] ?? ''); ?></p>
                </div>
            </div>
            <?php if (!empty($data['quotable'])): ?>
                <h4><?php esc_html_e('Most quotable passages', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-quotes"><?php foreach ($data['quotable'] as $q): ?><li>&ldquo;<?php echo esc_html($q); ?>&rdquo;</li><?php endforeach; ?></ul>
            <?php endif; ?>
            <?php if (!empty($data['issues'])): ?>
                <h4><?php esc_html_e('Issues', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-tips"><?php foreach ($data['issues'] as $i): ?><li><?php echo esc_html($i); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
            <?php if (!empty($data['suggestions'])): ?>
                <h4><?php esc_html_e('Add citable sentences', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-tips"><?php foreach ($data['suggestions'] as $s): ?><li><?php echo esc_html($s); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
        </div>
        <?php
    }

    public static function pairs($pairs, $kind = 'faq') {
        if (empty($pairs)) {
            return;
        }
        $is_qa = $kind === 'qa';
        ?>
        <div class="aivt-pairs">
            <?php foreach ($pairs as $p): ?>
                <div class="aivt-pair">
                    <p class="aivt-pair-q"><?php echo esc_html($is_qa ? ($p['query'] ?? '') : ($p['question'] ?? '')); ?>
                        <?php if ($is_qa && !empty($p['intent'])): ?><span class="aivt-pill"><?php echo esc_html($p['intent']); ?></span><?php endif; ?>
                    </p>
                    <p class="aivt-pair-a"><?php echo wp_kses_post($p['answer'] ?? ''); ?></p>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
    }

    /** Autopilot dry-run preview: predicted gain + the proposed additions. */
    public static function autopilot_preview(array $plan) {
        $cur = (int) ($plan['current_score'] ?? 0);
        $pred = (int) ($plan['predicted_score'] ?? 0);
        $gain = max(0, $pred - $cur);
        ?>
        <div class="aivt-result aivt-autopilot-preview">
            <div class="aivt-ap-scores">
                <div class="aivt-ap-score"><span class="aivt-ap-num"><?php echo esc_html($cur); ?></span><span class="aivt-ap-cap"><?php esc_html_e('Current', 'pewit-geo-analysis-tool'); ?></span></div>
                <div class="aivt-ap-arrow" aria-hidden="true">→</div>
                <div class="aivt-ap-score aivt-ap-pred"><span class="aivt-ap-num"><?php echo esc_html($pred); ?></span><span class="aivt-ap-cap"><?php esc_html_e('Predicted', 'pewit-geo-analysis-tool'); ?></span></div>
                <div class="aivt-ap-gain"><?php echo esc_html(($gain > 0 ? '+' : '') . $gain); ?></div>
            </div>
            <?php if (!empty($plan['summary'])): ?>
                <p class="description"><?php echo esc_html($plan['summary']); ?></p>
            <?php endif; ?>
            <?php if (!empty($plan['weak'])): ?>
                <p class="aivt-ap-weak"><strong><?php esc_html_e('Targets:', 'pewit-geo-analysis-tool'); ?></strong> <?php echo esc_html(implode(' · ', $plan['weak'])); ?></p>
            <?php endif; ?>
            <?php if (!empty($plan['intro'])): ?>
                <h4><?php esc_html_e('Answer-first intro', 'pewit-geo-analysis-tool'); ?></h4>
                <p class="aivt-ap-intro"><?php echo esc_html($plan['intro']); ?></p>
            <?php endif; ?>
            <?php if (!empty($plan['key_facts'])): ?>
                <h4><?php esc_html_e('Key facts', 'pewit-geo-analysis-tool'); ?></h4>
                <ul class="aivt-tips"><?php foreach ($plan['key_facts'] as $f): ?><li><?php echo esc_html($f); ?></li><?php endforeach; ?></ul>
            <?php endif; ?>
            <?php if (!empty($plan['faq'])): ?>
                <h4><?php /* translators: %d: number of FAQ pairs */ echo esc_html(sprintf(_n('%d FAQ pair', '%d FAQ pairs', count($plan['faq']), 'pewit-geo-analysis-tool'), count($plan['faq']))); ?></h4>
                <?php self::pairs($plan['faq'], 'faq'); ?>
            <?php endif; ?>
            <p class="description"><?php esc_html_e('Applying prepends the intro and key facts, appends the FAQ, stores FAQ schema, and saves a revision you can revert.', 'pewit-geo-analysis-tool'); ?></p>
        </div>
        <?php
    }

    public static function prompt_result($res) {
        ?>
        <div class="aivt-result aivt-prompt-result">
            <div class="aivt-prompt-verdict <?php echo $res['mentioned'] ? 'is-found' : 'is-missing'; ?>">
                <?php if ($res['mentioned']): ?>
                    <strong><?php esc_html_e('Brand mentioned', 'pewit-geo-analysis-tool'); ?></strong>
                    <?php if (isset($res['position_pct'])): ?>
                        <span class="aivt-pill"><?php
                            /* translators: %d: position percentage within the answer */
                            echo esc_html(sprintf(__('appears at ~%d%% of the answer', 'pewit-geo-analysis-tool'), (int) $res['position_pct'])); ?></span>
                    <?php endif; ?>
                <?php else: ?>
                    <strong><?php esc_html_e('Brand NOT mentioned', 'pewit-geo-analysis-tool'); ?></strong>
                <?php endif; ?>
            </div>
            <?php if (!empty($res['competitors_found'])): ?>
                <p><strong><?php esc_html_e('Competitors in the answer:', 'pewit-geo-analysis-tool'); ?></strong> <?php echo esc_html(implode(', ', $res['competitors_found'])); ?></p>
            <?php endif; ?>
            <details class="aivt-prompt-answer" open>
                <summary><?php echo esc_html(sprintf(/* translators: %s: AI provider name */ __('%s answer', 'pewit-geo-analysis-tool'), $res['provider'] ?? 'AI')); ?></summary>
                <div class="aivt-answer-body"><?php echo wp_kses_post(wpautop($res['answer'] ?? '')); ?></div>
            </details>
        </div>
        <?php
    }
}
