import { __, _n, sprintf } from '@wordpress/i18n';
import React from 'react';
import { useSettings } from '../useSettings';
import ScreenVerdict from '../components/ScreenVerdict';
import { GoogleSerp } from '../components/SnippetPreview';
import { api, env } from '../api';
import { Card, Button, Switch, Badge, Notice, Tabs, LengthMeter, PageState } from '../components/ui';
import Social from './Social';

const SEPARATORS = ['–', '—', '-', '·', '•', '|', '/', '>', '~', '»'];

/** The sample values a preview is rendered against. */
const SAMPLE = {
	'%title%': __('What is GEO optimization?', 'ai-rank-suite'),
	'%excerpt%': __('A short introduction to generative engine optimization.', 'ai-rank-suite'),
	'%category%': __('Guides', 'ai-rank-suite'),
	'%author%': 'Alex Weber',
	'%date%': new Date().toLocaleDateString(),
};

function fill(template, sep) {
	if (!template) return '';
	return template
		.replaceAll('%sitename%', env.siteName || window.airanksuiteData?.siteName || '')
		.replaceAll('%tagline%', window.airanksuiteData?.tagline || '')
		.replaceAll('%sep%', sep)
		.replace(/%([a-z0-9_]+)%/gi, (m) => SAMPLE[m] ?? '')
		.replace(/\s{2,}/g, ' ')
		.trim();
}

/* The Google preview is the shared GoogleSerp from SnippetPreview — the
   fourth hand-rolled copy of Google's result markup died here (audit L2). */

function VariableHints({ variables, className = '' }) {
	return (
		<div className={`flex flex-wrap gap-1.5 text-[12px] ${className}`} style={{ color: 'var(--ars-ink-3)' }}>
			{Object.entries(variables).map(([token, label]) => (
				<code
					key={token}
					title={label}
					className="ars-mono px-1.5 py-0.5 rounded"
					style={{ background: 'var(--ars-surface-2)' }}
				>
					{token}
				</code>
			))}
		</div>
	);
}

