/**
 * Retrieves the translation of text.
 */
import { __ } from "@wordpress/i18n";

/**
 * React hook that is used to mark the block wrapper element.
 */
import { useBlockProps, InspectorControls } from "@wordpress/block-editor";

/**
 * Inspector controls components
 */
import {
	PanelBody,
	SelectControl,
	TextControl,
	Flex,
	FlexItem,
	Button,
	Spinner,
	Notice,
	Modal,
	TabPanel,
	SearchControl,
	Card,
	CardBody,
} from "@wordpress/components";

/**
 * WordPress data hooks
 */
import { useSelect } from "@wordpress/data";
import { useState, useEffect } from "@wordpress/element";
import apiFetch from "@wordpress/api-fetch";

// ==================== CONSTANTS ====================
const MIN_WIDTH = 800;
const MIN_HEIGHT = 450;
const DEMO_IMAGE_URL =
	"https://static.scan-the-world.com/assets/DEFAULT_THUMBNAIL.jpg";

const getPricingUrl = () => {
	return window.location.hostname === "localhost"
		? "https://staging.scan-the-world.com/pricing"
		: "https://www.scan-the-world.com/pricing";
};

// ==================== CONTEXT DETECTION ====================
const useEditorContext = () => {
	return useSelect((select) => {
		const editor = select("core/editor");
		const editSite = select("core/edit-site");

		const postId = editor?.getCurrentPostId?.() || null;
		const postType = editor?.getCurrentPostType?.() || null;
		const editedPostType = editSite?.getEditedPostType?.() || null;
		const templateId = editSite?.getEditedPostId?.() || null;

		// We're in a template if editedPostType is 'wp_template'
		const isInTemplate = editedPostType === "wp_template";

		// Check if it's specifically single-product template
		const isSingleProductTemplate =
			isInTemplate &&
			templateId &&
			typeof templateId === "string" &&
			templateId.split("//").pop() === "single-product";

		// We're in a page context only if we have a numeric postId and NOT in template editor.
		// WordPress can sometimes provide non-numeric identifiers (e.g. "twentytwentyfive//index"),
		// in which case we should NOT treat it as a page context for embedding.
		const isNumericPostId =
			(typeof postId === "number" && Number.isInteger(postId)) ||
			(typeof postId === "string" && /^\d+$/.test(postId));
		const isPageContext = isNumericPostId;

		return {
			postId,
			postType,
			isInTemplate,
			isSingleProductTemplate,
			isPageContext,
			// Embed is allowed only in pages or single-product template
			isEmbedAllowed: isPageContext || isSingleProductTemplate,
		};
	}, []);
};

/**
 * The edit function - displays demo STW 3D iframe in editor with container size controls
 */
