import { useState, useRef, useEffect, useLayoutEffect } from 'react';
import useOnboarding from '@/hooks/useOnboarding';
import usePageView from '@/hooks/analytics/usePageView';

// Import all steps
import Goal from '@/features/onboarding/steps/Goal';
import LoadingProfile from '@/features/onboarding/steps/LoadingProfile';
import BusinessChat from '@/features/onboarding/steps/BusinessChat';
import LoadingTaglines from '@/features/onboarding/steps/LoadingTaglines';
import TaglineSelection from '@/features/onboarding/steps/TaglineSelection';
import TaglineLive from '@/features/onboarding/steps/TaglineLive';
import AgentMode from '@/features/onboarding/steps/AgentMode';
import Complete from '@/features/onboarding/steps/Complete';
import HttpsRequired from '@/features/onboarding/steps/HttpsRequired';

/**
 * OnboardingPage Component
 *
 * Multi-step onboarding wizard.
 * Goal → LoadingProfile → BusinessChat → LoadingTaglines → TaglineSelection
 * → Complete → TaglineLive → AgentMode
 *
 * @param {Function} onComplete - Callback when onboarding is complete
 */
const OnboardingPage = ({ onComplete }) => {
	const { data: backendData, currentStep: resumeStep } = useOnboarding();

	const steps = [Goal, LoadingProfile, BusinessChat, LoadingTaglines, TaglineSelection, Complete, TaglineLive, AgentMode];
	const totalSteps = steps.length;

	// Resume from backend state, or start at 1
	const [currentStep, setCurrentStep] = useState(resumeStep || 1);

	const [sessionData, setSessionData] = useState({});

	// Set once any Executor call reports the site is unreachable (http-only).
	// Transient: the screen's "Check again" reloads the page, so we don't persist it.
	const [connectionBlocked, setConnectionBlocked] = useState(false);

	// Merge backend data with session data
	const data = { ...backendData, ...sessionData };

	usePageView('onboarding');

	const mainRef = useRef(null);
	const CurrentStepComponent = steps[currentStep - 1];

	// Scroll to top on step change
	useEffect(() => {
		mainRef.current?.scrollTo(0, 0);
	}, [currentStep]);

	// The plugin renders inside wp-admin, where the chrome above us (admin bar +
	// any admin notices) pushes #flavio down by a variable, CSS-unknowable amount.
	// Pin the scroll area's height to exactly the space left below it so its
	// content can be vertically centered (via my-auto) without overflowing the
	// fold. Recompute on resize and whenever the surrounding chrome changes height.
	useLayoutEffect(() => {
		const el = mainRef.current;
		if (!el) return;

		const resize = () => {
			const top = el.getBoundingClientRect().top;
			el.style.height = `${Math.max(0, window.innerHeight - top)}px`;
		};

		resize();
		window.addEventListener('resize', resize);
		const observer = new ResizeObserver(resize);
		observer.observe(document.body);
		return () => {
			window.removeEventListener('resize', resize);
			observer.disconnect();
		};
	}, []);

	const handleNext = (stepData) => {
		if (stepData) {
			setSessionData((prev) => ({ ...prev, ...stepData }));
		}

		if (currentStep >= totalSteps) {
			onComplete?.();
		} else {
			setCurrentStep((prev) => prev + 1);
		}
	};

	const goToNextStep = () => {
		setCurrentStep((prev) => Math.min(prev + 1, totalSteps));
	};

	return (
		<main
			ref={mainRef}
			className="flex flex-col overflow-auto min-h-0"
		>
			<div className="my-auto w-full py-12">
				{connectionBlocked ? (
					<HttpsRequired />
				) : (
					CurrentStepComponent && (
						<CurrentStepComponent
							onNext={handleNext}
							goToNextStep={goToNextStep}
							data={data}
							onConnectionBlocked={() =>
								setConnectionBlocked(true)
							}
						/>
					)
				)}
			</div>
		</main>
	);
};

export default OnboardingPage;