export default function Seo({ tab = 'general', onTab }) {
	const { data, setData, s, update, save, busy, saved, error } = useSettings('/settings/seo');

	if (!data) return <PageState error={error} />;
	const variables = data.variables || {};
	const postTypes = data.post_types || [];
	const templates = s.templates || {};

	const setTemplate = (type, kind, value) =>
		update({ templates: { ...templates, [type]: { ...(templates[type] || {}), [kind]: value } } });

	const SaveRow = () => (
		<div className="flex items-center gap-2">
			<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
			{saved && <Badge tone="good">✓ Saved</Badge>}
		</div>
	);

	const sampleUrl = `${env.homeUrl.replace(/\/$/, '')}/what-is-geo-optimization/`;

	// What this screen controls is whether the plugin writes the <title> and
	// meta tags at all — and whether another SEO plugin is doing so already.
	const verdict = data.conflict && !s.force_output
		? {
				tone: 'neutral',
				text: sprintf(__('%s is writing titles and metas, so this plugin steps back.', 'ai-rank-suite'), data.conflict),
				why: __('Two plugins writing the same tags produce duplicate <title>s. Force output below only after switching the other one off.', 'ai-rank-suite'),
			}
		: !s.enabled
			? {
					tone: 'warning',
					text: __('Title and meta output is switched off.', 'ai-rank-suite'),
					why: __('Pages fall back to whatever the theme prints — usually the bare post title and no description at all.', 'ai-rank-suite'),
				}
			: {
					tone: 'good',
					text: sprintf(__('Titles follow “%s”.', 'ai-rank-suite'), s.title_template || '%title% %sep% %sitename%'),
					why: __('The templates below are the default for every page; a page with its own SEO title in the editor overrides them.', 'ai-rank-suite'),
				};

	return (
		<div className="ars-page">
			<ScreenVerdict {...verdict} />
			{data.conflict && (
				<Notice tone={s.force_output ? 'serious' : 'warning'}>
					<strong>{data.conflict}</strong> {__('is active and already outputs SEO meta tags.', 'ai-rank-suite')}{' '}
					{s.force_output
						? __('Forced output is ON — you will get duplicate tags unless you disable the other plugin.', 'ai-rank-suite')
						: __('AI Rank Suite automatically defers its SEO output to avoid duplicates; per-page analysis keeps working. Enable “Force output” only after disabling the other plugin.', 'ai-rank-suite')}
				</Notice>
			)}

			{error && <Notice tone="serious">{error}</Notice>}

			<Tabs
				tabs={[
					{ id: 'general', label: __('General', 'ai-rank-suite') },
					{ id: 'templates', label: __('Templates', 'ai-rank-suite') },
					{ id: 'social', label: __('Social', 'ai-rank-suite') },
					{ id: 'rss', label: __('RSS', 'ai-rank-suite') },
				]}
				active={tab}
				onChange={onTab}
			/>

			{tab === 'general' && (
				<Card
					title={__('On-page SEO output', 'ai-rank-suite')}
					subtitle={__('Title tag, meta description, canonical, Open Graph and Twitter cards — the tags every engine and assistant reads. Set them once as a pattern; override per page only where it earns its keep.', 'ai-rank-suite')}
					action={saved && <Badge tone="good">✓ Saved</Badge>}
				>
					<div className="grid gap-4">
						<Switch checked={!!s.enabled} onChange={(v) => update({ enabled: v })} label={__('Enable SEO output', 'ai-rank-suite')} />

						{/* Capped at the width of a real SERP entry. Full-bleed, the 6px
					    length meter ran 900px across the card and read as a stray rule
					    under the token chips rather than as a gauge belonging to the
					    field above it — and the snippet preview lied about how much room
					    Google actually gives a title. */}
						<div className="max-w-[620px]">
							<label className="block font-medium mb-1">{__('Site-wide title template', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={s.title_template}
								onChange={(e) => update({ title_template: e.target.value })}
							/>
							<VariableHints variables={variables} className="mt-1.5" />
							<div className="mt-1.5">
								<LengthMeter value={fill(s.title_template, s.separator)} kind="title" />
							</div>
							<div className="mt-2">
								<GoogleSerp serp={{ site: env.siteName || window.airanksuiteData?.siteName || '', url: sampleUrl, title: fill(s.title_template, s.separator), desc: '' }} emptyTitle={__('(empty — WordPress will pick the title)', 'ai-rank-suite')} emptyDesc={__('(empty — the excerpt is used)', 'ai-rank-suite')} />
							</div>
						</div>

						<div>
							<label className="block font-medium mb-1.5">{__('Separator', 'ai-rank-suite')}</label>
							<div className="flex flex-wrap items-center gap-2">
								{SEPARATORS.map((sep) => (
									<button
										key={sep}
										type="button"
										onClick={() => update({ separator: sep })}
										className="cursor-pointer grid place-items-center"
										style={{
											width: 38,
											height: 38,
											borderRadius: 'var(--ars-r-md)',
											fontSize: 16,
											border: `1px solid ${s.separator === sep ? 'var(--ars-brand)' : 'var(--ars-border)'}`,
											background: s.separator === sep ? 'var(--ars-brand-tonal)' : 'var(--ars-surface)',
											color: s.separator === sep ? 'var(--ars-brand-tonal-ink)' : 'var(--ars-ink-2)',
										}}
										aria-pressed={s.separator === sep}
										aria-label={`Separator ${sep}`}
									>
										{sep}
									</button>
								))}
								{/* An unlabelled 90px box at the end of a row of 38px swatches read
								    as a stray field. Same height as the swatches now, and it says
								    what it is. */}
								<span className="inline-flex items-center gap-1.5 ml-1">
									<span className="t-caption">{__('or type one', 'ai-rank-suite')}</span>
									<input
										type="text"
										value={s.separator}
										onChange={(e) => update({ separator: e.target.value })}
										style={{ width: 72, height: 38, textAlign: 'center', padding: '0 8px' }}
										aria-label={__('Custom separator', 'ai-rank-suite')}
									/>
								</span>
							</div>
						</div>

						<Switch
							checked={!!s.social_tags}
							onChange={(v) => update({ social_tags: v })}
							label={__('Output Open Graph & Twitter card tags', 'ai-rank-suite')}
						/>

						{data.conflict && (
							<Switch
								checked={!!s.force_output}
								onChange={(v) => update({ force_output: v })}
								label={sprintf(__('Force output although %s is active (advanced)', 'ai-rank-suite'), data.conflict)}
							/>
						)}

						<SaveRow />
					</div>
				</Card>
			)}

			{tab === 'templates' && (
				<div className="grid gap-4">
					<Card
						title={__('Per content type', 'ai-rank-suite')}
						subtitle={__('A blog post and a product page rarely want the same title pattern. Leave a field empty and the site-wide template applies.', 'ai-rank-suite')}
						action={<SaveRow />}
					>
						<div className="grid gap-5">
							{postTypes.map((pt) => {
								const t = templates[pt.name] || {};
								const titleTemplate = t.title || s.title_template;
								return (
									<div key={pt.name} className="grid gap-3 ars-r-lg p-4" style={{ background: 'var(--ars-surface-2)' }}>
										<div className="flex items-center gap-2">
											<span className="font-semibold text-[13px]">{pt.label}</span>
											<Badge tone={t.title || t.desc ? 'brand' : 'neutral'}>
												{t.title || t.desc ? 'custom' : 'site-wide'}
											</Badge>
										</div>

										<div>
											<label className="block font-medium mb-1 text-[12.5px]">{__('Title template', 'ai-rank-suite')}</label>
											<input
												type="text"
												placeholder={s.title_template}
												value={t.title || ''}
												onChange={(e) => setTemplate(pt.name, 'title', e.target.value)}
											/>
										</div>
										<div>
											<label className="block font-medium mb-1 text-[12.5px]">{__('Meta description template', 'ai-rank-suite')}</label>
											<textarea
												rows={2}
												placeholder={__('Leave empty to use the page excerpt', 'ai-rank-suite')}
												value={t.desc || ''}
												onChange={(e) => setTemplate(pt.name, 'desc', e.target.value)}
											/>
										</div>

										<GoogleSerp serp={{ site: env.siteName || window.airanksuiteData?.siteName || '', url: sampleUrl, title: fill(titleTemplate, s.separator), desc: fill(t.desc, s.separator) }} emptyTitle={__('(empty — WordPress will pick the title)', 'ai-rank-suite')} emptyDesc={__('(empty — the excerpt is used)', 'ai-rank-suite')} />
										<div className="grid gap-1.5">
											<LengthMeter value={fill(titleTemplate, s.separator)} kind="title" />
											{t.desc && <LengthMeter value={fill(t.desc, s.separator)} kind="description" />}
										</div>
									</div>
								);
							})}
						</div>
					</Card>

					<Card title={__('Variables', 'ai-rank-suite')} subtitle={__('Replaced per page wherever a template accepts text', 'ai-rank-suite')}>
						<div className="grid gap-1.5 sm:grid-cols-2">
							{Object.entries(variables).map(([token, label]) => (
								<div
									key={token}
									className="flex items-center justify-between gap-3 ars-r-lg px-3 py-2"
									style={{ background: 'var(--ars-surface-2)' }}
								>
									<code className="ars-mono text-[12px]">{token}</code>
									<span className="text-[12px]" style={{ color: 'var(--ars-ink-2)' }}>
										{label}
									</span>
								</div>
							))}
						</div>
						<p className="m-0 mt-3 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
							{__('A description you wrote for a specific page always wins over a template — a pattern fills the gaps, it never overwrites deliberate work.', 'ai-rank-suite')}
						</p>
					</Card>
				</div>
			)}

			{tab === 'social' && <Social />}

			{tab === 'rss' && (
				<Card
					title={__('RSS feed protection', 'ai-rank-suite')}
					subtitle={__('Scrapers steal content through your feed. A credit line in every item turns stolen copies into backlinks.', 'ai-rank-suite')}
					action={<SaveRow />}
				>
					<div className="grid gap-4">
						<div>
							<label className="block font-medium mb-1">{__('Before each feed item', 'ai-rank-suite')}</label>
							<input type="text" value={s.rss_before || ''} onChange={(e) => update({ rss_before: e.target.value })} />
						</div>
						<div>
							<label className="block font-medium mb-1">{__('After each feed item', 'ai-rank-suite')}</label>
							<input
								type="text"
								placeholder={__('This post first appeared on %sitename%: %post_link%', 'ai-rank-suite')}
								value={s.rss_after || ''}
								onChange={(e) => update({ rss_after: e.target.value })}
							/>
						</div>
						<div className="flex flex-wrap gap-1.5 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>
							{['%post_link%', '%post_url%', '%sitename%', '%site_link%', '%author%'].map((v) => (
								<code key={v} className="ars-mono px-1.5 py-0.5 rounded" style={{ background: 'var(--ars-surface-2)' }}>
									{v}
								</code>
							))}
						</div>
						<div className="ars-r-lg px-4 py-3 text-[13px]" style={{ background: 'var(--ars-surface-2)' }}>
							<div className="text-[11.5px] font-semibold mb-1" style={{ color: 'var(--ars-ink-3)' }}>{__('Preview of one feed item', 'ai-rank-suite')}</div>
							{s.rss_before && <div style={{ color: 'var(--ars-ink-2)' }}>{fill(s.rss_before, s.separator)}</div>}
							<div style={{ color: 'var(--ars-ink-3)' }}>{__('… the post content …', 'ai-rank-suite')}</div>
							{s.rss_after && <div style={{ color: 'var(--ars-ink-2)' }}>{fill(s.rss_after, s.separator)}</div>}
							{!s.rss_before && !s.rss_after && (
								<div style={{ color: 'var(--ars-ink-3)' }}>{__('No credit line — a scraped copy carries nothing back.', 'ai-rank-suite')}</div>
							)}
						</div>
					</div>
				</Card>
			)}
		</div>
	);
}
