/**
 * Splash Screen Component.
 *
 * Displays when user is not authenticated and needs to connect to Sideconvo.
 * Left panel: branding, headline, API Key input, notice.
 * Right panel: full-bleed platform iframe.
 *
 * @package Sideconvo
 */

import { useState } from '@wordpress/element';
import { useAuth } from '../../contexts/AuthContext';
import { useSettings } from '../../contexts/SettingsContext';
import { useViewMode } from '../../contexts/ViewModeContext';
import './splash-screen.css';

// Sideconvo Logo SVG
const SideconvoLogo = (
	<svg
		width="162"
		height="32"
		viewBox="0 0 162 32"
		fill="none"
		xmlns="http://www.w3.org/2000/svg"
	>
		<g clipPath="url(#clip0_41_355)">
			<path
				d="M16.0399 14.0754C15.4247 14.0754 14.8963 13.883 14.4585 13.4983C14.0207 13.1136 13.8009 12.65 13.8009 12.1094L19.8296 2.86817L18.2809 8.57758H30.2496C27.5689 3.47989 22.2133 0 16.0399 0C7.182 0 0 7.16369 0 15.999C0 16.6512 0.0443571 17.2917 0.119571 17.9227H16.0399C16.6551 17.9227 17.1836 18.1151 17.6214 18.4998C18.0591 18.8845 18.279 19.3481 18.279 19.8887L12.2503 29.1299L13.7989 23.4205H1.83021C4.51286 28.5182 9.86657 31.9981 16.0399 31.9981C24.8998 31.9981 32.0799 24.8344 32.0799 15.999C32.0799 15.3469 32.0355 14.7063 31.9603 14.0754H16.0399Z"
				fill="#0F1629"
			/>
			<path
				d="M39.3738 21.8951L40.7566 19.654C41.3043 20.0368 41.8867 20.3446 42.5019 20.5754C43.1191 20.8082 43.7863 20.9236 44.5096 20.9236C45.2945 20.9236 45.9039 20.7793 46.3379 20.4927C46.7718 20.2061 46.9878 19.7752 46.9878 19.2019C46.9878 18.746 46.8065 18.3671 46.4458 18.0612C46.0852 17.7554 45.4719 17.5034 44.6041 17.3033C42.851 16.8936 41.6206 16.3511 40.9128 15.6778C40.205 15.0045 39.8521 14.1158 39.8521 13.0136C39.8521 11.7478 40.3458 10.7109 41.3313 9.90492C42.3168 9.09891 43.6089 8.69495 45.2077 8.69495C46.0023 8.69495 46.7602 8.7969 47.4815 9.00273C48.2028 9.20856 48.9067 9.53366 49.5914 9.97995L48.3031 12.1652C47.7014 11.7824 47.1478 11.5093 46.6464 11.3457C46.145 11.1822 45.6281 11.0995 45.0978 11.0995C44.3495 11.0995 43.7671 11.238 43.3505 11.5169C42.9358 11.794 42.7276 12.1787 42.7276 12.6711C42.7276 13.1905 42.9397 13.5753 43.364 13.8253C43.7883 14.0754 44.5038 14.3197 45.5086 14.5563C47.0244 14.9199 48.1333 15.447 48.8373 16.1337C49.5412 16.8224 49.8922 17.738 49.8922 18.8865C49.8922 20.2446 49.3966 21.3257 48.4053 22.1317C47.414 22.9377 46.0736 23.3416 44.3861 23.3416C43.472 23.3416 42.5984 23.2205 41.7633 22.98C40.9282 22.7395 40.1317 22.376 39.3738 21.8931V21.8951Z"
				fill="#1A2236"
			/>
			<path
				d="M54.4398 6.32108C53.8554 6.32108 53.3713 6.13449 52.9876 5.7613C52.6038 5.38811 52.4128 4.92836 52.4128 4.38204C52.4128 3.83572 52.6038 3.35288 52.9876 2.98931C53.3713 2.62574 53.8554 2.44299 54.4398 2.44299C55.0241 2.44299 55.5217 2.62574 55.9055 2.98931C56.2893 3.35288 56.4802 3.81841 56.4802 4.38204C56.4802 4.94567 56.2893 5.39965 55.9055 5.76899C55.5217 6.13833 55.0338 6.323 54.4398 6.323V6.32108ZM56.0154 23.0165H52.8236V9.02574H56.0154V23.0165Z"
				fill="#1A2236"
			/>
			<path
				d="M69.6696 20.8428C69.1681 21.6815 68.5317 22.3067 67.7661 22.7203C66.9985 23.1339 66.0998 23.3416 65.068 23.3416C63.3149 23.3416 61.9071 22.7203 60.8425 21.4776C59.7779 20.2349 59.2476 18.5248 59.2476 16.3472C59.2476 14.0331 59.8338 12.1806 61.0083 10.786C62.1809 9.39323 63.7315 8.69495 65.6581 8.69495C66.5993 8.69495 67.4016 8.87 68.0688 9.2201C68.7361 9.57021 69.2703 10.1011 69.6715 10.811H69.7255V2.30457H72.9173V23.0166H69.7255V20.8447H69.6715L69.6696 20.8428ZM62.4933 16.2261C62.4933 17.6649 62.8173 18.7903 63.4653 19.6001C64.1133 20.41 64.9947 20.8159 66.1094 20.8159C67.2241 20.8159 68.0766 20.41 68.7535 19.6001C69.4285 18.7903 69.7679 17.7477 69.7679 16.4723V14.8737C69.7679 13.8349 69.4439 12.9674 68.7959 12.271C68.1479 11.5747 67.3167 11.2265 66.3023 11.2265C65.1143 11.2265 64.1847 11.6708 63.5078 12.5576C62.8328 13.4464 62.4953 14.6679 62.4953 16.2261H62.4933Z"
				fill="#1A2236"
			/>
			<path
				d="M88.9284 16.855H79.3549C79.4089 18.1766 79.7927 19.1807 80.5063 19.8675C81.2179 20.5561 82.2131 20.8986 83.4917 20.8986C84.0124 20.8986 84.6064 20.7947 85.2718 20.585C85.9391 20.3753 86.5948 20.0387 87.2447 19.5732L88.6834 21.5545C87.8156 22.1836 86.9342 22.6395 86.0394 22.9203C85.1445 23.2031 84.159 23.3435 83.0809 23.3435C80.8978 23.3435 79.2007 22.7183 77.9857 21.466C76.7707 20.2137 76.1593 18.4632 76.1497 16.2125C76.1497 13.9715 76.7764 12.1594 78.0319 10.7744C79.2874 9.38932 80.8959 8.69873 82.8611 8.69873C84.8263 8.69873 86.2245 9.28929 87.3064 10.4685C88.3884 11.6477 88.9303 13.3174 88.9303 15.4758V16.855H88.9284ZM85.8465 14.6544C85.8465 13.4521 85.5842 12.548 85.0597 11.942C84.5351 11.3361 83.7926 11.034 82.8341 11.034C81.9296 11.034 81.1601 11.3591 80.5256 12.0113C79.8911 12.6634 79.4996 13.5444 79.3549 14.6544H85.8465Z"
				fill="#1A2236"
			/>
			<path
				d="M101.747 22.224C101.109 22.6164 100.469 22.9011 99.8305 23.0781C99.1902 23.255 98.492 23.3435 97.7341 23.3435C95.7978 23.3435 94.2202 22.7126 93.0014 21.4507C91.7825 20.1887 91.1731 18.4709 91.1731 16.2933C91.1731 14.1158 91.8211 12.2133 93.1171 10.8013C94.4131 9.38933 96.1218 8.68335 98.2394 8.68335C98.8777 8.68335 99.4968 8.75837 100.095 8.90842C100.693 9.05846 101.302 9.29315 101.923 9.61248L101.198 10.9648C100.696 10.7013 100.205 10.5089 99.7263 10.3916C99.2461 10.2742 98.7235 10.2146 98.1584 10.2146C96.5519 10.2146 95.2867 10.7667 94.3649 11.867C93.443 12.9693 92.9821 14.3851 92.9821 16.1164C92.9821 17.8476 93.4315 19.2981 94.3321 20.3042C95.2308 21.3102 96.4072 21.8142 97.8595 21.8142C98.3802 21.8142 98.8951 21.743 99.4081 21.6026C99.9192 21.4622 100.43 21.2314 100.941 20.912L101.749 22.224H101.747Z"
				fill="#1A2236"
			/>
			<path
				d="M110.609 23.3436C108.546 23.3436 106.906 22.6818 105.691 21.3564C104.476 20.0311 103.869 18.294 103.869 16.1453C103.869 13.8138 104.501 11.9902 105.767 10.6744C107.032 9.35861 108.723 8.69495 110.841 8.68726C112.887 8.68726 114.493 9.33553 115.662 10.634C116.831 11.9325 117.415 13.7234 117.415 16.0106C117.415 18.2978 116.804 19.9887 115.579 21.3314C114.356 22.6761 112.698 23.3474 110.607 23.3474L110.609 23.3436ZM110.706 21.8277C112.276 21.8277 113.487 21.3199 114.335 20.3042C115.184 19.2885 115.61 17.865 115.61 16.0356C115.61 14.2062 115.186 12.7173 114.335 11.7112C113.487 10.7052 112.285 10.2012 110.733 10.2012C109.18 10.2012 107.961 10.7244 107.047 11.7728C106.135 12.8212 105.678 14.2678 105.678 16.1164C105.678 17.8554 106.129 19.2424 107.034 20.2773C107.938 21.3122 109.161 21.8277 110.704 21.8277H110.706Z"
				fill="#1A2236"
			/>
			<path
				d="M132.155 23.0165H130.402V14.9564C130.402 13.3713 130.115 12.1825 129.54 11.3899C128.965 10.5974 128.101 10.2011 126.952 10.2011C125.72 10.2011 124.701 10.6589 123.897 11.5746C123.093 12.4903 122.692 13.6348 122.692 15.0103V23.0165H120.939V9.02576H122.692V11.4573H122.746C123.267 10.5281 123.918 9.8337 124.705 9.37394C125.49 8.91419 126.404 8.68335 127.444 8.68335C128.969 8.68335 130.136 9.18158 130.944 10.18C131.752 11.1783 132.157 12.6095 132.157 14.4774V23.0165H132.155Z"
				fill="#1A2236"
			/>
			<path
				d="M146.974 9.02582L141.399 23.0166H139.713L134.344 9.02582H136.288L140.151 19.6675C140.269 19.9868 140.365 20.2888 140.439 20.5754C140.512 20.8621 140.572 21.1295 140.616 21.3738H140.67C140.724 21.0544 140.786 20.7582 140.855 20.485C140.925 20.2119 141 19.956 141.081 19.7194L145.108 9.02197H146.971L146.974 9.02582Z"
				fill="#1A2236"
			/>
			<path
				d="M155.194 23.3436C153.13 23.3436 151.491 22.6818 150.276 21.3564C149.061 20.0311 148.454 18.294 148.454 16.1453C148.454 13.8138 149.086 11.9902 150.351 10.6744C151.616 9.35861 153.308 8.69495 155.425 8.68726C157.472 8.68726 159.078 9.33553 160.247 10.634C161.416 11.9325 162 13.7234 162 16.0106C162 18.2978 161.389 19.9887 160.164 21.3314C158.941 22.6761 157.283 23.3474 155.192 23.3474L155.194 23.3436ZM155.288 21.8277C156.858 21.8277 158.069 21.3199 158.918 20.3042C159.767 19.2885 160.193 17.865 160.193 16.0356C160.193 14.2062 159.769 12.7173 158.918 11.7112C158.069 10.7052 156.868 10.2012 155.315 10.2012C153.763 10.2012 152.544 10.7244 151.63 11.7728C150.718 12.8212 150.261 14.2678 150.261 16.1164C150.261 17.8554 150.712 19.2424 151.616 20.2773C152.521 21.3122 153.744 21.8277 155.287 21.8277H155.288Z"
				fill="#1A2236"
			/>
		</g>
		<defs>
			<clipPath id="clip0_41_355">
				<rect width="162" height="32" fill="white" />
			</clipPath>
		</defs>
	</svg>
);

