'use client';

import { useEffect, useRef, useState } from 'react';
import dynamic from 'next/dynamic';
import Autocomplete from '@mui/material/Autocomplete';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import Backdrop from '@mui/material/Backdrop';
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';
import Dialog from '@mui/material/Dialog';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
import OpenInFullRoundedIcon from '@mui/icons-material/OpenInFullRounded';
import BadgeOutlinedIcon from '@mui/icons-material/BadgeOutlined';
import BusinessOutlinedIcon from '@mui/icons-material/BusinessOutlined';
import CheckCircleOutlineRoundedIcon from '@mui/icons-material/CheckCircleOutlineRounded';
import EmailOutlinedIcon from '@mui/icons-material/EmailOutlined';
import ErrorOutlineRoundedIcon from '@mui/icons-material/ErrorOutlineRounded';
import GpsFixedRoundedIcon from '@mui/icons-material/GpsFixedRounded';
import HomeOutlinedIcon from '@mui/icons-material/HomeOutlined';
import LocationOnOutlinedIcon from '@mui/icons-material/LocationOnOutlined';
import PersonOutlineRoundedIcon from '@mui/icons-material/PersonOutlineRounded';
import PhoneOutlinedIcon from '@mui/icons-material/PhoneOutlined';
import PublicRoundedIcon from '@mui/icons-material/PublicRounded';
import { DEPARTAMENTOS, PARAGUAY_GEO } from './paraguayGeo';
import StoreLoginForm from './StoreLoginForm';
import StoreRegisterForm from './StoreRegisterForm';
import AddIcon from '@mui/icons-material/Add';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded';
import CheckCircleRoundedIcon from '@mui/icons-material/CheckCircleRounded';
import CreditCardRoundedIcon from '@mui/icons-material/CreditCardRounded';
import LocalShippingOutlinedIcon from '@mui/icons-material/LocalShippingOutlined';
import LockRoundedIcon from '@mui/icons-material/LockRounded';
import PersonOutlineOutlinedIcon from '@mui/icons-material/PersonOutlineOutlined';
import RemoveIcon from '@mui/icons-material/Remove';
import ShoppingCartRoundedIcon from '@mui/icons-material/ShoppingCartRounded';

const GeoMap = dynamic(() => import('./GeoMap'), { ssr: false });
import type { DeliveryMethod, PaymentMethod, StoreConfig } from '../../config/defaultStoreConfig';
import type { CartItem } from './cartTypes';
import {
	CheckoutPage,
	ProductDetailTop,
	CheckoutSuccess,
	CheckoutSuccessActions,
	CheckoutAccessGate,
	CheckoutAccessHero,
	CheckoutAccessOptions,
	CheckoutAccessCard,
	CheckoutStepNav,
	CheckoutStepper,
	CheckoutWorkLayout,
	CheckoutLeftColumn,
	CheckoutRightColumn,
	CheckoutMethodGrid,
	CheckoutNotesField,
	CheckoutPanel,
	CheckoutSectionTitle,
	CheckoutFields,
	CheckoutChoiceList,
	CheckoutRadioRow,
	PaymentBox,
	CheckoutCartTable,
	CheckoutCartHead,
	CheckoutCartRow,
	CheckoutOrderTotals,
	TermsCheck,
	CheckoutConfirmActions,
	QtyControl
} from '../styles';
import { storeImageSrc } from '@/lib/storeImage';

interface BillingData {
	ruc: string;
	dv: string;
	dvError: string;
	razonSocial: string;
	naturaleza: number | null;
	tipoContribuyente: number | null;
	consultadoSIFEN: boolean;
	consultaLoading: boolean;
	consultaError: string;
	/** 'no_encontrado' = SIFEN respondió y no está | 'sin_servicio' = no se pudo consultar. */
	consultaMotivo?: 'no_encontrado' | 'sin_servicio' | '';
}

interface StoreAuth {
	cliente: { nombre: string; email: string; telefono?: string } | null;
	loading: boolean;
	error: string | null;
	login: (email: string, password: string) => Promise<unknown>;
	register: (data: { email: string; password: string; nombre: string; telefono?: string }) => Promise<unknown>;
	clearError: () => void;
}

type CustomerField = 'name' | 'email' | 'phone' | 'address' | 'departamento' | 'distrito' | 'ciudad' | 'nroCasa';

