var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import sha256 from 'sha256';
import doctorApi from 'src/lib/api/services/doctor';
import { GlobalCtx } from '../Providers/GlobalProvider';
import { useAppDispatch, useAppSelector } from 'src/app/redux/store';
import { setScheduleLoading, updateAppointment } from 'src/app/redux/slices/doctor';
import { track } from 'src/lib/common/helpers/tracking';
import { useForm } from 'src/lib/common/hooks/useForm';
import { getFiltersFromUrl, getVisitorId, hasProgram, } from 'src/lib/common/helpers';
import { canadaZipValidator, isValidZip, makePath, msToMinsAndSecs, setCookie, } from 'src/lib/utils';
import Modal from 'src/components/Modal/ModalModule';
import Profile from '../../components/DoctorProfile';
import { DocLocViews, ContactTime } from 'src/lib/types/types';
import { DOC_TYPE_NAME, numRegExp } from 'src/lib/constants';
import { PatientType, SFDCPatientType, } from 'src/lib/types/types';
import SubmitNoti from './SubmitNoti';
import MaskedInputNumber from '../MaskedInputNumber';
import Button from 'src/components/Button';
import CheckBox from 'src/components/CheckBox';
import Input from 'src/components/Input';
import Radio from 'src/components/Radio';
import TextArea from 'src/components/TextArea';
import Loader from '../Loader';
import css from './AppointmentForm.module.scss';
import { HfdLogo } from 'src/lib/utils';
import { _cx } from 'src/utility/class';
var cx = _cx(css);
var getDateDiffInYears = function (date) {
    var today = new Date();
    var m = today.getMonth() - date.getMonth();
    var age = today.getFullYear() - date.getFullYear();
    var st = m < 0 || (m === 0 && today.getDate() < date.getDate());
    return st ? age - 1 : age;
};
var isWithinTimeRange = function (startTime, endTime) {
    if (!startTime || !endTime) {
        return true;
    }
    try {
        // Get current time in EST timezone
        var now = new Date();
        var estTime_1 = new Date(now.toLocaleString('en-US', { timeZone: 'America/New_York' }));
        // Check if current day is weekend (Saturday = 6, Sunday = 0)
        var currentDay = estTime_1.getDay();
        if (currentDay === 0 || currentDay === 6) {
            return false; // Weekend - not within business hours
        }
        // Parse start and end times (assuming format like "HH:MM" or "HH:MM:SS")
        var parseTime = function (timeStr) {
            var _a = __read(timeStr.split(':'), 3), hours = _a[0], minutes = _a[1], _b = _a[2], seconds = _b === void 0 ? '00' : _b;
            var timeDate = new Date(estTime_1);
            timeDate.setHours(parseInt(hours || '0'), parseInt(minutes || '0'), parseInt(seconds || '0'), 0);
            return timeDate;
        };
        var startDate = parseTime(startTime);
        var endDate = parseTime(endTime);
        // If end time is before start time, it means the range spans midnight
        if (endDate < startDate) {
            return estTime_1 >= startDate || estTime_1 <= endDate;
        }
        return estTime_1 >= startDate && estTime_1 <= endDate;
    }
    catch (error) {
        console.error('Error parsing time range:', error);
        return false;
    }
};
export default function AppointmentForm(_a) {
    var _this = this;
    var t = _a.t, isMobile = _a.isMobile, profileId = _a.profileId, data = _a.data, _b = _a.isModal, isModal = _b === void 0 ? false : _b, closeModal = _a.closeModal;
    var dispatch = useAppDispatch();
    var _c = __read(useState(false), 2), isMounted = _c[0], setIsMounted = _c[1];
    var _d = __read(useState(false), 2), ageLimit = _d[0], setAgeLimit = _d[1];
    var _e = __read(useState(false), 2), teenError = _e[0], setTeenError = _e[1];
    var _f = __read(useState(false), 2), isSubmitted = _f[0], setIsSubmitted = _f[1];
    var _g = __read(useState(new Date()), 1), startedAt = _g[0];
    var _h = __read(useState(false), 2), preferredContactTimeEnabled = _h[0], setPreferredContactTimeEnabled = _h[1];
    var sendAppointment = useContext(GlobalCtx).sendAppointment;
    var _j = useMemo(function () { return getFiltersFromUrl(); }, []), vivera = _j.vivera, program = _j.program;
    var scheduleLoading = useAppSelector(function (state) { return state.doctor.scheduleLoading; });
    var appointment = useAppSelector(function (state) { return state.doctor.appointment; });
    var _k = useAppSelector(function (state) { return state.config.config; }), heetFormId = _k.heetFormId, zipUtility = _k.zipUtility, dobUtility = _k.dobUtility, mobileUtility = _k.mobileUtility, trackingUtility = _k.trackingUtility, privacyPolicyUrl = _k.privacyPolicyUrl, appointmentFormCookie = _k.appointmentFormCookie, ageRestriction = _k.ageRestriction, optin = _k.optin, appointmentExtraFields = _k.appointmentExtraFields, isLatam = _k.isLatam, hideAppointmentFields = _k.hideAppointmentFields, thankyouPageUrl = _k.thankyouPageUrl, modalsData = _k.modalsData, customAppointmentUrl = _k.customAppointmentUrl, enableHeartlandButtonSwap = _k.enableHeartlandButtonSwap, scheduleAppointmentUrl = _k.scheduleAppointmentUrl, zocdocScheduleAppointmentUrl = _k.zocdocScheduleAppointmentUrl, localeId = _k.localeId, country = _k.country, tierPins = _k.tierPins, programData = _k.programData, availablePrograms = _k.availablePrograms, enableZocdoc = _k.enableZocdoc, enableNexHealth = _k.enableNexHealth, nexHealthScheduleAppointmentUrl = _k.nexHealthScheduleAppointmentUrl, appointmentButtonSecquence = _k.appointmentButtonSecquence;
    var isCa = localeId === null || localeId === void 0 ? void 0 : localeId.toLowerCase().includes('ca');
    var partner = useAppSelector(function (state) { return state.common; }).partner;
    // const program = useAppSelector((state: Store) => state.filter.filters.program);
    var patientType = appointment.patientType, preferredContactTime = appointment.preferredContactTime, firstName = appointment.firstName, lastName = appointment.lastName, dateOfBirth = appointment.dateOfBirth, zip = appointment.zip, mobile = appointment.mobile, email = appointment.email, comments = appointment.comments, alignInfoAgreed = appointment.alignInfoAgreed, alignInfoAgreed2 = appointment.alignInfoAgreed2;
    var mobileMaxLength = mobileUtility.maxLength, mobileMask = mobileUtility.mask, mobilePrefix = mobileUtility.prefix;
    var acceptedProgram = (programData === null || programData === void 0 ? void 0 : programData.find(function (t) {
        return program &&
            t.filterValue === program &&
            t.subleadSource &&
            data.dynamic_programs[t.programKey] === 't' &&
            isWithinTimeRange(t.startTime, t.endTime);
    })) ||
        (programData === null || programData === void 0 ? void 0 : programData.find(function (t) {
            return data.dynamic_programs[t.programKey] === 't' &&
                !(availablePrograms === null || availablePrograms === void 0 ? void 0 : availablePrograms.includes(t.filterValue)) &&
                isWithinTimeRange(t.startTime, t.endTime);
        }));
    var tierData = tierPins.find(function (pins) { return pins.segmentCode === data.advantage_level; });
    var getDobValidator = useCallback(function (ageMin) { return ({
        custom: {
            isValid: function (value) {
                var _a;
                var _b = dobUtility, mask = _b.mask, separator = _b.separator;
                var maskParts = mask.split(separator);
                var indices = [];
                var maskIndices = [];
                for (var i = 0; i < value.length; i++) {
                    if (value[i] === separator && (i === 2 || i === 5) && !indices.includes(i)) {
                        indices.push(i);
                    }
                }
                for (var i = 0; i < mask.length; i++) {
                    if (mask[i] === separator && (i === 2 || i === 5) && !maskIndices.includes(i)) {
                        maskIndices.push(i);
                    }
                }
                if (value.length !== mask.length ||
                    value
                        .split('')
                        .reduce(function (numCount, char) { return numCount + Number(numRegExp.test(char)); }, 0) !==
                        (maskParts.length < 3 ? 6 : 8) ||
                    indices.length !== maskIndices.length) {
                    return false;
                }
                var dateParts = value
                    .split(separator)
                    .reduce(function (parts, part) { return __spreadArray(__spreadArray([], __read(parts), false), [Number(part)], false); }, []);
                var month = dateParts[isLatam ? 1 : 0];
                if (month > 12)
                    return false;
                if (month < 1)
                    return false;
                var ageRestrictionAge = ageRestriction ? ((_a = ageRestriction[0]) === null || _a === void 0 ? void 0 : _a.age) || 13 : 13;
                if (maskParts.length === 3) {
                    var date = dateParts[isLatam ? 0 : 1];
                    if (date < 1)
                        return false;
                    var year = dateParts[2];
                    if (year < 1900)
                        return false;
                    var lastDayInMonth = new Date(year, month, 0).getDate();
                    if (date > lastDayInMonth)
                        return false;
                    var dob = new Date(year, month - 1, date);
                    if (dob.getTime() > new Date().getTime())
                        return false;
                    if (ageMin && getDateDiffInYears(dob) < ageRestrictionAge) {
                        return false;
                    }
                }
                if (maskParts.length === 2) {
                    var today = new Date();
                    var year = dateParts[1];
                    if (year < 1900 || year > today.getFullYear())
                        return false;
                    var dob = new Date(year, month - 1, 1);
                    if (ageMin && getDateDiffInYears(dob) < ageRestrictionAge) {
                        return false;
                    }
                }
                return true;
            },
            message: 'Invalid Date of Birth.',
        },
    }); }, []);
    var _l = useForm({
        customData: appointment,
        onChangeDispatch: updateAppointment,
        validations: __assign(__assign({ firstName: {
                custom: {
                    isValid: function (value) { return value.length > 0; },
                    message: 'First Name must be at least 1 character long.',
                },
            }, lastName: {
                custom: {
                    isValid: function (value) { return value.length > 0; },
                    message: 'Last Name must be at least 1 character long.',
                },
            }, dateOfBirth: getDobValidator(ageLimit), zip: {
                custom: {
                    isValid: function (value) { return (showZip ? isValidZip(value.trim(), isCa) : true); },
                    message: 'ZIP Code must be valid.',
                },
            }, mobile: {
                custom: {
                    isValid: function (value) {
                        var indices = [];
                        for (var i = 0; i < value.length; i++) {
                            if (value[i] === '-' && (i === 2 || i === 5) && !indices.includes(i)) {
                                indices.push(i);
                            }
                        }
                        var numCount = value
                            .split('')
                            .reduce(function (numCount, char) { return numCount + Number(numRegExp.test(char)); }, 0);
                        return numCount + indices.length === mobileMaxLength;
                    },
                    message: 'Invalid phone number.',
                },
            }, email: {
                custom: {
                    isValid: function (value) {
                        return new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value);
                    },
                    message: 'Please provide a valid email address.',
                },
            }, comments: {
                custom: {
                    isValid: function () { return true; },
                },
            } }, (preferredContactTimeEnabled && {
            preferredContactTime: {
                custom: {
                    isValid: function () { return true; },
                },
            },
        })), { alignInfoAgreed: {
                custom: {
                    isValid: function (value) { return ((optin === null || optin === void 0 ? void 0 : optin.mandatory) ? Boolean(value) === true : true); },
                    message: 'Please select to proceed.',
                },
            }, alignInfoAgreed2: {
                custom: {
                    isValid: function (value) { return ((optin === null || optin === void 0 ? void 0 : optin.mandatory) && (optin === null || optin === void 0 ? void 0 : optin.secondOptinLabel) ? Boolean(value) === true : true); },
                    message: 'Please select to proceed.',
                },
            } }),
        errorOnInit: true,
    }), handleChange = _l.handleChange, errors = _l.errors, checkErrors = _l.checkErrors;
    var errorKeys = useMemo(function () { return Object.keys(errors); }, [errors]);
    var _m = __read(useState(false), 2), showAgeModal = _m[0], setShowAgeModal = _m[1];
    var _o = __read(useState(!!(appointmentExtraFields === null || appointmentExtraFields === void 0 ? void 0 : appointmentExtraFields.comment)), 1), showCommentField = _o[0];
    var _p = __read(useState(false), 2), showError = _p[0], setShowError = _p[1];
    var _q = __read(useState(false), 2), firstNameFocused = _q[0], setFirstNameFocused = _q[1];
    var _r = __read(useState(false), 2), lastNameFocused = _r[0], setLastNameFocused = _r[1];
    var _s = __read(useState(false), 2), dobFocused = _s[0], setDobFocused = _s[1];
    var _t = __read(useState(false), 2), zipFocused = _t[0], setZipFocused = _t[1];
    var _u = __read(useState(false), 2), mobileFocused = _u[0], setMobileFocused = _u[1];
    var _v = __read(useState(false), 2), emailFocused = _v[0], setEmailFocused = _v[1];
    var _w = __read(useState(false), 2), intracted = _w[0], setIntracted = _w[1];
    var isDobLabelValid = useMemo(function () {
        return (dobFocused && dateOfBirth !== (dobUtility === null || dobUtility === void 0 ? void 0 : dobUtility.mask)) || dobFocused
            ? !errorKeys.includes('dateOfBirth')
            : true;
    }, [dateOfBirth, dobUtility, dobFocused, errorKeys]);
    var isZipLabelValid = useMemo(function () { return (zip.length > 0 || zipFocused ? !errorKeys.includes('zip') : true); }, [zip, zipFocused, errorKeys]);
    var isMobileLabelValid = useMemo(function () {
        return (mobileFocused && mobile !== mobileMask) || mobileFocused
            ? !errorKeys.includes('mobile')
            : true;
    }, [mobile, mobileMask, mobileFocused, errorKeys]);
    var isEmailLabelValid = useMemo(function () { return (email.length > 0 || emailFocused ? !errorKeys.includes('email') : true); }, [email, emailFocused, errorKeys]);
    var showZip = useMemo(function () { return !hideAppointmentFields || (hideAppointmentFields && !!!hideAppointmentFields.zip); }, [hideAppointmentFields]);
    var handleSubmit = useCallback(function (e) { return __awaiter(_this, void 0, void 0, function () {
        var doErrorChecks, formHasError, getAgeGroup, subleadSource, errorOrResult, hashed_email;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    e.preventDefault();
                    doErrorChecks = function () { return __awaiter(_this, void 0, void 0, function () {
                        var hasError, _a, mask, separator, dobParts, dobMonth, dobYear, isOnlyMonth, today, dob, setAgeErrors;
                        return __generator(this, function (_b) {
                            hasError = errorKeys.length > 0;
                            if (hasError) {
                                setShowError(true);
                                ['firstName', 'lastName', 'dateOfBirth', 'zip', 'mobile', 'email'].some(function (inputName) {
                                    var _a;
                                    if (errorKeys.includes(inputName)) {
                                        (_a = document.getElementById("".concat(inputName, "-input"))) === null || _a === void 0 ? void 0 : _a.focus();
                                        return true;
                                    }
                                });
                                return [2 /*return*/, true];
                            }
                            _a = dobUtility, mask = _a.mask, separator = _a.separator;
                            dobParts = dateOfBirth.split(separator);
                            dobMonth = Number(dobParts[isLatam ? 1 : 0]);
                            dobYear = Number(dobParts[dobParts.length - 1]);
                            isOnlyMonth = mask.split(separator).length === 2;
                            today = new Date();
                            dob = new Date(dobYear, dobMonth - 1, !isOnlyMonth ? Number(dobParts[isLatam ? 0 : 1]) : today.getDate());
                            setAgeErrors = function () {
                                setAgeLimit(true);
                                checkErrors(undefined, { dateOfBirth: getDobValidator(true) });
                                setShowError(true);
                                setShowAgeModal(true);
                                setTeenError(true);
                                return true;
                            };
                            if (ageRestriction) {
                                return [2 /*return*/, ageRestriction.some(function (ar) {
                                        var _a;
                                        var validAge = ar.age || 13;
                                        if (patientType === PatientType[(_a = ar.patientType) === null || _a === void 0 ? void 0 : _a.toUpperCase()] &&
                                            getDateDiffInYears(dob) < validAge) {
                                            return setAgeErrors();
                                        }
                                    })];
                            }
                            if (patientType === PatientType.TEEN && getDateDiffInYears(dob) < 13) {
                                return [2 /*return*/, setAgeErrors()];
                            }
                            if ((optin === null || optin === void 0 ? void 0 : optin.mandatory) && !alignInfoAgreed) {
                                return [2 /*return*/, true];
                            }
                            return [2 /*return*/, false];
                        });
                    }); };
                    return [4 /*yield*/, doErrorChecks()];
                case 1:
                    formHasError = _a.sent();
                    if (formHasError)
                        return [2 /*return*/];
                    dispatch(setScheduleLoading(true));
                    getAgeGroup = function () {
                        if (patientType === PatientType.ADULT)
                            return SFDCPatientType.ADULT;
                        if (patientType === PatientType.PARENT)
                            return SFDCPatientType.PARENT;
                        return SFDCPatientType.TEEN;
                    };
                    window.scrollTo(0, 0);
                    subleadSource = acceptedProgram && acceptedProgram.subleadSource ? acceptedProgram.subleadSource : '';
                    return [4 /*yield*/, doctorApi.postAppointment(__assign(__assign({ docID: Number(profileId), firstName: firstName, lastName: lastName, email: email, comments: comments, ageGroup: getAgeGroup(), phone: mobile.replace('-', '').replace('-', ''), zip: zip, age: dateOfBirth, leadSource: vivera ? 'Vivera Doctor Locator' : 'Doc Locator', optin: alignInfoAgreed, optin2: alignInfoAgreed2, vid: getVisitorId(), stage_in_funnel__c: 'Low', minutes_on_site: msToMinsAndSecs(new Date().getTime() - startedAt.getTime()), sub_lead_source: subleadSource }, (preferredContactTimeEnabled && { preferred_contact_time: preferredContactTime })), (partner && { corporateBenefitsPartner: (partner === null || partner === void 0 ? void 0 : partner.sfdcValue) || (partner === null || partner === void 0 ? void 0 : partner.name) })), sendAppointment)];
                case 2:
                    errorOrResult = _a.sent();
                    if (errorOrResult != null) {
                        hashed_email = sha256(email.toLowerCase().trim());
                        track('doc_loc_help_me_schedule_completed', __assign(__assign(__assign(__assign({ form_name: heetFormId, user_category: getAgeGroup(), profile_number: profileId, contact_consent: alignInfoAgreed ? 'opt-in' : 'opt-out', profile_service: vivera ? 'vivera retainer' : 'invisalign aligner' }, (data.doctor_type
                            ? {
                                profile_designation: DOC_TYPE_NAME[data.doctor_type],
                            }
                            : {})), (data.advantage_level
                            ? { profile_tier: (tierData === null || tierData === void 0 ? void 0 : tierData.label) || t.no_tier_event_label }
                            : {})), ((trackingUtility === null || trackingUtility === void 0 ? void 0 : trackingUtility.hashEmailAndPhone) === 'true'
                            ? {
                                uhe: hashed_email,
                                uhp: sha256(mobile.replace(/[\D_]/g, '')),
                            }
                            : {})), { is_ols: data.is_heartland_ols, hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal') }));
                        setCookie('appointmentForm', JSON.stringify(appointment));
                        if (acceptedProgram && (acceptedProgram === null || acceptedProgram === void 0 ? void 0 : acceptedProgram.thankyouPageUrl)) {
                            window.location.href = acceptedProgram.thankyouPageUrl;
                        }
                        else if (thankyouPageUrl) {
                            window.location.href = thankyouPageUrl;
                        }
                        else {
                            setIsSubmitted(true);
                        }
                    }
                    dispatch(setScheduleLoading(false));
                    return [2 /*return*/];
            }
        });
    }); }, [errorKeys, appointment]);
    // const optinModalData: ModalData = modalsData.find((data) => data.id === 'optinModal')!;
    var ageModalData = modalsData.find(function (data) { return data.id === 'ageModal'; });
    useEffect(function () {
        var _a;
        appointmentFormCookie &&
            ((_a = appointmentFormCookie.profileIds) === null || _a === void 0 ? void 0 : _a.includes(profileId)) &&
            setIsSubmitted(true);
        setIsMounted(true);
        if ((optin === null || optin === void 0 ? void 0 : optin.preChecked) !== undefined) {
            dispatch(updateAppointment({
                alignInfoAgreed: optin.preChecked,
                alignInfoAgreed2: optin.preChecked,
            }));
        }
    }, []);
    useEffect(function () {
        setPreferredContactTimeEnabled(document.body.classList.contains('preferredContactTimeEnable'));
    }, []);
    useEffect(function () {
        if (intracted) {
            track('doc_loc_help_me_schedule_started', {
                form_name: heetFormId,
                hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal'),
            });
        }
    }, [intracted]);
    if (isSubmitted)
        return _jsx(SubmitNoti, { t: t });
    var customRAURL = customAppointmentUrl.find(function (it) {
        return it.docID === data.location_id;
    });
    var isHeartland = enableHeartlandButtonSwap && data.is_heartland_ols;
    var isHfdEnabled = document.body.classList.contains('hfdEnable') &&
        data &&
        hasProgram(data, 'is_hfd_prequal') &&
        data.hfd_prequal_url;
    var isZocdocEnabled = enableZocdoc && hasProgram(data, 'is_zocdoc') && zocdocScheduleAppointmentUrl;
    var isNexHealthEnabled = enableNexHealth && hasProgram(data, 'is_nexhealth') && nexHealthScheduleAppointmentUrl;
    var defaultButtonSequence = ['zocdoc', 'nexhealth', 'heartland', 'customRAUrl', 'hfd', 'default'];
    var buttonSequence = (appointmentButtonSecquence === null || appointmentButtonSecquence === void 0 ? void 0 : appointmentButtonSecquence.length)
        ? appointmentButtonSecquence
        : defaultButtonSequence;
    var buttonConditions = {
        zocdoc: !!isZocdocEnabled,
        nexhealth: !!isNexHealthEnabled,
        heartland: !!(isHeartland && scheduleAppointmentUrl),
        customRAUrl: !!(customRAURL === null || customRAURL === void 0 ? void 0 : customRAURL.url),
        hfd: !!isHfdEnabled,
        default: true,
    };
    var activeButton = buttonSequence.find(function (key) { return buttonConditions[key]; }) || 'default';
    var renderEarlyReturnButton = function () {
        switch (activeButton) {
            case 'zocdoc':
                return (_jsxs("div", { className: cx('form-wrap'), children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule_custom }), _jsx(Button, { styleType: "primary", width: "80%", buttonStyle: { margin: 'auto', display: 'block' }, bgColor: "#E10098", onClick: function () {
                                track('doc_loc_form_cta_click', {
                                    link_location: 'doc_loc_profile',
                                    link_text: t.schedule_online_zocdoc_button,
                                    link_url: "".concat(zocdocScheduleAppointmentUrl, "?id=").concat(data.location_id),
                                    profile_number: data.location_id,
                                    profile_tier: (tierData === null || tierData === void 0 ? void 0 : tierData.label) || t.no_tier_event_label,
                                    profile_designation: DOC_TYPE_NAME[data.doctor_type],
                                    is_ols: true,
                                    ols_api: 'Zocdoc',
                                    hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal'),
                                });
                                window.location.href = "".concat(zocdocScheduleAppointmentUrl, "?id=").concat(data.location_id);
                            }, children: t.schedule_online_zocdoc_button })] }));
            case 'nexhealth':
                return (_jsxs("div", { className: cx('form-wrap'), children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule_custom }), _jsx(Button, { styleType: "primary", width: "80%", buttonStyle: { margin: 'auto', display: 'block' }, bgColor: "#E10098", onClick: function () {
                                track('doc_loc_form_cta_click', {
                                    link_location: 'doc_loc_profile',
                                    link_text: t.schedule_online_nexhealth_button,
                                    link_url: "".concat(nexHealthScheduleAppointmentUrl, "?id=").concat(data.location_id),
                                    profile_number: data.location_id,
                                    profile_tier: (tierData === null || tierData === void 0 ? void 0 : tierData.label) || t.no_tier_event_label,
                                    profile_designation: DOC_TYPE_NAME[data.doctor_type],
                                    is_ols: true,
                                    ols_api: 'NexHealth',
                                    hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal'),
                                });
                                window.location.href = "".concat(nexHealthScheduleAppointmentUrl, "?id=").concat(data.location_id);
                            }, children: t.schedule_online_nexhealth_button })] }));
            case 'heartland':
                return (_jsxs("div", { className: cx('form-wrap'), children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule_custom }), _jsx(Button, { styleType: "normal", width: "80%", buttonStyle: { display: 'flex', justifyContent: 'center', margin: 'auto' }, onClick: function () {
                                track('doc_loc_form_cta_click', {
                                    link_location: 'doc_loc_profile',
                                    link_text: t.result_schedule_appointment_button,
                                    link_url: "".concat(scheduleAppointmentUrl, "?id=").concat(data.location_id),
                                    profile_number: data.location_id,
                                    profile_tier: (tierData === null || tierData === void 0 ? void 0 : tierData.label) || t.no_tier_event_label,
                                    profile_designation: DOC_TYPE_NAME[data.doctor_type],
                                    is_ols: true,
                                    ols_api: 'Heartland',
                                    hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal'),
                                });
                                window.location.href = "".concat(scheduleAppointmentUrl, "?id=").concat(data.location_id);
                            }, children: t.result_schedule_appointment_button })] }));
            case 'customRAUrl':
                return (_jsxs("div", { className: cx('form-wrap'), children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule_custom }), _jsx(Button, { styleType: "normal", width: "80%", buttonStyle: { display: 'flex', justifyContent: 'center', margin: 'auto' }, onClick: function () {
                                track('doc_loc_custom_schedule_online_click', {
                                    profile_number: data.location_id,
                                    link_url: customRAURL.url,
                                });
                                window.open(customRAURL.url, '_blank');
                            }, children: t.schedule_online })] }));
            case 'hfd':
                return (_jsxs("div", { className: cx('form-wrap'), children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule_custom }), _jsx(Button, { styleType: "secondryWithIcon", icon: [_jsx(HfdLogo, { width: "24px" }), _jsx(HfdLogo, { color: "white", width: "24px" })], width: "60%", buttonStyle: { display: 'flex', justifyContent: 'center', margin: 'auto' }, onClick: function () {
                                track('doc_loc_hfd_cta_click', {
                                    link_location: 'doc_loc_profile',
                                    link_text: t.get_prequalified,
                                    link_url: data.hfd_prequal_url,
                                    profile_number: data.location_id,
                                    profile_tier: (tierData === null || tierData === void 0 ? void 0 : tierData.label) || t.no_tier_event_label,
                                    profile_designation: DOC_TYPE_NAME[data.doctor_type],
                                    hfd_prequal_eligible: hasProgram(data, 'is_hfd_prequal'),
                                });
                                window.open("".concat(t.fhd_page_url, "?id=").concat(data === null || data === void 0 ? void 0 : data.location_id, "&iframeurl=").concat((data === null || data === void 0 ? void 0 : data.hfd_prequal_url) && encodeURIComponent(data === null || data === void 0 ? void 0 : data.hfd_prequal_url)), '_self');
                            }, children: t.get_prequalified })] }));
            default:
                return null;
        }
    };
    var earlyReturnButton = renderEarlyReturnButton();
    if (earlyReturnButton)
        return earlyReturnButton;
    return isMounted && !isSubmitted ? (_jsxs("div", { className: cx('form-wrapper'), "data-is-heartland-ols": data.is_heartland_ols, "data-is-hfd-prequal": hasProgram(data, 'is_hfd_prequal'), "data-doc-id": data.location_id, children: [_jsxs("form", { className: "form-container-selector ".concat(cx('form-container', { isMobile: isMobile })), "data-id": heetFormId, children: [_jsx("h2", { className: cx('eyebrow-head'), children: t.appointment_help_me_schedule }), isModal && (_jsx(Profile, { data: data, profileId: profileId || '', t: t, isMobile: isMobile, view: DocLocViews.DOC_PROFILE, showAddress: true, hideAction: true, hideDistance: true, isModal: isModal, hideWebsite: true, closeModal: closeModal })), _jsxs("p", { className: cx('form-body'), children: [t.appointment_help_you_schedule, _jsx("span", { className: cx('d-name'), children: country === 'br'
                                    ? data.practice_name ||
                                        (data === null || data === void 0 ? void 0 : data.practice_name2) ||
                                        "".concat(data.first_name || '', " ").concat(data.last_name || '')
                                    : data.is_dso
                                        ? data.practice_name ||
                                            (data === null || data === void 0 ? void 0 : data.practice_name2) ||
                                            "".concat(data.first_name || '', " ").concat(data.last_name || '')
                                        : data.display_name || data.last_name || '' })] }), _jsx("p", { className: cx('required-text'), children: t.required_text }), !scheduleLoading && (_jsxs(_Fragment, { children: [_jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "firstName-input", children: t.appointment_first_name }), _jsx(Input, { id: "firstName-input", placeholder: t.placeholder_first_name, value: firstName, isInValid: firstName.length > 0 ? errorKeys.includes('firstName') : undefined, error: errorKeys.includes('firstName'), showError: showError, onChange: function (e) {
                                            handleChange('firstName')(e);
                                            setIntracted(true);
                                        }, handleOnBlur: !firstNameFocused ? function () { return setFirstNameFocused(true); } : undefined })] }), _jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "lastName-input", children: t.appointment_last_name }), _jsx(Input, { id: "lastName-input", placeholder: t.placeholder_last_name, value: lastName, isInValid: lastName.length > 0 ? errorKeys.includes('lastName') : undefined, error: errorKeys.includes('lastName'), showError: showError, onChange: function (e) {
                                            handleChange('lastName')(e);
                                            setIntracted(true);
                                        }, handleOnBlur: !lastNameFocused ? function () { return setLastNameFocused(true); } : undefined })] }), _jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "dateOfBirth-input", children: t.appointment_dob_label }), _jsx(MaskedInputNumber, { placeholder: t.placeholder_dob, id: "dateOfBirth-input", value: dateOfBirth, error: errorKeys.includes('dateOfBirth'), mask: dobUtility === null || dobUtility === void 0 ? void 0 : dobUtility.mask, showError: showError, isInValid: dateOfBirth !== (dobUtility === null || dobUtility === void 0 ? void 0 : dobUtility.mask) ? errorKeys.includes('dateOfBirth') : undefined, handleOnBlur: !dobFocused ? function () { return setDobFocused(true); } : undefined, onChange: function (e) {
                                            handleChange('dateOfBirth')(e);
                                            setIntracted(true);
                                        }, isDOB: true }), !isDobLabelValid && _jsx("p", { className: cx('error-text'), children: t.invalid_dob })] }), _jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "email-input", children: t.appointment_email_label }), _jsx(Input, { id: "email-input", placeholder: t.placeholder_email, value: email, isInValid: email.length > 0 ? errorKeys.includes('email') : undefined, error: errorKeys.includes('email'), showError: showError, onChange: function (e) {
                                            handleChange('email')(e);
                                            setIntracted(true);
                                        }, handleOnBlur: !emailFocused ? function () { return setEmailFocused(true); } : undefined }), !isEmailLabelValid && _jsx("p", { className: cx('error-text'), children: t.invalid_email })] }), _jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "mobile-input", children: t.appointment_mobile_label }), _jsx(MaskedInputNumber, { id: "mobile-input", placeholder: t.placeholder_mobile, value: mobile, mask: mobileMask, maxLength: mobileMaxLength, prefix: mobilePrefix, error: errorKeys.includes('mobile'), showError: showError, isInValid: mobile !== mobileMask ? errorKeys.includes('mobile') : undefined, onChange: function (e) {
                                            handleChange('mobile')(e);
                                            setIntracted(true);
                                        }, handleOnBlur: !mobileFocused ? function () { return setMobileFocused(true); } : undefined }), !isMobileLabelValid && _jsx("p", { className: cx('error-text'), children: t.invalid_phone })] }), showZip && (_jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "zip-input", children: t.appointment_zip_label }), _jsx(Input, { id: "zip-input", type: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.type, value: zip, onChange: function (e) {
                                            if (isCa) {
                                                if (e.target.value.length > 7) {
                                                    return false;
                                                }
                                                var res = canadaZipValidator(e.target.value, zip);
                                                if (res !== false && typeof res === 'string') {
                                                    // @ts-ignore
                                                    handleChange('zip')({ target: { value: res } });
                                                }
                                            }
                                            else {
                                                handleChange('zip')(e);
                                            }
                                            setIntracted(true);
                                        }, handleOnBlur: !zipFocused ? function () { return setZipFocused(true); } : undefined, isInValid: zip.length > 0 ? errorKeys.includes('zip') : undefined, error: errorKeys.includes('zip'), showError: showError, mask: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.mask, maskChar: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.maskChar, placeholder: t.placeholder_zip, maxLength: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.maxLength }), !isZipLabelValid && _jsx("p", { className: cx('error-text'), children: t.invalid_zip })] })), _jsxs("div", { className: cx('input-wrapper'), children: [_jsxs("label", { className: cx('label'), children: [t.appointment_i_am, ":"] }), _jsxs("div", { className: cx('radio-wrapper'), children: [_jsx(Radio, { id: "age_adult", label: t.appointment_adult, value: PatientType.ADULT, checked: patientType === PatientType.ADULT, onChange: function (e) {
                                                    handleChange('patientType')(e);
                                                    setAgeLimit(false);
                                                    setShowError(false);
                                                    checkErrors(undefined, { dateOfBirth: getDobValidator(false) });
                                                    setIntracted(true);
                                                } }), _jsx(Radio, { id: "age_parent", label: t.appointment_parent, value: PatientType.PARENT, checked: patientType === PatientType.PARENT, onChange: function (e) {
                                                    handleChange('patientType')(e);
                                                    setAgeLimit(false);
                                                    setShowError(false);
                                                    checkErrors(undefined, { dateOfBirth: getDobValidator(false) });
                                                    setIntracted(true);
                                                } }), _jsx(Radio, { id: "age_teen", label: t.appointment_teen, value: PatientType.TEEN, checked: patientType === PatientType.TEEN, onChange: function (e) {
                                                    handleChange('patientType')(e);
                                                    teenError && setAgeLimit(true);
                                                    setIntracted(true);
                                                } })] })] }), preferredContactTimeEnabled && (_jsxs("div", { className: cx('input-wrapper'), children: [_jsxs("label", { className: cx('label'), children: [t.preffered_contact_time, ":"] }), _jsxs("div", { className: cx('radio-wrapper contact-time-wrapper'), children: [_jsx(Radio, { id: "preferred_contact_time_morning", label: t.appointment_morning, value: ContactTime.MORNING, checked: preferredContactTime === ContactTime.MORNING, onChange: function (e) {
                                                    handleChange('preferredContactTime')(e);
                                                    setIntracted(true);
                                                } }), _jsx(Radio, { id: "preferred_contact_time_afternoon", label: t.appointment_afternoon, value: ContactTime.AFTERNOON, checked: preferredContactTime === ContactTime.AFTERNOON, onChange: function (e) {
                                                    handleChange('preferredContactTime')(e);
                                                    setIntracted(true);
                                                } }), _jsx(Radio, { id: "preferred_contact_time_evening", label: t.appointment_evening, value: ContactTime.EVENING, checked: preferredContactTime === ContactTime.EVENING, onChange: function (e) {
                                                    handleChange('preferredContactTime')(e);
                                                    setIntracted(true);
                                                } }), _jsx(Radio, { id: "preferred_contact_time_no_preference", label: t.appointment_no_preference, value: ContactTime.NO_PREFERENCE, checked: preferredContactTime
                                                    ? preferredContactTime === ContactTime.NO_PREFERENCE
                                                    : true, onChange: function (e) {
                                                    handleChange('preferredContactTime')(e);
                                                    setIntracted(true);
                                                } })] })] })), showCommentField && (_jsxs("div", { className: cx('input-wrapper'), children: [_jsx("label", { className: cx('label'), htmlFor: "comment-input", children: t.appointment_comment_label }), _jsx(TextArea, { id: "comment-input", value: comments || '', onChange: function (e) {
                                            handleChange('comments')(e);
                                            setIntracted(true);
                                        }, placeholder: t.placeholder_comment })] })), t.privacy_notice && (_jsx("p", { className: cx('privacy_notice_text'), dangerouslySetInnerHTML: { __html: t.privacy_notice } })), _jsxs("div", { className: cx('input-wrapper'), children: [t.appointment_align_info_sub_heading && (_jsx("label", { className: cx('label'), children: t.appointment_align_info_sub_heading })), _jsxs("div", { className: "flex", children: [_jsx(CheckBox, { id: "alignInfoAgreed", onChange: function (e) {
                                                    handleChange('alignInfoAgreed')(e);
                                                    setIntracted(true);
                                                }, checked: alignInfoAgreed, isMandatory: Boolean(optin === null || optin === void 0 ? void 0 : optin.mandatory), mandatoryMessage: optin === null || optin === void 0 ? void 0 : optin.message }), _jsx("label", { htmlFor: "alignInfoAgreed", children: _jsx("p", { className: cx('cursor-pointer'), dangerouslySetInnerHTML: {
                                                        __html: t.appointment_align_info.replace('$link', "<a class=\"text-underline\" href=\"".concat(makePath(privacyPolicyUrl), "\" target=\"_blank\" rel=\"noreferrer noopener\">").concat(t.appointment_privacy_statement, "</a>")),
                                                    } }) })] }), !alignInfoAgreed && Boolean(optin === null || optin === void 0 ? void 0 : optin.mandatory) && (_jsx("p", { className: cx('error-text'), style: { marginLeft: 38, marginTop: -20 }, children: t.unsubscribe_error_message })), (optin === null || optin === void 0 ? void 0 : optin.secondOptinLabel) && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "flex", children: [_jsx(CheckBox, { id: "alignInfoAgreed2", onChange: function (e) {
                                                            handleChange('alignInfoAgreed2')(e);
                                                            setIntracted(true);
                                                        }, checked: alignInfoAgreed2, isMandatory: Boolean(optin === null || optin === void 0 ? void 0 : optin.mandatory), mandatoryMessage: optin === null || optin === void 0 ? void 0 : optin.message }), _jsx("label", { htmlFor: "alignInfoAgreed2", children: _jsx("p", { className: "mt-0", dangerouslySetInnerHTML: {
                                                                __html: optin.secondOptinLabel,
                                                            } }) })] }), !alignInfoAgreed2 && Boolean(optin === null || optin === void 0 ? void 0 : optin.mandatory) && (_jsx("p", { className: cx('error-text'), style: { marginLeft: 38, marginTop: -20 }, children: t.unsubscribe_error_message2 }))] }))] }), isModal && _jsx("hr", {}), _jsxs("div", { className: "flex-space-between", children: [isModal && (_jsx(Button, { styleType: "cancel", onClick: closeModal, padding: "14px 40px 14px 0px", children: t.result_sort_button_cancel })), _jsx(Button, { id: "submit-btn", styleType: "normal", onClick: handleSubmit, padding: "14px 20px", fontSize: "16px", disabled: scheduleLoading, width: "100%", children: t.result_schedule_button_label })] })] })), scheduleLoading && _jsx(Loader, { showText: false }), t.appointment_disclaimer && (_jsx("div", { className: cx('appointment_disclaimer'), children: _jsx("p", { children: t.appointment_disclaimer }) }))] }), showAgeModal && (_jsx(Modal, { setShowModal: function () { return setShowAgeModal(false); }, size: "sm", padding: "15px", children: _jsxs(_Fragment, { children: [_jsxs("div", { className: cx('opin-modal-content'), children: [_jsx("h2", { children: ageModalData === null || ageModalData === void 0 ? void 0 : ageModalData.title }), _jsx("p", { children: ageModalData === null || ageModalData === void 0 ? void 0 : ageModalData.description }), _jsx("hr", {})] }), _jsx("div", { style: { textAlign: 'center' }, children: _jsx(Button, { type: "submit", styleType: "normal", onClick: function () {
                                    window.location.href = '/';
                                }, children: t.goToInvisalignHomepage }) })] }) }))] })) : (_jsx(_Fragment, {}));
}
