/**
 * Onboarding / demo-setup wizard. Registered as a banner toolbar item so it lives
 * in the admin shell: it auto-opens on first run (when not yet onboarded) and can
 * be reopened any time from the "Setup" button or a `cliq-sl:onboarding` event.
 *
 * Flow: Welcome → pick an industry (each demo is based in a different country) →
 * seed 20 stores + a matching category → done. Backed by /admin/onboarding*.
 */
import { useEffect, useState, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { Modal, Button, Spinner } from '@wordpress/components';
import {
	Sparkles,
	Check,
	ArrowRight,
	MapPin,
	Pizza,
	Pill,
	UtensilsCrossed,
	FerrisWheel,
	BedDouble,
	Coffee,
	Store,
	Layers3,
	X,
} from 'lucide-react';
import { adminGet, adminPost } from './adminApi';
import './sharedAdmin.scss';

// One line-icon per demo industry (no emojis).
const VERTICAL_ICONS = {
	pizza: Pizza,
	pharmacy: Pill,
	restaurant: UtensilsCrossed,
	amusement: FerrisWheel,
	hotel: BedDouble,
	coffee: Coffee,
};

const STEP_ORDER = [ 'welcome', 'pick', 'seeding', 'done' ];

const Onboarding = () => {
	const [ open, setOpen ] = useState( false );
	const [ step, setStep ] = useState( 'welcome' ); // welcome | pick | seeding | done
	const [ verticals, setVerticals ] = useState( [] );
	const [ selected, setSelected ] = useState( null );
	const [ result, setResult ] = useState( null );
	const [ ready, setReady ] = useState( false );

	const load = useCallback( () => {
		adminGet( 'onboarding' )
			.then( ( res ) => {
				setVerticals(
					Array.isArray( res?.verticals ) ? res.verticals : []
				);
				setReady( true );
				// Auto-open the first time (no demos run yet AND not dismissed).
				if ( ! res?.onboarded ) {
					setOpen( true );
				}
			} )
			.catch( () => setReady( true ) );
	}, [] );

	useEffect( () => {
		load();
		const reopen = () => {
			setStep( 'welcome' );
			setSelected( null );
			setResult( null );
			setOpen( true );
		};
		window.addEventListener( 'cliq-sl:onboarding', reopen );
		return () => window.removeEventListener( 'cliq-sl:onboarding', reopen );
	}, [ load ] );

	const dismiss = () => {
		adminPost( 'onboarding/dismiss', {} ).catch( () => {} );
		setOpen( false );
	};

	const seed = ( vertical ) => {
		setSelected( vertical );
		setStep( 'seeding' );
		adminPost( 'onboarding/seed', { vertical: vertical.key } )
			.then( ( res ) => {
				setResult( res );
				setStep( 'done' );
			} )
			.catch( () => {
				setResult( { error: true } );
				setStep( 'done' );
			} );
	};

	const launcher = (
		<button
			type="button"
			className="cliq-sl-bannerlink cliq-onb-launch"
			onClick={ () => {
				setStep( 'welcome' );
				setOpen( true );
			} }
			title={ __( 'Setup wizard', 'cliq-store-locator' ) }
		>
			<Sparkles size={ 15 } strokeWidth={ 2 } />
			<span>{ __( 'Setup', 'cliq-store-locator' ) }</span>
		</button>
	);

	if ( ! ready ) {
		return null;
	}

	return (
		<>
			{ launcher }
			{ open && (
				<Modal
					title=""
					className="cliq-onb-modal"
					onRequestClose={ step === 'seeding' ? () => {} : dismiss }
					style={ { maxWidth: 760, width: '92vw' } }
					__experimentalHideHeader
				>
					<div className="cliq-onb__chrome">
						<div className="cliq-onb__brand">
							<span>
								<Layers3 size={ 17 } strokeWidth={ 1.9 } />
							</span>
							<div>
								<strong>
									{ __(
										'Store Locator setup',
										'cliq-store-locator'
									) }
								</strong>
								<small>
									{ __(
										'Guided workspace',
										'cliq-store-locator'
									) }
								</small>
							</div>
						</div>
						<div
							className="cliq-onb__progress"
							aria-label={ __(
								'Setup progress',
								'cliq-store-locator'
							) }
						>
							{ STEP_ORDER.map( ( item, index ) => (
								<span
									key={ item }
									className={
										index <= STEP_ORDER.indexOf( step )
											? 'is-active'
											: ''
									}
								/>
							) ) }
						</div>
						{ step !== 'seeding' && (
							<button
								type="button"
								className="cliq-onb__close"
								onClick={ dismiss }
								aria-label={ __(
									'Close setup',
									'cliq-store-locator'
								) }
							>
								<X size={ 18 } />
							</button>
						) }
					</div>
					{ step === 'welcome' && (
						<div className="cliq-onb">
							<div className="cliq-onb__hero">
								<span className="cliq-onb__spark">
									<Sparkles size={ 26 } />
								</span>
								<h1>
									{ __(
										'Welcome to Store Locator',
										'cliq-store-locator'
									) }
								</h1>
								<p>
									{ __(
										'Let’s get you set up in seconds. Spin up a fully-working demo locator with 20 sample stores, or start from a blank slate and add your own.',
										'cliq-store-locator'
									) }
								</p>
							</div>
							<div className="cliq-onb__actions">
								<Button
									variant="primary"
									className="cliq-onb__cta"
									onClick={ () => setStep( 'pick' ) }
								>
									{ __(
										'Set up demo stores',
										'cliq-store-locator'
									) }{ ' ' }
									<ArrowRight size={ 16 } />
								</Button>
								<Button variant="tertiary" onClick={ dismiss }>
									{ __(
										'Skip — I’ll add my own',
										'cliq-store-locator'
									) }
								</Button>
							</div>
						</div>
					) }

					{ step === 'pick' && (
						<div className="cliq-onb">
							<div className="cliq-onb__head">
								<h2>
									{ __(
										'Pick a demo industry',
										'cliq-store-locator'
									) }
								</h2>
								<p>
									{ __(
										'We’ll create 20 sample stores and a matching category — each demo is based in a different country.',
										'cliq-store-locator'
									) }
								</p>
							</div>
							<div className="cliq-onb__grid">
								{ verticals.map( ( v ) => {
									const Icon =
										VERTICAL_ICONS[ v.key ] || Store;
									return (
										<button
											type="button"
											key={ v.key }
											className="cliq-onb__card"
											onClick={ () => seed( v ) }
										>
											<span
												className="cliq-onb__icon"
												style={ {
													background: `${ v.color }14`,
													color: v.color,
												} }
											>
												<Icon
													size={ 26 }
													strokeWidth={ 1.8 }
												/>
											</span>
											<span className="cliq-onb__label">
												{ v.label }
											</span>
											<span className="cliq-onb__meta">
												<MapPin size={ 12 } />{ ' ' }
												{ v.countryLabel } ·{ ' ' }
												{ sprintf(
													__(
														'%d stores',
														'cliq-store-locator'
													),
													v.count
												) }
											</span>
										</button>
									);
								} ) }
							</div>
							<div className="cliq-onb__actions cliq-onb__actions--split">
								<Button
									variant="tertiary"
									onClick={ () => setStep( 'welcome' ) }
								>
									{ __( 'Back', 'cliq-store-locator' ) }
								</Button>
								<Button variant="tertiary" onClick={ dismiss }>
									{ __( 'Skip', 'cliq-store-locator' ) }
								</Button>
							</div>
						</div>
					) }

					{ step === 'seeding' && (
						<div className="cliq-onb cliq-onb--center">
							<Spinner />
							<h2>
								{ sprintf(
									__(
										'Creating your %s demo…',
										'cliq-store-locator'
									),
									selected?.label || ''
								) }
							</h2>
							<p>
								{ __(
									'Adding stores, locations, opening hours and a category. This takes a few seconds.',
									'cliq-store-locator'
								) }
							</p>
						</div>
					) }

					{ step === 'done' && (
						<div className="cliq-onb cliq-onb--center">
							{ result?.error ? (
								<>
									<h2>
										{ __(
											'Something went wrong',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ __(
											'The demo couldn’t be created. Please try again.',
											'cliq-store-locator'
										) }
									</p>
									<Button
										variant="primary"
										onClick={ () => setStep( 'pick' ) }
									>
										{ __(
											'Try again',
											'cliq-store-locator'
										) }
									</Button>
								</>
							) : (
								<>
									<span className="cliq-onb__tick">
										<Check size={ 30 } />
									</span>
									<h2>
										{ __(
											'Your demo is ready!',
											'cliq-store-locator'
										) }
									</h2>
									<p>
										{ sprintf(
											__(
												'Created %1$d new %2$s stores%3$s. You now have %4$d stores in total.',
												'cliq-store-locator'
											),
											result?.created || 0,
											selected?.label || '',
											result?.skipped
												? sprintf(
														__(
															' (%d already existed)',
															'cliq-store-locator'
														),
														result.skipped
												  )
												: '',
											result?.total || 0
										) }
									</p>
									<div className="cliq-onb__actions">
										<Button
											variant="primary"
											className="cliq-onb__cta"
											onClick={ () => {
												window.location.hash =
													'#/stores';
												setOpen( false );
												window.location.reload();
											} }
										>
											{ __(
												'View my stores',
												'cliq-store-locator'
											) }{ ' ' }
											<ArrowRight size={ 16 } />
										</Button>
										<Button
											variant="tertiary"
											onClick={ () => setStep( 'pick' ) }
										>
											{ __(
												'Add another demo',
												'cliq-store-locator'
											) }
										</Button>
									</div>
								</>
							) }
						</div>
					) }
				</Modal>
			) }
		</>
	);
};

export default Onboarding;
