/**
 * Schema Tester component — Google Rich Results Test integration.
 *
 * @package Schema_AI
 */

import { useState, useEffect } from '@wordpress/element';
import { Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

const siteUrl = window.schemaAiData?.wpDefaults?.siteUrl || '';

function openRichResultsTest( url ) {
	window.open(
		`https://search.google.com/test/rich-results?url=${ encodeURIComponent( url ) }`,
		'_blank',
		'noopener,noreferrer'
	);
}

function SchemaTester() {
	const [ url, setUrl ] = useState( siteUrl );
	const [ pages, setPages ] = useState( [] );
	const [ loading, setLoading ] = useState( true );

	useEffect( () => {
		let cancelled = false;

		async function fetchContent() {
			try {
				const [ posts, wpPages ] = await Promise.all( [
					apiFetch( { path: '/wp/v2/posts?per_page=20&status=publish&_fields=id,title,link' } ),
					apiFetch( { path: '/wp/v2/pages?per_page=10&status=publish&_fields=id,title,link' } ),
				] );
				if ( ! cancelled ) {
					const combined = [
						...( posts || [] ).map( ( p ) => ( { id: p.id, title: p.title.rendered, link: p.link, type: 'post' } ) ),
						...( wpPages || [] ).map( ( p ) => ( { id: p.id, title: p.title.rendered, link: p.link, type: 'page' } ) ),
					];
					setPages( combined );
				}
			} catch ( err ) {
				// Silently fail — the table will just be empty.
			} finally {
				if ( ! cancelled ) {
					setLoading( false );
				}
			}
		}

		fetchContent();
		return () => {
			cancelled = true;
		};
	}, [] );

	function truncateUrl( fullUrl ) {
		try {
			const parsed = new URL( fullUrl );
			const path = parsed.pathname + parsed.search;
			return path.length > 50 ? path.substring( 0, 47 ) + '...' : path;
		} catch {
			return fullUrl;
		}
	}

	return (
		<div className="schema-ai-tester">
			{ /* Header */ }
			<div className="schema-ai-header">
				<div className="schema-ai-header-left">
					<h1 className="schema-ai-header-title">{ __( 'Schema Tester', 'schema-ai' ) }</h1>
					<span className="schema-ai-header-subtitle">{ __( 'Powered by Google Rich Results Test', 'schema-ai' ) }</span>
				</div>
			</div>

			{ /* URL Test Card */ }
			<div className="schema-ai-card schema-ai-tester-url-card">
				<h2>{ __( 'Test a URL', 'schema-ai' ) }</h2>
				<div className="schema-ai-tester-input-row">
					<input
						type="url"
						className="schema-ai-tester-url-input"
						value={ url }
						onChange={ ( e ) => setUrl( e.target.value ) }
						placeholder="https://example.com"
					/>
					<button
						type="button"
						className="button button-primary button-hero schema-ai-tester-btn"
						onClick={ () => url && openRichResultsTest( url ) }
						disabled={ ! url }
					>
						{ __( 'Test with Google', 'schema-ai' ) }
					</button>
				</div>
				<p className="schema-ai-tester-helper">
					{ __( 'Opens Google\'s Rich Results Test in a new tab', 'schema-ai' ) }
				</p>
			</div>

			{ /* Your Pages Card */ }
			<div className="schema-ai-card">
				<h2>{ __( 'Your Pages', 'schema-ai' ) }</h2>
				{ loading ? (
					<div className="schema-ai-loading"><Spinner /></div>
				) : pages.length === 0 ? (
					<p className="schema-ai-muted">{ __( 'No published posts or pages found.', 'schema-ai' ) }</p>
				) : (
					<table className="widefat striped">
						<thead>
							<tr>
								<th>{ __( 'Title', 'schema-ai' ) }</th>
								<th>{ __( 'URL', 'schema-ai' ) }</th>
								<th>{ __( 'Action', 'schema-ai' ) }</th>
							</tr>
						</thead>
						<tbody>
							{ pages.map( ( page ) => (
								<tr key={ `${ page.type }-${ page.id }` }>
									<td dangerouslySetInnerHTML={ { __html: page.title } } />
									<td className="schema-ai-tester-url-cell" title={ page.link }>{ truncateUrl( page.link ) }</td>
									<td>
										<button
											type="button"
											className="button button-small"
											onClick={ () => openRichResultsTest( page.link ) }
										>
											{ __( 'Test', 'schema-ai' ) } &#8599;
										</button>
									</td>
								</tr>
							) ) }
						</tbody>
					</table>
				) }
			</div>
		</div>
	);
}

export default SchemaTester;
