/**
 * Content Analysis Panel - Optimized for Narrow Sidebar
 * Vertical stacking, compact design
 */

import { debounce } from 'lodash';
import { analyzeFocusKeyword, analyzeAllKeywords } from '../../shared/focusKeywordAnalysis';

const PRORANK_EDITOR_META_SYNC_EVENT = 'prorank:editor-meta-sync';

const DEFAULT_CONTENT_ANALYSIS_SETTINGS = {
  enabled: true,
  autoAnalyze: true,
  focusKeywordEnabled: true,
  seoScoreEnabled: true,
  readabilityEnabled: true,
  enable_realtime: true,
  enable_ai_insights: false,
  min_content_length: 300,
  target_readability_score: 60,
  auto_analyze_delay: 2000,
  show_keyword_density: false,
  show_entity_detection: false,
  show_intent_classification: false,
};

const cancelDebounced = (fn) => {
  if (fn && typeof fn.cancel === 'function') {
    fn.cancel();
  }
};

const ContentAnalysisPanel = ({ postId }) => {
  const { useState, useEffect, useCallback, useMemo, useRef } = window.wp.element;
  const { __ = (text) => text } = window.wp?.i18n || {};
  const apiFetch = window.wp.apiFetch;
  const { useSelect } = window.wp.data;
  const { Spinner } = window.wp.components;

  const [readabilityScore, setReadabilityScore] = useState(null);
  const [readabilityLevel, setReadabilityLevel] = useState(null);
  const [readabilityGrade, setReadabilityGrade] = useState(null);
  const [readabilityStats, setReadabilityStats] = useState(null);
  const [isLoadingReadability, setIsLoadingReadability] = useState(false);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [analysis, setAnalysis] = useState(null);
  const [searchIntent, setSearchIntent] = useState(null);
  const [focusKeywords, setFocusKeywords] = useState([]);
  const [focusKeywordsLimit, setFocusKeywordsLimit] = useState(3);
  const [newKeywordInput, setNewKeywordInput] = useState('');
  const [seoTitleMeta, setSeoTitleMeta] = useState('');
  const [seoDescriptionMeta, setSeoDescriptionMeta] = useState('');
  const [canonicalUrlMeta, setCanonicalUrlMeta] = useState('');
  const [seoScore, setSeoScore] = useState(0);
  const [analysisSettings] = useState(() => {
    const merged = {
      ...DEFAULT_CONTENT_ANALYSIS_SETTINGS,
      ...(window?.proRankSidebar?.contentAnalysis || {}),
    };

    // Keep compatibility keys coherent with canonical runtime keys.
    merged.enabled = Boolean(merged.enable_realtime);
    merged.autoAnalyze = Boolean(merged.enable_realtime);
    merged.focusKeywordEnabled = Boolean(merged.show_keyword_density);
    if (typeof merged.seoScoreEnabled !== 'boolean') {
      merged.seoScoreEnabled = true;
    }
    if (typeof merged.readabilityEnabled !== 'boolean') {
      merged.readabilityEnabled = true;
    }

    // Free build: AI insight widgets are not shown in the editor side panel.
    merged.enable_ai_insights = false;
    merged.show_keyword_density = false;
    merged.show_entity_detection = false;
    merged.show_intent_classification = false;
    merged.focusKeywordEnabled = false;

    return merged;
  });
  const hasLoadedKeyword = useRef(false);

  const { content, title } = useSelect((select) => {
    const editor = select('core/editor');
    return {
      content: editor.getEditedPostContent() || '',
      title: editor.getEditedPostAttribute('title') || '',
    };
  }, []);

  const wordCount = useMemo(
    () => (content ? content.split(/\s+/).filter((w) => w.length > 0).length : 0),
    [content]
  );
  const minContentLength = Math.max(100, parseInt(analysisSettings.min_content_length, 10) || 300);
  const hasEnoughContent = wordCount >= minContentLength;
  const remainingWords = Math.max(0, minContentLength - wordCount);
  const targetReadability = Math.max(30, parseInt(analysisSettings.target_readability_score, 10) || 60);
  const autoAnalyzeDelay = Math.max(500, Math.min(5000, parseInt(analysisSettings.auto_analyze_delay, 10) || 2000));
  const primaryKeyword = useMemo(() => {
    const primary = focusKeywords.find(kw => kw.primary);
    return primary ? primary.keyword : (focusKeywords[0]?.keyword || '');
  }, [focusKeywords]);

  const analysisContext = useMemo(() => ({
    title,
    seoTitle: seoTitleMeta,
    description: seoDescriptionMeta,
    url: canonicalUrlMeta,
    content,
  }), [title, seoTitleMeta, seoDescriptionMeta, canonicalUrlMeta, content]);

  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, __]
  );

  const calculateSeoScore = useCallback(() => {
    let score = 0;
    let weight = 0;

    if (readabilityScore !== null) {
      const readabilityNormalized = Math.min(100, Math.max(0, (readabilityScore / targetReadability) * 100));
      score += readabilityNormalized * 0.3;
      weight += 0.3;
    }
    if (analysis?.structure_score) {
      score += analysis.structure_score.score * 0.15;
      weight += 0.15;
    }

    const keywordScore = multiKeywordAnalysis.aggregate;
    score += keywordScore * 0.35;
    weight += 0.35;

    score += (
      wordCount >= Math.max(minContentLength, 1000)
        ? 100
        : wordCount >= Math.max(minContentLength, 600)
          ? 75
          : wordCount >= minContentLength
            ? 50
            : 0
    ) * 0.2;
    weight += 0.2;

    setSeoScore(weight > 0 ? Math.round(score / weight) : 0);
  }, [readabilityScore, analysis, targetReadability, wordCount, minContentLength, multiKeywordAnalysis.aggregate]);

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

  const fetchReadabilityScore = useCallback(async (pid) => {
    if (!pid) return;
    setIsLoadingReadability(true);
    try {
      const res = await apiFetch({ path: `/prorank-seo/v1/readability-score/${pid}`, method: 'GET' });
      if (res?.data) {
        setReadabilityScore(res.data.score);
        setReadabilityLevel(res.data.level);
        setReadabilityGrade(res.data.grade);
        setReadabilityStats(res.data.stats);
      }
    } catch (e) { console.error('Readability error:', e); }
    finally { setIsLoadingReadability(false); }
  }, []);

  const debouncedFetch = useMemo(() => debounce((id) => fetchReadabilityScore(id), autoAnalyzeDelay), [fetchReadabilityScore, autoAnalyzeDelay]);
  useEffect(() => {
    if (!analysisSettings.enable_realtime || !analysisSettings.readabilityEnabled) {
      return () => cancelDebounced(debouncedFetch);
    }
    if (postId && content && wordCount >= minContentLength) {
      debouncedFetch(postId);
    }
    return () => cancelDebounced(debouncedFetch);
  }, [analysisSettings.enable_realtime, analysisSettings.readabilityEnabled, postId, content, wordCount, minContentLength, debouncedFetch]);

  const saveFocusKeywords = useCallback(
    async (keywords) => {
      if (!postId) return;
      try {
        const response = await apiFetch({
          path: `/prorank-seo/v1/meta/${postId}`,
          method: 'POST',
          data: { focus_keywords: keywords },
        });
        // Reconcile: apply server-normalized keywords back to local state.
        if (Array.isArray(response?.data?.focus_keywords)) {
          setFocusKeywords(response.data.focus_keywords);
        }
      } catch (e) {
        console.error('Focus keywords save failed:', e);
      }
    },
    [postId]
  );

  const debouncedSaveFocusKeywords = useMemo(
    () => debounce((keywords) => saveFocusKeywords(keywords), 600),
    [saveFocusKeywords]
  );

  useEffect(() => () => cancelDebounced(debouncedSaveFocusKeywords), [debouncedSaveFocusKeywords]);

  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('');
      debouncedSaveFocusKeywords(next);
    },
    [focusKeywords, focusKeywordsLimit, debouncedSaveFocusKeywords]
  );

  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);
      debouncedSaveFocusKeywords(next);
    },
    [focusKeywords, debouncedSaveFocusKeywords]
  );

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

  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);
      debouncedSaveFocusKeywords(next);
    },
    [focusKeywords, debouncedSaveFocusKeywords]
  );

  useEffect(() => {
    if (!postId || hasLoadedKeyword.current) return;
    apiFetch({ path: `/prorank-seo/v1/meta/${postId}`, method: 'GET' })
      .then((response) => {
        if (response?.data) {
          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);
          }
          setSeoTitleMeta(response.data.seo_title || '');
          setSeoDescriptionMeta(response.data.seo_description || '');
          setCanonicalUrlMeta(response.data.canonical_url || response.data.defaults?.url || '');
        }
      })
      .catch((e) => console.error('Focus keyword load failed:', e))
      .finally(() => { hasLoadedKeyword.current = true; });
  }, [postId, apiFetch]);

  useEffect(() => {
    const handleMetaSync = (event) => {
      const detail = event?.detail || {};
      if (detail.postId !== postId) {
        return;
      }

      if (Object.prototype.hasOwnProperty.call(detail, 'seoTitle')) {
        setSeoTitleMeta(detail.seoTitle || '');
      }
      if (Object.prototype.hasOwnProperty.call(detail, 'seoDescription')) {
        setSeoDescriptionMeta(detail.seoDescription || '');
      }
      if (Object.prototype.hasOwnProperty.call(detail, 'canonicalUrl')) {
        setCanonicalUrlMeta(detail.canonicalUrl || '');
      }
      if (Array.isArray(detail.focusKeywords)) {
        setFocusKeywords(detail.focusKeywords);
      }
    };

    window.addEventListener(PRORANK_EDITOR_META_SYNC_EVENT, handleMetaSync);
    return () => window.removeEventListener(PRORANK_EDITOR_META_SYNC_EVENT, handleMetaSync);
  }, [postId]);

  const analyzeContent = useCallback(async () => {
    if (!content || !analysisSettings.enable_ai_insights || wordCount < minContentLength) return;
    setIsAnalyzing(true);
    try {
      await saveFocusKeywords(focusKeywords);
      const res = await apiFetch({ path: '/prorank-seo/v1/content/analyze', method: 'POST', data: { content, title, focus_keyword: primaryKeyword } });
      if (res?.data) {
        setAnalysis(res.data);
      }
      if (analysisSettings.show_intent_classification) {
        try {
          const intentRes = await apiFetch({ path: '/prorank-seo/v1/content/intent', method: 'POST', data: { title, content } });
          if (intentRes?.data) {
            setSearchIntent(intentRes.data);
          }
        } catch (intentError) {
          setSearchIntent(null);
          console.error('Intent analysis error:', intentError);
        }
      }
    } catch (e) { console.error('Analysis error:', e); }
    finally { setIsAnalyzing(false); }
  }, [content, title, primaryKeyword, focusKeywords, analysisSettings.enable_ai_insights, analysisSettings.show_intent_classification, wordCount, minContentLength, saveFocusKeywords, apiFetch]);

  const debouncedAnalyze = useMemo(() => debounce(() => analyzeContent(), autoAnalyzeDelay), [analyzeContent, autoAnalyzeDelay]);
  useEffect(() => {
    if (
      analysisSettings.enable_realtime &&
      analysisSettings.enable_ai_insights &&
      content &&
      primaryKeyword &&
      wordCount >= minContentLength
    ) {
      debouncedAnalyze();
    }
    return () => cancelDebounced(debouncedAnalyze);
  }, [analysisSettings.enable_realtime, analysisSettings.enable_ai_insights, content, primaryKeyword, wordCount, minContentLength, debouncedAnalyze]);

  const getColor = (s) => s >= 70 ? '#3b82f6' : s >= 40 ? '#f59e0b' : '#ef4444';
  const getContentStatus = (s) => {
    if (!hasEnoughContent) return __('Build Out', 'prorank-seo');
    return s >= 80
      ? __('Strong', 'prorank-seo')
      : s >= 60
        ? __('Solid', 'prorank-seo')
        : s >= 40
          ? __('Developing', 'prorank-seo')
          : __('Needs Work', 'prorank-seo');
  };
  const displayedSeoScore = hasEnoughContent ? seoScore : '—';
  const displayedReadabilityScore = hasEnoughContent && readabilityScore !== null ? Math.round(readabilityScore) : '—';
  const readTime = readabilityStats?.estimated_reading_time || Math.ceil(wordCount / 200);

  return (
    <div className="prs">
      <style>{`
        .prs { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 13px; color: #374151; }

        /* Score - Centered Vertical */
        .prs-score { text-align: center; padding: 18px 14px; background: linear-gradient(180deg, #f8fafc 0%, #fff 100%); border-bottom: 1px solid #e5e7eb; }
        .prs-circle { position: relative; width: 80px; height: 80px; margin: 0 auto 12px; }
        .prs-circle svg { transform: rotate(-90deg); }
        .prs-val { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; }
        .prs-num { font-size: 26px; font-weight: 700; color: #111827; line-height: 1; }
        .prs-lbl { font-size: 9px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 2px; }
        .prs-score-status { margin-top: 10px; font-size: 12px; font-weight: 600; color: #334155; }

        /* Stats Row - Horizontal */
        .prs-stats { display: flex; flex-wrap: wrap; justify-content: space-around; gap: 10px; }
        .prs-stat { text-align: center; flex: 1; min-width: 70px; }
        .prs-stat-val { font-size: 15px; font-weight: 700; color: #111827; }
        .prs-stat-val.good { color: #3b82f6; }
        .prs-stat-val.warn { color: #f59e0b; }
        .prs-stat-val.bad { color: #ef4444; }
        .prs-stat-name { font-size: 9px; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.3px; }

        /* Section */
        .prs-sec { padding: 12px; border-bottom: 1px solid #e5e7eb; }
        .prs-sec:last-child { border-bottom: none; }
        .prs-title { font-size: 10px; font-weight: 600; color: #3b82f6; text-transform: uppercase; letter-spacing: 0.5px; margin: 0 0 8px 0; }

        /* Keyword - Full Width Stacked */
        .prs-input { width: 100%; padding: 9px 10px; border: 2px solid #e5e7eb; border-radius: 6px; font-size: 13px; box-sizing: border-box; margin-bottom: 10px; }
        .prs-input:focus { outline: none; border-color: #3b82f6; }
        .prs-btn { width: 100%; padding: 9px 12px; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; border: none; border-radius: 6px; font-size: 13px; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 6px; }
        .prs-btn:hover:not(:disabled) { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); }
        .prs-btn:disabled { opacity: 0.5; cursor: not-allowed; }

        /* Keyword Stats - Compact */
        .prs-kw-stats { display: flex; gap: 6px; margin-top: 10px; }
        .prs-kw-stat { flex: 1; text-align: center; padding: 8px 4px; background: #f8fafc; border-radius: 6px; border: 1px solid #e5e7eb; }
        .prs-kw-stat-val { font-size: 16px; font-weight: 700; }
        .prs-kw-stat-lbl { font-size: 8px; color: #9ca3af; text-transform: uppercase; margin-top: 1px; }
        .prs-kw-summary { display: flex; align-items: center; gap: 10px; padding: 10px; background: #f8fafc; border-radius: 8px; border: 1px solid #e5e7eb; margin-top: 10px; }
        .prs-kw-score { width: 42px; height: 42px; border-radius: 999px; display: flex; align-items: center; justify-content: center; font-size: 13px; font-weight: 700; color: #fff; flex-shrink: 0; }
        .prs-kw-copy { min-width: 0; flex: 1; }
        .prs-kw-copy strong { display: block; font-size: 12px; color: #111827; }
        .prs-kw-copy span { display: block; font-size: 11px; color: #6b7280; margin-top: 2px; }
        .prs-checks { margin-top: 10px; display: flex; flex-direction: column; gap: 6px; }
        .prs-check { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 8px 9px; border-radius: 6px; border: 1px solid #e5e7eb; background: #fff; }
        .prs-check-main { display: flex; gap: 8px; min-width: 0; }
        .prs-check-icon { width: 16px; text-align: center; font-weight: 700; flex-shrink: 0; }
        .prs-check-icon.pass { color: #2563eb; }
        .prs-check-icon.fail { color: #ef4444; }
        .prs-check-icon.na { color: #9ca3af; }
        .prs-check-label { font-size: 11px; color: #111827; }
        .prs-check-meta { font-size: 10px; color: #6b7280; white-space: nowrap; flex-shrink: 0; }

        /* Readability Card - Compact */
        .prs-read { display: flex; align-items: center; gap: 10px; padding: 10px; background: #f8fafc; border-radius: 8px; border: 1px solid #e5e7eb; }
        .prs-read-badge { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; color: white; flex-shrink: 0; }
        .prs-read-info { flex: 1; min-width: 0; }
        .prs-read-level { font-size: 13px; font-weight: 600; color: #111827; }
        .prs-read-grade { font-size: 11px; color: #6b7280; }

        /* Issues - Compact */
        .prs-issues { margin-top: 6px; }
        .prs-issue { display: flex; align-items: flex-start; gap: 6px; padding: 5px 0; font-size: 11px; color: #4b5563; border-bottom: 1px solid #f3f4f6; }
        .prs-issue:last-child { border-bottom: none; }
        .prs-dot { width: 5px; height: 5px; border-radius: 50%; background: #f59e0b; margin-top: 4px; flex-shrink: 0; }

        .prs-loading { display: flex; justify-content: center; padding: 16px; }
        .prs-empty { padding: 12px; text-align: center; color: #9ca3af; font-size: 12px; }
        .prs-note { margin-top: 8px; padding: 10px; text-align: left; color: #475569; font-size: 11px; line-height: 1.5; background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 8px; }
        .prs-score-note { margin-top: 10px; padding: 9px 10px; border-radius: 8px; background: #fff7ed; border: 1px solid #fdba74; color: #9a3412; font-size: 11px; line-height: 1.45; }
      `}</style>

      {/* Score Section */}
      {analysisSettings.seoScoreEnabled && (
        <div className="prs-score">
          <div className="prs-circle">
            <svg width="80" height="80">
              <circle cx="40" cy="40" r="34" fill="none" stroke="#e5e7eb" strokeWidth="5" />
              <circle cx="40" cy="40" r="34" fill="none" stroke={hasEnoughContent ? getColor(seoScore) : '#cbd5e1'} strokeWidth="5" strokeLinecap="round"
                strokeDasharray={`${(hasEnoughContent ? seoScore : 0) / 100 * 214} 214`} style={{ transition: 'stroke-dasharray 0.5s ease' }} />
            </svg>
            <div className="prs-val">
              <div className="prs-num">{displayedSeoScore}</div>
              <div className="prs-lbl">{__('Content Score', 'prorank-seo')}</div>
            </div>
          </div>
          <div className="prs-score-status">{getContentStatus(seoScore)}</div>
          <div className="prs-stats">
            <div className="prs-stat">
              <div className={`prs-stat-val ${hasEnoughContent && readabilityScore >= targetReadability ? 'good' : hasEnoughContent && readabilityScore >= Math.max(30, targetReadability - 20) ? 'warn' : hasEnoughContent ? 'bad' : ''}`}>
                {displayedReadabilityScore}
              </div>
              <div className="prs-stat-name">Readable</div>
            </div>
            <div className="prs-stat">
              <div className={`prs-stat-val ${wordCount >= minContentLength ? 'good' : 'warn'}`}>{wordCount}</div>
              <div className="prs-stat-name">Words</div>
            </div>
            <div className="prs-stat">
              <div className="prs-stat-val">{readTime}m</div>
              <div className="prs-stat-name">Read</div>
            </div>
          </div>
          {!hasEnoughContent && (
            <div className="prs-score-note">
              {`${wordCount} / ${minContentLength} words. Add ${remainingWords} more words to unlock full readability and content scoring.`}
            </div>
          )}
        </div>
      )}

      {/* Focus Keywords - Stacked */}
      <div className="prs-sec">
        <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>
          <h4 className="prs-title" style={{ margin: 0 }}>Focus Keywords</h4>
          <span style={{ fontSize: '10px', color: '#6b7280', padding: '1px 6px', background: '#f3f4f6', borderRadius: '8px' }}>
            {`${focusKeywords.length}/${focusKeywordsLimit}`}
          </span>
        </div>
        <div style={{ display: 'flex', gap: '6px', marginBottom: focusKeywords.length > 0 ? '6px' : '0' }}>
          <input
            type="text"
            className="prs-input"
            style={{ marginBottom: 0 }}
            value={newKeywordInput}
            onChange={(e) => setNewKeywordInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                addKeyword(newKeywordInput);
              }
            }}
            placeholder={focusKeywords.length >= focusKeywordsLimit ? 'Limit reached' : 'Enter keyword...'}
            disabled={focusKeywords.length >= focusKeywordsLimit}
            aria-label="Add keyword"
          />
          <button
            type="button"
            onClick={() => addKeyword(newKeywordInput)}
            disabled={!newKeywordInput.trim() || focusKeywords.length >= focusKeywordsLimit}
            style={{ padding: '6px 10px', background: '#3b82f6', color: '#fff', border: 'none', borderRadius: '6px', fontSize: '12px', fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap', opacity: (!newKeywordInput.trim() || focusKeywords.length >= focusKeywordsLimit) ? 0.5 : 1 }}
          >
            Add
          </button>
        </div>

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

        {analysisSettings.enable_ai_insights && (
          <button
            className="prs-btn"
            onClick={analyzeContent}
            disabled={isAnalyzing || !content || !hasEnoughContent}
          >
            {isAnalyzing ? <Spinner /> : hasEnoughContent ? 'Analyze Content' : `Add ${remainingWords} More Words`}
          </button>
        )}

        {!hasEnoughContent && (
          <div className="prs-note">
            {`Basic keyword checks work on short drafts. Add at least ${minContentLength} words to enable full content analysis and readability scoring.`}
          </div>
        )}

        {!primaryKeyword ? (
          <div className="prs-empty" style={{ marginTop: '8px', textAlign: 'left' }}>
            {__('Add a focus keyword to check title, description, URL, headings, paragraph placement, density, and image alt text.', 'prorank-seo')}
          </div>
        ) : (
          <>
            {/* Aggregate score banner (shown when multiple keywords) */}
            {multiKeywordAnalysis.secondary.length > 0 && (
              <div className="prs-kw-summary">
                <div
                  className="prs-kw-score"
                  style={{
                    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 className="prs-kw-copy">
                  <strong>{__('Overall keyword score', 'prorank-seo')}</strong>
                  <span>
                    {`${focusKeywords.length} ${__('keywords', 'prorank-seo')} · ${__('primary 70% + secondary 30%', 'prorank-seo')}`}
                  </span>
                </div>
              </div>
            )}

            {/* Primary keyword detail */}
            <div className="prs-kw-summary" style={multiKeywordAnalysis.secondary.length > 0 ? { marginTop: '6px' } : undefined}>
              <div
                className="prs-kw-score"
                style={{
                  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 className="prs-kw-copy">
                <strong>
                  {multiKeywordAnalysis.secondary.length > 0
                    ? `\u2605 "${focusKeywordAnalysis.keyword}"`
                    : __('Focus keyword coverage', 'prorank-seo')
                  }
                </strong>
                <span>
                  {`${focusKeywordAnalysis.occurrenceCount} ${__('uses', 'prorank-seo')} · ${focusKeywordAnalysis.density.toFixed(2)}% ${__('density', 'prorank-seo')}`}
                </span>
              </div>
            </div>

            <div className="prs-checks">
              {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} className="prs-check">
                    <div className="prs-check-main">
                      <span className={`prs-check-icon ${state}`}>
                        {state === 'pass' ? '✓' : state === 'fail' ? '!' : '–'}
                      </span>
                      <span className="prs-check-label">{check.label}</span>
                    </div>
                    {meta ? <span className="prs-check-meta">{meta}</span> : null}
                  </div>
                );
              })}
            </div>

            {/* Secondary keyword summaries */}
            {multiKeywordAnalysis.secondary.length > 0 && (
              <div style={{ marginTop: '8px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                <div style={{ fontSize: '10px', fontWeight: 600, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.3px' }}>
                  {__('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: '6px',
                        padding: '5px 8px',
                        borderRadius: '5px',
                        border: '1px solid #e5e7eb',
                        background: '#fff',
                      }}
                    >
                      <span
                        style={{
                          width: '24px',
                          height: '24px',
                          borderRadius: '999px',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          fontSize: '10px',
                          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: '11px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {`"${result.keyword}"`}
                      </span>
                      <span style={{ fontSize: '10px', color: '#6b7280', whiteSpace: 'nowrap' }}>
                        {`${passedCount}/${applicableCount}`}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </div>

      {/* Entities */}
      {analysisSettings.enable_ai_insights && analysisSettings.show_entity_detection && Array.isArray(analysis?.entities) && analysis.entities.length > 0 && (
        <div className="prs-sec">
          <h4 className="prs-title">Entities</h4>
          <div className="prs-issues">
            {analysis.entities.slice(0, 5).map((entity, i) => (
              <div key={i} className="prs-issue">
                <span className="prs-dot"></span>
                <span>{`${entity.value} (${entity.type})`}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Search Intent */}
      {analysisSettings.enable_ai_insights && analysisSettings.show_intent_classification && searchIntent?.primary_intent && (
        <div className="prs-sec">
          <h4 className="prs-title">Search Intent</h4>
          <div className="prs-read">
            <div className="prs-read-badge" style={{ background: 'linear-gradient(135deg, #3b82f6, #2563eb)' }}>
              {Math.max(0, parseInt(searchIntent.confidence || 0, 10))}%
            </div>
            <div className="prs-read-info">
              <div className="prs-read-level">{String(searchIntent.primary_intent || '').replace('_', ' ')}</div>
              <div className="prs-read-grade">Confidence</div>
            </div>
          </div>
        </div>
      )}

      {/* Readability */}
      {analysisSettings.readabilityEnabled && (
        <div className="prs-sec">
          <h4 className="prs-title">Readability</h4>
          {isLoadingReadability ? (
            <div className="prs-loading"><Spinner /></div>
          ) : readabilityScore !== null ? (
            <div className="prs-read">
              <div className="prs-read-badge" style={{ background: readabilityScore >= targetReadability ? 'linear-gradient(135deg, #3b82f6, #2563eb)' : readabilityScore >= Math.max(30, targetReadability - 20) ? 'linear-gradient(135deg, #f59e0b, #d97706)' : 'linear-gradient(135deg, #ef4444, #dc2626)' }}>
                {Math.round(readabilityScore)}
              </div>
              <div className="prs-read-info">
                <div className="prs-read-level">{readabilityLevel}</div>
                <div className="prs-read-grade">{readabilityGrade}</div>
              </div>
            </div>
          ) : (
            <div className="prs-empty">
              {hasEnoughContent ? 'Add content to analyze' : `${wordCount} / ${minContentLength} words. Readability analysis starts once the draft is longer.`}
            </div>
          )}
        </div>
      )}

      {/* Issues */}
      {analysisSettings.enable_ai_insights && analysis?.structure_score?.issues?.length > 0 && (
        <div className="prs-sec">
          <h4 className="prs-title">Issues ({analysis.structure_score.issues.length})</h4>
          <div className="prs-issues">
            {analysis.structure_score.issues.slice(0, 5).map((issue, i) => (
              <div key={i} className="prs-issue">
                <span className="prs-dot"></span>
                <span>{issue}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default ContentAnalysisPanel;
