import { useState, useEffect, useRef, useCallback } from '@wordpress/element';

// ── Design tokens ──────────────────────────────────────────────────────────────
const C = {
	brand:  '#871A37',
	good:   '#1a8a5e',
	warn:   '#c47a1e',
	fail:   '#c0392b',
	border: '#e2d9d5',
	muted:  '#9a8e8a',
	text:   '#1d1717',
	hint:   '#6d6368',
	track:  '#f0ebe8',
	tabBg:  '#faf7f6',
	bg:     '#ffffff',
};

// ── Hooks ──────────────────────────────────────────────────────────────────────

function useDebounce( value, delay ) {
	const [ dv, setDv ] = useState( value );
	useEffect( () => {
		const t = setTimeout( () => setDv( value ), delay );
		return () => clearTimeout( t );
	}, [ value, delay ] );
	return dv;
}

function useMediaPicker( onSelect ) {
	const picker = useRef( null );
	return useCallback( () => {
		if ( ! window.wp?.media ) return;
		if ( picker.current ) { picker.current.open(); return; }
		picker.current = window.wp.media( {
			title: 'Select Image',
			button: { text: 'Use Image' },
			multiple: false,
		} );
		picker.current.on( 'select', () => {
			const att = picker.current.state().get( 'selection' ).first().toJSON();
			onSelect( att.url );
		} );
		picker.current.open();
	}, [ onSelect ] );
}

// ── Colour helpers ─────────────────────────────────────────────────────────────

function scoreColor( s ) {
	return s >= 80 ? C.good : s >= 50 ? C.warn : C.fail;
}
function scoreLabel( s ) {
	return s >= 80 ? 'Good SEO' : s >= 50 ? 'Needs work' : 'Poor SEO';
}
function barColor( len, lo, hi ) {
	if ( len > hi )               return C.fail;
	if ( len >= lo && len <= hi ) return C.good;
	return C.warn;
}

// ── Reusable atoms ─────────────────────────────────────────────────────────────

function ScoreRing( { score, loading } ) {
	const R    = 38;
	const circ = 2 * Math.PI * R;
	const off  = circ - ( score / 100 ) * circ;
	const col  = scoreColor( score );

	return (
		<div style={ { position: 'relative', width: 96, height: 96, flexShrink: 0 } }>
			<svg width="96" height="96" viewBox="0 0 96 96">
				<circle cx="48" cy="48" r={ R } fill="none" stroke={ C.track } strokeWidth="7" />
				<circle
					cx="48" cy="48" r={ R }
					fill="none"
					stroke={ col }
					strokeWidth="7"
					strokeLinecap="round"
					strokeDasharray={ circ }
					strokeDashoffset={ loading ? circ * 0.75 : off }
					style={ {
						transform:       'rotate(-90deg)',
						transformOrigin: '48px 48px',
						transition:      'stroke-dashoffset .65s cubic-bezier(.4,0,.2,1), stroke .25s ease',
					} }
				/>
			</svg>
			<div style={ {
				position:       'absolute',
				inset:          0,
				display:        'flex',
				flexDirection:  'column',
				alignItems:     'center',
				justifyContent: 'center',
				pointerEvents:  'none',
			} }>
				<span style={ {
					fontSize:   22,
					fontWeight: 700,
					lineHeight: 1,
					color:      loading ? C.muted : col,
					transition: 'color .25s',
				} }>
					{ loading ? '…' : score }
				</span>
				<span style={ { fontSize: 10, color: C.muted, marginTop: 2 } }>/100</span>
			</div>
		</div>
	);
}

function LengthBar( { len, lo, hi, max } ) {
	const pct = Math.min( 100, ( len / max ) * 100 );
	return (
		<div style={ { height: 3, background: C.track, borderRadius: 2, marginTop: 4 } }>
			<div style={ {
				height:     '100%',
				width:      pct + '%',
				background: barColor( len, lo, hi ),
				borderRadius: 2,
				transition: 'width .15s, background .15s',
			} } />
		</div>
	);
}

