/**
 * 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,
} 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;

  // 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;

  // 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 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;
  };
}

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: 3600,
    exclude_urls: '',

    // 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: '',
    keycdn_zone_id: '',
    keycdn_api_key: '',

    // 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 [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 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 ?? 3600,
          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();
  }, [loadSettings, loadCacheStats]);

  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 {
      // Map frontend keys back to backend keys (cache_enabled, etc.)
      const backendSettings = {
        ...settings,
        cache_enabled: settings.enabled,
        cache_lifetime: settings.lifetime,
        cache_exclude_urls: settings.exclude_urls,
      };
      const response = await apiFetch<SafeModeApplyResponse>({
        path: '/prorank-seo/v1/performance/cache-settings',
        method: 'POST',
        data: { settings: backendSettings },
      });
      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');
      }
    } catch (error: any) {
      showNotification(error.message || __('Failed to save settings', '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 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 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);
    }
  };

  // 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">
        <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;

  return (
    <div className="prorank-performance-container">
      {/* 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>{__('Prevents double minify/cache/lazy-load behavior when competitor 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="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>

      {/* 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.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={86400}
                  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-actions">
                <ProrankButton
                  variant="secondary"
                  onClick={clearCache}
                  disabled={clearing}
                >
                  {clearing ? __('Clearing...', 'prorank-seo') : __('Clear Cache', 'prorank-seo')}
                </ProrankButton>
              </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>
              <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.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>
          )}
          <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' },
                    { label: __('1 Year', 'prorank-seo'), value: '31536000' },
                  ]}
                  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' },
                    { label: __('1 Year', 'prorank-seo'), value: '31536000' },
                  ]}
                  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', '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', '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.', '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', 'prorank-seo')}</span>
              <span>{__('On HTTP/2, split + async is usually faster than combining.', '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>{__('Safe mode: delay full CSS until interaction/timeout when critical CSS coverage is available', '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.', '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.', '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;
