import React, { useEffect, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Badge, Notice } from './ui';
import Explain from './Explain';
import { EngineMark } from './brands';

/**
 * Readiness per answer engine.
 *
 * A single blended "AI score" hides the only thing worth knowing: which engine
 * you are invisible to. Six columns, each with its own open items, makes the
 * gap the first thing you see rather than something you have to derive.
 */
export default function EngineReadiness() {
	const [data, setData] = useState(null);
	const [open, setOpen] = useState(null);
	const [error, setError] = useState(null);

	useEffect(() => {
		api.get('/score/engines').then(setData).catch((e) => setError(e.message));
	}, []);

	if (!data)
		return (
			<Card title={__('Answer engines', 'ai-rank-suite')}>
				{error ? <Notice tone="serious">{error}</Notice> : <div className="ars-pageskel-block" style={{ height: 120 }} aria-busy="true" />}
			</Card>
		);

	const tone = (n) => (n >= 85 ? 'green' : n >= 60 ? 'yellow' : 'red');

	return (
		<Card
			title={__('Answer engines', 'ai-rank-suite')}
			subtitle={__('Where you stand with each one — they retrieve differently, so they reward different things', 'ai-rank-suite')}
			action={<Badge tone={data.overall >= 85 ? 'good' : data.overall >= 60 ? 'warning' : 'serious'}>{sprintf(__('%d%% overall', 'ai-rank-suite'), data.overall)}</Badge>}
		>
			<div className="grid gap-3">
				{/*
				 * Six rows, not six sub-cards. The cards each carried a meter
				 * and a sentence, which made this half of the screen taller
				 * than the score it sits beside. A row per engine — name,
				 * meter, number — is the reference density; the sentence
				 * ("2 things to fix — OpenAI") moves to the hover and to the
				 * drill-down the row already opens.
				 */}
				<div className="ars-engrows">
					{data.engines.map((e) => {
						const t = tone(e.score);
						const isOpen = open === e.id;
						return (
							<button
								key={e.id}
								type="button"
								onClick={() => setOpen(isOpen ? null : e.id)}
								className={`ars-engrow${isOpen ? ' is-active' : ''}`}
								aria-expanded={isOpen}
								title={
									e.open.length === 0
										? sprintf(__('%s — nothing outstanding', 'ai-rank-suite'), e.label)
										: sprintf(_n('%1$s — %2$d thing to fix (%3$s)', '%1$s — %2$d things to fix (%3$s)', e.open.length, 'ai-rank-suite'), e.label, e.open.length, e.vendor)
								}
							>
								<span className="ars-engrow-name">
								<EngineMark id={e.id} />
								{e.label}
							</span>
								<span className="ars-engrow-track">
									<span
										className="ars-engrow-fill"
										style={{ width: `${e.score}%`, background: `var(--ars-c-${t}-ink)` }}
									/>
								</span>
								<span className="ars-engrow-value" style={{ color: `var(--ars-c-${t}-ink)` }}>
									{e.score}%
								</span>
							</button>
						);
					})}
				</div>

				{open &&
					(() => {
						const e = data.engines.find((x) => x.id === open);
						if (!e) return null;
						return (
							<div
								className="grid gap-3 p-3"
								style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)' }}
							>
								<div>
									<div className="t-overline mb-1">{sprintf(__('How %s decides', 'ai-rank-suite'), e.label)}</div>
									<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
										{e.why}
									</p>
								</div>
								<div className="grid gap-1.5">
									{e.checks.map((c) => (
										<div key={c.id} className="flex items-start gap-2">
											<span
												aria-hidden="true"
												style={{
													marginTop: 2,
													color: c.pass ? 'var(--ars-good)' : 'var(--ars-warning)',
													fontWeight: 700,
													fontSize: 12,
												}}
											>
												{c.pass ? '✓' : '!'}
											</span>
											<span className="min-w-0">
												<span
													className="block text-[12.5px] font-medium"
													style={{ color: c.pass ? 'var(--ars-ink-3)' : 'var(--ars-ink)' }}
												>
													{c.label}
												</span>
												{!c.pass && (
													<span className="block text-[11.5px]" style={{ color: 'var(--ars-ink-2)' }}>
														{c.fix}
													</span>
												)}
											</span>
										</div>
									))}
								</div>
							</div>
						);
					})()}

				<Explain title={__('Why six scores instead of one', 'ai-rank-suite')}>
					<p>
						{__('“Optimise for AI” is not one job. ChatGPT reads its own crawl and honours llms.txt. Google AI Overviews are built on the classic index, so ordinary technical SEO decides eligibility and nothing AI-specific does. Perplexity is search-grounded and rewards freshness. Copilot retrieves through Bing, so if Bing has not indexed the page nothing else matters.', 'ai-rank-suite')}
					</p>
					<p>
						{__('A single blended number averages those away and hides the only thing worth knowing — which engine you are invisible to.', 'ai-rank-suite')}
					</p>
				</Explain>
			</div>
		</Card>
	);
}