function Counter( { len, max } ) {
	const over = len > max;
	return (
		<span style={ {
			marginLeft:          'auto',
			fontSize:            11,
			color:               over ? C.fail : C.muted,
			fontVariantNumeric:  'tabular-nums',
			fontWeight:          over ? 600 : 400,
		} }>
			{ len } / { max }
		</span>
	);
}

function CheckItem( { check } ) {
	const colors = { pass: C.good, warn: C.warn, fail: C.fail };
	const icons  = { pass: '✓', warn: '!', fail: '✕' };
	const col    = colors[ check.status ] || C.muted;

	return (
		<div style={ {
			display:       'flex',
			gap:           10,
			padding:       '9px 0',
			borderBottom:  `1px solid ${ C.track }`,
			alignItems:    'flex-start',
		} }>
			<span style={ {
				width:          20,
				height:         20,
				borderRadius:   '50%',
				background:     col + '1c',
				color:          col,
				display:        'flex',
				alignItems:     'center',
				justifyContent: 'center',
				fontSize:       10,
				fontWeight:     700,
				flexShrink:     0,
				marginTop:      1,
			} }>
				{ icons[ check.status ] }
			</span>
			<span style={ { fontSize: 13, color: C.text, lineHeight: 1.55 } }>
				{ check.message }
			</span>
		</div>
	);
}

function SerpPreview( { title, url, description } ) {
	return (
		<div style={ {
			background:   '#fff',
			border:       `1px solid ${ C.border }`,
			borderRadius: 8,
			padding:      '12px 16px',
			marginTop:    16,
			fontFamily:   'arial,sans-serif',
		} }>
			<div style={ { fontSize: 11, color: C.muted, marginBottom: 6, fontFamily: 'inherit' } }>
				SERP Preview
			</div>
			<div style={ {
				fontSize:       18,
				color:          '#1a0dab',
				fontWeight:     400,
				overflow:       'hidden',
				textOverflow:   'ellipsis',
				whiteSpace:     'nowrap',
				lineHeight:     1.3,
				fontFamily:     'inherit',
			} }>
				{ title || 'Your SEO Title' }
			</div>
			<div style={ { fontSize: 13, color: '#006621', marginTop: 2, fontFamily: 'inherit' } }>
				{ url || window.location.origin }
			</div>
			<div style={ {
				fontSize:           14,
				color:              '#545454',
				marginTop:          4,
				lineHeight:         1.5,
				fontFamily:         'inherit',
				display:            '-webkit-box',
				WebkitLineClamp:    2,
				WebkitBoxOrient:    'vertical',
				overflow:           'hidden',
			} }>
				{ description || 'Your meta description will appear here.' }
			</div>
		</div>
	);
}

function Field( { label, hint, right, children } ) {
	return (
		<div style={ { marginBottom: 18 } }>
			{ label && (
				<div style={ {
					display:    'flex',
					alignItems: 'center',
					marginBottom: 5,
					gap:        4,
				} }>
					<label style={ { fontSize: 13, fontWeight: 600, color: C.text } }>
						{ label }
					</label>
					{ right }
				</div>
			) }
			{ children }
			{ hint && (
				<p style={ { fontSize: 12, color: C.hint, margin: '5px 0 0', lineHeight: 1.5 } }>
					{ hint }
				</p>
			) }
		</div>
	);
}

function SectionHead( { children } ) {
	return (
		<h3 style={ {
			fontSize:     13,
			fontWeight:   700,
			color:        C.text,
			margin:       '0 0 14px',
			paddingBottom: 7,
			borderBottom: `1px solid ${ C.track }`,
		} }>
			{ children }
		</h3>
	);
}

