<?php
/**
 * Usage Dashboard
 *
 * @package AllAccessible
 * @since   2.0.0
 */

if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * Render the usage card.
 *
 * @param object $site_options Response from the validation endpoint (must expose ->usageSummary)
 * @param string $account_tier free|trial|starter|legacy|enterprise|unknown
 * @param string $addon_url    URL to plan/addons page on app.allaccessible.org
 * @param string $audits_url   URL to accessibility audits page on app.allaccessible.org
 */
function aacb_render_usage_dashboard($site_options, $account_tier, $addon_url, $audits_url) {
    $is_free = ($account_tier === 'free');
    $is_paid = in_array($account_tier, array('starter', 'legacy', 'enterprise', 'trial'), true);

    $has_usage = ($site_options && !is_wp_error($site_options) && isset($site_options->usageSummary));
    $usage     = $has_usage ? $site_options->usageSummary : null;
    $site_id   = $has_usage && isset($site_options->siteID) ? $site_options->siteID : get_option('aacb_siteID');
    $sub_id    = $has_usage && isset($site_options->subID)  ? $site_options->subID  : null;
    ?>

    <section class="aacx-v2__card aacx-v2__card--elevated" aria-label="<?php esc_attr_e('Usage overview', 'allaccessible'); ?>">
        <header class="aacx-v2__card-header">
            <div>
                <h2 style="font-size: var(--aacx-text-xl);"><?php esc_html_e('Usage this month', 'allaccessible'); ?></h2>
                <p style="font-size: var(--aacx-text-sm); color: var(--aacx-text-muted); margin-top: var(--aacx-space-1);">
                    <?php esc_html_e('Tracks pageviews and AllAccessible AI activity against your plan.', 'allaccessible'); ?>
                </p>
            </div>
            <?php if ($is_free) : ?>
                <a href="<?php echo esc_url($addon_url); ?>" target="_blank" rel="noopener"
                   class="aacx-v2__btn aacx-v2__btn--primary aacx-v2__btn--sm">
                    <?php esc_html_e('Upgrade plan', 'allaccessible'); ?>
                </a>
            <?php endif; ?>
        </header>

        <div class="aacx-v2__card-body">
            <?php if (!$has_usage) :
                // Empty state: API didn't return usage yet
                ?>
                <div class="aacx-v2__empty">
                    <svg class="aacx-v2__empty-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
                    </svg>
                    <p class="aacx-v2__empty-title"><?php esc_html_e('No usage to show yet', 'allaccessible'); ?></p>
                    <p style="margin-bottom: var(--aacx-space-4);">
                        <?php esc_html_e('Usage appears here once your widget starts serving pageviews.', 'allaccessible'); ?>
                    </p>
                    <a href="<?php echo esc_url(get_bloginfo('wpurl') . '/?aacb_preview=true'); ?>" target="_blank" rel="noopener"
                       class="aacx-v2__btn aacx-v2__btn--secondary aacx-v2__btn--sm">
                        <?php esc_html_e('Preview your widget', 'allaccessible'); ?>
                    </a>
                </div>
                <?php
            else :
                // ── Usage rows ──────────────────────────────────────────
                $metrics = array(
                    'pageviews_monthly' => array(
                        'label' => __('Pageviews', 'allaccessible'),
                        'help'  => __('Active visits served by your widget this month.', 'allaccessible'),
                        'ai'    => false,
                    ),
                    'ai_images_monthly' => array(
                        'label' => __('AI image alt text', 'allaccessible'),
                        'help'  => __('Alt text generated by AllAccessible AI for images on your site.', 'allaccessible'),
                        'ai'    => true,
                    ),
                    'audit_runs_monthly' => array(
                        'label' => __('Accessibility audits', 'allaccessible'),
                        'help'  => __('Automated scans run by AllAccessible agents.', 'allaccessible'),
                        'ai'    => false,
                    ),
                    'reports_monthly' => array(
                        'label' => __('Compliance reports', 'allaccessible'),
                        'help'  => __('VPAT and accessibility statement PDFs generated.', 'allaccessible'),
                        'ai'    => false,
                    ),
                );

                $rendered = 0;
                ?>
                <div class="aacx-v2__stack">
                    <?php
                    foreach ($metrics as $key => $meta) :
                        if (!isset($usage->$key)) {
                            continue;
                        }
                        $rendered++;

                        $row       = $usage->$key;
                        $current   = isset($row->current) ? (int) $row->current : 0;
                        $limit     = isset($row->limit)   ? (int) $row->limit   : 0;
                        $percent   = isset($row->percent) ? (int) $row->percent : 0;
                        $exceeded  = !empty($row->exceeded);
                        $remaining = isset($row->remaining) ? (int) $row->remaining : max(0, $limit - $current);
                        $is_locked = ($limit === 0);

                        // Severity → badge class + bar color (token-based)
                        if ($exceeded || $percent >= 100) {
                            $badge_class = 'aacx-v2__badge aacx-v2__badge--danger';
                            $bar_color   = 'var(--aacx-danger-500)';
                        } elseif ($percent >= 80) {
                            $badge_class = 'aacx-v2__badge aacx-v2__badge--warn';
                            $bar_color   = 'var(--aacx-warn-500)';
                        } else {
                            $badge_class = 'aacx-v2__badge aacx-v2__badge--ok';
                            $bar_color   = 'var(--aacx-ok-500)';
                        }

                        // Per-feature dashboard URL (paid users)
                        if ($key === 'audit_runs_monthly') {
                            $feature_url = $audits_url;
                        } elseif ($site_id && $sub_id && $key === 'reports_monthly') {
                            $feature_url = 'https://app.allaccessible.org/site/' . rawurlencode($site_id) . '/' . rawurlencode($sub_id) . '/reports';
                        } elseif ($site_id) {
                            $feature_url = 'https://app.allaccessible.org/site/' . rawurlencode($site_id);
                        } else {
                            $feature_url = 'https://app.allaccessible.org';
                        }
                        ?>

                        <div role="group"
                             aria-label="<?php echo esc_attr(sprintf(__('%1$s usage: %2$d percent', 'allaccessible'), $meta['label'], $percent)); ?>"
                             style="padding: var(--aacx-space-4) 0; border-bottom: 1px solid var(--aacx-border);">
                            <div class="aacx-v2__row aacx-v2__row--between" style="margin-bottom: var(--aacx-space-2);">
                                <div>
                                    <div class="aacx-v2__row" style="gap: var(--aacx-space-2);">
                                        <span style="font-weight: var(--aacx-weight-semibold); color: var(--aacx-text-strong); font-size: var(--aacx-text-sm);">
                                            <?php echo esc_html($meta['label']); ?>
                                        </span>
                                        <?php if ($meta['ai']) : ?>
                                            <span class="aacx-v2__ai-badge"><?php esc_html_e('AllAccessible AI', 'allaccessible'); ?></span>
                                        <?php endif; ?>
                                        <?php if (!$is_locked) : ?>
                                            <span class="<?php echo esc_attr($badge_class); ?>">
                                                <?php echo esc_html($percent); ?>%
                                            </span>
                                        <?php elseif ($is_free) : ?>
                                            <span class="aacx-v2__badge aacx-v2__badge--primary">
                                                <?php esc_html_e('Upgrade to unlock', 'allaccessible'); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="aacx-v2__help" style="margin-top: var(--aacx-space-1);">
                                        <?php echo esc_html($meta['help']); ?>
                                    </p>
                                </div>

                                <?php if (!$is_locked) : ?>
                                    <span style="font-variant-numeric: tabular-nums; font-size: var(--aacx-text-sm); font-weight: var(--aacx-weight-semibold); color: var(--aacx-text-strong); white-space: nowrap;">
                                        <?php echo esc_html(number_format_i18n($current)); ?>
                                        <span style="color: var(--aacx-text-muted); font-weight: var(--aacx-weight-normal);">
                                            / <?php echo esc_html(number_format_i18n($limit)); ?>
                                        </span>
                                    </span>
                                <?php endif; ?>
                            </div>

                            <?php if (!$is_locked) : ?>
                                <!-- CSS-only progress bar (no external chart lib) -->
                                <div role="progressbar"
                                     aria-valuenow="<?php echo esc_attr($percent); ?>"
                                     aria-valuemin="0"
                                     aria-valuemax="100"
                                     aria-label="<?php echo esc_attr(sprintf(__('%s percent used', 'allaccessible'), $percent)); ?>"
                                     style="height: 6px; background: var(--aacx-slate-100); border-radius: var(--aacx-radius-pill); overflow: hidden;">
                                    <div style="height: 100%; width: <?php echo esc_attr(min(100, max(0, $percent))); ?>%; background: <?php echo esc_attr($bar_color); ?>; transition: width 300ms ease-out;"></div>
                                </div>

                                <p style="margin-top: var(--aacx-space-2); font-size: var(--aacx-text-xs); color: var(--aacx-text-muted);">
                                    <?php if ($exceeded) : ?>
                                        <strong style="color: var(--aacx-danger-700);">
                                            <?php esc_html_e('Limit reached — widget temporarily on free features.', 'allaccessible'); ?>
                                        </strong>
                                    <?php else :
                                        printf(
                                            /* translators: %s: count of remaining units this month */
                                            esc_html__('%s remaining this month', 'allaccessible'),
                                            esc_html(number_format_i18n($remaining))
                                        );
                                    endif; ?>
                                    <?php if ($is_paid) : ?>
                                        &nbsp;·&nbsp;
                                        <a href="<?php echo esc_url($feature_url); ?>" target="_blank" rel="noopener">
                                            <?php esc_html_e('Manage', 'allaccessible'); ?> →
                                        </a>
                                    <?php endif; ?>
                                </p>
                            <?php else : ?>
                                <?php if ($is_free) : ?>
                                    <p style="font-size: var(--aacx-text-xs); color: var(--aacx-text-muted);">
                                        <a href="<?php echo esc_url($addon_url); ?>" target="_blank" rel="noopener">
                                            <?php esc_html_e('Upgrade your plan', 'allaccessible'); ?> →
                                        </a>
                                    </p>
                                <?php else : ?>
                                    <p style="font-size: var(--aacx-text-xs); color: var(--aacx-text-muted);">
                                        <a href="<?php echo esc_url($feature_url); ?>" target="_blank" rel="noopener">
                                            <?php esc_html_e('Manage in dashboard', 'allaccessible'); ?> →
                                        </a>
                                    </p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>

                <?php if ($rendered === 0) : ?>
                    <div class="aacx-v2__empty">
                        <p class="aacx-v2__empty-title"><?php esc_html_e('No metered features on your plan yet', 'allaccessible'); ?></p>
                        <p><?php esc_html_e('Usage will appear here once your widget starts serving pages.', 'allaccessible'); ?></p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <?php if ($is_free && $has_usage) : ?>
            <footer class="aacx-v2__card-footer">
                <p style="font-size: var(--aacx-text-sm); color: var(--aacx-text-muted); margin: 0;">
                    <?php esc_html_e('Need more pageviews or AllAccessible AI capacity?', 'allaccessible'); ?>
                </p>
                <a href="<?php echo esc_url($addon_url); ?>" target="_blank" rel="noopener"
                   class="aacx-v2__btn aacx-v2__btn--primary aacx-v2__btn--sm">
                    <?php esc_html_e('Upgrade plan', 'allaccessible'); ?>
                </a>
            </footer>
        <?php endif; ?>
    </section>
    <?php
}