export default function Edit({ attributes, setAttributes }) {
	const { width, height, aspectRatio } = attributes;

	// Get editor context
	const { postId, isPageContext, isSingleProductTemplate, isEmbedAllowed } =
		useEditorContext();

	// State management
	const [state, setState] = useState({
		linkedEntityId: null,
		linkedEntityType: null,
		isLoadingLink: false,
		linkMessage: null,
		isModalOpen: false,
		allItems: [],
		allRooms: [],
		isLoadingModal: false,
		searchTerm: "",
		selectedEntity: null,
		isEnablingEmbed: false,
		embedError: null,
		confirmModal: null,
	});

	// Helper to update state
	const updateState = (updates) => {
		setState((prev) => ({ ...prev, ...updates }));
	};

	// ==================== DATA FETCHING ====================
	// Load current link when in page context
	useEffect(() => {
		if (!isPageContext || !postId) return;

		updateState({ isLoadingLink: true });

		apiFetch({
			path: `/3d-scan-and-show/v1/page-item-link/${postId}`,
		})
			.then((response) => {
				if (response.success && response.entity_id) {
					updateState({
						linkedEntityId: response.entity_id,
						linkedEntityType: response.entity_type || "item",
					});
				}
			})
			.catch((error) => {
				console.error("Error fetching linked entity:", error);
			})
			.finally(() => {
				updateState({ isLoadingLink: false });
			});
	}, [isPageContext, postId]);

	// ==================== MODAL HANDLERS ====================
	const loadModalData = () => {
		updateState({ isLoadingModal: true, embedError: null });

		Promise.all([
			apiFetch({ path: "/3d-scan-and-show/v1/all-items" }),
			apiFetch({
				path: "/3d-scan-and-show/v1/rooms?page=1&pageSize=100",
			}),
		])
			.then(([itemsResponse, roomsResponse]) => {
				updateState({
					allItems: itemsResponse.success ? itemsResponse.items : [],
					allRooms: roomsResponse.success ? roomsResponse.rooms : [],
				});
			})
			.catch((error) => {
				console.error("Error loading modal data:", error);

				// Check if the error is due to not being connected/logged in
				const isNotConnectedError =
					error.code === "fetch_failed" ||
					error.message === "Not connected" ||
					(error.data && error.data.status === 500);

				updateState({
					embedError: {
						message: isNotConnectedError
							? __(
									"You are not connected to STW. Please go to the plugin settings page and log in with your STW account.",
									"3d-scan-and-show",
							  )
							: __("Failed to load items and rooms.", "3d-scan-and-show"),
						showPricingButton: false,
						showSettingsButton: isNotConnectedError,
					},
				});
			})
			.finally(() => {
				updateState({ isLoadingModal: false });
			});
	};

	const handleOpenModal = () => {
		updateState({
			isModalOpen: true,
			searchTerm: "",
			selectedEntity: null,
		});
		loadModalData();
	};

	const handleSelectEntity = (entity, type) => {
		updateState({ selectedEntity: { ...entity, entityType: type } });
	};

	// ==================== EMBED MANAGEMENT ====================
	const enableEmbed = async (entityId, entityType, entityName) => {
		return new Promise((resolve) => {
			updateState({
				confirmModal: {
					title: __("Confirm Enable Embed", "3d-scan-and-show"),
					message: __(
						`Are you sure you want to enable embed for "${entityName}"? This will use one of your embed quota.`,
						"3d-scan-and-show",
					),
					onConfirm: async () => {
						updateState({
							confirmModal: null,
							isEnablingEmbed: true,
							embedError: null,
						});

						try {
							const path =
								entityType === "room"
									? `/3d-scan-and-show/v1/room/${entityId}/embed`
									: `/3d-scan-and-show/v1/item/${entityId}/embed`;

							const response = await apiFetch({ path, method: "POST" });

							if (response.success) {
								updateState({ isEnablingEmbed: false });
								resolve(true);
								return;
							}
						} catch (error) {
							console.error("Error enabling embed:", error);

							const isQuotaError =
								(error.data &&
									(error.data.status === 500 || error.data.status === 403)) ||
								error.code === "embed_failed";

							updateState({
								embedError: isQuotaError
									? {
											message: __(
												"Insufficient embed quota. Please upgrade your subscription.",
												"3d-scan-and-show",
											),
											showPricingButton: true,
											pricingUrl: getPricingUrl(),
									  }
									: {
											message: __(
												"Failed to enable embed.",
												"3d-scan-and-show",
											),
											showPricingButton: false,
									  },
								isEnablingEmbed: false,
							});
							resolve(false);
							return;
						}

						updateState({ isEnablingEmbed: false });
						resolve(false);
					},
					onCancel: () => {
						updateState({ confirmModal: null });
						resolve(false);
					},
				},
			});
		});
	};

	// ==================== LINK MANAGEMENT ====================
	const handleSaveSelection = async () => {
		const { selectedEntity } = state;
		if (!selectedEntity || !postId) return;

		updateState({ isLoadingLink: true, linkMessage: null, embedError: null });

		try {
			// Check if embed needs to be enabled
			if (!selectedEntity.is_embed_enabled) {
				const embedSuccess = await enableEmbed(
					selectedEntity.id,
					selectedEntity.entityType,
					selectedEntity.name,
				);
				if (!embedSuccess) {
					updateState({ isLoadingLink: false });
					return;
				}
			}

			// Link the page to the entity
			const response = await apiFetch({
				path: "/3d-scan-and-show/v1/page-item-link",
				method: "POST",
				data: {
					page_id: postId,
					entity_id: selectedEntity.id,
					entity_type: selectedEntity.entityType,
				},
			});

			if (response.success) {
				updateState({
					linkedEntityId: selectedEntity.id,
					linkedEntityType: selectedEntity.entityType,
					linkMessage: {
						type: "success",
						text: __("Linked successfully!", "3d-scan-and-show"),
					},
					isModalOpen: false,
				});
			}
		} catch (error) {
			console.error("Error linking:", error);
			updateState({
				linkMessage: {
					type: "error",
					text: __("Failed to link.", "3d-scan-and-show"),
				},
			});
		} finally {
			updateState({ isLoadingLink: false });
		}
	};

	const handleUnlink = () => {
		if (!postId) return;

		updateState({ isLoadingLink: true, linkMessage: null });

		apiFetch({
			path: `/3d-scan-and-show/v1/page-item-link/${postId}`,
			method: "DELETE",
		})
			.then((response) => {
				if (response.success) {
					updateState({
						linkedEntityId: null,
						linkedEntityType: null,
						linkMessage: {
							type: "success",
							text: __("Unlinked successfully!", "3d-scan-and-show"),
						},
					});
				}
			})
			.catch((error) => {
				console.error("Error unlinking:", error);
				updateState({
					linkMessage: {
						type: "error",
						text: __("Failed to unlink.", "3d-scan-and-show"),
					},
				});
			})
			.finally(() => {
				updateState({ isLoadingLink: false });
			});
	};

	// ==================== DIMENSIONS & STYLING ====================
	const actualWidth = width || MIN_WIDTH;
	const actualHeight = height || MIN_HEIGHT;

	const containerStyle = {
		width: `${actualWidth}px`,
		margin: "0 auto",
		...(aspectRatio === "custom" || (aspectRatio === "auto" && height)
			? { height: `${actualHeight}px` }
			: aspectRatio && aspectRatio !== "auto"
			? { aspectRatio }
			: { aspectRatio: "16/9" }),
	};

	const blockProps = useBlockProps({ style: containerStyle });

	const onChangeWidth = (value) => {
		const numValue = value ? parseInt(value) : undefined;
		setAttributes({
			width: numValue && numValue > 0 ? numValue : undefined,
		});
	};

	const onChangeHeight = (value) => {
		const numValue = value ? parseInt(value) : undefined;
		if (numValue && numValue > 0) {
			setAttributes({
				height: numValue,
				...(width || actualWidth ? { aspectRatio: "custom" } : {}),
			});
		} else {
			setAttributes({ height: undefined });
		}
	};

	const onChangeAspectRatio = (newRatio) => {
		setAttributes({
			aspectRatio: newRatio,
			...(newRatio !== "custom" && newRatio !== "auto"
				? { height: undefined }
				: {}),
		});
	};

	// ==================== HELPERS ====================
	const getLinkedEntity = () => {
		const { linkedEntityId, linkedEntityType, allRooms, allItems } = state;
		if (!linkedEntityId) return null;

		return linkedEntityType === "room"
			? allRooms.find((room) => room.id === linkedEntityId)
			: allItems.find((item) => item.id === linkedEntityId);
	};

	const linkedEntity = getLinkedEntity();

	const filterEntities = (entities) => {
		const { searchTerm } = state;
		if (!searchTerm) return entities;
		const term = searchTerm.toLowerCase();
		return entities.filter(
			(entity) =>
				entity.name?.toLowerCase().includes(term) ||
				entity.id?.toLowerCase().includes(term),
		);
	};

	const filteredItems = filterEntities(state.allItems);
	const filteredRooms = filterEntities(state.allRooms);

	// If embedding is not allowed, show a message
	if (!isEmbedAllowed) {
		return (
			<div {...blockProps}>
				<div
					style={{
						border: "2px solid #000",
						borderRadius: "8px",
						background: "#f9f9f9",
						padding: "40px 20px",
						textAlign: "center",
						minHeight: "200px",
						display: "flex",
						alignItems: "center",
						justifyContent: "center",
					}}
				>
					<p
						style={{
							fontSize: "16px",
							color: "#666",
							margin: 0,
							lineHeight: "1.6",
						}}
					>
						{__(
							"This block is not valid in this template. Please use it on a page or in the single product template.",
							"3d-scan-and-show",
						)}
					</p>
				</div>
			</div>
		);
	}

	return (
		<>
			<InspectorControls>
				{isPageContext && (
					<PanelBody
						title={__("STW Item Linking", "3d-scan-and-show")}
						initialOpen={true}
					>
						<p style={{ marginBottom: "12px" }}>
							{__(
								"Link this block to a 3D item or scene from your STW collection:",
								"3d-scan-and-show",
							)}
						</p>

						{state.linkMessage && (
							<Notice
								status={state.linkMessage.type}
								isDismissible={true}
								onRemove={() => updateState({ linkMessage: null })}
							>
								{state.linkMessage.text}
							</Notice>
						)}

						{state.isLoadingLink && <Spinner />}

						{state.linkedEntityId && linkedEntity ? (
							<div
								style={{
									padding: "12px",
									border: "1px solid #ddd",
									borderRadius: "4px",
									marginBottom: "12px",
								}}
							>
								<strong>
									{state.linkedEntityType === "room"
										? __("Current Scene:", "3d-scan-and-show")
										: __("Current Item:", "3d-scan-and-show")}
								</strong>
								<div style={{ marginTop: "8px" }}>
									{linkedEntity.thumbnail_url && (
										<img
											src={linkedEntity.thumbnail_url}
											alt={linkedEntity.name}
											style={{
												width: "100%",
												maxHeight: "150px",
												objectFit: "cover",
												borderRadius: "4px",
												marginBottom: "8px",
											}}
										/>
									)}
									<div>
										<strong>{linkedEntity.name}</strong>
									</div>
									<div style={{ fontSize: "12px", color: "#666" }}>
										{__("Type:", "3d-scan-and-show")}{" "}
										{state.linkedEntityType === "room" ? "Scene" : "Item"}
									</div>
								</div>
								<Flex gap={2} style={{ marginTop: "12px" }}>
									<FlexItem>
										<Button
											variant="secondary"
											onClick={handleOpenModal}
											disabled={state.isLoadingLink}
											style={{ width: "100%" }}
										>
											{__("Change", "3d-scan-and-show")}
										</Button>
									</FlexItem>
									<FlexItem>
										<Button
											variant="secondary"
											isDestructive
											onClick={handleUnlink}
											disabled={state.isLoadingLink}
											style={{ width: "100%" }}
										>
											{__("Unlink", "3d-scan-and-show")}
										</Button>
									</FlexItem>
								</Flex>
							</div>
						) : (
							<Button
								variant="primary"
								onClick={handleOpenModal}
								disabled={state.isLoadingLink}
								style={{ width: "100%" }}
							>
								{__("Select Item or Scene", "3d-scan-and-show")}
							</Button>
						)}
					</PanelBody>
				)}
				<PanelBody
					title={__("Container Settings", "3d-scan-and-show")}
					initialOpen={!isPageContext}
				>
					<SelectControl
						label={__("Aspect Ratio", "3d-scan-and-show")}
						value={aspectRatio}
						options={[
							{
								label: __("Original", "3d-scan-and-show"),
								value: "auto",
							},
							{
								label: __("Square - 1:1", "3d-scan-and-show"),
								value: "1/1",
							},
							{
								label: __("Standard - 4:3", "3d-scan-and-show"),
								value: "4/3",
							},
							{
								label: __("Portrait - 3:4", "3d-scan-and-show"),
								value: "3/4",
							},
							{
								label: __("Classic - 3:2", "3d-scan-and-show"),
								value: "3/2",
							},
							{
								label: __("Classic Portrait - 2:3", "3d-scan-and-show"),
								value: "2/3",
							},
							{
								label: __("Wide - 16:9", "3d-scan-and-show"),
								value: "16/9",
							},
							{
								label: __("Tall - 9:16", "3d-scan-and-show"),
								value: "9/16",
							},
							{
								label: __("Custom", "3d-scan-and-show"),
								value: "custom",
							},
						]}
						onChange={onChangeAspectRatio}
						help={__(
							"Select the aspect ratio for the container",
							"3d-scan-and-show",
						)}
					/>
					<Flex gap={4} align="flex-start">
						<FlexItem>
							<div style={{ position: "relative" }}>
								<TextControl
									label={__("Width", "3d-scan-and-show")}
									type="text"
									value={width || ""}
									placeholder={`Auto (${MIN_WIDTH}px)`}
									onChange={onChangeWidth}
									help={__(
										`default display: ${MIN_WIDTH}px`,
										"3d-scan-and-show",
									)}
									style={{ paddingRight: "30px" }}
								/>
								<span
									style={{
										position: "absolute",
										right: "8px",
										top: "30px",
										color: "#2271b1",
										fontWeight: "500",
										pointerEvents: "none",
									}}
								>
									px
								</span>
							</div>
						</FlexItem>
						<FlexItem>
							<div style={{ position: "relative" }}>
								<TextControl
									label={__("Height", "3d-scan-and-show")}
									type="text"
									value={height || ""}
									placeholder={`Auto (${MIN_HEIGHT}px)`}
									onChange={onChangeHeight}
									help={__(
										`default display: ${MIN_HEIGHT}px`,
										"3d-scan-and-show",
									)}
									style={{ paddingRight: "30px" }}
								/>
								<span
									style={{
										position: "absolute",
										right: "8px",
										top: "30px",
										color: "#2271b1",
										fontWeight: "500",
										pointerEvents: "none",
									}}
								>
									px
								</span>
							</div>
						</FlexItem>
					</Flex>
				</PanelBody>
			</InspectorControls>

			<div {...blockProps}>
				<div
					style={{
						border: "2px solid #000",
						borderRadius: "8px",
						background: "#f9f9f9",
						height: "100%",
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						justifyContent: "center",
						position: "relative",
						overflow: "hidden",
					}}
				>
					<img
						src={DEMO_IMAGE_URL}
						alt="STW 3D Preview"
						style={{
							width: "100%",
							height: "100%",
							objectFit: "cover",
						}}
					/>
					<div
						style={{
							position: "absolute",
							bottom: "20px",
							left: "50%",
							transform: "translateX(-50%)",
							background: "rgba(0, 0, 0, 0.7)",
							color: "#fff",
							padding: "12px 24px",
							borderRadius: "4px",
							fontSize: "14px",
							fontWeight: "500",
							textAlign: "center",
							whiteSpace: "nowrap",
						}}
					>
						{isPageContext
							? __(
									"Select Item or Scene in the Block Settings",
									"3d-scan-and-show",
							  )
							: isSingleProductTemplate
							? __(
									"3D Viewer successfully deployed. Link 3D model to product via the dashboard",
									"3d-scan-and-show",
							  )
							: __(
									"Select Item or Scene in the Block Settings",
									"3d-scan-and-show",
							  )}
					</div>
				</div>
			</div>

			{/* Modal for selecting items or rooms */}
			{state.isModalOpen && (
				<Modal
					title={__("Select Item or Scene", "3d-scan-and-show")}
					onRequestClose={() => updateState({ isModalOpen: false })}
					style={{ maxWidth: "800px", width: "90%" }}
				>
					<div style={{ minHeight: "400px" }}>
						{state.isEnablingEmbed && (
							<Notice status="info" isDismissible={false}>
								<Flex align="center" gap={2}>
									<Spinner />
									<span>{__("Enabling embed...", "3d-scan-and-show")}</span>
								</Flex>
							</Notice>
						)}

						<SearchControl
							value={state.searchTerm}
							onChange={(value) => updateState({ searchTerm: value })}
							placeholder={__("Search by name or ID...", "3d-scan-and-show")}
							style={{ marginBottom: "16px" }}
						/>

						{state.isLoadingModal ? (
							<div
								style={{
									display: "flex",
									justifyContent: "center",
									padding: "40px",
								}}
							>
								<Spinner />
							</div>
						) : (
							<TabPanel
								tabs={[
									{
										name: "items",
										title:
											__("Items", "3d-scan-and-show") +
											` (${filteredItems.length})`,
									},
									{
										name: "rooms",
										title:
											__("Scenes", "3d-scan-and-show") +
											` (${filteredRooms.length})`,
									},
								]}
							>
								{(tab) => (
									<div
										style={{
											maxHeight: "400px",
											overflowY: "auto",
											padding: "8px",
										}}
									>
										{tab.name === "items" ? (
											filteredItems.length > 0 ? (
												<div
													style={{
														display: "grid",
														gridTemplateColumns:
															"repeat(auto-fill, minmax(200px, 1fr))",
														gap: "12px",
													}}
												>
													{filteredItems.map((item) => (
														<Card
															key={item.id}
															style={{
																cursor: "pointer",
																border:
																	state.selectedEntity?.id === item.id
																		? "2px solid #2271b1"
																		: "1px solid #ddd",
															}}
															onClick={() => handleSelectEntity(item, "item")}
														>
															<CardBody>
																{item.thumbnail_url && (
																	<img
																		src={item.thumbnail_url}
																		alt={item.name}
																		style={{
																			width: "100%",
																			height: "120px",
																			objectFit: "cover",
																			borderRadius: "4px",
																			marginBottom: "8px",
																		}}
																	/>
																)}
																<div
																	style={{
																		fontSize: "14px",
																		fontWeight: "bold",
																		marginBottom: "4px",
																	}}
																>
																	{item.name}
																</div>
																<div
																	style={{
																		fontSize: "12px",
																		color: "#666",
																	}}
																>
																	{item.is_embed_enabled ? (
																		<span style={{ color: "#46b450" }}>
																			✓{" "}
																			{__("Embed enabled", "3d-scan-and-show")}
																		</span>
																	) : (
																		<span style={{ color: "#f0b849" }}>
																			⚠{" "}
																			{__(
																				"Will enable embed",
																				"3d-scan-and-show",
																			)}
																		</span>
																	)}
																</div>
															</CardBody>
														</Card>
													))}
												</div>
											) : (
												<Notice status="warning" isDismissible={false}>
													{__("No items found.", "3d-scan-and-show")}
												</Notice>
											)
										) : filteredRooms.length > 0 ? (
											<div
												style={{
													display: "grid",
													gridTemplateColumns:
														"repeat(auto-fill, minmax(200px, 1fr))",
													gap: "12px",
												}}
											>
												{filteredRooms.map((room) => (
													<Card
														key={room.id}
														style={{
															cursor: "pointer",
															border:
																state.selectedEntity?.id === room.id
																	? "2px solid #2271b1"
																	: "1px solid #ddd",
														}}
														onClick={() => handleSelectEntity(room, "room")}
													>
														<CardBody>
															{room.thumbnail_url && (
																<img
																	src={room.thumbnail_url}
																	alt={room.name}
																	style={{
																		width: "100%",
																		height: "120px",
																		objectFit: "cover",
																		borderRadius: "4px",
																		marginBottom: "8px",
																	}}
																/>
															)}
															<div
																style={{
																	fontSize: "14px",
																	fontWeight: "bold",
																	marginBottom: "4px",
																}}
															>
																{room.name}
															</div>
															<div
																style={{
																	fontSize: "12px",
																	color: "#666",
																}}
															>
																{room.is_embed_enabled ? (
																	<span style={{ color: "#46b450" }}>
																		✓ {__("Embed enabled", "3d-scan-and-show")}
																	</span>
																) : (
																	<span style={{ color: "#f0b849" }}>
																		⚠{" "}
																		{__(
																			"Will enable embed",
																			"3d-scan-and-show",
																		)}
																	</span>
																)}
															</div>
														</CardBody>
													</Card>
												))}
											</div>
										) : (
											<Notice status="warning" isDismissible={false}>
												{__("No scenes found.", "3d-scan-and-show")}
											</Notice>
										)}
									</div>
								)}
							</TabPanel>
						)}

						<div
							style={{
								marginTop: "20px",
								paddingTop: "16px",
								borderTop: "1px solid #ddd",
								display: "flex",
								justifyContent: "flex-end",
								gap: "8px",
							}}
						>
							<Button
								variant="secondary"
								onClick={() => updateState({ isModalOpen: false })}
								disabled={state.isLoadingLink || state.isEnablingEmbed}
							>
								{__("Cancel", "3d-scan-and-show")}
							</Button>
							<Button
								variant="primary"
								onClick={handleSaveSelection}
								disabled={
									!state.selectedEntity ||
									state.isLoadingLink ||
									state.isEnablingEmbed
								}
							>
								{state.isLoadingLink || state.isEnablingEmbed ? (
									<>
										<Spinner />
										{__("Saving...", "3d-scan-and-show")}
									</>
								) : (
									__("Save Selection", "3d-scan-and-show")
								)}
							</Button>
						</div>
					</div>
				</Modal>
			)}

			{/* Confirmation Dialog */}
			{state.confirmModal && (
				<Modal
					title={state.confirmModal.title}
					onRequestClose={state.confirmModal.onCancel}
					style={{ maxWidth: "500px" }}
				>
					<div style={{ padding: "20px" }}>
						<p style={{ fontSize: "14px", marginBottom: "20px" }}>
							{state.confirmModal.message}
						</p>
						<div
							style={{
								display: "flex",
								justifyContent: "flex-end",
								gap: "10px",
							}}
						>
							<Button variant="secondary" onClick={state.confirmModal.onCancel}>
								{__("Cancel", "3d-scan-and-show")}
							</Button>
							<Button variant="primary" onClick={state.confirmModal.onConfirm}>
								{__("OK", "3d-scan-and-show")}
							</Button>
						</div>
					</div>
				</Modal>
			)}

			{/* Error Dialog */}
			{state.embedError && (
				<Modal
					title={__("Error", "3d-scan-and-show")}
					onRequestClose={() => updateState({ embedError: null })}
					style={{ maxWidth: "500px" }}
				>
					<div style={{ padding: "20px" }}>
						<p style={{ fontSize: "14px", marginBottom: "20px" }}>
							{typeof state.embedError === "string"
								? state.embedError
								: state.embedError.message}
						</p>
						<div
							style={{
								display: "flex",
								justifyContent: "flex-end",
								gap: "10px",
							}}
						>
							{state.embedError.showPricingButton && (
								<Button
									variant="secondary"
									onClick={() => {
										window.open(state.embedError.pricingUrl, "_blank");
										updateState({ embedError: null });
									}}
								>
									{__("Go to Pricing", "3d-scan-and-show")}
								</Button>
							)}
							{state.embedError.showSettingsButton && (
								<Button
									variant="secondary"
									onClick={() => {
										const settingsUrl =
											window.location.origin +
											"/wp-admin/admin.php?page=stw-settings";
										window.open(settingsUrl, "_blank");
										updateState({ embedError: null });
									}}
								>
									{__("Go to Settings", "3d-scan-and-show")}
								</Button>
							)}
							<Button
								variant="primary"
								onClick={() => updateState({ embedError: null })}
							>
								{__("OK", "3d-scan-and-show")}
							</Button>
						</div>
					</div>
				</Modal>
			)}
		</>
	);
}
