import React, { useCallback, useState } from 'react';
import type { IconType } from 'react-icons';
import {
  LuAlertCircle,
  LuBot,
  LuCheckCircle,
  LuFileText,
  LuHelpCircle,
  LuLightbulb,
  LuListChecks,
  LuMessageSquare,
  LuPackage,
  LuSend,
  LuType,
  LuWand2,
  LuXCircle,
  LuZap,
} from 'react-icons/lu';

import CheckerFixCard from '../components/content-generator/CheckerFixCard';
import SearchableSelect from '../components/widgets/SearchableSelect';
import { Spinner } from '../components/ui/Spinner';
import { LANGUAGE_OPTIONS } from '../data/locales';
import {
  evaluateBlogContent,
  evaluateProductContent,
  evaluateQueryLab,
  fixProductContent,
} from '../service/content-generator/content-generator.service';
import type {
  BaseAgentResponse,
  BlogEvaluation,
  ContentCheckType,
  ContentCheckerEvaluateResponse,
  ContentCheckerFixResult,
  PreAnsweredQuestion,
  QueryLabResult,
  TitleDescriptionEvaluation,
} from '../service/content-generator/content-generator.interface';

/** Check mode: the three product modes plus the standalone blog mode. */
type CheckType = ContentCheckType | 'blog';

/** Dropdown labels for every check mode. */
const CHECK_TYPE_LABELS: Record<CheckType, string> = {
  both: 'Both',
  title: 'Title',
  description: 'Description',
  blog: 'Blog',
};

/** Credits billed per fixed topic - title or description - so fixing both
 *  costs double (agent: CREDITS_INLINE_SINGLE_CALL per topic). */
const FIX_CREDITS_PER_TOPIC = 10;

/** Fix is offered under this score even when the issue lists come back empty
 *  (mirrors the catalog audit's "ok" band: avg >= 80). */
const FIX_SCORE_THRESHOLD = 80;

/** Query Lab questions allowed per evaluation. */
const QUERY_LAB_LIMIT = 5;

const TITLE_MAX_LENGTH = 500;
const DESCRIPTION_MAX_LENGTH = 5000;
const BLOG_MAX_LENGTH = 50000;
const KEYWORDS_MAX_LENGTH = 500;

const SCORE_EXCELLENT = 90;
const SCORE_GOOD = 70;
const SCORE_ACCEPTABLE = 50;
const SCORE_POOR = 30;

const CONFIDENCE_HIGH = 80;
const CONFIDENCE_MEDIUM = 50;

/** Tailwind classes describing one score band. */
interface ScoreGrade {
  label: string;
  color: string;
  border: string;
  bg: string;
}

/**
 * Map a 0-100 score to its band label and colours.
 *
 * @param {number} score - The score to grade.
 * @return {ScoreGrade} Label plus text / border / background classes.
 */
const scoreGrade = (score: number): ScoreGrade => {
  if (score >= SCORE_EXCELLENT)
    return {
      label: 'Excellent',
      color: 'text-emerald-600',
      border: 'border-emerald-200',
      bg: 'bg-emerald-50',
    };
  if (score >= SCORE_GOOD)
    return {
      label: 'Good',
      color: 'text-blue-600',
      border: 'border-blue-200',
      bg: 'bg-blue-50',
    };
  if (score >= SCORE_ACCEPTABLE)
    return {
      label: 'Acceptable',
      color: 'text-amber-600',
      border: 'border-amber-200',
      bg: 'bg-amber-50',
    };
  if (score >= SCORE_POOR)
    return {
      label: 'Poor',
      color: 'text-orange-600',
      border: 'border-orange-200',
      bg: 'bg-orange-50',
    };

  return {
    label: 'Bad',
    color: 'text-red-600',
    border: 'border-red-200',
    bg: 'bg-red-50',
  };
};

/**
 * Map a Query Lab confidence score to its badge colours.
 *
 * @param {number} score - Confidence percentage.
 * @return {{ bg: string; border: string; text: string }} Badge classes.
 */
const confidenceColor = (
  score: number
): { bg: string; border: string; text: string } => {
  if (score >= CONFIDENCE_HIGH)
    return {
      bg: 'bg-emerald-50',
      border: 'border-emerald-200',
      text: 'text-emerald-700',
    };
  if (score >= CONFIDENCE_MEDIUM)
    return {
      bg: 'bg-amber-50',
      border: 'border-amber-200',
      text: 'text-amber-700',
    };

  return { bg: 'bg-red-50', border: 'border-red-200', text: 'text-red-700' };
};

