import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useNotification } from '../../../contexts/NotificationContext';
import { Toggle, Button, Alert, Radio, Tabs, Card, Badge } from '../../../components/ui';
import { Text } from '../../../components/common/Typography';
import {
  LinkIcon,
  CogIcon,
  ExclamationTriangleIcon,
  WrenchScrewdriverIcon,
  QuestionMarkCircleIcon,
  CheckCircleIcon,
  ClockIcon,
  ArrowPathIcon,
  ShieldCheckIcon,
  FunnelIcon,
  DocumentTextIcon,
  AdjustmentsHorizontalIcon,
  PhotoIcon,
  FolderIcon,
} from '@heroicons/react/24/outline';

const UrlCleanupSettings = () => {
  const [settings, setSettings] = useState({
    strip_category_base: false,
    strip_tag_base: false,
    remove_replytocom: false,
    remove_utm_parameters: false,
    utm_to_fragment: false,
    force_trailing_slash: false,
    remove_trailing_slash: false,
    normalize_internal_archive_links: false,
    author_date_archive_link_policy: 'default',
    convert_to_lowercase: false,
    remove_stop_words: false,
    attachment_redirect: 'off',
    author_archive_handling: 'default',
    date_archive_handling: 'default',
    // Head Cleanup settings
    remove_query_strings: false,
    remove_feed_links: false,
    remove_shortlink: false,
    remove_rest_api_links: false,
    clean_permalinks: false,
    // Query parameter settings
    param_whitelist: 'gclid,fbclid,msclkid,_ga',
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [showWarning, setShowWarning] = useState(false);

  // URL Test state
  const [testUrl, setTestUrl] = useState('');
  const [testResult, setTestResult] = useState(null);
  const [testing, setTesting] = useState(false);

  // Bulk cleanup state
  const [bulkCleaning, setBulkCleaning] = useState(false);

  const { showNotification } = useNotification();
  const hasAccess = true;

  // Load settings
  useEffect(() => {
    const loadSettings = async () => {
      setLoading(true);
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/settings/url-cleanup',
        });
        setSettings(
          response?.settings || {
            strip_category_base: false,
            strip_tag_base: false,
            remove_replytocom: false,
            remove_utm_parameters: false,
            utm_to_fragment: false,
            force_trailing_slash: false,
            remove_trailing_slash: false,
            normalize_internal_archive_links: false,
            author_date_archive_link_policy: 'default',
            convert_to_lowercase: false,
            remove_stop_words: false,
            attachment_redirect: 'off',
            author_archive_handling: 'default',
            date_archive_handling: 'default',
            // Head Cleanup settings
            remove_query_strings: false,
            remove_feed_links: false,
            remove_shortlink: false,
            remove_rest_api_links: false,
            clean_permalinks: false,
            // Query parameter settings
            param_whitelist: 'gclid,fbclid,msclkid,_ga',
          }
        );
      } catch (error) {
        showNotification(__('Failed to load settings', 'prorank-seo'), 'error');
      } finally {
        setLoading(false);
      }
    };

    loadSettings();
  }, [showNotification]);

  const handleSettingChange = (key, value) => {
    setSettings((prev) => ({
      ...prev,
      [key]: value,
    }));
    setHasChanges(true);

    // Show warning for risky settings
    if ((key === 'strip_category_base' || key === 'strip_tag_base') && value) {
      setShowWarning(true);
    }

    // Handle mutually exclusive settings
    if (key === 'force_trailing_slash' && value) {
      setSettings((prev) => ({
        ...prev,
        [key]: value,
        remove_trailing_slash: false,
      }));
      return;
    }
    if (key === 'remove_trailing_slash' && value) {
      setSettings((prev) => ({
        ...prev,
        [key]: value,
        force_trailing_slash: false,
      }));
      return;
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/url-cleanup',
        method: 'POST',
        data: settings,
      });

      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
      setHasChanges(false);
      setShowWarning(false);
    } catch (error) {
      showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  // URL Test functionality
  const handleTestUrl = async () => {
    if (!testUrl.trim()) return;

    setTesting(true);
    setTestResult(null);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/url-cleanup/test',
        method: 'POST',
        data: { url: testUrl },
      });
      setTestResult(response);
    } catch (error) {
      showNotification(__('Failed to test URL', 'prorank-seo'), 'error');
    } finally {
      setTesting(false);
    }
  };

  // Bulk cleanup
  const handleBulkCleanup = async () => {
    if (!window.confirm(__('This will apply URL cleanup rules to all existing posts. Continue?', 'prorank-seo'))) {
      return;
    }

    setBulkCleaning(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/url-cleanup/bulk-cleanup',
        method: 'POST',
      });
      showNotification(
        __('Bulk cleanup completed. ', 'prorank-seo') +
        (response?.updated || 0) + __(' URLs processed.', 'prorank-seo'),
        'success'
      );
    } catch (error) {
      showNotification(__('Bulk cleanup failed', 'prorank-seo'), 'error');
    } finally {
      setBulkCleaning(false);
    }
  };

  // URL length indicator helper (2025 best practices: <50 optimal, 50-60 acceptable, >60 too long)
  const getUrlLengthStatus = (url) => {
    const length = url?.length || 0;
    if (length === 0) return { status: 'neutral', label: '' };
    if (length < 50) return { status: 'good', label: __('Optimal length', 'prorank-seo'), color: '#22c55e' };
    if (length <= 60) return { status: 'warning', label: __('Acceptable', 'prorank-seo'), color: '#f59e0b' };
    return { status: 'bad', label: __('Too long (>60)', 'prorank-seo'), color: '#ef4444' };
  };

  // Count active cleanup settings
  const countActiveSettings = () => {
    const booleanSettings = [
      'strip_category_base', 'strip_tag_base', 'remove_replytocom', 'remove_utm_parameters',
      'utm_to_fragment', 'force_trailing_slash', 'remove_trailing_slash', 'normalize_internal_archive_links', 'convert_to_lowercase',
      'remove_stop_words', 'remove_query_strings', 'remove_feed_links',
      'remove_shortlink', 'remove_rest_api_links', 'clean_permalinks'
    ];
    return booleanSettings.filter(key => settings[key]).length + (settings.author_date_archive_link_policy && settings.author_date_archive_link_policy !== 'default' ? 1 : 0);
  };

  // Stats dashboard component
  const StatsDashboard = () => (
    <div className="pr:grid pr:grid-cols-1 pr:sm:grid-cols-2 pr:lg:grid-cols-4 pr:gap-4 pr:mb-6">
      {/* Active Rules */}
      <div className="pr:bg-gradient-to-br pr:from-blue-50 pr:to-blue-100 pr:rounded-xl pr:p-4 pr:border pr:border-blue-200/50 pr:transition-all pr:duration-300 pr:hover:shadow-md">
        <div className="pr:flex pr:items-center pr:gap-3">
          <div className="pr:p-2 pr:bg-blue-500/10 pr:rounded-lg">
            <CogIcon className="pr:w-6 pr:h-6 pr:text-blue-600" />
          </div>
          <div>
            <div className="pr:text-2xl pr:font-bold pr:text-blue-700">{countActiveSettings()}</div>
            <div className="pr:text-sm pr:text-blue-600/80">{__('Active Rules', 'prorank-seo')}</div>
          </div>
        </div>
      </div>

      {/* Redirect Manager */}
      <div className="pr:bg-gradient-to-br pr:from-amber-50 pr:to-amber-100 pr:rounded-xl pr:p-4 pr:border pr:border-amber-200/50 pr:transition-all pr:duration-300 pr:hover:shadow-md">
        <div className="pr:flex pr:items-center pr:gap-3">
          <div className="pr:p-2 pr:rounded-lg pr:bg-amber-500/10">
            <ExclamationTriangleIcon className="pr:w-6 pr:h-6 pr:text-amber-600" />
          </div>
          <div>
            <div className="pr:text-lg pr:font-bold pr:text-amber-700">{__('Redirect Manager', 'prorank-seo')}</div>
            <div className="pr:text-sm pr:text-amber-700/80">{__('404 monitoring moved here', 'prorank-seo')}</div>
          </div>
        </div>
      </div>

      {/* URL Status */}
      <div className="pr:bg-gradient-to-br pr:from-emerald-50 pr:to-emerald-100 pr:rounded-xl pr:p-4 pr:border pr:border-emerald-200/50 pr:transition-all pr:duration-300 pr:hover:shadow-md">
        <div className="pr:flex pr:items-center pr:gap-3">
          <div className="pr:p-2 pr:bg-emerald-500/10 pr:rounded-lg">
            <CheckCircleIcon className="pr:w-6 pr:h-6 pr:text-emerald-600" />
          </div>
          <div>
            <div className="pr:text-2xl pr:font-bold pr:text-emerald-700">{__('Active', 'prorank-seo')}</div>
            <div className="pr:text-sm pr:text-emerald-600/80">{__('Module Status', 'prorank-seo')}</div>
          </div>
        </div>
      </div>

      {/* Access */}
      <div className="pr:bg-gradient-to-br pr:from-gray-50 pr:to-gray-100 pr:border-gray-200/50 pr:rounded-xl pr:p-4 pr:border pr:transition-all pr:duration-300 pr:hover:shadow-md">
        <div className="pr:flex pr:items-center pr:gap-3">
          <div className="pr:p-2 pr:rounded-lg pr:bg-gray-500/10">
            <ShieldCheckIcon className="pr:w-6 pr:h-6 pr:text-gray-600" />
          </div>
          <div>
            <div className="pr:text-2xl pr:font-bold pr:text-gray-700">{__('Free', 'prorank-seo')}</div>
            <div className="pr:text-sm pr:text-gray-600/80">{__('Included in this plugin', 'prorank-seo')}</div>
          </div>
        </div>
      </div>
    </div>
  );

  const tabs = [
    {
      name: 'general',
      title: (
        <span className="pr:flex pr:items-center pr:gap-2">
          <CogIcon className="pr:w-4 pr:h-4" />
          {__('General', 'prorank-seo')}
        </span>
      ),
      content: (
        <div className="prorank-settings-content pr:space-y-6 pr:transition-all pr:duration-300">
          {showWarning && (
            <Alert variant="warning" dismissible onDismiss={() => setShowWarning(false)} className="pr:mb-4">
              <strong>{__('Important: Permalink Structure Change', 'prorank-seo')}</strong>
              <p>
                {__(
                  'Removing the category or tag base will change your taxonomy URLs. Old URLs will be automatically redirected, but you should:',
                  'prorank-seo'
                )}
              </p>
              <ul className="pr:ml-5 pr:list-disc pr:mt-2 pr:space-y-1">
                <li>{__('Update any hardcoded category links in your content', 'prorank-seo')}</li>
                <li>{__('Notify search engines by submitting a new sitemap', 'prorank-seo')}</li>
                <li>{__('Monitor your site for any broken links', 'prorank-seo')}</li>
              </ul>
            </Alert>
          )}

          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <LinkIcon className="pr:w-5 pr:h-5 pr:text-blue-500" />
                {__('Taxonomy URLs', 'prorank-seo')}
                <Badge variant="info" size="sm">2</Badge>
              </h3>

              <div className={`pr:space-y-5 pr:transition-all pr:duration-300`}>
                <Toggle
                  label={__('Strip Category Base', 'prorank-seo')}
                  helpText={__(
                    'Remove /category/ from category archive URLs (e.g., /category/news/ becomes /news/)',
                    'prorank-seo'
                  )}
                  checked={settings.strip_category_base || false}
                  onChange={(checked) => handleSettingChange('strip_category_base', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Strip Tag Base', 'prorank-seo')}
                  helpText={__(
                    'Remove /tag/ from tag archive URLs (e.g., /tag/wordpress/ becomes /wordpress/)',
                    'prorank-seo'
                  )}
                  checked={settings.strip_tag_base || false}
                  onChange={(checked) => handleSettingChange('strip_tag_base', checked)}
                  disabled={!hasAccess}
                />
              </div>

          </Card>

          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <FunnelIcon className="pr:w-5 pr:h-5 pr:text-orange-500" />
                {__('URL Parameters', 'prorank-seo')}
                <Badge variant="warning" size="sm">3</Badge>
              </h3>

              <div className={`pr:space-y-5 pr:transition-all pr:duration-300`}>
                <Toggle
                  label={__('Remove Reply Parameters', 'prorank-seo')}
                  helpText={__(
                    'Remove ?replytocom parameters from comment URLs to prevent duplicate content',
                    'prorank-seo'
                  )}
                  checked={settings.remove_replytocom || false}
                  onChange={(checked) => handleSettingChange('remove_replytocom', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Remove UTM Parameters', 'prorank-seo')}
                  helpText={__(
                    'Automatically remove UTM tracking parameters from URLs (utm_source, utm_medium, etc.)',
                    'prorank-seo'
                  )}
                  checked={settings.remove_utm_parameters || false}
                  onChange={(checked) => handleSettingChange('remove_utm_parameters', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('UTM to Fragment (Yoast-style)', 'prorank-seo')}
                  helpText={__(
                    'Convert UTM parameters to URL fragments (#utm_source=x). Keeps URLs clean while preserving Analytics tracking.',
                    'prorank-seo'
                  )}
                  checked={settings.utm_to_fragment || false}
                  onChange={(checked) => handleSettingChange('utm_to_fragment', checked)}
                  disabled={!hasAccess || !settings.remove_utm_parameters}
                />

                <div className="pr:pt-2">
                  <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
                    {__('Parameter Whitelist', 'prorank-seo')}
                  </label>
                  <input
                    type="text"
                    value={settings.param_whitelist || ''}
                    onChange={(e) => handleSettingChange('param_whitelist', e.target.value)}
                    placeholder="gclid,fbclid,msclkid,_ga"
                    className="pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-lg pr:text-sm pr:focus:ring-2 pr:focus:ring-blue-500 pr:focus:border-blue-500"
                    disabled={!hasAccess}
                  />
                  <p className="pr:mt-1 pr:text-xs pr:text-gray-500">
                    {__('Comma-separated list of parameters to keep (e.g., ad tracking parameters). These won\'t be removed.', 'prorank-seo')}
                  </p>
                </div>
              </div>

          </Card>

          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <AdjustmentsHorizontalIcon className="pr:w-5 pr:h-5 pr:text-indigo-500" />
                {__('URL Structure', 'prorank-seo')}
                <Badge variant="primary" size="sm">5</Badge>
              </h3>

              <div className={`pr:space-y-5 pr:transition-all pr:duration-300`}>
                <Toggle
                  label={__('Force Trailing Slash', 'prorank-seo')}
                  helpText={__(
                    'Ensure all URLs end with a trailing slash (e.g., /blog/ instead of /blog)',
                    'prorank-seo'
                  )}
                  checked={settings.force_trailing_slash || false}
                  onChange={(checked) => handleSettingChange('force_trailing_slash', checked)}
                  disabled={!hasAccess || settings.remove_trailing_slash}
                />

                <Toggle
                  label={__('Remove Trailing Slash', 'prorank-seo')}
                  helpText={__(
                    'Remove trailing slashes from all URLs (e.g., /blog instead of /blog/)',
                    'prorank-seo'
                  )}
                  checked={settings.remove_trailing_slash || false}
                  onChange={(checked) => handleSettingChange('remove_trailing_slash', checked)}
                  disabled={!hasAccess || settings.force_trailing_slash}
                />

                <Toggle
                  label={__('Convert to Lowercase', 'prorank-seo')}
                  helpText={__(
                    'Automatically convert URLs to lowercase to prevent duplicate content issues',
                    'prorank-seo'
                  )}
                  checked={settings.convert_to_lowercase || false}
                  onChange={(checked) => handleSettingChange('convert_to_lowercase', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Normalize Internal Archive Links', 'prorank-seo')}
                  helpText={__(
                    'Fix same-site author, date, category, and tag archive links in rendered HTML so they match your site\'s trailing-slash format.',
                    'prorank-seo'
                  )}
                  checked={settings.normalize_internal_archive_links || false}
                  onChange={(checked) => handleSettingChange('normalize_internal_archive_links', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Remove Stop Words', 'prorank-seo')}
                  helpText={__(
                    'Remove common stop words (a, an, the, etc.) from new post slugs for cleaner URLs',
                    'prorank-seo'
                  )}
                  checked={settings.remove_stop_words || false}
                  onChange={(checked) => handleSettingChange('remove_stop_words', checked)}
                  disabled={!hasAccess}
                />
              </div>

          </Card>

          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <PhotoIcon className="pr:w-5 pr:h-5 pr:text-pink-500" />
                {__('Attachment Pages', 'prorank-seo')}
              </h3>

              <div className="pr:transition-all pr:duration-300">
                <Radio
                  label={__('Redirect Attachment Pages', 'prorank-seo')}
                  help={__('Choose how to handle media attachment pages', 'prorank-seo')}
                  selected={settings.attachment_redirect || 'off'}
                  options={[
                    {
                      label: __('Disabled', 'prorank-seo'),
                      value: 'off',
                    },
                    {
                      label: __('Redirect to Parent Post', 'prorank-seo'),
                      value: 'parent',
                    },
                    {
                      label: __('Redirect to Media File', 'prorank-seo'),
                      value: 'file',
                    },
                  ]}
                  onChange={(value) => handleSettingChange('attachment_redirect', value)}
                  disabled={!hasAccess}
                />
              </div>

          </Card>

          {/* Archive Pages Section */}
          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <FolderIcon className="pr:w-5 pr:h-5 pr:text-teal-500" />
                {__('Archive Pages', 'prorank-seo')}
              </h3>
              <Text className="pr:mb-4 pr:text-gray-600">
                {__('Control how author and date archive pages are handled for better SEO.', 'prorank-seo')}
              </Text>

              <div className="pr:transition-all pr:duration-300">
                <div className="pr:mb-6">
                  <Radio
                    label={__('Author Archives', 'prorank-seo')}
                    help={__('Control author archive page behavior', 'prorank-seo')}
                    selected={settings.author_archive_handling || 'default'}
                    options={[
                      {
                        label: __('Default (Keep Enabled)', 'prorank-seo'),
                        value: 'default',
                      },
                      {
                        label: __('Disable & Redirect to Homepage', 'prorank-seo'),
                        value: 'redirect_home',
                      },
                      {
                        label: __('Disable & Return 404', 'prorank-seo'),
                        value: 'disable_404',
                      },
                      {
                        label: __('Add noindex (Keep but Hide from Search)', 'prorank-seo'),
                        value: 'noindex',
                      },
                    ]}
                    onChange={(value) => handleSettingChange('author_archive_handling', value)}
                    disabled={!hasAccess}
                  />
                </div>

                <Radio
                  label={__('Date Archives', 'prorank-seo')}
                  help={__('Control date-based archive page behavior', 'prorank-seo')}
                  selected={settings.date_archive_handling || 'default'}
                  options={[
                    {
                      label: __('Default (Keep Enabled)', 'prorank-seo'),
                      value: 'default',
                    },
                    {
                      label: __('Disable & Redirect to Homepage', 'prorank-seo'),
                      value: 'redirect_home',
                    },
                    {
                      label: __('Disable & Return 404', 'prorank-seo'),
                      value: 'disable_404',
                    },
                    {
                      label: __('Add noindex (Keep but Hide from Search)', 'prorank-seo'),
                      value: 'noindex',
                    },
                  ]}
                  onChange={(value) => handleSettingChange('date_archive_handling', value)}
                  disabled={!hasAccess}
                />

                <div className="pr:mt-6">
                  <Radio
                    label={__('Rendered Author/Date Links', 'prorank-seo')}
                    help={__('Choose how same-site author and date archive links should behave in rendered HTML. Useful when those archives are noindexed or disabled.', 'prorank-seo')}
                    selected={settings.author_date_archive_link_policy || 'default'}
                    options={[
                      {
                        label: __('Leave Links Unchanged', 'prorank-seo'),
                        value: 'default',
                      },
                      {
                        label: __('Add nofollow to Rendered Links', 'prorank-seo'),
                        value: 'nofollow',
                      },
                      {
                        label: __('Remove Rendered Links but Keep Text', 'prorank-seo'),
                        value: 'remove',
                      },
                    ]}
                    onChange={(value) => handleSettingChange('author_date_archive_link_policy', value)}
                    disabled={!hasAccess}
                  />
                </div>
              </div>

          </Card>

          {/* Head Cleanup Section */}
          <Card className="pr:transition-all pr:duration-300 pr:hover:shadow-lg">
              <h3 className="pr:flex pr:items-center pr:gap-2">
                <DocumentTextIcon className="pr:w-5 pr:h-5 pr:text-emerald-500" />
                {__('Head Cleanup', 'prorank-seo')}
                <Badge variant="success" size="sm">5</Badge>
              </h3>
              <Text className="pr:mb-4 pr:text-gray-600">
                {__('Clean up unnecessary elements from the HTML head section to improve performance and security.', 'prorank-seo')}
              </Text>

              <div className={`pr:space-y-5 pr:transition-all pr:duration-300`}>
                <Toggle
                  label={__('Remove Query Strings', 'prorank-seo')}
                  helpText={__(
                    'Remove version query strings (?ver=x.x.x) from static assets like CSS and JS files. Improves caching efficiency.',
                    'prorank-seo'
                  )}
                  checked={settings.remove_query_strings || false}
                  onChange={(checked) => handleSettingChange('remove_query_strings', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Remove Feed Links', 'prorank-seo')}
                  helpText={__(
                    'Remove RSS and Atom feed discovery links from the HTML head. Useful if you don\'t use feeds.',
                    'prorank-seo'
                  )}
                  checked={settings.remove_feed_links || false}
                  onChange={(checked) => handleSettingChange('remove_feed_links', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Remove Shortlink', 'prorank-seo')}
                  helpText={__(
                    'Remove the WordPress shortlink (/?p=123) from the HTML head section.',
                    'prorank-seo'
                  )}
                  checked={settings.remove_shortlink || false}
                  onChange={(checked) => handleSettingChange('remove_shortlink', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Remove REST API Links', 'prorank-seo')}
                  helpText={__(
                    'Remove REST API discovery links from the HTML head. May improve security by hiding API endpoints.',
                    'prorank-seo'
                  )}
                  checked={settings.remove_rest_api_links || false}
                  onChange={(checked) => handleSettingChange('remove_rest_api_links', checked)}
                  disabled={!hasAccess}
                />

                <Toggle
                  label={__('Clean Permalinks', 'prorank-seo')}
                  helpText={__(
                    'Remove default WordPress permalink structure references from the HTML head.',
                    'prorank-seo'
                  )}
                  checked={settings.clean_permalinks || false}
                  onChange={(checked) => handleSettingChange('clean_permalinks', checked)}
                  disabled={!hasAccess}
                />
              </div>
          </Card>

          {/* Progressive Onboarding Hint */}
          <div className="prorank-onboarding-hint pr:transition-all pr:duration-300">
            <Text>
              <strong>{__('Pro Tip:', 'prorank-seo')}</strong>{' '}
              {__(
                "These cleanup features help improve your site's URL structure and prevent duplicate content issues. Start with attachment redirects for immediate SEO benefits.",
                'prorank-seo'
              )}
            </Text>
          </div>
        </div>
      ),
    },
    {
      name: 'tools',
      title: (
        <span className="pr:flex pr:items-center pr:gap-2">
          <WrenchScrewdriverIcon className="pr:w-4 pr:h-4" />
          {__('Tools', 'prorank-seo')}
        </span>
      ),
      content: (
        <div className="prorank-url-tools pr:space-y-6 pr:transition-all pr:duration-300">
          {/* URL Test Tool */}
          <Card>

              <h3>{__('URL Test & Preview', 'prorank-seo')}</h3>
              <Text className="pr:text-gray-600 pr:mb-4">
                {__('Test how your URL cleanup settings will affect a specific URL.', 'prorank-seo')}
              </Text>

              <div className="">
                <div className="pr:flex pr:gap-3 pr:mb-4">
                  <div className="pr:flex-1">
                    <input
                      type="text"
                      value={testUrl}
                      onChange={(e) => setTestUrl(e.target.value)}
                      placeholder={__('Enter a URL to test (e.g., /my-page/)', 'prorank-seo')}
                      className="pr:w-full pr:px-4 pr:py-2 pr:border pr:border-gray-300 pr:rounded-lg pr:focus:ring-2 pr:focus:ring-orange-500 pr:focus:border-orange-500"
                      disabled={!hasAccess}
                    />
                    {testUrl && (
                      <div className="pr:mt-2 pr:flex pr:items-center pr:gap-2">
                        <span className="pr:text-sm pr:text-gray-500">
                          {__('Length:', 'prorank-seo')} {testUrl.length} {__('characters', 'prorank-seo')}
                        </span>
                        {(() => {
                          const status = getUrlLengthStatus(testUrl);
                          if (status.status === 'neutral') return null;
                          return (
                            <Badge style={{ backgroundColor: status.color, color: '#fff' }}>
                              {status.label}
                            </Badge>
                          );
                        })()}
                      </div>
                    )}
                  </div>
                  <Button
                    variant="primary"
                    onClick={handleTestUrl}
                    disabled={!hasAccess || !testUrl.trim() || testing}
                  >
                    {testing ? __('Testing...', 'prorank-seo') : __('Test URL', 'prorank-seo')}
                  </Button>
                </div>

                {testResult && (
                  <div className="pr:bg-gray-50 pr:rounded-lg pr:p-4">
                    <div className="pr:grid pr:grid-cols-2 pr:gap-4">
                      <div>
                        <Text className="pr:text-sm pr:font-medium pr:text-gray-500 pr:mb-1">
                          {__('Original URL', 'prorank-seo')}
                        </Text>
                        <code className="pr:block pr:bg-white pr:px-3 pr:py-2 pr:rounded-xs pr:border pr:text-sm">
                          {testResult.original}
                        </code>
                      </div>
                      <div>
                        <Text className="pr:text-sm pr:font-medium pr:text-gray-500 pr:mb-1">
                          {__('Cleaned URL', 'prorank-seo')}
                        </Text>
                        <code className="pr:block pr:bg-white pr:px-3 pr:py-2 pr:rounded-xs pr:border pr:text-sm pr:text-green-600">
                          {testResult.cleaned}
                        </code>
                      </div>
                    </div>
                    {testResult.changes && testResult.changes.length > 0 && (
                      <div className="pr:mt-4">
                        <Text className="pr:text-sm pr:font-medium pr:text-gray-500 pr:mb-2">
                          {__('Applied Rules', 'prorank-seo')}
                        </Text>
                        <ul className="pr:list-disc pr:ml-5 pr:space-y-1">
                          {testResult.changes.map((change, idx) => (
                            <li key={idx} className="pr:text-sm pr:text-gray-600">{change}</li>
                          ))}
                        </ul>
                      </div>
                    )}
                    {(!testResult.changes || testResult.changes.length === 0) && testResult.original === testResult.cleaned && (
                      <Alert variant="info" className="pr:mt-4">
                        {__('No cleanup rules apply to this URL with current settings.', 'prorank-seo')}
                      </Alert>
                    )}
                  </div>
                )}
              </div>

          </Card>

          {/* Bulk Cleanup Tool */}
          <Card>

              <h3>{__('Bulk URL Cleanup', 'prorank-seo')}</h3>
              <Text className="pr:text-gray-600 pr:mb-4">
                {__('Apply cleanup rules to all existing post and page URLs. This will update slugs based on your current settings.', 'prorank-seo')}
              </Text>

              <Alert variant="warning" className="pr:mb-4">
                <strong>{__('Caution:', 'prorank-seo')}</strong>{' '}
                {__('This operation will modify existing URLs. Redirects will be created automatically, but you should backup your database first.', 'prorank-seo')}
              </Alert>

              <div className="">
                <Button
                  variant="secondary"
                  onClick={handleBulkCleanup}
                  disabled={!hasAccess || bulkCleaning}
                >
                  {bulkCleaning ? __('Processing...', 'prorank-seo') : __('Run Bulk Cleanup', 'prorank-seo')}
                </Button>
              </div>

          </Card>

        </div>
      ),
    },
    {
      name: 'help',
      title: (
        <span className="pr:flex pr:items-center pr:gap-2">
          <QuestionMarkCircleIcon className="pr:w-4 pr:h-4" />
          {__('Help', 'prorank-seo')}
        </span>
      ),
      content: (
        <div className="prorank-settings-help pr:transition-all pr:duration-300">
          <Card>

              <h3>{__('About URL Cleanup', 'prorank-seo')}</h3>
              <Text>
                {__(
                  'Clean URLs are important for both SEO and user experience. This module helps you:',
                  'prorank-seo'
                )}
              </Text>

              <ul className="pr:ml-5 pr:list-disc pr:mt-2 pr:space-y-1">
                <li>{__('Create cleaner, more memorable category URLs', 'prorank-seo')}</li>
                <li>{__('Prevent duplicate content from comment reply links', 'prorank-seo')}</li>
                <li>{__('Control how media attachment pages are handled', 'prorank-seo')}</li>
                <li>{__('Normalize permalink structure and reduce duplicate URL variants', 'prorank-seo')}</li>
                <li>{__('Manage author and date archive pages', 'prorank-seo')}</li>
              </ul>

              <h3 className="pr:mt-4">{__('Best Practices', 'prorank-seo')}</h3>

              <Text>
                <strong>{__('Category Base Removal:', 'prorank-seo')}</strong>
                <br />
                {__(
                  "Only enable this if you're prepared to update internal links and monitor for issues. The plugin will automatically redirect old URLs.",
                  'prorank-seo'
                )}
              </Text>

              <Text className="pr:mt-2">
                <strong>{__('Attachment Redirects:', 'prorank-seo')}</strong>
                <br />
                {__(
                  'Redirecting to parent posts is recommended for most sites. This prevents thin content pages and consolidates link equity.',
                  'prorank-seo'
                )}
              </Text>

              <Text className="pr:mt-2">
                <strong>{__('404 Monitoring:', 'prorank-seo')}</strong>
                <br />
                {__(
                  'Use Redirect Manager for 404 monitoring and redirect workflows. URL Cleanup focuses only on permalink and parameter normalization.',
                  'prorank-seo'
                )}
              </Text>

              <Text className="pr:mt-2">
                <strong>{__('Archive Pages:', 'prorank-seo')}</strong>
                <br />
                {__(
                  'Consider disabling author archives for single-author sites, and date archives if they provide no value. This reduces thin content and focuses crawl budget.',
                  'prorank-seo'
                )}
              </Text>

              <Text className="pr:mt-2">
                <strong>{__('URL Length:', 'prorank-seo')}</strong>
                <br />
                {__(
                  'Keep URLs under 60 characters for optimal SEO. URLs between 60-75 characters are acceptable, but over 75 may be truncated in search results.',
                  'prorank-seo'
                )}
              </Text>

              <div className="prorank-help-links pr:mt-4">
                <Button variant="link" href="https://prorank.io/docs/url-cleanup">
                  {__('View Documentation', 'prorank-seo')}
                </Button>
              </div>

          </Card>
        </div>
      ),
    },
  ];

  if (loading) {
    return (
      <div className="prorank-settings-loading pr:transition-all pr:duration-300">
        <p>{__('Loading settings...', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-url-cleanup-settings">
      {/* Stats Dashboard Header */}
      <StatsDashboard />

      <Tabs className="prorank-settings-tabs" activeClass="is-active" tabs={tabs}>
        {(tab) => <div className="pr:transition-all pr:duration-300">{tab.content}</div>}
      </Tabs>

      <div className="prorank-settings-footer pr:transition-all pr:duration-300">
        <Button
          variant="primary"
          onClick={handleSave}
          loading={saving}
          disabled={saving || !hasChanges || !hasAccess}
        >
          {saving ? __('Saving...', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
        </Button>

        {hasChanges && (
          <Text className="prorank-unsaved-notice pr:ml-3">
            {__('You have unsaved changes', 'prorank-seo')}
          </Text>
        )}
      </div>
    </div>
  );
};

export default UrlCleanupSettings;
