/**
 * Caching & CDN Settings - Unified Design with TypeScript
 */

import {  useState, useEffect, useCallback  } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {
  TextControl,
  TextareaControl,
  SelectControl,
  Notice,
  Spinner,
  RangeControl,
  Modal,
  Button,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import ProrankToggleSlider from '../../../components/ProrankToggleSlider';
import ProrankButton from '../../../components/ProrankButton';
import { useNotification } from '../../../contexts/NotificationContext';
import * as React from 'react';

// TypeScript Interfaces - Keys match settings manager (cache group)
interface CachingSettings {
  // Page Cache (settings manager uses short names without cache_ prefix)
  enabled: boolean;
  lifetime: number;
  exclude_urls: string;
  cache_exclude_categories: string[];
  cache_exclude_tags: string[];
  cache_exclude_post_types: string[];

  // CDN
  cdn_provider: 'none' | 'cloudflare' | 'bunnycdn' | 'fastly' | 'cloudfront' | 'keycdn' | 'webhook';
  cloudflare_zone_id: string;
  cloudflare_api_token: string;
  bunny_pullzone_id: string;
  bunny_api_key: string;
  fastly_service_id: string;
  fastly_api_token: string;
  cdn_webhook_url: string;
  cdn_webhook_secret: string;
  keycdn_zone_id: string;
  keycdn_api_key: string;
  cloudfront_distribution_id: string;
  cloudfront_access_key: string;
  cloudfront_secret_key: string;
  cdn_clear_on_purge_all: boolean;

  // Cache Warming + adaptive throttle
  preload_enabled: boolean;
  preload_load_throttle_enabled: boolean;
  preload_max_load_average: number;
  preload_batch_delay: number;

  // WooCommerce cache safety
  woocommerce_safe_cache_enabled: boolean;

  // Read-only runtime flags (from API; never persisted)
  preload_throttle_supported?: boolean;
  preload_current_load?: number | null;
  woocommerce_active?: boolean;

  // Link Preloading
  link_preload_enabled: boolean;
  link_preload_delay: number;

  // DNS Prefetch
  dns_prefetch_enabled: boolean;
  dns_prefetch_hosts: string;
  dynamic_resource_hints_enabled: boolean;

  // Font Preloading
  font_preload_enabled: boolean;
  font_preload_urls: string;

  // Browser Cache
  browser_cache_enabled: boolean;
  browser_cache_images: string;
  browser_cache_css: string;
  browser_cache_js: string;
  browser_cache_fonts: string;
  browser_cache_html: string;

  // JS Optimization
  js_defer: boolean;
  js_delay: boolean;
  tracker_delay_enabled: boolean;
  js_delay_jquery: boolean;
  js_delay_elementor_modules: boolean;
  js_exclude: string;

  // CSS Optimization
  css_minify: boolean;
  css_combine: boolean;
  css_async: boolean;
  inline_css_minify_enabled: boolean;
  inline_css_relocate_enabled: boolean;
  css_exclude: string;
  performance_conflict_safe_mode: boolean;
}

interface CachingDeliverySettingsProps {
  onClose?: () => void;
  embedded?: boolean;
  betaEnabled?: boolean;
}

interface ApiSettingsResponse {
  settings: Partial<CachingSettings>;
  performance_conflicts?: {
    count?: number;
    plugins?: string[];
    safe_mode_enabled?: boolean;
  };
}

interface ApiClearResponse {
  cleared: number;
}

interface ApiNginxConfigResponse {
  success?: boolean;
  config?: string;
  cache_path?: string;
}

interface CacheStats {
  hit_rate?: number;
  miss_rate?: number;
  hits?: number;
  misses?: number;
  total_cached?: number;
  cached_files?: number;
  cache_size?: string;
  bytes_saved?: number;
  bandwidth_saved?: string;
  avg_response_time?: string | number;
  edge_locations?: number;
  compression_ratio?: string | number;
  cache_efficiency?: string | number;
  real_time_status?: string;
}

interface SafeModeApplyResponse {
  safe_mode?: {
    enabled?: boolean;
    conflicts?: string[];
    applied?: boolean;
    message?: string;
  };
}

interface JsDeferInlineDependencyViolation {
  label?: string;
  reason?: string;
  snippet?: string;
  src?: string;
  href?: string;
}

interface JsDeferPreflightSample {
  label?: string;
  url?: string;
  passed?: boolean;
  blocking_findings?: string[];
  warnings?: string[];
  inline_jquery_examples?: string[];
  inline_dependency_violations?: JsDeferInlineDependencyViolation[];
  critical_styles_stripped?: JsDeferInlineDependencyViolation[];
}

interface JsDeferPreflightBlock {
  message?: string;
  title?: string;
  ackKey?: string;
  preflight?: {
    flag?: string;
    label?: string;
    blocking_findings?: string[];
    warnings?: string[];
    inline_jquery_examples?: string[];
    inline_dependency_violations?: JsDeferInlineDependencyViolation[];
    critical_styles_stripped?: JsDeferInlineDependencyViolation[];
    samples?: JsDeferPreflightSample[];
    sample_urls?: Array<{ label?: string; url?: string }>;
    url?: string;
  };
  pendingSettings: Record<string, unknown>;
}

const CachingDeliverySettings: React.FC<CachingDeliverySettingsProps> = ({ 
  onClose, 
  embedded = false,
  betaEnabled = false 
}) => {
  const { showNotification } = useNotification();
  const nginxInfo = (window as any)?.prorankSeoAdmin?.server?.nginx ?? {};
  const litespeedInfo = (window as any)?.prorankSeoAdmin?.server?.litespeed ?? {};
  const litespeedMessage = litespeedInfo.cache_plugin
    ? __('LiteSpeed Cache detected. ProRank will purge LSCache automatically on content updates.', 'prorank-seo')
    : litespeedInfo.server
      ? __('LiteSpeed server detected. ProRank is compatible and can purge LSCache when active.', 'prorank-seo')
      : __('LiteSpeed compatible. If you use LiteSpeed Cache, ProRank can purge it on content updates.', 'prorank-seo');
  const litespeedTone = litespeedInfo.cache_plugin || litespeedInfo.server
    ? 'prorank-notice prorank-notice-success'
    : 'prorank-notice prorank-notice-info';
  
  const [settings, setSettings] = useState<CachingSettings>({
    // Page Cache (short keys match settings manager)
    enabled: false,
    lifetime: 604800,
    exclude_urls: '',
    cache_exclude_categories: [],
    cache_exclude_tags: [],
    cache_exclude_post_types: [],

    // CDN
    cdn_provider: 'none',
    cloudflare_zone_id: '',
    cloudflare_api_token: '',
    bunny_pullzone_id: '',
    bunny_api_key: '',
    fastly_service_id: '',
    fastly_api_token: '',
    cdn_webhook_url: '',
    cdn_webhook_secret: '',
    cloudfront_distribution_id: '',
    cloudfront_access_key: '',
    cloudfront_secret_key: '',
    cdn_clear_on_purge_all: false,
    keycdn_zone_id: '',
    keycdn_api_key: '',

    // Cache Warming + adaptive throttle
    preload_enabled: false,
    preload_load_throttle_enabled: false,
    preload_max_load_average: 4,
    preload_batch_delay: 45,

    // WooCommerce cache safety
    woocommerce_safe_cache_enabled: true,

    // Link Preloading
    link_preload_enabled: false,
    link_preload_delay: 50,
    
    // DNS Prefetch
    dns_prefetch_enabled: false,
    dns_prefetch_hosts: '',
    dynamic_resource_hints_enabled: true,
    
    // Font Preloading
    font_preload_enabled: false,
    font_preload_urls: '',
    
    // Browser Cache
    browser_cache_enabled: false,
    browser_cache_images: '31536000',
    browser_cache_css: '31536000',
    browser_cache_js: '31536000',
    browser_cache_fonts: '31536000',
    browser_cache_html: '3600',
    
    // JS Optimization
    js_defer: false,
    js_delay: false,
    tracker_delay_enabled: true,
    js_delay_jquery: false,
    js_delay_elementor_modules: false,
    js_exclude: '',
    
    // CSS Optimization
    css_minify: false,
    css_combine: false,
    css_async: false,
    inline_css_minify_enabled: true,
    inline_css_relocate_enabled: true,
    css_exclude: '',
    performance_conflict_safe_mode: true,
  });

  const [loading, setLoading] = useState<boolean>(true);
  const [saving, setSaving] = useState<boolean>(false);
  const [clearing, setClearing] = useState<boolean>(false);
  const [cdnTesting, setCdnTesting] = useState<boolean>(false);
  const [cdnChecking, setCdnChecking] = useState<boolean>(false);
  const [cdnPurging, setCdnPurging] = useState<boolean>(false);
  const [cdnStatus, setCdnStatus] = useState<any>(null);
  const [cdnSetup, setCdnSetup] = useState<any>(null);
  const [cfZoneDetecting, setCfZoneDetecting] = useState<boolean>(false);
  const [cfDevMode, setCfDevMode] = useState<{ enabled: boolean; time_remaining: number } | null>(null);
  const [cfDevModeBusy, setCfDevModeBusy] = useState<boolean>(false);
  const [applyingPreset, setApplyingPreset] = useState<string | null>(null);
  const [cacheStats, setCacheStats] = useState<CacheStats | null>(null);
  const [statsLoading, setStatsLoading] = useState<boolean>(false);
  const [statsError, setStatsError] = useState<string | null>(null);
  const [performanceConflicts, setPerformanceConflicts] = useState<string[]>([]);
  const [applyingSafeMode, setApplyingSafeMode] = useState<boolean>(false);
  const [nginxConfig, setNginxConfig] = useState<string>('');
  const [nginxCachePath, setNginxCachePath] = useState<string>('');
  const [nginxConfigLoading, setNginxConfigLoading] = useState<boolean>(false);
  const [nginxConfigError, setNginxConfigError] = useState<string | null>(null);
  const [jsDeferPreflightBlock, setJsDeferPreflightBlock] = useState<JsDeferPreflightBlock | null>(null);

  const loadNginxConfig = useCallback(async (notify = false) => {
    if (!nginxInfo.server) {
      setNginxConfig('');
      setNginxCachePath('');
      setNginxConfigError(null);
      return;
    }

    setNginxConfigLoading(true);
    setNginxConfigError(null);

    try {
      const response = await apiFetch<ApiNginxConfigResponse>({
        path: '/prorank-seo/v1/performance/nginx-config',
      });

      setNginxConfig(response?.config || '');
      setNginxCachePath(response?.cache_path || '');

      if (notify) {
        showNotification(__('Nginx snippet refreshed', 'prorank-seo'), 'success');
      }
    } catch (error: any) {
      const message = error?.message || __('Failed to load Nginx snippet', 'prorank-seo');
      setNginxConfig('');
      setNginxCachePath('');
      setNginxConfigError(message);

      if (notify) {
        showNotification(message, 'error');
      }
    } finally {
      setNginxConfigLoading(false);
    }
  }, [nginxInfo.server, showNotification]);

  const loadSettings = useCallback(async () => {
    setLoading(true);
    try {
      const response = await apiFetch<ApiSettingsResponse>({
        path: '/prorank-seo/v1/performance/cache-settings',
      });
      if (response?.settings) {
        // Map backend keys (cache_enabled) to frontend keys (enabled)
        const apiSettings = response.settings as any;
        const mappedSettings: Partial<CachingSettings> = {
          ...response.settings,
          // Map cache-prefixed keys to short keys
          enabled: apiSettings.cache_enabled ?? apiSettings.enabled ?? false,
          lifetime: apiSettings.cache_lifetime ?? apiSettings.lifetime ?? 604800,
          exclude_urls: apiSettings.cache_exclude_urls ?? apiSettings.exclude_urls ?? '',
          performance_conflict_safe_mode:
            apiSettings.performance_conflict_safe_mode ?? response.performance_conflicts?.safe_mode_enabled ?? true,
        };
        setSettings(prev => {
          const newSettings = { ...prev, ...mappedSettings };
          return newSettings;
        });
      }
      setPerformanceConflicts(response?.performance_conflicts?.plugins || []);
    } catch (error) {
      console.error('[CachingDelivery] Failed to load cache settings:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  const loadCacheStats = useCallback(async () => {
    setStatsLoading(true);
    setStatsError(null);
    try {
      const response = await apiFetch<CacheStats>({
        path: '/prorank-seo/v1/cache/stats',
      });
      const hits = Number((response as any)?.hits ?? 0);
      const misses = Number((response as any)?.misses ?? 0);
      const derivedHitRate = (hits + misses) > 0
        ? Math.round((hits / (hits + misses)) * 10000) / 100
        : undefined;
      const normalized: CacheStats = {
        ...response,
        hit_rate: derivedHitRate ?? response?.hit_rate,
        miss_rate: derivedHitRate !== undefined ? Math.round((100 - derivedHitRate) * 100) / 100 : response?.miss_rate,
        total_cached: typeof response?.total_cached === 'number'
          ? response.total_cached
          : Number((response as any)?.cached_files ?? 0),
        bandwidth_saved: response?.bandwidth_saved
          || (typeof (response as any)?.bytes_saved === 'number'
            ? `${(response as any).bytes_saved} B`
            : undefined),
      };
      setCacheStats(normalized);
    } catch (error: any) {
      setStatsError(error?.message || __('Failed to load cache stats', 'prorank-seo'));
    } finally {
      setStatsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadSettings();
    loadCacheStats();
    loadNginxConfig();
  }, [loadSettings, loadCacheStats, loadNginxConfig]);

  const buildBackendSettings = (ackJsDeferPreflight = false): Record<string, unknown> => ({
    ...settings,
    cache_enabled: settings.enabled,
    cache_lifetime: settings.lifetime,
    cache_exclude_urls: settings.exclude_urls,
    ...(ackJsDeferPreflight ? { js_defer_preflight_ack: true } : {}),
  });

  const handleSaveSuccess = async (response: SafeModeApplyResponse) => {
    if (response?.safe_mode?.conflicts) {
      setPerformanceConflicts(response.safe_mode.conflicts);
    }
    if (response?.safe_mode?.applied) {
      showNotification(response?.safe_mode?.message || __('Settings saved and conflict safe mode applied', 'prorank-seo'), 'warning');
    } else {
      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
    }

    await loadNginxConfig();
  };

  const getPreflightErrorCode = (error: any): string => {
    const code = String(error?.error || error?.code || '');
    return ['js_defer_preflight_failed', 'js_delay_preflight_failed', 'unused_css_preflight_failed'].includes(code)
      ? code
      : '';
  };

  const getPreflightAckKey = (code: string): string => {
    if (code === 'js_delay_preflight_failed') {
      return 'js_delay_preflight_ack';
    }
    if (code === 'unused_css_preflight_failed') {
      return 'unused_css_preflight_ack';
    }
    return 'js_defer_preflight_ack';
  };

  const saveSettings = async () => {
    setSaving(true);
    
    // Validate CDN settings
    if (settings.cdn_provider === 'cloudflare' && (!settings.cloudflare_zone_id || !settings.cloudflare_api_token)) {
      showNotification(__('Please provide Cloudflare credentials', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }
    
    if (settings.cdn_provider === 'bunnycdn' && (!settings.bunny_pullzone_id || !settings.bunny_api_key)) {
      showNotification(__('Please provide BunnyCDN credentials', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }

    if (settings.cdn_provider === 'fastly' && (!settings.fastly_service_id || !settings.fastly_api_token)) {
      showNotification(__('Please provide Fastly Service ID and API token', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }

    if (settings.cdn_provider === 'webhook' && !settings.cdn_webhook_url) {
      showNotification(__('Please provide a webhook URL', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }

    if (settings.cdn_provider === 'cloudfront' && (!settings.cloudfront_distribution_id || !settings.cloudfront_access_key || !settings.cloudfront_secret_key)) {
      showNotification(__('Please provide CloudFront distribution ID and access keys', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }

    if (settings.cdn_provider === 'keycdn' && (!settings.keycdn_zone_id || !settings.keycdn_api_key)) {
      showNotification(__('Please provide KeyCDN Zone ID and API key', 'prorank-seo'), 'warning');
      setSaving(false);
      return;
    }
    
    try {
      const backendSettings = buildBackendSettings(false);
      const response = await apiFetch<SafeModeApplyResponse>({
        path: '/prorank-seo/v1/performance/cache-settings',
        method: 'POST',
        data: { settings: backendSettings },
      });
      await handleSaveSuccess(response);
    } catch (error: any) {
      const preflightCode = getPreflightErrorCode(error);
      if (preflightCode) {
        const preflightLabel = error?.preflight?.label || __('Performance setting', 'prorank-seo');
        setJsDeferPreflightBlock({
          message: error?.message,
          title: sprintf(
            /* translators: %s: performance feature label */
            __('%s preflight failed', 'prorank-seo'),
            preflightLabel
          ),
          ackKey: getPreflightAckKey(preflightCode),
          preflight: error?.preflight,
          pendingSettings: buildBackendSettings(false),
        });
        showNotification(sprintf(
          /* translators: %s: performance feature label */
          __('%s was not enabled. Review the preflight warning.', 'prorank-seo'),
          preflightLabel
        ), 'warning');
        return;
      }

      showNotification(error.message || __('Failed to save settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const enableJsDeferAnyway = async () => {
    if (!jsDeferPreflightBlock) {
      return;
    }

    setSaving(true);
    try {
      const response = await apiFetch<SafeModeApplyResponse>({
        path: '/prorank-seo/v1/performance/cache-settings',
        method: 'POST',
        data: {
          settings: {
            ...jsDeferPreflightBlock.pendingSettings,
            [jsDeferPreflightBlock.ackKey || 'js_defer_preflight_ack']: true,
          },
        },
      });

      setJsDeferPreflightBlock(null);
      await handleSaveSuccess(response);
    } catch (error: any) {
      showNotification(error?.message || __('Failed to enable JS defer', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const testCdn = async () => {
    if (settings.cdn_provider === 'none') {
      showNotification(__('Select a CDN provider to test credentials', 'prorank-seo'), 'warning');
      return;
    }
    setCdnTesting(true);
    try {
      const response = await apiFetch<any>({
        path: '/prorank-seo/v1/cdn/test',
        method: 'POST',
        data: {
          settings: {
            cdn_provider: settings.cdn_provider,
            cloudflare_zone_id: settings.cloudflare_zone_id,
            cloudflare_api_token: settings.cloudflare_api_token,
            bunny_pullzone_id: settings.bunny_pullzone_id,
            bunny_api_key: settings.bunny_api_key,
            fastly_service_id: settings.fastly_service_id,
            fastly_api_token: settings.fastly_api_token,
            cloudfront_distribution_id: settings.cloudfront_distribution_id,
            cloudfront_access_key: settings.cloudfront_access_key,
            cloudfront_secret_key: settings.cloudfront_secret_key,
            keycdn_zone_id: settings.keycdn_zone_id,
            keycdn_api_key: settings.keycdn_api_key,
            cdn_webhook_url: settings.cdn_webhook_url,
            cdn_webhook_secret: settings.cdn_webhook_secret,
          },
        },
      });
      setCdnStatus(response);
      showNotification(__('CDN credentials verified', 'prorank-seo'), 'success');
    } catch (error: any) {
      setCdnStatus({ error: error?.message || __('CDN test failed', 'prorank-seo') });
      showNotification(error?.message || __('CDN test failed', 'prorank-seo'), 'error');
    } finally {
      setCdnTesting(false);
    }
  };

  const checkCdnSetup = async () => {
    setCdnChecking(true);
    try {
      const response = await apiFetch<any>({
        path: '/prorank-seo/v1/cdn-setup/check',
      });
      setCdnSetup(response?.summary || response);
      showNotification(__('Edge/CDN header check completed', 'prorank-seo'), 'success');
    } catch (error: any) {
      setCdnSetup({ error: error?.message || __('Edge/CDN header check failed', 'prorank-seo') });
      showNotification(error?.message || __('Edge/CDN header check failed', 'prorank-seo'), 'error');
    } finally {
      setCdnChecking(false);
    }
  };

  const purgeCdnCache = async () => {
    if (settings.cdn_provider === 'none') {
      showNotification(__('Select a CDN provider before purging', 'prorank-seo'), 'warning');
      return;
    }
    setCdnPurging(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/cdn/purge',
        method: 'POST',
      });
      showNotification(__('CDN cache purged', 'prorank-seo'), 'success');
    } catch (error: any) {
      showNotification(error?.message || __('Failed to purge CDN cache', 'prorank-seo'), 'error');
    } finally {
      setCdnPurging(false);
    }
  };

  const detectCloudflareZone = async () => {
    if (!settings.cloudflare_api_token) {
      showNotification(__('Enter your Cloudflare API token first', 'prorank-seo'), 'warning');
      return;
    }
    setCfZoneDetecting(true);
    try {
      const response = await apiFetch<{ success: boolean; result?: { zone_id: string; name: string } }>({
        path: '/prorank-seo/v1/cdn/cloudflare/detect-zone',
        method: 'POST',
        data: { api_token: settings.cloudflare_api_token },
      });
      const zone = response?.result;
      if (zone?.zone_id) {
        updateSetting('cloudflare_zone_id', zone.zone_id);
        showNotification(
          __('Cloudflare zone detected: ', 'prorank-seo') + (zone.name || zone.zone_id),
          'success'
        );
      } else {
        showNotification(__('No Cloudflare zone matched this domain', 'prorank-seo'), 'warning');
      }
    } catch (error: any) {
      showNotification(error?.message || __('Cloudflare zone detection failed', 'prorank-seo'), 'error');
    } finally {
      setCfZoneDetecting(false);
    }
  };

  const refreshCloudflareDevMode = useCallback(async () => {
    if (settings.cdn_provider !== 'cloudflare' || !settings.cloudflare_zone_id || !settings.cloudflare_api_token) {
      setCfDevMode(null);
      return;
    }
    try {
      const response = await apiFetch<{ success: boolean; result?: { enabled: boolean; time_remaining: number } }>({
        path: '/prorank-seo/v1/cdn/cloudflare/dev-mode',
      });
      if (response?.result) {
        setCfDevMode(response.result);
      }
    } catch {
      setCfDevMode(null);
    }
  }, [settings.cdn_provider, settings.cloudflare_zone_id, settings.cloudflare_api_token]);

  useEffect(() => {
    refreshCloudflareDevMode();
  }, [refreshCloudflareDevMode]);

  const toggleCloudflareDevMode = async (enabled: boolean) => {
    setCfDevModeBusy(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/cdn/cloudflare/dev-mode',
        method: 'POST',
        data: { enabled },
      });
      showNotification(
        enabled
          ? __('Cloudflare development mode enabled (3 hours)', 'prorank-seo')
          : __('Cloudflare development mode disabled', 'prorank-seo'),
        'success'
      );
      await refreshCloudflareDevMode();
    } catch (error: any) {
      showNotification(error?.message || __('Failed to toggle Cloudflare dev mode', 'prorank-seo'), 'error');
    } finally {
      setCfDevModeBusy(false);
    }
  };

  const clearCache = async () => {
    if (!window.confirm(__('Clear all cached pages?', 'prorank-seo'))) {
      return;
    }
    
    setClearing(true);
    try {
      const response = await apiFetch<ApiClearResponse>({
        path: '/prorank-seo/v1/cache/clear',
        method: 'POST',
      });
      showNotification(
        (response as any)?.message || __('All cache cleared successfully', 'prorank-seo'),
        'success'
      );
    } catch (error: any) {
      showNotification(error.message || __('Failed to clear cache', 'prorank-seo'), 'error');
    } finally {
      setClearing(false);
    }
  };

  const listToTextarea = (value?: string[]): string => Array.isArray(value) ? value.join('\n') : '';
  const textareaToList = (value: string): string[] => value
    .split(/[\r\n,]+/)
    .map((item) => item.trim())
    .filter(Boolean);

  const applyPerformancePreset = async (name: string, label: string) => {
    if (!window.confirm(sprintf(__('Apply the %s preset? This updates cache, asset, and image optimisation settings.', 'prorank-seo'), label))) {
      return;
    }

    setApplyingPreset(name);
    try {
      const response = await apiFetch<{ message?: string }>({
        path: '/prorank-seo/v1/performance/presets/apply',
        method: 'POST',
        data: { name },
      });
      showNotification(response?.message || sprintf(__('%s preset applied', 'prorank-seo'), label), 'success');
      await loadSettings();
      await loadCacheStats();
      await loadNginxConfig();
    } catch (error: any) {
      showNotification(error?.message || __('Failed to apply performance preset', 'prorank-seo'), 'error');
    } finally {
      setApplyingPreset(null);
    }
  };

  const applyConflictSafeModeNow = async () => {
    setApplyingSafeMode(true);
    try {
      const response = await apiFetch<SafeModeApplyResponse>({
        path: '/prorank-seo/v1/performance/conflict-safe-mode/apply',
        method: 'POST',
        data: { enabled: settings.performance_conflict_safe_mode },
      });

      if (response?.safe_mode?.conflicts) {
        setPerformanceConflicts(response.safe_mode.conflicts);
      }

      showNotification(
        response?.safe_mode?.message || __('Conflict safe mode processed', 'prorank-seo'),
        response?.safe_mode?.applied ? 'warning' : 'success'
      );
      await loadSettings();
    } catch (error: any) {
      showNotification(error?.message || __('Failed to apply conflict safe mode', 'prorank-seo'), 'error');
    } finally {
      setApplyingSafeMode(false);
    }
  };

  const copyNginxConfig = async () => {
    if (!nginxConfig) {
      return;
    }

    try {
      if (!window?.navigator?.clipboard) {
        throw new Error(__('Clipboard access is not available in this browser', 'prorank-seo'));
      }

      await window.navigator.clipboard.writeText(nginxConfig);
      showNotification(__('Nginx snippet copied', 'prorank-seo'), 'success');
    } catch (error: any) {
      showNotification(error?.message || __('Failed to copy Nginx snippet', 'prorank-seo'), 'error');
    }
  };

  // Helper function to update settings
  const updateSetting = <K extends keyof CachingSettings>(key: K, value: CachingSettings[K]) => {
    setSettings(prev => {
      return { ...prev, [key]: value };
    });
  };

  const formatPercent = (value?: number) => {
    if (value === 0) {
      return '0%';
    }
    if (typeof value !== 'number') {
      return '—';
    }
    return `${Math.round(value)}%`;
  };

  const formatValue = (value?: number | string, suffix?: string) => {
    if (value === 0) {
      return suffix ? `0${suffix}` : '0';
    }
    if (!value) {
      return '—';
    }
    return suffix ? `${value}${suffix}` : String(value);
  };

  if (loading) {
    return (
      <div className="prorank-performance-container prorank-caching-delivery-settings">
        <div className="prorank-flex-center" style={{ padding: '50px' }}>
          <Spinner />
          <p>{__('Loading caching settings...', 'prorank-seo')}</p>
        </div>
      </div>
    );
  }

  const hitRate = typeof cacheStats?.hit_rate === 'number' ? cacheStats?.hit_rate : undefined;
  const avgResponse = typeof cacheStats?.avg_response_time === 'number'
    ? `${cacheStats?.avg_response_time}ms`
    : (cacheStats?.avg_response_time || '—');
  const totalCached = typeof cacheStats?.total_cached === 'number' ? cacheStats.total_cached : 0;
  const showCacheStatsHelp = !statsLoading && !statsError && totalCached === 0;
  const preflightSamples = jsDeferPreflightBlock?.preflight?.samples || [];
  const performancePresets = [
    {
      name: 'standard',
      label: __('Standard', 'prorank-seo'),
      description: __('Safe default for most sites: page cache, DNS prefetch, lazy loading, and WebP.', 'prorank-seo'),
    },
    {
      name: 'aggressive',
      label: __('Aggressive', 'prorank-seo'),
      description: __('Maximum optimisation: defer/delay JavaScript, CSS minify/combine, HTML minify, and AVIF.', 'prorank-seo'),
    },
    {
      name: 'ecommerce',
      label: __('E-commerce', 'prorank-seo'),
      description: __('WooCommerce-safe profile with cache variants on and risky JavaScript delays off.', 'prorank-seo'),
    },
  ];

  return (
    <div className="prorank-performance-container prorank-caching-delivery-settings">
      {jsDeferPreflightBlock && (
        <Modal
          title={jsDeferPreflightBlock.title || __('Performance preflight failed', 'prorank-seo')}
          onRequestClose={() => setJsDeferPreflightBlock(null)}
          className="prorank-js-defer-preflight-modal"
        >
          <p>
            {jsDeferPreflightBlock.message || __('ProRank did not enable this setting because frontend checks found a possible menu, runtime, or layout break.', 'prorank-seo')}
          </p>

          {preflightSamples.length > 0 && (
            <>
              <strong>{__('Checked URLs', 'prorank-seo')}</strong>
              <div className="prorank-preflight-samples">
                {preflightSamples.map((sample, index) => {
                  const findings = sample.blocking_findings || [];
                  return (
                    <div key={`preflight-sample-${index}`} className="prorank-preflight-sample">
                      <p>
                        <strong>{sample.label || sample.url || __('Frontend URL', 'prorank-seo')}</strong>
                        {sample.url ? <><br /><code>{sample.url}</code></> : null}
                      </p>
                      {findings.length > 0 ? (
                        <ul>
                          {findings.map((finding, findingIndex) => (
                            <li key={`preflight-sample-${index}-finding-${findingIndex}`}>{finding}</li>
                          ))}
                        </ul>
                      ) : (
                        <p>{__('Passed', 'prorank-seo')}</p>
                      )}
                    </div>
                  );
                })}
              </div>
            </>
          )}

          {preflightSamples.length === 0 && (jsDeferPreflightBlock.preflight?.blocking_findings || []).length > 0 && (
            <>
              <strong>{__('Blocking findings', 'prorank-seo')}</strong>
              <ul>
                {(jsDeferPreflightBlock.preflight?.blocking_findings || []).map((finding, index) => (
                  <li key={`finding-${index}`}>{finding}</li>
                ))}
              </ul>
            </>
          )}

          {(jsDeferPreflightBlock.preflight?.inline_jquery_examples || []).length > 0 && (
            <>
              <strong>{__('Example inline scripts', 'prorank-seo')}</strong>
              <ul>
                {(jsDeferPreflightBlock.preflight?.inline_jquery_examples || []).map((snippet, index) => (
                  <li key={`snippet-${index}`}><code>{snippet}</code></li>
                ))}
              </ul>
            </>
          )}

          {(jsDeferPreflightBlock.preflight?.inline_dependency_violations || []).length > 0 && (
            <>
              <strong>{__('Runtime dependency examples', 'prorank-seo')}</strong>
              <ul>
                {(jsDeferPreflightBlock.preflight?.inline_dependency_violations || []).map((violation, index) => (
                  <li key={`runtime-dependency-${index}`}>
                    <strong>{violation.label || __('Runtime provider', 'prorank-seo')}</strong>
                    {violation.reason ? ` (${violation.reason})` : ''}
                    {violation.snippet ? <><br /><code>{violation.snippet}</code></> : null}
                  </li>
                ))}
              </ul>
            </>
          )}

          {(jsDeferPreflightBlock.preflight?.critical_styles_stripped || []).length > 0 && (
            <>
              <strong>{__('Protected stylesheet examples', 'prorank-seo')}</strong>
              <ul>
                {(jsDeferPreflightBlock.preflight?.critical_styles_stripped || []).map((style, index) => (
                  <li key={`critical-style-${index}`}>
                    <strong>{style.label || __('Stylesheet', 'prorank-seo')}</strong>
                    {style.reason ? ` (${style.reason})` : ''}
                    {style.href || style.src ? <><br /><code>{style.href || style.src}</code></> : null}
                  </li>
                ))}
              </ul>
            </>
          )}

          <Notice status="warning" isDismissible={false}>
            {__('Recommended: fix the listed dependency issue, then try again. Only enable anyway if you have manually tested the menu, checkout, booking, and key interactions.', 'prorank-seo')}
          </Notice>

          <div className="prorank-actions" style={{ justifyContent: 'flex-end', marginTop: '16px' }}>
            <Button variant="secondary" onClick={() => setJsDeferPreflightBlock(null)}>
              {__('Fix and try again', 'prorank-seo')}
            </Button>
            <Button variant="primary" onClick={enableJsDeferAnyway} disabled={saving}>
              {saving ? __('Enabling...', 'prorank-seo') : __('Enable anyway', 'prorank-seo')}
            </Button>
          </div>
        </Modal>
      )}

      {/* Performance Conflict Safe Mode */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-shield"></span>
            {__('Performance Conflict Safe Mode', 'prorank-seo')}
          </h3>
          <div className={`prorank-badge ${settings.performance_conflict_safe_mode ? 'prorank-badge-success' : 'prorank-badge-error'}`}>
            {settings.performance_conflict_safe_mode ? __('Enabled', 'prorank-seo') : __('Disabled', 'prorank-seo')}
          </div>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Auto-disable overlapping optimizations', 'prorank-seo')}</strong>
              <span>{__('Automatically turns off overlapping ProRank runtime features when other performance plugins are active.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.performance_conflict_safe_mode}
              onChange={(value) => updateSetting('performance_conflict_safe_mode', value)}
              label=""
            />
          </div>

          {performanceConflicts.length > 0 ? (
            <>
              <Notice status="warning" isDismissible={false}>
                {sprintf(
                  /* translators: %d: number of active plugin conflicts */
                  __('Detected %d active optimization plugins that may conflict with ProRank.', 'prorank-seo'),
                  performanceConflicts.length
                )}
                <div style={{ marginTop: '6px' }}>
                  {performanceConflicts.join(', ')}
                </div>
              </Notice>
              <Notice status="info" isDismissible={false}>
                {__('Keep only one tool responsible for page cache, CSS delivery, JavaScript delay, lazy loading, and HTML minification. After changing performance stacks, retest builder/template pages before leaving the setup in production.', 'prorank-seo')}
              </Notice>
            </>
          ) : (
            <Notice status="success" isDismissible={false}>
              {__('No active performance plugin conflicts detected.', 'prorank-seo')}
            </Notice>
          )}

          {settings.performance_conflict_safe_mode && performanceConflicts.length > 0 && (
            <div className="prorank-actions" style={{ marginTop: '12px' }}>
              <ProrankButton
                variant="secondary"
                onClick={applyConflictSafeModeNow}
                disabled={applyingSafeMode}
              >
                {applyingSafeMode ? __('Applying...', 'prorank-seo') : __('Apply Safe Mode Now', 'prorank-seo')}
              </ProrankButton>
            </div>
          )}
        </div>
      </div>

      {/* Performance Presets */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-controls-repeat"></span>
            {__('Performance Presets', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="pr:grid pr:grid-cols-1 pr:gap-4 pr:lg:grid-cols-3">
            {performancePresets.map((preset) => (
              <div
                key={preset.name}
                className="pr:flex pr:min-h-[180px] pr:flex-col pr:justify-between pr:rounded-xl pr:border pr:border-gray-200 pr:bg-white pr:p-5 pr:shadow-xs"
              >
                <div>
                  <h4 className="pr:m-0 pr:text-lg pr:font-semibold pr:leading-7 pr:text-gray-900">{preset.label}</h4>
                  <p className="pr:mt-2 pr:m-0 pr:text-sm pr:leading-6 pr:text-gray-600">{preset.description}</p>
                </div>
                <div className="pr:mt-5 pr:flex pr:justify-end">
                  <ProrankButton
                    variant="secondary"
                    className="pr:whitespace-nowrap"
                    onClick={() => applyPerformancePreset(preset.name, preset.label)}
                    disabled={!!applyingPreset}
                  >
                    {applyingPreset === preset.name ? __('Applying...', 'prorank-seo') : __('Apply Preset', 'prorank-seo')}
                  </ProrankButton>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Cache Insights Card */}
      <div className="prorank-card prorank-stats-dashboard">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-chart-area"></span>
            {__('Cache Insights', 'prorank-seo')}
          </h3>
          <ProrankButton
            variant="secondary"
            onClick={loadCacheStats}
            disabled={statsLoading}
          >
            {statsLoading ? __('Refreshing...', 'prorank-seo') : __('Refresh Stats', 'prorank-seo')}
          </ProrankButton>
        </div>
        <div className="prorank-card-body">
          {statsError && (
            <Notice status="error" isDismissible={false}>
              {statsError}
            </Notice>
          )}

          {!statsError && (
            <>
              {statsLoading ? (
                <div className="prorank-flex-center" style={{ padding: '20px' }}>
                  <Spinner />
                  <p>{__('Loading cache stats...', 'prorank-seo')}</p>
                </div>
              ) : (
                <>
                  {showCacheStatsHelp && (
                    <div className="prorank-notice prorank-notice-info" style={{ marginBottom: '16px' }}>
                      {__(
                        'Cache stats appear after logged-out visits. Open your site in an incognito window, browse a few pages, then refresh stats.',
                        'prorank-seo'
                      )}
                    </div>
                  )}
                  <div className="prorank-stats-grid">
                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-chart-line"></span>
                      </div>
                      <div className="prorank-stat-value">{formatPercent(hitRate)}</div>
                      <div className="prorank-stat-label">{__('Hit Rate', 'prorank-seo')}</div>
                      <div className="prorank-stat-gauge">
                        <div
                          className="prorank-stat-gauge-fill"
                          style={{ width: `${Math.min(hitRate || 0, 100)}%` }}
                        />
                      </div>
                    </div>

                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-database"></span>
                      </div>
                      <div className="prorank-stat-value">{formatValue(cacheStats?.total_cached)}</div>
                      <div className="prorank-stat-label">{__('Cached Pages', 'prorank-seo')}</div>
                    </div>

                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-media-archive"></span>
                      </div>
                      <div className="prorank-stat-value">{formatValue(cacheStats?.cache_size)}</div>
                      <div className="prorank-stat-label">{__('Cache Size', 'prorank-seo')}</div>
                    </div>

                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-cloud"></span>
                      </div>
                      <div className="prorank-stat-value">{formatValue(cacheStats?.bandwidth_saved)}</div>
                      <div className="prorank-stat-label">{__('Bandwidth Saved', 'prorank-seo')}</div>
                    </div>

                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-clock"></span>
                      </div>
                      <div className="prorank-stat-value">{avgResponse}</div>
                      <div className="prorank-stat-label">{__('Avg Response', 'prorank-seo')}</div>
                    </div>

                    <div className="prorank-stat-card">
                      <div className="prorank-stat-icon">
                        <span className="dashicons dashicons-location"></span>
                      </div>
                      <div className="prorank-stat-value">{formatValue(cacheStats?.edge_locations)}</div>
                      <div className="prorank-stat-label">{__('Edge Locations', 'prorank-seo')}</div>
                    </div>
                  </div>
                </>
              )}
            </>
          )}
        </div>
      </div>

      {/* Page Cache Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-database"></span>
            {__('Page Cache', 'prorank-seo')}
          </h3>
          <div className={`prorank-badge ${settings.enabled ? 'prorank-badge-success' : 'prorank-badge-error'}`}>
            {settings.enabled ? __('Enabled', 'prorank-seo') : __('Disabled', 'prorank-seo')}
          </div>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Enable Page Cache', 'prorank-seo')}</strong>
              <span>{__('Cache static HTML files for faster loading', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.enabled}
              onChange={(value) => updateSetting('enabled', value)}
              label=""
            />
          </div>

          {settings.woocommerce_active ? (
            <>
              <div className="prorank-toggle-row">
                <div className="prorank-toggle-label">
                  <strong>{__('WooCommerce Safe Cache', 'prorank-seo')}</strong>
                  <span>{__('Never cache cart, checkout, my-account or order pages, and bypass the cache while a customer has an active cart/session. Recommended for all stores.', 'prorank-seo')}</span>
                </div>
                <ProrankToggleSlider
                  checked={settings.woocommerce_safe_cache_enabled !== false}
                  onChange={(value) => updateSetting('woocommerce_safe_cache_enabled', value)}
                  label=""
                />
              </div>
              {settings.woocommerce_safe_cache_enabled !== false && (
                <div className="prorank-notice prorank-notice-info" style={{ marginTop: '8px' }}>
                  <div>
                    <strong>{__('Active WooCommerce protections:', 'prorank-seo')}</strong>
                    <ul style={{ margin: '6px 0 0', paddingLeft: '18px' }}>
                      <li>{__('Cart, checkout, my-account & order pages bypass the cache', 'prorank-seo')}</li>
                      <li>{__('Cache bypassed while a cart / session cookie is present', 'prorank-seo')}</li>
                      <li>{__('Cart, checkout, wc-ajax & Store API URLs excluded from preloading', 'prorank-seo')}</li>
                      <li>{__('Cart fragments, checkout & payment-gateway scripts excluded from JS delay/defer/minify', 'prorank-seo')}</li>
                    </ul>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="prorank-toggle-row">
              <div className="prorank-toggle-label">
                <strong>{__('WooCommerce Safe Cache', 'prorank-seo')}</strong>
                <span>{__('Activate WooCommerce to protect cart, checkout, and account pages from caching.', 'prorank-seo')}</span>
              </div>
              <div className="prorank-badge prorank-badge-info">
                {__('WooCommerce not active', 'prorank-seo')}
              </div>
            </div>
          )}

          {settings.enabled && (
            <>
              <div className="prorank-control-group">
                <RangeControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Cache Lifetime', 'prorank-seo')}
                  value={settings.lifetime}
                  onChange={(value) => updateSetting('lifetime', value)}
                  min={60}
                  max={2592000}
                  step={60}
                  help={`${settings.lifetime} ${__('seconds', 'prorank-seo')}`}
                />
              </div>

              <div className="prorank-control-group">
                <TextareaControl
              __nextHasNoMarginBottom
                  label={__('Exclude URLs', 'prorank-seo')}
                  help={__('One URL pattern per line', 'prorank-seo')}
                  value={settings.exclude_urls}
                  onChange={(value) => updateSetting('exclude_urls', value)}
                  rows={4}
                  placeholder="/checkout/*&#10;/cart/*&#10;/my-account/*"
                />
              </div>

              <div className="prorank-control-group">
                <TextareaControl
                  __nextHasNoMarginBottom
                  label={__('Exclude Categories', 'prorank-seo')}
                  help={__('Category IDs or slugs, one per line. Matching posts will bypass page cache.', 'prorank-seo')}
                  value={listToTextarea(settings.cache_exclude_categories)}
                  onChange={(value) => updateSetting('cache_exclude_categories', textareaToList(value))}
                  rows={3}
                  placeholder="news&#10;123"
                />
              </div>

              <div className="prorank-control-group">
                <TextareaControl
                  __nextHasNoMarginBottom
                  label={__('Exclude Tags', 'prorank-seo')}
                  help={__('Tag IDs or slugs, one per line. Matching posts will bypass page cache.', 'prorank-seo')}
                  value={listToTextarea(settings.cache_exclude_tags)}
                  onChange={(value) => updateSetting('cache_exclude_tags', textareaToList(value))}
                  rows={3}
                  placeholder="uncached&#10;456"
                />
              </div>

              <div className="prorank-control-group">
                <TextareaControl
                  __nextHasNoMarginBottom
                  label={__('Exclude Post Types', 'prorank-seo')}
                  help={__('Post type slugs, one per line. Useful for events, bookings, or dynamic catalogue pages.', 'prorank-seo')}
                  value={listToTextarea(settings.cache_exclude_post_types)}
                  onChange={(value) => updateSetting('cache_exclude_post_types', textareaToList(value))}
                  rows={3}
                  placeholder="tribe_events&#10;product"
                />
              </div>

              <div className="prorank-actions">
                <ProrankButton
                  variant="secondary"
                  onClick={clearCache}
                  disabled={clearing}
                >
                  {clearing ? __('Clearing...', 'prorank-seo') : __('Clear Cache', 'prorank-seo')}
                </ProrankButton>
              </div>

              <div className="prorank-toggle-row">
                <div className="prorank-toggle-label">
                  <strong>{__('Cache Warming', 'prorank-seo')}</strong>
                  <span>{__('Keep core pages warm by re-priming the cache every 15 minutes after it is cleared.', 'prorank-seo')}</span>
                </div>
                <ProrankToggleSlider
                  checked={settings.preload_enabled}
                  onChange={(value) => updateSetting('preload_enabled', value)}
                  label=""
                />
              </div>

              {settings.preload_enabled && (
                <>
                  <div className="prorank-toggle-row">
                    <div className="prorank-toggle-label">
                      <strong>{__('Adaptive Load Throttle', 'prorank-seo')}</strong>
                      <span>{__('Skip cache warming while the server is under heavy load, then resume on the next cycle.', 'prorank-seo')}</span>
                    </div>
                    <ProrankToggleSlider
                      checked={settings.preload_load_throttle_enabled}
                      onChange={(value) => updateSetting('preload_load_throttle_enabled', value)}
                      label=""
                    />
                  </div>

                  {settings.preload_load_throttle_enabled && (
                    <>
                      <div className="prorank-control-group">
                        <RangeControl
                          __next40pxDefaultSize
                          __nextHasNoMarginBottom
                          label={__('Max Server Load Average', 'prorank-seo')}
                          value={settings.preload_max_load_average}
                          onChange={(value) => updateSetting('preload_max_load_average', value ?? 4)}
                          min={0.5}
                          max={32}
                          step={0.5}
                          help={__('Skip warming when the 1-minute load average exceeds this value.', 'prorank-seo')}
                        />
                      </div>

                      <div className="prorank-control-group">
                        <RangeControl
                          __next40pxDefaultSize
                          __nextHasNoMarginBottom
                          label={__('Batch Delay (seconds)', 'prorank-seo')}
                          value={settings.preload_batch_delay}
                          onChange={(value) => updateSetting('preload_batch_delay', value ?? 45)}
                          min={5}
                          max={600}
                          step={5}
                          help={__('Minimum wait before throttled warming is retried.', 'prorank-seo')}
                        />
                      </div>

                      <div className="prorank-notice prorank-notice-info">
                        <span className="dashicons dashicons-info"></span>
                        <div>
                          {settings.preload_throttle_supported === false
                            ? __('Server load monitoring is unavailable on this host, so throttling will not engage.', 'prorank-seo')
                            : (typeof settings.preload_current_load === 'number'
                                ? `${__('Active — current server load:', 'prorank-seo')} ${settings.preload_current_load.toFixed(2)}`
                                : __('Active — server load monitoring is available.', 'prorank-seo'))}
                        </div>
                      </div>
                    </>
                  )}
                </>
              )}
            </>
          )}
        </div>
      </div>

      {/* CDN Configuration Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-cloud"></span>
            {__('CDN Configuration', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-control-group">
            <SelectControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
              label={__('CDN Provider', 'prorank-seo')}
              value={settings.cdn_provider}
              options={[
                { label: __('No CDN', 'prorank-seo'), value: 'none' },
                { label: __('Cloudflare (Free/Paid)', 'prorank-seo'), value: 'cloudflare' },
                { label: __('BunnyCDN', 'prorank-seo'), value: 'bunnycdn' },
                { label: __('Fastly', 'prorank-seo'), value: 'fastly' },
                { label: __('CloudFront', 'prorank-seo'), value: 'cloudfront' },
                { label: __('KeyCDN', 'prorank-seo'), value: 'keycdn' },
                { label: __('Custom Webhook', 'prorank-seo'), value: 'webhook' },
              ]}
              onChange={(value: any) => updateSetting('cdn_provider', value)}
            />
          </div>

          {settings.cdn_provider === 'cloudflare' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Cloudflare Zone ID', 'prorank-seo')}
                  placeholder="32-character Zone ID"
                  value={settings.cloudflare_zone_id}
                  onChange={(value) => updateSetting('cloudflare_zone_id', value)}
                />
                <div style={{ marginTop: '8px' }}>
                  <Button
                    variant="secondary"
                    onClick={detectCloudflareZone}
                    disabled={cfZoneDetecting || !settings.cloudflare_api_token}
                  >
                    {cfZoneDetecting
                      ? __('Detecting zone…', 'prorank-seo')
                      : __('Auto-detect zone', 'prorank-seo')}
                  </Button>
                </div>
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  type="password"
                  label={__('API Token', 'prorank-seo')}
                  placeholder="API Token"
                  value={settings.cloudflare_api_token}
                  onChange={(value) => updateSetting('cloudflare_api_token', value)}
                />
              </div>

              {settings.cloudflare_zone_id && settings.cloudflare_api_token && (
                <div className="prorank-control-group prorank-control-row">
                  <div className="prorank-control-text">
                    <strong>{__('Cloudflare Development Mode', 'prorank-seo')}</strong>
                    <span>
                      {cfDevMode?.enabled
                        ? sprintf(
                            // translators: %d is the number of seconds remaining.
                            __('On — %d seconds remaining before automatic shutoff', 'prorank-seo'),
                            cfDevMode.time_remaining
                          )
                        : __('Bypass Cloudflare cache for 3 hours while you test changes', 'prorank-seo')}
                    </span>
                  </div>
                  <ProrankToggleSlider
                    checked={!!cfDevMode?.enabled}
                    onChange={(value) => toggleCloudflareDevMode(value)}
                    disabled={cfDevModeBusy}
                    label=""
                  />
                </div>
              )}

              <div className="prorank-control-group prorank-control-row">
                <div className="prorank-control-text">
                  <strong>{__('Clear Cloudflare when purging all', 'prorank-seo')}</strong>
                  <span>{__('Also purge the Cloudflare zone whenever ProRank clears all cached pages', 'prorank-seo')}</span>
                </div>
                <ProrankToggleSlider
                  checked={settings.cdn_clear_on_purge_all}
                  onChange={(value) => updateSetting('cdn_clear_on_purge_all', value)}
                  label=""
                />
              </div>
            </>
          )}

          {settings.cdn_provider === 'cloudfront' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Distribution ID', 'prorank-seo')}
                  placeholder="E123ABC..."
                  value={settings.cloudfront_distribution_id}
                  onChange={(value) => updateSetting('cloudfront_distribution_id', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Access Key', 'prorank-seo')}
                  placeholder="AWS Access Key"
                  value={settings.cloudfront_access_key}
                  onChange={(value) => updateSetting('cloudfront_access_key', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  type="password"
                  label={__('Secret Key', 'prorank-seo')}
                  placeholder="AWS Secret Key"
                  value={settings.cloudfront_secret_key}
                  onChange={(value) => updateSetting('cloudfront_secret_key', value)}
                />
              </div>
            </>
          )}

          {settings.cdn_provider === 'keycdn' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Zone ID', 'prorank-seo')}
                  placeholder="KeyCDN Zone ID"
                  value={settings.keycdn_zone_id}
                  onChange={(value) => updateSetting('keycdn_zone_id', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  type="password"
                  label={__('API Key', 'prorank-seo')}
                  placeholder="API Key"
                  value={settings.keycdn_api_key}
                  onChange={(value) => updateSetting('keycdn_api_key', value)}
                />
              </div>
            </>
          )}

          {settings.cdn_provider === 'bunnycdn' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Pull Zone ID', 'prorank-seo')}
                  placeholder="Pull Zone ID"
                  value={settings.bunny_pullzone_id}
                  onChange={(value) => updateSetting('bunny_pullzone_id', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  type="password"
                  label={__('API Key', 'prorank-seo')}
                  placeholder="API Key"
                  value={settings.bunny_api_key}
                  onChange={(value) => updateSetting('bunny_api_key', value)}
                />
              </div>
            </>
          )}

          {settings.cdn_provider === 'fastly' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Fastly Service ID', 'prorank-seo')}
                  placeholder="Service ID"
                  value={settings.fastly_service_id}
                  onChange={(value) => updateSetting('fastly_service_id', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  type="password"
                  label={__('Fastly API Token', 'prorank-seo')}
                  placeholder="API Token"
                  value={settings.fastly_api_token}
                  onChange={(value) => updateSetting('fastly_api_token', value)}
                />
              </div>
            </>
          )}

          {settings.cdn_provider === 'webhook' && (
            <>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Webhook URL', 'prorank-seo')}
                  placeholder="https://example.com/purge"
                  value={settings.cdn_webhook_url}
                  onChange={(value) => updateSetting('cdn_webhook_url', value)}
                />
              </div>
              <div className="prorank-control-group">
                <TextControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Webhook Secret (optional)', 'prorank-seo')}
                  placeholder="Shared secret header"
                  value={settings.cdn_webhook_secret}
                  onChange={(value) => updateSetting('cdn_webhook_secret', value)}
                />
              </div>
            </>
          )}
          <div className="prorank-actions" style={{ gap: 8, flexWrap: 'wrap' }}>
            <ProrankButton
              variant="secondary"
              onClick={testCdn}
              disabled={cdnTesting || settings.cdn_provider === 'none'}
            >
              {cdnTesting ? __('Testing…', 'prorank-seo') : __('Test Credentials', 'prorank-seo')}
            </ProrankButton>
            <ProrankButton
              variant="secondary"
              onClick={checkCdnSetup}
              disabled={cdnChecking}
            >
              {cdnChecking ? __('Checking…', 'prorank-seo') : __('Check Edge/CDN Headers', 'prorank-seo')}
            </ProrankButton>
            <ProrankButton
              variant="secondary"
              onClick={purgeCdnCache}
              disabled={cdnPurging || settings.cdn_provider === 'none'}
            >
              {cdnPurging ? __('Purging…', 'prorank-seo') : __('Purge CDN Cache', 'prorank-seo')}
            </ProrankButton>
          </div>

          {cdnStatus && (
            <Notice status={cdnStatus?.success ? 'success' : 'warning'} isDismissible={false}>
              {cdnStatus?.success
                ? __('CDN connected: ', 'prorank-seo') +
                  (cdnStatus?.result?.provider || settings.cdn_provider)
                : cdnStatus?.error || __('CDN test failed', 'prorank-seo')}
            </Notice>
          )}

          {cdnSetup && !cdnSetup?.error && (
            <div className="prorank-control-group">
              <h4>{__('Edge Cache Status', 'prorank-seo')}</h4>
              <div className="prorank-metrics-grid" style={{ gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))' }}>
                <div className="prorank-metric">
                  <strong>{__('Status', 'prorank-seo')}</strong>
                  <div>{cdnSetup.status || '—'}</div>
                </div>
                <div className="prorank-metric">
                  <strong>{__('Cache', 'prorank-seo')}</strong>
                  <div>{cdnSetup.cache_status || __('Unknown', 'prorank-seo')}</div>
                </div>
                <div className="prorank-metric">
                  <strong>{__('Server', 'prorank-seo')}</strong>
                  <div>{cdnSetup.server || '—'}</div>
                </div>
                <div className="prorank-metric">
                  <strong>{__('Brotli', 'prorank-seo')}</strong>
                  <div>{cdnSetup.brotli ? __('Yes', 'prorank-seo') : __('No', 'prorank-seo')}</div>
                </div>
                <div className="prorank-metric">
                  <strong>{__('HTTP/3', 'prorank-seo')}</strong>
                  <div>{cdnSetup.http3 ? __('Yes', 'prorank-seo') : __('No', 'prorank-seo')}</div>
                </div>
                <div className="prorank-metric">
                  <strong>{__('Edge timing (ms)', 'prorank-seo')}</strong>
                  <div>{cdnSetup.timing_ms ?? '—'}</div>
                </div>
              </div>
              {Array.isArray(cdnSetup.warnings) && cdnSetup.warnings.length > 0 && (
                <Notice status="warning" isDismissible={false}>
                  <ul style={{ margin: 0, paddingLeft: 18 }}>
                    {cdnSetup.warnings.map((w: string, idx: number) => (
                      <li key={idx}>{w}</li>
                    ))}
                  </ul>
                </Notice>
              )}
            </div>
          )}

          {cdnSetup?.error && (
            <Notice status="error" isDismissible={false}>
              {cdnSetup.error}
            </Notice>
          )}
        </div>
      </div>

      {/* Resource Preloading Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-performance"></span>
            {__('Resource Preloading', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Link Preloading', 'prorank-seo')}</strong>
              <span>{__('Prefetch links on hover for instant navigation', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.link_preload_enabled}
              onChange={(value) => updateSetting('link_preload_enabled', value)}
              label=""
            />
          </div>

          {settings.link_preload_enabled && (
            <div className="prorank-control-group">
              <RangeControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                label={__('Hover Delay (ms)', 'prorank-seo')}
                value={settings.link_preload_delay}
                onChange={(value) => updateSetting('link_preload_delay', value)}
                min={0}
                max={500}
                step={10}
              />
            </div>
          )}

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('DNS Prefetch', 'prorank-seo')}</strong>
              <span>{__('Resolve DNS for external domains early', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.dns_prefetch_enabled}
              onChange={(value) => updateSetting('dns_prefetch_enabled', value)}
              label=""
            />
          </div>

          {settings.dns_prefetch_enabled && (
            <div className="prorank-control-group">
              <TextareaControl
              __nextHasNoMarginBottom
                label={__('External Hosts', 'prorank-seo')}
                help={__('One domain per line', 'prorank-seo')}
                value={settings.dns_prefetch_hosts}
                onChange={(value) => updateSetting('dns_prefetch_hosts', value)}
                rows={4}
                placeholder="fonts.googleapis.com&#10;fonts.gstatic.com&#10;www.example-cdn.com"
              />
            </div>
          )}

          {settings.dns_prefetch_enabled && (
            <div className="prorank-toggle-row">
              <div className="prorank-toggle-label">
                <strong>{__('Auto-Discover Third-Party Origins', 'prorank-seo')}</strong>
                <span>{__('Let ProRank inspect final HTML and add a small preconnect budget for external origins discovered on the page.', 'prorank-seo')}</span>
              </div>
              <ProrankToggleSlider
                checked={settings.dynamic_resource_hints_enabled}
                onChange={(value) => updateSetting('dynamic_resource_hints_enabled', value)}
                label=""
              />
            </div>
          )}

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Font Preloading', 'prorank-seo')}</strong>
              <span>{__('Load critical fonts early to prevent flash', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.font_preload_enabled}
              onChange={(value) => updateSetting('font_preload_enabled', value)}
              label=""
            />
          </div>

          {settings.font_preload_enabled && (
            <div className="prorank-control-group">
              <TextareaControl
              __nextHasNoMarginBottom
                label={__('Font URLs', 'prorank-seo')}
                help={__('One font URL per line', 'prorank-seo')}
                value={settings.font_preload_urls}
                onChange={(value) => updateSetting('font_preload_urls', value)}
                rows={4}
              />
            </div>
          )}
        </div>
      </div>

      {/* Browser Cache Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-archive"></span>
            {__('Browser Cache', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Enable Browser Caching', 'prorank-seo')}</strong>
              <span>{__('Store resources in visitor browsers', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.browser_cache_enabled}
              onChange={(value) => updateSetting('browser_cache_enabled', value)}
              label=""
            />
          </div>
          {nginxInfo.server && (
            <div className="prorank-notice prorank-notice-warning" style={{ marginTop: '12px' }}>
              {__(
                'Nginx detected. Browser cache values from this screen do not apply through .htaccess. Use the generated Nginx snippet or your server config to enforce them.',
                'prorank-seo'
              )}
            </div>
          )}
          {nginxInfo.server && (
            <div className="prorank-notice prorank-notice-info" style={{ marginTop: '12px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
                <div>
                  <strong>{__('Generated Nginx Snippet', 'prorank-seo')}</strong>
                  <div style={{ marginTop: '4px' }}>
                    {__('This snippet reflects your saved ProRank cache settings. Save changes first, then copy it into your Nginx server block to enforce static asset cache headers.', 'prorank-seo')}
                  </div>
                  {nginxCachePath && (
                    <div style={{ marginTop: '4px' }}>
                      {sprintf(__('Page cache path: %s', 'prorank-seo'), nginxCachePath)}
                    </div>
                  )}
                </div>
                <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                  <ProrankButton
                    variant="secondary"
                    onClick={() => loadNginxConfig(true)}
                    disabled={nginxConfigLoading}
                  >
                    {nginxConfigLoading ? __('Refreshing...', 'prorank-seo') : __('Refresh Snippet', 'prorank-seo')}
                  </ProrankButton>
                  <ProrankButton
                    variant="secondary"
                    onClick={copyNginxConfig}
                    disabled={nginxConfigLoading || !nginxConfig}
                  >
                    {__('Copy Snippet', 'prorank-seo')}
                  </ProrankButton>
                </div>
              </div>

              {nginxConfigError && (
                <div style={{ marginTop: '12px', color: '#b32d2e' }}>
                  {nginxConfigError}
                </div>
              )}

              {!nginxConfigError && nginxConfig && (
                <pre style={{ marginTop: '12px', maxHeight: '320px', overflow: 'auto', padding: '12px', borderRadius: '8px', background: '#111827', color: '#f9fafb', fontSize: '12px', lineHeight: '1.5', whiteSpace: 'pre-wrap' }}>
                  {nginxConfig}
                </pre>
              )}
            </div>
          )}
          <div className={litespeedTone} style={{ marginTop: '12px' }}>
            {litespeedMessage}
          </div>

          {settings.browser_cache_enabled && (
            <>
              <div className="prorank-control-group">
                <SelectControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('Images Cache', 'prorank-seo')}
                  value={settings.browser_cache_images}
                  options={[
                    { label: __('1 Day', 'prorank-seo'), value: '86400' },
                    { label: __('1 Week', 'prorank-seo'), value: '604800' },
                    { label: __('1 Month', 'prorank-seo'), value: '2592000' },
                  ]}
                  onChange={(value) => updateSetting('browser_cache_images', value)}
                />
              </div>

              <div className="prorank-control-group">
                <SelectControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('CSS/JS Cache', 'prorank-seo')}
                  value={settings.browser_cache_css}
                  options={[
                    { label: __('1 Day', 'prorank-seo'), value: '86400' },
                    { label: __('1 Week', 'prorank-seo'), value: '604800' },
                    { label: __('1 Month', 'prorank-seo'), value: '2592000' },
                  ]}
                  onChange={(value) => {
                    updateSetting('browser_cache_css', value);
                    updateSetting('browser_cache_js', value);
                  }}
                />
              </div>

              <div className="prorank-control-group">
                <SelectControl
              __next40pxDefaultSize
              __nextHasNoMarginBottom
                  label={__('HTML Cache', 'prorank-seo')}
                  value={settings.browser_cache_html}
                  options={[
                    { label: __('No Cache', 'prorank-seo'), value: '0' },
                    { label: __('10 Minutes', 'prorank-seo'), value: '600' },
                    { label: __('1 Hour', 'prorank-seo'), value: '3600' },
                    { label: __('1 Day', 'prorank-seo'), value: '86400' },
                  ]}
                  onChange={(value) => updateSetting('browser_cache_html', value)}
                />
              </div>
            </>
          )}
        </div>
      </div>

      {/* JavaScript Optimization Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-media-code"></span>
            {__('JavaScript Optimization', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Defer JavaScript', 'prorank-seo')}</strong>
              <span>{__('Load scripts after page content. Keep off if another plugin already rewrites script loading.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.js_defer}
              onChange={(value) => updateSetting('js_defer', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Delay JavaScript', 'prorank-seo')}</strong>
              <span>{__('Delay scripts until user interaction. Builder and booking-heavy pages need explicit testing before production use.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.js_delay}
              onChange={(value) => updateSetting('js_delay', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Delay Third-Party Trackers', 'prorank-seo')}</strong>
              <span>{__('Safely push known analytics and ad trackers behind interaction without enabling full-site JavaScript delay.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.tracker_delay_enabled}
              onChange={(value) => updateSetting('tracker_delay_enabled', value)}
              label=""
            />
          </div>

          <div className="prorank-control-group">
            <TextareaControl
              __nextHasNoMarginBottom
              label={__('Exclude Scripts', 'prorank-seo')}
              help={__('Scripts to never optimize (one per line)', 'prorank-seo')}
              value={settings.js_exclude}
              onChange={(value) => updateSetting('js_exclude', value)}
              rows={4}
            />
          </div>

          <div className="prorank-notice prorank-notice-info" style={{ marginTop: '14px' }}>
            <span className="dashicons dashicons-warning"></span>
            <div>
              <strong>{__('Experimental JS Delay (Advanced)', 'prorank-seo')}</strong>
              <div style={{ marginTop: '4px' }}>
                {__('Use only for benchmarking/tuning. Keep disabled for universal-safe defaults, especially on Elementor or conversion-critical pages.', 'prorank-seo')}
              </div>
            </div>
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Delay jQuery Core', 'prorank-seo')}</strong>
              <span>{__('Can reduce unused JavaScript, but may affect legacy plugins.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.js_delay_jquery}
              onChange={(value) => updateSetting('js_delay_jquery', value)}
              label=""
              disabled={!settings.js_delay}
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Delay Elementor Frontend Modules', 'prorank-seo')}</strong>
              <span>{__('Aggressive mode for lower unused JS. Test layout/interactions before using in production.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.js_delay_elementor_modules}
              onChange={(value) => updateSetting('js_delay_elementor_modules', value)}
              label=""
              disabled={!settings.js_delay}
            />
          </div>
        </div>
      </div>

      {/* CSS Optimization Card */}
      <div className="prorank-card">
        <div className="prorank-card-header">
          <h3>
            <span className="dashicons dashicons-art"></span>
            {__('CSS Optimization', 'prorank-seo')}
          </h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Minify CSS', 'prorank-seo')}</strong>
              <span>{__('Remove whitespace and comments', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.css_minify}
              onChange={(value) => updateSetting('css_minify', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Combine CSS', 'prorank-seo')}</strong>
              <span>{__('Merge multiple CSS files into one. Keep off if another optimizer already handles CSS aggregation.', 'prorank-seo')}</span>
              <span>{__('On HTTP/2, split delivery is often safer than combining on builder-heavy sites.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.css_combine}
              onChange={(value) => updateSetting('css_combine', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Optimize CSS Delivery', 'prorank-seo')}</strong>
              <span>{__('Builder-sensitive beta. Do not combine with another CSS optimizer, and retest Elementor/template pages before production use.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.css_async}
              onChange={(value) => updateSetting('css_async', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Minify Large Inline CSS Blocks', 'prorank-seo')}</strong>
              <span>{__('Compress builder and plugin-generated inline style tags in the final HTML. Keep off if another optimizer already rewrites final HTML.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.inline_css_minify_enabled}
              onChange={(value) => updateSetting('inline_css_minify_enabled', value)}
              label=""
            />
          </div>

          <div className="prorank-toggle-row">
            <div className="prorank-toggle-label">
              <strong>{__('Move Body Styles Into Head', 'prorank-seo')}</strong>
              <span>{__('Relocate late body-injected style tags into the document head so CSS arrives earlier. Avoid when another optimizer is already relocating or inlining styles.', 'prorank-seo')}</span>
            </div>
            <ProrankToggleSlider
              checked={settings.inline_css_relocate_enabled}
              onChange={(value) => updateSetting('inline_css_relocate_enabled', value)}
              label=""
            />
          </div>

          <div className="prorank-control-group">
            <TextareaControl
              __nextHasNoMarginBottom
              label={__('Exclude Stylesheets', 'prorank-seo')}
              help={__('CSS files to never optimize (one per line)', 'prorank-seo')}
              value={settings.css_exclude}
              onChange={(value) => updateSetting('css_exclude', value)}
              rows={4}
            />
          </div>
        </div>
      </div>

      {/* Save Button */}
      <div className="prorank-actions prorank-actions-center prorank-mt-32">
        <ProrankButton
          variant="primary"
          onClick={saveSettings}
          disabled={saving}
          style={{ minWidth: '200px' }}
        >
          {saving ? __('Saving...', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
        </ProrankButton>
      </div>
    </div>
  );
};

export default CachingDeliverySettings;
