"use client";
import React, { useState } from "react";
import style from "./StepEngine.module.css";
import { useRouter } from "next/navigation";
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import QuestionCard from "../QuestionCard/QuestionCard";
import QuestionInput from "../QuestionCard/QuestionInput";
import { useSessionStore } from "@core/Store/Sesion.Store";
import ReactAvatar from "react-avatar";
import API from "@services/Api.Service";
import dayjs from "dayjs";
import "dayjs/locale/es";
import weekday from "dayjs/plugin/weekday";

dayjs.extend(weekday);
dayjs.locale("es");

import categories from "@models/Categories.type";
import OnboardingPhone from "../OnboardingPhone/OnboardingPhone";
import OnboardingLocation, { OnboardingLocationData } from "../OnboardingLocation/OnboardingLocation";
import SelectLocationMap from "@core/app/components/SelectLocationMap/SelectLocationMap";
import { validatePhone } from "@core/helpers/validatePhone";

interface StepEngineProps {
    flowId: string;
    action?: string | null;
    initialCompanyId?: string | null;
    initialEmployeeId?: string | null;
}

export default function StepEngine({ flowId, action, initialCompanyId, initialEmployeeId }: StepEngineProps) {
    const router = useRouter();
    const SessionInfo = useSessionStore();
    const [currentStepIndex, setCurrentStepIndex] = useState(0);
    const [imageError, setImageError] = useState(false);

    // State for the organization flow
    const [orgName, setOrgName] = useState("");
    const [isCheckingName, setIsCheckingName] = useState(false);
    const [nameError, setNameError] = useState("");
    const [categoryId, setCategoryId] = useState<number | null>(null);
    const [orgDescription, setOrgDescription] = useState("");
    const [isCreating, setIsCreating] = useState(false);
    const [createdCompanyId, setCreatedCompanyId] = useState<string | null>(null);

    // State for Location
    const [street, setStreet] = useState("");
    const [streetNumber, setStreetNumber] = useState("");
    const [builingFloor, setBuilingFloor] = useState("");
    const [buildingApartament, setBuildingApartament] = useState("");
    const [state, setState] = useState("");
    const [city, setCity] = useState("");
    const [block, setBlock] = useState("");
    const [zipCode, setZipCode] = useState("");
    const [latitude, setLatitude] = useState<number>(-34.6037);
    const [longitude, setLongitude] = useState<number>(-58.3816);
    
    // State for Contact
    const [phoneAreaCode, setPhoneAreaCode] = useState("");
    const [phoneNumber, setPhoneNumber] = useState("");

    // State for Rules
    const [heatMapFraction, setHeatMapFraction] = useState<number>(60);
    const [appointmentTime, setAppointmentTime] = useState<number>(24);
    const [cancellationTime, setCancellationTime] = useState<number>(12);

    // State for Service Flow
    const [serviceName, setServiceName] = useState("");
    const [serviceDescription, setServiceDescription] = useState("");
    const [serviceLength, setServiceLength] = useState<number | null>(null);
    const [servicePrice, setServicePrice] = useState<number | string>("");
    const [serviceLimit, setServiceLimit] = useState<number>(1);
    const [serviceImage, setServiceImage] = useState<File | null>(null);
    const [createdServiceId, setCreatedServiceId] = useState<string | null>(null);
    const [employeeId, setEmployeeId] = useState<string | null>(null);
    const [doesProvideServices, setDoesProvideServices] = useState<boolean | null>(null);

    // State for Schedule Flow
    const [workingDaysMode, setWorkingDaysMode] = useState<string>(""); // "mon-fri", "mon-sat", "mon-sun", "custom"
    const [openTime, setOpenTime] = useState<string>("09:00");
    const [closeTime, setCloseTime] = useState<string>("18:00");
    const [hasBreak, setHasBreak] = useState<boolean | null>(null);
    const [breakStart, setBreakStart] = useState<string>("13:00");
    const [breakEnd, setBreakEnd] = useState<string>("14:00");

    // State for Custom Schedules
    const [customDays, setCustomDays] = useState<number[]>([]); 
    const [unifiedCustomSchedule, setUnifiedCustomSchedule] = useState<boolean | null>(null);
    const [customSchedulesMap, setCustomSchedulesMap] = useState<Record<number, {openTime: string, closeTime: string, hasBreak: boolean, breakStart: string, breakEnd: string}>>({});


    const [isSuccess, setIsSuccess] = useState<boolean>(false);
    const [isAddingAnotherService, setIsAddingAnotherService] = useState<boolean>(false);

    const [isResuming, setIsResuming] = useState(false);

    const [headerImage, setHeaderImage] = useState<File | null>(null);
    const [headerColor, setHeaderColor] = useState<string>("#250525");
    const [headerFontColor, setHeaderFontColor] = useState<string>("#FFFFFF");

    const [previewServices, setPreviewServices] = useState<any[]>([]);

    // State for standalone update schedule flow
    const [scheduleScope, setScheduleScope] = useState<"me" | "specific" | "all" | null>(null);
    const [targetEmployeeId, setTargetEmployeeId] = useState<string | null>(null);
    const [allEmployees, setAllEmployees] = useState<any[]>([]);
    const [overrideDate, setOverrideDate] = useState<string>("");
    const [allOrganizations, setAllOrganizations] = useState<any[]>([]);
    const [disableStartDate, setDisableStartDate] = useState<string>("");
    const [disableEndDate, setDisableEndDate] = useState<string>("");
    const [disableDuration, setDisableDuration] = useState<string>("");
    const [isFullDayDisabled, setIsFullDayDisabled] = useState<boolean>(true);
    const [disableStartTime, setDisableStartTime] = useState<string>("");
    const [disableEndTime, setDisableEndTime] = useState<string>("");

    // State for New Collaborator Flow
    const [inviteEmail, setInviteEmail] = useState("");
    const [inviteCollaborator, setInviteCollaborator] = useState<any | null>(null);
    const [inviteEmailError, setInviteEmailError] = useState("");
    const [inviteRole, setInviteRole] = useState<"admin" | "colaborador">("colaborador");
    const [isSearchingEmail, setIsSearchingEmail] = useState(false);
    const [isUpgradeRequired, setIsUpgradeRequired] = useState(false);

    // State for Setup Collaborator Flow
    const [collaboratorToSetup, setCollaboratorToSetup] = useState<any | null>(null);
    const [setupMissingServices, setSetupMissingServices] = useState(false);
    const [setupMissingSchedules, setSetupMissingSchedules] = useState(false);
    const [setupSelectedServices, setSetupSelectedServices] = useState<string[]>([]);
    const [setupAvailableServices, setSetupAvailableServices] = useState<any[]>([]);

    const loadOrganizationContext = (org: any) => {
        setCreatedCompanyId(org.id || org._id);
        setOrgName(org.name || "");
        setCategoryId(org.categoryId || null);
        setOrgDescription(org.description || "");
        setStreet(org.street || "");
        setStreetNumber(org.streetNumber || "");
        setBuilingFloor(org.builingFloor || "");
        setBuildingApartament(org.buildingApartament || "");
        setState(org.state || "");
        setCity(org.city || "");
        setBlock(org.block || "");
        setZipCode(org.zipCode || "");
        setLatitude(org.latitude || -34.6037);
        setLongitude(org.longitude || -58.3816);
        setPhoneAreaCode(org.phoneAreaCode || "");
        setPhoneNumber(org.phoneNumber || "");
        setHeatMapFraction(org.heatMapFraction || 60);
        setAppointmentTime(org.appointmentTime || 24);
        setCancellationTime(org.cancellationTime || 12);
        if (org.headerColor) setHeaderColor(org.headerColor);
        if (org.headerFontColor) setHeaderFontColor(org.headerFontColor);
        
        if (flowId === "onboarding-org") {
            if (action === "edit-location") {
                setCurrentStepIndex(4);
            } else if (action === "edit-contact") {
                setCurrentStepIndex(6);
            } else if (action === "edit-appearance") {
                setCurrentStepIndex(8);
            } else if (org.onboardingStep !== undefined && org.onboardingStep > 0) {
                setCurrentStepIndex(org.onboardingStep);
            } else {
                const isNameMissing = !org.name || org.name.trim() === "";
                const isCategoryMissing = !org.categoryId;
                const isDescriptionMissing = !org.description || org.description.trim() === "";
                const isRulesMissing = !org.heatMapFraction;
                const isLocationMissing = !org.street || org.street.trim() === "";
                const isContactMissing = !org.phoneNumber || org.phoneNumber.trim() === "";
                const isHeaderMissing = !org.headerFile || org.headerFile === "";

                if (isNameMissing) {
                    setCurrentStepIndex(1);
                } else if (isCategoryMissing) {
                    setCurrentStepIndex(2);
                } else if (isDescriptionMissing) {
                    setCurrentStepIndex(3);
                } else if (isLocationMissing) {
                    setCurrentStepIndex(4);
                } else if (isContactMissing) {
                    setCurrentStepIndex(6);
                } else if (isRulesMissing) {
                    setCurrentStepIndex(7);
                } else if (isHeaderMissing) {
                    setCurrentStepIndex(8);
                } else {
                    setCurrentStepIndex(9);
                }
            }
        } else if (flowId === "onboarding-service") {
            if (!action) {
                API.post<any[]>("services/get-by-company", { companyId: org.id || org._id })
                    .then(servRes => {
                        if (servRes && servRes.length > 0) {
                            router.replace("/admin/assistant?flow=onboarding-schedule");
                        }
                    }).catch(console.error);
            }
        } else if (flowId === "onboarding-schedule") {
            API.post<any[]>("services/get-by-company", { companyId: org.id || org._id })
                .then(res => {
                    if (res && res.length > 0) setPreviewServices(res);
                }).catch(console.error);

            API.post<any[]>("employees/get-by-company", { companyId: org.id || org._id })
                .then(empRes => {
                    if (empRes && empRes.length > 0) {
                        const foundEmployeeId = empRes[0].id || empRes[0]._id || empRes[0].employeeId;
                        setEmployeeId(foundEmployeeId);
                        API.post<any>("schedules/get-all-by-collaborator", { 
                            companyId: org.id || org._id, 
                            employeeId: foundEmployeeId 
                        }).then(schedRes => {
                            // Pre-fill logic could go here
                        }).catch(console.error);
                    }
                }).catch(console.error);
        } else if (flowId === "update-schedule" || flowId === "override-schedule" || flowId === "disable-schedule") {
            API.post<any[]>("employees/get-by-company", { companyId: org.id || org._id })
                .then(empRes => {
                    if (empRes && empRes.length > 0) {
                        setAllEmployees(empRes);
                        const me = empRes.find((e: any) => {
                            const eUserId = e.userId?._id || e.userId?.id || e.userId;
                            return String(eUserId) === String(SessionInfo.userId);
                        });
                        if (me) {
                            setEmployeeId(me.id || me._id || me.employeeId);
                        }
                    }
                }).catch(console.error);
        } else if (flowId === "new-collaborator") {
            setCurrentStepIndex(1);
        } else if (flowId === "setup-collaborator") {
            setCurrentStepIndex(0);
            if (initialEmployeeId) {
                setEmployeeId(initialEmployeeId);
                API.post<any[]>("employees/get-incomplete-setup", { sessionUser: SessionInfo.userId })
                    .then(res => {
                        if (res && res.length > 0) {
                            const collab = res.find(c => c.employeeId === initialEmployeeId);
                            if (collab) {
                                setCollaboratorToSetup(collab);
                                setSetupMissingServices(collab.missingServices);
                                setSetupMissingSchedules(collab.missingSchedules);
                            }
                        }
                    }).catch(console.error);
                
                API.post<any[]>("services/get-by-company", { companyId: org.id || org._id })
                    .then(res => {
                        if (res && res.length > 0) {
                            setSetupAvailableServices(res);
                        }
                    }).catch(console.error);
            }
        }
    };

    React.useEffect(() => {
        if (flowId === "new-collaborator" || flowId === "setup-collaborator" || flowId.startsWith("onboarding") || flowId === "update-schedule" || flowId === "override-schedule" || flowId === "disable-schedule") {
            setIsResuming(true);
            API.post<any[]>("companies/get-by-user", { sessionUser: SessionInfo.userId })
                .then(response => {
                    const orgs = response || [];
                    if (orgs.length > 0) {
                        setAllOrganizations(orgs);
                        if (initialCompanyId) {
                            const targetOrg = orgs.find((o: any) => (o.id || o._id) === initialCompanyId);
                            if (targetOrg) {
                                loadOrganizationContext(targetOrg);
                            }
                        } else if (orgs.length === 1 && action !== "new-org") {
                            loadOrganizationContext(orgs[0]);
                        }
                    }
                })
                .catch(console.error)
                .finally(() => setIsResuming(false));
        }
        
        if (flowId === "onboarding-service" || flowId === "onboarding-schedule" || flowId === "setup-collaborator" || (flowId === "onboarding-org" && action === "new-org")) {
            setCurrentStepIndex(0);
        }
    }, [flowId, SessionInfo.metrics.organizationsCount, SessionInfo.userId, router]);

    const handleBack = () => {
        let minStepIndex = 0;
        if (flowId === "onboarding-org" && action) {
            if (action === "edit-location") minStepIndex = 4;
            else if (action === "edit-contact") minStepIndex = 6;
            else if (action === "edit-appearance") minStepIndex = 8;
        }

        if (currentStepIndex > minStepIndex) {
            setCurrentStepIndex(currentStepIndex - 1);
        } else {
            router.push("/admin/assistant");
        }
    };

    const handleNext = () => {
        setCurrentStepIndex(prev => prev + 1);
    };

    const handleActionSuccess = () => {
        setIsSuccess(true);
    };

    const proceedNext = () => {
        if (action) {
            handleActionSuccess();
        } else {
            handleNext();
        }
    };

    const handleNextName = async () => {
        if (orgName.trim().length < 3 || isCheckingName) return;
        
        setIsCheckingName(true);
        setNameError("");
        try {
            const response = await API.post<{ valid: boolean }>("companies/check-name", { name: orgName });
            if (response.valid) {
                handleNext();
            } else {
                setNameError("Este nombre ya existe, intenta con otro.");
            }
        } catch (error) {
            setNameError("Error al verificar el nombre.");
        } finally {
            setIsCheckingName(false);
        }
    };

    const handleCreateCompany = async () => {
        if (!orgName) {
            alert("Error: Falta el nombre de la organización.");
            return;
        }
        if (!categoryId) {
            alert("Error: Falta la categoría. Serás redirigido al paso anterior.");
            setCurrentStepIndex(2);
            return;
        }
        if (!orgDescription || orgDescription.trim().length < 10) {
            alert("Error: La descripción debe tener al menos 10 caracteres.");
            return;
        }
        if (isCreating) return;
        
        setIsCreating(true);
        try {
            if (createdCompanyId) {
                // Update existing instead of creating a new one
                await API.post<any>("companies/update", {
                    id: createdCompanyId,
                    name: orgName,
                    categoryId: categoryId,
                    description: orgDescription,
                    onboardingStep: currentStepIndex + 1,
                    sessionUser: SessionInfo.userId
                });
                console.log("API.post update succeeded!");
            } else {
                const company = await API.post<any>("companies/create", {
                    name: orgName,
                    categoryId: categoryId,
                    description: orgDescription,
                    onboardingStep: currentStepIndex + 1,
                    ownerId: SessionInfo.userId
                });
                console.log("API.post create succeeded!", company);
                const newCompanyId = company?.id || company?._id;
                if (newCompanyId) {
                    setCreatedCompanyId(newCompanyId);
                } else {
                    console.error("No se pudo obtener el ID de la organización creada", company);
                }
            }
            handleNext(); // Move to Step 4 (Location)
        } catch (error: any) {
            console.error("Error creando compañía:", error);
            alert(error?.message || "Hubo un error al guardar. Intenta nuevamente.");
        } finally {
            setIsCreating(false);
            console.log("handleCreateCompany finished");
        }
    };

    const handleUpdateLocation = async () => {
        if (!createdCompanyId) {
            alert("Error: No se encontró el ID de la organización. Por favor recarga la página e intenta continuar.");
            return;
        }
        if (!street) {
            alert("Error: Falta ingresar la calle.");
            return;
        }
        if (!streetNumber) {
            alert("Error: Falta ingresar el número.");
            return;
        }
        if (!state || !city || !block) {
            alert("Error: Provincia, Partido y Localidad son obligatorios.");
            return;
        }
        if (isCreating) return;
        
        setIsCreating(true);
        try {
            await API.post<any>("companies/update", {
                id: createdCompanyId,
                street: street,
                streetNumber: streetNumber,
                builingFloor: builingFloor,
                buildingApartament: buildingApartament,
                state: state,
                city: city,
                block: block,
                zipCode: zipCode,
                latitude: latitude,
                longitude: longitude,
                onboardingStep: action ? undefined : currentStepIndex + 1,
                sessionUser: SessionInfo.userId
            });
            proceedNext(); // Move to Step 5 (Contact)
        } catch (error: any) {
            console.error("Error actualizando ubicación:", error);
            alert(error?.message || "Hubo un error al guardar la ubicación.");
        } finally {
            setIsCreating(false);
        }
    };

    const handleUpdateContact = async () => {
        if (!createdCompanyId) {
            alert("Error: No se encontró el ID de la organización. Por favor recarga la página.");
            return;
        }
        if (!phoneNumber) {
            alert("Error: Falta ingresar el número de teléfono.");
            return;
        }
        if (isCreating) return;
        
        setIsCreating(true);
        try {
            await API.post<any>("companies/update", {
                id: createdCompanyId,
                phoneAreaCode: phoneAreaCode,
                phoneNumber: phoneNumber,
                sessionUser: SessionInfo.userId
            });
            handleNext(); // Move to Step 6 (Rules)
        } catch (error: any) {
            console.error("Error actualizando contacto:", error);
            alert(error?.message || "Hubo un error al guardar el contacto.");
        } finally {
            setIsCreating(false);
        }
    };

    const handleUpdateRules = async () => {
        if (!createdCompanyId) {
            alert("Error: No se encontró el ID de la organización. Por favor recarga la página.");
            return;
        }
        if (isCreating) return;
        setIsCreating(true);
        try {
            await API.post<any>("companies/update", {
                id: createdCompanyId,
                heatMapFraction: heatMapFraction,
                appointmentTime: appointmentTime,
                cancellationTime: cancellationTime,
                sessionUser: SessionInfo.userId
            });
            handleNext(); // Move to Step 7 (Appearance)
        } catch (error: any) {
            console.error("Error actualizando reglas:", error);
            alert(error?.message || "Hubo un error al guardar las reglas del negocio.");
        } finally {
            setIsCreating(false);
        }
    };

    const handleUploadHeader = async () => {
        if (!createdCompanyId) {
            alert("Error: No se encontró el ID de la organización. Por favor recarga la página.");
            return;
        }
        setIsCreating(true);
        try {
            // Guardar colores de cabecera
            await API.post<any>("companies/update", {
                id: createdCompanyId,
                headerColor: headerColor,
                headerFontColor: headerFontColor,
                onboardingStep: currentStepIndex + 1,
                sessionUser: SessionInfo.userId
            });

            if (headerImage) {
                const formData = new FormData();
                formData.append("companyId", createdCompanyId);
                formData.append("sessionUser", SessionInfo.userId);
                formData.append("file", headerImage);
                await API.postFile<any>("companies/upload-header", formData);
            }
            
            // Finish Org Onboarding
            if (action) { handleActionSuccess(); } else { router.push("/admin/assistant?flow=onboarding-service"); }
        } catch (error: any) {
            console.error("Error actualizando apariencia:", error);
            alert(error?.message || "Hubo un error al guardar la configuración de apariencia.");
        } finally {
            setIsCreating(false);
        }
    };

    // Helper to allow Enter key to submit
    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, action: () => void) => {
        if (e.key === "Enter") {
            e.preventDefault();
            action();
        }
    };

    const renderOnboardingOrgFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title={`¡Bienvenido a TurnosXpress, ${SessionInfo.userFullName.split(" ")[0]}!`}
                    description="Vamos a configurar tu negocio en solo unos minutos. Relájate, yo te guiaré paso a paso para que todo quede perfecto."
                    onNext={handleNext}
                    nextLabel="Empezar ahora"
                    topAccessory={
                        SessionInfo.avatar && !imageError ? (
                            <img 
                                src={SessionInfo.avatar} 
                                alt="Avatar" 
                                style={{ width: 90, height: 90, borderRadius: '50%', objectFit: 'cover' }} 
                                onError={() => setImageError(true)}
                            />
                        ) : (
                            <ReactAvatar 
                                name={SessionInfo.userFullName || "Usuario"} 
                                size="90" 
                                round={true} 
                                textSizeRatio={2.5} 
                                maxInitials={2} 
                                color="#600018"
                            />
                        )
                    }
                >
                    {null}
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="1. Identidad de tu Negocio"
                    description="Para empezar, ¿cuál es el nombre de tu organización o emprendimiento?"
                    onNext={handleNextName}
                    disableNext={orgName.trim().length < 3 || isCheckingName}
                    nextLabel={isCheckingName ? "Validando..." : "Siguiente"}
                >
                    <QuestionInput 
                        placeholder="Ej. Salón de Belleza VIP"
                        value={orgName}
                        onChange={(e) => {
                            setOrgName(e.target.value);
                            if (nameError) setNameError("");
                        }}
                        onKeyDown={(e) => {
                            if (orgName.trim().length >= 3) {
                                handleKeyDown(e, handleNextName);
                            }
                        }}
                        autoFocus
                        error={nameError}
                    />
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="2. ¿A qué te dedicas?"
                    description="Elige la categoría que mejor describa los servicios que ofreces."
                    onNext={handleNext}
                    disableNext={categoryId === null}
                >
                    <div className={style.categoryGrid}>
                        {categories.filter(c => c.id !== 0).map(cat => (
                            <div 
                                key={cat.id} 
                                className={`${style.categoryItem} ${categoryId === cat.id ? style.categorySelected : ''}`}
                                onClick={() => {
                                    setCategoryId(cat.id);
                                    setTimeout(handleNext, 400); 
                                }}
                            >
                                <div className={style.categoryIcon}>✧</div>
                                <div className={style.categoryName}>{cat.name}</div>
                            </div>
                        ))}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3}
                    title="3. Una breve descripción"
                    description={`Cuentanos un poco sobre "${orgName}". Esta descripción la verán tus clientes.`}
                    onNext={handleCreateCompany}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Creando..." : "Guardar Organización"}
                >
                    <QuestionInput 
                        placeholder="Ej. Ofrecemos los mejores cortes..."
                        value={orgDescription}
                        onChange={(e) => setOrgDescription(e.target.value)}
                        onKeyDown={(e) => {
                            if (orgDescription.trim().length >= 10) {
                                handleKeyDown(e, handleCreateCompany);
                            }
                        }}
                        autoFocus
                    />
                </QuestionCard>
                <QuestionCard 
                    isActive={currentStepIndex === 4}
                    title="4. Ubicación de tu Negocio"
                    description={`¿Dónde queda "${orgName}"? Esto es crucial para que tus clientes te encuentren.`}
                    onNext={handleUpdateLocation}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Guardando..." : (action ? "Guardar Cambios" : "Siguiente")}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
                        <OnboardingLocation 
                            data={{
                                street, streetNumber, builingFloor, buildingApartament, state, city, block, zipCode, latitude, longitude
                            }}
                            onChange={(newData) => {
                                if (newData.street !== undefined) setStreet(newData.street);
                                if (newData.streetNumber !== undefined) setStreetNumber(newData.streetNumber);
                                if (newData.builingFloor !== undefined) setBuilingFloor(newData.builingFloor);
                                if (newData.buildingApartament !== undefined) setBuildingApartament(newData.buildingApartament);
                                if (newData.state !== undefined) setState(newData.state);
                                if (newData.city !== undefined) setCity(newData.city);
                                if (newData.block !== undefined) setBlock(newData.block);
                                if (newData.zipCode !== undefined) setZipCode(newData.zipCode);
                                if (newData.latitude !== undefined) setLatitude(newData.latitude);
                                if (newData.longitude !== undefined) setLongitude(newData.longitude);
                            }}
                        />
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 5}
                    title="5. Ubica tu local en el mapa (Opcional)"
                    description={`Para que los clientes encuentren "${orgName}" con exactitud. Por favor, haz el máximo zoom posible y arrastra el marcador a tu ubicación exacta.`}
                    onNext={handleUpdateLocation}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Guardando..." : "Guardar Ubicación"}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
                        <div style={{ width: '100%', borderRadius: '8px', overflow: 'hidden' }}>
                            <SelectLocationMap 
                                initialCoordinates={{ latitude, longitude }}
                                height="350px"
                                onChange={(loc) => {
                                    setLatitude(loc.latitude);
                                    setLongitude(loc.longitude);
                                }}
                            />
                        </div>
                        <div 
                            style={{ 
                                marginTop: '10px', 
                                fontSize: '13px', 
                                color: 'rgba(255,255,255,0.6)', 
                                cursor: 'pointer',
                                textDecoration: 'underline'
                            }}
                            onClick={() => {
                                if (!isCreating) handleUpdateLocation();
                            }}
                        >
                            Omitir este paso
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 6}
                    title="6. Contacto"
                    description="¿Cómo pueden contactarte tus clientes? Ingresa el número de teléfono (preferiblemente WhatsApp)."
                    onNext={handleUpdateContact}
                    disableNext={!validatePhone(phoneAreaCode, phoneNumber).isValid || isCreating}
                    nextLabel={isCreating ? "Guardando..." : (action ? "Guardar Cambios" : "Siguiente")}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%', alignItems: 'center' }}>
                        <OnboardingPhone
                            value={phoneAreaCode + phoneNumber}
                            onChange={(area, num, full) => {
                                setPhoneAreaCode(area);
                                setPhoneNumber(num);
                            }}
                            onKeyDown={(e) => {
                                if (validatePhone(phoneAreaCode, phoneNumber).isValid) {
                                    handleKeyDown(e, handleUpdateContact);
                                }
                            }}
                        />
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 7}
                    title="7. Reglas de Negocio"
                    description="Configura los tiempos de tu agenda. Esto determinará cómo se muestran los turnos a tus clientes."
                    onNext={handleUpdateRules}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Guardando..." : "Siguiente: Crear Servicio"}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
                        <div>
                            <div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Fracción de la Agenda (Minutos)</div>
                            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                                {[15, 30, 45, 60, 120].map(val => (
                                    <div 
                                        key={val}
                                        onClick={() => setHeatMapFraction(val)}
                                        style={{ 
                                            padding: '8px 16px', 
                                            borderRadius: '8px', 
                                            cursor: 'pointer',
                                            background: heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                            border: `1px solid ${heatMapFraction === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                            color: 'white',
                                            fontWeight: heatMapFraction === val ? 'bold' : 'normal',
                                            transition: 'all 0.2s ease'
                                        }}
                                    >
                                        {val}m
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div>
                            <div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para reservar (Horas)</div>
                            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                                {[1, 2, 12, 24, 48].map(val => (
                                    <div 
                                        key={val}
                                        onClick={() => setAppointmentTime(val)}
                                        style={{ 
                                            padding: '8px 16px', 
                                            borderRadius: '8px', 
                                            cursor: 'pointer',
                                            background: appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                            border: `1px solid ${appointmentTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                            color: 'white',
                                            fontWeight: appointmentTime === val ? 'bold' : 'normal',
                                            transition: 'all 0.2s ease'
                                        }}
                                    >
                                        {val}h
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div>
                            <div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Anticipación mínima para cancelar (Horas)</div>
                            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                                {[1, 2, 12, 24, 48].map(val => (
                                    <div 
                                        key={val}
                                        onClick={() => setCancellationTime(val)}
                                        style={{ 
                                            padding: '8px 16px', 
                                            borderRadius: '8px', 
                                            cursor: 'pointer',
                                            background: cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                            border: `1px solid ${cancellationTime === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                            color: 'white',
                                            fontWeight: cancellationTime === val ? 'bold' : 'normal',
                                            transition: 'all 0.2s ease'
                                        }}
                                    >
                                        {val}h
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 8}
                    title="8. Apariencia"
                    description="Sube una foto de portada para tu negocio y elige tus colores corporativos. Esto es lo primero que verán tus clientes."
                    onNext={handleUploadHeader}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Guardando..." : (action ? "Guardar Cambios" : "Siguiente")}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
                        <div style={{
                            display: 'flex', gap: '20px', width: '100%', maxWidth: '500px', 
                            justifyContent: 'center', background: 'rgba(255,255,255,0.05)', 
                            padding: '15px', borderRadius: '12px'
                        }}>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
                                <label style={{ color: 'white', fontSize: '13px' }}>Color de Fondo</label>
                                <input 
                                    type="color" 
                                    value={headerColor} 
                                    onChange={(e) => setHeaderColor(e.target.value)} 
                                    style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
                                />
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '5px', flex: 1 }}>
                                <label style={{ color: 'white', fontSize: '13px' }}>Color del Texto</label>
                                <input 
                                    type="color" 
                                    value={headerFontColor} 
                                    onChange={(e) => setHeaderFontColor(e.target.value)} 
                                    style={{ width: '100%', height: '40px', border: 'none', borderRadius: '8px', cursor: 'pointer' }}
                                />
                            </div>
                        </div>

                        {/* PREVIEW BOX */}
                        <div style={{ width: '100%', maxWidth: '500px', marginTop: '10px' }}>
                            <div style={{ color: 'rgba(255,255,255,0.7)', fontSize: '13px', marginBottom: '8px', textAlign: 'left' }}>
                                Vista previa:
                            </div>
                            <div style={{
                                width: '100%', 
                                height: '120px', 
                                backgroundColor: headerColor, 
                                borderRadius: '12px',
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
                                position: 'relative',
                                overflow: 'hidden'
                            }}>
                                {headerImage && (
                                    <img 
                                        src={URL.createObjectURL(headerImage)} 
                                        style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.4 }} 
                                        alt="Preview" 
                                    />
                                )}
                                <div style={{ 
                                    color: headerFontColor, 
                                    fontSize: '24px', 
                                    fontWeight: 'bold', 
                                    position: 'relative',
                                    zIndex: 1,
                                    textShadow: '0 2px 4px rgba(0,0,0,0.5)'
                                }}>
                                    {orgName || "Tu Negocio"}
                                </div>
                                <div style={{
                                    color: headerFontColor,
                                    fontSize: '14px',
                                    position: 'relative',
                                    zIndex: 1,
                                    opacity: 0.9,
                                    marginTop: '5px'
                                }}>
                                    Categoría seleccionada
                                </div>
                            </div>
                        </div>

                        <label style={{
                            position: 'relative',
                            width: '100%',
                            maxWidth: '500px',
                            height: '200px',
                            border: '2px dashed rgba(255, 255, 255, 0.3)',
                            borderRadius: '12px',
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center',
                            overflow: 'hidden',
                            cursor: 'pointer',
                            background: headerImage ? 'transparent' : 'rgba(255,255,255,0.05)'
                        }}>
                            {headerImage ? (
                                <img 
                                    src={URL.createObjectURL(headerImage)} 
                                    alt="Preview" 
                                    style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                                />
                            ) : (
                                <span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
                            )}
                            <input 
                                type="file" 
                                accept="image/*" 
                                onChange={(e) => {
                                    if (e.target.files && e.target.files.length > 0) {
                                        setHeaderImage(e.target.files[0]);
                                    }
                                }}
                                style={{
                                    position: 'absolute',
                                    top: 0,
                                    left: 0,
                                    width: '100%',
                                    height: '100%',
                                    opacity: 0,
                                    cursor: 'pointer'
                                }}
                            />
                        </label>
                    </div>
                </QuestionCard>
            </>
        );
    };

    const handleCreateService = async () => {
        if (!createdCompanyId || !serviceName || !serviceDescription || !serviceLength || isCreating) return;
        setIsCreating(true);
        try {
            const service = await API.post<any>("services/create", {
                companyId: createdCompanyId,
                name: serviceName,
                description: serviceDescription,
                length: serviceLength,
                originalPrice: Number(servicePrice) || 0,
                limit: serviceLimit,
                sessionUser: SessionInfo.userId
            });
            if (service && service.id) {
                setCreatedServiceId(service.id);
            } else if (service && service._id) {
                setCreatedServiceId(service._id);
            }
            handleNext(); // Move to Step 4 (Service Image)
        } catch (error: any) {
            console.error("Error creando servicio:", error);
            alert(error?.message || "Hubo un error al guardar el servicio.");
        } finally {
            setIsCreating(false);
        }
    };

    const handleUploadServiceImage = async () => {
        if (!createdCompanyId || !createdServiceId) return;

        const finalizeService = () => {
            if (isAddingAnotherService) {
                setIsAddingAnotherService(false);
                setCurrentStepIndex(5); // Return to summary step in schedule flow
                // Reload preview services
                API.post<any[]>("services/get-by-company", { companyId: createdCompanyId })
                    .then(res => {
                        setPreviewServices(res || []);
                    });
            } else if (action) {
                handleActionSuccess();
            } else {
                router.push("/admin/assistant?flow=onboarding-schedule");
            }
        };

        if (!serviceImage) {
            // Skip image upload if none provided
            finalizeService();
            return;
        }

        setIsCreating(true);
        try {
            const formData = new FormData();
            formData.append("companyId", createdCompanyId);
            formData.append("serviceId", createdServiceId);
            formData.append("sessionUser", SessionInfo.userId);
            formData.append("file", serviceImage);

            await API.postFile<any>("services/upload-image", formData);
            finalizeService();
        } catch (error: any) {
            console.error("Error subiendo imagen del servicio:", error);
            alert(error?.message || "Hubo un error al subir la imagen. Puedes intentarlo más tarde desde tu panel.");
        } finally {
            setIsCreating(false);
        }
    };

    const renderOnboardingServiceFlow = () => {
        const fraction = heatMapFraction || 60;
        const durationOptions = [fraction, fraction * 2, fraction * 3, fraction * 4];

        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title="Configura tus Servicios"
                    description="Ya creaste tu negocio. Ahora necesitas configurar al menos un servicio para que tus clientes puedan empezar a reservar."
                    onNext={handleNext}
                    nextLabel="Comenzar"
                >
                    <div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
                        Vamos a crear el primer servicio de tu negocio. ¡Es muy fácil!
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="1. Nombre y Descripción"
                    description="Elige un nombre atractivo y describe de qué trata el servicio."
                    onNext={handleNext}
                    disableNext={serviceName.trim().length < 3 || serviceDescription.trim().length < 5}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
                        <QuestionInput 
                            placeholder="Ej. Corte clásico con lavado"
                            value={serviceName}
                            onChange={(e) => setServiceName(e.target.value)}
                            autoFocus
                        />
                        <QuestionInput 
                            placeholder="Breve descripción del servicio..."
                            value={serviceDescription}
                            onChange={(e) => setServiceDescription(e.target.value)}
                            onKeyDown={(e) => {
                                if (serviceName.trim().length >= 3 && serviceDescription.trim().length >= 5) {
                                    handleKeyDown(e, handleNext);
                                }
                            }}
                        />
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="2. Duración del Servicio"
                    description={`Elige cuánto tiempo tomará. Las opciones están basadas en tu fracción de agenda (${fraction} min).`}
                    onNext={handleNext}
                    disableNext={!serviceLength}
                >
                    <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
                        {durationOptions.map(val => {
                            const hours = Math.floor(val / 60);
                            const minutes = val % 60;
                            const label = hours > 0 
                                ? `${hours}h ${minutes > 0 ? minutes + 'm' : ''}`.trim()
                                : `${minutes} min`;

                            return (
                                <div 
                                    key={val}
                                    onClick={() => setServiceLength(val)}
                                    style={{ 
                                        padding: '12px 24px', 
                                        borderRadius: '12px', 
                                        cursor: 'pointer',
                                        background: serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                        border: `2px solid ${serviceLength === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
                                        color: 'white',
                                        fontWeight: serviceLength === val ? 'bold' : 'normal',
                                        transition: 'all 0.2s ease',
                                        fontSize: '16px'
                                    }}
                                >
                                    {label}
                                </div>
                            );
                        })}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3}
                    title="3. Precio y Cupos"
                    description="¿Cuánto cuesta y a cuántas personas puedes atender a la vez en este servicio?"
                    onNext={handleCreateService}
                    disableNext={isCreating || !servicePrice}
                    nextLabel={isCreating ? "Guardando..." : "Crear Servicio"}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%' }}>
                        <div>
                            <div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Precio Original</div>
                            <div style={{ position: 'relative' }}>
                                <span style={{ position: 'absolute', left: '15px', top: '50%', transform: 'translateY(-50%)', color: 'white', fontSize: '18px' }}>$</span>
                                <input 
                                    type="number"
                                    placeholder="0.00"
                                    value={servicePrice}
                                    onChange={(e) => setServicePrice(e.target.value)}
                                    style={{
                                        width: '100%',
                                        padding: '15px 15px 15px 35px',
                                        borderRadius: '12px',
                                        border: '1px solid rgba(255,255,255,0.2)',
                                        background: 'rgba(255,255,255,0.05)',
                                        color: 'white',
                                        fontSize: '18px',
                                        outline: 'none'
                                    }}
                                />
                            </div>
                        </div>

                        <div>
                            <div style={{ color: 'white', marginBottom: '10px', fontSize: '14px' }}>Cupos Simultáneos (Por defecto 1)</div>
                            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                                {[1, 2, 3, 5, 10].map(val => (
                                    <div 
                                        key={val}
                                        onClick={() => setServiceLimit(val)}
                                        style={{ 
                                            padding: '8px 16px', 
                                            borderRadius: '8px', 
                                            cursor: 'pointer',
                                            background: serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                            border: `1px solid ${serviceLimit === val ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                            color: 'white',
                                            fontWeight: serviceLimit === val ? 'bold' : 'normal',
                                            transition: 'all 0.2s ease'
                                        }}
                                    >
                                        {val}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 4}
                    title="4. Imagen del Servicio"
                    description="Sube una foto representativa para que los clientes sepan qué ofreces. (Opcional)"
                    onNext={handleUploadServiceImage}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Subiendo..." : (serviceImage ? "Subir y Finalizar" : "Omitir por ahora")}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
                        <div style={{
                            width: '100%',
                            height: '150px',
                            border: '2px dashed rgba(255,255,255,0.3)',
                            borderRadius: '12px',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            position: 'relative',
                            overflow: 'hidden',
                            cursor: 'pointer',
                            background: serviceImage ? 'transparent' : 'rgba(255,255,255,0.05)'
                        }}>
                            {serviceImage ? (
                                <img 
                                    src={URL.createObjectURL(serviceImage)} 
                                    alt="Preview" 
                                    style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                                />
                            ) : (
                                <span style={{ color: 'rgba(255,255,255,0.6)' }}>Toca para seleccionar imagen</span>
                            )}
                            <input 
                                type="file" 
                                accept="image/*" 
                                onChange={(e) => {
                                    if (e.target.files && e.target.files.length > 0) {
                                        setServiceImage(e.target.files[0]);
                                    }
                                }}
                                style={{
                                    position: 'absolute',
                                    top: 0,
                                    left: 0,
                                    width: '100%',
                                    height: '100%',
                                    opacity: 0,
                                    cursor: 'pointer'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>
            </>
        );
    };

    const handleCreateSchedule = async () => {
        if (!createdCompanyId || isCreating) return;
        setIsCreating(true);
        try {
            let finalEmployeeId = employeeId;

            // 1. Ensure employee exists
            if (!finalEmployeeId) {
                try {
                    const newEmp = await API.post<any>("employees/create", {
                        companyId: createdCompanyId,
                        userId: SessionInfo.userId,
                        roles: ["owner", "employee"],
                        sessionUser: SessionInfo.userId
                    });
                    if (newEmp && (newEmp.id || newEmp._id)) {
                        finalEmployeeId = newEmp.id || newEmp._id;
                        setEmployeeId(finalEmployeeId);
                    } else {
                        throw new Error("No se pudo crear el empleado");
                    }
                } catch (e) {
                    console.error("Error creando empleado:", e);
                    throw new Error("No se pudo inicializar tu perfil de colaborador.");
                }
            }

            // 2. Assign services to employee (if they provide services)
            if (doesProvideServices) {
                try {
                    const services = await API.post<any[]>("services/get-by-company", { companyId: createdCompanyId });
                    if (services && services.length > 0) {
                        const serviceStatusItems = services.map(s => ({
                            serviceId: s.id || s._id,
                            active: true
                        }));
                        await API.post<any>("employees/update-collaborator-services", {
                            companyId: createdCompanyId,
                            employeeId: finalEmployeeId,
                            services: serviceStatusItems,
                            sessionUser: SessionInfo.userId
                        });
                    }
                } catch (e) {
                    console.error("Error asignando servicios al empleado:", e);
                }
            }

            // 3. Create Schedules
            let workingDays: number[] = [];
            if (workingDaysMode === "mon-fri") workingDays = [1, 2, 3, 4, 5];
            else if (workingDaysMode === "mon-sat") workingDays = [1, 2, 3, 4, 5, 6];
            else if (workingDaysMode === "mon-sun") workingDays = [1, 2, 3, 4, 5, 6, 0];

            for (let i = 0; i <= 6; i++) {
                const isWorkingDay = workingDays.includes(i);
                
                let schedules = [];
                if (isWorkingDay) {
                    if (hasBreak) {
                        schedules = [
                            { from: openTime, to: breakStart, disabled: false },
                            { from: breakEnd, to: closeTime, disabled: false }
                        ];
                    } else {
                        schedules = [
                            { from: openTime, to: closeTime, disabled: false }
                        ];
                    }
                } else {
                    schedules = [
                        { from: "00:00", to: "23:59", disabled: true }
                    ];
                }

                await API.post<any>("schedules/update", {
                    companyId: createdCompanyId,
                    employeeId: finalEmployeeId,
                    weekDay: i,
                    schedules: schedules,
                    sessionUser: SessionInfo.userId
                });
            }

            // 3.5 Habilitar periodo de agenda por defecto (8 semanas) semana por semana para que la UI lo reconozca
            try {
                // Hacemos un loop de 8 semanas, habilitando bloques exactos de lunes a domingo
                for (let i = 0; i < 8; i++) {
                    const weekStart = dayjs().weekday(i * 7).format("YYYY-MM-DD");
                    const weekEnd = dayjs().weekday(i * 7 + 6).format("YYYY-MM-DD");

                    await API.post<any>("schedules-enabled/enable", {
                        companyId: createdCompanyId,
                        employees: [{ employeeId: finalEmployeeId }],
                        startDate: weekStart,
                        endDate: weekEnd,
                        sessionUser: SessionInfo.userId
                    });
                }
            } catch (e) {
                console.error("Error habilitando periodo de agenda automático:", e);
            }

            // 4. Publish the organization and its services automatically so it appears in search
            try {
                await API.post<any>("companies/set-published-status", {
                    companyId: createdCompanyId,
                    published: "published",
                    sessionUser: SessionInfo.userId
                });
                const servicesList = await API.post<any[]>("services/get-by-company", { companyId: createdCompanyId });
                if (servicesList && servicesList.length > 0) {
                    for (const s of servicesList) {
                        await API.post<any>("services/set-published-status", {
                            companyId: createdCompanyId,
                            serviceId: s.id || s._id,
                            published: "published",
                            sessionUser: SessionInfo.userId
                        });
                    }
                }
            } catch (e) {
                console.error("Error publicando organización/servicios:", e);
            }

                        try {
                await API.post("companies/update", {
                    id: createdCompanyId,
                    onboardingCompleted: true,
                    sessionUser: SessionInfo.userId
                });
            } catch (e) {
                console.error("Error setting onboarding completed", e);
            }
            if (action) {
                handleActionSuccess();
            } else {
                setIsSuccess(true);
            }
        } catch (error: any) {
            console.error("Error creando horarios:", error);
            alert("Hubo un error al guardar los horarios: " + error?.message);
        } finally {
            setIsCreating(false);
        }
    };

    const renderOnboardingScheduleFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title="Configura tus Horarios"
                    description="El último paso. Vamos a definir cuándo estás disponible para recibir clientes."
                    onNext={handleNext}
                    nextLabel="Comenzar"
                >
                    <div style={{ color: "rgba(255, 255, 255, 0.7)", textAlign: "center", padding: "10px" }}>
                        Con esta información, tu agenda online comenzará a aceptar reservas automáticamente.
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="Atención al Cliente"
                    description="¿Brindas tú mismo los servicios que configuraste?"
                    onNext={() => {
                        if (doesProvideServices === null) return;
                        if (!doesProvideServices) {
                            // If they don't provide services, finish setup directly
                            window.location.href = "/landing/dashboard";
                        } else {
                            handleNext();
                        }
                    }}
                    disableNext={doesProvideServices === null}
                    nextLabel={doesProvideServices === false ? "Finalizar" : "Siguiente"}
                >
                    <div style={{ display: 'flex', gap: '15px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
                        <div 
                            onClick={() => setDoesProvideServices(true)}
                            style={{ 
                                padding: '20px 24px', 
                                borderRadius: '12px', 
                                cursor: 'pointer',
                                background: doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${doesProvideServices === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
                                color: 'white',
                                transition: 'all 0.2s ease',
                                textAlign: 'center',
                                flex: '1',
                                minWidth: '200px'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === true ? 'bold' : 'normal' }}>Sí, yo atiendo a los clientes</h4>
                            <p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Asignaremos los servicios a tu nombre.</p>
                        </div>
                        <div 
                            onClick={() => setDoesProvideServices(false)}
                            style={{ 
                                padding: '20px 24px', 
                                borderRadius: '12px', 
                                cursor: 'pointer',
                                background: doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${doesProvideServices === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
                                color: 'white',
                                transition: 'all 0.2s ease',
                                textAlign: 'center',
                                flex: '1',
                                minWidth: '200px'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0', fontSize: '18px', fontWeight: doesProvideServices === false ? 'bold' : 'normal' }}>No, tengo un equipo</h4>
                            <p style={{ margin: 0, fontSize: '13px', color: 'rgba(255,255,255,0.7)' }}>Terminaremos aquí. Luego podrás invitar a tus colaboradores.</p>
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="1. Días Laborables"
                    description="¿Qué días de la semana atiendes?"
                    onNext={handleNext}
                    disableNext={!workingDaysMode}
                >
                    <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', width: '100%', justifyContent: 'center' }}>
                        {[
                            { value: "mon-fri", label: "Lunes a Viernes" },
                            { value: "mon-sat", label: "Lunes a Sábado" },
                            { value: "mon-sun", label: "Lunes a Domingo" },
                        ].map(opt => (
                            <div 
                                key={opt.value}
                                onClick={() => setWorkingDaysMode(opt.value)}
                                style={{ 
                                    padding: '12px 24px', 
                                    borderRadius: '12px', 
                                    cursor: 'pointer',
                                    background: workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                    border: `2px solid ${workingDaysMode === opt.value ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)'}`,
                                    color: 'white',
                                    fontWeight: workingDaysMode === opt.value ? 'bold' : 'normal',
                                    transition: 'all 0.2s ease',
                                    fontSize: '16px'
                                }}
                            >
                                {opt.label}
                            </div>
                        ))}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3}
                    title="2. Horario General"
                    description="¿A qué hora abres y cierras tu negocio?"
                    onNext={handleNext}
                    disableNext={!openTime || !closeTime}
                >
                    <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <span style={{ color: 'white', fontSize: '14px' }}>Apertura</span>
                            <input 
                                type="time"
                                value={openTime}
                                onChange={(e) => setOpenTime(e.target.value)}
                                style={{
                                    padding: '12px',
                                    borderRadius: '8px',
                                    border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.05)',
                                    color: 'white',
                                    fontSize: '16px'
                                }}
                            />
                        </div>
                        <span style={{ color: 'white', fontSize: '18px' }}>a</span>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <span style={{ color: 'white', fontSize: '14px' }}>Cierre</span>
                            <input 
                                type="time"
                                value={closeTime}
                                onChange={(e) => setCloseTime(e.target.value)}
                                style={{
                                    padding: '12px',
                                    borderRadius: '8px',
                                    border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.05)',
                                    color: 'white',
                                    fontSize: '16px'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 4}
                    title="3. Horario Cortado"
                    description="¿Cierras tu negocio al mediodía para descansar?"
                    onNext={handleNext}
                    disableNext={hasBreak === null}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
                        <div style={{ display: 'flex', gap: '10px' }}>
                            <div 
                                onClick={() => setHasBreak(true)}
                                style={{ 
                                    padding: '10px 20px', 
                                    borderRadius: '8px', 
                                    cursor: 'pointer',
                                    background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                    border: `1px solid ${hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                    color: 'white',
                                    transition: 'all 0.2s ease'
                                }}
                            >
                                Sí, tengo descanso
                            </div>
                            <div 
                                onClick={() => setHasBreak(false)}
                                style={{ 
                                    padding: '10px 20px', 
                                    borderRadius: '8px', 
                                    cursor: 'pointer',
                                    background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.1)',
                                    border: `1px solid ${hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`,
                                    color: 'white',
                                    transition: 'all 0.2s ease'
                                }}
                            >
                                No, horario corrido
                            </div>
                        </div>

                        {hasBreak && (
                            <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center', alignItems: 'center', marginTop: '10px' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <span style={{ color: 'white', fontSize: '14px' }}>Inicia el descanso</span>
                                    <input 
                                        type="time"
                                        value={breakStart}
                                        onChange={(e) => setBreakStart(e.target.value)}
                                        style={{
                                            padding: '12px',
                                            borderRadius: '8px',
                                            border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.05)',
                                            color: 'white',
                                            fontSize: '16px'
                                        }}
                                    />
                                </div>
                                <span style={{ color: 'white', fontSize: '18px' }}>a</span>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <span style={{ color: 'white', fontSize: '14px' }}>Termina</span>
                                    <input 
                                        type="time"
                                        value={breakEnd}
                                        onChange={(e) => setBreakEnd(e.target.value)}
                                        style={{
                                            padding: '12px',
                                            borderRadius: '8px',
                                            border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.05)',
                                            color: 'white',
                                            fontSize: '16px'
                                        }}
                                    />
                                </div>
                            </div>
                        )}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 5}
                    title="Resumen Final y Vista Previa"
                    description="Revisa cómo se verá tu negocio. Al finalizar, será publicado automáticamente."
                    onNext={handleCreateSchedule}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Publicando..." : "Publicar y Activar Agenda"}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
                        
                        {/* Mockup visual */}
                        <div style={{
                            width: '100%', maxWidth: '500px', borderRadius: '12px', overflow: 'hidden',
                            boxShadow: '0 4px 20px rgba(0,0,0,0.5)', background: '#1e1e1e', border: '1px solid rgba(255,255,255,0.1)'
                        }}>
                            {/* Cabecera Mockup */}
                            <div style={{ 
                                background: headerColor, 
                                height: '120px', 
                                display: 'flex', 
                                alignItems: 'center', 
                                justifyContent: 'center',
                                position: 'relative'
                            }}>
                                {/* Simular imagen de cabecera si hay Archivo */}
                                {headerImage && (
                                    <img src={URL.createObjectURL(headerImage)} style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.6 }} />
                                )}
                                <h2 style={{ color: headerFontColor, margin: 0, zIndex: 1, textShadow: '0 2px 4px rgba(0,0,0,0.5)' }}>{orgName || "Tu Negocio"}</h2>
                            </div>

                            {/* Cuerpo Mockup (Servicios y Horarios) */}
                            <div style={{ padding: '20px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                                    <h4 style={{ margin: 0, color: 'white' }}>Servicios ({previewServices.length})</h4>
                                    <button 
                                        onClick={() => {
                                            setServiceName("");
                                            setServiceDescription("");
                                            setServiceLength(null);
                                            setServicePrice("");
                                            setServiceLimit(1);
                                            setServiceImage(null);
                                            setCreatedServiceId(null);
                                            setIsAddingAnotherService(true);
                                            setCurrentStepIndex(1); // Service creation starts at step 1
                                        }}
                                        style={{ 
                                            background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
                                            color: 'white', borderRadius: '15px', padding: '4px 12px', fontSize: '12px',
                                            cursor: 'pointer', transition: 'background 0.2s'
                                        }}
                                        onMouseOver={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.2)'}
                                        onMouseOut={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
                                    >
                                        + Agregar otro
                                    </button>
                                </div>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '20px' }}>
                                    {previewServices.map((s, idx) => (
                                        <div key={idx} style={{ background: 'rgba(255,255,255,0.05)', padding: '10px', borderRadius: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                <span style={{ color: 'white', fontWeight: 'bold', fontSize: '14px' }}>{s.name}</span>
                                                <span style={{ color: 'rgba(255,255,255,0.6)', fontSize: '12px' }}>{s.length} min</span>
                                            </div>
                                            <span style={{ color: 'var(--wine-red)', fontWeight: 'bold' }}>${s.originalPrice}</span>
                                        </div>
                                    ))}
                                    {previewServices.length === 0 && (
                                        <span style={{ color: 'rgba(255,255,255,0.5)', fontSize: '14px' }}>Sin servicios configurados aún.</span>
                                    )}
                                </div>

                                <h4 style={{ margin: '0 0 10px 0', color: 'white' }}>Horario Laboral</h4>
                                <div style={{ background: 'rgba(255,255,255,0.05)', padding: '15px', borderRadius: '8px' }}>
                                    <div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
                                        <strong>Días:</strong> {workingDaysMode === "mon-fri" ? "Lunes a Viernes" : (workingDaysMode === "mon-sat" ? "Lunes a Sábado" : "Lunes a Domingo")}
                                    </div>
                                    <div style={{ color: 'white', fontSize: '14px', marginBottom: '5px' }}>
                                        <strong>Horario:</strong> {openTime} a {closeTime}
                                    </div>
                                    {hasBreak && (
                                        <div style={{ color: 'white', fontSize: '14px' }}>
                                            <strong>Descanso:</strong> {breakStart} a {breakEnd}
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Advertencia Explícita */}
                        <div style={{
                            background: 'rgba(255, 60, 60, 0.1)',
                            borderLeft: '4px solid #ff3c3c',
                            padding: '15px',
                            borderRadius: '0 8px 8px 0',
                            width: '100%',
                            maxWidth: '500px'
                        }}>
                            <h4 style={{ margin: '0 0 5px 0', color: '#ff3c3c', fontSize: '16px' }}>🚨 Aviso de Publicación</h4>
                            <p style={{ margin: 0, color: 'rgba(255,255,255,0.8)', fontSize: '13px', lineHeight: '1.4' }}>
                                Al hacer clic en <strong>Publicar y Activar Agenda</strong>, tu organización, servicios y esta primera jornada laboral serán publicados en TurnosXpress. 
                                <br/><br/>
                                ¡Tus clientes podrán empezar a reservar turnos de inmediato! Podrás editar todo más tarde desde tu panel.
                            </p>
                        </div>
                    </div>
                </QuestionCard>
            </>
        );
    };


    const handleUpdateScheduleSubmit = async () => {
        if (!createdCompanyId || isCreating || !scheduleScope) return;
        setIsCreating(true);
        try {
            let targetEmployees: any[] = [];
            
            if (scheduleScope === "me") {
                const me = allEmployees.find((e: any) => {
                    const eUserId = e.userId?._id || e.userId?.id || e.userId;
                    return String(eUserId) === String(SessionInfo.userId);
                });
                if (me) targetEmployees.push(me);
            } else if (scheduleScope === "specific") {
                const specific = allEmployees.find(e => e.id === targetEmployeeId || e._id === targetEmployeeId || e.employeeId === targetEmployeeId);
                if (specific) targetEmployees.push(specific);
            } else if (scheduleScope === "all") {
                targetEmployees = [...allEmployees];
            }

            if (targetEmployees.length === 0) {
                alert("No se encontró ningún colaborador seleccionado.");
                setIsCreating(false);
                return;
            }

            let workingDays: number[] = [];
            if (workingDaysMode === "mon-fri") workingDays = [1, 2, 3, 4, 5];
            else if (workingDaysMode === "mon-sat") workingDays = [1, 2, 3, 4, 5, 6];
            else if (workingDaysMode === "mon-sun") workingDays = [1, 2, 3, 4, 5, 6, 0];

            for (const emp of targetEmployees) {
                const empId = emp.id || emp._id || emp.employeeId;
                if (!empId) continue;

                for (let i = 0; i <= 6; i++) {
                    const isWorkingDay = workingDays.includes(i);
                    
                    let schedules = [];
                    if (isWorkingDay) {
                        if (hasBreak) {
                            schedules = [
                                { from: openTime, to: breakStart, disabled: false },
                                { from: breakEnd, to: closeTime, disabled: false }
                            ];
                        } else {
                            schedules = [
                                { from: openTime, to: closeTime, disabled: false }
                            ];
                        }
                    } else {
                        schedules = [
                            { from: "00:00", to: "23:59", disabled: true }
                        ];
                    }

                    await API.post<any>("schedules/update", {
                        companyId: createdCompanyId,
                        employeeId: empId,
                        weekDay: i,
                        schedules: schedules,
                        sessionUser: SessionInfo.userId
                    });
                }
            }
            handleActionSuccess();
        } catch (error: any) {
            console.error("Error actualizando horarios:", error);
            alert("Hubo un error al guardar los horarios: " + error?.message);
        } finally {
            setIsCreating(false);
        }
    };

    const renderUpdateScheduleFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title="Actualizar Horarios"
                    description="¿A quiénes quieres aplicar esta nueva rutina de horarios?"
                    onNext={() => {
                        if (scheduleScope === "specific" && !targetEmployeeId) {
                            alert("Por favor selecciona un colaborador.");
                            return;
                        }
                        handleNext();
                    }}
                    disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
                        <div 
                            onClick={() => setScheduleScope("me")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
                            <p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina únicamente a tus horarios.</p>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("specific")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
                            <p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Aplica esta rutina a un integrante específico de tu equipo.</p>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("all")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
                            <p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>Sobrescribe masivamente los horarios de todo tu equipo.</p>
                        </div>
                        
                        {scheduleScope === "specific" && (
                            <div style={{ marginTop: '15px', width: '100%' }}>
                                <label style={{ color: 'white', display: 'block', marginBottom: '8px', fontSize: '14px' }}>Selecciona el colaborador:</label>
                                <select 
                                    value={targetEmployeeId || ""}
                                    onChange={(e) => setTargetEmployeeId(e.target.value)}
                                    style={{
                                        width: '100%', padding: '12px', borderRadius: '8px', 
                                        background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
                                        outline: 'none', fontSize: '16px'
                                    }}
                                >
                                    <option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
                                    {allEmployees.map(emp => (
                                        <option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
                                            {emp.firstName} {emp.lastName}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="Días de Trabajo"
                    description="¿Qué días aplicará esta rutina?"
                    onNext={handleNext}
                    disableNext={!workingDaysMode}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
                        {[
                            { id: 'mon-fri', label: 'Lunes a Viernes' },
                            { id: 'mon-sat', label: 'Lunes a Sábado' },
                            { id: 'mon-sun', label: 'Todos los días' }
                        ].map(mode => (
                            <div 
                                key={mode.id}
                                onClick={() => setWorkingDaysMode(mode.id)}
                                style={{ 
                                    padding: '15px', 
                                    borderRadius: '12px', 
                                    cursor: 'pointer',
                                    background: workingDaysMode === mode.id ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                    border: `2px solid ${workingDaysMode === mode.id ? 'var(--wine-red)' : 'transparent'}`,
                                    color: 'white',
                                    textAlign: 'center',
                                    transition: 'all 0.2s ease'
                                }}
                            >
                                {mode.label}
                            </div>
                        ))}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="Horario Comercial"
                    description="¿A qué hora empieza y termina la jornada laboral?"
                    onNext={handleNext}
                    disableNext={!openTime || !closeTime}
                >
                    <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
                            <input 
                                type="time" 
                                value={openTime}
                                onChange={(e) => setOpenTime(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
                            <input 
                                type="time" 
                                value={closeTime}
                                onChange={(e) => setCloseTime(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3}
                    title="Descansos"
                    description="¿Tienen un horario de corte al mediodía o descanso?"
                    onNext={() => {
                        if (hasBreak) {
                            handleNext();
                        } else {
                            handleUpdateScheduleSubmit();
                        }
                    }}
                    disableNext={hasBreak === null}
                    nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Horarios")}
                >
                    <div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
                        <div 
                            onClick={() => setHasBreak(true)}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            Sí, hay descanso
                        </div>
                        <div 
                            onClick={() => setHasBreak(false)}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            No, horario corrido
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 4}
                    title="Horario de Descanso"
                    description="¿De qué hora a qué hora no estarán disponibles?"
                    onNext={handleUpdateScheduleSubmit}
                    disableNext={!breakStart || !breakEnd || isCreating}
                    nextLabel={isCreating ? "Guardando..." : "Guardar Horarios"}
                >
                    <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
                            <input 
                                type="time" 
                                value={breakStart}
                                onChange={(e) => setBreakStart(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
                            <input 
                                type="time" 
                                value={breakEnd}
                                onChange={(e) => setBreakEnd(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>
            </>
        );
    };



    const handleOverrideScheduleSubmit = async () => {
        if (!createdCompanyId || isCreating || !scheduleScope || !overrideDate) return;
        setIsCreating(true);
        try {
            let targetEmployees: any[] = [];
            
            if (scheduleScope === "me") {
                const me = allEmployees.find((e: any) => {
                    const eUserId = e.userId?._id || e.userId?.id || e.userId;
                    return String(eUserId) === String(SessionInfo.userId);
                });
                if (me) targetEmployees.push(me);
            } else if (scheduleScope === "specific") {
                const specific = allEmployees.find(e => e.id === targetEmployeeId || e._id === targetEmployeeId || e.employeeId === targetEmployeeId);
                if (specific) targetEmployees.push(specific);
            } else if (scheduleScope === "all") {
                targetEmployees = [...allEmployees];
            }

            if (targetEmployees.length === 0) {
                alert("No se encontró ningún colaborador seleccionado.");
                setIsCreating(false);
                return;
            }

            let schedules = [];
            if (hasBreak) {
                schedules = [
                    { from: openTime, to: breakStart, disabled: false },
                    { from: breakEnd, to: closeTime, disabled: false }
                ];
            } else {
                schedules = [
                    { from: openTime, to: closeTime, disabled: false }
                ];
            }

            for (const emp of targetEmployees) {
                const empId = emp.id || emp._id || emp.employeeId;
                if (!empId) continue;

                await API.post<any>("schedules-overrides/update", {
                    companyId: createdCompanyId,
                    employeeId: empId,
                    date: overrideDate,
                    schedules: schedules,
                    sessionUser: SessionInfo.userId
                });
            }
            handleActionSuccess();
        } catch (error: any) {
            console.error("Error actualizando horario excepcional:", error);
            alert("Hubo un error al guardar la excepción: " + error?.message);
        } finally {
            setIsCreating(false);
        }
    };

    const renderOverrideScheduleFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title="Horario Especial"
                    description="¿A quiénes quieres aplicar este horario especial?"
                    onNext={() => {
                        if (scheduleScope === "specific" && !targetEmployeeId) {
                            alert("Por favor selecciona un colaborador.");
                            return;
                        }
                        handleNext();
                    }}
                    disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
                        <div 
                            onClick={() => setScheduleScope("me")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("specific")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("all")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
                        </div>
                        
                        {scheduleScope === "specific" && (
                            <div style={{ marginTop: '15px', width: '100%' }}>
                                <select 
                                    value={targetEmployeeId || ""}
                                    onChange={(e) => setTargetEmployeeId(e.target.value)}
                                    style={{
                                        width: '100%', padding: '12px', borderRadius: '8px', 
                                        background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
                                        outline: 'none', fontSize: '16px'
                                    }}
                                >
                                    <option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
                                    {allEmployees.map(emp => (
                                        <option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
                                            {emp.firstName} {emp.lastName}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="Fecha de la Excepción"
                    description="¿En qué fecha deseas aplicar este horario distinto?"
                    onNext={handleNext}
                    disableNext={!overrideDate}
                >
                    <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
                        <input 
                            type="date"
                            value={overrideDate}
                            onChange={(e) => setOverrideDate(e.target.value)}
                            style={{
                                padding: '12px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                fontSize: '18px', fontFamily: 'sans-serif'
                            }}
                        />
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="Horario Especial"
                    description="¿A qué hora empieza y termina la jornada para este día en particular?"
                    onNext={handleNext}
                    disableNext={!openTime || !closeTime}
                >
                    <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Apertura</label>
                            <input 
                                type="time" 
                                value={openTime}
                                onChange={(e) => setOpenTime(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Cierre</label>
                            <input 
                                type="time" 
                                value={closeTime}
                                onChange={(e) => setCloseTime(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3}
                    title="Descansos"
                    description="¿Habrá algún horario de descanso en este día especial?"
                    onNext={() => {
                        if (hasBreak) {
                            handleNext();
                        } else {
                            handleOverrideScheduleSubmit();
                        }
                    }}
                    disableNext={hasBreak === null}
                    nextLabel={hasBreak ? "Siguiente" : (isCreating ? "Guardando..." : "Guardar Excepción")}
                >
                    <div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
                        <div 
                            onClick={() => setHasBreak(true)}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: hasBreak === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${hasBreak === true ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            Sí, hay descanso
                        </div>
                        <div 
                            onClick={() => setHasBreak(false)}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: hasBreak === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${hasBreak === false ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            No, de corrido
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 4}
                    title="Horario de Descanso"
                    description="¿De qué hora a qué hora no estarán disponibles en este día?"
                    onNext={handleOverrideScheduleSubmit}
                    disableNext={!breakStart || !breakEnd || isCreating}
                    nextLabel={isCreating ? "Guardando..." : "Guardar Excepción"}
                >
                    <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Inicio descanso</label>
                            <input 
                                type="time" 
                                value={breakStart}
                                onChange={(e) => setBreakStart(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fin descanso</label>
                            <input 
                                type="time" 
                                value={breakEnd}
                                onChange={(e) => setBreakEnd(e.target.value)}
                                style={{ 
                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                    fontSize: '18px', fontFamily: 'monospace'
                                }}
                            />
                        </div>
                    </div>
                </QuestionCard>
            </>
        );
    };


    
    const handleDisableScheduleSubmit = async () => {
        if (!createdCompanyId || isCreating || !scheduleScope || !disableDuration) return;
        setIsCreating(true);
        try {
            let targetEmployees: any[] = [];
            
            if (scheduleScope === "me") {
                const me = allEmployees.find((e: any) => {
                    const eUserId = e.userId?._id || e.userId?.id || e.userId;
                    return String(eUserId) === String(SessionInfo.userId);
                });
                if (me) targetEmployees.push(me);
            } else if (scheduleScope === "specific") {
                const specific = allEmployees.find(e => e.id === targetEmployeeId || e._id === targetEmployeeId || e.employeeId === targetEmployeeId);
                if (specific) targetEmployees.push(specific);
            } else if (scheduleScope === "all") {
                targetEmployees = [...allEmployees];
            }

            if (targetEmployees.length === 0) {
                alert("No se encontró ningún colaborador seleccionado.");
                setIsCreating(false);
                return;
            }

            let finalStartDateStr = disableStartDate;
            let finalEndDateStr = disableEndDate;

            if (disableDuration === "one-day") {
                finalEndDateStr = disableStartDate;
                if (isFullDayDisabled) {
                    finalStartDateStr += "T00:00:00";
                    finalEndDateStr += "T23:59:59";
                } else {
                    if (!disableStartTime || !disableEndTime) {
                        alert("Por favor selecciona un horario de inicio y de fin.");
                        setIsCreating(false);
                        return;
                    }
                    finalStartDateStr += "T" + disableStartTime + ":00";
                    finalEndDateStr += "T" + disableEndTime + ":00";
                }
            } else {
                // multi-day
                if (!disableStartDate || !disableEndDate || !disableStartTime || !disableEndTime) {
                    alert("Faltan datos de fecha u hora.");
                    setIsCreating(false);
                    return;
                }
                finalStartDateStr += "T" + disableStartTime + ":00";
                finalEndDateStr += "T" + disableEndTime + ":00";
            }

            const employeesPayload = targetEmployees.map(emp => ({
                employeeId: emp.id || emp._id || emp.employeeId
            }));

            await API.post<any>("schedules-disabled/disable", {
                companyId: createdCompanyId,
                employees: employeesPayload,
                startDate: new Date(finalStartDateStr),
                endDate: new Date(finalEndDateStr),
                sessionUser: SessionInfo.userId
            });

            handleActionSuccess();
        } catch (error: any) {
            console.error("Error cargando restricciones:", error);
            alert("Hubo un error al guardar la restricción: " + error?.message);
        } finally {
            setIsCreating(false);
        }
    };

    const renderDisableScheduleFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 0}
                    title="Cerrar Agenda"
                    description="¿A quiénes quieres aplicar esta inhabilitación de agenda?"
                    onNext={() => {
                        if (scheduleScope === "specific" && !targetEmployeeId) {
                            alert("Por favor selecciona un colaborador.");
                            return;
                        }
                        handleNext();
                    }}
                    disableNext={!scheduleScope || (scheduleScope === "specific" && !targetEmployeeId)}
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
                        <div 
                            onClick={() => setScheduleScope("me")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "me" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "me" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>Solo a mí</h4>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("specific")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "specific" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "specific" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A un colaborador en particular</h4>
                        </div>
                        <div 
                            onClick={() => setScheduleScope("all")}
                            style={{ 
                                padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: scheduleScope === "all" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${scheduleScope === "all" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center', transition: 'all 0.2s ease'
                            }}
                        >
                            <h4 style={{ margin: '0 0 5px 0' }}>A todos mis colaboradores</h4>
                        </div>
                        
                        {scheduleScope === "specific" && (
                            <div style={{ marginTop: '15px', width: '100%' }}>
                                <select 
                                    value={targetEmployeeId || ""}
                                    onChange={(e) => setTargetEmployeeId(e.target.value)}
                                    style={{
                                        width: '100%', padding: '12px', borderRadius: '8px', 
                                        background: 'rgba(255,255,255,0.1)', color: 'white', border: '1px solid rgba(255,255,255,0.2)',
                                        outline: 'none', fontSize: '16px'
                                    }}
                                >
                                    <option value="" disabled style={{ color: 'black' }}>-- Seleccionar --</option>
                                    {allEmployees.map(emp => (
                                        <option key={emp.id || emp._id || emp.employeeId} value={emp.id || emp._id || emp.employeeId} style={{ color: 'black' }}>
                                            {emp.firstName} {emp.lastName}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        )}
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="Duración del Cierre"
                    description="¿Por cuánto tiempo se cerrará la agenda?"
                    onNext={handleNext}
                    disableNext={!disableDuration}
                >
                    <div style={{ display: 'flex', gap: '15px', width: '100%', justifyContent: 'center' }}>
                        <div 
                            onClick={() => setDisableDuration("one-day")}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: disableDuration === "one-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${disableDuration === "one-day" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            Solo por un día
                        </div>
                        <div 
                            onClick={() => setDisableDuration("multi-day")}
                            style={{ 
                                flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                background: disableDuration === "multi-day" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                border: `2px solid ${disableDuration === "multi-day" ? 'var(--wine-red)' : 'transparent'}`,
                                color: 'white', textAlign: 'center'
                            }}
                        >
                            Por varios días
                        </div>
                    </div>
                </QuestionCard>

                {disableDuration === "one-day" && (
                    <>
                        <QuestionCard 
                            isActive={currentStepIndex === 2}
                            title="Fecha del Cierre"
                            description="Selecciona la fecha en la que no se recibirán turnos."
                            onNext={handleNext}
                            disableNext={!disableStartDate}
                        >
                            <div style={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
                                <input 
                                    type="date"
                                    value={disableStartDate}
                                    onChange={(e) => setDisableStartDate(e.target.value)}
                                    style={{
                                        padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                        background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                        fontSize: '16px', fontFamily: 'sans-serif'
                                    }}
                                />
                            </div>
                        </QuestionCard>

                        <QuestionCard 
                            isActive={currentStepIndex === 3}
                            title="Rango Horario"
                            description="¿Esta inhabilitación aplica para todo el día o solo en una franja horaria?"
                            onNext={() => {
                                if (isFullDayDisabled) {
                                    handleDisableScheduleSubmit();
                                } else if (disableStartTime && disableEndTime) {
                                    handleDisableScheduleSubmit();
                                }
                            }}
                            nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
                            disableNext={(!isFullDayDisabled && (!disableStartTime || !disableEndTime)) || isCreating}
                        >
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', width: '100%', alignItems: 'center' }}>
                                <div style={{ display: 'flex', gap: '15px', width: '100%' }}>
                                    <div 
                                        onClick={() => setIsFullDayDisabled(true)}
                                        style={{ 
                                            flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                            background: isFullDayDisabled === true ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                            border: `2px solid ${isFullDayDisabled === true ? 'var(--wine-red)' : 'transparent'}`,
                                            color: 'white', textAlign: 'center'
                                        }}
                                    >
                                        Todo el día
                                    </div>
                                    <div 
                                        onClick={() => setIsFullDayDisabled(false)}
                                        style={{ 
                                            flex: 1, padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                            background: isFullDayDisabled === false ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)',
                                            border: `2px solid ${isFullDayDisabled === false ? 'var(--wine-red)' : 'transparent'}`,
                                            color: 'white', textAlign: 'center'
                                        }}
                                    >
                                        Franja Específica
                                    </div>
                                </div>
                                {!isFullDayDisabled && (
                                    <div style={{ display: 'flex', gap: '20px' }}>
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Desde (Hora)</label>
                                            <input 
                                                type="time" 
                                                value={disableStartTime}
                                                onChange={(e) => setDisableStartTime(e.target.value)}
                                                style={{ 
                                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                                    fontSize: '18px', fontFamily: 'monospace'
                                                }}
                                            />
                                        </div>
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                            <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hasta (Hora)</label>
                                            <input 
                                                type="time" 
                                                value={disableEndTime}
                                                onChange={(e) => setDisableEndTime(e.target.value)}
                                                style={{ 
                                                    padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                                    background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                                    fontSize: '18px', fontFamily: 'monospace'
                                                }}
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                        </QuestionCard>
                    </>
                )}

                {disableDuration === "multi-day" && (
                    <>
                        <QuestionCard 
                            isActive={currentStepIndex === 2}
                            title="¿Cuándo inicia?"
                            description="Selecciona la fecha y hora de inicio de la inhabilitación."
                            onNext={handleNext}
                            disableNext={!disableStartDate || !disableStartTime}
                        >
                            <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Inicio</label>
                                    <input 
                                        type="date"
                                        value={disableStartDate}
                                        onChange={(e) => setDisableStartDate(e.target.value)}
                                        style={{
                                            padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                            fontSize: '16px', fontFamily: 'sans-serif'
                                        }}
                                    />
                                </div>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Inicio</label>
                                    <input 
                                        type="time" 
                                        value={disableStartTime}
                                        onChange={(e) => setDisableStartTime(e.target.value)}
                                        style={{ 
                                            padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                            fontSize: '18px', fontFamily: 'monospace'
                                        }}
                                    />
                                </div>
                            </div>
                        </QuestionCard>

                        <QuestionCard 
                            isActive={currentStepIndex === 3}
                            title="¿Cuándo termina?"
                            description="Selecciona la fecha y hora en la que finaliza el cierre."
                            onNext={handleDisableScheduleSubmit}
                            nextLabel={isCreating ? "Guardando..." : "Cerrar Agenda"}
                            disableNext={!disableEndDate || !disableEndTime || isCreating}
                        >
                            <div style={{ display: 'flex', gap: '20px', width: '100%', justifyContent: 'center' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Fecha de Fin</label>
                                    <input 
                                        type="date"
                                        value={disableEndDate}
                                        onChange={(e) => setDisableEndDate(e.target.value)}
                                        min={disableStartDate}
                                        style={{
                                            padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                            fontSize: '16px', fontFamily: 'sans-serif'
                                        }}
                                    />
                                </div>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '5px' }}>
                                    <label style={{ color: 'white', fontSize: '12px', opacity: 0.7 }}>Hora de Fin</label>
                                    <input 
                                        type="time" 
                                        value={disableEndTime}
                                        onChange={(e) => setDisableEndTime(e.target.value)}
                                        style={{ 
                                            padding: '10px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.2)',
                                            background: 'rgba(255,255,255,0.1)', color: 'white', outline: 'none',
                                            fontSize: '18px', fontFamily: 'monospace'
                                        }}
                                    />
                                </div>
                            </div>
                        </QuestionCard>
                    </>
                )}
            </>
        );
    };

    const handleSearchCollaboratorEmail = async () => {
        if (!inviteEmail || !inviteEmail.includes("@")) return;
        setIsSearchingEmail(true);
        setInviteEmailError("");
        setInviteCollaborator(null);
        try {
            const data = await API.post<any>("users/get-by-email", { email: inviteEmail.trim().toLowerCase() });
            if (data && (data.id || data._id)) {
                if ((data.id || data._id) === SessionInfo.userId) {
                    setInviteEmailError("No puedes invitarte a ti mismo.");
                    setIsSearchingEmail(false);
                    return;
                }
                setInviteCollaborator(data);
                handleNext(); // Go to role selection
            } else {
                setInviteEmailError("Usuario no registrado");
            }
        } catch (error: any) {
            setInviteEmailError("Usuario no registrado");
        } finally {
            setIsSearchingEmail(false);
        }
    };

    const handleCreateCollaborator = async () => {
        if (!inviteCollaborator || !createdCompanyId) return;
        setIsCreating(true);
        try {
            await API.post<any>("employees/create", {
                companyId: createdCompanyId,
                userId: inviteCollaborator.id || inviteCollaborator._id,
                roles: inviteRole === "admin" ? ["admin"] : [],
                hostOk: true,
                sessionUser: SessionInfo.userId
            });
            handleActionSuccess();
        } catch (error: any) {
            const errorMessage = error.desc || error.message || "Error al invitar al colaborador";
            if (errorMessage.toLowerCase().includes("limite") || errorMessage.toLowerCase().includes("límite")) {
                setIsUpgradeRequired(true);
            } else {
                alert(errorMessage);
            }
        } finally {
            setIsCreating(false);
        }
    };

    const renderNewCollaboratorFlow = () => {
        return (
            <>
                <QuestionCard 
                    isActive={currentStepIndex === 1}
                    title="Buscar Colaborador"
                    description="Ingresa el e-mail del usuario. Importante: debe estar registrado previamente en TurnosXpress."
                    onNext={handleSearchCollaboratorEmail}
                    disableNext={!inviteEmail || !inviteEmail.includes("@") || isSearchingEmail}
                    nextLabel={isSearchingEmail ? "Buscando..." : "Buscar"}
                >
                    <QuestionInput 
                        placeholder="ejemplo@correo.com"
                        value={inviteEmail}
                        onChange={(e) => {
                            setInviteEmail(e.target.value);
                            setInviteEmailError("");
                        }}
                        onKeyDown={(e) => {
                            if (inviteEmail.includes("@") && !isSearchingEmail) {
                                handleKeyDown(e, handleSearchCollaboratorEmail);
                            }
                        }}
                        autoFocus
                    />
                    {inviteEmailError && (
                        <div style={{ marginTop: '15px', padding: '15px', background: 'rgba(255,0,0,0.1)', border: '1px solid rgba(255,0,0,0.3)', borderRadius: '8px', color: '#ff9999', fontSize: '13px' }}>
                            <b>No encontramos este e-mail.</b><br/>
                            Asegúrate de que la persona ya haya creado una cuenta en TurnosXpress con este correo. Pídele que se registre primero y vuelve a intentarlo.
                        </div>
                    )}
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 2}
                    title="Configurar Rol"
                    description={`¿Qué permisos quieres darle a ${inviteCollaborator?.firstName || inviteCollaborator?.fullName}?`}
                    onNext={handleNext}
                >
                    {inviteCollaborator && (
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: '20px' }}>
                            {inviteCollaborator.avatar ? (
                                <img src={inviteCollaborator.avatar} alt="Avatar" style={{ width: 60, height: 60, borderRadius: '50%', marginBottom: '10px', objectFit: 'cover' }} />
                            ) : (
                                <ReactAvatar name={inviteCollaborator.fullName} size="60" round color="#600018" style={{ marginBottom: '10px' }}/>
                            )}
                            <div style={{ color: 'white', fontWeight: 'bold' }}>{inviteCollaborator.fullName}</div>
                        </div>
                    )}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '15px', width: '100%' }}>
                        <div 
                            onClick={() => setInviteRole("colaborador")}
                            style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "colaborador" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}
                        >
                            <div style={{ fontWeight: 'bold' }}>Colaborador</div>
                            <div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Solo podrá ver y gestionar su propia agenda de turnos.</div>
                        </div>
                        <div 
                            onClick={() => setInviteRole("admin")}
                            style={{ padding: '15px', borderRadius: '12px', background: inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.05)', border: `1px solid ${inviteRole === "admin" ? 'var(--wine-red)' : 'rgba(255,255,255,0.2)'}`, cursor: 'pointer', color: 'white', transition: 'all 0.2s' }}
                        >
                            <div style={{ fontWeight: 'bold' }}>Administrador</div>
                            <div style={{ fontSize: '12px', opacity: 0.8, marginTop: '5px' }}>Tendrá acceso total para modificar horarios, servicios y otros colaboradores de esta organización.</div>
                        </div>
                    </div>
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3 && !isUpgradeRequired}
                    title="Confirmar Invitación"
                    description={`Se enviará una invitación a ${inviteCollaborator?.email}. El usuario deberá aceptarla para comenzar.`}
                    onNext={handleCreateCollaborator}
                    disableNext={isCreating}
                    nextLabel={isCreating ? "Enviando..." : "Enviar Invitación"}
                >
                    {null}
                </QuestionCard>

                <QuestionCard 
                    isActive={currentStepIndex === 3 && isUpgradeRequired}
                    title="¡Haz crecer tu equipo!"
                    description="Parece que has alcanzado el límite de colaboradores de tu plan actual. Actualiza tu suscripción para seguir sumando profesionales a tu negocio."
                    onNext={() => window.location.href = "/landing/pricing"}
                    nextLabel="Ver Planes y Mejorar"
                >
                    <div style={{ padding: '20px', background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', border: '1px solid var(--wine-red)', borderRadius: '15px', color: 'white', textAlign: 'center', margin: '15px 0' }}>
                        <div style={{ fontSize: '40px', marginBottom: '10px' }}>🚀</div>
                        <h4 style={{ margin: '0 0 10px 0', fontSize: '18px' }}>Beneficios de expandirte</h4>
                        <ul style={{ textAlign: 'left', margin: '0', padding: '0 0 0 20px', opacity: 0.9, fontSize: '14px', lineHeight: '1.6' }}>
                            <li>Agendas ilimitadas para todo tu equipo.</li>
                            <li>Aumento exponencial de tus reservas diarias.</li>
                            <li>Control total sobre los permisos de cada integrante.</li>
                        </ul>
                    </div>
                </QuestionCard>
            </>
        );
    };
    const renderSetupCollaboratorFlow = () => {
        if (currentStepIndex === 0) {
            return (
                <QuestionCard
                    isActive={true}
                    title="Configuración de Colaborador"
                    description={`El colaborador ${collaboratorToSetup?.name || ""} requiere tu atención para comenzar a recibir reservas.`}
                    step={1}
                    totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2}
                    onNext={() => {
                        if (setupMissingServices) setCurrentStepIndex(1);
                        else if (setupMissingSchedules) setCurrentStepIndex(2);
                    }}
                    nextLabel="Comenzar Configuración"
                >
                    <div style={{ 
                        padding: "30px", 
                        background: 'linear-gradient(135deg, rgba(255, 65, 108, 0.1) 0%, rgba(255, 75, 43, 0.1) 100%)', 
                        border: '1px solid var(--wine-red)', 
                        borderRadius: '15px', 
                        color: 'white', 
                        textAlign: 'center', 
                        margin: '15px 0' 
                    }}>
                        <div style={{ fontSize: '40px', marginBottom: '10px' }}>⚠️</div>
                        <p style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '15px' }}>Hemos detectado que a este colaborador le falta:</p>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', alignItems: 'center', marginBottom: '20px' }}>
                            {setupMissingServices && (
                                <div style={{ background: 'rgba(0,0,0,0.3)', padding: '10px 20px', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '10px' }}>
                                    <span>✂️</span> Servicios asignados
                                </div>
                            )}
                            {setupMissingSchedules && (
                                <div style={{ background: 'rgba(0,0,0,0.3)', padding: '10px 20px', borderRadius: '20px', display: 'flex', alignItems: 'center', gap: '10px' }}>
                                    <span>🕒</span> Horarios de atención
                                </div>
                            )}
                        </div>
                        <p style={{ opacity: 0.8, fontSize: '14px' }}>Te guiaremos paso a paso para configurarlo rápidamente.</p>
                    </div>
                </QuestionCard>
            );
        }

        if (currentStepIndex === 1) {
            return (
                <QuestionCard
                    isActive={true}
                    title="Asignación de Servicios"
                    description="Selecciona los servicios que este colaborador podrá realizar."
                    step={2}
                    totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2}
                    onNext={async () => {
                        if (setupSelectedServices.length === 0) {
                            alert("Debes seleccionar al menos un servicio");
                            return;
                        }
                        setIsCreating(true);
                        try {
                            for (const serviceId of setupSelectedServices) {
                                await API.post<any>("employees/add-service", {
                                    companyId: createdCompanyId,
                                    employeeId: employeeId,
                                    serviceId: serviceId,
                                    sessionUser: SessionInfo.userId
                                });
                            }
                            if (setupMissingSchedules) {
                                setCurrentStepIndex(2);
                            } else {
                                setIsSuccess(true);
                            }
                        } catch (e) {
                            console.error(e);
                        } finally {
                            setIsCreating(false);
                        }
                    }}
                    nextLabel="Guardar y Continuar"
                    disableNext={isCreating}
                >
                    <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                        {setupAvailableServices.map(service => (
                            <div 
                                key={service.id || service._id}
                                onClick={() => {
                                    const id = service.id || service._id;
                                    setSetupSelectedServices(prev => 
                                        prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
                                    );
                                }}
                                style={{
                                    padding: "15px",
                                    borderRadius: "10px",
                                    background: setupSelectedServices.includes(service.id || service._id) ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)",
                                    border: `1px solid ${setupSelectedServices.includes(service.id || service._id) ? "#fff" : "rgba(255,255,255,0.1)"}`,
                                    cursor: "pointer",
                                    display: "flex",
                                    justifyContent: "space-between",
                                    alignItems: "center"
                                }}
                            >
                                <div>
                                    <div style={{ color: "#fff", fontWeight: "bold" }}>{service.name}</div>
                                    <div style={{ color: "rgba(255,255,255,0.6)", fontSize: "13px" }}>{service.duration} min - ${service.price}</div>
                                </div>
                                {setupSelectedServices.includes(service.id || service._id) && (
                                    <div style={{ color: "#fff" }}>✓</div>
                                )}
                            </div>
                        ))}
                        {setupAvailableServices.length === 0 && (
                            <div style={{ color: "rgba(255,255,255,0.6)" }}>No hay servicios creados en la organización.</div>
                        )}
                    </div>
                </QuestionCard>
            );
        }

        if (currentStepIndex === 2) {
            const DAY_LABELS = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
            const getDayLabel = (day: number) => DAY_LABELS[day];

            const canProceed = () => {
                if (!workingDaysMode) return false;
                if (workingDaysMode === "custom") {
                    if (customDays.length === 0) return false;
                    if (unifiedCustomSchedule === null) return false;
                }
                return true;
            };

            return (
                <QuestionCard
                    isActive={true}
                    title="Horarios de Atención"
                    description="¿En qué días y horarios trabajará este colaborador?"
                    step={setupMissingServices ? 3 : 2}
                    totalSteps={setupMissingServices && setupMissingSchedules ? 3 : 2}
                    onNext={async () => {
                        if (!canProceed()) {
                            alert("Por favor completa la configuración de días y horarios");
                            return;
                        }
                        setIsCreating(true);
                        try {
                            const days = workingDaysMode === "mon-fri" ? [1,2,3,4,5] : 
                                         workingDaysMode === "mon-sat" ? [1,2,3,4,5,6] :
                                         workingDaysMode === "custom" ? customDays :
                                         [0,1,2,3,4,5,6]; // mon-sun

                            for (const day of days) {
                                let dayOpenTime = openTime;
                                let dayCloseTime = closeTime;
                                let dayHasBreak = hasBreak;
                                let dayBreakStart = breakStart;
                                let dayBreakEnd = breakEnd;

                                if (workingDaysMode === "custom" && unifiedCustomSchedule === false) {
                                    const customSettings = customSchedulesMap[day];
                                    if (customSettings) {
                                        dayOpenTime = customSettings.openTime;
                                        dayCloseTime = customSettings.closeTime;
                                        dayHasBreak = customSettings.hasBreak;
                                        dayBreakStart = customSettings.breakStart;
                                        dayBreakEnd = customSettings.breakEnd;
                                    } else {
                                        // Defaults if missing
                                        dayOpenTime = "09:00";
                                        dayCloseTime = "18:00";
                                        dayHasBreak = false;
                                        dayBreakStart = "13:00";
                                        dayBreakEnd = "14:00";
                                    }
                                }

                                const schedules = dayHasBreak ? [
                                    { from: dayOpenTime, to: dayBreakStart, disabled: false },
                                    { from: dayBreakEnd, to: dayCloseTime, disabled: false }
                                ] : [
                                    { from: dayOpenTime, to: dayCloseTime, disabled: false }
                                ];

                                await API.post<any>("schedules/create", {
                                    companyId: createdCompanyId,
                                    employeeId: employeeId,
                                    weekDay: day,
                                    schedules: schedules,
                                    sessionUser: SessionInfo.userId
                                });
                            }
                            setIsSuccess(true);
                        } catch (e) {
                            console.error(e);
                            alert("Ocurrió un error al guardar los horarios");
                        } finally {
                            setIsCreating(false);
                        }
                    }}
                    nextLabel="Guardar Horarios"
                    disableNext={isCreating || !canProceed()}
                >
                    <div style={{ display: "flex", flexDirection: "column", gap: "10px", marginBottom: "20px" }}>
                        <div 
                            style={{ padding: "15px", borderRadius: "10px", background: workingDaysMode === "mon-fri" ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${workingDaysMode === "mon-fri" ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }}
                            onClick={() => setWorkingDaysMode("mon-fri")}
                        >
                            <h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>Lunes a Viernes</h4>
                            <p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>Horario comercial estándar</p>
                        </div>
                        <div 
                            style={{ padding: "15px", borderRadius: "10px", background: workingDaysMode === "mon-sat" ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${workingDaysMode === "mon-sat" ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }}
                            onClick={() => setWorkingDaysMode("mon-sat")}
                        >
                            <h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>Lunes a Sábado</h4>
                            <p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>Jornada extendida</p>
                        </div>
                        <div 
                            style={{ padding: "15px", borderRadius: "10px", background: workingDaysMode === "mon-sun" ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${workingDaysMode === "mon-sun" ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }}
                            onClick={() => setWorkingDaysMode("mon-sun")}
                        >
                            <h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>Todos los días</h4>
                            <p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>Lunes a Domingo</p>
                        </div>
                        <div 
                            style={{ padding: "15px", borderRadius: "10px", background: workingDaysMode === "custom" ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.05)", border: `1px solid ${workingDaysMode === "custom" ? "#fff" : "rgba(255,255,255,0.1)"}`, cursor: "pointer", transition: "all 0.2s" }}
                            onClick={() => setWorkingDaysMode("custom")}
                        >
                            <h4 style={{ color: "#fff", margin: "0 0 5px 0", fontSize: "16px" }}>Otros / Personalizado</h4>
                            <p style={{ color: "rgba(255,255,255,0.6)", margin: 0, fontSize: "13px" }}>Selecciona días específicos y horarios variables</p>
                        </div>
                    </div>

                    {workingDaysMode === "custom" && (
                        <div style={{ marginBottom: "25px", padding: "20px", background: "rgba(0,0,0,0.2)", borderRadius: "15px" }}>
                            <h4 style={{ color: "white", marginBottom: "15px" }}>Selecciona los días:</h4>
                            <div style={{ display: "flex", flexWrap: "wrap", gap: "10px", marginBottom: "20px" }}>
                                {[1,2,3,4,5,6,0].map(day => (
                                    <div
                                        key={day}
                                        onClick={() => setCustomDays(prev => prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day].sort())}
                                        style={{
                                            padding: "8px 16px",
                                            borderRadius: "20px",
                                            cursor: "pointer",
                                            background: customDays.includes(day) ? "var(--wine-red)" : "rgba(255,255,255,0.1)",
                                            color: "white",
                                            fontWeight: customDays.includes(day) ? "bold" : "normal",
                                            transition: "all 0.2s",
                                            border: `1px solid ${customDays.includes(day) ? "var(--wine-red)" : "transparent"}`
                                        }}
                                    >
                                        {getDayLabel(day)}
                                    </div>
                                ))}
                            </div>

                            {customDays.length > 0 && (
                                <div style={{ marginTop: "20px" }}>
                                    <h4 style={{ color: "white", marginBottom: "15px", fontSize: "15px" }}>¿Utiliza el mismo horario para todos estos días?</h4>
                                    <div style={{ display: "flex", gap: "10px" }}>
                                        <button 
                                            className={style.primaryButton} 
                                            style={{ flex: 1, background: unifiedCustomSchedule === true ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }}
                                            onClick={() => setUnifiedCustomSchedule(true)}
                                        >
                                            Sí, el mismo
                                        </button>
                                        <button 
                                            className={style.primaryButton} 
                                            style={{ flex: 1, background: unifiedCustomSchedule === false ? "var(--wine-red)" : "rgba(255,255,255,0.1)", color: "white" }}
                                            onClick={() => setUnifiedCustomSchedule(false)}
                                        >
                                            No, personalizar por día
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {((workingDaysMode && workingDaysMode !== "custom") || (workingDaysMode === "custom" && unifiedCustomSchedule === true && customDays.length > 0)) && (
                        <div className={style.timeSettingsContainer}>
                            <h4 style={{ color: "rgba(255,255,255,0.9)", marginBottom: "15px" }}>Horario de apertura y cierre</h4>
                            <div style={{ display: "flex", gap: "20px", marginBottom: "20px" }}>
                                <QuestionInput 
                                    label="Hora de Apertura"
                                    type="time"
                                    value={openTime}
                                    onChange={(e) => setOpenTime(e.target.value)}
                                />
                                <QuestionInput 
                                    label="Hora de Cierre"
                                    type="time"
                                    value={closeTime}
                                    onChange={(e) => setCloseTime(e.target.value)}
                                />
                            </div>

                            <div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "20px" }}>
                                <input 
                                    type="checkbox" 
                                    id="hasBreak"
                                    checked={hasBreak === true}
                                    onChange={(e) => setHasBreak(e.target.checked)}
                                    style={{ width: "18px", height: "18px" }}
                                />
                                <label htmlFor="hasBreak" style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer" }}>
                                    Tiene horario de descanso (almuerzo)
                                </label>
                            </div>

                            {hasBreak && (
                                <div style={{ display: "flex", gap: "20px", marginBottom: "20px", padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "10px" }}>
                                    <QuestionInput 
                                        label="Inicio de Descanso"
                                        type="time"
                                        value={breakStart}
                                        onChange={(e) => setBreakStart(e.target.value)}
                                    />
                                    <QuestionInput 
                                        label="Fin de Descanso"
                                        type="time"
                                        value={breakEnd}
                                        onChange={(e) => setBreakEnd(e.target.value)}
                                    />
                                </div>
                            )}
                        </div>
                    )}

                    {workingDaysMode === "custom" && unifiedCustomSchedule === false && customDays.length > 0 && (
                        <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
                            {customDays.map(day => {
                                const ds = customSchedulesMap[day] || { openTime: "09:00", closeTime: "18:00", hasBreak: false, breakStart: "13:00", breakEnd: "14:00" };
                                const updateDS = (updates: any) => {
                                    setCustomSchedulesMap(prev => ({...prev, [day]: { ...ds, ...updates } }));
                                };

                                return (
                                    <div key={day} style={{ padding: "15px", background: "rgba(0,0,0,0.2)", borderRadius: "15px", border: "1px solid rgba(255,255,255,0.1)" }}>
                                        <h4 style={{ color: "white", marginBottom: "15px", borderBottom: "1px solid rgba(255,255,255,0.1)", paddingBottom: "10px" }}>
                                            Configuración para {getDayLabel(day)}
                                        </h4>
                                        <div style={{ display: "flex", gap: "20px", marginBottom: "15px" }}>
                                            <QuestionInput label="Apertura" type="time" value={ds.openTime} onChange={(e) => updateDS({ openTime: e.target.value })} />
                                            <QuestionInput label="Cierre" type="time" value={ds.closeTime} onChange={(e) => updateDS({ closeTime: e.target.value })} />
                                        </div>
                                        <div style={{ display: "flex", alignItems: "center", gap: "10px", marginBottom: "15px" }}>
                                            <input type="checkbox" id={`hasBreak_${day}`} checked={ds.hasBreak === true} onChange={(e) => updateDS({ hasBreak: e.target.checked })} style={{ width: "18px", height: "18px" }} />
                                            <label htmlFor={`hasBreak_${day}`} style={{ color: "rgba(255,255,255,0.8)", cursor: "pointer", fontSize: "14px" }}>
                                                Descanso
                                            </label>
                                        </div>
                                        {ds.hasBreak && (
                                            <div style={{ display: "flex", gap: "20px", padding: "10px", background: "rgba(0,0,0,0.3)", borderRadius: "10px" }}>
                                                <QuestionInput label="Inicio" type="time" value={ds.breakStart} onChange={(e) => updateDS({ breakStart: e.target.value })} />
                                                <QuestionInput label="Fin" type="time" value={ds.breakEnd} onChange={(e) => updateDS({ breakEnd: e.target.value })} />
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </QuestionCard>
            );
        }

        return null;
    };
    const renderFlow = () => {
        if (allOrganizations.length > 1 && !createdCompanyId && action !== "new-org") {
            return (
                <QuestionCard 
                    isActive={true}
                    title="Selecciona la Organización"
                    description="¿A qué negocio deseas aplicar estos cambios?"
                    onNext={() => {}}
                    disableNext={true}
                    nextLabel=""
                >
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', width: '100%' }}>
                        {allOrganizations.map(org => (
                            <div 
                                key={org.id || org._id}
                                onClick={() => loadOrganizationContext(org)}
                                style={{ 
                                    padding: '15px', borderRadius: '12px', cursor: 'pointer',
                                    background: 'rgba(255,255,255,0.05)',
                                    border: '2px solid transparent',
                                    color: 'white', transition: 'all 0.2s ease',
                                    display: 'flex', flexDirection: 'column', alignItems: 'center'
                                }}
                                onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--wine-red)'}
                                onMouseLeave={(e) => e.currentTarget.style.borderColor = 'transparent'}
                            >
                                <h4 style={{ margin: '0 0 5px 0' }}>{org.name}</h4>
                                <p style={{ margin: 0, fontSize: '12px', opacity: 0.7 }}>{org.street} {org.streetNumber}, {org.city}</p>
                            </div>
                        ))}
                    </div>
                </QuestionCard>
            );
        }

        if (flowId === "setup-collaborator") return renderSetupCollaboratorFlow();
        if (flowId === "new-collaborator") return renderNewCollaboratorFlow();
        if (flowId === "disable-schedule") return renderDisableScheduleFlow();
        if (flowId === "override-schedule") return renderOverrideScheduleFlow();
        if (flowId === "update-schedule") return renderUpdateScheduleFlow();
        if (isAddingAnotherService || flowId === "onboarding-service") return renderOnboardingServiceFlow();
        if (flowId === "onboarding-schedule") return renderOnboardingScheduleFlow();
        return renderOnboardingOrgFlow(); // Default to org flow
    };

    if (isSuccess) {
        const getSuccessMessage = () => {
            if (action === "new-service") return "Has agregado tu nuevo servicio exitosamente.";
            if (action === "edit-schedule") return "Tus horarios se han actualizado exitosamente.";
            if (action === "edit-location") return "La ubicación de tu negocio ha sido actualizada.";
            if (action === "edit-contact") return "Tus datos de contacto han sido actualizados.";
            if (action === "edit-appearance") return "La apariencia de tu negocio ha sido actualizada.";
            if (flowId === "override-schedule" || flowId === "disable-schedule") return "El horario especial ha sido guardado exitosamente.";
            if (flowId === "new-collaborator") return "El colaborador fue invitado exitosamente.";
            if (flowId === "setup-collaborator") return "El colaborador ha sido configurado exitosamente y ya puede comenzar a recibir reservas.";
            if (action) return "Tus cambios se han guardado exitosamente.";
            return "Has configurado exitosamente tu negocio. Todo está listo para que empieces a recibir reservas y gestionar tu agenda como un profesional.";
        };

        return (
            <div style={{
                position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh',
                background: 'linear-gradient(135deg, #1a0515 0%, #300018 100%)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                zIndex: 9999, overflow: 'hidden', padding: '20px', boxSizing: 'border-box'
            }}>
                <div style={{
                    width: '120px', height: '120px', borderRadius: '50%', background: 'rgba(255,255,255,0.1)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '30px',
                    boxShadow: '0 0 50px rgba(255, 255, 255, 0.2)',
                    animation: 'pulse 2s infinite ease-in-out'
                }}>
                    <span style={{ fontSize: '60px' }}>🎉</span>
                </div>
                
                <h1 style={{ 
                    color: 'white', fontSize: '32px', marginBottom: '15px', textAlign: 'center',
                    textShadow: '0 2px 10px rgba(0,0,0,0.5)'
                }}>
                    ¡Felicitaciones!
                </h1>
                
                <p style={{ 
                    color: 'rgba(255,255,255,0.8)', fontSize: '18px', maxWidth: '500px', 
                    textAlign: 'center', marginBottom: '40px', lineHeight: '1.5'
                }}>
                    {getSuccessMessage()}
                </p>

                <button 
                    onClick={() => {
                        if (action) {
                            router.push("/admin/assistant");
                        } else {
                            window.location.href = "/landing/dashboard";
                        }
                    }}
                    style={{
                        padding: '16px 40px', fontSize: '18px', fontWeight: 'bold',
                        background: 'white', color: 'var(--wine-red)', border: 'none',
                        borderRadius: '30px', cursor: 'pointer',
                        boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
                        transition: 'transform 0.2s, box-shadow 0.2s'
                    }}
                    onMouseOver={(e) => {
                        e.currentTarget.style.transform = 'translateY(-2px)';
                        e.currentTarget.style.boxShadow = '0 6px 20px rgba(255,255,255,0.3)';
                    }}
                    onMouseOut={(e) => {
                        e.currentTarget.style.transform = 'translateY(0)';
                        e.currentTarget.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
                    }}
                >
                    {action ? "Volver al Menú Principal" : "Ir a mi Panel de Control"}
                </button>

                <style>{`
                    @keyframes pulse {
                        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.4); }
                        70% { transform: scale(1.05); box-shadow: 0 0 0 30px rgba(255, 255, 255, 0); }
                        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
                    }
                `}</style>
            </div>
        );
    }

    return (
        <div className={style.engineContainer}>
            <div className={style.header}>
                <div className={style.backButton} onClick={handleBack}>
                    <ArrowBackIcon fontSize="small" style={{ marginRight: '5px' }} /> 
                    <span>Volver</span>
                </div>
                <div className={style.flowTitle}>
                    Configuración de Negocio
                </div>
                <div className={style.progressIndicator}>
                    {/* Placeholder for progress dots or percentage */}
                    Paso {currentStepIndex}
                </div>
            </div>

            <div className={style.stepContent}>
                {renderFlow()}
            </div>
        </div>
    );
}