// Info Icon SVG
const InfoIcon = (
	<svg
		width="24"
		height="24"
		viewBox="0 0 24 24"
		fill="none"
		xmlns="http://www.w3.org/2000/svg"
	>
		<defs>
			<linearGradient id="info-icon-gradient" x1="0%" y1="0%" x2="100%" y2="100%" gradientTransform="rotate(22.87, 0.5, 0.5)">
				<stop offset="0%" style={{ stopColor: 'var(--gradient-brand-start)' }} />
				<stop offset="100%" style={{ stopColor: 'var(--gradient-brand-end)' }} />
			</linearGradient>
		</defs>
		<circle cx="12" cy="12" r="10" stroke="url(#info-icon-gradient)" strokeWidth="2" />
		<path
			d="M12 16V12M12 8H12.01"
			stroke="url(#info-icon-gradient)"
			strokeWidth="2"
			strokeLinecap="round"
			strokeLinejoin="round"
		/>
	</svg>
);

/**
 * Splash Screen component.
 *
 * @return {JSX.Element} Splash screen component.
 */
interface SplashScreenProps {
	/** When true the platform iframe is suppressed (API key validation in progress). */
	isValidating?: boolean;
	/** The API key being validated from the URL (auto-expands the input section). */
	validatingApiKey?: string;
}

