import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Tabs } from './ui';

/**
 * Renders the page exactly as Google, Facebook/LinkedIn and X will show it.
 * The values come from the server's own resolver, so what you see here is what
 * actually ships in the <head> — no second implementation to drift apart.
 */

function truncate(text, max) {
	const value = String(text || '');
	return value.length > max ? `${value.slice(0, max - 1).trimEnd()}…` : value;
}

function prettyUrl(url) {
	try {
		const u = new URL(url);
		const parts = u.pathname.split('/').filter(Boolean);
		return [u.hostname.replace(/^www\./, ''), ...parts].join(' › ');
	} catch {
		return url;
	}
}

/**
 * A card image that degrades to the placeholder when the URL fails to load — a
 * broken-image icon in a preview reads as a plugin bug, when it is really the
 * user's image URL that is wrong.
 */
function CardImage({ src, style, placeholder, placeholderStyle }) {
	const [failed, setFailed] = useState(false);
	if (!src || failed) {
		return (
			<div className="flex items-center justify-center text-center text-[11.5px] px-3" style={placeholderStyle}>
				{src ? __('That image URL could not be loaded', 'ai-rank-suite') : placeholder}
			</div>
		);
	}
	return <img src={src} alt="" style={style} onError={() => setFailed(true)} />;
}

function Frame({ children, width = 500 }) {
	return (
		<div
			className="ars-r-md p-4 ars-frame"
			style={{ background: '#fff', border: '1px solid var(--ars-border)', maxWidth: width }}
		>
			{children}
		</div>
	);
}

export function GoogleSerp({ serp, device = 'desktop', emptyTitle, emptyDesc }) {
	const titleMax = device === 'mobile' ? 55 : 60;
	const descMax = device === 'mobile' ? 120 : 160;
	return (
		<Frame width={device === 'mobile' ? 380 : 560}>
			<div style={{ fontFamily: 'arial, sans-serif' }}>
				<div className="flex items-center gap-2 mb-1.5">
					<span
						className="inline-flex items-center justify-center ars-r-sm text-[11px] font-bold"
						style={{ width: 26, height: 26, background: '#f1f3f4', color: '#5f6368' }}
					>
						{(serp.site || '?').slice(0, 1).toUpperCase()}
					</span>
					<div className="leading-tight">
						<div style={{ fontSize: 12, color: '#202124' }}>{serp.site}</div>
						<div style={{ fontSize: 12, color: '#4d5156' }}>{truncate(prettyUrl(serp.url), 60)}</div>
					</div>
				</div>
				<div style={{ fontSize: device === 'mobile' ? 18 : 20, color: '#1a0dab', lineHeight: 1.3 }}>
					{truncate(serp.title, titleMax) || emptyTitle || __('Untitled', 'ai-rank-suite')}
				</div>
				<div style={{ fontSize: 14, color: '#4d5156', lineHeight: 1.58, marginTop: 3 }}>
					{truncate(serp.desc, descMax) || emptyDesc || __('No meta description — Google will invent one from the page text.', 'ai-rank-suite')}
				</div>
			</div>
		</Frame>
	);
}

function Facebook({ card, url }) {
	let host = url;
	try {
		host = new URL(url).hostname.replace(/^www\./, '');
	} catch {
		/* keep the raw string */
	}
	return (
		<Frame width={500}>
			<div style={{ fontFamily: 'Helvetica, Arial, sans-serif' }}>
				<CardImage
					src={card.og_image}
					style={{ width: '100%', aspectRatio: '1.91 / 1', objectFit: 'cover', display: 'block', borderRadius: 3 }}
					placeholder={__('No image — add a featured image or an OpenGraph image', 'ai-rank-suite')}
					placeholderStyle={{
						width: '100%',
						aspectRatio: '1.91 / 1',
						background: '#f0f2f5',
						color: '#65676b',
						borderRadius: 3,
					}}
				/>
				<div style={{ background: '#f2f3f5', padding: '10px 12px', borderRadius: '0 0 3px 3px' }}>
					<div style={{ fontSize: 12, color: '#65676b', textTransform: 'uppercase' }}>{host}</div>
					<div style={{ fontSize: 16, fontWeight: 600, color: '#050505', lineHeight: 1.3, marginTop: 2 }}>
						{truncate(card.og_title, 88)}
					</div>
					<div style={{ fontSize: 14, color: '#65676b', lineHeight: 1.4, marginTop: 2 }}>
						{truncate(card.og_desc, 110)}
					</div>
				</div>
			</div>
		</Frame>
	);
}

