// src/components/site/Signup.tsx

const TOTAL_STEPS = stageSchemas.length;
//const TOTAL_STEPS = 9;

function Signup()
{
	// Signup process
	const [step, setStep] = useState<number>(1);
	const [userId, setUserId] = useState<number | null>(null);
	const [categories, setCategories] = useState<BusinessCategoryData[]>([]);
	const [signupData, setSignupData] = useState<SignupData>(initialSignupData);
	
	// CSRF token and param names
	const [csrf, setCsrf] = useState<CsrfData | null>(null);
	
	const [loading, setLoading] = useState(false);
	
	// Error handling
	const [error, setError] = useState<string | null>(null);
	const [formErrors, setFormErrors] = useState<Record<string, string[] | string>>({});
	
	/**
	* Update Feild Helper
	* Helper that updates field value and clears the error on change
	*/
	const updateField = useCallback(<Key extends keyof SignupData>
	(
		field: Key,
		value: SignupData[Key]
	) =>
	{
		setSignupData(prev => ({ ...prev, [field]: value }));
		
		// Clear error for this field on change
		setFormErrors(prev =>
		{
			if (field in prev)
			{
				const copy = { ...prev };
				delete copy[field];
				return copy;
			}
			
			return prev;
		});
		
	}, []);// Empty dependency array ensures it only runs once
	
	/**
	* Handle file input updates
	*/
	const handleFileChange = useCallback(
	(
		error: ChangeEvent<HTMLInputElement>,
		field: keyof SignupData
	) =>
	{
		updateField(field, error.target.files?.[0] || null);
	}, [updateField]);
	
	/**
	* Progress calculation
	*/
	const progressPercent = (step / TOTAL_STEPS) * 100;
	
	/**
	* Centralized submit handler keyed by stage number
	*/
	const submitStage = useCallback(async () =>
	{
		// Clear previous errors
		setError(null);
		setFormErrors({});
		
		if (!csrf)
		{
			setError('CSRF token missing, please refresh.');
			return;
		}
		
		setLoading(true);
		
		try
		{
			let response;
			
			switch (step)
			{
				//  Stage One - Submit email
				case 1 :
					// Yup validation
					await stageSchemas[0].validate({ email: signupData.email }, { abortEarly: false });
				
					response = await signupService.submitSignupStageOneEmail(
						{ email: signupData.email },
						csrf
					);
					if (response.success && response.userId)
					{
						setUserId(response.userId);
						setStep(2);
					}
					else
					{
						if (typeof response.message === 'object' && response.message !== null)
						{
							setFormErrors(response.message);
						}
						else
						{
							throw new Error(response.message || 'Failed to submit email');
						}
					}
					break;
					
				default :
					throw new Error('Invalid step');
			}	
		}
		catch (error: any)
		{
			setError(error.message || 'Unknown error occurred');
		}
		finally
		{
			setLoading(false);
		}
	
	//}, [step, signupData, userId, csrf]);
	}, [step, signupData, csrf]);
	
	/**
	* Navigation: Back button
	*/
	const handleBack = useCallback(() =>
	{
		if (step > 1)
		{
			setError(null);
			setStep(step - 1);
		}
	}, [step]);
	
	/**
	* Render file inputs helper
	*/
	const renderFileInput = (
		label: string,
		fieldName: keyof SignupData,
		accept?: string
	) => (
		<>
			<label className="form-label">{label}</label>
			<input
				type="file"
				accept={accept}
				disabled={loading}
				onChange={(e) => handleFileChange(e, fieldName)}
				className="form-control mb-3"
			/>
		</>
	);
	
	/**
	* Render fields based on current step
	*/
	const renderStepFields = () =>
	{
		switch (step)
		{
			case 1 :
				return (
					<div className="mb-3">
					
						<input type="hidden" name={csrf?.csrfParam} value={csrf?.csrfToken} />
						<label htmlFor="email" className="form-label">Email</label>
						<input
							id="email"
							type="email"
							className={`form-control ${formErrors.email ? 'is-invalid' : ''}`}
							value={signupData.email}
							onChange={e => updateField('email', e.target.value)}
							disabled={loading}
							required
						/>
						{formErrors.email && (
							<div className="invalid-feedback">
								{Array.isArray(formErrors.email) ? formErrors.email[0] : formErrors.email}
							</div>
						)}
						
					</div>
				);
			
			default :
				return <p>Invalid step</p>;
		}
	};
	
	return (
		<div id="site-signup-page" className="site-signup-page d-flex justify-content-center align-items-center" style={{ minheight: '80vh' }}>
			<div className="row justify-content-center align-items-center w-100 h-100">
			
				<div className="col-lg-6 col-md-6 col-sm-12">
				
					<div className="alert alert-info mt-4" role="alert">
						You are currently signing up during our beta phase. Once we are out of beta, there will 
						be a 14-day trial period. Pricing details will be provided then.
					</div>
			
					<h3 className="text-center mt-5">Sign Up - Step {step} of {TOTAL_STEPS}</h3>
			
					<div className="progress mb-4" style={{ height: '1.5rem' }}>
						<div
							className="progress-bar progress-bar-striped"
							//className="progress-bar progress-bar-striped progress-bar-animated"
							role="progressbar"
							style={{ width: `${progressPercent}%` }}
							aria-valuenow={step}
							aria-valuemin={1}
							aria-valuemax={TOTAL_STEPS}
						>
							Step {step} of {TOTAL_STEPS}
						</div>
					</div>
			
					{error && <div className="alert alert-danger">{error}</div>}
			
					{/**
					* Wrap current step fields in a form for accessibility 
					* Note: Using React.FormEvent
					*/}
					<form onSubmit={(e: FormEvent) =>
					{
						e.preventDefault();
						if (!loading)
						{
							submitStage();
						}
					}} noValidate>
						
						{renderStepFields()}
						
						
						{step > 1 && (
							<button
								type="button"
								className="btn btn-secondary"
								onClick={handleBack}
								disabled={loading}
							>
								Back
							</button>
						)}
						
						<button
							type="submit"
							className="btn btn-blue w-100"
							disabled={loading || (step === 1 && !signupData.email) || (step === 2 && !signupData.token)}
						>
							{loading ? 'Please wait...' : step === TOTAL_STEPS ? 'Confirm & Submit' : 'Next'}
						</button>
					</form>
					
					<p className="mt-3 text-center">Already have an account? <a href="/login">Log in</a></p>
				</div>
			</div>
		</div>
	);
}

export default Signup;


want the h3 and processbar to only appear in step 2, once the email has been submitted. step 2 is offically step on on the progressbar.