/**
 * Platform Frame Component.
 *
 * Reusable iframe component for embedding Sideconvo platform features.
 *
 * @package Sideconvo
 */

import { useState, useEffect, useRef } from '@wordpress/element';
import './platform-frame.css';

interface PlatformFrameProps {
	route: string;
	fullBleed?: boolean;
	tab?: string;
}

/**
 * PlatformFrame component.
 *
 * @param {PlatformFrameProps} props Component props.
 * @return {JSX.Element} PlatformFrame component.
 */
export default function PlatformFrame({ route, fullBleed = false, tab }: PlatformFrameProps) {
	const [isLoading, setIsLoading] = useState(true);
	const [hasError, setHasError] = useState(false);
	const iframeRef = useRef<HTMLIFrameElement>(null);

	// Get platform URL from global data and remove trailing slash.
	const platformUrl = ((window as any).sideconvoData?.platformUrl || '').replace(/\/$/, '');

	// Read namespace (siteId) and siteUrl from WordPress-provided global data.
	// Strip any http(s):// scheme from siteUrl — the platform expects a bare hostname.
	const namespace = (window as any).sideconvoData?.siteId || '';
	const siteUrl = ((window as any).sideconvoData?.scSiteUrl || '').replace(/^https?:\/\//, '');
	const pluginVersion = (window as any).sideconvoData?.pluginVersion || '';
	const widgetParamsNonce = (window as any).sideconvoData?.widgetParamsNonce || '';

	// Construct iframe URL with namespace, site URL, and plugin metadata.
	// The nonce is passed so the platform can echo it back in the redirect URL,
	// allowing WordPress to verify the request origin (CSRF protection).
	const tabParam = tab ? `&tab=${encodeURIComponent(tab)}` : '';
	const iframeUrl = `${platformUrl}/#/${route}/${namespace}/${siteUrl}?plugin_name=sideconvo-wp&plugin_version=${encodeURIComponent(pluginVersion)}&_wpnonce=${encodeURIComponent(widgetParamsNonce)}${tabParam}`;

	useEffect(() => {
		// Reset states when route changes.
		setIsLoading(true);
		setHasError(false);

		// Preserve scroll position when iframe loads.
		const currentScrollY = window.scrollY;

		// Restore scroll position after a brief delay to prevent auto-scroll.
		const timeoutId = setTimeout(() => {
			window.scrollTo(0, currentScrollY);
		}, 100);

		return () => clearTimeout(timeoutId);
	}, [route, namespace, siteUrl]);

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

		// Prevent iframe from scrolling into view on load.
		if (iframeRef.current) {
			iframeRef.current.focus({ preventScroll: true });
		}
	};

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

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

	if (hasError) {
		return (
			<div className="platform-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 platform content</h3>
				<p>Please check your connection and try again.</p>
				<button
					className="platform-frame__retry-button"
					onClick={() => window.location.reload()}
				>
					Retry
				</button>
			</div>
		);
	}

	const frameClass = fullBleed
		? 'platform-frame platform-frame--full-bleed'
		: 'platform-frame';

	return (
		<div className={frameClass}>
			{isLoading && <div className="platform-frame__loading" />}

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