function Twitter({ card, url }) {
	let host = url;
	try {
		host = new URL(url).hostname.replace(/^www\./, '');
	} catch {
		/* keep the raw string */
	}
	const large = card.tw_card === 'summary_large_image';
	return (
		<Frame width={440}>
			<div
				style={{
					fontFamily: 'Helvetica, Arial, sans-serif',
					border: '1px solid #cfd9de',
					borderRadius: 4,
					overflow: 'hidden',
					display: large ? 'block' : 'flex',
				}}
			>
				<CardImage
					src={card.tw_image}
					style={
						large
							? { width: '100%', aspectRatio: '1.91 / 1', objectFit: 'cover', display: 'block' }
							: { width: 128, height: 128, objectFit: 'cover', flexShrink: 0 }
					}
					placeholder={__('No image', 'ai-rank-suite')}
					placeholderStyle={
						large
							? { width: '100%', aspectRatio: '1.91 / 1', background: '#f7f9f9', color: '#536471' }
							: { width: 128, height: 128, background: '#f7f9f9', color: '#536471', flexShrink: 0 }
					}
				/>
				<div style={{ padding: '10px 12px' }}>
					<div style={{ fontSize: 13, color: '#536471' }}>{host}</div>
					<div style={{ fontSize: 15, color: '#0f1419', lineHeight: 1.3, marginTop: 2 }}>
						{truncate(card.tw_title, 70)}
					</div>
					<div style={{ fontSize: 13, color: '#536471', lineHeight: 1.4, marginTop: 2 }}>
						{truncate(card.tw_desc, large ? 100 : 60)}
					</div>
				</div>
			</div>
		</Frame>
	);
}


/**
 * How the page looks as an AI citation.
 *
 * Not a mock of any one product's chrome — those change monthly and a pixel
 * copy dates instantly. What is stable is the *shape* of a generative answer:
 * a paragraph the assistant wrote, and beneath it a short list of sources,
 * each reduced to a site name and a page title. That is the entire surface a
 * page gets, and it is why the meta description and the entity name matter
 * more here than the title tag does.
 *
 * The paragraph shown is the page's own summary or description, because that
 * is the text an assistant is most likely to paraphrase. Where there is none,
 * saying so is more useful than inventing filler that suggests the page is
 * ready when it is not.
 */
