/**
 * Report Issues View Component
 *
 * Groups audit issues by type (title), organized by category,
 * with severity filtering, affected page counts, fix guidance,
 * and links to the relevant ProRank module.
 */

import React, { useState, useMemo } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import {
  Card,
  CardBody,
  CardHeader,
  Button,
  Icon,
  __experimentalHeading as Heading,
  __experimentalText as Text,
  Flex,
  FlexItem,
  FlexBlock,
} from '@wordpress/components';
import { external, arrowRight } from '@wordpress/icons';

const SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3, warning: 4 };

const normalizeIssueKey = (value) => String(value || '')
  .trim()
  .toLowerCase()
  .replace(/[\s-]+/g, '_')
  .replace(/[^a-z0-9_]/g, '');

const humanizeIssueKey = (value) => String(value || '')
  .replace(/[_-]+/g, ' ')
  .replace(/\b\w/g, (char) => char.toUpperCase())
  .trim();

const SITE_WIDE_ISSUE_TYPES = new Set([
  'plugins_need_updates',
  'potential_plugin_conflict',
  'database_optimization',
  'security_headers',
  'ssl_certificate',
  'mixed_content',
]);

const CRAWL_SERVER_ISSUE_TYPES = new Set([
  'connectivity',
  'crawl_fetch_failed',
  'crawl_timeout',
  'crawl_error',
  'server_response_error',
  'http_status',
]);

const normalizeIssueUrl = (url) => {
  const value = String(url || '').trim();
  if (!value || value.includes('?_site_level_checks')) {
    return '';
  }

  return value;
};

const SEVERITY_META = {
  critical: { label: 'Critical', color: '#dc2626', bg: '#fef2f2', border: '#fecaca' },
  high:     { label: 'High',     color: '#ea580c', bg: '#fff7ed', border: '#fed7aa' },
  medium:   { label: 'Medium',   color: '#ca8a04', bg: '#fefce8', border: '#fef08a' },
  low:      { label: 'Low',      color: '#16a34a', bg: '#f0fdf4', border: '#bbf7d0' },
  warning:  { label: 'Warnings', color: '#6b7280', bg: '#f9fafb', border: '#e5e7eb' },
};

const CATEGORY_LABELS = {
  technical_seo: 'Technical SEO',
  on_page_seo: 'On-Page SEO',
  performance: 'Performance',
  security: 'Security',
  content: 'Content',
  accessibility: 'Accessibility',
  wordpress: 'WordPress',
};

const CATEGORY_ORDER = ['technical_seo', 'on_page_seo', 'performance', 'security', 'content', 'accessibility', 'wordpress'];
const SCOPE_ORDER = ['page', 'sitewide', 'crawl'];

const CATEGORY_MODULE = {
  technical_seo: 'admin.php?page=prorank-technical-seo',
  security:      'admin.php?page=prorank-technical-seo',
  on_page_seo:   'admin.php?page=prorank-on-page-seo',
  content:       'admin.php?page=prorank-on-page-seo',
  performance:   'admin.php?page=prorank-performance',
  accessibility: 'admin.php?page=prorank-site-audit',
  wordpress:     'admin.php?page=prorank-site-audit',
};