function MediaField( { label, hint, value, onChange } ) {
	const openPicker = useMediaPicker( onChange );
	return (
		<Field label={ label } hint={ hint }>
			<div style={ { display: 'flex', gap: 8 } }>
				<input
					type="url"
					value={ value }
					onChange={ e => onChange( e.target.value ) }
					placeholder="https://"
					style={ { ...inputSt, flex: 1 } }
				/>
				<button type="button" onClick={ openPicker } style={ smallBtnSt }>
					Choose
				</button>
			</div>
			{ value && (
				<img
					src={ value }
					alt=""
					style={ {
						maxWidth:   '100%',
						maxHeight:  72,
						marginTop:  8,
						borderRadius: 4,
						objectFit:  'cover',
						display:    'block',
					} }
				/>
			) }
		</Field>
	);
}

// ── Tab definitions ────────────────────────────────────────────────────────────
const TABS = [
	{ id: 'general',  label: 'General'  },
	{ id: 'social',   label: 'Social'   },
	{ id: 'advanced', label: 'Advanced' },
	{ id: 'schema',   label: 'Schema'   },
	{ id: 'analysis', label: 'Analysis' },
];

// ── Main component ─────────────────────────────────────────────────────────────
export default function MetaBox( {
	postId,
	nonce,
	ajaxUrl,
	meta: initialMeta,
	analysis: initialAnalysis,
	schemaTypes,
	autoTitle,
	autoDesc,
	permalink,
} ) {
	const [ tab, setTab ] = useState( 'general' );

	// All editable fields — names must match what save_post_meta() expects (minus awbseo_ prefix)
	const [ fields, setFields ] = useState( {
		focus_keyword:   initialMeta.focus_keyword   || '',
		title:           initialMeta.title           || '',
		description:     initialMeta.description     || '',
		robots_index:    initialMeta.robots_index    || 'index',
		robots_follow:   initialMeta.robots_follow   || 'follow',
		canonical:       initialMeta.canonical       || '',
		og_title:        initialMeta.og_title        || '',
		og_description:  initialMeta.og_description  || '',
		og_image:        initialMeta.og_image        || '',
		twitter_title:   initialMeta.twitter_title   || '',
		twitter_desc:    initialMeta.twitter_desc    || '',
		twitter_image:   initialMeta.twitter_image   || '',
		schema_type:     initialMeta.schema_type     || '',
		schema_data:     initialMeta.schema_data     || '',
	} );

	const [ analysis,   setAnalysis  ] = useState( initialAnalysis );
	const [ analyzing,  setAnalyzing ] = useState( false );
	const [ suggesting, setSuggesting ] = useState( false );
	const isFirstRender = useRef( true );

	// Debounce only the fields that drive the live analysis
	const analyzeKey = useDebounce(
		JSON.stringify( {
			kw: fields.focus_keyword,
			t:  fields.title,
			d:  fields.description,
		} ),
		850
	);

	// Live analysis — skip first mount (we already have server-rendered analysis)
	useEffect( () => {
		if ( isFirstRender.current ) {
			isFirstRender.current = false;
			return;
		}
		if ( ! postId ) return;

		setAnalyzing( true );
		const body = new URLSearchParams( {
			action:        'awbseo_live_analyze',
			nonce,
			post_id:       postId,
			focus_keyword: fields.focus_keyword,
			title:         fields.title,
			description:   fields.description,
		} );

		fetch( ajaxUrl, { method: 'POST', credentials: 'same-origin', body } )
			.then( r => r.json() )
			.then( d => { if ( d.success ) setAnalysis( d.data ); } )
			.catch( () => {} )
			.finally( () => setAnalyzing( false ) );
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ analyzeKey ] );

	const set = key => e => setFields( f => ( { ...f, [ key ]: e.target.value } ) );
	const setVal = key => val => setFields( f => ( { ...f, [ key ]: val } ) );

	// Suggest description
	const suggestDesc = () => {
		setSuggesting( true );
		const body = new URLSearchParams( {
			action:  'awbseo_suggest_meta_desc',
			nonce,
			post_id: postId,
		} );
		fetch( ajaxUrl, { method: 'POST', credentials: 'same-origin', body } )
			.then( r => r.json() )
			.then( d => {
				if ( d.success && d.data?.suggestion ) {
					setFields( f => ( { ...f, description: d.data.suggestion } ) );
				} else {
					const msg = d.data || 'Could not generate a suggestion. Please try again.';
					// eslint-disable-next-line no-alert
					window.alert( 'Suggest for me: ' + msg );
				}
			} )
			.catch( () => {
				// eslint-disable-next-line no-alert
				window.alert( 'Suggest for me: Request failed. Please check your connection.' );
			} )
			.finally( () => setSuggesting( false ) );
	};

	const score  = analysis?.score  ?? 0;
	const checks = analysis?.checks ?? [];

	const displayTitle = fields.title || autoTitle || '';
	const displayDesc  = fields.description || autoDesc || '';

	return (
		<div style={ {
			fontFamily: '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',
			fontSize:   14,
		} }>
			{/* Hidden inputs — submitted with the WP Update form automatically */}
			{ Object.entries( fields ).map( ( [ k, v ] ) => (
				<input key={ k } type="hidden" name={ `awbseo_${ k }` } value={ v } readOnly />
			) ) }

			{/* ── Score panel ── */}
			<div style={ {
				display:        'flex',
				alignItems:     'center',
				gap:            16,
				padding:        '14px 16px 12px',
				borderBottom:   `1px solid ${ C.border }`,
				background:     C.tabBg,
			} }>
				<ScoreRing score={ score } loading={ analyzing } />
				<div style={ { flex: 1, minWidth: 0 } }>
					<div style={ {
						fontSize:   17,
						fontWeight: 700,
						color:      scoreColor( score ),
						lineHeight: 1.2,
						transition: 'color .25s',
					} }>
						{ scoreLabel( score ) }
					</div>
					{ fields.focus_keyword ? (
						<div style={ { fontSize: 12, color: C.hint, marginTop: 4 } }>
							Keyword:{ ' ' }
							<strong style={ { color: C.text } }>{ fields.focus_keyword }</strong>
						</div>
					) : (
						<div style={ { fontSize: 12, color: C.warn, marginTop: 4 } }>
							Set a focus keyword below to unlock full analysis.
						</div>
					) }
					<div style={ { display: 'flex', gap: 5, marginTop: 8, flexWrap: 'wrap' } }>
						{ [
							{ label: 'Pass', count: checks.filter( c => c.status === 'pass' ).length, col: C.good },
							{ label: 'Warn', count: checks.filter( c => c.status === 'warn' ).length, col: C.warn },
							{ label: 'Fail', count: checks.filter( c => c.status === 'fail' ).length, col: C.fail },
						].map( ( { label, count, col } ) => (
							<span key={ label } style={ {
								fontSize:     11,
								padding:      '2px 8px',
								borderRadius: 10,
								background:   col + '18',
								color:        col,
								fontWeight:   600,
							} }>
								{ count } { label }
							</span>
						) ) }
						{ analyzing && (
							<span style={ { fontSize: 11, color: C.muted, fontStyle: 'italic' } }>
								Updating…
							</span>
						) }
					</div>
				</div>
			</div>

			{/* ── Tab bar ── */}
			<div style={ {
				display:      'flex',
				borderBottom: `1px solid ${ C.border }`,
				background:   C.tabBg,
			} }>
				{ TABS.map( t => (
					<button
						key={ t.id }
						type="button"
						onClick={ () => setTab( t.id ) }
						style={ {
							flex:        1,
							padding:     '9px 4px',
							border:      'none',
							cursor:      'pointer',
							background:  'transparent',
							fontSize:    12,
							fontWeight:  600,
							color:       tab === t.id ? C.brand : C.hint,
							borderBottom: tab === t.id ? `2px solid ${ C.brand }` : '2px solid transparent',
							transition:  'color .15s, border-color .15s',
							lineHeight:  1,
							fontFamily:  'inherit',
						} }
					>
						{ t.label }
					</button>
				) ) }
			</div>

			{/* ── Tab content ── */}
			<div style={ { padding: '18px 16px' } }>

				{/* General */}
				{ tab === 'general' && (
					<div>
						<Field
							label="Focus Keyword"
							hint="The main keyword you want this page to rank for."
						>
							<input
								type="text"
								value={ fields.focus_keyword }
								onChange={ set( 'focus_keyword' ) }
								placeholder="e.g. best wordpress seo plugin"
								style={ inputSt }
							/>
						</Field>

						<Field
							label="SEO Title"
							hint={ `Leave blank to auto-generate: ${ autoTitle }` }
							right={ <Counter len={ fields.title.length } max={ 60 } /> }
						>
							<input
								type="text"
								value={ fields.title }
								onChange={ set( 'title' ) }
								placeholder={ autoTitle }
								maxLength={ 70 }
								style={ inputSt }
							/>
							<LengthBar len={ fields.title.length } lo={ 50 } hi={ 60 } max={ 70 } />
						</Field>

						<Field
							label="Meta Description"
							hint="Write a compelling summary (120-155 chars) that makes people want to click."
							right={ <Counter len={ fields.description.length } max={ 155 } /> }
						>
							<textarea
								value={ fields.description }
								onChange={ set( 'description' ) }
								rows={ 3 }
								maxLength={ 160 }
								placeholder="Write a compelling summary..."
								style={ { ...inputSt, resize: 'vertical', minHeight: 72 } }
							/>
							<LengthBar len={ fields.description.length } lo={ 120 } hi={ 155 } max={ 160 } />
							<button
								type="button"
								onClick={ suggestDesc }
								disabled={ suggesting }
								style={ { ...smallBtnSt, marginTop: 8 } }
							>
								{ suggesting ? 'Generating…' : '✨ Suggest for me' }
							</button>
						</Field>

						<SerpPreview
							title={ displayTitle }
							url={ permalink }
							description={ displayDesc }
						/>
					</div>
				) }

				{/* Social */}
				{ tab === 'social' && (
					<div>
						<SectionHead>Open Graph (Facebook, LinkedIn)</SectionHead>

						<Field label="OG Title">
							<input
								type="text"
								value={ fields.og_title }
								onChange={ set( 'og_title' ) }
								placeholder="Leave blank to use SEO title"
								style={ inputSt }
							/>
						</Field>
						<Field label="OG Description">
							<textarea
								value={ fields.og_description }
								onChange={ set( 'og_description' ) }
								rows={ 2 }
								placeholder="Leave blank to use meta description"
								style={ { ...inputSt, resize: 'vertical' } }
							/>
						</Field>
						<MediaField
							label="OG Image"
							hint="Recommended: 1200 x 630 px"
							value={ fields.og_image }
							onChange={ setVal( 'og_image' ) }
						/>

						<div style={ { height: 20 } } />
						<SectionHead>Twitter / X Card</SectionHead>

						<Field label="Twitter Title">
							<input
								type="text"
								value={ fields.twitter_title }
								onChange={ set( 'twitter_title' ) }
								placeholder="Leave blank to use OG title"
								style={ inputSt }
							/>
						</Field>
						<Field label="Twitter Description">
							<textarea
								value={ fields.twitter_desc }
								onChange={ set( 'twitter_desc' ) }
								rows={ 2 }
								placeholder="Leave blank to use OG description"
								style={ { ...inputSt, resize: 'vertical' } }
							/>
						</Field>
						<MediaField
							label="Twitter Image"
							hint="Recommended: 1200 x 600 px"
							value={ fields.twitter_image }
							onChange={ setVal( 'twitter_image' ) }
						/>
					</div>
				) }

				{/* Advanced */}
				{ tab === 'advanced' && (
					<div>
						<Field
							label="Robots"
							hint="Set noindex on thin, duplicate, or private pages. Set nofollow if you don't want to pass link equity through this page."
						>
							<div style={ { display: 'flex', gap: 8 } }>
								<select
									value={ fields.robots_index }
									onChange={ set( 'robots_index' ) }
									style={ selectSt }
								>
									<option value="index">index</option>
									<option value="noindex">noindex</option>
								</select>
								<select
									value={ fields.robots_follow }
									onChange={ set( 'robots_follow' ) }
									style={ selectSt }
								>
									<option value="follow">follow</option>
									<option value="nofollow">nofollow</option>
								</select>
							</div>
						</Field>
						<Field
							label="Canonical URL"
							hint="Only set if this page is a duplicate and the canonical is a different URL."
						>
							<input
								type="url"
								value={ fields.canonical }
								onChange={ set( 'canonical' ) }
								placeholder={ permalink }
								style={ inputSt }
							/>
						</Field>
					</div>
				) }

				{/* Schema */}
				{ tab === 'schema' && (
					<div>
						<Field
							label="Schema Type"
							hint="CitedSEO provides 60+ schema types, all free. Leave blank to auto-detect."
						>
							<select
								value={ fields.schema_type }
								onChange={ set( 'schema_type' ) }
								style={ { ...selectSt, width: '100%' } }
							>
								<option value="">— Auto-detect —</option>
								{ Object.entries( schemaTypes || {} ).map( ( [ val, label ] ) => (
									<option key={ val } value={ val }>{ label }</option>
								) ) }
							</select>
						</Field>
						<Field
							label="Schema Data (JSON)"
							hint='Optional. Paste a full schema block or simple data. For FAQ: [{"question":"Q1?","answer":"A1"}]'
						>
							<textarea
								value={ fields.schema_data }
								onChange={ set( 'schema_data' ) }
								rows={ 8 }
								placeholder='[{"question":"Q1?","answer":"A1"},{"question":"Q2?","answer":"A2"}]'
								style={ {
									...inputSt,
									fontFamily: 'monospace',
									fontSize:   12,
									resize:     'vertical',
								} }
							/>
						</Field>
					</div>
				) }

				{/* Analysis */}
				{ tab === 'analysis' && (
					<div>
						<div style={ {
							display:        'flex',
							alignItems:     'center',
							justifyContent: 'space-between',
							marginBottom:   14,
						} }>
							<span style={ { fontSize: 13, fontWeight: 600, color: C.text } }>
								SEO Checks ({ checks.filter( c => c.status === 'pass' ).length }/{ checks.length } passing)
							</span>
							{ analyzing && (
								<span style={ { fontSize: 12, color: C.muted } }>Updating…</span>
							) }
						</div>

						{ checks.length === 0 ? (
							<p style={ { color: C.muted, fontSize: 13 } }>
								Set a focus keyword on the General tab to see your full analysis.
							</p>
						) : (
							checks.map( ( c, i ) => <CheckItem key={ i } check={ c } /> )
						) }

						<p style={ {
							marginTop:  16,
							fontSize:   12,
							color:      C.muted,
							fontStyle:  'italic',
						} }>
							Analysis updates live as you edit. Content-level checks (images, links, word count) reflect the last saved version.
						</p>
					</div>
				) }

			</div>
		</div>
	);
}

// ── Shared style objects ───────────────────────────────────────────────────────

const inputSt = {
	width:       '100%',
	padding:     '8px 10px',
	border:      '1px solid #ddd',
	borderRadius: 5,
	fontSize:    13,
	lineHeight:  1.5,
	color:       '#1d1717',
	background:  '#fff',
	boxSizing:   'border-box',
	fontFamily:  'inherit',
	outline:     'none',
};

const selectSt = {
	padding:     '8px 10px',
	border:      '1px solid #ddd',
	borderRadius: 5,
	fontSize:    13,
	background:  '#fff',
	color:       '#1d1717',
	cursor:      'pointer',
	fontFamily:  'inherit',
};

const smallBtnSt = {
	padding:     '5px 12px',
	background:  '#fff',
	border:      '1px solid #ddd',
	borderRadius: 5,
	fontSize:    12,
	cursor:      'pointer',
	color:       '#3d3535',
	fontFamily:  'inherit',
};