/**
 * Read a checker envelope, collapsing every failure shape into one message.
 *
 * @param {BaseAgentResponse<T>} response - Agent envelope (or service error).
 * @param {string} fallbackMessage - Message shown when the call did not succeed.
 * @return {{ data?: T; error?: string }} Payload on success, message on failure.
 */
const readEnvelope = <T,>(
  response: BaseAgentResponse<T>,
  fallbackMessage: string
): { data?: T; error?: string } => {
  if (response && !response.errors && response.data) {
    return { data: response.data };
  }

  return { error: fallbackMessage };
};

/** Props for {@link CheckItem}. */
interface CheckItemProps {
  checked: boolean;
  label: string;
}

/**
 * One checklist row: a tick or a cross plus its label.
 *
 * @param {CheckItemProps} props - Checked flag and label.
 * @return {JSX.Element} The checklist row.
 */
const CheckItem = ({ checked, label }: CheckItemProps): JSX.Element => (
  <div className="flex items-center gap-2">
    {checked ? (
      <LuCheckCircle
        className="h-4 w-4 shrink-0 text-emerald-600"
        aria-hidden
      />
    ) : (
      <LuXCircle className="h-4 w-4 shrink-0 text-red-500" aria-hidden />
    )}
    <span className={`text-xs ${checked ? 'text-gray-900' : 'text-gray-500'}`}>
      {label}
    </span>
  </div>
);

/** Props for {@link ScoreCard}. */
interface ScoreCardProps {
  label: string;
  score: number;
  Icon: IconType;
}

/**
 * A single graded score tile.
 *
 * @param {ScoreCardProps} props - Label, score and leading icon.
 * @return {JSX.Element} The score tile.
 */
const ScoreCard = ({ label, score, Icon }: ScoreCardProps): JSX.Element => {
  const grade = scoreGrade(score);

  return (
    <div
      className={`rounded-lg border p-3 text-center ${grade.border} ${grade.bg}`}
    >
      <Icon className={`mx-auto mb-1 h-4 w-4 ${grade.color}`} aria-hidden />
      <p className="text-xs text-gray-500">{label}</p>
      <p className={`text-2xl font-bold ${grade.color}`}>{score}</p>
      <span
        className={`mt-1 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${grade.border} ${grade.bg} ${grade.color}`}
      >
        {grade.label}
      </span>
    </div>
  );
};

const inputClass =
  'block w-full rounded-md border-gray-300 px-3 py-2 text-sm placeholder:text-gray-400 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900';
const errorInputClass =
  'border-red-500 focus:border-red-500 focus:ring-red-500';
const sectionClass = 'rounded-xl border border-gray-200 bg-white p-5';
const primaryButtonClass =
  'inline-flex items-center justify-center gap-2 rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50';

/**
 * Content Checker page. Scores pasted product copy or a blog post for AI
 * search readiness, offers a one-click "Fix with AI" pass through the Product
 * Content pipeline, and lets the merchant interrogate a description in the
 * Query Lab.
 *
 * Client-only: every call goes straight to the agent backend with the
 * merchant's recomaze JWT, so there is no loader / action round trip.
 *
 * @return {JSX.Element} The Content Checker page.
 */
