/**
 * External dependencies.
 */
import { useState, useEffect, useMemo, useRef } from "@wordpress/element";

/**
 * Internal dependencies.
 */
import { showPromiseToast, showPromiseToastRefresh, deepEqual } from "../../../utils";
import {
	fetchOptions,
	fetchData,
	saveOptions,
	runUpdate,
	updateFrequency,
	fetchSyncingData,
	fetchProjectKeywords,
	fetchImageSizes,
	refreshFields,
	runManualFullSyncWrapper,
	sendTestEmail,
} from "../../../api/settings";
import SettingsLayout from "../../layout/SettingsLayout";
import {
	SettingsCard,
	SkeletonCard,
	InfoCallout,
	SelectInput,
	TextInput,
	RadioSelectInput,
	SyncingBanner,
	SettingsButtons,
	GroupedSelect,
} from "../../templates";
import { useSyncData } from "../../../context/SyncContext";
import useUnsavedChangesWarning from "../../../hooks/useUnsavedChangesWarning";
import { useSettingsDirty } from "../../../context/SettingsDirtyContext";
import { Link, CheckCircle, FolderSync } from 'lucide-react';

const GeneralSettings = () => {
	const [processing, setProcessing] = useState(true); // For initial data loading
	const [isSaving, setIsSaving] = useState(false); // State specifically for save button
	const {
		syncData,
		isInitialized, // Use this instead of custom 'processing' for initial load visibility
		handleTriggerSync,
		isTriggering,
	} = useSyncData();

	const [options, setOptions] = useState({
		"general-settings": {},
	});

	// State and Ref for unsaved changes detection
	const { isDirty, setIsDirty } = useSettingsDirty();
	const initialOptionsRef = useRef(null);

	const [projectShow, setProjectShow] = useState(null);
	const [employeeShow, setEmployeeShow] = useState(null);
	const [textAssetShow, setTextAssetShow] = useState(null);
	const [fieldsLoaded, setFieldsLoaded] = useState(false);
	const [data, setData] = useState({});
	const [employeeFieldValues, setEmployeeFieldValues] = useState([]);
	const [loadingFieldValues, setLoadingFieldValues] = useState(false);
	const [projectFieldValues, setProjectFieldValues] = useState([]);
	const [loadingProjectFieldValues, setLoadingProjectFieldValues] =
		useState(false);
	const [isDesktop, setIsDesktop] = useState(false);
	const [projectKeywords, setProjectKeywords] = useState([]);
	const [loadingProjectKeywords, setLoadingProjectKeywords] = useState(false);
	const [imageSizes, setImageSizes] = useState([]);
	const [loadingImageSizes, setLoadingImageSizes] = useState(true); // Start as true to show loading state
	const [isSyncDisabled, setIsSyncDisabled] = useState(true); // Initially disabled until context is ready

	const updateOption = (value, id) => {
		setOptions({
			...options,
			"general-settings": {
				...options["general-settings"],
				[id]: value,
			},
		});
	};

	// Add useEffect to handle role-show settings when project-show or employee-show changes
	useEffect(() => {
		// If either project-show or employee-show is set to "no", set role-show to "no"
		if (
			options["general-settings"]?.["project-show"] === "no" ||
			options["general-settings"]?.["employee-show"] === "no"
		) {
			// Only update if it's currently set to "yes" to avoid unnecessary state updates
			if (options["general-settings"]?.["role-show"] === "yes") {
				updateOption("no", "role-show");
			}
		}
	}, [
		options["general-settings"]?.["project-show"],
		options["general-settings"]?.["employee-show"],
	]);

	const onSave = () => {
		if (!processing) {
			setIsSaving(true);
			const res = saveOptions({ options });
			const data = {
				frequency:
					options["general-settings"]["feed-frequency"] ||
					"openasset_24",
			};
			// Chain frequency update after saving options completes
			res.then((response) => {
					// Check if we need to refresh after showing success toast
					const shouldRefresh = response && response._shouldRefresh;
					
					return updateFrequency(data).then(() => {
						// Reset initial state reference after successful save
						initialOptionsRef.current = JSON.parse(JSON.stringify(options)); // Deep copy
						setIsDirty(false);
						
						// Auto-refresh for first-run CPT enablement
						if (shouldRefresh) {
							setTimeout(() => {
								window.location.reload();
							}, 1000); // Give time for success toast to show
						}
					});
			   })
			   .catch(() => {
					// Handle potential errors from saveOptions or updateFrequency if needed
					// Toast might already show an error from showPromiseToastRefresh
			   })
			   .finally(() => setIsSaving(false));

			// Show toast notification based on the initial saveOptions promise result
			showPromiseToast(res, "Saving...", "Settings updated!");
		}
	};

	// Simplified onRun - just calls the context function
	// Note: Saving settings before syncing might still be desired behavior.
	// If so, call onSave() first, await its promise, then call handleTriggerSync.
	// For now, keeping them separate as per the context implementation.
	const onRun = () => {
		if (!processing) {
			setIsSaving(true); // Use the saving indicator
			// First, save the options
			const savePromise = saveOptions({ options });

			// Show saving toast
			showPromiseToast(savePromise, "Saving settings...", "Settings saved!");

			// After saving succeeds, update frequency, reset dirty state, and trigger sync
			savePromise.then((response) => {
					// Check if we need to refresh after showing success toast
					const shouldRefresh = response && response._shouldRefresh;
					
					// Update frequency
					const freqData = {
						frequency:
							options["general-settings"]["feed-frequency"] ||
							"openasset_24",
					};
					return updateFrequency(freqData).then(() => {
						// Reset dirty state after save and frequency update
						initialOptionsRef.current = JSON.parse(JSON.stringify(options));
						setIsDirty(false);

						// Auto-refresh for first-run CPT enablement (before sync starts)
						if (shouldRefresh) {
							setTimeout(() => {
								window.location.reload();
							}, 1000); // Give time for success toast to show
							return; // Skip sync if refreshing
						}

						// Now trigger the sync using the context function
						handleTriggerSync(); // Context handles its own toasts/notifications
					});
				})
				.catch((error) => {
					// Handle potential errors from saveOptions or updateFrequency
					console.error("Error saving settings or updating frequency before sync:", error);
					// Toast for saving error is handled by showPromiseToast above
				})
				.finally(() => {
					// Stop saving indicator
					setIsSaving(false);
				});
		}
	};

	useEffect(() => {
		const updateOptions = (settings) => {
			setOptions({ ...options, ...settings });

			// Initialize project filter if needed
			if (
				settings?.["general-settings"]?.["project-filter-type"] ===
					"fields" &&
				settings?.["general-settings"]?.["project-field-filter"]
			) {
				const fieldId =
					settings["general-settings"]["project-field-filter"];
				setOptions((prev) => ({
					...prev,
					"general-settings": {
						...prev["general-settings"],
						"project-filter": `field_${fieldId}`,
						"project-filter-type": "fields",
					},
				}));
			} else if (
				settings?.["general-settings"]?.["project-filter-type"] ===
					"keywords" &&
				settings?.["general-settings"]?.["project-keyword-category"]
			) {
				const categoryId =
					settings["general-settings"]["project-keyword-category"];
				setOptions((prev) => ({
					...prev,
					"general-settings": {
						...prev["general-settings"],
						"project-filter": `keyword_${categoryId}`,
						"project-filter-type": "keywords",
					},
				}));
			}
		};

		const loadData = async () => {
			try {
				setLoadingProjectKeywords(true);
				setLoadingProjectFieldValues(true);
				setLoadingFieldValues(true);
				setFieldsLoaded(false);

				// First, try to refresh fields from OpenAsset to get the latest data
				let fieldsRefreshed = false;
				try {
					await refreshFields();
					fieldsRefreshed = true;
				} catch (refreshError) {
					// If refresh fails, log the error but continue with cached data
					console.warn('Failed to refresh fields, using cached data:', refreshError);
				}

				const optionsRes = await fetchOptions({ updateOptions });
				const dataRes = await fetchData();

				// If fields refresh failed and we have no cached field data, try refresh again
				if (!fieldsRefreshed && (!dataRes["fields"]?.["project"] || !dataRes["fields"]?.["employee"])) {
					console.log('No cached field data found, attempting fields refresh again...');
					try {
						await refreshFields();
						// Re-fetch data after successful refresh
						const updatedDataRes = await fetchData();
						Object.assign(dataRes, updatedDataRes);
					} catch (retryError) {
						console.warn('Retry fields refresh also failed:', retryError);
					}
				}

				// Ensure project keywords are properly initialized
				if (!dataRes["project-keywords"]) {
					dataRes["project-keywords"] = [];
				}

			// Get full keyword information
			const keywordData = await fetchProjectKeywords();

			// Update the data with full keyword information
			dataRes["project-keywords"] = keywordData;
			
			// Fetch available image sizes
			setLoadingImageSizes(true);
			try {
				const sizesData = await fetchImageSizes();
				setImageSizes(sizesData || []);
			} catch (sizesError) {
				console.warn('Failed to fetch image sizes:', sizesError);
				setImageSizes([]);
			} finally {
				setLoadingImageSizes(false);
			}
			
			setData(dataRes);

				// Set project show flag - be more defensive about field detection
				if (dataRes["fields"]?.["project"] && Array.isArray(dataRes["fields"]["project"])) {
					const hasProjectShowField = dataRes["fields"]["project"].some(
						(project) =>
							project.rest_code &&
							project.rest_code.startsWith("show_on_website")
					);
					setProjectShow(hasProjectShowField);
					console.log('Project show field detected:', hasProjectShowField, 'from', dataRes["fields"]["project"].length, 'fields');
				} else {
					console.warn('No project fields found in data response');
					setProjectShow(null); // Keep as null to show loading state
				}

				// Set employee show flag - be more defensive about field detection
				if (dataRes["fields"]?.["employee"] && Array.isArray(dataRes["fields"]["employee"])) {
					const hasEmployeeShowField = dataRes["fields"]["employee"].some(
						(employee) =>
							employee.rest_code &&
							employee.rest_code.startsWith("show_on_website")
					);
					setEmployeeShow(hasEmployeeShowField);
					console.log('Employee show field detected:', hasEmployeeShowField, 'from', dataRes["fields"]["employee"].length, 'fields');
				} else {
					console.warn('No employee fields found in data response');
					setEmployeeShow(null); // Keep as null to show loading state
				}

				// Set text asset show flag - check for show_on_website field in text asset fields
				if (dataRes["fields"]?.["text-asset"] && Array.isArray(dataRes["fields"]["text-asset"])) {
					const hasTextAssetShowField = dataRes["fields"]["text-asset"].some(
						(textAsset) =>
							textAsset.rest_code &&
							textAsset.rest_code.startsWith("show_on_website")
					);
					setTextAssetShow(hasTextAssetShowField);
					console.log('Text Asset show field detected:', hasTextAssetShowField, 'from', dataRes["fields"]["text-asset"].length, 'fields');
				} else {
					console.warn('No text asset fields found in data response');
					setTextAssetShow(null); // Keep as null to show loading state
				}

				setFieldsLoaded(true);
				setProcessing(false);
				setLoadingProjectKeywords(false);
				setLoadingProjectFieldValues(false);
				setLoadingFieldValues(false);

				return optionsRes;
			} catch (error) {
				console.error("Error loading data:", error);
				setFieldsLoaded(true); // Set to true even on error to prevent infinite loading
				setProcessing(false);
				setLoadingProjectKeywords(false);
				setLoadingProjectFieldValues(false);
				setLoadingFieldValues(false);
				throw error;
			}
		};

		const promise = loadData();
		showPromiseToast(promise, "Loading...", "Loaded!");
	}, []);

	// Effect to initialize the initial options ref after data is loaded
	useEffect(() => {
		if (!processing && initialOptionsRef.current === null) {
			initialOptionsRef.current = JSON.parse(JSON.stringify(options)); // Deep copy
		}
	}, [processing, options]);

	// Effect to check if options have changed from the initial state
	useEffect(() => {
		if (!processing && initialOptionsRef.current !== null) {
			const newDirtyState = !deepEqual(options, initialOptionsRef.current);
			setIsDirty(newDirtyState);
		}
	}, [options, processing, setIsDirty]);

	// Call the hook to manage warnings
	useUnsavedChangesWarning(isDirty);

	useEffect(() => {
		// Initialize project field values when data and options are available
		if (
			data["fields"]?.["project"] &&
			options["general-settings"]?.["project-filter"] &&
			options["general-settings"]?.["project-filter"].startsWith("field_")
		) {
			setLoadingProjectFieldValues(true);
			
			const [_, id] =
				options["general-settings"]["project-filter"].split("_");

			try {
				const selectedField = data["fields"]["project"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setProjectFieldValues(sortedValues);
				} else {
					setProjectFieldValues([]);
				}
			} catch (error) {
				console.error("Error initializing project field values:", error);
				setProjectFieldValues([]);
			} finally {
				setLoadingProjectFieldValues(false);
			}
		}
	}, [
		data["fields"]?.["project"],
		options["general-settings"]?.["project-filter"],
	]);

	useEffect(() => {
		// Initialize employee field values when data and options are available
		if (
			data["fields"]?.["employee"] &&
			options["general-settings"]?.["employee-field-filter"] &&
			options["general-settings"]?.["employee-field-filter"].startsWith(
				"field_"
			)
		) {
			setLoadingFieldValues(true);
			const [_, id] =
				options["general-settings"]["employee-field-filter"].split("_");

			try {
				const selectedField = data["fields"]["employee"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setEmployeeFieldValues(sortedValues);
				} else {
					setEmployeeFieldValues([]);
				}
			} catch (error) {
				console.error(
					"Error initializing employee field values:",
					error
				);
				setEmployeeFieldValues([]);
			} finally {
				setLoadingFieldValues(false);
			}
		}
	}, [
		data["fields"]?.["employee"],
		options["general-settings"]?.["employee-field-filter"],
	]);

	// Handle employee field filter changes
	const handleEmployeeFieldChange = (value) => {
		if (!value || value === "no_filter") {
			// Clear all filter-related values
			setOptions((prevOptions) => ({
				...prevOptions,
				"general-settings": {
					...prevOptions["general-settings"],
					"employee-field-filter": value || "",
					"employee-filter-type": "",
					"employee-field-filter-value": "",
				},
			}));
			setEmployeeFieldValues([]);
			return;
		}

		const [type, id] = value.split("_");

		if (type === "field") {
			setLoadingFieldValues(true);
			try {
				// Update all states in a single batch for fields
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"employee-filter-type": "fields",
						"employee-field-filter": value, // Store the full field_id format
						"employee-field-filter-value": "",
					},
				}));

				// Find the selected field
				const selectedField = data["fields"]["employee"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setEmployeeFieldValues(sortedValues);
				} else {
					setEmployeeFieldValues([]);
				}
			} catch (error) {
				console.error("Error getting field values:", error);
				setEmployeeFieldValues([]);
			} finally {
				setLoadingFieldValues(false);
			}
		}
	};

	// Handle project field filter changes
	const handleProjectFieldFilter = (value) => {
		if (!value || value === "no_filter") {
			// Clear all filter-related values
			setOptions((prevOptions) => ({
				...prevOptions,
				"general-settings": {
					...prevOptions["general-settings"],
					"project-filter": value || "",
					"project-filter-type": "",
					"project-field-filter": "",
					"project-field-filter-value": "",
					"project-keyword-category": "",
					"project-keyword": "",
				},
			}));
			setProjectFieldValues([]);
			setProjectKeywords([]);
			return;
		}

		const [type, id] = value.split("_");

		if (type === "field") {
			setLoadingProjectFieldValues(true);
			try {
				// Update all states in a single batch for fields
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"project-filter-type": "fields",
						"project-filter": value, // Store the full field_id format
						"project-field-filter": id,
						"project-field-filter-value": "",
						"project-keyword-category": "",
						"project-keyword": "",
					},
				}));

				setProjectKeywords([]);

				const selectedField = data["fields"]["project"]?.find(
					(field) => field.id.toString() === id
				);

				if (selectedField?.fieldLookupStrings) {
					const values =
						selectedField.fieldLookupStrings.map(
							(item) => item.value
						) || [];
					const sortedValues = [...new Set(values)].sort();
					setProjectFieldValues(sortedValues);
				} else {
					setProjectFieldValues([]);
				}
			} catch (error) {
				console.error("Error getting field values:", error);
				setProjectFieldValues([]);
			} finally {
				setLoadingProjectFieldValues(false);
			}
		} else if (type === "keyword") {
			setLoadingProjectKeywords(true);
			try {
				// Update all states in a single batch for keywords
				setOptions((prevOptions) => ({
					...prevOptions,
					"general-settings": {
						...prevOptions["general-settings"],
						"project-filter-type": "keywords",
						"project-filter": value,
						"project-keyword-category": id,
						"project-keyword": "",
						"project-field-filter": "",
						"project-field-filter-value": "",
					},
				}));

				setProjectFieldValues([]);

				const selectedCategory = data["project-keywords"]?.find(
					(category) => category.category.id.toString() === id
				);

				if (
					selectedCategory &&
					Array.isArray(selectedCategory.keywords)
				) {
					setProjectKeywords(selectedCategory.keywords);
				} else {
					setProjectKeywords([]);
				}
			} catch (error) {
				console.error("Error filtering project keywords:", error);
				setProjectKeywords([]);
			} finally {
				setLoadingProjectKeywords(false);
			}
		}
	};

	// Handle project field change (when selecting a specific field value)
	const handleProjectFieldChange = (value, id) => {
		// Clear the project field filter value when changing fields
		updateOption("", "project-field-filter-value");
		updateOption(value, id);

		setLoadingProjectFieldValues(true);
		try {
			// Find the selected field
			const selectedField = data["fields"]["project"]?.find(
				(field) => field.id.toString() === value
			);

			// Get and sort the values from fieldLookupStrings
			const values =
				selectedField?.fieldLookupStrings?.map((item) => item.value) ||
				[];
			const sortedValues = [...new Set(values)].sort();

			setProjectFieldValues(sortedValues);
		} catch (error) {
			console.error("Error getting field values:", error);
			setProjectFieldValues([]);
		} finally {
			setLoadingProjectFieldValues(false);
		}
	};

	// Handle the selection of a value in the project field filter value dropdown
	const handleProjectFieldValueChange = (value, id) => {
		// Just update the value without clearing anything
		updateOption(value, id);
	};

	// Handle the selection of a value in the employee field filter value dropdown
	const handleEmployeeFieldValueChange = (value, id) => {
		// Just update the value without clearing anything
		updateOption(value, id);
	};

	// Handle image size exclusion checkbox changes
	const handleImageSizeExclusionToggle = (sizeId) => {
		const currentExcluded = options["general-settings"]["excluded-image-sizes"] || [];
		let newExcluded;
		
		if (currentExcluded.includes(sizeId)) {
			// Remove from excluded list
			newExcluded = currentExcluded.filter(id => id !== sizeId);
		} else {
			// Add to excluded list
			newExcluded = [...currentExcluded, sizeId];
		}
		
		updateOption(newExcluded, "excluded-image-sizes");
	};

	// Handle manual full sync button click
	const handleManualFullSync = async () => {
		try {
			await runManualFullSyncWrapper();
			// No toast needed - sync banner provides all the feedback
		} catch (error) {
			console.error("Manual full sync error:", error);
			// Only show toast for actual errors
			showPromiseToast(
				Promise.reject(error),
				"",
				"Failed to start manual full sync."
			);
		}
	};
	
	// Handle test email button click
	const handleTestEmail = async () => {
		const email = options["general-settings"]["sync-email-address"] || null;
		
		showPromiseToast(
			sendTestEmail(email),
			"Sending test email...",
			"Test email sent successfully! Check your inbox.",
			"Failed to send test email. Check your email configuration."
		);
	};

	// Memoized project filter options
	const projectFilterOptions = useMemo(() => {
		// Only compute when data is available
		if (!data || !data.fields || !data.fields.project) {
			return [];
		}

		// Create the option groups
		return [
			{
				label: "No Filter",
				options: [
					{
						value: "no_filter",
						label: "No Filter",
						type: "none",
					},
				],
			},
			{
				label: "Fields",
				options: (data.fields.project || [])
					.filter(
						(field) =>
							(field.field_display_type === "option" ||
								field.field_display_type ===
									"fixedSuggestion" ||
								field.field_display_type === "suggestion") &&
							field.rest_code !== "show_on_website" &&
							field.rest_code !== "roles" &&
							field.rest_code !== "code" &&
							field.rest_code !== "name"
					)
					.map((field) => ({
						value: `field_${field.id}`,
						label: field.name,
						type: "field",
						fieldId: field.id,
					})),
			},
			{
				label: "Keyword Category",
				options: (data["project-keywords"] || []).map((item) => ({
					value: `keyword_${item.category.id}`,
					label: item.category.name,
					type: "keyword",
					categoryId: item.category.id,
				})),
			},
		];
	}, [data?.fields?.project, data?.["project-keywords"]]);

	// Memoized employee filter options
	const employeeFilterOptions = useMemo(() => {
		// Only compute when data is available
		if (!data || !data.fields || !data.fields.employee) {
			return [];
		}

		return [
			{
				label: "No Filter",
				options: [
					{
						value: "no_filter",
						label: "No Filter",
						type: "none",
					},
				],
			},
			{
				label: "Fields",
				options: (data.fields.employee || [])
					.filter(
						(field) =>
							(field.field_display_type === "option" ||
								field.field_display_type ===
									"fixedSuggestion" ||
								field.field_display_type === "suggestion") &&
							field.rest_code !== "show_on_website" &&
							field.rest_code !== "roles"
					)
					.map((field) => ({
						value: `field_${field.id}`,
						label: field.name,
						type: "field",
						fieldId: field.id,
					})),
			},
		];
	}, [data?.fields?.employee]);

	// Memoized options for the filter value dropdown
	const filterValueOptions = useMemo(() => {
		const filterType = options["general-settings"]["project-filter-type"];

		if (
			filterType === "keywords" &&
			projectKeywords &&
			projectKeywords.length > 0
		) {
			return Object.fromEntries(
				projectKeywords.map((keyword) => [
					keyword.id.toString(),
					keyword.name,
				])
			);
		} else {
			return Object.fromEntries(
				(projectFieldValues || []).map((value) => [value, value])
			);
		}
	}, [
		options["general-settings"]["project-filter-type"],
		projectKeywords,
		projectFieldValues,
	]);

	// Memoized options for the employee filter value dropdown
	const employeeFilterValueOptions = useMemo(() => {
		return Object.fromEntries(
			(employeeFieldValues || []).map((value) => [value, value])
		);
	}, [employeeFieldValues]);

	useEffect(() => {
		// Initialize project keywords when data and options are available
		if (
			data["project-keywords"] &&
			options["general-settings"]?.["project-filter-type"] === "keywords" &&
			options["general-settings"]?.["project-keyword-category"]
		) {
			setLoadingProjectKeywords(true);
			try {
				const selectedCategory = data["project-keywords"]?.find(
					(category) => category.category.id.toString() === options["general-settings"]["project-keyword-category"]
				);

				if (selectedCategory && Array.isArray(selectedCategory.keywords)) {
					setProjectKeywords(selectedCategory.keywords);
				} else {
					setProjectKeywords([]);
				}
			} catch (error) {
				console.error("Error initializing project keywords:", error);
				setProjectKeywords([]);
			} finally {
				setLoadingProjectKeywords(false);
			}
		}
	}, [data["project-keywords"], options["general-settings"]?.["project-filter-type"], options["general-settings"]?.["project-keyword-category"]]);

	useEffect(() => {
		// Update disabled state based on context data
		if (isInitialized) {
			setIsSyncDisabled(
				!!syncData?.is_initiating ||
					!!syncData?.is_processing ||
					isTriggering
			);
		}
	}, [syncData, isTriggering, isInitialized]);

	// Get the sync status text and style based on the current state
	const getSyncStatusDisplay = () => {
		if (!isInitialized) {
			return { text: "Loading status...", style: "loading" };
		}
		if (syncData?.is_initiating) {
			return { text: "Populating sync queue...", style: "syncing" };
		}
		if (syncData?.is_processing) {
			return {
				text: `Syncing: ${syncData.queue_count} items remaining...`,
				style: "syncing",
			};
		}
		if (syncData?.queue_count > 0) {
			// Queue has items but not actively processing (waiting for cron trigger)
			return {
				text: `Pending: ${syncData.queue_count} items in queue. Next sync: ${syncData.next_scheduled_human}`,
				style: "warning", // Or a different style
			};
		}
		// Idle state
		return {
			text: `Idle. Next sync: ${syncData.next_scheduled_human}`,
			style: "synced", // Or 'idle'
		};
	};

	const { text: syncStatusText, style: syncStatusStyle } = getSyncStatusDisplay();

	return (
		<SettingsLayout
			onSave={onSave}
			onRun={onRun}
			isSaving={isSaving}
			isSyncing={isSyncDisabled}
		>
			<div className='space-y-6'>
				{/* Page Header */}
				<div>
					<h1 className='text-2xl font-oa-bold text-oa-text-primary'>
						General Settings
					</h1>
					<p className='text-oa-sm text-oa-text-tertiary mt-1'>
						Configure your OpenAsset connection and sync preferences
					</p>
				</div>

				{/* Loading State - Show skeleton cards */}
				{processing ? (
					<>
						<SkeletonCard hasIcon={true} />
						<SkeletonCard hasIcon={true} />
						<SkeletonCard hasIcon={true} />
					</>
				) : (
					<>
					{/* Real content below */}

				{/* Card 1: OpenAsset API */}
				<SettingsCard
					icon={Link}
					title='OpenAsset API'
					description='Connect to your OpenAsset instance'
				>
					{/* Connection Status Badge - only show when URL is loaded */}
					{options["general-settings"]["client-instance-url"] && (
						<div className='flex items-center gap-2 px-3 py-2 bg-green-50 border border-green-200 rounded-oa-md w-fit'>
							<CheckCircle className='w-4 h-4 text-green-600' />
							<span className='text-oa-sm font-oa-medium text-green-800'>
								Connected to {options["general-settings"]["client-instance-url"]?.replace('https://', '').replace('http://', '').split('/')[0]}
							</span>
						</div>
					)}

					<div>
						<p className='text-oa-sm font-oa-semibold text-oa-text-secondary mb-2'>
							Your OpenAsset Instance URL
						</p>
						{options && (
							<a
								href={options["general-settings"]["client-instance-url"]}
								className='text-[#22706f] hover:text-[#1d5a59] underline text-oa-sm font-oa-medium transition-colors'
								target='_blank'
								rel='noopener noreferrer'
							>
								{options["general-settings"]["client-instance-url"]}
							</a>
						)}
					</div>
					
					<TextInput
						id='your-real-token-id'
						label='Token ID'
						value={options["general-settings"]["your-real-token-id"]}
						setOption={updateOption}
					/>
					
					<TextInput
						id='your-real-api-token'
						label='API Token'
						value={options["general-settings"]["your-real-api-token"]}
						setOption={updateOption}
						type='password'
					/>
				</SettingsCard>

				{/* Card 2: Asset Sync */}
				<SettingsCard
					icon={FolderSync}
					title='Asset Sync'
					description='Select which content types to sync from OpenAsset'
				>
					<InfoCallout type='info' title='Important'>
						Projects, Employees, and Text Assets must have a "Show on Website" 
						(show_on_website) field set to "yes" in OpenAsset.
					</InfoCallout>

					<div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
					<fieldset className='order-1 sm:order-1'>
						<legend className='text-sm font-semibold leading-6 text-gray-900'>
							Sync Projects?
						</legend>
						{!fieldsLoaded && (
							<p className='text-blue-500 italic text-xs mt-1 mb-2'>
								Loading field information from OpenAsset...
							</p>
						)}
						{fieldsLoaded && projectShow === false && (
							<p className='text-gray-500 italic text-xs mt-1 mb-2'>
								Project sync is not possible until you have
								created a "Show on Website" field in OpenAsset.
							</p>
						)}
						<select
							id='project-show'
							name='project-show'
							className='block w-full rounded-md border-0 mt-2 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-gray-600 sm:text-sm sm:leading-6 max-w-none'
							value={
								options["general-settings"]["project-show"] ||
								"no"
							}
							onChange={(e) =>
								updateOption(e.target.value, "project-show")
							}
							disabled={!fieldsLoaded}
						>
							{Object.entries({
								yes: "Yes",
								no: "No",
							}).map(([value, label]) => (
								<option
									key={value}
									value={value}
								>
									{label}
								</option>
							))}
						</select>
					</fieldset>

					<fieldset className='order-2 sm:order-3'>
						<legend className='text-sm font-semibold leading-6 text-gray-900'>
							Sync Employees?
						</legend>
						{!fieldsLoaded && (
							<p className='text-blue-500 italic text-xs mt-1 mb-2'>
								Loading field information from OpenAsset...
							</p>
						)}
						{fieldsLoaded && employeeShow === false && (
							<p className='text-gray-500 italic text-xs mt-1 mb-2'>
								Employee sync is not possible until you have
								created a "Show on Website" field in OpenAsset.
							</p>
						)}
						<select
							id='employee-show'
							name='employee-show'
							className='block w-full rounded-md border-0 mt-2 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-gray-600 sm:text-sm sm:leading-6 max-w-none'
							value={
								options["general-settings"]["employee-show"] ||
								"no"
							}
							onChange={(e) =>
								updateOption(e.target.value, "employee-show")
							}
							disabled={!fieldsLoaded}
						>
							{Object.entries({
								yes: "Yes",
								no: "No",
							}).map(([value, label]) => (
								<option
									key={value}
									value={value}
								>
									{label}
								</option>
							))}
						</select>
					</fieldset>

					<fieldset className='order-6 sm:order-4'>
						<legend className='text-sm font-semibold leading-6 text-gray-900'>
							Sync Roles?
						</legend>
						{(options["general-settings"]["project-show"] ===
							"no" ||
							options["general-settings"]["employee-show"] ===
								"no") && (
							<p className='text-gray-500 italic text-xs mt-1 mb-2'>
								Roles can only be synced if you are syncing both
								Projects and Employees.
							</p>
						)}
						<select
							id='role-show'
							name='role-show'
							className='block w-full rounded-md border-0 mt-2 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-gray-600 sm:text-sm sm:leading-6 max-w-none'
							value={options["general-settings"]["role-show"]}
							onChange={(e) =>
								updateOption(e.target.value, "role-show")
							}
							disabled={
								options["general-settings"]["project-show"] ===
									"no" ||
								options["general-settings"]["employee-show"] ===
									"no"
							}
						>
							{Object.entries({
								yes: "Yes",
								no: "No",
							}).map(([value, label]) => (
								<option
									key={value}
									value={value}
								>
									{label}
								</option>
							))}
						</select>
					</fieldset>

					<fieldset className='order-3 sm:order-5'>
						<legend className='text-sm font-semibold leading-6 text-gray-900'>
							Sync Text Assets?
						</legend>
						{!fieldsLoaded && (
							<p className='text-blue-500 italic text-xs mt-1 mb-2'>
								Loading field information from OpenAsset...
							</p>
						)}
						{fieldsLoaded && textAssetShow === false && (
							<p className='text-gray-500 italic text-xs mt-1 mb-2'>
								Text Asset sync is not possible until you have
								created a "Show on Website" field in OpenAsset.
							</p>
						)}

						<select
							id='text-assets-show'
							name='text-assets-show'
							className='block w-full rounded-md border-0 mt-2 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-gray-600 sm:text-sm sm:leading-6 max-w-none'
							value={options["general-settings"]["text-assets-show"] || "no"}
							onChange={(e) =>
								updateOption(e.target.value, "text-assets-show")
							}
							disabled={!fieldsLoaded}
						>
							{Object.entries({
								yes: "Yes",
								no: "No",
							}).map(([value, label]) => (
								<option
									key={value}
									value={value}
								>
									{label}
								</option>
							))}
						</select>
					</fieldset>										
					

				<SelectInput
					id='image-size-sync'
					label='Image Size Sync'
					value={
						options["general-settings"]["image-size-sync"] ||
						"2000"
					}
					options={{
						2000: "Closest to 2000x2000px, up to 3.15MB",
						3000: "Closest to 3000x3000px, up to 3.15MB",
					}}
					setOption={updateOption}
					order='order-7 sm:order-6'
				/>

			<div className='order-8 sm:order-7 col-span-2'>
				<label className='text-sm font-semibold leading-6 text-gray-900 block mb-2'>
					Excluded Image Sizes
				</label>
				{loadingImageSizes ? (
					<p className='text-blue-500 italic text-xs'>
						Loading available sizes...
					</p>
				) : imageSizes.length === 0 ? (
					<p className='text-gray-500 italic text-xs'>
						No image sizes found. Make sure you have files in OpenAsset.
					</p>
				) : (
					<div className='space-y-2'>
						<p className='text-xs text-gray-600 mb-3'>
						Images closest to your selected size (2000x2000px or 3000x3000px) will be synced. Check the boxes below to exclude specific image sizes from syncing (for example, grayscale or other variants you don’t want). Only the most relevant size will be pulled in, not all sizes.
						</p>
						<div className='grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-80 overflow-y-auto border border-gray-200 rounded-md p-4 bg-gray-50'>
							{imageSizes.map((size) => {
								const isExcluded = (options["general-settings"]["excluded-image-sizes"] || []).includes(size.id);
								return (
									<label 
										key={size.id} 
										className='flex items-start gap-3 cursor-pointer hover:bg-white p-2 rounded transition-colors'
									>
										<input
											type="checkbox"
											checked={isExcluded}
											onChange={() => handleImageSizeExclusionToggle(size.id)}
											className='mt-0.5 h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-600'
										/>
										<span className='text-sm text-gray-700 select-none'>
											{size.display_name}
										</span>
									</label>
								);
							})}
						</div>
						{(options["general-settings"]["excluded-image-sizes"] || []).length > 0 && (
							<p className='text-xs text-amber-600 mt-2'>
								⚠️ {(options["general-settings"]["excluded-image-sizes"] || []).length} size(s) will be excluded from syncing
							</p>
						)}
					</div>
				)}
			</div>
				
			</div>

				<div className='border-b w-100 border-[#E6E6E6] max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Auto + Manual Asset Sync
				</h2>

				<p>
					<i>
					Regular syncs only update assets that have changed, whereas Maintenance Syncs sync everything again. Maintenance Syncs are much slower but are advised to run occationally to ensure data integrity.
					</i>
				</p>

				<div className='flex flex-col sm:items-start px-3 sm:px-0 sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] mt-2'>
					
						<SelectInput
							id='feed-frequency'
							label='Auto Sync Frequency'
							value={options["general-settings"]["feed-frequency"]}
							options={{
								none: "None",
								openasset_8: "Every 8 Hours",
								openasset_24: "Every 24 Hours",
							}}
							setOption={updateOption}
						/>
					
						<div >
							<label className='text-sm font-semibold leading-6 text-gray-900 block mb-2'>
								Maintenance Sync
							</label>
							<button
								type="button"
								className='inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed'
								disabled={isSyncDisabled}
								onClick={handleManualFullSync}
							>
								<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
									<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
								</svg>
								Run Maintenance Sync
							</button>
							<p className='text-gray-500 text-xs mt-1'>
								Forces a complete sync of all data, ignoring timestamps
							</p>
						</div>
						<SelectInput
							id='enable-logging'
							label='Enable Error Logging?'
							value={options["general-settings"]["enable-logging"]}
							options={{
								true: "Yes",
								false: "No",
							}}
							setOption={updateOption}
							
						/>
						<div>
						<SelectInput
							id='maintenance-sync-cycle'
							label='Auto Maintenance Sync'
							value={options["general-settings"]["maintenance-sync-cycle"] || "none"}
							options={{
								"10": "Every 10 syncs", 
								"20": "Every 20 syncs",
								"50": "Every 50 syncs",
								"100": "Every 100 syncs",
								"none": "None (Manual only)",
							}}
							setOption={updateOption}
						/>
						{options["general-settings"]["maintenance-sync-cycle"] === "none" && (
							<p className='text-amber-600 text-xs mt-1'>
								⚠️ Auto Maintenance Syncs are disabled. These are advised to run occationally to ensure data integrity.
							</p>
						)}
						</div>
					</div>
					
					{/* Sync Notifications - Full width section */}
					<div className='col-span-2 px-3 sm:px-0 max-w-none sm:max-w-[80%]'>
						<div className='border-t border-gray-200 pt-6 mt-2'>
							<h3 className='text-lg font-semibold leading-6 text-gray-900 mb-4'>
								Sync Notifications
							</h3>
							
							<div className='space-y-4'>
								{/* Email toggle */}
								<div className='flex items-center justify-between'>
									<div className='flex-1'>
										<label className='text-sm font-semibold leading-6 text-gray-900 block'>
											Send email when sync completes
										</label>
										<p className='text-xs text-gray-500 mt-1'>
											Get notified via email when syncs finish (success or failure)
										</p>
									</div>
									<div className='ml-4'>
										<button
											type="button"
											onClick={() => updateOption(
												options["general-settings"]["sync-email-enabled"] === "yes" ? "no" : "yes",
												"sync-email-enabled"
											)}
											className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-[#247070] focus:ring-offset-2 ${
												options["general-settings"]["sync-email-enabled"] === "yes" ? 'bg-[#247070]' : 'bg-gray-200'
											}`}
										>
											<span
												className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
													options["general-settings"]["sync-email-enabled"] === "yes" ? 'translate-x-5' : 'translate-x-0'
												}`}
											/>
										</button>
									</div>
								</div>
								
								{/* Email input - only show if enabled */}
								{options["general-settings"]["sync-email-enabled"] === "yes" && (
									<>
										<div>
											<label className='text-sm font-semibold leading-6 text-gray-900 block mb-2'>
												Notification Email Address
											</label>
											<input
												type="email"
												value={options["general-settings"]["sync-email-address"] || ""}
												onChange={(e) => updateOption(e.target.value, "sync-email-address")}
												placeholder="admin@yoursite.com (site admin email)"
												className='block w-full rounded-md border-gray-300 shadow-sm focus:border-[#247070] focus:ring-[#247070] sm:text-sm'
											/>
											<p className='text-xs text-gray-500 mt-1'>
												Leave blank to use site admin email
											</p>
										</div>
										
										{/* Test email button */}
										<div>
											<button
												type="button"
												onClick={handleTestEmail}
												className='inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#247070]'
											>
												<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
													<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
												</svg>
												Send Test Email
											</button>
											<p className='text-xs text-gray-500 mt-2'>
												Send a test email to verify your email configuration is working
											</p>
										</div>
										
										{/* Warning about email reliability */}
										<div className='bg-amber-50 border border-amber-200 rounded-md p-3'>
											<div className='flex'>
												<div className='flex-shrink-0'>
													<svg className="h-5 w-5 text-amber-400" viewBox="0 0 20 20" fill="currentColor">
														<path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
													</svg>
												</div>
												<div className='ml-3'>
													<h3 className='text-sm font-medium text-amber-800'>
														Email Delivery Notice
													</h3>
													<div className='mt-2 text-sm text-amber-700'>
														<p>
															Email notifications may not work reliably on all servers. Shared hosting often blocks or limits email sending. 
															We recommend using the <strong>Test Email</strong> button to verify delivery before relying on notifications.
														</p>
														<p className='mt-2'>
															For reliable email delivery, consider installing an SMTP plugin like <strong>WP Mail SMTP</strong> or <strong>Post SMTP</strong>.
														</p>
													</div>
												</div>
											</div>
										</div>
									</>
								)}
							</div>
						</div>
					</div>


				<div className='border-b w-100 border-[#E6E6E6] max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Custom Project Filter
				</h2>

				<p>
					<i>
						You can filter Project syncing based on Fixed
						Auto-Complete or Drop Down Menu fields or Keyword
						Categories.
					</i>
				</p>

				{data["fields"] && data["fields"]["project"] && (
					<div className='px-3 sm:px-0'>
						<div className='flex flex-col sm:items-end sm:grid sm:grid-cols-[3fr_1fr_3fr] gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] mt-6'>
							<GroupedSelect
								id='project-filter'
								label='Only sync Projects where...'
								value={
									options["general-settings"][
										"project-filter"
									] || ""
								}
								options={projectFilterOptions}
								setOption={handleProjectFieldFilter}
								noDefaultOption={true}
							/>
							<p className='font-semibold mx-auto text-sm leading-6 text-gray-900'>
								{options["general-settings"][
									"project-filter-type"
								] === "keywords"
									? "has"
									: "is"}
							</p>
							<SelectInput
								id={
									options["general-settings"][
										"project-filter-type"
									] === "keywords"
										? "project-keyword"
										: "project-field-filter-value"
								}
								label=''
								value={
									options["general-settings"][
										"project-filter-type"
									] === "keywords"
										? options["general-settings"][
												"project-keyword"
										  ]
										: options["general-settings"][
												"project-field-filter-value"
										  ]
								}
								options={filterValueOptions}
								setOption={handleProjectFieldValueChange}
								disabled={
									options["general-settings"][
										"project-filter-type"
									] === "keywords"
										? loadingProjectKeywords ||
										  !options["general-settings"][
												"project-keyword-category"
										  ]
										: loadingProjectFieldValues ||
										  !options["general-settings"][
												"project-field-filter"
										  ] ||
										  options["general-settings"][
												"project-filter"
										  ] === "no_filter"
								}
								loading={
									options["general-settings"][
										"project-filter-type"
									] === "keywords"
										? loadingProjectKeywords
										: loadingProjectFieldValues
								}
							/>
						</div>
					</div>
				)}

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Custom Employee Filter
				</h2>

				<p>
					<i>
						You can filter Employee syncing based on a Fixed
						Auto-Complete or Drop Down Menu field.
					</i>
				</p>
				{data["fields"] && data["fields"]["employee"] && (
					<div className='flex flex-col sm:items-end px-3 sm:px-0 sm:grid grid-cols-[3fr_1fr_3fr] gap-x-10 gap-y-6 max-w-none sm:max-w-[80%] pb-2'>
						<GroupedSelect
							id='employee-field-filter'
							label='Only sync Employees where...'
							value={
								options["general-settings"][
									"employee-field-filter"
								] || ""
							}
							options={employeeFilterOptions}
							setOption={handleEmployeeFieldChange}
							noDefaultOption={true}
						/>
						<p className='font-semibold mx-auto text-sm leading-6 text-gray-900'>
							is
						</p>
						<SelectInput
							id='employee-field-filter-value'
							label=''
							value={
								options["general-settings"][
									"employee-field-filter-value"
								]
							}
							options={employeeFilterValueOptions}
							setOption={handleEmployeeFieldValueChange}
							disabled={
								loadingFieldValues ||
								!options["general-settings"][
									"employee-field-filter"
								] ||
								options["general-settings"][
									"employee-field-filter"
								] === "no_filter"
							}
							loading={loadingFieldValues}
						/>
					</div>
				)}

				<div className='border-b w-100 border-[#E6E6E6] max-w-none sm:max-w-[80%] mx-3 sm:mx-0'></div>

				<h2 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					WordPress Settings
				</h2>

				<h3 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Post Status
				</h3>

				<div className='flex flex-col sm:items-end px-3 sm:px-0 sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%]'>
					<SelectInput
						id='project-post-status'
						label='Project Post Status'
						value={
							options["general-settings"][
								"project-post-status"
							] || "public"
						}
						options={{
							public: "Public",
							private: "Private",
						}}
						setOption={updateOption}
					/>
					<SelectInput
						id='employee-post-status'
						label='Employee Post Status'
						value={
							options["general-settings"][
								"employee-post-status"
							] || "public"
						}
						options={{
							public: "Public",
							private: "Private",
						}}
						setOption={updateOption}
					/>
				</div>

				<h3 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Project Naming
				</h3>
				<div className='flex flex-col sm:items-end px-3 sm:px-0 sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%]'>
					<TextInput
						id='project-name-plural'
						label='Projects Name (plural)'
						placeholder='Eg. projects'
						value={
							options["general-settings"]["project-name-plural"]
						}
						setOption={updateOption}
					/>
					<TextInput
						id='project-name-singular'
						label='Projects Name (singular)'
						placeholder='Eg. project'
						value={
							options["general-settings"]["project-name-singular"]
						}
						setOption={updateOption}
					/>
					<TextInput
						id='project-url-key'
						label='Projects URL Key'
						value={options["general-settings"]["project-url-key"]}
						setOption={updateOption}
						placeholder='Eg. projects'
					/>
				</div>

				<h3 className='text-xl font-semibold leading-7 text-gray-900 px-3 sm:px-0'>
					Employee Naming
				</h3>
				<div className='flex flex-col sm:items-end px-3 sm:px-0 sm:grid grid-cols-2 gap-x-10 gap-y-6 max-w-none sm:max-w-[80%]'>
					<TextInput
						id='employee-name-plural'
						label='Employees Name (plural)'
						placeholder='Eg. employees'
						value={
							options["general-settings"]["employee-name-plural"]
						}
						setOption={updateOption}
					/>
					<TextInput
						id='employee-name-singular'
						label='Employees Name (singular)'
						placeholder='Eg. employee'
						value={
							options["general-settings"][
								"employee-name-singular"
							]
						}
						setOption={updateOption}
					/>
					<TextInput
						id='employee-url-key'
						label='Employees URL Key'
						value={options["general-settings"]["employee-url-key"]}
						setOption={updateOption}
						placeholder='Eg. employees'
					/>
				</div>
				</SettingsCard>
					</>
				)}

				{/* Syncing Banner - show regardless of loading state */}
				{(syncData?.is_initiating || syncData?.is_processing || syncData?.queue_count > 0) && (
					<SyncingBanner options={options} syncData={syncData} />
				)}
				
				{/* Error Alert */}
				{syncData && syncData.syncRunning == 2 && (
					<div
						className='bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded fixed md:bottom-12 bottom-0.5 m-4 md:m-0'
						role='alert'
					>
						<strong className='font-bold'>
							Syncing terminated due to an API error.
						</strong>
						<span> - </span>
						<span className='block sm:inline'>
							Please try again or contact support.
						</span>
					</div>
				)}
			</div>
		</SettingsLayout>
	);
};

export default GeneralSettings;
