/**
 * Meta Tab Content Component
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import {
  TextControl,
  TextareaControl,
  CheckboxControl,
  Spinner,
  Button,
  Popover,
  Card,
  CardBody,
  Flex,
} from '@wordpress/components';
import { useState, useEffect, useCallback, useMemo, useRef } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { analyzeFocusKeyword, analyzeAllKeywords } from '../shared/focusKeywordAnalysis';
import {
  isElementorEditor,
  getElementorContent,
  getElementorTitle,
  getElementorPermalink,
  subscribeToElementorChanges,
} from '../shared/elementorContentBridge';
import {
  isDiviEditor,
  getDiviContent,
  getDiviTitle,
  getDiviPermalink,
  subscribeToDiviChanges,
} from '../shared/diviContentBridge';
import {
  isBeaverBuilderEditor,
  getBeaverBuilderContent,
  getBeaverBuilderTitle,
  getBeaverBuilderPermalink,
  subscribeToBeaverBuilderChanges,
} from '../shared/beaverBuilderContentBridge';

// Access lodash from WordPress global
const { debounce } = window.lodash || { debounce: (fn) => fn };
const PRORANK_EDITOR_META_SYNC_EVENT = 'prorank:editor-meta-sync';

// Import components
import SERPPreview from './components/SERPPreview';
import CharacterCounter from './components/CharacterCounter';

const slugifyPreviewSegment = (value = '') => (
  value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
);

const normalizePreviewUrl = (url = '', title = '') => {
  if (!url || /\?p=\d+/i.test(url)) {
    const slug = slugifyPreviewSegment(title);
    return slug ? `${window.location.origin}/${slug}/` : '';
  }

  return url;
};

const extractPreviewDescription = (value = '') => {
  if (!value) {
    return '';
  }

  const container = document.createElement('div');
  container.innerHTML = value;

  const text = (container.textContent || container.innerText || '')
    .replace(/\s+/g, ' ')
    .trim();

  if (/^(welcome to wordpress\.\s*)?this is your first post\.\s*edit or delete it,\s*then start writing!?$/i.test(text)) {
    return '';
  }

  return text;
};

const MetaTabContent = ({ postId }) => {
  // State for form fields
  const [seoTitle, setSeoTitle] = useState('');
  const [seoDescription, setSeoDescription] = useState('');
  const [focusKeywords, setFocusKeywords] = useState([]);
  const [focusKeywordsLimit, setFocusKeywordsLimit] = useState(3);
  const [newKeywordInput, setNewKeywordInput] = useState('');
  const [canonicalUrl, setCanonicalUrl] = useState('');
  const [sitemapPriorityOverride, setSitemapPriorityOverride] = useState('');
  const [metaRobots, setMetaRobots] = useState([]);

  // State for UI
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [saveError, setSaveError] = useState(null);
  const [defaults, setDefaults] = useState({ title: '', url: '', description: '' });
  const [editorSnapshot, setEditorSnapshot] = useState({ title: '', content: '', url: '' });

  // AI suggestion states
  const [showTitleSuggestions, setShowTitleSuggestions] = useState(false);
  const [showDescSuggestions, setShowDescSuggestions] = useState(false);
  const [showKeywordSuggestions, setShowKeywordSuggestions] = useState(false);
  const [titleSuggestions, setTitleSuggestions] = useState([]);
  const [descSuggestions, setDescSuggestions] = useState([]);
  const [keywordSuggestions, setKeywordSuggestions] = useState([]);
  const [isLoadingAI, setIsLoadingAI] = useState(false);
  const [isLoadingKeywordAI, setIsLoadingKeywordAI] = useState(false);
  const [aiError, setAiError] = useState(null);
  const closeMetaSuggestionPopovers = useCallback(() => {
    setShowTitleSuggestions(false);
    setShowDescSuggestions(false);
  }, []);
  const primaryKeyword = useMemo(() => {
    const primary = focusKeywords.find(kw => kw.primary);
    return primary ? primary.keyword : (focusKeywords[0]?.keyword || '');
  }, [focusKeywords]);

  const analysisContext = useMemo(() => ({
    title: editorSnapshot.title || defaults.title,
    seoTitle,
    description: seoDescription,
    url: canonicalUrl || defaults.url,
    content: editorSnapshot.content,
  }), [editorSnapshot.title, editorSnapshot.content, defaults.title, defaults.url, seoTitle, seoDescription, canonicalUrl]);

  const multiKeywordAnalysis = useMemo(
    () => analyzeAllKeywords(focusKeywords, analysisContext),
    [focusKeywords, analysisContext]
  );

  // Primary keyword analysis — used for the detailed 7-check card.
  const focusKeywordAnalysis = multiKeywordAnalysis.primary || analyzeFocusKeyword({ keyword: '', ...analysisContext });

  const focusKeywordChecks = useMemo(
    () => [
      {
        key: 'title',
        label: __('Keyword in SEO title', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.title,
      },
      {
        key: 'description',
        label: __('Keyword in meta description', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.description,
      },
      {
        key: 'url',
        label: __('Keyword in URL', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.url,
      },
      {
        key: 'firstParagraph',
        label: __('Keyword in first paragraph', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.firstParagraph,
      },
      {
        key: 'headings',
        label: __('Keyword in headings', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.headings,
      },
      {
        key: 'density',
        label: __('Keyword density looks natural', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.density,
      },
      {
        key: 'imageAlt',
        label: __('Keyword in image alt text', 'prorank-seo'),
        data: focusKeywordAnalysis.checks.imageAlt,
      },
    ],
    [focusKeywordAnalysis.checks]
  );

  // Check if user has AI access (Pro+ tier with premium runtime active)
  const resolvedTier = (
    window.prorankMetaboxData?.licenseTier ||
    window.prorankSettings?.license?.tier ||
    'free'
  );
  const normalizedTier = resolvedTier === 'core' ? 'pro' : resolvedTier;
  const isPremiumRuntimeActive = Boolean(
    window.prorankMetaboxData?.isPremiumActive ??
    window.prorankSettings?.isPremiumActive ??
    false
  );
  const hasAIAccess =
    isPremiumRuntimeActive && ['pro', 'business', 'agency'].includes(normalizedTier);

  // Fetch existing meta data on mount
  useEffect(() => {
    if (!postId) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);

    apiFetch({
      path: `/prorank-seo/v1/meta/${postId}`,
      method: 'GET',
    })
      .then((response) => {
        if (response.success && response.data) {
          setSeoTitle(response.data.seo_title || '');
          setSeoDescription(response.data.seo_description || '');
          if (Array.isArray(response.data.focus_keywords) && response.data.focus_keywords.length > 0) {
            setFocusKeywords(response.data.focus_keywords);
          } else if (response.data.focus_keyword) {
            setFocusKeywords([{ keyword: response.data.focus_keyword, primary: true }]);
          }
          if (response.data.focus_keywords_limit) {
            setFocusKeywordsLimit(response.data.focus_keywords_limit);
          }
          setCanonicalUrl(response.data.canonical_url || '');
          setSitemapPriorityOverride(response.data.sitemap_priority_override || '');
          setMetaRobots(response.data.meta_robots || []);
          setDefaults(response.data.defaults || { title: '', url: '', description: '' });
        }
      })
      .catch(() => {
        setSaveError(__('Failed to load meta data.', 'prorank-seo'));
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [postId]);

  useEffect(() => {
    const getSnapshot = () => {
      // --- Elementor editor ---
      if (isElementorEditor()) {
        const elTitle = getElementorTitle() || defaults.title || '';
        const elUrl = getElementorPermalink() || defaults.url || '';
        return {
          title: elTitle,
          content: getElementorContent() || '',
          url: normalizePreviewUrl(elUrl, elTitle),
        };
      }

      // --- Divi Builder ---
      if (isDiviEditor()) {
        const dvTitle = getDiviTitle() || defaults.title || '';
        const dvUrl = getDiviPermalink() || defaults.url || '';
        return {
          title: dvTitle,
          content: getDiviContent() || '',
          url: normalizePreviewUrl(dvUrl, dvTitle),
        };
      }

      // --- Beaver Builder ---
      if (isBeaverBuilderEditor()) {
        const bbTitle = getBeaverBuilderTitle() || defaults.title || '';
        const bbUrl = getBeaverBuilderPermalink() || defaults.url || '';
        return {
          title: bbTitle,
          content: getBeaverBuilderContent() || '',
          url: normalizePreviewUrl(bbUrl, bbTitle),
        };
      }

      // --- Gutenberg / Block editor ---
      const editor = window.wp?.data?.select?.('core/editor');
      if (editor) {
        const liveTitle = editor.getEditedPostAttribute('title') || defaults.title || '';
        const liveUrl =
          (editor.getPermalink && editor.getPermalink()) ||
          editor.getEditedPostAttribute('link') ||
          editor.getCurrentPost?.()?.link ||
          defaults.url ||
          '';

        return {
          title: liveTitle,
          content: editor.getEditedPostContent() || '',
          url: normalizePreviewUrl(liveUrl, liveTitle),
        };
      }

      // --- Classic editor fallback ---
      const titleInput = document.querySelector('#title');
      const classicEditor = window.tinyMCE?.get?.('content');
      const contentField = document.querySelector('#content');

      return {
        title: titleInput?.value || defaults.title || '',
        content: classicEditor?.getContent?.() || contentField?.value || '',
        url: normalizePreviewUrl(defaults.url || '', titleInput?.value || defaults.title || ''),
      };
    };

    const applySnapshot = () => {
      const next = getSnapshot();
      setEditorSnapshot((prev) => (
        prev.title === next.title && prev.content === next.content && prev.url === next.url ? prev : next
      ));
    };

    applySnapshot();

    let unsubscribe = null;
    let intervalId = null;

    // Detect builder pages from URL before their JS initialises.
    const params = (() => {
      try { return new URLSearchParams(window.location.search); }
      catch { return null; }
    })();
    const onElementorPage = params?.get('action') === 'elementor';
    const onDiviPage = params?.get('et_fb') === '1' || params?.get('et_bfb') === '1';
    const onBeaverBuilderPage = params?.has('fl_builder');

    if (isElementorEditor()) {
      // Elementor fully ready — use event-based subscription
      unsubscribe = subscribeToElementorChanges(applySnapshot);
    } else if (onElementorPage) {
      // Elementor page but JS not ready yet — poll, then upgrade to events
      intervalId = window.setInterval(() => {
        applySnapshot();
        if (isElementorEditor() && !unsubscribe) {
          window.clearInterval(intervalId);
          intervalId = null;
          unsubscribe = subscribeToElementorChanges(applySnapshot);
        }
      }, 1000);
    } else if (isDiviEditor()) {
      // Divi fully ready — use event-based subscription
      unsubscribe = subscribeToDiviChanges(applySnapshot);
    } else if (onDiviPage) {
      // Divi VB page but JS not ready yet — poll, then upgrade to events
      intervalId = window.setInterval(() => {
        applySnapshot();
        if (isDiviEditor() && !unsubscribe) {
          window.clearInterval(intervalId);
          intervalId = null;
          unsubscribe = subscribeToDiviChanges(applySnapshot);
        }
      }, 1000);
    } else if (isBeaverBuilderEditor()) {
      unsubscribe = subscribeToBeaverBuilderChanges(applySnapshot);
    } else if (onBeaverBuilderPage) {
      intervalId = window.setInterval(() => {
        applySnapshot();
        if (isBeaverBuilderEditor() && !unsubscribe) {
          window.clearInterval(intervalId);
          intervalId = null;
          unsubscribe = subscribeToBeaverBuilderChanges(applySnapshot);
        }
      }, 1000);
    } else if (window.wp?.data?.subscribe && window.wp?.data?.select?.('core/editor')) {
      unsubscribe = window.wp.data.subscribe(applySnapshot);
    } else {
      intervalId = window.setInterval(applySnapshot, 1000);
    }

    return () => {
      if (typeof unsubscribe === 'function') {
        unsubscribe();
      }
      if (intervalId) {
        window.clearInterval(intervalId);
      }
    };
  }, [defaults.title, defaults.url]);

  const previewTitle = seoTitle || editorSnapshot.title || defaults.title;
  const previewUrl =
    canonicalUrl ||
    normalizePreviewUrl(editorSnapshot.url || defaults.url, editorSnapshot.title || defaults.title);
  const previewDescription =
    seoDescription ||
    extractPreviewDescription(editorSnapshot.content) ||
    defaults.description ||
    '';

  useEffect(() => {
    if (!postId) {
      return;
    }

    window.dispatchEvent(new CustomEvent(PRORANK_EDITOR_META_SYNC_EVENT, {
      detail: {
        postId,
        seoTitle,
        seoDescription,
        canonicalUrl,
        focusKeywords,
      },
    }));
  }, [postId, seoTitle, seoDescription, canonicalUrl, focusKeywords]);

  // Ref keeps latest field values so the debounced save never fires stale data.
  const metaStateRef = useRef({});
  metaStateRef.current = { seoTitle, seoDescription, focusKeywords, canonicalUrl, sitemapPriorityOverride, metaRobots };

  // Create save function — reads from ref, so callback is stable (postId-only dep).
  const saveMetaDataImpl = useCallback(
    (data) => {
      if (!postId) return;

      setIsSaving(true);
      setSaveError(null);

      const s = metaStateRef.current;
      apiFetch({
        path: `/prorank-seo/v1/meta/${postId}`,
        method: 'POST',
        data: {
          seo_title: s.seoTitle,
          seo_description: s.seoDescription,
          focus_keywords: s.focusKeywords,
          canonical_url: s.canonicalUrl,
          sitemap_priority_override: s.sitemapPriorityOverride,
          meta_robots: s.metaRobots,
          ...data,
        },
      })
        .then((response) => {
          if (!response.success) {
            throw new Error(response.message || __('Save failed', 'prorank-seo'));
          }
          // Reconcile: apply server-normalized keywords back to local state.
          if (Array.isArray(response.data?.focus_keywords)) {
            setFocusKeywords(response.data.focus_keywords);
          }
        })
        .catch((error) => {
          setSaveError(error.message || __('Failed to save changes.', 'prorank-seo'));
        })
        .finally(() => {
          setIsSaving(false);
        });
    },
    [postId]
  );

  // Stable debounced save — created once per postId, old timers cancelled on unmount.
  const saveMetaData = useMemo(() => debounce(saveMetaDataImpl, 500), [saveMetaDataImpl]);
  useEffect(() => () => { if (saveMetaData.cancel) saveMetaData.cancel(); }, [saveMetaData]);

  // Generate AI suggestions for meta title/description and only open the requested popover.
  const generateAISuggestions = useCallback(async (target) => {
    if (!postId || !hasAIAccess) return;

    setIsLoadingAI(true);
    setAiError(null);
    closeMetaSuggestionPopovers();

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/ai/suggest-meta/${postId}`,
        method: 'POST',
      });

      if (response.success && response.data?.suggestions) {
        const suggestions = response.data.suggestions;

        if (suggestions.titles) {
          setTitleSuggestions(suggestions.titles);
        }

        if (suggestions.descriptions) {
          setDescSuggestions(suggestions.descriptions);
        }

        if (target === 'title' && suggestions.titles?.length) {
          setShowTitleSuggestions(true);
        } else if (target === 'description' && suggestions.descriptions?.length) {
          setShowDescSuggestions(true);
        }
      }
    } catch (error) {
      setAiError(error.message || __('Failed to generate AI suggestions.', 'prorank-seo'));
    } finally {
      setIsLoadingAI(false);
    }
  }, [postId, hasAIAccess, closeMetaSuggestionPopovers]);

  // Generate AI keyword suggestions
  const generateKeywordSuggestions = useCallback(async () => {
    if (!postId || !hasAIAccess) return;

    setIsLoadingKeywordAI(true);
    setAiError(null);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/ai/suggest-keywords/${postId}`,
        method: 'POST',
      });

      if (response.success && response.data?.suggestions) {
        setKeywordSuggestions(response.data.suggestions);
        setShowKeywordSuggestions(true);
      }
    } catch (error) {
      setAiError(error.message || __('Failed to generate keyword suggestions.', 'prorank-seo'));
    } finally {
      setIsLoadingKeywordAI(false);
    }
  }, [postId, hasAIAccess]);

  // Handle field changes
  const handleTitleChange = useCallback(
    (value) => {
      setSeoTitle(value);
      saveMetaData({ seo_title: value });
    },
    [saveMetaData]
  );

  const handleDescriptionChange = useCallback(
    (value) => {
      setSeoDescription(value);
      saveMetaData({ seo_description: value });
    },
    [saveMetaData]
  );

  const addKeyword = useCallback(
    (keyword) => {
      const trimmed = (typeof keyword === 'string' ? keyword : '').trim();
      if (!trimmed || focusKeywords.length >= focusKeywordsLimit) return;
      const lower = trimmed.toLowerCase();
      if (focusKeywords.some(kw => kw.keyword.toLowerCase() === lower)) return;
      const isPrimary = focusKeywords.length === 0;
      const next = [...focusKeywords, { keyword: trimmed, primary: isPrimary }];
      setFocusKeywords(next);
      setNewKeywordInput('');
      saveMetaData({ focus_keywords: next });
    },
    [focusKeywords, focusKeywordsLimit, saveMetaData]
  );

  const removeKeyword = useCallback(
    (index) => {
      const next = [...focusKeywords];
      const wasPrimary = next[index].primary;
      next.splice(index, 1);
      if (wasPrimary && next.length > 0) {
        next[0].primary = true;
      }
      setFocusKeywords(next);
      saveMetaData({ focus_keywords: next });
    },
    [focusKeywords, saveMetaData]
  );

  const setPrimaryKeyword = useCallback(
    (index) => {
      const next = focusKeywords.map((kw, i) => ({ ...kw, primary: i === index }));
      setFocusKeywords(next);
      saveMetaData({ focus_keywords: next });
    },
    [focusKeywords, saveMetaData]
  );

  const moveKeyword = useCallback(
    (fromIndex, direction) => {
      const toIndex = fromIndex + direction;
      if (toIndex < 0 || toIndex >= focusKeywords.length) return;
      const next = [...focusKeywords];
      const [moved] = next.splice(fromIndex, 1);
      next.splice(toIndex, 0, moved);
      setFocusKeywords(next);
      saveMetaData({ focus_keywords: next });
    },
    [focusKeywords, saveMetaData]
  );

  const handleCanonicalChange = useCallback(
    (value) => {
      setCanonicalUrl(value);
      saveMetaData({ canonical_url: value });
    },
    [saveMetaData]
  );

  const handleSitemapPriorityOverrideChange = useCallback(
    (value) => {
      setSitemapPriorityOverride(value);
      saveMetaData({ sitemap_priority_override: value });
    },
    [saveMetaData]
  );

  const handleRobotsChange = useCallback(
    (directive, checked) => {
      const newRobots =
        checked === true ? [...metaRobots, directive] : metaRobots.filter((r) => r !== directive);

      setMetaRobots(newRobots);
      saveMetaData({ meta_robots: newRobots });
    },
    [metaRobots, saveMetaData]
  );

  if (isLoading) {
    return (
      <div className="prorank-meta-tab-loading">
        <Spinner />
        <span>{__('Loading meta data…', 'prorank-seo')}</span>
      </div>
    );
  }

  return (
    <div className="prorank-meta-tab-content">
      {/* SERP Preview - Moved to top */}
      <div className="prorank-field-group prorank-field-group--preview">
        <h3>{__('Google Search Preview', 'prorank-seo')}</h3>
        <SERPPreview
          title={previewTitle}
          url={previewUrl}
          description={previewDescription}
        />
      </div>

      {/* SEO Title */}
      <div className="prorank-field-group">
        <div className="prorank-field-with-ai">
          <TextControl
            label={
              <Flex gap={2}>
                <span>{__('SEO Title', 'prorank-seo')}</span>
                {hasAIAccess && (
                  <Button
                    variant="tertiary"
                    size="small"
                    icon={window.wp?.icons?.starFilled}
                    onClick={() => generateAISuggestions('title')}
                    disabled={isLoadingAI}
                    title={__('Generate AI suggestions', 'prorank-seo')}
                  >
                    {__('AI Suggest', 'prorank-seo')}
                  </Button>
                )}
              </Flex>
            }
            value={seoTitle}
            onChange={handleTitleChange}
            help={__(
              'Optimal length: 50-60 characters. This will override the default post title in search results.',
              'prorank-seo'
            )}
            placeholder={editorSnapshot.title || defaults.title || __('Enter SEO title…', 'prorank-seo')}
            __nextHasNoMarginBottom={true}
            __next40pxDefaultSize={true}
          />
          {showTitleSuggestions && titleSuggestions.length > 0 && (
            <Popover
              position="bottom center"
              onClose={() => setShowTitleSuggestions(false)}
              className="prorank-ai-suggestions-popover"
              noArrow={false}
            >
              <Card size="small" className="prorank-ai-suggestions prorank-ai-suggestions--list">
                <CardBody>
                  <div className="prorank-ai-suggestions__header">
                    <div>
                      <h4>{__('AI Title Suggestions', 'prorank-seo')}</h4>
                      <p className="prorank-ai-helper-text">
                        {__('Pick a suggestion to replace the current SEO title.', 'prorank-seo')}
                      </p>
                    </div>
                    <span className="prorank-ai-suggestions__count">
                      {`${titleSuggestions.length} ${__('ideas', 'prorank-seo')}`}
                    </span>
                  </div>
                  <div className="prorank-ai-suggestions__body">
                    <div className="prorank-ai-suggestion-list">
                    {titleSuggestions.map((suggestion, index) => (
                      <Button
                        key={index}
                        variant="secondary"
                        onClick={() => {
                          handleTitleChange(suggestion);
                          setShowTitleSuggestions(false);
                        }}
                        className="prorank-ai-suggestion-list-button"
                      >
                        {suggestion}
                      </Button>
                    ))}
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Popover>
          )}
        </div>
        <CharacterCounter
          value={previewTitle}
          recommended={60}
          minimum={30}
          type="title"
        />
      </div>

      {/* Meta Description */}
      <div className="prorank-field-group">
        <div className="prorank-field-with-ai">
          <TextareaControl
            label={
              <Flex gap={2}>
                <span>{__('Meta Description', 'prorank-seo')}</span>
                {hasAIAccess && (
                  <Button
                    variant="tertiary"
                    size="small"
                    icon={window.wp?.icons?.starFilled}
                    onClick={() => generateAISuggestions('description')}
                    disabled={isLoadingAI}
                    title={__('Generate AI suggestions', 'prorank-seo')}
                  >
                    {__('AI Suggest', 'prorank-seo')}
                  </Button>
                )}
              </Flex>
            }
            value={seoDescription}
            onChange={handleDescriptionChange}
            help={__(
              'Optimal length: 150-160 characters. This appears below the title in search results.',
              'prorank-seo'
            )}
            placeholder={__('Enter meta description…', 'prorank-seo')}
            rows={3}
            __nextHasNoMarginBottom={true}
          />
          {showDescSuggestions && descSuggestions.length > 0 && (
            <Popover
              position="bottom center"
              onClose={() => setShowDescSuggestions(false)}
              className="prorank-ai-suggestions-popover"
              noArrow={false}
            >
              <Card size="small" className="prorank-ai-suggestions prorank-ai-suggestions--list">
                <CardBody>
                  <div className="prorank-ai-suggestions__header">
                    <div>
                      <h4>{__('AI Description Suggestions', 'prorank-seo')}</h4>
                      <p className="prorank-ai-helper-text">
                        {__('Pick a suggestion to replace the current meta description.', 'prorank-seo')}
                      </p>
                    </div>
                    <span className="prorank-ai-suggestions__count">
                      {`${descSuggestions.length} ${__('ideas', 'prorank-seo')}`}
                    </span>
                  </div>
                  <div className="prorank-ai-suggestions__body">
                    <div className="prorank-ai-suggestion-list">
                    {descSuggestions.map((suggestion, index) => (
                      <Button
                        key={index}
                        variant="secondary"
                        onClick={() => {
                          handleDescriptionChange(suggestion);
                          setShowDescSuggestions(false);
                        }}
                        className="prorank-ai-suggestion-list-button"
                      >
                        {suggestion}
                      </Button>
                    ))}
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Popover>
          )}
        </div>
        <CharacterCounter
          value={seoDescription}
          recommended={160}
          minimum={120}
          type="description"
        />
      </div>

      {/* Focus Keywords */}
      <div className="prorank-field-group">
        <div className="prorank-field-with-ai">
          <Flex gap={2} align="center" style={{ marginBottom: '8px' }}>
            <span style={{ fontWeight: 600, fontSize: '13px' }}>
              {__('Focus Keywords', 'prorank-seo')}
            </span>
            <span style={{ fontSize: '12px', color: '#6b7280', padding: '1px 8px', background: '#f3f4f6', borderRadius: '10px' }}>
              {`${focusKeywords.length}/${focusKeywordsLimit}`}
            </span>
            {hasAIAccess && (
              <Button
                variant="tertiary"
                size="small"
                icon={window.wp?.icons?.starFilled}
                onClick={generateKeywordSuggestions}
                disabled={isLoadingKeywordAI}
                title={__('Generate keyword suggestions', 'prorank-seo')}
              >
                {__('AI Suggest', 'prorank-seo')}
              </Button>
            )}
          </Flex>

          <div style={{ display: 'flex', gap: '8px', marginBottom: focusKeywords.length > 0 ? '8px' : '0' }}>
            <div style={{ flex: 1 }}>
              <TextControl
                hideLabelFromVision
                label={__('Add keyword', 'prorank-seo')}
                value={newKeywordInput}
                onChange={setNewKeywordInput}
                placeholder={
                  focusKeywords.length >= focusKeywordsLimit
                    ? __('Keyword limit reached', 'prorank-seo')
                    : __('Enter focus keyword…', 'prorank-seo')
                }
                disabled={focusKeywords.length >= focusKeywordsLimit}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                    addKeyword(newKeywordInput);
                  }
                }}
                __nextHasNoMarginBottom={true}
                __next40pxDefaultSize={true}
              />
            </div>
            <Button
              variant="secondary"
              onClick={() => addKeyword(newKeywordInput)}
              disabled={!newKeywordInput.trim() || focusKeywords.length >= focusKeywordsLimit}
              style={{ height: '40px' }}
            >
              {__('Add', 'prorank-seo')}
            </Button>
          </div>

          {focusKeywords.length > 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', marginBottom: '4px' }}>
              {focusKeywords.map((kw, index) => (
                <div
                  key={index}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '6px 10px',
                    borderRadius: '6px',
                    border: `1px solid ${kw.primary ? '#3b82f6' : '#e5e7eb'}`,
                    background: kw.primary ? '#eff6ff' : '#fff',
                  }}
                >
                  <button
                    type="button"
                    onClick={() => setPrimaryKeyword(index)}
                    aria-label={kw.primary ? __('Primary keyword', 'prorank-seo') : __('Set as primary keyword', 'prorank-seo')}
                    title={kw.primary ? __('Primary keyword', 'prorank-seo') : __('Set as primary', 'prorank-seo')}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '2px', color: kw.primary ? '#2563eb' : '#9ca3af', fontSize: '16px', lineHeight: 1 }}
                  >
                    {kw.primary ? '\u2605' : '\u2606'}
                  </button>
                  <span style={{ flex: 1, fontSize: '13px' }}>{kw.keyword}</span>
                  {focusKeywords.length > 1 && (
                    <>
                      <button
                        type="button"
                        onClick={() => moveKeyword(index, -1)}
                        disabled={index === 0}
                        aria-label={__('Move up', 'prorank-seo')}
                        title={__('Move up', 'prorank-seo')}
                        style={{ background: 'none', border: 'none', cursor: index === 0 ? 'default' : 'pointer', padding: '2px', color: index === 0 ? '#d1d5db' : '#6b7280', fontSize: '11px', lineHeight: 1 }}
                      >
                        {'\u25B2'}
                      </button>
                      <button
                        type="button"
                        onClick={() => moveKeyword(index, 1)}
                        disabled={index === focusKeywords.length - 1}
                        aria-label={__('Move down', 'prorank-seo')}
                        title={__('Move down', 'prorank-seo')}
                        style={{ background: 'none', border: 'none', cursor: index === focusKeywords.length - 1 ? 'default' : 'pointer', padding: '2px', color: index === focusKeywords.length - 1 ? '#d1d5db' : '#6b7280', fontSize: '11px', lineHeight: 1 }}
                      >
                        {'\u25BC'}
                      </button>
                    </>
                  )}
                  <button
                    type="button"
                    onClick={() => removeKeyword(index)}
                    aria-label={__('Remove keyword', 'prorank-seo')}
                    title={__('Remove keyword', 'prorank-seo')}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '2px', color: '#ef4444', fontSize: '13px', lineHeight: 1 }}
                  >
                    {'\u2715'}
                  </button>
                </div>
              ))}
            </div>
          )}

          <p className="components-base-control__help" style={{ marginTop: '4px', marginBottom: 0 }}>
            {focusKeywords.length === 0
              ? __('Add target keywords to optimize your content for specific search terms.', 'prorank-seo')
              : __('Click the star to set a primary keyword. Analysis runs on the primary keyword.', 'prorank-seo')
            }
          </p>

          {showKeywordSuggestions && keywordSuggestions.length > 0 && (
            <Popover
              position="bottom center"
              onClose={() => setShowKeywordSuggestions(false)}
              className="prorank-ai-suggestions-popover"
              noArrow={false}
            >
              <Card size="small" className="prorank-ai-suggestions prorank-keyword-suggestions-popover">
                <CardBody>
                  <div className="prorank-ai-suggestions__header">
                    <div>
                      <h4>{__('AI Keyword Suggestions', 'prorank-seo')}</h4>
                      <p className="prorank-ai-helper-text">
                        {__('Click a keyword to add it:', 'prorank-seo')}
                      </p>
                    </div>
                    <span className="prorank-ai-suggestions__count">
                      {`${keywordSuggestions.length} ${__('ideas', 'prorank-seo')}`}
                    </span>
                  </div>
                  <div className="prorank-ai-suggestions__body">
                    <p className="prorank-ai-suggestions__note">
                      {__('Already-added keywords are disabled.', 'prorank-seo')}
                    </p>
                    <div className="prorank-keyword-suggestions-grid">
                      {keywordSuggestions.map((keyword, index) => (
                        <Button
                          key={index}
                          variant="secondary"
                          onClick={() => {
                            addKeyword(keyword);
                            if (focusKeywords.length + 1 >= focusKeywordsLimit) {
                              setShowKeywordSuggestions(false);
                            }
                          }}
                          className="prorank-keyword-suggestion-button"
                          disabled={focusKeywords.length >= focusKeywordsLimit || focusKeywords.some(kw => kw.keyword.toLowerCase() === keyword.toLowerCase())}
                        >
                          {keyword}
                        </Button>
                      ))}
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Popover>
          )}
        </div>

        <Card size="small" style={{ marginTop: '12px' }}>
          <CardBody>
            {!primaryKeyword ? (
              <p style={{ margin: 0, color: '#6b7280' }}>
                {__('Add a focus keyword to evaluate title, description, URL, paragraph placement, headings, density, and image alt text.', 'prorank-seo')}
              </p>
            ) : (
              <div>
                {/* Aggregate score (shown when multiple keywords) */}
                {multiKeywordAnalysis.secondary.length > 0 && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px', padding: '10px', background: '#f8fafc', borderRadius: '8px', border: '1px solid #e5e7eb' }}>
                    <div
                      style={{
                        width: '44px',
                        height: '44px',
                        borderRadius: '999px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: '13px',
                        fontWeight: 700,
                        color: '#fff',
                        background:
                          multiKeywordAnalysis.aggregate >= 75
                            ? 'linear-gradient(135deg, #3b82f6, #2563eb)'
                            : multiKeywordAnalysis.aggregate >= 50
                              ? 'linear-gradient(135deg, #f59e0b, #d97706)'
                              : 'linear-gradient(135deg, #ef4444, #dc2626)',
                      }}
                    >
                      {multiKeywordAnalysis.aggregate}
                    </div>
                    <div>
                      <div style={{ fontWeight: 600 }}>{__('Overall keyword score', 'prorank-seo')}</div>
                      <div style={{ fontSize: '12px', color: '#6b7280' }}>
                        {`${focusKeywords.length} ${__('keywords', 'prorank-seo')} · ${__('primary 70% + secondary 30%', 'prorank-seo')}`}
                      </div>
                    </div>
                  </div>
                )}

                {/* Primary keyword detail */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>
                  <div
                    style={{
                      width: '44px',
                      height: '44px',
                      borderRadius: '999px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      fontSize: '13px',
                      fontWeight: 700,
                      color: '#fff',
                      background:
                        focusKeywordAnalysis.score >= 75
                          ? 'linear-gradient(135deg, #3b82f6, #2563eb)'
                          : focusKeywordAnalysis.score >= 50
                            ? 'linear-gradient(135deg, #f59e0b, #d97706)'
                            : 'linear-gradient(135deg, #ef4444, #dc2626)',
                    }}
                  >
                    {focusKeywordAnalysis.score}
                  </div>
                  <div>
                    <div style={{ fontWeight: 600 }}>
                      {multiKeywordAnalysis.secondary.length > 0
                        ? `\u2605 "${focusKeywordAnalysis.keyword}"`
                        : __('Focus keyword coverage', 'prorank-seo')
                      }
                    </div>
                    <div style={{ fontSize: '12px', color: '#6b7280' }}>
                      {`${focusKeywordAnalysis.occurrenceCount} ${__('uses', 'prorank-seo')} · ${focusKeywordAnalysis.density.toFixed(2)}% ${__('density', 'prorank-seo')}`}
                    </div>
                  </div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  {focusKeywordChecks.map((check) => {
                    const state = check.data.applicable ? (check.data.passed ? 'pass' : 'fail') : 'na';
                    let meta = '';

                    if (check.key === 'density' && check.data.applicable) {
                      meta = `${focusKeywordAnalysis.density.toFixed(2)}%`;
                    } else if (check.key === 'headings' && check.data.applicable) {
                      meta = `${focusKeywordAnalysis.checks.headings.detail.length} H`;
                    } else if (check.key === 'imageAlt' && check.data.applicable) {
                      meta = `${focusKeywordAnalysis.checks.imageAlt.detail.length} alt`;
                    }

                    return (
                      <div
                        key={check.key}
                        style={{
                          display: 'flex',
                          alignItems: 'flex-start',
                          justifyContent: 'space-between',
                          gap: '8px',
                          padding: '8px 10px',
                          borderRadius: '6px',
                          border: '1px solid #e5e7eb',
                        }}
                      >
                        <div style={{ display: 'flex', gap: '8px', minWidth: 0 }}>
                          <span
                            style={{
                              width: '16px',
                              fontWeight: 700,
                              color: state === 'pass' ? '#2563eb' : state === 'fail' ? '#ef4444' : '#9ca3af',
                            }}
                          >
                            {state === 'pass' ? '\u2713' : state === 'fail' ? '!' : '\u2013'}
                          </span>
                          <span>{check.label}</span>
                        </div>
                        {meta ? (
                          <span style={{ fontSize: '11px', color: '#6b7280', whiteSpace: 'nowrap' }}>{meta}</span>
                        ) : null}
                      </div>
                    );
                  })}
                </div>

                {/* Secondary keyword summaries */}
                {multiKeywordAnalysis.secondary.length > 0 && (
                  <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: '#6b7280' }}>
                      {__('Secondary keywords', 'prorank-seo')}
                    </div>
                    {multiKeywordAnalysis.secondary.map((result, i) => {
                      const passedCount = Object.values(result.checks).filter(c => c.applicable && c.passed).length;
                      const applicableCount = Object.values(result.checks).filter(c => c.applicable).length;
                      return (
                        <div
                          key={i}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: '8px',
                            padding: '6px 10px',
                            borderRadius: '6px',
                            border: '1px solid #e5e7eb',
                          }}
                        >
                          <span
                            style={{
                              width: '28px',
                              height: '28px',
                              borderRadius: '999px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: '11px',
                              fontWeight: 700,
                              color: '#fff',
                              flexShrink: 0,
                              background:
                                result.score >= 75
                                  ? 'linear-gradient(135deg, #3b82f6, #2563eb)'
                                  : result.score >= 50
                                    ? 'linear-gradient(135deg, #f59e0b, #d97706)'
                                    : 'linear-gradient(135deg, #ef4444, #dc2626)',
                            }}
                          >
                            {result.score}
                          </span>
                          <span style={{ flex: 1, fontSize: '13px' }}>{`"${result.keyword}"`}</span>
                          <span style={{ fontSize: '11px', color: '#6b7280', whiteSpace: 'nowrap' }}>
                            {`${passedCount}/${applicableCount} ${__('checks', 'prorank-seo')}`}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}
          </CardBody>
        </Card>
      </div>

      {/* Canonical URL */}
      <div className="prorank-field-group">
        <TextControl
          label={__('Canonical URL', 'prorank-seo')}
          type="url"
          value={canonicalUrl}
          onChange={handleCanonicalChange}
          help={__(
            'The canonical URL helps prevent duplicate content issues. Leave empty to use the default permalink.',
            'prorank-seo'
          )}
            placeholder={previewUrl || __('https://example.com/page', 'prorank-seo')}
          __nextHasNoMarginBottom={true}
          __next40pxDefaultSize={true}
        />
      </div>

      <div className="prorank-field-group">
        <TextControl
          label={__('Sitemap Priority Override', 'prorank-seo')}
          type="number"
          value={sitemapPriorityOverride}
          onChange={handleSitemapPriorityOverrideChange}
          help={__(
            'Override the XML sitemap priority for this page. Leave empty to keep the automatic value. Use a number between 0.0 and 1.0.',
            'prorank-seo'
          )}
          placeholder={__('Automatic', 'prorank-seo')}
          min={0}
          max={1}
          step={0.1}
          __nextHasNoMarginBottom={true}
          __next40pxDefaultSize={true}
        />
      </div>

      {/* Meta Robots */}
      <div className="prorank-field-group">
        <h3>{__('Meta Robots', 'prorank-seo')}</h3>
        <p className="description">
          {__('Control how search engines index and display this content.', 'prorank-seo')}
        </p>

        <CheckboxControl
          label={__('No Index', 'prorank-seo')}
          help={__('Prevent search engines from indexing this page.', 'prorank-seo')}
          checked={metaRobots.includes('noindex')}
          onChange={(checked) => handleRobotsChange('noindex', checked)}
          __nextHasNoMarginBottom={true}
        />

        <CheckboxControl
          label={__('No Follow', 'prorank-seo')}
          help={__('Prevent search engines from following links on this page.', 'prorank-seo')}
          checked={metaRobots.includes('nofollow')}
          onChange={(checked) => handleRobotsChange('nofollow', checked)}
          __nextHasNoMarginBottom={true}
        />

        <CheckboxControl
          label={__('No Archive', 'prorank-seo')}
          help={__('Prevent search engines from showing cached version.', 'prorank-seo')}
          checked={metaRobots.includes('noarchive')}
          onChange={(checked) => handleRobotsChange('noarchive', checked)}
          __nextHasNoMarginBottom={true}
        />

        <CheckboxControl
          label={__('No Snippet', 'prorank-seo')}
          help={__('Prevent search engines from showing text snippets.', 'prorank-seo')}
          checked={metaRobots.includes('nosnippet')}
          onChange={(checked) => handleRobotsChange('nosnippet', checked)}
          __nextHasNoMarginBottom={true}
        />
      </div>

      {/* Save Status */}
      {isSaving === true && (
        <div className="prorank-save-status prorank-save-status--saving">
          <Spinner />
          <span>{__('Saving…', 'prorank-seo')}</span>
        </div>
      )}

      {saveError && (
        <div className="prorank-save-status prorank-save-status--error">
          <span className="dashicons dashicons-warning"></span>
          <span>{saveError}</span>
        </div>
      )}

      {/* AI Status */}
      {isLoadingAI && (
        <div className="prorank-ai-status prorank-ai-status--loading">
          <Spinner />
          <span>{__('Generating AI suggestions…', 'prorank-seo')}</span>
        </div>
      )}

      {aiError && (
        <div className="prorank-ai-status prorank-ai-status--error">
          <span className="dashicons dashicons-warning"></span>
          <span>{aiError}</span>
        </div>
      )}
    </div>
  );
};

export default MetaTabContent;
