/**
 * Advanced Settings Tab Component
 *
 * Modern React 19 component with React Query and Zod validation
 *
 * @module Support/AdvancedSettingsTab
 * @since 1.0.0
 */

import React, { useState, useCallback, useRef } from 'react';
import { Card, Button, Input, Select, Toggle, Alert } from '../../../components/ui';
import { __ } from '@wordpress/i18n';
import SettingsSnapshotUI from '../../../components/SettingsSnapshot';
import { useNotification } from '../../../contexts/NotificationContext';
import {
  useAdvancedSettings,
  useSaveAdvancedSettings,
  useClearCache,
  useExportSettings,
  useImportSettings,
  useImportFromCompetitor,
} from '../../../hooks/useAdvancedSettings';
import type {
  AdvancedSettings,
  TabComponentProps,
  CompetitorSource
} from '../../../types/advanced-settings';
import {
  advancedSettingsDefaults,
  logLevelOptions,
  competitorOptions
} from '../../../types/advanced-settings';

declare global {
  interface Window {
    prorankSeo?: {
      version?: string;
      buildFingerprint?: string;
      buildTimestamp?: number;
      buildCommit?: string;
    };
  }
}

const AdvancedSettingsTab: React.FC<TabComponentProps> = ({ addNotice = () => {} }) => {
  const { showNotification } = useNotification();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [localSettings, setLocalSettings] = useState<AdvancedSettings | null>(null);
  const [selectedCompetitor, setSelectedCompetitor] = useState<CompetitorSource>('yoast');

  // Use context notification as primary, fall back to prop if context is unavailable
  const notify = useCallback((type: 'success' | 'error' | 'warning' | 'info', message: string) => {
    showNotification(message, type);
    addNotice(type, message);
  }, [showNotification, addNotice]);

  // React Query hooks
  const { data: settings, isLoading, error } = useAdvancedSettings();
  const saveMutation = useSaveAdvancedSettings();
  const clearCacheMutation = useClearCache();
  const exportMutation = useExportSettings();
  const importMutation = useImportSettings();
  const competitorMutation = useImportFromCompetitor();

  // Use local state if modified, otherwise use fetched data
  const currentSettings = localSettings ?? settings ?? advancedSettingsDefaults;
  const buildTimestamp = Number(window.prorankSeo?.buildTimestamp ?? 0);
  const thirdPartyGovernance =
    currentSettings.third_party_governance ?? advancedSettingsDefaults.third_party_governance;

  const handleSettingChange = useCallback(<K extends keyof AdvancedSettings>(
    key: K,
    value: AdvancedSettings[K]
  ) => {
    setLocalSettings(prev => ({
      ...(prev ?? settings ?? advancedSettingsDefaults),
      [key]: value,
    }));
  }, [settings]);

  const handleSave = useCallback(async () => {
    try {
      await saveMutation.mutateAsync(currentSettings);
      setLocalSettings(null);
      notify('success', __('Advanced settings saved successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to save settings', 'prorank-seo'));
    }
  }, [currentSettings, saveMutation, notify]);

  const handleClearCache = useCallback(async () => {
    if (!confirm(__('Are you sure you want to clear all caches?', 'prorank-seo'))) {
      return;
    }

    try {
      await clearCacheMutation.mutateAsync();
      notify('success', __('All caches cleared successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to clear cache', 'prorank-seo'));
    }
  }, [clearCacheMutation, notify]);

  const handleExport = useCallback(async () => {
    try {
      await exportMutation.mutateAsync();
      notify('success', __('Settings exported successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to export settings', 'prorank-seo'));
    }
  }, [exportMutation, notify]);

  const handleImport = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      const text = await file.text();
      const importedData = JSON.parse(text);

      await importMutation.mutateAsync(importedData);
      notify('success', __('Settings imported successfully! Page will reload...', 'prorank-seo'));
      setTimeout(() => window.location.reload(), 2000);
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to import settings', 'prorank-seo'));
    } finally {
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  }, [importMutation, notify]);

  const handleCompetitorImport = useCallback(async () => {
    if (!confirm(
      __(`Are you sure you want to import data from ${selectedCompetitor}? This will overwrite existing settings.`, 'prorank-seo')
    )) {
      return;
    }

    try {
      const result = await competitorMutation.mutateAsync({
        source: selectedCompetitor,
        types: ['meta', 'settings', 'redirects', 'schema', 'locations'],
      });

      if (result.success) {
        const stats = result.stats;
        const message = __('Import complete! ', 'prorank-seo') +
          (stats ? `Posts: ${stats.posts || 0}, Locations: ${stats.locations || 0}, Settings: ${stats.settings || 0}` : '');
        notify('success', message);
      } else {
        notify('error', result.message || __('Import failed', 'prorank-seo'));
      }
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to import from competitor', 'prorank-seo'));
    }
  }, [selectedCompetitor, competitorMutation, notify]);

  if (isLoading) {
    return (
      <div className="prorank-advanced-settings-tab prorank-loading">
        <p>{__('Loading settings...', 'prorank-seo')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="prorank-advanced-settings-tab">
        <Alert variant="error">
          {__('Failed to load settings. Please refresh the page.', 'prorank-seo')}
        </Alert>
      </div>
    );
  }

  return (
    <div className="prorank-advanced-settings-tab">
      <div className="prorank-section-header">
        <h2 className="prorank-section-title">{__('Advanced Settings', 'prorank-seo')}</h2>
        <p className="prorank-section-description">
          {__('Fine-tune ProRank SEO with advanced configuration options for power users', 'prorank-seo')}
        </p>
      </div>

      <Alert variant="warning" className="advanced-warning">
        {__("Warning: These settings can affect your site's functionality. Only modify if you know what you're doing.", 'prorank-seo')}
      </Alert>

      <div className="prorank-support-grid">
        {/* Debug & Development */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Debug & Development', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Debug Mode', 'prorank-seo')}
              help={__('Enable detailed error logging and debug information', 'prorank-seo')}
              checked={currentSettings.debug_mode}
              onChange={(value) => handleSettingChange('debug_mode', value)}
            />

            <Select
              label={__('Log Level', 'prorank-seo')}
              value={currentSettings.log_level}
              options={logLevelOptions.map(opt => ({
                label: __(opt.label, 'prorank-seo'),
                value: opt.value
              }))}
              onChange={(value) => handleSettingChange('log_level', value as AdvancedSettings['log_level'])}
            />
          </div>
        </Card>

        {/* Performance */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Performance', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Input
              label={__('API Timeout (seconds)', 'prorank-seo')}
              type="number"
              value={String(currentSettings.api_timeout)}
              onChange={(value) => handleSettingChange('api_timeout', parseInt(value, 10) || 30)}
              help={__('Maximum time to wait for API responses (5-120)', 'prorank-seo')}
            />

            <Input
              label={__('Cache Duration (seconds)', 'prorank-seo')}
              type="number"
              value={String(currentSettings.cache_duration)}
              onChange={(value) => handleSettingChange('cache_duration', parseInt(value, 10) || 3600)}
              help={__('How long to cache API responses (60-86400)', 'prorank-seo')}
            />

            <Button
              variant="secondary"
              onClick={handleClearCache}
              disabled={clearCacheMutation.isPending}
            >
              {clearCacheMutation.isPending
                ? __('Clearing...', 'prorank-seo')
                : __('Clear All Caches', 'prorank-seo')}
            </Button>
          </div>
        </Card>

        {/* Security */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Security', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable XML-RPC', 'prorank-seo')}
              help={__('Disable XML-RPC to prevent brute force attacks', 'prorank-seo')}
              checked={currentSettings.disable_xmlrpc}
              onChange={(value) => handleSettingChange('disable_xmlrpc', value)}
            />

            <Toggle
              label={__('Disable REST API for non-authenticated users', 'prorank-seo')}
              help={__('Restrict REST API access to logged-in users only', 'prorank-seo')}
              checked={currentSettings.disable_rest_api_public}
              onChange={(value) => handleSettingChange('disable_rest_api_public', value)}
            />

            <Toggle
              label={__('Remove WordPress version strings', 'prorank-seo')}
              help={__('Hide WordPress version from HTML, RSS feeds, etc.', 'prorank-seo')}
              checked={currentSettings.remove_version_strings}
              onChange={(value) => handleSettingChange('remove_version_strings', value)}
            />

            <Toggle
              label={__('Disable file editing', 'prorank-seo')}
              help={__('Disable the theme and plugin file editor in admin', 'prorank-seo')}
              checked={currentSettings.disable_file_editing}
              onChange={(value) => handleSettingChange('disable_file_editing', value)}
            />
          </div>
        </Card>

        {/* WordPress Features */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('WordPress Features', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable Emojis', 'prorank-seo')}
              help={__('Remove WordPress emoji scripts and styles', 'prorank-seo')}
              checked={currentSettings.disable_emojis}
              onChange={(value) => handleSettingChange('disable_emojis', value)}
            />

            <Toggle
              label={__('Disable Gutenberg Block Editor', 'prorank-seo')}
              help={__('Use the classic editor instead of Gutenberg', 'prorank-seo')}
              checked={currentSettings.disable_gutenberg}
              onChange={(value) => handleSettingChange('disable_gutenberg', value)}
            />

            <Toggle
              label={__('Disable Dashicons (frontend)', 'prorank-seo')}
              help={__('Remove Dashicon font from the frontend for logged-out visitors', 'prorank-seo')}
              checked={currentSettings.disable_dashicons}
              onChange={(value) => handleSettingChange('disable_dashicons', value)}
            />

            <Toggle
              label={__('Remove Global Styles', 'prorank-seo')}
              help={__('Remove inline global styles and SVG filters added by WordPress', 'prorank-seo')}
              checked={currentSettings.remove_global_styles}
              onChange={(value) => handleSettingChange('remove_global_styles', value)}
            />

            <Toggle
              label={__('Disable Password Strength Meter', 'prorank-seo')}
              help={__('Remove the password strength meter script on account and checkout pages', 'prorank-seo')}
              checked={currentSettings.disable_password_strength_meter}
              onChange={(value) => handleSettingChange('disable_password_strength_meter', value)}
            />
          </div>
        </Card>

        {/* WooCommerce */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('WooCommerce', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable WooCommerce Scripts', 'prorank-seo')}
              help={__('Remove WooCommerce scripts and styles from non-shop pages', 'prorank-seo')}
              checked={currentSettings.disable_woocommerce_scripts}
              onChange={(value) => handleSettingChange('disable_woocommerce_scripts', value)}
            />

            <Toggle
              label={__('Disable Cart Fragments', 'prorank-seo')}
              help={__('Prevent AJAX cart fragment calls on every page load', 'prorank-seo')}
              checked={currentSettings.disable_woocommerce_cart_fragments}
              onChange={(value) => handleSettingChange('disable_woocommerce_cart_fragments', value)}
            />

            <Toggle
              label={__('Disable WooCommerce Widgets', 'prorank-seo')}
              help={__('Deregister default WooCommerce sidebar widgets', 'prorank-seo')}
              checked={currentSettings.disable_woocommerce_widgets}
              onChange={(value) => handleSettingChange('disable_woocommerce_widgets', value)}
            />

            <Toggle
              label={__('Disable WooCommerce Status Meta Box', 'prorank-seo')}
              help={__('Remove the WooCommerce status widget from the admin dashboard', 'prorank-seo')}
              checked={currentSettings.disable_woocommerce_status_meta_box}
              onChange={(value) => handleSettingChange('disable_woocommerce_status_meta_box', value)}
            />
          </div>
        </Card>

        {/* Google Maps */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Google Maps', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable Google Maps Scripts', 'prorank-seo')}
              help={__('Block Google Maps API scripts from loading on the frontend', 'prorank-seo')}
              checked={currentSettings.disable_google_maps}
              onChange={(value) => handleSettingChange('disable_google_maps', value)}
            />

            {currentSettings.disable_google_maps && (
              <Input
                label={__('Exclusions', 'prorank-seo')}
                help={__('Comma-separated post IDs, slugs, or URL substrings where Maps should remain loaded', 'prorank-seo')}
                value={currentSettings.disable_google_maps_exclusions || ''}
                onChange={(value) => handleSettingChange('disable_google_maps_exclusions', value)}
                placeholder="contact, 3019, /our-clinics/"
              />
            )}
          </div>
        </Card>

        {/* Third-Party Governance */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Third-Party Governance', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Delay Google Services', 'prorank-seo')}
              help={__('Delay GTM, gtag, Analytics, Ads, and related Google measurement scripts until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_google_services}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_google_services: value,
              })}
            />

            <Toggle
              label={__('Delay Review Widgets', 'prorank-seo')}
              help={__('Delay review widget loaders like Trustindex until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_review_widgets}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_review_widgets: value,
              })}
            />

            <Toggle
              label={__('Keep Consent Scripts Non-Blocking', 'prorank-seo')}
              help={__('Apply ProRank non-blocking handling to consent managers like CookieYes and Cookiebot.', 'prorank-seo')}
              checked={thirdPartyGovernance.defer_consent_scripts}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                defer_consent_scripts: value,
              })}
            />

            <Toggle
              label={__('Delay Identity Widgets', 'prorank-seo')}
              help={__('Delay sign-in clients like Google Sign-In until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_identity_widgets}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_identity_widgets: value,
              })}
            />
          </div>
        </Card>

        {/* Performance Profile */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Performance Profile', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Select
              label={__('Performance Profile', 'prorank-seo')}
              help={__('Controls which performance features are auto-enabled. Safe mode suppresses CSS/JS optimization on builder sites.', 'prorank-seo')}
              value={currentSettings.performance_profile}
              options={[
                { label: __('Safe (recommended for builder sites)', 'prorank-seo'), value: 'safe' },
                { label: __('Balanced', 'prorank-seo'), value: 'balanced' },
                { label: __('Aggressive', 'prorank-seo'), value: 'aggressive' },
              ]}
              onChange={(value) => handleSettingChange('performance_profile', value)}
            />

            <Toggle
              label={__('Compatibility Mode', 'prorank-seo')}
              help={__('Auto-detect page builders and suppress risky optimizations', 'prorank-seo')}
              checked={currentSettings.performance_compatibility_mode}
              onChange={(value) => handleSettingChange('performance_compatibility_mode', value)}
            />

            <Toggle
              label={__('Auto Rollback', 'prorank-seo')}
              help={__('Automatically revert performance changes if they cause errors', 'prorank-seo')}
              checked={currentSettings.performance_auto_rollback}
              onChange={(value) => handleSettingChange('performance_auto_rollback', value)}
            />
          </div>
        </Card>

        {/* Code Injection */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Code Injection', 'prorank-seo')}</h3>
            <p className="prorank-card-description">{__('Add custom code to the head, body open, or footer of your site. Frontend only - excluded from admin, REST, feeds, and sitemaps.', 'prorank-seo')}</p>
          </div>
          <div className="prorank-card-body">
            <div className="pr:flex pr:flex-col pr:gap-4">
              <div>
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-1">{__('Head Code', 'prorank-seo')}</label>
                <textarea
                  className="pr:w-full pr:min-h-[80px] pr:p-2 pr:border pr:border-gray-300 pr:rounded pr:font-mono pr:text-sm"
                  value={currentSettings.code_injection?.head_code || ''}
                  onChange={(e) => handleSettingChange('code_injection', { ...currentSettings.code_injection, head_code: e.target.value })}
                  placeholder="<!-- Analytics, meta tags, etc. -->"
                />
              </div>
              <div>
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-1">{__('Body Open Code', 'prorank-seo')}</label>
                <textarea
                  className="pr:w-full pr:min-h-[80px] pr:p-2 pr:border pr:border-gray-300 pr:rounded pr:font-mono pr:text-sm"
                  value={currentSettings.code_injection?.body_code || ''}
                  onChange={(e) => handleSettingChange('code_injection', { ...currentSettings.code_injection, body_code: e.target.value })}
                  placeholder="<!-- GTM noscript, etc. -->"
                />
              </div>
              <div>
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-1">{__('Footer Code', 'prorank-seo')}</label>
                <textarea
                  className="pr:w-full pr:min-h-[80px] pr:p-2 pr:border pr:border-gray-300 pr:rounded pr:font-mono pr:text-sm"
                  value={currentSettings.code_injection?.footer_code || ''}
                  onChange={(e) => handleSettingChange('code_injection', { ...currentSettings.code_injection, footer_code: e.target.value })}
                  placeholder="<!-- Chat widgets, tracking pixels, etc. -->"
                />
              </div>
            </div>
          </div>
        </Card>

        {/* CDN Rewrite */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('CDN URL Rewrite', 'prorank-seo')}</h3>
            <p className="prorank-card-description">{__('Rewrite local static asset URLs to a CDN hostname. Leave URL blank to disable.', 'prorank-seo')}</p>
          </div>
          <div className="prorank-card-body">
            <Input
              label={__('CDN URL', 'prorank-seo')}
              help={__('Full CDN hostname including protocol, e.g. https://cdn.example.com', 'prorank-seo')}
              value={currentSettings.cdn_rewrite?.url || ''}
              onChange={(value) => handleSettingChange('cdn_rewrite', { ...currentSettings.cdn_rewrite, url: value })}
              placeholder="https://cdn.example.com"
            />

            <Input
              label={__('Directories', 'prorank-seo')}
              help={__('Comma-separated directories to rewrite', 'prorank-seo')}
              value={currentSettings.cdn_rewrite?.directories || 'wp-content,wp-includes'}
              onChange={(value) => handleSettingChange('cdn_rewrite', { ...currentSettings.cdn_rewrite, directories: value })}
            />

            <Input
              label={__('Exclusions', 'prorank-seo')}
              help={__('Comma-separated URL substrings to exclude from CDN rewriting', 'prorank-seo')}
              value={currentSettings.cdn_rewrite?.exclusions || ''}
              onChange={(value) => handleSettingChange('cdn_rewrite', { ...currentSettings.cdn_rewrite, exclusions: value })}
              placeholder=".php, wp-admin"
            />
          </div>
        </Card>

        {/* Performance Module Overrides */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Performance Module Overrides', 'prorank-seo')}</h3>
            <p className="prorank-card-description">{__('Force-enable specific performance modules that the compatibility profile would normally suppress on builder sites.', 'prorank-seo')}</p>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('CSS Optimization (css_opt)', 'prorank-seo')}
              help={__('Force-enable CSS minification and concatenation even on Elementor/Divi sites', 'prorank-seo')}
              checked={!!currentSettings.performance_module_overrides?.css_opt}
              onChange={(value) => handleSettingChange('performance_module_overrides', { ...currentSettings.performance_module_overrides, css_opt: value })}
            />

            <Toggle
              label={__('JS Optimization (js_opt)', 'prorank-seo')}
              help={__('Force-enable JS defer/delay optimization on builder sites', 'prorank-seo')}
              checked={!!currentSettings.performance_module_overrides?.js_opt}
              onChange={(value) => handleSettingChange('performance_module_overrides', { ...currentSettings.performance_module_overrides, js_opt: value })}
            />

            <Toggle
              label={__('Critical CSS', 'prorank-seo')}
              help={__('Force-enable critical CSS generation on builder sites', 'prorank-seo')}
              checked={!!currentSettings.performance_module_overrides?.critical_css}
              onChange={(value) => handleSettingChange('performance_module_overrides', { ...currentSettings.performance_module_overrides, critical_css: value })}
            />

            <Toggle
              label={__('Unused CSS Removal', 'prorank-seo')}
              help={__('Force-enable unused CSS removal on builder sites', 'prorank-seo')}
              checked={!!currentSettings.performance_module_overrides?.unused_css}
              onChange={(value) => handleSettingChange('performance_module_overrides', { ...currentSettings.performance_module_overrides, unused_css: value })}
            />
          </div>
        </Card>
      </div>

      {/* Debug Information */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Debug Information', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-debug-info">
            <p>
              <strong>{__('Plugin Version:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeo?.version || 'Unknown'}
            </p>
            <p>
              <strong>{__('Build Fingerprint:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeo?.buildFingerprint || 'Not available'}
            </p>
            <p>
              <strong>{__('Build Timestamp:', 'prorank-seo')}</strong>{' '}
              {Number.isFinite(buildTimestamp) && buildTimestamp > 0
                ? new Date(buildTimestamp * 1000).toLocaleString()
                : 'Not available'}
            </p>
            <p>
              <strong>{__('Build Source:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeo?.buildCommit || 'local-package'}
            </p>
          </div>
        </div>
      </Card>

      {/* Import/Export */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Import/Export', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <p>{__('Backup your ProRank settings or transfer them to another site.', 'prorank-seo')}</p>

          <div className="import-export-buttons">
            <Button
              variant="secondary"
              onClick={handleExport}
              disabled={exportMutation.isPending}
            >
              {exportMutation.isPending
                ? __('Exporting...', 'prorank-seo')
                : __('Export Settings', 'prorank-seo')}
            </Button>

            <label className="import-button-wrapper">
              <Button
                variant="secondary"
                disabled={importMutation.isPending}
                as="span"
              >
                {importMutation.isPending
                  ? __('Importing...', 'prorank-seo')
                  : __('Import Settings', 'prorank-seo')}
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                accept=".json"
                onChange={handleImport}
                style={{ display: 'none' }}
                disabled={importMutation.isPending}
              />
            </label>
          </div>
        </div>
      </Card>

      {/* Settings History */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Settings History', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <SettingsSnapshotUI embedded />
        </div>
      </Card>

      {/* Import from Competitors */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Import from Other SEO Plugins', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <p>{__('Import your SEO data from other popular SEO plugins.', 'prorank-seo')}</p>

          <div className="competitor-import-section">
            <Select
              label={__('Select SEO Plugin', 'prorank-seo')}
              value={selectedCompetitor}
              options={competitorOptions.map(opt => ({
                label: opt.label,
                value: opt.value
              }))}
              onChange={(value) => setSelectedCompetitor(value as CompetitorSource)}
            />

            <Button
              variant="secondary"
              onClick={handleCompetitorImport}
              disabled={competitorMutation.isPending}
              className="competitor-import-button"
            >
              {competitorMutation.isPending
                ? __('Importing...', 'prorank-seo')
                : __('Import Data', 'prorank-seo')}
            </Button>
          </div>

          <p className="import-note">
            {__('This will import meta titles, descriptions, focus keywords, redirects, and settings.', 'prorank-seo')}
          </p>
        </div>
      </Card>

      {/* Save Button */}
      <div className="prorank-settings-actions">
        <Button
          variant="primary"
          onClick={handleSave}
          disabled={saveMutation.isPending || !localSettings}
        >
          {saveMutation.isPending
            ? __('Saving...', 'prorank-seo')
            : __('Save Advanced Settings', 'prorank-seo')}
        </Button>

        {localSettings && (
          <Button
            variant="tertiary"
            onClick={() => setLocalSettings(null)}
          >
            {__('Discard Changes', 'prorank-seo')}
          </Button>
        )}
      </div>
    </div>
  );
};

export default AdvancedSettingsTab;