const ReportIssuesView = ({ issues = [], embedded = false }) => {
  const [activeSeverity, setActiveSeverity] = useState('all');
  const [expandedGroups, setExpandedGroups] = useState({});

  const getIssueTypeKey = (issue) => normalizeIssueKey(
    issue?.type
    || issue?.issue_type
    || issue?.issue_key
    || issue?.key
    || issue?.title
  );

  const getIssueCategory = (issue) => {
    const explicitCategory = normalizeIssueKey(
      issue?.display_category
      || issue?.category
      || issue?.issue_category
      || issue?.displayCategory
      || issue?.issueCategory
    );

    if (explicitCategory && explicitCategory !== 'other') {
      return explicitCategory;
    }

    const typeKey = getIssueTypeKey(issue);
    const categoryMap = {
      connectivity: 'technical_seo',
      redirect_chain: 'technical_seo',
      redirect_loop: 'technical_seo',
      orphaned_page: 'on_page_seo',
      plugins_need_updates: 'wordpress',
      potential_plugin_conflict: 'wordpress',
      database_optimization: 'wordpress',
      security_headers: 'security',
      mixed_content: 'security',
      ssl_certificate: 'security',
      page_speed: 'performance',
      core_web_vitals: 'performance',
      css_import_usage: 'performance',
      duplicate_content: 'content',
      low_lexical_diversity: 'content',
      links_without_accessible_text: 'accessibility',
      iframes_missing_title: 'accessibility',
      multiple_h1: 'content',
      heading_levels_skipped: 'content',
    };

    if (categoryMap[typeKey]) {
      return categoryMap[typeKey];
    }

    if (typeKey.includes('plugin') || typeKey.includes('wordpress') || typeKey.includes('database')) {
      return 'wordpress';
    }

    if (typeKey.includes('security') || typeKey.includes('ssl') || typeKey.includes('mixed')) {
      return 'security';
    }

    if (typeKey.includes('speed') || typeKey.includes('performance') || typeKey.includes('cache') || typeKey.includes('cwv')) {
      return 'performance';
    }

    if (typeKey.includes('content') || typeKey.includes('title') || typeKey.includes('meta') || typeKey.includes('heading')) {
      return 'content';
    }

    return 'technical_seo';
  };

  const getIssueDisplayTitle = (issue) => {
    const explicitTitle = String(issue?.title || '').trim();
    const typeKey = getIssueTypeKey(issue);

    const typeLabels = {
      connectivity: __('Server response could not be read by the audit crawler', 'prorank-seo'),
      orphaned_page: __('Orphaned page', 'prorank-seo'),
      plugins_need_updates: __('Plugins need updates', 'prorank-seo'),
      potential_plugin_conflict: __('Potential plugin conflict', 'prorank-seo'),
      security_headers: __('Missing security headers', 'prorank-seo'),
      mixed_content: __('Mixed content detected', 'prorank-seo'),
      css_import_usage: __('CSS @import usage', 'prorank-seo'),
      duplicate_content: __('Duplicate content', 'prorank-seo'),
      low_lexical_diversity: __('Low lexical diversity', 'prorank-seo'),
      links_without_accessible_text: __('Links without accessible text', 'prorank-seo'),
      iframes_missing_title: __('Iframes missing title', 'prorank-seo'),
      multiple_h1: __('Multiple H1 headings', 'prorank-seo'),
      heading_levels_skipped: __('Heading levels skipped', 'prorank-seo'),
    };

    if (typeLabels[typeKey]) {
      return typeLabels[typeKey];
    }

    if (explicitTitle && !/^[a-z0-9_ -]+$/i.test(explicitTitle)) {
      return explicitTitle;
    }

    if (explicitTitle && !explicitTitle.includes('_')) {
      return explicitTitle;
    }

    if (typeKey) {
      return humanizeIssueKey(typeKey);
    }

    if (explicitTitle) {
      return humanizeIssueKey(explicitTitle);
    }

    return __('Issue', 'prorank-seo');
  };

  const getIssueDescription = (issue) => {
    const typeKey = getIssueTypeKey(issue);
    const description = String(issue?.description || '').trim();
    if (description) {
      return description;
    }

    if (typeKey === 'connectivity') {
      return __('The audit crawler could not decode the server response. This usually points to broken compression or caching headers rather than a problem with the page content itself.', 'prorank-seo');
    }

    if (typeKey === 'plugins_need_updates') {
      return __('Installed plugins have updates available. This is a site-wide maintenance item, not a page-specific content issue.', 'prorank-seo');
    }

    if (typeKey === 'potential_plugin_conflict') {
      return __('Another plugin may overlap with ProRank features. Review overlapping optimization or caching features before enabling both together.', 'prorank-seo');
    }

    const message = String(issue?.message || '').trim();
    if (!message) {
      return '';
    }

    return message === getIssueDisplayTitle(issue) ? '' : message;
  };

  const getIssueTechnicalDetails = (issue) => {
    const message = String(issue?.message || '').trim();
    const description = String(issue?.description || '').trim();
    if (!message || message === description) {
      return '';
    }

    return message;
  };

  const getIssueUrls = (issue) => {
    const rawUrls = Array.isArray(issue?.affected_urls) && issue.affected_urls.length
      ? issue.affected_urls
      : Array.isArray(issue?.urls) && issue.urls.length
        ? issue.urls
        : issue?.url
          ? [issue.url]
          : [];

    return Array.from(new Set(rawUrls.map(normalizeIssueUrl).filter(Boolean)));
  };

  const isSiteLevelIssue = (issue) => {
    if (SITE_WIDE_ISSUE_TYPES.has(getIssueTypeKey(issue))) {
      return true;
    }

    const rawUrls = []
      .concat(Array.isArray(issue?.affected_urls) ? issue.affected_urls : [])
      .concat(Array.isArray(issue?.urls) ? issue.urls : [])
      .concat(typeof issue?.url === 'string' ? [issue.url] : []);

    return rawUrls.some((url) => String(url || '').includes('?_site_level_checks'));
  };

  const isCrawlServerIssue = (issue) => {
    const typeKey = getIssueTypeKey(issue);
    if (CRAWL_SERVER_ISSUE_TYPES.has(typeKey)) {
      return true;
    }

    if (
      typeKey.includes('connectivity')
      || typeKey.includes('crawl')
      || typeKey.includes('fetch')
      || typeKey.includes('timeout')
      || typeKey.includes('http_status')
    ) {
      return true;
    }

    const explicitCategory = normalizeIssueKey(
      issue?.display_category
      || issue?.category
      || issue?.issue_category
      || issue?.displayCategory
      || issue?.issueCategory
    );

    return explicitCategory === 'crawl' || explicitCategory === 'server';
  };

  const getIssueScopeType = (issue) => {
    if (isSiteLevelIssue(issue)) {
      return 'sitewide';
    }

    if (isCrawlServerIssue(issue)) {
      return 'crawl';
    }

    return 'page';
  };

  // Group issues by title, compute per-group metadata
  const issueGroups = useMemo(() => {
    const map = {};
    issues.forEach((issue) => {
      const key = getIssueDisplayTitle(issue);
      if (!map[key]) {
        map[key] = {
          title: key,
          severity: issue.severity || 'warning',
          category: getIssueCategory(issue),
          how_to_fix: issue.how_to_fix || '',
          description: getIssueDescription(issue),
          technicalDetails: getIssueTechnicalDetails(issue),
          scope: getIssueScopeType(issue),
          urls: [],
          findings: 0,
        };
      }

      if (!map[key].how_to_fix && issue.how_to_fix) {
        map[key].how_to_fix = issue.how_to_fix;
      }
      if (!map[key].description && getIssueDescription(issue)) {
        map[key].description = getIssueDescription(issue);
      }
      if (!map[key].technicalDetails && getIssueTechnicalDetails(issue)) {
        map[key].technicalDetails = getIssueTechnicalDetails(issue);
      }

      const issueCount = Number(issue?.count ?? 0);
      map[key].findings += Number.isFinite(issueCount) && issueCount > 0 ? issueCount : 1;

      const affectedUrls = getIssueUrls(issue);

      affectedUrls.forEach((url) => {
        if (!url || map[key].urls.includes(url)) return;
        map[key].urls.push(url);
      });

      map[key].scope = getIssueScopeType(issue);
    });
    return Object.values(map);
  }, [issues]);

  // Severity summary counts (by group, not by individual URL)
  const severityCounts = useMemo(() => {
    const counts = { critical: 0, high: 0, medium: 0, low: 0, warning: 0 };
    issueGroups.forEach((g) => {
      if (counts[g.severity] !== undefined) counts[g.severity]++;
    });
    return counts;
  }, [issueGroups]);

  // Filter groups by selected severity
  const filteredGroups = useMemo(() => {
    if (activeSeverity === 'all') return issueGroups;
    return issueGroups.filter((g) => g.severity === activeSeverity);
  }, [issueGroups, activeSeverity]);

  const totalFindings = useMemo(
    () => issueGroups.reduce((sum, group) => sum + Math.max(1, Number(group.findings || 0)), 0),
    [issueGroups]
  );

  function normalizeCategoryKey(cat) {
    return String(cat || '')
      .trim()
      .toLowerCase()
      .replace(/[\s-]+/g, '_')
      .replace(/[^a-z_]/g, '');
  }

  function getCategoryLabel(cat) {
    const key = normalizeCategoryKey(cat);
    return CATEGORY_LABELS[key] || humanizeIssueKey(cat);
  }

  function getModuleUrl(cat) {
    const key = normalizeCategoryKey(cat);
    return CATEGORY_MODULE[key] || 'admin.php?page=prorank-seo';
  }

  const groupedBySection = useMemo(() => {
    const scopeMap = {};
    filteredGroups.forEach((group) => {
      const scope = group.scope || 'page';
      const category = group.category;
      if (!scopeMap[scope]) {
        scopeMap[scope] = {};
      }
      if (!scopeMap[scope][category]) {
        scopeMap[scope][category] = [];
      }
      scopeMap[scope][category].push(group);
    });

    return SCOPE_ORDER
      .map((scope) => {
        const categories = scopeMap[scope] || {};
        const orderedCategories = [];

        CATEGORY_ORDER.forEach((category) => {
          if (categories[category]) {
            orderedCategories.push([category, categories[category]]);
          }
        });

        Object.keys(categories).forEach((category) => {
          if (!CATEGORY_ORDER.includes(category)) {
            orderedCategories.push([category, categories[category]]);
          }
        });

        orderedCategories.forEach(([, groups]) => {
          groups.sort((a, b) => (SEVERITY_ORDER[a.severity] ?? 5) - (SEVERITY_ORDER[b.severity] ?? 5));
        });

        const issueTypeCount = orderedCategories.reduce((count, [, groups]) => count + groups.length, 0);

        const sectionMeta = {
          page: {
            title: __('Page Issues', 'prorank-seo'),
            description: __('Issues tied to specific pages or posts. These are the findings that most directly affect on-page SEO and content quality.', 'prorank-seo'),
          },
          sitewide: {
            title: __('Site-wide Checks', 'prorank-seo'),
            description: __('Environment and maintenance checks that apply to the whole WordPress site rather than a single page.', 'prorank-seo'),
          },
          crawl: {
            title: __('Crawl / Server Errors', 'prorank-seo'),
            description: __('Crawler transport failures and server-response problems. These can affect audit coverage, but they do not always mean the page content itself is broken.', 'prorank-seo'),
          },
        };

        return {
          key: scope,
          ...sectionMeta[scope],
          issueTypeCount,
          categories: orderedCategories,
        };
      })
      .filter((section) => section.issueTypeCount > 0);
  }, [filteredGroups]);

  const toggleGroup = (groupKey) => {
    setExpandedGroups((prev) => ({ ...prev, [groupKey]: !prev[groupKey] }));
  };

  const getGroupScopeLabel = (group) => {
    if ((group.scope || 'page') === 'sitewide') {
      return __('Site-wide check', 'prorank-seo');
    }

    if ((group.scope || 'page') === 'crawl') {
      if (group.urls.length > 0) {
        return sprintf(
          group.urls.length === 1
            ? __('Crawler/server issue affecting %d page', 'prorank-seo')
            : __('Crawler/server issue affecting %d pages', 'prorank-seo'),
          group.urls.length
        );
      }

      return __('Crawler/server check', 'prorank-seo');
    }

    return group.urls.length > 0
      ? sprintf(
          group.urls.length === 1 ? __('%d page affected', 'prorank-seo') : __('%d pages affected', 'prorank-seo'),
          group.urls.length
        )
      : __('Scope not available', 'prorank-seo');
  };

  if (!issues.length) {
    return (
      <Card>
        <CardBody style={{ textAlign: 'center', padding: '40px 20px' }}>
          <Heading level={4} style={{ marginBottom: '8px' }}>
            {__('No Issues Found', 'prorank-seo')}
          </Heading>
          <Text>{__('This audit found no issues. Great job!', 'prorank-seo')}</Text>
        </CardBody>
      </Card>
    );
  }

  return (
    <div className={`prorank-report-issues-view ${embedded ? 'is-embedded' : ''}`}>
      {!embedded && (
        <div className="prorank-audit-hero">
          <div className="prorank-audit-hero__copy">
            <span className="prorank-audit-hero__eyebrow">
              {__('Audit Report', 'prorank-seo')}
            </span>
            <Heading level={2} style={{ margin: '0 0 8px' }}>
              {__('Grouped findings for faster review and action', 'prorank-seo')}
            </Heading>
            <Text className="prorank-audit-hero__description">
              {__('Each issue type is grouped by category and scope so you can review the report the same way you would triage real SEO work.', 'prorank-seo')}
            </Text>
          </div>
          <div className="prorank-audit-hero__metrics">
            <div className="prorank-audit-hero__metric">
              <span className="prorank-audit-hero__metric-value">{issueGroups.length}</span>
              <span className="prorank-audit-hero__metric-label">{__('Issue types', 'prorank-seo')}</span>
            </div>
            <div className="prorank-audit-hero__metric">
              <span className="prorank-audit-hero__metric-value">{totalFindings}</span>
              <span className="prorank-audit-hero__metric-label">{__('Total findings', 'prorank-seo')}</span>
            </div>
            <div className="prorank-audit-hero__metric">
              <span className="prorank-audit-hero__metric-value">{groupedBySection.length}</span>
              <span className="prorank-audit-hero__metric-label">{__('Sections', 'prorank-seo')}</span>
            </div>
          </div>
        </div>
      )}

      {embedded && (
        <div className="prorank-audit-inline-header">
          <div>
            <span className="prorank-audit-inline-header__eyebrow">
              {__('Grouped Findings', 'prorank-seo')}
            </span>
            <Heading level={3} style={{ margin: '8px 0 0' }}>
              {__('Issue sections and remediation paths', 'prorank-seo')}
            </Heading>
            <Text className="prorank-audit-inline-header__description">
              {__('The report keeps page issues, site-wide checks, and crawler failures separate so the action plan stays clear.', 'prorank-seo')}
            </Text>
          </div>
          <div className="prorank-audit-inline-header__meta">
            <span className="prorank-audit-inline-header__chip">
              {sprintf(__('%d issue types', 'prorank-seo'), issueGroups.length)}
            </span>
            <span className="prorank-audit-inline-header__chip">
              {sprintf(__('%d findings', 'prorank-seo'), totalFindings)}
            </span>
            <span className="prorank-audit-inline-header__chip">
              {sprintf(__('%d sections', 'prorank-seo'), groupedBySection.length)}
            </span>
          </div>
        </div>
      )}

      <div className="prorank-audit-summary-grid">
        {Object.entries(SEVERITY_META).map(([key, meta]) => {
          const count = severityCounts[key] || 0;
          const isActive = activeSeverity === key;
          return (
            <div
              key={key}
              onClick={() => setActiveSeverity(isActive ? 'all' : key)}
              className={`prorank-audit-summary-card ${isActive ? 'is-active' : ''}`}
              data-severity={key}
            >
              <div className="prorank-audit-summary-card__body">
                <div className="prorank-audit-summary-card__value" style={{ color: meta.color }}>
                  {count}
                </div>
                <div className="prorank-audit-summary-card__label">
                  {meta.label}
                </div>
                {isActive && (
                  <div className="prorank-audit-summary-card__state" style={{ color: meta.color }}>
                    {__('Filtering active', 'prorank-seo')}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <div className="prorank-audit-results-bar">
        {activeSeverity !== 'all'
          ? sprintf(
              __('Showing %d of %d issue types (%s only)', 'prorank-seo'),
              filteredGroups.length,
              issueGroups.length,
              SEVERITY_META[activeSeverity]?.label || activeSeverity
            )
          : sprintf(__('%d unique issue types across %d total findings', 'prorank-seo'), issueGroups.length, totalFindings)
        }
        {activeSeverity !== 'all' && (
          <span className="prorank-audit-results-bar__tag">
            {__('Severity filter active', 'prorank-seo')}
          </span>
        )}
      </div>

      {groupedBySection.map((section) => (
        <section key={section.key} className={`prorank-audit-section prorank-audit-section--${section.key}`}>
          <div className="prorank-audit-section__header">
            <div>
            <Heading level={3} style={{ marginBottom: '4px' }}>
              {section.title}
            </Heading>
              <Text className="prorank-audit-section__description">{section.description}</Text>
            </div>
            <div className="prorank-audit-section__badge">
              {sprintf(
                section.issueTypeCount === 1
                  ? __('%d issue type', 'prorank-seo')
                  : __('%d issue types', 'prorank-seo'),
                section.issueTypeCount
              )}
            </div>
          </div>

          {section.categories.map(([category, groups]) => (
            <Card key={`${section.key}-${category}`} className="prorank-audit-category-card">
              <CardHeader className="prorank-audit-category-card__header">
                <Flex justify="space-between" align="center">
                  <Flex align="center" gap={3}>
                    <div>
                      <Heading level={4} style={{ margin: '0 0 4px' }}>
                      {getCategoryLabel(category)}
                    </Heading>
                      <Text className="prorank-audit-category-card__copy">
                        {__('Grouped issue types in this category share the same module and remediation path.', 'prorank-seo')}
                      </Text>
                    </div>
                    <a
                      href={getModuleUrl(category)}
                      className="prorank-audit-category-card__link"
                    >
                      {__('Open Module', 'prorank-seo')} →
                    </a>
                  </Flex>
                  <span className="prorank-audit-category-card__count">
                    {sprintf(__('%d issue types', 'prorank-seo'), groups.length)}
                  </span>
                </Flex>
              </CardHeader>
              <CardBody className="prorank-audit-category-card__body">
                {groups.map((group, idx) => {
                  const groupKey = `${section.key}--${category}--${group.title}`;
                  const isExpanded = !!expandedGroups[groupKey];
                  const sevMeta = SEVERITY_META[group.severity] || SEVERITY_META.warning;

                  return (
                    <div
                      key={groupKey}
                      className={`prorank-audit-issue-row ${isExpanded ? 'is-expanded' : ''}`}
                      data-severity={group.severity}
                      style={{
                        borderBottom: idx < groups.length - 1 ? '1px solid #e2e8f0' : 'none',
                      }}
                    >
                      <div
                        onClick={() => toggleGroup(groupKey)}
                        className="prorank-audit-issue-row__trigger"
                      >
                        <Flex align="center" gap={3}>
                          <div className="prorank-audit-issue-row__severity">
                            {group.severity}
                          </div>

                          <FlexBlock className="prorank-audit-issue-row__content">
                            <div className="prorank-audit-issue-row__title">
                              {group.title}
                            </div>
                            {group.description && (
                              <div className="prorank-audit-issue-row__description">
                                {group.description}
                              </div>
                            )}
                            <div className="prorank-audit-issue-row__meta">
                              {getGroupScopeLabel(group)}
                              <span className="prorank-audit-issue-row__meta-separator">•</span>
                              <span>
                                {sprintf(__('%d findings', 'prorank-seo'), Math.max(1, Number(group.findings || 0)))}
                              </span>
                              <span className="prorank-audit-issue-row__meta-separator">•</span>
                              <span>{getCategoryLabel(group.category)}</span>
                            </div>
                          </FlexBlock>

                          <div className="prorank-audit-issue-row__arrow">
                            <Icon icon={arrowRight} size={20} />
                          </div>
                        </Flex>
                      </div>

                      {isExpanded && (
                        <div className="prorank-audit-issue-row__panel">
                          <div className="prorank-audit-issue-row__panel-card">
                            {group.description && (
                              <div className="prorank-audit-detail-card">
                                <div className="prorank-audit-detail-card__label">
                                  {__('Why this matters', 'prorank-seo')}
                                </div>
                                <p style={{ margin: 0, color: '#334155', fontSize: '14px', lineHeight: 1.6 }}>
                                  {group.description}
                                </p>
                              </div>
                            )}

                            {group.technicalDetails && (
                              <div className="prorank-audit-detail-card prorank-audit-detail-card--technical">
                                <div className="prorank-audit-detail-card__label">
                                  {__('Technical details', 'prorank-seo')}
                                </div>
                                <p style={{ margin: 0, color: '#64748b', fontFamily: 'monospace', fontSize: '12px', wordBreak: 'break-word' }}>
                                  {group.technicalDetails}
                                </p>
                              </div>
                            )}

                            {(group.scope || 'page') === 'sitewide' && group.urls.length === 0 && (
                              <div className="prorank-audit-inline-note">
                                {__('This issue was detected during a site-wide environment check.', 'prorank-seo')}
                              </div>
                            )}

                            {(group.scope || 'page') === 'crawl' && (
                              <div className="prorank-audit-inline-note prorank-audit-inline-note--warning">
                                {__('This is a crawler/server response problem. Fix the transport layer first, then rerun the audit before treating it like a page-content issue.', 'prorank-seo')}
                              </div>
                            )}

                            {group.how_to_fix && (
                              <div className="prorank-audit-detail-card prorank-audit-detail-card--fix">
                                <div className="prorank-audit-detail-card__label">
                                  {__('Recommended action', 'prorank-seo')}
                                </div>
                                <p style={{ margin: 0, color: '#1e40af', fontSize: '14px', lineHeight: 1.6 }}>
                                  {group.how_to_fix}
                                </p>
                              </div>
                            )}

                            <div className="prorank-audit-action-row" style={{ marginBottom: '16px' }}>
                              <Button
                                variant="primary"
                                href={getModuleUrl(group.category)}
                                style={{
                                  backgroundColor: '#2563eb',
                                  borderColor: '#2563eb',
                                  borderRadius: '8px',
                                  padding: '8px 20px',
                                  fontWeight: 600,
                                  textDecoration: 'none',
                                }}
                              >
                                {__('Fix in Module', 'prorank-seo')}
                                <span style={{ marginLeft: '6px' }}>→</span>
                              </Button>
                            </div>

                            {group.urls.length > 0 && (
                              <div className="prorank-audit-url-card">
                                <div className="prorank-audit-detail-card__label">
                                  {sprintf(__('Affected Pages (%d)', 'prorank-seo'), group.urls.length)}
                                </div>
                                <div className="prorank-audit-url-list">
                                  {group.urls.map((url, i) => (
                                    <a
                                      key={i}
                                      href={url}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="prorank-audit-url-list__item"
                                    >
                                      <span>{url}</span>
                                      <Icon icon={external} size={12} style={{ flexShrink: 0, color: '#94a3b8' }} />
                                    </a>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </CardBody>
            </Card>
          ))}
        </section>
      ))}

      {filteredGroups.length === 0 && (
        <Card className="prorank-audit-empty-card">
          <CardBody className="prorank-audit-empty-card__body">
            <Text style={{ color: '#64748b' }}>
              {__('No issues match the selected severity filter.', 'prorank-seo')}
            </Text>
            <div style={{ marginTop: '12px' }}>
              <Button variant="secondary" onClick={() => setActiveSeverity('all')}>
                {__('Clear Filter', 'prorank-seo')}
              </Button>
            </div>
          </CardBody>
        </Card>
      )}
    </div>
  );
};

export default ReportIssuesView;