interface Props {
	cartItems: CartItem[];
	cartTotal: number;
	checkoutConfirmed: boolean;
	checkoutWarnings?: string[] | null;
	checkoutStage: 'auth' | 'checkout';
	checkoutAccessMode: 'login' | 'register' | 'guest' | null;
	effectiveDeliveryType: 'delivery' | 'pickup';
	/** Se entró desde el ícono de cuenta: sólo identificarse, sin compra invitada. */
	soloAcceso?: boolean;
	effectiveDeliveryMethodId: string;
	deliveryMethods: DeliveryMethod[];
	deliveryCost: number;
	effectivePaymentMethodId: string;
	paymentMethods: PaymentMethod[];
	paymentDiscount: number;
	checkoutTotal: number;
	checkoutOrderCode: string;
	acceptTerms: boolean;
	config: StoreConfig;
	customer: { name: string; email: string; phone: string; address: string; departamento: string; distrito: string; ciudad: string; nroCasa: string };
	checkoutSubmitting: boolean;
	storeAuth: StoreAuth;
	formatPrice: (value: number) => string;
	onClose: () => void;
	onConfirm: () => void;
	onContinueAs: (mode: 'login' | 'register' | 'guest', clienteData?: { nombre: string; email: string; telefono?: string; documento?: string }) => void;
	onUpdateQuantity: (id: string, delta: number) => void;
	onSetDeliveryMethod: (methodId: string) => void;
	onSetPaymentMethod: (methodId: string) => void;
	onSetAcceptTerms: (value: boolean) => void;
	onSetCheckoutStage: (stage: 'auth' | 'checkout') => void;
	onCustomerChange: (field: CustomerField, value: string) => void;
	onBillingChange: (data: Partial<BillingData>) => void;
	/** RUC/CI guardado en la cuenta del cliente, para no volver a pedírselo. */
	rucPrecargado?: string | null;
	comentarios: string;
	onComentariosChange: (value: string) => void;
	onOpenContentPage: (key: string) => void;
	onGeoChange?: (coords: { lat: number; lng: number } | null) => void;
	checkoutError?: string | null;
	onClearCheckoutError?: () => void;
}

export type { BillingData };


