/**
 * Playground Frame Component.
 *
 * Iframe component for embedding the Sideconvo client playground.
 * URL format: {clientUrl}/playground/{siteId}
 *
 * @package Sideconvo
 */

import { useState } from '@wordpress/element';
import './playground-frame.css';

/**
 * PlaygroundFrame component.
 *
 * @return {JSX.Element} PlaygroundFrame component.
 */
export default function PlaygroundFrame() {
	const [isLoading, setIsLoading] = useState(true);
	const [hasError, setHasError] = useState(false);

	const clientUrl = ((window as any).sideconvoData?.clientUrl || '').replace(/\/$/, '');
	const siteId    = (window as any).sideconvoData?.siteId || '';
	const iframeUrl = `${clientUrl}/playground/${siteId}`;

	const handleLoad = () => {
		setIsLoading(false);
		setHasError(false);
	};

	const handleError = () => {
		setIsLoading(false);
		setHasError(true);
	};

	if (!siteId) {
		return (
			<div className="playground-frame__error">
				<h3>Site not connected</h3>
				<p>Your site is not configured. Please check your API key in Settings.</p>
			</div>
		);
	}

	if (hasError) {
		return (
			<div className="playground-frame__error">
				<svg width="48" height="48" viewBox="0 0 48 48" fill="none">
					<circle cx="24" cy="24" r="20" stroke="#EF4444" strokeWidth="2"/>
					<path d="M24 16V26M24 30V32" stroke="#EF4444" strokeWidth="2" strokeLinecap="round"/>
				</svg>
				<h3>Failed to load playground</h3>
				<p>Please check your connection and try again.</p>
				<button
					className="playground-frame__retry-button"
					onClick={() => window.location.reload()}
				>
					Retry
				</button>
			</div>
		);
	}

	return (
		<div className="playground-frame playground-frame--full-bleed">
			{isLoading && <div className="playground-frame__loading" />}

			<iframe
				src={iframeUrl}
				className="playground-frame__iframe"
				title="Sideconvo Playground"
				onLoad={handleLoad}
				onError={handleError}
				allow="clipboard-write"
				sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation-by-user-activation"
			/>
		</div>
	);
}
