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

/**
 * Render the scanner tab content.
 */
function webability_acwg_render_scanner_page() {
    $meta       = get_option(WEBABILITY_SCAN_META_KEY, []);
    $results    = get_option(WEBABILITY_SCAN_RESULTS_KEY, []);
    $all_scans  = get_option(WEBABILITY_SCANS_KEY, []);
    $has_scans  = !empty($all_scans);
    $has_results = !empty($results);

    // Determine active URL key
    $active_url_key = '';
    if (!empty($meta['url'])) {
        $active_url_key = md5($meta['url']);
    }
    ?>
    <div id="webability-scanner">

        <?php if (!$has_scans): ?>
        <!-- Empty state / first scan -->
        <div class="wa-scan-header">
            <h2><?php esc_html_e('Accessibility Scanner', 'webability-accessibility-widget'); ?></h2>
            <p class="description"><?php esc_html_e('Scan your site for WCAG 2.2 issues and fix them natively in WordPress.', 'webability-accessibility-widget'); ?></p>
            <div class="wa-scan-row">
                <input type="url" id="wa-scan-url" class="regular-text" value="<?php echo esc_attr(home_url('/')); ?>" placeholder="https://yoursite.com" />
                <button id="wa-scan-btn" class="button button-primary"><?php esc_html_e('Scan Now', 'webability-accessibility-widget'); ?></button>
            </div>
        </div>
        <div class="wa-empty-state">
            <div class="wa-empty-icon" aria-hidden="true">&#128269;</div>
            <h3><?php esc_html_e('No scan results yet', 'webability-accessibility-widget'); ?></h3>
            <p><?php esc_html_e('Enter your site URL above and click Scan Now to find accessibility issues.', 'webability-accessibility-widget'); ?></p>
        </div>
        <?php else: ?>

        <!-- Scanned Pages Table -->
        <?php webability_acwg_render_scans_table($all_scans, $active_url_key); ?>

        <!-- Detail view for active scan -->
        <?php if ($has_results): ?>
            <div id="wa-detail-view">
                <?php webability_acwg_render_results_header($results, $meta); ?>
                <?php webability_acwg_render_categories($results); ?>
            </div>
        <?php endif; ?>

        <p class="wa-powered-by">
            <?php printf(
                esc_html__('Powered by %s Accessibility Scanner', 'webability-accessibility-widget'),
                '<a href="https://webability.io" target="_blank" rel="noopener">WebAbility.io</a>'
            ); ?>
        </p>
        <?php endif; ?>

        <!-- Hidden scan URL for JS (used on re-scan) -->
        <input type="hidden" id="wa-scan-url-stored" value="<?php echo esc_attr(!empty($meta['url']) ? $meta['url'] : home_url('/')); ?>" />

        <!-- Progress (shown during scan) -->
        <div id="wa-scan-progress" style="display:none;">
            <div class="wa-progress-bar"><div class="wa-progress-fill"></div></div>
            <p id="wa-scan-status"><?php esc_html_e('Scanning...', 'webability-accessibility-widget'); ?></p>
        </div>

        <!-- Toast -->
        <div id="wa-toast" class="wa-toast" role="status" aria-live="polite"></div>
    </div>
    <?php
}

/**
 * Render the scanned pages table with add-URL input.
 */
