import React, { useEffect, useState } from 'react';
import { __, sprintf, _n } from '@wordpress/i18n';
import { api } from '../api';
import { Panel, MetricGrid, SectionTitle } from './ui';

/*
 * The sixteen-signal reference grid, moved off the dashboard (1.0 Phase 2).
 *
 * The dashboard opens on the verdict and the work queue; the full metric
 * inventory is reference, and reference lives with the analytics on the
 * Insights screen. Self-fetching, so any screen can mount it without
 * plumbing KPI state through its own props.
 */

const go = (hash) => {
	window.location.hash = hash;
};

const dash = (v) => (v === null || v === undefined ? '–' : v);

/**
 * A MetricGrid whose cells are destinations: `MetricGrid` hands back the
 * cell's id on click, so the route rides on the metric itself.
 */
function LaunchGrid({ metrics, columns = 4 }) {
	return (
		<MetricGrid
			columns={columns}
			metrics={metrics}
			onSelect={(id) => {
				const m = metrics.find((x) => (x.id || x.label) === id);
				if (m && m.href) go(m.href);
			}}
		/>
	);
}

export default function SiteMetricsPanel() {
	const [kpis, setKpis] = useState(null);
	const [setup, setSetup] = useState(null);
	const [content, setContent] = useState(null);

	useEffect(() => {
		api.get('/dashboard/kpis').then(setKpis).catch(() => {});
		api.get('/setup/status').then(setSetup).catch(() => {});
		api.get('/score/content').then(setContent).catch(() => {});
	}, []);

	if (!kpis) return null;

	const k = kpis;
	const vis = k.visibility || {};
	const search = k.search || {};
	const links = k.links || {};
	const idx = k.indexing || {};
	const cnt = k.content || {};
	const commerce = k.commerce || {};
	const health = k.health || {};

	return (
		<Panel title={__('All site metrics', 'ai-rank-suite')} note={__('16 live signals · open when you need the detail', 'ai-rank-suite')}>
		<div className="grid gap-5 p-4">
			<section className="grid gap-2">
				<SectionTitle hint={__('Where the next decade of traffic comes from', 'ai-rank-suite')}>{__('AI search', 'ai-rank-suite')}</SectionTitle>
				<LaunchGrid
					metrics={[
						{
							id: 'geo',
							label: __('AI search readiness', 'ai-rank-suite'),
							hint: __('Site-wide AI optimization, averaged across every analyzed page. The score the rest of this suite works to raise.', 'ai-rank-suite'),
							value: dash(k.geo?.value),
							unit: '/ 100',
							delta: k.geo?.delta,
							spark: k.geo?.series,
							href: '/content',
						},
						{
							id: 'visibility',
							label: __('AI Answer Simulation', 'ai-rank-suite'),
							hint: __('How often a simulated AI answer mentions this site when asked the prompts you monitor.', 'ai-rank-suite'),
							value: vis.value == null ? '—' : vis.value,
							unit: vis.value == null ? '' : '/ 100',
							delta: vis.delta,
							spark: vis.series,
							sub: vis.total
								? sprintf(/* translators: 1: mentions, 2: prompts. */ __('mentioned in %1$d of %2$d prompts', 'ai-rank-suite'), vis.mentioned, vis.total)
								: __('add prompts to start monitoring', 'ai-rank-suite'),
							href: '/ai-visibility',
						},
						{
							id: 'llms',
							label: 'llms.txt',
							hint: __('A curated map of this site for AI assistants, served at /llms.txt. One click to turn on, no config.', 'ai-rank-suite'),
							value: idx.llms_txt ? __('Live', 'ai-rank-suite') : __('Off', 'ai-rank-suite'),
							accent: idx.llms_txt ? 'var(--ars-c-green-ink)' : 'var(--ars-accent)',
							href: '/llms-txt',
						},
						{
							id: 'engine',
							label: __('AI engine', 'ai-rank-suite'),
							hint: __('The connected model powers titles, descriptions, FAQs and the autopilot. One key, stored encrypted on your own server.', 'ai-rank-suite'),
							value: setup?.ai ? __('Connected', 'ai-rank-suite') : __('Not set', 'ai-rank-suite'),
							accent: setup?.ai ? undefined : 'var(--ars-accent)',
							href: '/ai',
						},
					]}
				/>
			</section>

			<section className="grid gap-2">
				<SectionTitle hint={search.connected ? __('Live from Search Console', 'ai-rank-suite') : __('Connect Search Console for live data', 'ai-rank-suite')}>{__('Search', 'ai-rank-suite')}</SectionTitle>
				<LaunchGrid
					metrics={[
						{
							id: 'position',
							label: __('Avg. position', 'ai-rank-suite'),
							hint: __('Averaged across every tracked keyword. Lower is better.', 'ai-rank-suite'),
							value: dash(search.avg_position),
							sub: `${search.tracked || 0} keywords tracked`,
							href: '/search-console/keywords',
						},
						{
							id: 'top10',
							label: __('Top 10 positions', 'ai-rank-suite'),
							hint: __('Keywords at an average Search Console position on page one — the only page most people ever see.', 'ai-rank-suite'),
							value: search.top10 ?? 0,
							sub: sprintf(__('%s in the top 3', 'ai-rank-suite'), search.top3 ?? 0),
							href: '/search-console/keywords',
						},
						{
							id: 'clicks',
							label: __('Clicks', 'ai-rank-suite'),
							hint: __('Times somebody chose your result and arrived on the site, in the reporting period.', 'ai-rank-suite'),
							value: (search.clicks ?? 0).toLocaleString(),
							spark: search.series,
							sub: `${(search.impressions ?? 0).toLocaleString()} impressions`,
							href: '/search-console',
						},
						{
							id: 'indexnow',
							label: __('Instant indexing', 'ai-rank-suite'),
							hint: __('URLs pushed to search engines via IndexNow the moment they change. No account needed.', 'ai-rank-suite'),
							value: idx.indexnow_on ? idx.indexnow_week ?? 0 : __('Off', 'ai-rank-suite'),
							unit: idx.indexnow_on ? __('this week', 'ai-rank-suite') : '',
							accent: idx.indexnow_on ? undefined : 'var(--ars-accent)',
							href: '/google',
						},
					]}
				/>
			</section>

			<section className="grid gap-2">
				<SectionTitle hint={__('Scores stored per page — nothing is recomputed here', 'ai-rank-suite')}>{__('Content health', 'ai-rank-suite')}</SectionTitle>
				<LaunchGrid
					metrics={[
						{
							id: 'analyzed',
							label: __('Pages analyzed', 'ai-rank-suite'),
							hint: __('Published content with a stored score. Everything else on this screen reads from these results.', 'ai-rank-suite'),
							value: cnt.analyzed ?? 0,
							href: '/content',
						},
						{
							id: 'avg-geo',
							label: __('Avg. AI score', 'ai-rank-suite'),
							hint: __('How ready the analyzed pages are for AI search, averaged. The distribution behind it is in "Where this site is weak" below.', 'ai-rank-suite'),
							value: cnt.avg_geo ?? 0,
							unit: '/ 100',
							href: '/content',
						},
						{
							id: 'avg-seo',
							label: __('Avg. SEO score', 'ai-rank-suite'),
							hint: __('Classic search readiness of the same pages.', 'ai-rank-suite'),
							value: cnt.avg_seo ?? 0,
							unit: '/ 100',
							href: '/content',
						},
						{
							id: 'missing-desc',
							label: __('Missing descriptions', 'ai-rank-suite'),
							hint: __('Published pages with no meta description. Google scrapes its own snippet and llms.txt has nothing to describe the page with. The autopilot can write all of them in one run.', 'ai-rank-suite'),
							value: content?.missing_desc ?? 0,
							accent: content?.missing_desc > 0 ? 'var(--ars-accent)' : undefined,
							sub: sprintf(__('%s thin pages', 'ai-rank-suite'), content?.thin_content ?? 0),
							href: '/content/bulk',
						},
					]}
				/>
			</section>

			<section className="grid gap-2">
				<SectionTitle
					hint={
						commerce.active
							? __('Broken paths cost crawl budget — WooCommerce feeds included', 'ai-rank-suite')
							: __('Broken paths cost you crawl budget and rankings', 'ai-rank-suite')
					}
				>
					{commerce.active ? __('Technical health & store', 'ai-rank-suite') : __('Technical health', 'ai-rank-suite')}
				</SectionTitle>
				<LaunchGrid
					columns={commerce.active ? 3 : 4}
					metrics={[
						{
							id: 'broken',
							label: __('Broken links', 'ai-rank-suite'),
							hint: __('A dead link is a trust signal pointing the wrong way, and crawlers spend budget rediscovering it every time.', 'ai-rank-suite'),
							value: links.broken ?? 0,
							accent: links.broken > 0 ? 'var(--ars-c-red-ink)' : undefined,
							sub: commerce.active
								? sprintf(__('%1$s checked · %2$s redirected', 'ai-rank-suite'), (links.checked ?? 0).toLocaleString(), links.redirected ?? 0)
								: sprintf(__('%s links checked', 'ai-rank-suite'), (links.checked ?? 0).toLocaleString()),
							href: '/links/checker',
						},
						{
							id: 'notfound',
							label: __('404 errors', 'ai-rank-suite'),
							hint: __('Requests that hit nothing. A redirect rule turns each one back into a page.', 'ai-rank-suite'),
							value: links.not_found ?? 0,
							accent: links.not_found > 0 ? 'var(--ars-accent)' : undefined,
							sub: sprintf(_n('%s redirect rule active', '%s redirect rules active', links.redirects ?? 0, 'ai-rank-suite'), (links.redirects ?? 0).toLocaleString()),
							href: '/links/redirects',
						},
						...(commerce.active
							? []
							: [
									{
										id: 'redirected',
										label: __('Redirected links', 'ai-rank-suite'),
										hint: __('Links that only resolve after a redirect hop. Point them at the final URL and save the hop.', 'ai-rank-suite'),
										value: links.redirected ?? 0,
										href: '/links/checker',
									},
								]),
						{
							id: 'system',
							label: __('System', 'ai-rank-suite'),
							hint: __('Module health. A failing module is quarantined so it cannot take the site down; a second SEO plugin active means output may collide.', 'ai-rank-suite'),
							value: health.quarantined > 0 ? sprintf(__('%d failed', 'ai-rank-suite'), health.quarantined) : __('Healthy', 'ai-rank-suite'),
							accent: health.quarantined > 0 || health.conflict ? 'var(--ars-c-red-ink)' : undefined,
							sub: health.conflict ? `${health.conflict} also active` : `${health.modules ?? 0} modules running`,
							href: '/developer',
						},
						...(commerce.active
							? [
									{
										id: 'products',
										label: __('Products', 'ai-rank-suite'),
										hint: __('Published products carrying Product, Offer, Review and Shipping structured data.', 'ai-rank-suite'),
										value: commerce.products ?? 0,
										sub: 'schema-enriched',
										href: '/schema',
									},
									{
										id: 'feed-google',
										label: __('Google Merchant feed', 'ai-rank-suite'),
										hint: __('The product feed Google Merchant Center reads. Built once, cached, served instantly.', 'ai-rank-suite'),
										value: dash(commerce.feed_google),
										unit: commerce.feed_google == null ? '' : 'items',
										sub: commerce.feed_google == null ? 'not built yet' : 'cached, served instantly',
										href: '/feeds',
									},
									{
										id: 'feed-meta',
										label: __('Meta catalog feed', 'ai-rank-suite'),
										hint: __('The catalog feed Facebook & Instagram Shops read.', 'ai-rank-suite'),
										value: dash(commerce.feed_meta),
										unit: commerce.feed_meta == null ? '' : 'items',
										sub: commerce.feed_meta == null ? 'not built yet' : 'Facebook & Instagram Shops',
										href: '/feeds',
									},
								]
							: []),
					]}
				/>
			</section>
		</div>
		</Panel>
	);
}