export default function SplashScreen( { isValidating = false, validatingApiKey = '' }: SplashScreenProps ) {
	const { saveApiKey } = useAuth();
	const { showNotification } = useSettings();
	const { isRTL } = useViewMode();

	const [apiKey, setApiKey] = useState( () => ( isValidating && validatingApiKey ) ? validatingApiKey : '' );
	const [isSaving, setIsSaving] = useState( () => isValidating && !! validatingApiKey );
	const [errorMessage, setErrorMessage] = useState('');
	const [showApiKey, setShowApiKey] = useState( () => isValidating && !! validatingApiKey );

	const toastPosition = isRTL ? 'top-left' : 'top-right';

	// Build platform signup iframe URL with query params.
	const platformUrl = ((window as any).sideconvoData?.platformUrl || '').replace(/\/$/, '');
	const rawSiteUrl = (window as any).sideconvoData?.siteUrl || (window as any).sideconvoData?.siteDomain || '';
	const siteDomain = rawSiteUrl.replace(/^https?:\/\//, '').replace(/:\d+$/, '').replace(/^localhost$/, 'localhost.com');
	const siteId = (window as any).sideconvoData?.siteId || '';
	const pluginVersion = (window as any).sideconvoData?.pluginVersion || '';
	const indexedCount = (window as any).sideconvoData?.indexedCount || 0;
	const siteIdParam = siteId ? `&site_id=${encodeURIComponent(siteId)}` : '';
	const indexedCountParam = indexedCount > 0 ? `&indexed_count=${indexedCount}` : '';
	const iframeUrl = `${platformUrl}/#/signup?site_url=${encodeURIComponent(siteDomain)}${siteIdParam}${indexedCountParam}&plugin_name=sideconvo-wp&plugin_version=${encodeURIComponent(pluginVersion)}`;

	const handleContinue = async () => {
		if (!apiKey.trim()) {
			setErrorMessage('API Key is required');
			return;
		}

		if (apiKey.trim().length < 20) {
			setErrorMessage('Invalid API Key format');
			return;
		}

		setIsSaving(true);
		setErrorMessage('');

		const result = await saveApiKey(apiKey);

		if (result === true) {
			showNotification(
				'success',
				'API Key validated and saved successfully!',
				toastPosition
			);
		} else {
			setErrorMessage(
				typeof result === 'string'
					? result
					: 'Failed to validate API Key. Please check and try again.'
			);
			setIsSaving(false);
		}
	};

	const handleClear = () => {
		setApiKey('');
		setErrorMessage('');
	};

	return (
		<div className="splash-screen-container">
			<div className="splash-screen">
				{/* Left Panel */}
				<div className="splash-screen__left">

					{/* Logo */}
					<div className="splash-screen__logo">{SideconvoLogo}</div>

					{/* Header */}
					<div className="splash-screen__header">
						<h1 className="splash-screen__headline">
							Connect your WordPress site
						</h1>
						<p className="splash-screen__subtext">
							Sign in with Sideconvo using the panel on the right to get started.
						</p>
					</div>

					{/* Toggle */}
					<button
						type="button"
						className={`splash-screen__toggle${showApiKey ? ' splash-screen__toggle--open' : ''}`}
						onClick={() => setShowApiKey(!showApiKey)}
					>
						<span>Already have an API key?</span>
						<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
							<path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
						</svg>
					</button>

					{/* API Key Input */}
					{showApiKey && (
						<div className="splash-screen__field-wrapper">
							<label htmlFor="api-key" className="splash-screen__label">
								API Key
							</label>
							<div className="splash-screen__input-row">
								<div className="splash-screen__input-wrapper">
									<input
										id="api-key"
										type="text"
										className={`splash-screen__input ${
											errorMessage ? 'splash-screen__input--error' : ''
										}`}
										placeholder="Paste your API key..."
										value={apiKey}
										onChange={(e) => {
											setApiKey(e.target.value);
											if (errorMessage) setErrorMessage('');
										}}
										disabled={isSaving}
									/>
									{apiKey && !isSaving && (
										<button
											type="button"
											className="splash-screen__clear"
											onClick={handleClear}
											aria-label="Clear"
										>
											×
										</button>
									)}
								</div>
								<button
									type="button"
									className="splash-screen__submit"
									disabled={!apiKey.trim() || isSaving}
									onClick={handleContinue}
									aria-label="Connect with API key"
								>
									{isSaving ? (
										<span className="splash-screen__spinner" />
									) : (
										<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<path d="M5 12H19M19 12L13 6M19 12L13 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
										</svg>
									)}
								</button>
							</div>
							{errorMessage && (
								<p className="splash-screen__error">{errorMessage}</p>
							)}
						</div>
					)}

					{/* Notice */}
					<div className="splash-screen__notice">
						<div className="splash-screen__notice-icon">{InfoIcon}</div>
						<div className="splash-screen__notice-content">
							<h4 className="splash-screen__notice-title">
								For Staging & Development Sites
							</h4>
							<p className="splash-screen__notice-text">
								If you use a different domain name for your staging or development
								site, add it in your dashboard under Allowed Origins in Site
								Preferences.
							</p>
						</div>
					</div>

				</div>

				{/* Right Panel — suppressed while validating to avoid loading the iframe */}
				<div className="splash-screen__right">
					{ isValidating ? (
						<div className="splash-screen__validating">
							<span className="splash-screen__spinner" />
							<p className="splash-screen__validating-text">Validating your API key…</p>
						</div>
					) : (
						<iframe
							src={iframeUrl}
							className="splash-screen__iframe"
							title="Sideconvo Platform"
							allow="clipboard-write; payment"
							sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation-by-user-activation"
						/>
					) }
				</div>
			</div>
		</div>
	);
}