function webability_acwg_render_scans_table($all_scans, $active_url_key) {
    ?>
    <div class="wa-scans-section">
        <div class="wa-scans-header">
            <h2><?php esc_html_e('Scanned Pages', 'webability-accessibility-widget'); ?></h2>
            <p class="wa-scans-subtitle"><?php printf(esc_html__('%d pages scanned', 'webability-accessibility-widget'), count($all_scans)); ?></p>
        </div>

        <!-- Add new URL row -->
        <div class="wa-scan-add-row">
            <input type="url" id="wa-scan-url" class="regular-text" value="<?php echo esc_attr(home_url('/')); ?>" placeholder="https://yoursite.com/page" />
            <button id="wa-scan-btn" class="wa-btn-scan-add" type="button"><?php esc_html_e('Scan URL', 'webability-accessibility-widget'); ?></button>
        </div>

        <!-- Results table -->
        <table class="wa-scans-table">
            <thead>
                <tr>
                    <th class="wa-col-page"><?php esc_html_e('Page', 'webability-accessibility-widget'); ?></th>
                    <th class="wa-col-date"><?php esc_html_e('Last Scan', 'webability-accessibility-widget'); ?></th>
                    <th class="wa-col-progress"><?php esc_html_e('Issues Resolved', 'webability-accessibility-widget'); ?></th>
                    <th class="wa-col-actions"><?php esc_html_e('Actions', 'webability-accessibility-widget'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($all_scans as $url_key => $scan): ?>
                    <?php
                    $total  = intval($scan['total_issues']);
                    $fixed  = intval($scan['issues_fixed']);
                    $pct    = $total > 0 ? round(($fixed / $total) * 100) : 0;
                    $is_active = ($url_key === $active_url_key);

                    // Progress chip color
                    $chip_class = 'wa-chip-warning';
                    if ($pct >= 100) $chip_class = 'wa-chip-success';
                    elseif ($pct >= 60) $chip_class = 'wa-chip-default';
                    elseif ($pct <= 25) $chip_class = 'wa-chip-error';
                    ?>
                    <tr class="wa-scan-row-item <?php echo $is_active ? 'wa-scan-row-active' : ''; ?>" data-url-key="<?php echo esc_attr($url_key); ?>">
                        <td class="wa-col-page">
                            <span class="wa-scan-page-title"><?php echo esc_html($scan['page_title']); ?></span>
                            <span class="wa-scan-page-url"><?php echo esc_html($scan['url']); ?></span>
                        </td>
                        <td class="wa-col-date">
                            <?php echo esc_html($scan['last_scan']); ?>
                        </td>
                        <td class="wa-col-progress">
                            <div class="wa-scan-progress-wrap">
                                <div class="wa-scan-progress-bar">
                                    <div class="wa-scan-progress-fill <?php echo esc_attr($chip_class); ?>" style="width:<?php echo intval($pct); ?>%"></div>
                                </div>
                                <span class="wa-scan-progress-chip <?php echo esc_attr($chip_class); ?>">
                                    <?php echo intval($fixed) . '/' . intval($total); ?>
                                </span>
                            </div>
                        </td>
                        <td class="wa-col-actions">
                            <button type="button" class="wa-btn-view-scan" data-url-key="<?php echo esc_attr($url_key); ?>" <?php echo $is_active ? 'disabled' : ''; ?>>
                                <?php echo $is_active ? esc_html__('Viewing', 'webability-accessibility-widget') : esc_html__('View', 'webability-accessibility-widget'); ?>
                            </button>
                            <button type="button" class="wa-btn-rescan-url" data-url="<?php echo esc_attr($scan['url']); ?>" title="<?php esc_attr_e('Re-scan this URL', 'webability-accessibility-widget'); ?>">&#8635;</button>
                            <button type="button" class="wa-btn-delete-scan" data-url-key="<?php echo esc_attr($url_key); ?>" title="<?php esc_attr_e('Remove scan', 'webability-accessibility-widget'); ?>">&times;</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

/**
 * Render the results header: page title, stat tiles, progress bar, action buttons.
 */
function webability_acwg_render_results_header($results, $meta) {
    $total    = count($results);
    $fixed    = 0;
    $critical = 0;
    $serious  = 0;
    $auto     = 0;

    foreach ($results as $r) {
        if ($r['status'] === 'fixed') { $fixed++; }
        if ($r['auto_fixable'] && $r['status'] !== 'fixed') { $auto++; }
        $imp = isset($r['impact']) ? $r['impact'] : 'moderate';
        if ($imp === 'critical' && $r['status'] !== 'fixed') $critical++;
        if ($imp === 'serious' && $r['status'] !== 'fixed') $serious++;
    }

    $open = $total - $fixed;
    $pct  = $total > 0 ? round(($fixed / $total) * 100) : 0;

    $scanned_url = !empty($meta['url']) ? $meta['url'] : '';
    ?>
    <!-- Page Header -->
    <div class="wa-page-header">
        <div class="wa-page-header-left">
            <h2><?php esc_html_e('Scan Results', 'webability-accessibility-widget'); ?></h2>
            <?php if (!empty($meta['last_scan'])): ?>
                <p><?php printf(esc_html__('Last scanned %s', 'webability-accessibility-widget'), esc_html($meta['last_scan'])); ?></p>
            <?php endif; ?>
        </div>
        <?php if ($scanned_url): ?>
            <span class="wa-scanned-url">
                <span class="wa-scanned-url-icon" aria-hidden="true">&#127760;</span>
                <?php echo esc_html($scanned_url); ?>
            </span>
        <?php endif; ?>
    </div>

    <!-- Stat Tiles -->
    <div class="wa-stat-tiles">
        <div class="wa-stat-tile wa-stat-tile--issues">
            <p class="wa-stat-tile-label"><?php esc_html_e('Total Issues', 'webability-accessibility-widget'); ?></p>
            <p class="wa-stat-tile-value"><?php echo intval($total); ?></p>
            <p class="wa-stat-tile-sub">
                <?php
                $parts = [];
                if ($critical > 0) $parts[] = intval($critical) . ' critical';
                if ($serious > 0) $parts[] = intval($serious) . ' serious';
                echo $parts ? esc_html(implode(', ', $parts)) : esc_html__('No critical issues', 'webability-accessibility-widget');
                ?>
            </p>
        </div>
        <div class="wa-stat-tile wa-stat-tile--fixed">
            <p class="wa-stat-tile-label"><?php esc_html_e('Resolved', 'webability-accessibility-widget'); ?></p>
            <p class="wa-stat-tile-value"><?php echo intval($fixed); ?></p>
            <p class="wa-stat-tile-sub"><?php printf(esc_html__('%d%% complete', 'webability-accessibility-widget'), intval($pct)); ?></p>
        </div>
        <div class="wa-stat-tile wa-stat-tile--open <?php echo $open === 0 ? 'wa-stat-tile--clear' : ''; ?>">
            <p class="wa-stat-tile-label"><?php esc_html_e('Outstanding', 'webability-accessibility-widget'); ?></p>
            <p class="wa-stat-tile-value"><?php echo intval($open); ?></p>
            <p class="wa-stat-tile-sub">
                <?php
                if ($auto > 0) {
                    printf(esc_html__('%d auto-fixable', 'webability-accessibility-widget'), intval($auto));
                } elseif ($open > 0) {
                    esc_html_e('Manual review needed', 'webability-accessibility-widget');
                } else {
                    esc_html_e('All clear', 'webability-accessibility-widget');
                }
                ?>
            </p>
        </div>
        <div class="wa-stat-tile wa-stat-tile--donut">
            <?php
            $circumference = 2 * M_PI * 45;
            $offset = $circumference - ($pct / 100) * $circumference;
            ?>
            <div class="wa-donut" role="img" aria-label="<?php printf(esc_attr__('%d percent resolved', 'webability-accessibility-widget'), intval($pct)); ?>">
                <svg viewBox="0 0 120 120">
                    <circle class="wa-donut-track" cx="60" cy="60" r="45" />
                    <circle class="wa-donut-fill" cx="60" cy="60" r="45"
                        stroke-dasharray="<?php echo esc_attr($circumference); ?>"
                        stroke-dashoffset="<?php echo esc_attr($offset); ?>" />
                </svg>
                <span class="wa-donut-label">
                    <span class="wa-donut-pct"><?php echo intval($pct); ?>%</span>
                    <span class="wa-donut-pct-sub"><?php esc_html_e('Resolved', 'webability-accessibility-widget'); ?></span>
                </span>
            </div>
        </div>
    </div>

    <!-- Actions Bar -->
    <div class="wa-actions-bar">
        <div class="wa-actions-bar-left">
            <p class="wa-section-label"><?php esc_html_e('Issues by Category', 'webability-accessibility-widget'); ?></p>
        </div>
        <div class="wa-actions-bar-right">
            <?php if ($auto > 0): ?>
                <button id="wa-fix-all-btn" class="wa-btn-fix-all" type="button">
                    <?php printf(esc_html__('Fix All (%d)', 'webability-accessibility-widget'), intval($auto)); ?>
                </button>
            <?php endif; ?>
            <button type="button" class="wa-btn-rescan wa-btn-rescan-url" data-url="<?php echo esc_attr($scanned_url); ?>">
                <?php esc_html_e('Re-scan', 'webability-accessibility-widget'); ?>
            </button>
        </div>
    </div>
    <?php
}

/**
 * Group issues by category and render as expandable cards.
 */
function webability_acwg_render_categories($results) {
    $categories = webability_acwg_categorize_issues($results);

    echo '<div class="wa-categories">';
    foreach ($categories as $cat_key => $cat) {
        $total_in_cat = count($cat['issues']);
        $fixed_in_cat = 0;
        foreach ($cat['issues'] as $issue) {
            if ($issue['status'] === 'fixed') $fixed_in_cat++;
        }
        $all_resolved = ($fixed_in_cat === $total_in_cat);
        $open_count = $total_in_cat - $fixed_in_cat;
        $cat_pct = $total_in_cat > 0 ? round(($fixed_in_cat / $total_in_cat) * 100) : 0;

        $btn_class = 'wa-category-btn';
        if ($all_resolved) $btn_class .= ' wa-category-resolved';
        ?>
        <div class="wa-category-wrapper">
            <button type="button" class="<?php echo esc_attr($btn_class); ?>" data-category="<?php echo esc_attr($cat_key); ?>" aria-expanded="false" aria-controls="wa-panel-<?php echo esc_attr($cat_key); ?>">
                <span class="wa-category-icon <?php echo esc_attr($cat['icon_class']); ?>" aria-hidden="true"><?php echo $cat['icon']; ?></span>
                <span class="wa-category-label-group" id="wa-cat-label-<?php echo esc_attr($cat_key); ?>">
                    <span class="wa-category-label"><?php echo esc_html($cat['label']); ?></span>
                    <span class="wa-category-desc"><?php echo esc_html($cat['desc']); ?></span>
                </span>
                <span class="wa-category-right">
                    <?php if (!$all_resolved && $fixed_in_cat > 0): ?>
                        <span class="wa-cat-progress"><span class="wa-cat-progress-fill" style="width:<?php echo intval($cat_pct); ?>%"></span></span>
                    <?php endif; ?>
                    <?php if ($all_resolved): ?>
                        <span class="wa-category-check" aria-label="<?php esc_attr_e('All resolved', 'webability-accessibility-widget'); ?>">&#10003;</span>
                    <?php else: ?>
                        <span class="wa-category-count"><?php echo intval($open_count); ?></span>
                    <?php endif; ?>
                </span>
            </button>
            <div class="wa-issue-panel" id="wa-panel-<?php echo esc_attr($cat_key); ?>" role="region" aria-labelledby="wa-cat-label-<?php echo esc_attr($cat_key); ?>">
                <?php foreach ($cat['issues'] as $issue): ?>
                    <?php webability_acwg_render_issue_row($issue); ?>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }
    echo '</div>';
}

/**
 * Render a single issue row inside a category panel.
 */
function webability_acwg_render_issue_row($issue) {
    $impact = isset($issue['impact']) ? $issue['impact'] : 'moderate';
    $is_fixed = ($issue['status'] === 'fixed');
    $row_class = 'wa-issue-item';
    if ($is_fixed) $row_class .= ' wa-issue-fixed';

    $impact_labels = [
        'critical' => 'Critical',
        'serious'  => 'Serious',
        'moderate' => 'Moderate',
        'minor'    => 'Minor',
    ];
    $target_labels = [
        'attachment'   => 'Image',
        'post_content' => 'Post',
        'theme'        => 'Theme',
        'manual'       => 'Manual',
    ];
    $target = isset($issue['fix_target']) ? $issue['fix_target'] : 'manual';
    ?>
    <div class="<?php echo esc_attr($row_class); ?>" id="wa-fix-row-<?php echo intval($issue['_index']); ?>">
        <div class="wa-issue-impact wa-impact-bar-<?php echo esc_attr($impact); ?>"></div>
        <div class="wa-issue-body">
            <p class="wa-issue-title"><?php echo esc_html($issue['description']); ?></p>
            <div class="wa-issue-meta">
                <span class="wa-impact-label wa-impact-label-<?php echo esc_attr($impact); ?>">
                    <?php echo esc_html(isset($impact_labels[$impact]) ? $impact_labels[$impact] : ucfirst($impact)); ?>
                </span>
                <?php if (!empty($issue['wcag'])): ?>
                    <span class="wa-wcag-tag"><?php echo esc_html($issue['wcag']); ?></span>
                <?php endif; ?>
                <span class="wa-target-tag">
                    <?php echo esc_html(isset($target_labels[$target]) ? $target_labels[$target] : $target); ?>
                    <?php if ($issue['wp_object_id']): ?>
                        #<?php echo intval($issue['wp_object_id']); ?>
                    <?php endif; ?>
                </span>
            </div>
            <?php if (!empty($issue['selector'])): ?>
                <code class="wa-issue-selector" title="<?php echo esc_attr($issue['selector']); ?>"><?php echo esc_html(webability_acwg_truncate($issue['selector'], 100)); ?></code>
            <?php endif; ?>
            <?php if (!empty($issue['suggested_fix']) && !$is_fixed): ?>
                <p class="wa-issue-suggestion"><?php echo esc_html(webability_acwg_truncate($issue['suggested_fix'], 150)); ?></p>
            <?php endif; ?>
        </div>
        <div class="wa-issue-action">
            <?php if ($is_fixed): ?>
                <span class="wa-badge-done">&#10003; Fixed</span>
            <?php elseif ($issue['auto_fixable']): ?>
                <button type="button" class="wa-btn-apply wa-fix-btn" data-index="<?php echo intval($issue['_index']); ?>">
                    <?php esc_html_e('Apply Fix', 'webability-accessibility-widget'); ?>
                </button>
            <?php else: ?>
                <span class="wa-badge-manual-sm"><?php esc_html_e('Manual', 'webability-accessibility-widget'); ?></span>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * Categorize issues into groups for display.
 */
function webability_acwg_categorize_issues($results) {
    $category_map = [
        'missing_alt'           => 'alt_text',
        'empty_alt_functional'  => 'alt_text',
        'color_contrast'        => 'color_contrast',
        'multiple_h1'           => 'headings',
        'empty_heading'         => 'headings',
        'heading_order'         => 'headings',
        'empty_link'            => 'links',
        'non_descriptive_link'  => 'links',
        'bypass_blocks'         => 'theme',
        'missing_focus_indicator' => 'theme',
        'language_of_page'      => 'theme',
    ];

    $category_meta = [
        'alt_text' => [
            'label'      => 'Alternative Text',
            'desc'       => 'Images missing descriptive alt attributes',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>',
            'icon_class'  => 'wa-icon-image',
        ],
        'color_contrast' => [
            'label'      => 'Color Contrast',
            'desc'       => 'Text with insufficient contrast ratios',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/></svg>',
            'icon_class'  => 'wa-icon-contrast',
        ],
        'headings' => [
            'label'      => 'Heading Structure',
            'desc'       => 'Heading hierarchy and semantic issues',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="m17 12 3-2v8"/></svg>',
            'icon_class'  => 'wa-icon-heading',
        ],
        'links' => [
            'label'      => 'Links & Navigation',
            'desc'       => 'Empty or non-descriptive links',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',
            'icon_class'  => 'wa-icon-link',
        ],
        'theme' => [
            'label'      => 'Theme & Structure',
            'desc'       => 'Page-level structural requirements',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>',
            'icon_class'  => 'wa-icon-theme',
        ],
        'other' => [
            'label'      => 'Other Issues',
            'desc'       => 'Additional accessibility concerns',
            'icon'        => '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',
            'icon_class'  => 'wa-icon-other',
        ],
    ];

    $groups = [];
    foreach ($results as $i => $r) {
        $type = isset($r['issue_type']) ? $r['issue_type'] : '';
        $cat_key = isset($category_map[$type]) ? $category_map[$type] : 'other';

        if (!isset($groups[$cat_key])) {
            $meta = isset($category_meta[$cat_key]) ? $category_meta[$cat_key] : $category_meta['other'];
            $groups[$cat_key] = array_merge($meta, ['issues' => []]);
        }

        $r['_index'] = $i;
        $groups[$cat_key]['issues'][] = $r;
    }

    return $groups;
}

/**
 * Truncate a string safely, with or without mbstring.
 */
function webability_acwg_truncate($string, $max, $suffix = '...') {
    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($string, 0, $max, $suffix);
    }
    if (strlen($string) <= $max) {
        return $string;
    }
    return substr($string, 0, $max - strlen($suffix)) . $suffix;
}
