/**
 * Issues Page Component
 * 
 * Organized, filterable list of all SEO issues
 */

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

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) {
    return '';
  }

  if (value.includes('?_site_level_checks')) {
    return '';
  }

  return value;
};

const IssuesPage = ({
  issues = [],
  isLoading = false,
  auditStatus = null,
  onFixIssue,
  onIgnoreIssue,
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [severityFilter, setSeverityFilter] = useState('all');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [expandedIssue, setExpandedIssue] = useState(null);
  const [sortBy, setSortBy] = useState('severity');

  // Severity order for sorting
  const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, warning: 4 };

  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',
      missing_meta_description: 'on_page_seo',
      missing_title: 'on_page_seo',
      duplicate_title: 'on_page_seo',
      duplicate_meta_description: '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',
      thin_content: 'content',
      low_lexical_diversity: 'content',
      multiple_h1: 'content',
      heading_levels_skipped: 'content',
      iframes_missing_title: 'accessibility',
      links_without_accessible_text: 'accessibility',
    };

    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
        : Array.isArray(issue?.pages) && issue.pages.length
          ? issue.pages.map((page) => (typeof page === 'string' ? page : page?.url))
          : 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';
  };

  const getIssueScopeLabel = (issue) => {
    const scopeType = getIssueScopeType(issue);

    if (scopeType === 'sitewide') {
      return __('Site-wide check', 'prorank-seo');
    }

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

    const urls = getIssueUrls(issue);

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

    return __('Scope not available', 'prorank-seo');
  };

  const getIssueRowKey = (issue, index) => String(
    issue?.id
    || issue?.issue_id
    || issue?.uuid
    || `${getIssueTypeKey(issue) || 'issue'}-${index}`
  );

  // Get unique categories from issues
  const categories = useMemo(() => {
    const cats = new Set(issues.map((issue) => getIssueCategory(issue)));
    return Array.from(cats);
  }, [issues]);

  // Filter and sort issues
  const filteredIssues = useMemo(() => {
    let filtered = [...issues];

    // Search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(issue =>
        getIssueDisplayTitle(issue).toLowerCase().includes(term) ||
        getIssueDescription(issue).toLowerCase().includes(term) ||
        getIssueUrls(issue).some((url) => String(url || '').toLowerCase().includes(term))
      );
    }

    // Severity filter
    if (severityFilter !== 'all') {
      filtered = filtered.filter(issue => issue.severity === severityFilter);
    }

    // Category filter
    if (categoryFilter !== 'all') {
      filtered = filtered.filter(issue => getIssueCategory(issue) === categoryFilter);
    }

    // Sort
    filtered.sort((a, b) => {
      if (sortBy === 'severity') {
        return (severityOrder[a.severity] || 5) - (severityOrder[b.severity] || 5);
      }
      if (sortBy === 'category') {
        return getIssueCategory(a).localeCompare(getIssueCategory(b));
      }
      return 0;
    });

    return filtered;
  }, [issues, searchTerm, severityFilter, categoryFilter, sortBy]);

  // Group issues by type for summary
  const issueSummary = useMemo(() => {
    const summary = { critical: 0, high: 0, medium: 0, low: 0, warning: 0 };
    issues.forEach(issue => {
      if (summary[issue.severity] !== undefined) {
        summary[issue.severity]++;
      }
    });
    return summary;
  }, [issues]);

  // Group filtered issues by category
  const groupedIssues = useMemo(() => {
    const groups = {};
    filteredIssues.forEach(issue => {
      const scope = getIssueScopeType(issue);
      const cat = getIssueCategory(issue);

      if (!groups[scope]) {
        groups[scope] = {};
      }

      if (!groups[scope][cat]) {
        groups[scope][cat] = [];
      }

      groups[scope][cat].push(issue);
    });
    return groups;
  }, [filteredIssues]);

  const issueSections = useMemo(() => {
    const sectionMeta = {
      page: {
        key: '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: {
        key: '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: {
        key: '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 ['page', 'sitewide', 'crawl']
      .map((scope) => {
        const categoriesMap = groupedIssues[scope] || {};
        const categoryEntries = Object.entries(categoriesMap).sort(([a], [b]) => {
          return getCategoryLabel(a).localeCompare(getCategoryLabel(b));
        });

        const issueCount = categoryEntries.reduce((count, [, scopeIssues]) => count + scopeIssues.length, 0);

        return {
          ...sectionMeta[scope],
          issueCount,
          categories: categoryEntries,
        };
      })
      .filter((section) => section.issueCount > 0);
  }, [groupedIssues]);

  const getSeverityColor = (severity) => {
    const colors = {
      critical: '#dc2626',
      high: '#ea580c',
      medium: '#d97706',
      low: '#2563eb',
      warning: '#6b7280',
    };
    return colors[severity] || '#6b7280';
  };

  const getSeverityBgColor = (severity) => {
    const colors = {
      critical: '#fef2f2',
      high: '#fff7ed',
      medium: '#fffbeb',
      low: '#eff6ff',
      warning: '#f9fafb',
    };
    return colors[severity] || '#f9fafb';
  };

  function getCategoryLabel(cat) {
    const labels = {
      technical_seo: __('Technical SEO', 'prorank-seo'),
      on_page_seo: __('On-Page SEO', 'prorank-seo'),
      performance: __('Performance', 'prorank-seo'),
      security: __('Security', 'prorank-seo'),
      content: __('Content', 'prorank-seo'),
      accessibility: __('Accessibility', 'prorank-seo'),
      wordpress: __('WordPress', 'prorank-seo'),
    };
    return labels[cat] || humanizeIssueKey(cat);
  }

  const visibleCategoryCount = issueSections.reduce((count, section) => count + section.categories.length, 0);
  const hasActiveFilters = Boolean(
    searchTerm
    || severityFilter !== 'all'
    || categoryFilter !== 'all'
    || sortBy !== 'severity'
  );

  const clearFilters = () => {
    setSearchTerm('');
    setSeverityFilter('all');
    setCategoryFilter('all');
    setSortBy('severity');
  };

  if (auditStatus?.state !== 'completed') {
    return (
      <Card>
        <CardBody>
          <div style={{ textAlign: 'center', padding: '40px 20px' }}>
            <Icon icon={info} size={48} style={{ color: '#6b7280', marginBottom: '16px' }} />
            <Heading level={3} style={{ marginBottom: '8px' }}>
              {__('No Audit Data', 'prorank-seo')}
            </Heading>
            <Text>{__('Run an audit to see issues.', 'prorank-seo')}</Text>
          </div>
        </CardBody>
      </Card>
    );
  }

  return (
    <div className="prorank-issues-page">
      <div className="prorank-audit-hero">
        <div className="prorank-audit-hero__copy">
          <span className="prorank-audit-hero__eyebrow">
            {__('Issue Review', 'prorank-seo')}
          </span>
          <Heading level={2} style={{ margin: '0 0 8px' }}>
            {__('Audit findings grouped by impact and scope', 'prorank-seo')}
          </Heading>
          <Text className="prorank-audit-hero__description">
            {__('Page issues, site-wide checks, and crawler/server failures are separated so the audit reads like a product report instead of a debug dump.', 'prorank-seo')}
          </Text>
        </div>
        <div className="prorank-audit-hero__metrics">
          <div className="prorank-audit-hero__metric">
            <span className="prorank-audit-hero__metric-value">{filteredIssues.length}</span>
            <span className="prorank-audit-hero__metric-label">{__('Visible findings', 'prorank-seo')}</span>
          </div>
          <div className="prorank-audit-hero__metric">
            <span className="prorank-audit-hero__metric-value">{issueSections.length}</span>
            <span className="prorank-audit-hero__metric-label">{__('Sections', 'prorank-seo')}</span>
          </div>
          <div className="prorank-audit-hero__metric">
            <span className="prorank-audit-hero__metric-value">{visibleCategoryCount}</span>
            <span className="prorank-audit-hero__metric-label">{__('Categories', 'prorank-seo')}</span>
          </div>
        </div>
      </div>

      <div className="prorank-audit-summary-grid">
        {[
          { key: 'critical', label: __('Critical', 'prorank-seo'), color: '#dc2626', bg: '#fef2f2' },
          { key: 'high', label: __('High', 'prorank-seo'), color: '#ea580c', bg: '#fff7ed' },
          { key: 'medium', label: __('Medium', 'prorank-seo'), color: '#ca8a04', bg: '#fefce8' },
          { key: 'low', label: __('Low', 'prorank-seo'), color: '#16a34a', bg: '#f0fdf4' },
          { key: 'warning', label: __('Warnings', 'prorank-seo'), color: '#6b7280', bg: '#f9fafb' },
        ].map(({ key, label, color, bg }) => (
          <Card
            key={key}
            className={`prorank-audit-summary-card ${severityFilter === key ? 'is-active' : ''}`}
            data-severity={key}
            onClick={() => setSeverityFilter(severityFilter === key ? 'all' : key)}
          >
            <CardBody className="prorank-audit-summary-card__body">
              <div className="prorank-audit-summary-card__value" style={{ color }}>
                {issueSummary[key]}
              </div>
              <div className="prorank-audit-summary-card__label">
                {label}
              </div>
              {severityFilter === key && (
                <div className="prorank-audit-summary-card__state" style={{ color }}>
                  {__('Filtering active', 'prorank-seo')}
                </div>
              )}
            </CardBody>
          </Card>
        ))}
      </div>

      <Card className="prorank-audit-toolbar-card">
        <CardBody>
          <div className="prorank-audit-toolbar">
            <div className="prorank-audit-toolbar__header">
              <div>
                <Heading level={4} style={{ margin: '0 0 4px' }}>
                  {__('Refine the issue list', 'prorank-seo')}
                </Heading>
                <Text className="prorank-audit-toolbar__copy">
                  {__('Search, filter, and sort while keeping the grouped audit layout intact.', 'prorank-seo')}
                </Text>
              </div>
              {hasActiveFilters && (
                <Button variant="secondary" onClick={clearFilters}>
                  {__('Clear filters', 'prorank-seo')}
                </Button>
              )}
            </div>
            <Flex className="prorank-audit-toolbar__filters">
            <FlexBlock>
              <TextControl
                label={__('Search Issues', 'prorank-seo')}
                value={searchTerm}
                onChange={setSearchTerm}
                placeholder={__('Search by title, description, or URL...', 'prorank-seo')}
                __next40pxDefaultSize
                __nextHasNoMarginBottom
              />
            </FlexBlock>
            <FlexItem>
              <SelectControl
                label={__('Severity', 'prorank-seo')}
                value={severityFilter}
                options={[
                  { label: __('All Severities', 'prorank-seo'), value: 'all' },
                  { label: __('Critical', 'prorank-seo'), value: 'critical' },
                  { label: __('High', 'prorank-seo'), value: 'high' },
                  { label: __('Medium', 'prorank-seo'), value: 'medium' },
                  { label: __('Low', 'prorank-seo'), value: 'low' },
                  { label: __('Warning', 'prorank-seo'), value: 'warning' },
                ]}
                onChange={setSeverityFilter}
                __next40pxDefaultSize
                __nextHasNoMarginBottom
              />
            </FlexItem>
            <FlexItem>
              <SelectControl
                label={__('Category', 'prorank-seo')}
                value={categoryFilter}
                options={[
                  { label: __('All Categories', 'prorank-seo'), value: 'all' },
                  ...categories.map(cat => ({ 
                    label: getCategoryLabel(cat), 
                    value: cat 
                  }))
                ]}
                onChange={setCategoryFilter}
                __next40pxDefaultSize
                __nextHasNoMarginBottom
              />
            </FlexItem>
            <FlexItem>
              <SelectControl
                label={__('Sort By', 'prorank-seo')}
                value={sortBy}
                options={[
                  { label: __('Severity', 'prorank-seo'), value: 'severity' },
                  { label: __('Category', 'prorank-seo'), value: 'category' },
                ]}
                onChange={setSortBy}
                __next40pxDefaultSize
                __nextHasNoMarginBottom
              />
            </FlexItem>
            </Flex>
          </div>
        </CardBody>
      </Card>

      <div className="prorank-audit-results-bar">
        <span>
          {sprintf(__('Showing %1$d of %2$d findings across %3$d sections', 'prorank-seo'), filteredIssues.length, issues.length, issueSections.length)}
        </span>
        {hasActiveFilters && (
          <span className="prorank-audit-results-bar__tag">
            {__('Filtered view', 'prorank-seo')}
          </span>
        )}
      </div>

      {isLoading && (
        <Card className="prorank-audit-empty-card">
          <CardBody className="prorank-audit-empty-card__body">
            <Spinner />
            <Text style={{ marginTop: '16px' }}>{__('Loading issues...', 'prorank-seo')}</Text>
          </CardBody>
        </Card>
      )}

      {!isLoading && filteredIssues.length === 0 && (
        <Card className="prorank-audit-empty-card">
          <CardBody>
            <Notice status="success" isDismissible={false}>
              <p>
                {issues.length === 0 
                  ? __('No issues found! Your site is in great shape.', 'prorank-seo')
                  : __('No issues match your filters.', 'prorank-seo')
                }
              </p>
            </Notice>
          </CardBody>
        </Card>
      )}

      {!isLoading && issueSections.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.issueCount === 1
                  ? __('%d finding', 'prorank-seo')
                  : __('%d findings', 'prorank-seo'),
                section.issueCount
              )}
            </div>
          </div>

          {section.categories.map(([category, categoryIssues]) => (
            <Card key={`${section.key}-${category}`} className="prorank-audit-category-card">
              <CardHeader className="prorank-audit-category-card__header">
                <Flex justify="space-between" align="center">
                  <div>
                    <Heading level={4} style={{ margin: '0 0 4px' }}>
                      {getCategoryLabel(category)}
                    </Heading>
                    <Text className="prorank-audit-category-card__copy">
                      {section.key === 'sitewide'
                        ? __('Environment and maintenance checks grouped under this category.', 'prorank-seo')
                        : section.key === 'crawl'
                          ? __('Crawler and server failures grouped under this category.', 'prorank-seo')
                          : __('Page-level findings grouped under this category.', 'prorank-seo')}
                    </Text>
                  </div>
                  <span className="prorank-audit-category-card__count">
                    {sprintf(
                      categoryIssues.length === 1
                        ? __('%d issue type', 'prorank-seo')
                        : __('%d issue types', 'prorank-seo'),
                      categoryIssues.length
                    )}
                  </span>
                </Flex>
              </CardHeader>
              <CardBody className="prorank-audit-category-card__body">
                {categoryIssues.map((issue, index) => (
                  <div
                    key={getIssueRowKey(issue, index)}
                    className={`prorank-audit-issue-row ${expandedIssue === getIssueRowKey(issue, index) ? 'is-expanded' : ''}`}
                    data-severity={issue.severity}
                    style={{
                      borderBottom: index < categoryIssues.length - 1 ? '1px solid #e2e8f0' : 'none',
                    }}
                  >
                    <div
                      className="prorank-audit-issue-row__trigger"
                      onClick={() => setExpandedIssue(expandedIssue === getIssueRowKey(issue, index) ? null : getIssueRowKey(issue, index))}
                    >
                      <Flex align="center" gap={3}>
                        <div className="prorank-audit-issue-row__severity">
                          {issue.severity}
                        </div>

                        <FlexBlock className="prorank-audit-issue-row__content">
                          <div className="prorank-audit-issue-row__title">
                            {getIssueDisplayTitle(issue)}
                          </div>
                          <div className="prorank-audit-issue-row__meta">
                            {getIssueScopeLabel(issue)}
                          </div>
                          {getIssueDescription(issue) && (
                            <div className="prorank-audit-issue-row__description">
                              {getIssueDescription(issue)}
                            </div>
                          )}
                        </FlexBlock>

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

                    {expandedIssue === getIssueRowKey(issue, index) && (
                      <div className="prorank-audit-issue-row__panel">
                        <div className="prorank-audit-issue-row__panel-card">
                          {getIssueDescription(issue) && (
                            <div className="prorank-audit-detail-card">
                              <strong className="prorank-audit-detail-card__label">
                                {__('Why this matters', 'prorank-seo')}
                              </strong>
                              <p style={{ margin: 0, color: '#4b5563' }}>{getIssueDescription(issue)}</p>
                            </div>
                          )}

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

                          {getIssueUrls(issue).length > 0 && (
                            <div className="prorank-audit-url-card">
                              <strong className="prorank-audit-detail-card__label">
                                {sprintf(
                                  getIssueUrls(issue).length === 1
                                    ? __('Affected Page (%d)', 'prorank-seo')
                                    : __('Affected Pages (%d)', 'prorank-seo'),
                                  getIssueUrls(issue).length
                                )}
                              </strong>
                              <div style={{ display: 'grid', gap: '8px' }}>
                                {getIssueUrls(issue).map((url) => (
                                  <a
                                    key={url}
                                    href={url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    onClick={(event) => event.stopPropagation()}
                                    className="prorank-audit-url-list__item"
                                  >
                                    <span>{url}</span>
                                    <Icon icon={external} size={12} />
                                  </a>
                                ))}
                              </div>
                            </div>
                          )}

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

                          {getIssueScopeType(issue) === '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>
                          )}

                          {(issue.current_value || issue.recommended_value) && (
                            <div className="prorank-audit-value-grid">
                              {issue.current_value && (
                                <div className="prorank-audit-value-card prorank-audit-value-card--current">
                                  <strong className="prorank-audit-value-card__label">
                                    {__('Current', 'prorank-seo')}
                                  </strong>
                                  <code style={{ fontSize: '13px', wordBreak: 'break-all' }}>
                                    {issue.current_value}
                                  </code>
                                </div>
                              )}
                              {issue.recommended_value && (
                                <div className="prorank-audit-value-card prorank-audit-value-card--recommended">
                                  <strong className="prorank-audit-value-card__label">
                                    {__('Recommended', 'prorank-seo')}
                                  </strong>
                                  <code style={{ fontSize: '13px', wordBreak: 'break-all' }}>
                                    {issue.recommended_value}
                                  </code>
                                </div>
                              )}
                            </div>
                          )}

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

                          <Flex gap={2} className="prorank-audit-action-row">
                            {issue.fix_available && onFixIssue && (
                              <Button 
                                variant="primary"
                                size="small"
                                onClick={() => onFixIssue(issue)}
                              >
                                {__('Apply Fix', 'prorank-seo')}
                              </Button>
                            )}
                            {onIgnoreIssue && (
                              <Button 
                                variant="secondary"
                                size="small"
                                onClick={() => onIgnoreIssue(issue)}
                              >
                                {__('Ignore', 'prorank-seo')}
                              </Button>
                            )}
                            {issue.reference && (
                              <Button 
                                variant="tertiary"
                                size="small"
                                href={issue.reference}
                                target="_blank"
                              >
                                {__('Learn More', 'prorank-seo')}
                                <Icon icon={external} size={14} style={{ marginLeft: '4px' }} />
                              </Button>
                            )}
                          </Flex>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </CardBody>
            </Card>
          ))}
        </section>
      ))}
    </div>
  );
};

export default IssuesPage;