const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
export default function CheckoutSection({
	cartItems,
	cartTotal,
	checkoutConfirmed,
	checkoutWarnings,
	checkoutStage,
	checkoutAccessMode,
	effectiveDeliveryType,
	soloAcceso = false,
	effectiveDeliveryMethodId,
	deliveryMethods,
	deliveryCost,
	effectivePaymentMethodId,
	paymentMethods,
	paymentDiscount,
	checkoutTotal,
	checkoutOrderCode,
	acceptTerms,
	config,
	customer,
	checkoutSubmitting,
	storeAuth,
	formatPrice,
	onClose,
	onConfirm,
	onContinueAs,
	onUpdateQuantity,
	onSetDeliveryMethod,
	onSetPaymentMethod,
	onSetAcceptTerms,
	onSetCheckoutStage,
	onCustomerChange,
	onBillingChange,
	rucPrecargado,
	comentarios,
	onComentariosChange,
	onOpenContentPage,
	onGeoChange,
	checkoutError,
	onClearCheckoutError,
}: Props) {

	// El radio guarda sólo el id; acá se resuelve el medio completo para poder
	// distinguir online de manual en los textos.
	const selectedPaymentMethod = paymentMethods.find((m) => m.id === effectivePaymentMethodId);

	// Checkout por pasos. `checkout.layout` ya estaba declarado en la config ('singlePage'
	// | 'steps') pero nadie lo leía: la tienda siempre mostraba todo junto. Los grupos
	// siguen el orden natural del formulario — quién sos, cómo lo recibís, qué llevás.
	const stepsMode = config.checkout.layout === 'steps';
	const [step, setStep] = useState(1);
	// Al pasar de paso la página quedaba scrolleada donde estaba el botón
	// "Siguiente": el paso nuevo arrancaba con su título fuera de la vista.
	const pasoInicialRef = useRef(true);
	useEffect(() => {
		if (pasoInicialRef.current) {
			pasoInicialRef.current = false;
			return;
		}
		window.scrollTo({ top: 0, behavior: 'smooth' });
	}, [step]);
	const errorRef = useRef<HTMLDivElement | null>(null);
	useEffect(() => {
		if (checkoutError) errorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
	}, [checkoutError]);
	const TOTAL_STEPS = 3;
	const showStep = (n: number) => !stepsMode || step === n;

	const [authForm, setAuthForm] = useState<'cards' | 'login' | 'register'>('cards');

	// login y registro comparten un único `storeAuth.error`, así que un fallo en uno
	// aparecía en el otro ("contraseña incorrecta" sobre el formulario de registro).
	// Al cambiar de formulario se descarta el error del anterior.
	const clearAuthError = storeAuth.clearError;
	useEffect(() => {
		clearAuthError();
		// `clearAuthError` se recrea en cada render del hook; incluirla haría un loop.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [authForm]);
	const [billing, setBilling] = useState<BillingData>({
		ruc: '', dv: '', dvError: '', razonSocial: '',
		naturaleza: null, tipoContribuyente: null,
		consultadoSIFEN: false, consultaLoading: false, consultaError: '', consultaMotivo: '',
	});
	const [geo, setGeo] = useState<{ lat: number; lng: number } | null>(null);
	const [geoStatus, setGeoStatus] = useState<'idle' | 'loading' | 'ok' | 'error'>('idle');
	const [geoError, setGeoError] = useState('');
	const [geoDialogOpen, setGeoDialogOpen] = useState(false);
	const rucDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
	const selectedDeliveryMethod = deliveryMethods.find((method) => method.id === effectiveDeliveryMethodId);
	// El botón de confirmar se deshabilitaba sin decir por qué. Enumeramos lo que falta
	// para que el comprador sepa a dónde volver en vez de quedarse trabado.
	const emailInvalido = Boolean(customer.email.trim()) && !EMAIL_RE.test(customer.email.trim());
	const telefonoInvalido = Boolean(customer.phone.trim()) && customer.phone.replace(/\D/g, '').length < 7;
	const datosFaltantes: string[] = [];
	if (cartItems.length === 0) datosFaltantes.push('agregar al menos un producto al carrito');
	if (customer.name.trim().length < 3) datosFaltantes.push('tu nombre y apellido');
	if (!billing.ruc.trim()) datosFaltantes.push('el RUC o CI para la factura');
	if (!customer.phone.trim() && !customer.email.trim())
		datosFaltantes.push('un teléfono o un email de contacto');
	// Sólo se miraba que no estuvieran vacíos: "esto-no-es-un-email" y "12" pasaban, y el
	// comercio se quedaba sin forma de contactar al comprador.
	if (emailInvalido) datosFaltantes.push('un email válido');
	if (telefonoInvalido) datosFaltantes.push('un teléfono válido (al menos 7 dígitos)');
	// Un delivery se confirmaba sin dirección, departamento ni ciudad.
	if (effectiveDeliveryType === 'delivery') {
		const faltaEntrega = [
			!customer.address.trim() && 'la dirección',
			!customer.departamento && 'el departamento',
			!customer.ciudad && 'la ciudad',
		].filter(Boolean);
		if (faltaEntrega.length) datosFaltantes.push(`${faltaEntrega.join(', ')} de entrega`);
	}
	if (config.checkout.requireTermsAcceptance && !acceptTerms)
		datosFaltantes.push('aceptar los términos y condiciones');

	// "Confirmar pedido" no decía qué iba a pasar al tocarlo: con un medio online lleva
	// a pagar, y con uno manual sólo deja el pedido tomado. El botón lo dice.
	const pagaAhora = selectedPaymentMethod?.type === 'online';
	const textoConfirmar = pagaAhora ? 'Ir a pagar' : 'Confirmar pedido';
	useEffect(() => () => { if (rucDebounceRef.current) clearTimeout(rucDebounceRef.current); }, []);

	const handleRequestGeo = () => {
		if (!navigator.geolocation) {
			setGeoStatus('error');
			setGeoError('La geolocalización no está disponible en este navegador.');
			return;
		}
		setGeoStatus('loading');
		setGeoError('');
		navigator.geolocation.getCurrentPosition(
			(pos) => {
				const coords = { lat: pos.coords.latitude, lng: pos.coords.longitude };
				setGeo(coords);
				setGeoStatus('ok');
				onGeoChange?.(coords);
			},
			(err) => {
				setGeoStatus('error');
				setGeoError(
					err.code === 1
						? 'Permiso de ubicación denegado. Habilitalo en la configuración del navegador.'
						: 'No se pudo obtener la ubicación. Intentá de nuevo.',
				);
			},
			{ enableHighAccuracy: true, timeout: 10000 },
		);
	};

	const handleSelectMode = (mode: 'login' | 'register' | 'guest') => {
		if (mode === 'guest') {
			onContinueAs('guest');
			return;
		}
		if (storeAuth.cliente) {
			onContinueAs(mode);
			return;
		}
		setAuthForm(mode);
	};

	const handleLoginSubmit = async (email: string, password: string) => {
		const cliente = (await storeAuth.login(email, password)) as { nombre: string; email: string; telefono?: string; documento?: string } | null;
		if (cliente) {
			onContinueAs('login', { nombre: cliente.nombre, email: cliente.email, telefono: cliente.telefono, documento: cliente.documento });
		}
	};

	const handleRegisterSubmit = async (data: { email: string; password: string; nombre: string; telefono?: string }) => {
		const cliente = (await storeAuth.register(data)) as { nombre: string; email: string; telefono?: string; documento?: string } | null;
		if (cliente) {
			onContinueAs('register', { nombre: cliente.nombre, email: cliente.email, telefono: data.telefono, documento: cliente.documento });
		}
	};

	const updateBilling = (patch: Partial<BillingData>) => {
		setBilling((prev) => {
			const next = { ...prev, ...patch };
			onBillingChange(next);
			return next;
		});
	};

	const consultarRuc = async (ruc: string) => {
		updateBilling({ consultaLoading: true, consultaError: '', consultadoSIFEN: false, razonSocial: '' });
		const subdominio = config.identity.subdomain ?? '';
		try {
			const res = await fetch(`/api/store/ruc/${ruc}?subdominio=${encodeURIComponent(subdominio)}`);
			const data = await res.json().catch(() => ({}));
			if (!res.ok) {
				// El backend distingue "SIFEN dice que no existe" de "no pudimos consultar".
				// Mezclarlos hacía que una caída del servicio le avisara al comprador que se
				// lo iba a facturar como no contribuyente.
				const motivo = data?.motivo === 'sin_servicio' ? 'sin_servicio' : 'no_encontrado';
				updateBilling({
					consultaLoading: false,
					consultaError: data?.message ?? 'RUC no encontrado en SIFEN',
					consultaMotivo: motivo,
					consultadoSIFEN: false,
					dv: '',
				});
				return;
			}
			updateBilling({
				consultaLoading: false, consultaError: '', consultaMotivo: '', consultadoSIFEN: true,
				razonSocial: data.razonSocial ?? '', naturaleza: data.naturaleza ?? null,
				tipoContribuyente: data.tipoContribuyente ?? null,
				dv: data.dv ? String(data.dv) : '',
			});
		} catch {
			updateBilling({
				consultaLoading: false,
				consultaError: 'Sin conexión con SIFEN',
				consultaMotivo: 'sin_servicio',
				consultadoSIFEN: false,
				dv: '',
			});
		}
	};

	// El cliente logueado ya dejó su RUC en una compra anterior: se siembra el campo y
	// se consulta a SIFEN una sola vez, en vez de mostrarlo vacío como si fuera nuevo.
	const rucSembradoRef = useRef<string | null>(null);
	useEffect(() => {
		const ruc = (rucPrecargado ?? '').replace(/\D/g, '').slice(0, 8);
		if (!ruc || !/^\d{6,8}$/.test(ruc)) return;
		if (rucSembradoRef.current === ruc) return;
		if (billing.ruc) return;
		rucSembradoRef.current = ruc;
		updateBilling({ ruc });
		consultarRuc(ruc);
		// `billing.ruc` sólo se lee para no pisar lo que el comprador ya escribió.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [rucPrecargado]);

	const handleRucChange = (val: string) => {
		const ruc = val.replace(/\D/g, '').slice(0, 8);
		updateBilling({
			ruc, dv: '', dvError: '',
			razonSocial: '', naturaleza: null, tipoContribuyente: null,
			consultadoSIFEN: false, consultaError: '',
		});
		if (rucDebounceRef.current) clearTimeout(rucDebounceRef.current);
		if (/^\d{6,8}$/.test(ruc)) {
			rucDebounceRef.current = setTimeout(() => consultarRuc(ruc), 700);
		}
	};

	return (
		<CheckoutPage>
			<ProductDetailTop>
				<Button
					variant="outlined"
					size="small"
					startIcon={<ArrowBackRoundedIcon />}
					onClick={onClose}
				>
					Volver al catálogo
				</Button>
				{!soloAcceso && <span>Checkout seguro con {config.checkout.paymentProviderLabel}</span>}
			</ProductDetailTop>

			{checkoutConfirmed ? (
				<CheckoutSuccess>
					<CheckCircleRoundedIcon />
					<Typography
						component="h1"
						variant="h4"
					>
						Pedido recibido
					</Typography>
					<p>
						Tu pedido {checkoutOrderCode} fue registrado correctamente. El equipo verificará los datos, preparará el envío y actualizará el seguimiento.
					</p>
					{!!checkoutWarnings?.length && (
						<Alert
							severity="warning"
							variant="outlined"
							sx={{ borderRadius: 2.5, textAlign: 'left', mb: 1 }}
						>
							{checkoutWarnings.join(' ')}
						</Alert>
					)}
					<CheckoutSuccessActions>
						<Button
							variant="contained"
							endIcon={<ArrowForwardRoundedIcon />}
							onClick={() => onOpenContentPage('seguimiento')}
						>
							Ver seguimiento
						</Button>
						<Button
							variant="outlined"
							onClick={onClose}
						>
							Seguir comprando
						</Button>
					</CheckoutSuccessActions>
				</CheckoutSuccess>
			) : checkoutStage === 'auth' ? (
				<CheckoutAccessGate>
					{authForm === 'login' ? (
						<StoreLoginForm
							loading={storeAuth.loading}
							error={storeAuth.error}
							onBack={() => { storeAuth.clearError(); setAuthForm('cards'); }}
							onSubmit={handleLoginSubmit}
							onSwitchToRegister={() => setAuthForm('register')}
						/>
					) : authForm === 'register' ? (
						<StoreRegisterForm
							loading={storeAuth.loading}
							error={storeAuth.error}
							onBack={() => { storeAuth.clearError(); setAuthForm('cards'); }}
							onSubmit={handleRegisterSubmit}
							onSwitchToLogin={() => setAuthForm('login')}
						/>
					) : (
						<>
							<CheckoutAccessHero>
								{/* Desde el ícono de cuenta no hay compra en curso: se habla de la cuenta,
								    no del checkout. */}
								<Chip label={soloAcceso ? 'Mi cuenta' : 'Antes de continuar'} size="small" sx={{ background: 'var(--store-primary)', color: '#fff' }} />
								<Typography component="h1" variant="h4">
									{storeAuth.cliente
										? `Hola, ${storeAuth.cliente.nombre.split(' ')[0]}`
										: soloAcceso
											? 'Ingresá a tu cuenta'
											: 'Identificate para finalizar la compra'}
								</Typography>
								<p>
									{storeAuth.cliente
										? `Continuarás como ${storeAuth.cliente.email}. Podés cambiar de cuenta a continuación.`
										: soloAcceso
											? 'Mirá tus pedidos, su seguimiento y tus datos de facturación y entrega.'
											: 'Usaremos tu cuenta para guardar datos de entrega, facturación y seguimiento del pedido.'}
								</p>
							</CheckoutAccessHero>
							<CheckoutAccessOptions>
								<CheckoutAccessCard type="button" onClick={() => handleSelectMode('login')}>
									<PersonOutlineOutlinedIcon />
									<strong>{storeAuth.cliente ? 'Continuar como ' + storeAuth.cliente.nombre.split(' ')[0] : 'Iniciar sesión'}</strong>
									<span>{storeAuth.cliente ? storeAuth.cliente.email : 'Recuperá tus direcciones, pedidos y precios asignados.'}</span>
								</CheckoutAccessCard>
								{!storeAuth.cliente && (
									<CheckoutAccessCard type="button" onClick={() => handleSelectMode('register')}>
										<CheckCircleRoundedIcon />
										<strong>Crear cuenta</strong>
										<span>Registrá tus datos una vez y comprá más rápido la próxima.</span>
									</CheckoutAccessCard>
								)}
								{config.checkout.allowGuestB2C && !soloAcceso && (
									<CheckoutAccessCard type="button" onClick={() => handleSelectMode('guest')}>
										<ShoppingCartRoundedIcon />
										<strong>Compra invitada</strong>
										<span>Seguí sin cuenta y recibí el seguimiento por email o WhatsApp.</span>
									</CheckoutAccessCard>
								)}
							</CheckoutAccessOptions>
						</>
					)}
				</CheckoutAccessGate>
			) : (
				<>
				{stepsMode && (
					<CheckoutStepper>
						{[
							{ n: 1, label: 'Tus datos' },
							{ n: 2, label: 'Entrega y pago' },
							{ n: 3, label: 'Confirmar' }
						].map((s, i) => (
							<li key={s.n} data-active={step === s.n} data-done={step > s.n}>
								{i > 0 && <span className="step-sep" />}
								<span className="step-dot">{step > s.n ? '✓' : s.n}</span>
								{s.label}
							</li>
						))}
					</CheckoutStepper>
				)}

				<CheckoutWorkLayout $steps={stepsMode}>
					{showStep(1) && (
					<CheckoutLeftColumn>
						{/* Panel 1: Datos de facturación */}
						<CheckoutPanel>
							<CheckoutSectionTitle>
								<span>1</span>
								Datos de facturación
							</CheckoutSectionTitle>
							<CheckoutFields>
								<div style={{ display: 'grid', gridTemplateColumns: billing.dv ? '1fr auto' : '1fr', gap: 8, alignItems: 'flex-start' }}>
									<TextField
										label="RUC / CI"
										size="small"
										fullWidth
										value={billing.ruc}
										onChange={(e) => handleRucChange(e.target.value)}
										inputProps={{ inputMode: 'numeric', maxLength: 8 }}
										placeholder="Ej: 80061967 o 1234567"
										InputProps={{
											startAdornment: (
												<InputAdornment position="start">
													<BadgeOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
												</InputAdornment>
											),
											endAdornment: billing.consultaLoading
												? <InputAdornment position="end"><CircularProgress size={14} /></InputAdornment>
												: billing.consultadoSIFEN
													? <InputAdornment position="end"><CheckCircleOutlineRoundedIcon sx={{ color: 'var(--store-success)', fontSize: 'small' }} /></InputAdornment>
													: billing.consultaError && billing.ruc
														? <InputAdornment position="end"><ErrorOutlineRoundedIcon sx={{ color: 'var(--store-danger)', fontSize: 'small' }} /></InputAdornment>
														: undefined,
										}}
									/>
									{billing.dv && (
										<TextField
											label="DV"
											size="small"
											value={billing.dv}
											inputProps={{ readOnly: true, style: { width: 44, textAlign: 'center' } }}
										/>
									)}
								</div>
								{billing.consultaError && billing.ruc && (
									<Typography
										variant="caption"
										sx={{
											color:
												billing.consultaMotivo === 'sin_servicio'
													? 'var(--store-muted)'
													: 'var(--store-danger)',
										}}
									>
										{billing.consultaMotivo === 'sin_servicio'
											? 'No pudimos verificar el RUC contra SIFEN en este momento. Podés seguir con la compra: el comercio lo valida antes de facturar.'
											: 'No encontrado en SIFEN — se facturará como no contribuyente con el documento ingresado'}
									</Typography>
								)}
								{billing.razonSocial && (
									<TextField
										label="Razón social"
										size="small"
										fullWidth
										value={billing.razonSocial}
										InputProps={{
											readOnly: true,
											startAdornment: (
												<InputAdornment position="start">
													<BusinessOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
												</InputAdornment>
											),
										}}
										helperText={billing.naturaleza === 2 ? 'Persona jurídica contribuyente' : billing.naturaleza === 1 ? 'Persona física contribuyente' : 'Contribuyente activo'}
									/>
								)}
								{!(billing.consultaError && billing.ruc) && (
									<Typography variant="caption" color="text.secondary">
										{billing.ruc.trim()
											? 'Si figura en SIFEN, se emitirá la factura a nombre de la razón social.'
											: 'Requerido. Ingresá tu RUC o CI para continuar.'}
									</Typography>
								)}
								<TextField
									label="Nombre y apellido"
									size="small"
									fullWidth
									value={customer.name}
									onChange={(e) => onCustomerChange('name', e.target.value)}
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<PersonOutlineRoundedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
								<TextField
									label="Email"
									size="small"
									type="email"
									fullWidth
									value={customer.email}
									onChange={(e) => onCustomerChange('email', e.target.value)}
									error={emailInvalido}
									helperText={emailInvalido ? 'Revisá el email: le falta la @ o el dominio.' : undefined}
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<EmailOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
								<TextField
									label="Teléfono / WhatsApp"
									size="small"
									fullWidth
									value={customer.phone}
									onChange={(e) => onCustomerChange('phone', e.target.value)}
									error={telefonoInvalido}
									helperText={telefonoInvalido ? 'Ingresá el número completo, ej. 0981 123 456.' : undefined}
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<PhoneOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
							</CheckoutFields>
						</CheckoutPanel>

						{/* Con retiro en local se seguía pidiendo departamento, ciudad, número de casa y
						    ubicación, que no se usan. En su lugar se muestra dónde y cuándo retirar. */}
						{effectiveDeliveryType === 'pickup' ? (
							<CheckoutPanel>
								<CheckoutSectionTitle>
									<span>2</span>
									Retiro en el local
								</CheckoutSectionTitle>
								<Typography variant="body2" sx={{ display: 'grid', gap: 0.5 }}>
									{config.footer.contact?.map?.title && <strong>{config.footer.contact.map.title}</strong>}
									{config.footer.contact?.address && <span>{config.footer.contact.address}</span>}
									{config.footer.contact?.hours && <span>Horario: {config.footer.contact.hours}</span>}
									{config.footer.contact?.map?.directionsUrl && (
										<a href={config.footer.contact.map.directionsUrl} target="_blank" rel="noreferrer" style={{ color: 'var(--store-primary)', fontWeight: 700 }}>
											Cómo llegar
										</a>
									)}
									<span style={{ color: 'var(--store-muted)' }}>Te avisamos cuando el pedido esté listo para retirar.</span>
								</Typography>
							</CheckoutPanel>
						) : (
						<CheckoutPanel>
							<CheckoutSectionTitle>
								<span>2</span>
								Dirección de entrega
							</CheckoutSectionTitle>
							<CheckoutFields>
								<TextField
									label="País"
									size="small"
									fullWidth
									value="Paraguay"
									disabled
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<PublicRoundedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
								<Autocomplete
									size="small"
									fullWidth
									autoHighlight
									options={DEPARTAMENTOS}
									value={customer.departamento || null}
									onChange={(_, value) => {
										onCustomerChange('departamento', value ?? '');
										onCustomerChange('distrito', '');
										onCustomerChange('ciudad', '');
									}}
									noOptionsText="Sin resultados"
									renderInput={(params) => <TextField {...params} label="Departamento" required />}
								/>
								<Autocomplete
									size="small"
									fullWidth
									autoHighlight
									disabled={!customer.departamento}
									options={PARAGUAY_GEO[customer.departamento] ?? []}
									value={customer.distrito || null}
									onChange={(_, value) => {
										onCustomerChange('distrito', value ?? '');
										onCustomerChange('ciudad', value ?? '');
									}}
									noOptionsText="Sin resultados"
									renderInput={(params) => <TextField {...params} label="Distrito" />}
								/>
								<Autocomplete
									size="small"
									fullWidth
									autoHighlight
									disabled={!customer.distrito}
									options={PARAGUAY_GEO[customer.departamento] ?? []}
									value={customer.ciudad || null}
									onChange={(_, value) => onCustomerChange('ciudad', value ?? '')}
									noOptionsText="Sin resultados"
									renderInput={(params) => <TextField {...params} label="Ciudad" required />}
								/>
								<TextField
									label="Nro. de casa"
									size="small"
									fullWidth
									value={customer.nroCasa}
									onChange={(e) => onCustomerChange('nroCasa', e.target.value)}
									placeholder="Ej: 345 (0 si no aplica)"
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<HomeOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
								<TextField
									label="Dirección"
									required
									size="small"
									fullWidth
									value={customer.address}
									onChange={(e) => onCustomerChange('address', e.target.value)}
									placeholder="Ej: Avda. España"
									InputProps={{
										startAdornment: (
											<InputAdornment position="start">
												<LocationOnOutlinedIcon sx={{ fontSize: 18, color: 'var(--store-muted)' }} />
											</InputAdornment>
										),
									}}
								/>
								{/* Geolocalización */}
								<div style={{ display: 'grid', gap: 10 }}>
									<Button
										variant="outlined"
										size="small"
										startIcon={geoStatus === 'loading'
											? <CircularProgress size={14} color="inherit" />
											: <GpsFixedRoundedIcon />}
										onClick={handleRequestGeo}
										disabled={geoStatus === 'loading'}
										sx={{
											borderRadius: 2, fontSize: 13, fontWeight: 700,
											borderColor: geoStatus === 'ok'
												? 'var(--store-success)'
												: 'color-mix(in srgb, var(--store-primary) 40%, transparent)',
											color: geoStatus === 'ok' ? 'var(--store-success)' : 'var(--store-primary)',
											justifyContent: 'flex-start',
										}}
									>
										{geoStatus === 'ok'
											? 'Ubicación detectada'
											: geoStatus === 'loading'
											? 'Detectando ubicación...'
											: 'Usar mi ubicación actual'}
									</Button>
									{geoStatus === 'ok' && geo && (
										<>
											<div style={{
												display: 'flex', alignItems: 'center', justifyContent: 'space-between',
												padding: '7px 12px', borderRadius: 8,
												background: 'color-mix(in srgb, var(--store-primary) 8%, #fff)',
												border: '1px solid color-mix(in srgb, var(--store-primary) 18%, transparent)',
											}}>
												<Typography variant="caption" sx={{ color: 'success.dark', display: 'flex', alignItems: 'center', gap: 0.5, fontWeight: 700 }}>
													<CheckCircleOutlineRoundedIcon sx={{ fontSize: 14 }} />
													{geo.lat.toFixed(5)}, {geo.lng.toFixed(5)}
												</Typography>
												<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
													<Typography variant="caption" sx={{ color: 'var(--store-muted)', fontStyle: 'italic' }}>
														Arrastrá el pin para ajustar
													</Typography>
													<IconButton
														size="small"
														title="Ver mapa en grande"
														onClick={() => setGeoDialogOpen(true)}
														sx={{ color: 'var(--store-primary)', p: 0.5 }}
													>
														<OpenInFullRoundedIcon sx={{ fontSize: 15 }} />
													</IconButton>
												</div>
											</div>
											<GeoMap
												lat={geo.lat}
												lng={geo.lng}
												onMove={(coords) => {
													setGeo(coords);
													onGeoChange?.(coords);
												}}
											/>

											{/* Dialog pantalla grande */}
											<Dialog
												open={geoDialogOpen}
												onClose={() => setGeoDialogOpen(false)}
												maxWidth="md"
												fullWidth
												PaperProps={{ sx: { borderRadius: 3, overflow: 'hidden' } }}
											>
												<DialogTitle sx={{
													display: 'flex', alignItems: 'center', justifyContent: 'space-between',
													pb: 1, fontWeight: 800, fontSize: 16,
												}}>
													<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
														<GpsFixedRoundedIcon sx={{ fontSize: 18, color: 'var(--store-primary)' }} />
														Ajustá tu ubicación
													</span>
													<div>
														<Typography variant="caption" sx={{ color: 'text.secondary', mr: 1.5, fontStyle: 'italic' }}>
															{geo.lat.toFixed(5)}, {geo.lng.toFixed(5)}
														</Typography>
														<IconButton size="small" onClick={() => setGeoDialogOpen(false)}>
															<CloseRoundedIcon />
														</IconButton>
													</div>
												</DialogTitle>
												<DialogContent sx={{ p: 0 }}>
													<GeoMap
														lat={geo.lat}
														lng={geo.lng}
														height={520}
														onMove={(coords) => {
															setGeo(coords);
															onGeoChange?.(coords);
														}}
													/>
												</DialogContent>
											</Dialog>
										</>
									)}
									{geoStatus === 'error' && (
										<Typography variant="caption" sx={{ color: 'var(--store-danger)' }}>
											{geoError}
										</Typography>
									)}
								</div>
							</CheckoutFields>
						</CheckoutPanel>
						)}
					</CheckoutLeftColumn>
					)}

					{(showStep(2) || showStep(3)) && (
					<CheckoutRightColumn>
						{showStep(2) && (
						<CheckoutMethodGrid>
							<CheckoutPanel>
								<CheckoutSectionTitle>
									<LocalShippingOutlinedIcon fontSize="small" />
									Método de entrega
								</CheckoutSectionTitle>
								<CheckoutChoiceList>
									{deliveryMethods.map((method) => (
										<CheckoutRadioRow key={method.id}>
											<input
												type="radio"
												checked={effectiveDeliveryMethodId === method.id}
												onChange={() => onSetDeliveryMethod(method.id)}
											/>
											<span>
												<strong>{method.name}</strong>
												<small>{method.cost > 0 ? formatPrice(method.cost) : 'Sin costo'}</small>
											</span>
										</CheckoutRadioRow>
									))}
								</CheckoutChoiceList>
							</CheckoutPanel>

							<CheckoutPanel>
								<CheckoutSectionTitle>
									<CreditCardRoundedIcon fontSize="small" />
									Método de pago
								</CheckoutSectionTitle>
								<CheckoutChoiceList>
									{paymentMethods.map((method) => (
										<CheckoutRadioRow key={method.id}>
											<input
												type="radio"
												checked={effectivePaymentMethodId === method.id}
												onChange={() => onSetPaymentMethod(method.id)}
											/>
											<span>
												<strong>{method.name}</strong>
												<small>
													{method.type === 'online'
														? 'Pago online'
														: 'Pago pendiente de confirmación manual'}
													{method.discountPercent > 0 ? ` · ${method.discountPercent}% de descuento` : ''}
												</small>
											</span>
										</CheckoutRadioRow>
									))}
								</CheckoutChoiceList>
								{/* Con un medio manual el pedido NO espera ninguna aprobación de pago, así que
								    el cartel de "pedido protegido" prometía algo que no pasa. Se muestra el
								    texto que corresponde a lo que el cliente eligió. */}
								<PaymentBox>
									<LockRoundedIcon />
									<div>
										{selectedPaymentMethod?.type === 'online' ? (
											<>
												<strong>Pedido protegido</strong>
												<span>El pedido se confirma después del pago aprobado.</span>
											</>
										) : (
											<>
												<strong>Pago a coordinar</strong>
												<span>
													Registramos tu pedido y te contactamos para coordinar el pago
													{selectedPaymentMethod?.name ? ` por ${selectedPaymentMethod.name.toLowerCase()}` : ''}.
													{selectedDeliveryMethod?.type === 'pickup'
														? ' Lo retirás en el local.'
														: ''}
												</span>
											</>
										)}
									</div>
								</PaymentBox>
							</CheckoutPanel>
						</CheckoutMethodGrid>
						)}

						{showStep(3) && (
						<>
						<CheckoutPanel>
							<CheckoutSectionTitle>
								<ShoppingCartRoundedIcon fontSize="small" />
								Carrito de compras
							</CheckoutSectionTitle>
							<CheckoutCartTable>
								<CheckoutCartHead>
									<span>Imagen</span>
									<span>Producto</span>
									<span>Cantidad</span>
									<span>Unitario</span>
									<span>Total</span>
								</CheckoutCartHead>
								{cartItems.map((item) => (
									<CheckoutCartRow key={item.id}>
										<img
											src={storeImageSrc(item.image, item.name)}
											alt={item.name}
										/>
										<strong>{item.name}</strong>
										<QtyControl>
											<IconButton
												size="small"
												onClick={() => onUpdateQuantity(item.id, -1)}
											>
												<RemoveIcon fontSize="small" />
											</IconButton>
											<span>{item.quantity}</span>
											<IconButton
												size="small"
												onClick={() => onUpdateQuantity(item.id, 1)}
											>
												<AddIcon fontSize="small" />
											</IconButton>
										</QtyControl>
										<span>{formatPrice(item.price)}</span>
										<b>{formatPrice(item.quantity * item.price)}</b>
									</CheckoutCartRow>
								))}
								<CheckoutOrderTotals>
									<div>
										<span>Subtotal</span>
										<strong>{formatPrice(cartTotal)}</strong>
									</div>
									<div>
										<span>{selectedDeliveryMethod?.name ?? (effectiveDeliveryType === 'delivery' ? 'Delivery' : 'Retiro')}</span>
										<strong>{deliveryCost ? formatPrice(deliveryCost) : 'Sin costo'}</strong>
									</div>
									{paymentDiscount > 0 && (
										<div>
											<span>Descuento por medio de pago</span>
											<strong>-{formatPrice(paymentDiscount)}</strong>
										</div>
									)}
									<div>
										<span>Total</span>
										<strong>{formatPrice(checkoutTotal)}</strong>
									</div>
								</CheckoutOrderTotals>
							</CheckoutCartTable>
						</CheckoutPanel>

						<CheckoutPanel>
							<CheckoutSectionTitle>
								<span>4</span>
								Comentarios del pedido
							</CheckoutSectionTitle>
							{/* Textarea nativo, no TextField de MUI: ver CheckoutNotesField en styles.ts. */}
							<CheckoutNotesField>
								<span>Indicaciones para entrega, horario o referencias</span>
								<textarea
									rows={4}
									maxLength={1000}
									value={comentarios}
									onChange={(e) => onComentariosChange(e.target.value.slice(0, 1000))}
									placeholder="Ej: dejar en portería, timbre 3. Entregar después de las 14:00."
								/>
								<small>{comentarios.length}/1000</small>
							</CheckoutNotesField>
							{config.checkout.requireTermsAcceptance && (
								<TermsCheck>
									<input
										type="checkbox"
										checked={acceptTerms}
										onChange={(event) => onSetAcceptTerms(event.target.checked)}
									/>
									<span>
										Acepto los{' '}
										<button type="button" onClick={() => onOpenContentPage('terminos')}>
											términos y condiciones
										</button>
										{', '}
										<button type="button" onClick={() => onOpenContentPage('privacidad')}>
											política de privacidad
										</button>
										{' '}y demás políticas del comercio.
									</span>
								</TermsCheck>
							)}
							{datosFaltantes.length > 0 && (
								<Alert
									severity="info"
									variant="outlined"
									sx={{ borderRadius: 2.5, mb: 1.5, fontSize: 13 }}
								>
									Para confirmar el pedido falta {datosFaltantes.join(', ')}.
									{stepsMode && ' Podés volver a los pasos anteriores con el botón Atrás.'}
								</Alert>
							)}
							{/* Un error del pedido (p. ej. el pago online que no arrancó) salía 8 s en un
							    snackbar al pie, lejos del botón: si no se veía, el comprador volvía a
							    tocar y generaba otro pedido cancelado. Queda fijo acá hasta que lo cierre
							    o cambie algo. */}
							{checkoutError && (
								<Alert
									ref={errorRef}
									severity="error"
									onClose={onClearCheckoutError}
									sx={{ borderRadius: 2.5, mb: 1.5 }}
								>
									<strong>No pudimos confirmar el pedido.</strong> {checkoutError}
									<br />
									Revisá los datos y volvé a intentar, o elegí otro medio de pago (transferencia o
									contra entrega).
								</Alert>
							)}
							<CheckoutConfirmActions>
								<Button
									variant="outlined"
									startIcon={<ArrowBackRoundedIcon />}
									onClick={() => onSetCheckoutStage('auth')}
								>
									Cambiar acceso
								</Button>
								<Button
									variant="contained"
									size="large"
									startIcon={<LockRoundedIcon />}
									disabled={datosFaltantes.length > 0 || checkoutSubmitting}
									onClick={onConfirm}
								>
									{checkoutSubmitting ? 'Procesando...' : textoConfirmar}
								</Button>
							</CheckoutConfirmActions>


						</CheckoutPanel>
						</>
						)}
					</CheckoutRightColumn>
					)}

					{stepsMode && step < TOTAL_STEPS && (
						<CheckoutStepNav>
							<Button variant="text" disabled={step === 1} onClick={() => setStep((n) => n - 1)}>
								Atrás
							</Button>
							<Button variant="contained" onClick={() => setStep((n) => Math.min(n + 1, TOTAL_STEPS))}>
								Siguiente
							</Button>
						</CheckoutStepNav>
					)}
				</CheckoutWorkLayout>
				</>
			)}
		<Backdrop
			open={checkoutSubmitting}
			sx={{ zIndex: 9999, flexDirection: 'column', gap: 2, backgroundColor: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(4px)' }}
		>
			<CircularProgress size={52} sx={{ color: '#fff' }} />
			<Box sx={{ color: '#fff', fontWeight: 600, fontSize: 16, letterSpacing: 0.2 }}>
				Procesando pedido...
			</Box>
		</Backdrop>
	</CheckoutPage>
	);
}