function AiAnswer({ serp, engine, brand }) {
	const engines = {
		chatgpt: { name: 'ChatGPT', accent: '#10a37f', lead: __('Based on the sources I found:', 'ai-rank-suite') },
		overview: { name: __('Google AI Overview', 'ai-rank-suite'), accent: '#4285f4', lead: __('AI Overview', 'ai-rank-suite') },
		perplexity: { name: 'Perplexity', accent: '#20808d', lead: __('Answer', 'ai-rank-suite') },
		copilot: { name: 'Copilot', accent: '#0067b8', lead: __('Here is what I found:', 'ai-rank-suite') },
	};
	const e = engines[engine] || engines.chatgpt;
	const summary = (serp.summary || serp.desc || '').trim();
	const site = brand || serp.site;

	return (
		<Frame width={560}>
			<div style={{ fontFamily: 'inherit' }}>
				<div
					style={{
						display: 'inline-flex',
						alignItems: 'center',
						gap: 6,
						fontSize: 11,
						fontWeight: 700,
						letterSpacing: '0.04em',
						textTransform: 'uppercase',
						color: e.accent,
						marginBottom: 8,
					}}
				>
					<span style={{ width: 8, height: 8, background: e.accent, borderRadius: 2 }} />
					{e.lead}
				</div>

				{summary ? (
					<p style={{ margin: '0 0 12px', fontSize: 14, lineHeight: 1.6, color: '#1f1f1f' }}>
						{truncate(summary, 260)}{' '}
						<sup
							style={{
								fontSize: 10,
								fontWeight: 700,
								color: e.accent,
								background: `color-mix(in srgb, ${e.accent} 12%, white)`,
								padding: '1px 4px',
								borderRadius: 2,
							}}
						>
							1
						</sup>
					</p>
				) : (
					<p style={{ margin: '0 0 12px', fontSize: 13.5, lineHeight: 1.6, color: '#8a4b00' }}>
						{__('This page has no summary or meta description, so an assistant has to build a sentence from whatever text it happens to extract — and it will attribute that sentence to you.', 'ai-rank-suite')}
					</p>
				)}

				<div style={{ fontSize: 11, fontWeight: 600, color: '#5f6368', marginBottom: 6 }}>{__('Sources', 'ai-rank-suite')}</div>
				<div
					style={{
						display: 'flex',
						alignItems: 'flex-start',
						gap: 8,
						border: '1px solid #e1e6ef',
						borderRadius: 3,
						padding: '8px 10px',
					}}
				>
					<span
						style={{
							width: 18,
							height: 18,
							flex: 'none',
							borderRadius: 2,
							background: '#f0f4f9',
							color: '#5f6368',
							fontSize: 10,
							fontWeight: 700,
							display: 'grid',
							placeItems: 'center',
						}}
					>
						{(site || '?').slice(0, 1).toUpperCase()}
					</span>
					<span style={{ minWidth: 0 }}>
						<span style={{ display: 'block', fontSize: 12.5, fontWeight: 600, color: '#1f1f1f' }}>
							{truncate(serp.title, 70) || __('Untitled', 'ai-rank-suite')}
						</span>
						<span style={{ display: 'block', fontSize: 11.5, color: '#5f6368' }}>
							{site} · {truncate(prettyUrl(serp.url), 52)}
						</span>
					</span>
				</div>
			</div>
		</Frame>
	);
}

export default function SnippetPreview({ serp, card, brand }) {
	const [view, setView] = useState('google');
	const [device, setDevice] = useState('desktop');
	const [engine, setEngine] = useState('chatgpt');

	if (!serp) return null;

	return (
		<div className="grid gap-3">
			<div className="flex items-center justify-between gap-3 flex-wrap">
				<Tabs
					tabs={[
						{ id: 'google', label: __('Google', 'ai-rank-suite') },
						{ id: 'ai', label: __('AI answer', 'ai-rank-suite') },
						{ id: 'facebook', label: __('Social', 'ai-rank-suite') },
						{ id: 'twitter', label: 'X' },
					]}
					active={view}
					onChange={setView}
				/>
				{view === 'google' && (
					<Tabs
						tabs={[
							{ id: 'desktop', label: __('Desktop', 'ai-rank-suite') },
							{ id: 'mobile', label: __('Mobile', 'ai-rank-suite') },
						]}
						active={device}
						onChange={setDevice}
					/>
				)}
				{view === 'ai' && (
					<Tabs
						tabs={[
							{ id: 'chatgpt', label: __('ChatGPT', 'ai-rank-suite') },
							{ id: 'overview', label: __('AI Overview', 'ai-rank-suite') },
							{ id: 'perplexity', label: __('Perplexity', 'ai-rank-suite') },
							{ id: 'copilot', label: __('Copilot', 'ai-rank-suite') },
						]}
						active={engine}
						onChange={setEngine}
					/>
				)}
			</div>

			{view === 'google' && <GoogleSerp serp={serp} device={device} />}
			{view === 'ai' && <AiAnswer serp={serp} engine={engine} brand={brand} />}
			{view === 'facebook' && card && <Facebook card={card} url={serp.url} />}
			{view === 'twitter' && card && <Twitter card={card} url={serp.url} />}

			<p className="m-0 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
				{view === 'ai'
					? __('Assistants redraw their interfaces constantly; what does not change is the shape — a paragraph they wrote, and a short source list. This is the surface your page actually gets.', 'ai-rank-suite')
					: __('Rendered from the same resolver that writes your <head> — save to refresh after an edit.', 'ai-rank-suite')}
			</p>
		</div>
	);
}