const ContentChecker = (): JSX.Element => {
  const [checkType, setCheckType] = useState<CheckType>('both');
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [blogContent, setBlogContent] = useState('');
  const [targetKeywords, setTargetKeywords] = useState('');
  const [language, setLanguage] = useState('en');

  const [fieldErrors, setFieldErrors] = useState<{
    title?: string;
    description?: string;
    blogContent?: string;
  }>({});

  const [result, setResult] = useState<TitleDescriptionEvaluation | null>(null);
  const [preAnswered, setPreAnswered] = useState<PreAnsweredQuestion[]>([]);
  const [blogResult, setBlogResult] = useState<BlogEvaluation | null>(null);
  const [apiError, setApiError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const [fixResult, setFixResult] = useState<ContentCheckerFixResult | null>(
    null
  );
  const [fixError, setFixError] = useState<string | null>(null);
  const [fixing, setFixing] = useState(false);

  const [queryQuestion, setQueryQuestion] = useState('');
  const [queryHistory, setQueryHistory] = useState<
    Array<{ question: string; result: QueryLabResult }>
  >([]);
  const [queryRemaining, setQueryRemaining] = useState(QUERY_LAB_LIMIT);
  const [productType, setProductType] = useState('');
  const [querying, setQuerying] = useState(false);

  const handleCheckTypeChange = (next: CheckType): void => {
    setCheckType(next);
    setFieldErrors({});
  };

  const onSubmit = useCallback(async (): Promise<void> => {
    const errors: {
      title?: string;
      description?: string;
      blogContent?: string;
    } = {};
    if (checkType === 'blog') {
      if (!blogContent.trim()) errors.blogContent = 'Blog content is required.';
    } else {
      if ((checkType === 'title' || checkType === 'both') && !title.trim()) {
        errors.title = 'Title is required.';
      }
      if (
        (checkType === 'description' || checkType === 'both') &&
        !description.trim()
      ) {
        errors.description = 'Description is required.';
      }
    }
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) return;

    setApiError(null);
    setSubmitting(true);
    try {
      if (checkType === 'blog') {
        const response = await evaluateBlogContent({
          blog_content: blogContent.trim(),
          target_keywords: targetKeywords.trim(),
          language,
        });
        const { data, error } = readEnvelope(
          response,
          'Blog evaluation failed.'
        );
        if (error) {
          setApiError(error);
        } else if (data) {
          setBlogResult(data);
        }
      } else {
        const response = await evaluateProductContent({
          check_type: checkType,
          title: title.trim(),
          description: description.trim(),
          language,
        });
        const { data, error } = readEnvelope<ContentCheckerEvaluateResponse>(
          response,
          'Evaluation failed.'
        );
        if (error) {
          setApiError(error);
        } else if (data) {
          setResult(data.result);
          setPreAnswered(data.pre_answered_questions ?? []);
          setProductType(data.result.detected_product_type);
          setQueryHistory([]);
          setQueryRemaining(QUERY_LAB_LIMIT);
          setFixResult(null);
          setFixError(null);
        }
      }
    } catch {
      setApiError(
        checkType === 'blog' ? 'Blog evaluation failed.' : 'Evaluation failed.'
      );
    } finally {
      setSubmitting(false);
    }
  }, [checkType, title, description, blogContent, targetKeywords, language]);

  const handleQuerySubmit = useCallback(async (): Promise<void> => {
    if (!queryQuestion.trim() || !description.trim() || queryRemaining <= 0) {
      return;
    }
    const askedQuestion = queryQuestion.trim();
    setQuerying(true);
    try {
      const response = await evaluateQueryLab({
        description: description.trim(),
        question: askedQuestion,
        product_type: productType,
        language,
      });
      const { data, error } = readEnvelope(response, 'Query lab failed.');
      if (error) {
        setApiError(error);
      } else if (data) {
        setQueryHistory(prev => [
          ...prev,
          { question: askedQuestion, result: data },
        ]);
        setQueryQuestion('');
        setQueryRemaining(prev => Math.max(0, prev - 1));
      }
    } catch {
      setApiError('Query lab failed.');
    } finally {
      setQuerying(false);
    }
  }, [queryQuestion, description, queryRemaining, productType, language]);

  const handleFix = useCallback(async (): Promise<void> => {
    if (!result) return;
    setFixError(null);
    setFixing(true);
    // Only the checked topics are sent (and billed): a leftover description
    // in form state must not turn a title-only fix into a 2-topic charge.
    const includeTitle = checkType === 'title' || checkType === 'both';
    const includeDescription =
      checkType === 'description' || checkType === 'both';
    try {
      const response = await fixProductContent({
        title: includeTitle ? title.trim() : '',
        description: includeDescription ? description.trim() : '',
        language,
        detected_product_type: result.detected_product_type ?? '',
        title_issues: result.title_issues ?? [],
        description_issues: result.description_issues ?? [],
      });
      const { data, error } = readEnvelope(response, 'Fix failed.');
      if (error) {
        setFixError(error);
      } else if (data) {
        setFixResult(data);
      }
    } catch {
      setFixError('Fix failed.');
    } finally {
      setFixing(false);
    }
  }, [result, checkType, title, description, language]);

  const fixTopicCount = checkType === 'both' ? 2 : 1;
  const fixCost = FIX_CREDITS_PER_TOPIC * fixTopicCount;

  const hasIssues =
    !!result &&
    checkType !== 'blog' &&
    (((checkType === 'title' || checkType === 'both') &&
      result.title_issues.length > 0) ||
      ((checkType === 'description' || checkType === 'both') &&
        result.description_issues.length > 0));
  const hasSuggestions =
    !!result &&
    checkType !== 'blog' &&
    (((checkType === 'title' || checkType === 'both') &&
      result.title_suggestions.length > 0) ||
      ((checkType === 'description' || checkType === 'both') &&
        result.description_suggestions.length > 0));
  // The evaluator sometimes returns a low score with empty issue lists, so
  // gating Fix on issues alone made it appear "only sometimes". Offer it
  // whenever anything scored under the ok band.
  const hasLowScore =
    !!result &&
    checkType !== 'blog' &&
    (((checkType === 'title' || checkType === 'both') &&
      result.title_score < FIX_SCORE_THRESHOLD) ||
      ((checkType === 'description' || checkType === 'both') &&
        result.description_score < FIX_SCORE_THRESHOLD));
  const canFix = hasIssues || hasLowScore;

  return (
    <div className="mx-auto w-full max-w-[1600px] space-y-6 bg-white p-6 md:p-10">
      <div>
        <h1 className="text-xl font-semibold text-gray-900">Content Checker</h1>
        <p className="mt-1 text-sm text-gray-500">
          Evaluate product titles, descriptions, and blog posts for AI search
          engine readiness.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Input panel */}
        <div className={sectionClass}>
          <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
            <LuZap className="h-4 w-4 text-pink-600" aria-hidden />
            Check type
          </h2>
          <div className="mt-4 space-y-4">
            <select
              value={checkType}
              onChange={event =>
                handleCheckTypeChange(event.target.value as CheckType)
              }
              className="block w-full rounded-md border-gray-300 py-2 pl-3 pr-10 text-sm focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900"
            >
              {(['both', 'title', 'description', 'blog'] as CheckType[]).map(
                value => (
                  <option key={value} value={value}>
                    {CHECK_TYPE_LABELS[value]}
                  </option>
                )
              )}
            </select>

            <div className="space-y-1">
              <label className="block text-xs font-medium text-gray-700">
                Output language
              </label>
              <SearchableSelect
                value={language}
                onChange={setLanguage}
                options={LANGUAGE_OPTIONS}
                placeholder="Select a language..."
                searchPlaceholder="Search a language..."
              />
            </div>

            {(checkType === 'title' || checkType === 'both') && (
              <div className="space-y-1">
                <label className="block text-xs font-medium text-gray-700">
                  Product title <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={title}
                  onChange={event => setTitle(event.target.value)}
                  placeholder="e.g. Samsung Galaxy S24 Ultra 256GB Black"
                  maxLength={TITLE_MAX_LENGTH}
                  className={`${inputClass} ${fieldErrors.title ? errorInputClass : ''}`}
                />
                {fieldErrors.title && (
                  <p className="text-xs text-red-600">{fieldErrors.title}</p>
                )}
              </div>
            )}

            {(checkType === 'description' || checkType === 'both') && (
              <div className="space-y-1">
                <label className="block text-xs font-medium text-gray-700">
                  Product description <span className="text-red-500">*</span>
                </label>
                <textarea
                  rows={5}
                  value={description}
                  onChange={event => setDescription(event.target.value)}
                  placeholder="Paste full product description here..."
                  maxLength={DESCRIPTION_MAX_LENGTH}
                  className={`${inputClass} ${fieldErrors.description ? errorInputClass : ''}`}
                />
                {fieldErrors.description && (
                  <p className="text-xs text-red-600">
                    {fieldErrors.description}
                  </p>
                )}
                <p className="text-[10px] text-gray-500">
                  {description.length} / {DESCRIPTION_MAX_LENGTH}
                </p>
              </div>
            )}

            {checkType === 'blog' && (
              <>
                <div className="space-y-1">
                  <label className="block text-xs font-medium text-gray-700">
                    Blog content <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    rows={8}
                    value={blogContent}
                    onChange={event => setBlogContent(event.target.value)}
                    placeholder="Paste your full blog post here including title, headings, and all content..."
                    maxLength={BLOG_MAX_LENGTH}
                    className={`${inputClass} ${fieldErrors.blogContent ? errorInputClass : ''}`}
                  />
                  {fieldErrors.blogContent && (
                    <p className="text-xs text-red-600">
                      {fieldErrors.blogContent}
                    </p>
                  )}
                  <p className="text-[10px] text-gray-500">
                    {blogContent.length.toLocaleString()} /{' '}
                    {BLOG_MAX_LENGTH.toLocaleString()}
                  </p>
                </div>
                <div className="space-y-1">
                  <label className="block text-xs font-medium text-gray-700">
                    Target keywords (optional)
                  </label>
                  <input
                    type="text"
                    value={targetKeywords}
                    onChange={event => setTargetKeywords(event.target.value)}
                    placeholder="e.g. AI SEO, content marketing, blog optimization"
                    maxLength={KEYWORDS_MAX_LENGTH}
                    className={inputClass}
                  />
                  <p className="text-[10px] text-gray-500">
                    Separate multiple keywords with commas.
                  </p>
                </div>
              </>
            )}

            {apiError && (
              <div className="flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3">
                <LuAlertCircle
                  className="mt-0.5 h-4 w-4 shrink-0 text-red-500"
                  aria-hidden
                />
                <p className="text-sm text-gray-900">{apiError}</p>
              </div>
            )}

            <button
              type="button"
              onClick={() => void onSubmit()}
              disabled={submitting}
              className={`${primaryButtonClass} w-full`}
            >
              {submitting ? (
                <>
                  <Spinner className="h-4 w-4" />
                  Analyzing...
                </>
              ) : (
                <>
                  <LuZap className="h-4 w-4" aria-hidden />
                  Analyze
                </>
              )}
            </button>
          </div>
        </div>

        {/* Results panel */}
        <div className="space-y-4">
          {result && checkType !== 'blog' && (
            <>
              {result.detected_product_type && (
                <div className={`${sectionClass} flex items-start gap-3`}>
                  <LuPackage
                    className="mt-0.5 h-4 w-4 shrink-0 text-pink-600"
                    aria-hidden
                  />
                  <div className="min-w-0 flex-1">
                    <p className="text-xs text-gray-500">Detected product</p>
                    <p className="text-sm font-semibold text-gray-900">
                      {result.detected_product_type}
                    </p>
                    {result.expected_specs_for_category.length > 0 && (
                      <div className="mt-2 flex flex-wrap gap-1">
                        {result.expected_specs_for_category.map(
                          (spec, index) => (
                            <span
                              key={index}
                              className="inline-flex items-center rounded-full border border-gray-300 bg-white px-2 py-0.5 text-[10px] font-medium text-gray-700"
                            >
                              {spec}
                            </span>
                          )
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}

              <div
                className={`grid gap-3 ${checkType === 'both' ? 'grid-cols-2' : 'grid-cols-1'}`}
              >
                {(checkType === 'title' || checkType === 'both') && (
                  <ScoreCard
                    label="Title score"
                    score={result.title_score}
                    Icon={LuType}
                  />
                )}
                {(checkType === 'description' || checkType === 'both') && (
                  <ScoreCard
                    label="Description score"
                    score={result.description_score}
                    Icon={LuFileText}
                  />
                )}
              </div>

              {(checkType === 'title' || checkType === 'both') && (
                <div className={sectionClass}>
                  <h3 className="flex items-center gap-2 text-sm font-semibold text-gray-900">
                    <LuType className="h-4 w-4 text-pink-600" aria-hidden />
                    Title checklist
                  </h3>
                  <div className="mt-3 space-y-2">
                    <CheckItem
                      checked={result.title_is_technical}
                      label="Uses specific, technical terms"
                    />
                    <CheckItem
                      checked={result.title_is_concise}
                      label="Readable and concise"
                    />
                    <CheckItem
                      checked={result.title_has_product_type}
                      label="Clearly names the product type"
                    />
                    <CheckItem
                      checked={result.title_has_specs}
                      label="Has 2+ differentiators (size, color, feature...)"
                    />
                  </div>
                </div>
              )}

              {(checkType === 'description' || checkType === 'both') && (
                <div className={sectionClass}>
                  <h3 className="flex items-center gap-2 text-sm font-semibold text-gray-900">
                    <LuFileText className="h-4 w-4 text-pink-600" aria-hidden />
                    Description checklist
                  </h3>
                  <div className="mt-3 space-y-2">
                    <CheckItem
                      checked={result.description_has_intro}
                      label="Has a clear introduction"
                    />
                    <CheckItem
                      checked={result.description_has_technical}
                      label="Includes technical specs / measurements"
                    />
                    <CheckItem
                      checked={result.description_has_attributes}
                      label="Structured attributes (bullet points, pairs)"
                    />
                    <CheckItem
                      checked={result.description_has_qa}
                      label="Contains Q&A or care instructions (bonus)"
                    />
                  </div>
                </div>
              )}
            </>
          )}

          {blogResult && checkType === 'blog' && (
            <>
              {blogResult.detected_topic && (
                <div className={`${sectionClass} flex items-start gap-3`}>
                  <LuFileText
                    className="mt-0.5 h-4 w-4 shrink-0 text-pink-600"
                    aria-hidden
                  />
                  <div className="min-w-0 flex-1">
                    <p className="text-xs text-gray-500">Detected topic</p>
                    <p className="text-sm font-semibold text-gray-900">
                      {blogResult.detected_topic}
                    </p>
                    <p className="mt-0.5 text-xs text-gray-500">
                      {blogResult.word_count.toLocaleString()} words
                    </p>
                    {blogResult.detected_keywords.length > 0 && (
                      <div className="mt-2 flex flex-wrap gap-1">
                        {blogResult.detected_keywords.map((keyword, index) => (
                          <span
                            key={index}
                            className="inline-flex items-center rounded-full border border-gray-300 bg-white px-2 py-0.5 text-[10px] font-medium text-gray-700"
                          >
                            {keyword}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              )}

              <div className="grid grid-cols-2 gap-3">
                <ScoreCard
                  label="Overall"
                  score={blogResult.overall_score}
                  Icon={LuZap}
                />
                <ScoreCard
                  label="Content quality"
                  score={blogResult.content_quality_score}
                  Icon={LuFileText}
                />
                <ScoreCard
                  label="Keywords"
                  score={blogResult.keyword_optimization_score}
                  Icon={LuType}
                />
                <ScoreCard
                  label="Structure"
                  score={blogResult.structure_score}
                  Icon={LuListChecks}
                />
                <ScoreCard
                  label="AI readiness"
                  score={blogResult.ai_readiness_score}
                  Icon={LuBot}
                />
              </div>

              <div className={sectionClass}>
                <h3 className="text-sm font-semibold text-gray-900">
                  Content checklist
                </h3>
                <div className="mt-3 space-y-2">
                  <CheckItem
                    checked={blogResult.has_compelling_title}
                    label="Compelling title"
                  />
                  <CheckItem
                    checked={blogResult.has_clear_intro}
                    label="Clear introduction"
                  />
                  <CheckItem
                    checked={blogResult.has_structured_headings}
                    label="Structured headings (H2, H3)"
                  />
                  <CheckItem
                    checked={blogResult.has_actionable_content}
                    label="Actionable content"
                  />
                  <CheckItem
                    checked={blogResult.has_conclusion}
                    label="Clear conclusion"
                  />
                  <CheckItem
                    checked={blogResult.has_internal_linking_opportunities}
                    label="Internal linking opportunities"
                  />
                </div>
              </div>

              <div className={sectionClass}>
                <h3 className="text-sm font-semibold text-gray-900">
                  Keyword optimization
                </h3>
                <div className="mt-3 space-y-2">
                  <CheckItem
                    checked={blogResult.keyword_density_ok}
                    label="Optimal keyword density (1-3%)"
                  />
                  <CheckItem
                    checked={blogResult.keywords_in_headings}
                    label="Keywords in headings"
                  />
                  <CheckItem
                    checked={blogResult.keywords_in_intro}
                    label="Keywords in introduction"
                  />
                  <CheckItem
                    checked={blogResult.keyword_variations_used}
                    label="Uses keyword variations / synonyms"
                  />
                </div>
              </div>
            </>
          )}

          {!result && !blogResult && !submitting && (
            <div
              className={`${sectionClass} flex min-h-[200px] items-center justify-center`}
            >
              <div className="py-12 text-center">
                <LuZap
                  className="mx-auto mb-3 h-8 w-8 text-gray-300"
                  aria-hidden
                />
                <p className="text-sm text-gray-500">
                  Fill in the form and click Analyze to see results.
                </p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Issues & Suggestions - full width */}
      {result && checkType !== 'blog' && (
        <div className={sectionClass}>
          <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
            <LuLightbulb className="h-4 w-4 text-amber-500" aria-hidden />
            Issues &amp; Suggestions
          </h2>
          <div className="mt-4">
            {!hasIssues && !hasSuggestions && (
              <div className="flex items-center gap-2 py-4">
                <LuCheckCircle
                  className="h-5 w-5 text-emerald-600"
                  aria-hidden
                />
                <p className="text-sm text-gray-900">
                  No issues found. Looks great!
                </p>
              </div>
            )}
            {(hasIssues || hasSuggestions) && (
              <div
                className={`grid gap-4 ${hasIssues && hasSuggestions ? 'md:grid-cols-2' : 'grid-cols-1'}`}
              >
                {hasIssues && (
                  <div className="rounded-lg border border-orange-200 bg-orange-50 p-4">
                    <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold text-orange-700">
                      <LuAlertCircle className="h-4 w-4" aria-hidden />
                      Issues
                    </h3>
                    <ul className="space-y-2">
                      {(checkType === 'title' || checkType === 'both') &&
                        result.title_issues.map((issue, index) => (
                          <li
                            key={`t-${index}`}
                            className="flex items-start gap-2 text-xs text-gray-900"
                          >
                            <LuXCircle
                              className="mt-0.5 h-3.5 w-3.5 shrink-0 text-orange-500"
                              aria-hidden
                            />
                            {issue}
                          </li>
                        ))}
                      {(checkType === 'description' || checkType === 'both') &&
                        result.description_issues.map((issue, index) => (
                          <li
                            key={`d-${index}`}
                            className="flex items-start gap-2 text-xs text-gray-900"
                          >
                            <LuXCircle
                              className="mt-0.5 h-3.5 w-3.5 shrink-0 text-orange-500"
                              aria-hidden
                            />
                            {issue}
                          </li>
                        ))}
                    </ul>
                  </div>
                )}
                {hasSuggestions && (
                  <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                    <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold text-blue-700">
                      <LuLightbulb className="h-4 w-4" aria-hidden />
                      Suggestions
                    </h3>
                    <ul className="space-y-2">
                      {(checkType === 'title' || checkType === 'both') &&
                        result.title_suggestions.map((suggestion, index) => (
                          <li
                            key={`t-${index}`}
                            className="flex items-start gap-2 text-xs text-gray-900"
                          >
                            <LuLightbulb
                              className="mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"
                              aria-hidden
                            />
                            {suggestion}
                          </li>
                        ))}
                      {(checkType === 'description' || checkType === 'both') &&
                        result.description_suggestions.map(
                          (suggestion, index) => (
                            <li
                              key={`d-${index}`}
                              className="flex items-start gap-2 text-xs text-gray-900"
                            >
                              <LuLightbulb
                                className="mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"
                                aria-hidden
                              />
                              {suggestion}
                            </li>
                          )
                        )}
                    </ul>
                  </div>
                )}
              </div>
            )}
            {canFix && (
              <div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-gray-200 pt-4">
                <p className="max-w-md text-xs text-gray-500">
                  Fix with AI runs your Product Content pipeline on what you
                  checked ({FIX_CREDITS_PER_TOPIC} credits per topic: title /
                  description). Description fixes also include tags and an FAQ.
                </p>
                <button
                  type="button"
                  onClick={() => void handleFix()}
                  disabled={fixing}
                  className={primaryButtonClass}
                >
                  {fixing ? (
                    <>
                      <Spinner className="h-4 w-4" />
                      Fixing...
                    </>
                  ) : (
                    <>
                      <LuWand2 className="h-4 w-4" aria-hidden />
                      Fix with AI · {fixCost} credits
                    </>
                  )}
                </button>
              </div>
            )}
            {fixError && (
              <div className="mt-3 flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3">
                <LuAlertCircle
                  className="mt-0.5 h-4 w-4 shrink-0 text-red-500"
                  aria-hidden
                />
                <p className="text-sm text-gray-900">{fixError}</p>
              </div>
            )}
          </div>
        </div>
      )}

      {/* AI Fix result - full width */}
      {fixResult && checkType !== 'blog' && (
        <CheckerFixCard result={fixResult} />
      )}

      {/* Blog issues & suggestions - full width */}
      {blogResult && checkType === 'blog' && (
        <div className={sectionClass}>
          <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
            <LuLightbulb className="h-4 w-4 text-amber-500" aria-hidden />
            Issues &amp; Suggestions
          </h2>
          <div className="mt-4 space-y-4">
            {blogResult.content_issues.length > 0 && (
              <div className="rounded-lg border border-orange-200 bg-orange-50 p-4">
                <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold text-orange-700">
                  <LuAlertCircle className="h-4 w-4" aria-hidden />
                  Content issues
                </h3>
                <ul className="space-y-1.5">
                  {blogResult.content_issues.map((issue, index) => (
                    <li
                      key={index}
                      className="flex items-start gap-2 text-xs text-gray-900"
                    >
                      <LuXCircle
                        className="mt-0.5 h-3.5 w-3.5 shrink-0 text-orange-500"
                        aria-hidden
                      />
                      {issue}
                    </li>
                  ))}
                </ul>
              </div>
            )}
            {blogResult.keyword_issues.length > 0 && (
              <div className="rounded-lg border border-amber-200 bg-amber-50 p-4">
                <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold text-amber-700">
                  <LuType className="h-4 w-4" aria-hidden />
                  Keyword issues
                </h3>
                <ul className="space-y-1.5">
                  {blogResult.keyword_issues.map((issue, index) => (
                    <li
                      key={index}
                      className="flex items-start gap-2 text-xs text-gray-900"
                    >
                      <LuXCircle
                        className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500"
                        aria-hidden
                      />
                      {issue}
                    </li>
                  ))}
                </ul>
              </div>
            )}
            {blogResult.seo_suggestions.length > 0 && (
              <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold text-blue-700">
                  <LuLightbulb className="h-4 w-4" aria-hidden />
                  SEO suggestions
                </h3>
                <ul className="space-y-1.5">
                  {blogResult.seo_suggestions.map((suggestion, index) => (
                    <li
                      key={index}
                      className="flex items-start gap-2 text-xs text-gray-900"
                    >
                      <LuLightbulb
                        className="mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"
                        aria-hidden
                      />
                      {suggestion}
                    </li>
                  ))}
                </ul>
              </div>
            )}
            {blogResult.ai_optimization_tips.length > 0 && (
              <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4">
                <h3 className="mb-2 flex items-center gap-2 text-sm font-semibold text-emerald-700">
                  <LuBot className="h-4 w-4" aria-hidden />
                  AI optimization tips
                </h3>
                <ul className="space-y-1.5">
                  {blogResult.ai_optimization_tips.map((tip, index) => (
                    <li
                      key={index}
                      className="flex items-start gap-2 text-xs text-gray-900"
                    >
                      <LuCheckCircle
                        className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600"
                        aria-hidden
                      />
                      {tip}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Query Lab */}
      {result &&
        (checkType === 'description' || checkType === 'both') &&
        description.trim() && (
          <div className={sectionClass}>
            <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
              <LuBot className="h-4 w-4 text-pink-600" aria-hidden />
              Query Lab
            </h2>
            <p className="mt-1 text-xs text-gray-500">
              Ask questions as if you were an AI shopping assistant. See how
              well your description answers them.
            </p>
            <div className="mt-4 space-y-4">
              {preAnswered.length > 0 && (
                <div className="space-y-3">
                  <p className="text-xs font-medium text-gray-500">
                    AI-generated questions
                  </p>
                  <div className="grid gap-3 sm:grid-cols-3">
                    {preAnswered.map((item, index) => {
                      const colors = confidenceColor(item.confidence_score);

                      return (
                        <div
                          key={index}
                          className="rounded-lg border border-gray-200 bg-gray-50 p-3"
                        >
                          <div className="mb-2 flex items-start gap-2">
                            <LuHelpCircle
                              className="mt-0.5 h-3.5 w-3.5 shrink-0 text-pink-600"
                              aria-hidden
                            />
                            <p className="text-xs font-medium text-gray-900">
                              {item.question}
                            </p>
                          </div>
                          <div
                            className={`mb-2 inline-block rounded-full border px-2 py-0.5 text-xs font-bold ${colors.bg} ${colors.text} ${colors.border}`}
                          >
                            {item.confidence_score}%
                          </div>
                          <p className="text-xs text-gray-500">{item.answer}</p>
                          {item.missing_info.length > 0 && (
                            <p className="mt-1 text-[10px] text-orange-600">
                              Missing:{' '}
                              {item.missing_info.slice(0, 2).join(', ')}
                            </p>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {queryHistory.length > 0 && (
                <div className="max-h-64 space-y-2 overflow-y-auto">
                  {queryHistory.map((item, index) => {
                    const colors = confidenceColor(
                      item.result.confidence_score
                    );

                    return (
                      <div
                        key={index}
                        className="rounded-lg border border-gray-200 p-3"
                      >
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex items-start gap-2">
                            <LuHelpCircle
                              className="mt-0.5 h-3.5 w-3.5 shrink-0 text-pink-600"
                              aria-hidden
                            />
                            <div>
                              <p className="text-xs font-medium text-gray-900">
                                {item.question}
                              </p>
                              <p className="mt-0.5 text-xs text-gray-500">
                                {item.result.answer}
                              </p>
                            </div>
                          </div>
                          <span
                            className={`inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs font-medium ${colors.bg} ${colors.text} ${colors.border}`}
                          >
                            {item.result.confidence_score}%
                          </span>
                        </div>
                        {item.result.missing_info.length > 0 && (
                          <p className="mt-1 text-[10px] text-orange-600">
                            Missing: {item.result.missing_info.join(', ')}
                          </p>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}

              {queryRemaining > 0 ? (
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <LuMessageSquare
                      className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"
                      aria-hidden
                    />
                    <input
                      type="text"
                      value={queryQuestion}
                      onChange={event => setQueryQuestion(event.target.value)}
                      onKeyDown={event => {
                        if (event.key === 'Enter' && !querying) {
                          void handleQuerySubmit();
                        }
                      }}
                      placeholder="Ask a customer question about this product..."
                      disabled={querying}
                      className={`${inputClass} pl-9`}
                    />
                  </div>
                  <button
                    type="button"
                    onClick={() => void handleQuerySubmit()}
                    disabled={querying || !queryQuestion.trim()}
                    aria-label="Ask"
                    className={`${primaryButtonClass} px-3`}
                  >
                    {querying ? (
                      <Spinner className="h-4 w-4" />
                    ) : (
                      <LuSend className="h-4 w-4" aria-hidden />
                    )}
                  </button>
                </div>
              ) : (
                <p className="text-center text-xs text-gray-500">
                  Query limit reached for this session.
                </p>
              )}

              <p className="text-center text-[10px] text-gray-500">
                {queryRemaining} question{queryRemaining !== 1 ? 's' : ''}{' '}
                remaining
              </p>
            </div>
          </div>
        )}
    </div>
  );
};

export default ContentChecker;
