// import { useState, useEffect } from 'react'

// // ** Next Imports
// import Link from 'next/link'
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import FormControl from '@mui/material/FormControl'
// import useMediaQuery from '@mui/material/useMediaQuery'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import TextField from '@mui/material/TextField'
// import IconButton from '@mui/material/IconButton'
// import Autocomplete from '@mui/material/Autocomplete'

// // ** Animation Imports
// import { AnimatePresence, motion } from 'framer-motion'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'
// import CryptoJS from 'crypto-js'

// // ** Hooks
// import { useSettings } from 'src/@core/hooks/useSettings'

// // ** Layout Import
// import BlankLayout from 'src/@core/layouts/BlankLayout'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Fake DB Import for countries
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios & Endpoints
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** Types
// interface UserDetails {
//   dialCountryCode?: string
//   firstName?: string
//   lastName?: string
//   emailVerified?: boolean
//   countryCode?: string
//   phoneVerified?: boolean
//   mobile?: string
//   emailId?: string
// }

// interface CountryOption {
//   code?: string
//   iso2?: string
//   dialCode?: string
//   phone?: string
//   name?: string
//   label?: string
// }

// interface ApiResponse {
//   code: number
//   content: string
//   uid?: string | null
//   timestamp?: string
//   success?: boolean
//   message?: string
// }

// interface UpdatePhonePayload {
//   dialCountryCode: string
//   countryCode: string
//   mobile: string
// }

// interface OtpFormValues {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// // ** Animation Variants
// const slideVariants = {
//   hiddenLeft: { x: -400, opacity: 0 },
//   hiddenRight: { x: 400, opacity: 0 },
//   visible: { x: 0, opacity: 1 },
//   exitLeft: { x: -400, opacity: 0 },
//   exitRight: { x: 400, opacity: 0 }
// }

// // ** Styled Components
// const TwoStepsIllustration = styled('img')(({ theme }) => ({
//   zIndex: 2,
//   maxHeight: 650,
//   marginTop: theme.spacing(12),
//   marginBottom: theme.spacing(12),
//   [theme.breakpoints.down(1540)]: {
//     maxHeight: 550
//   },
//   [theme.breakpoints.down('lg')]: {
//     maxHeight: 500
//   }
// }))

// const RightWrapper = styled(Box)(({ theme }) => ({
//   width: '100%',
//   [theme.breakpoints.up('md')]: {
//     maxWidth: 450
//   },
//   [theme.breakpoints.up('lg')]: {
//     maxWidth: 600
//   },
//   [theme.breakpoints.up('xl')]: {
//     maxWidth: 750
//   }
// }))

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(2),
//   color: theme.palette.primary.main,
//   cursor: 'pointer'
// }))

// const CallLinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(1),
//   color: theme.palette.error.main,
//   cursor: 'pointer'
// }))

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   },
//   [theme.breakpoints.down('sm')]: {
//     maxWidth: 40,
//     height: '40px !important',
//     fontSize: '120% !important'
//   }
// }))

// const defaultValues: OtpFormValues = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// // Secret key for AES encryption
// const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

// const deriveAESKey = (): CryptoJS.lib.WordArray => {
//   const secretWordArray = CryptoJS.enc.Utf8.parse(SECRET_KEY)
//   const keyHash = CryptoJS.SHA256(secretWordArray)
//   return keyHash
// }

// const encryptAES = (plainText: string): string | null => {
//   try {
//     const iv = CryptoJS.lib.WordArray.random(16)
//     const key = deriveAESKey()
//     const encrypted = CryptoJS.AES.encrypt(plainText, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })
//     const combined = iv.concat(encrypted.ciphertext)
//     return CryptoJS.enc.Base64.stringify(combined)
//   } catch (error) {
//     console.error('Encryption error:', error)
//     return null
//   }
// }

// const EmailVerify = () => {
//   const [isVerifying, setIsVerifying] = useState(false)
//   const [isResending, setIsResending] = useState(false)
//   const [isCalling, setIsCalling] = useState(false)
//   const [error, setError] = useState('')
//   const [successMessage, setSuccessMessage] = useState('')
//   const [isBackspace, setIsBackspace] = useState(false)
//   const [isVerifyingInitial, setIsVerifyingInitial] = useState(true)
//   const [emailAddress, setEmailAddress] = useState('')
//   const [userDetails, setUserDetails] = useState<UserDetails | null>(null)
//   const [isEditingPhone, setIsEditingPhone] = useState(false)
//   const [selectedCountryCode, setSelectedCountryCode] = useState<CountryOption | null>(null)
//   const [phoneNumber, setPhoneNumber] = useState('')
//   const [isUpdatingPhone, setIsUpdatingPhone] = useState(false)
//   const [pageLoaded, setPageLoaded] = useState(false)
//   const [decryptError, setDecryptError] = useState(false)
//   const [verifyError, setVerifyError] = useState(false)
  
//   const [attempt, setAttempt] = useState(0)
//   const [resendVisible, setResendVisible] = useState(false)
//   const [callVisible, setCallVisible] = useState(false)
//   const [countdown, setCountdown] = useState(0)
//   const [countdownActive, setCountdownActive] = useState(false)

//   const router = useRouter()
//   const { token } = router.query

//   const theme = useTheme()
//   const { settings } = useSettings()
//   const hidden = useMediaQuery(theme.breakpoints.down('md'))
//   const { skin } = settings

//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors }
//   } = useForm<OtpFormValues>({ defaultValues })

//   const errorsArray = Object.keys(errors)

//   // Function to decrypt token and get user details - GET request with token in URL path
//   const decryptTokenAndGetUserDetails = async (authToken: string) => {
//     try {
//       setDecryptError(false)
//       // GET request with token as path parameter
//       const response = await axios.get<UserDetails>(
//         `${endpoints.auth.decryptTokenEndpoint}/${authToken}`
//       )
//       console.log('Decrypted user details:', response.data)
      
//       if (response.data) {
//         setUserDetails(response.data)
//         setEmailAddress(response.data.emailId || 'your email address')
        
//         // Find and set the country code object
//         if (response.data.dialCountryCode || response.data.countryCode) {
//           const countryCodeValue = response.data.dialCountryCode || response.data.countryCode
//           const foundCountry = countries.find(
//             country => country.code === countryCodeValue || country.iso2 === countryCodeValue
//           )
//           setSelectedCountryCode(foundCountry || null)
//         }
        
//         // Set phone number
//         if (response.data.mobile) {
//           setPhoneNumber(response.data.mobile)
//         }
//         return true
//       }
//       return false
//     } catch (error: any) {
//       console.error('Error decrypting token:', error)
//       setDecryptError(true)
//       // Don't redirect to login, just show error on page
//       const errorMsg = error.response?.data?.message || 'Failed to decrypt token. Please try again.'
//       setError(errorMsg)
//       setEmailAddress('your email address')
//       return false
//     }
//   }

//   // Verify token with backend - GET request with query parameter
//   const verifyTokenWithBackend = async (authToken: string) => {
//     try {
//       setIsVerifyingInitial(true)
//       setError('')
//       setVerifyError(false)

//       const response = await axios.get<ApiResponse>(
//         endpoints.auth.verifyEmailTokenEndpoint,
//         {
//           params: { token: authToken }
//         }
//       )

//       if (response.data && response.data.code === 200) {
//         setSuccessMessage(
//           response.data.content || 'Email verified successfully!'
//         )
//         setIsVerifyingInitial(false)
//         return true
//       } else {
//         setIsVerifyingInitial(false)
//         setVerifyError(true)
//         startCountdown(40)
//         return false
//       }
//     } catch (error: any) {
//       setIsVerifyingInitial(false)
//       setVerifyError(true)
//       startCountdown(40)
//       return false
//     }
//   }

//   // Main useEffect to handle the verification flow
//   useEffect(() => {
//     // Important: Wait for router to be ready and token to be available
//     if (!router.isReady) {
//       console.log('Router not ready yet...')
//       return
//     }

//     const authToken = token as string
    
//     if (!authToken) {
//       console.log('No token found in URL')
//       setError('Invalid verification link. No token provided.')
//       setPageLoaded(true)
//       setIsVerifyingInitial(false)
//       return
//     }

//     console.log('Token found in URL:', authToken)
//     setPageLoaded(true)

//     const initializeVerification = async () => {
//       // Try to decrypt token first
//       const decrypted = await decryptTokenAndGetUserDetails(authToken)
      
//       // Then verify email - don't let failures prevent showing the form
//       await verifyTokenWithBackend(authToken)
//     }

//     initializeVerification()
//   }, [router.isReady, token])

//   // Handle countdown timer
//   useEffect(() => {
//     let timer: NodeJS.Timeout
//     if (countdown > 0 && countdownActive) {
//       timer = setTimeout(() => {
//         setCountdown(countdown - 1)
//       }, 1000)
//     } else if (countdown === 0 && countdownActive) {
//       setCountdownActive(false)
//       if (attempt === 0) {
//         setResendVisible(true)
//       } else if (attempt === 1) {
//         setCallVisible(true)
//       }
//     }
//     return () => clearTimeout(timer)
//   }, [countdown, countdownActive, attempt])

//   const startCountdown = (seconds: number) => {
//     setCountdown(seconds)
//     setCountdownActive(true)
//   }

//   const resetOtpInputs = () => {
//     reset(defaultValues)
//     setTimeout(() => {
//       const firstInput = document.querySelector('.CleaveInput') as HTMLInputElement
//       if (firstInput) firstInput.focus()
//     }, 100)
//   }

//   const handleFailedAttempt = () => {
//     setAttempt((prev) => {
//       const next = prev + 1
//       setCountdownActive(false)
      
//       if (next === 1) {
//         setResendVisible(true)
//         setCallVisible(false)
//       } else if (next === 2) {
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//       } else if (next >= 3) {
//         toast.error('Too many failed attempts. Please try again later.')
//         // Don't redirect to login, just reset attempts after a longer time
//         setTimeout(() => {
//           setAttempt(0)
//           setResendVisible(true)
//         }, 60000)
//       }
//       return next
//     })
//   }

//   const handleChange = (event: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
//     if (!isBackspace) {
//       onChange(event.target.value)
//       const form = event.target.form
//       if (form) {
//         const index = [...form].indexOf(event.target)
//         const formElements = [...form.elements] as HTMLInputElement[]
//         if (formElements[index].value && formElements[index].value.length) {
//           if (formElements[index + 1]) {
//             formElements[index + 1].focus()
//           }
//         }
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)
//       const form = event.currentTarget.form
//       if (form) {
//         const index = [...form.elements].indexOf(event.currentTarget)
//         if (index >= 1) {
//           const formElements = [...form.elements] as HTMLInputElement[]
//           if (!(formElements[index].value && formElements[index].value.length)) {
//             if (formElements[index - 1]) {
//               formElements[index - 1].focus()
//             }
//           }
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     const inputKeys: (keyof OtpFormValues)[] = ['val1', 'val2', 'val3', 'val4', 'val5', 'val6']
    
//     return inputKeys.map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <CleaveInput
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             onKeyDown={handleKeyDown}
//             onChange={(event: React.ChangeEvent<HTMLInputElement>) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ 
//               [theme.breakpoints.down('sm')]: { 
//                 px: `${theme.spacing(2)} !important`,
//                 marginRight: `${theme.spacing(1)} !important`
//               } 
//             }}
//           />
//         )}
//       />
//     ))
//   }

//   const handleEditPhone = () => {
//     setIsEditingPhone(true)
//   }

//   const handleCancelEdit = () => {
//     setIsEditingPhone(false)
//     if (userDetails) {
//       const foundCountry = countries.find(
//         country => country.code === (userDetails.dialCountryCode || userDetails.countryCode)
//       )
//       setSelectedCountryCode(foundCountry || null)
//       setPhoneNumber(userDetails.mobile || '')
//     }
//   }

//   const handleUpdatePhone = async () => {
//     if (!phoneNumber || phoneNumber.length < 6) {
//       toast.error('Please enter a valid phone number')
//       return
//     }

//     if (!selectedCountryCode) {
//       toast.error('Please select a country code')
//       return
//     }

//     setIsUpdatingPhone(true)
//     try {
//       const authToken = token as string
//       const payload: UpdatePhonePayload = {
//         dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2 || '',
//         countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//         mobile: phoneNumber
//       }
      
//       // POST request with token in URL path
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.updatePhoneNumberEndpoint}/${authToken}`,
//         payload
//       )
      
//       if (response.data && response.data.code === 200) {
//         toast.success(response.data.content || 'Phone number updated successfully!')
//         setIsEditingPhone(false)
        
//         setUserDetails({
//           ...userDetails,
//           dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2,
//           countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//           mobile: phoneNumber
//         })
//       } else {
//         toast.error(response.data?.message || 'Failed to update phone number')
//       }
//     } catch (error: any) {
//       console.error('Error updating phone:', error)
//       toast.error(error.response?.data?.message || 'Failed to update phone number')
//     } finally {
//       setIsUpdatingPhone(false)
//     }
//   }

//   const onSubmit = async (data: OtpFormValues) => {
//     if (isVerifying) return

//     setIsVerifying(true)
//     setError('')

//     const enteredOtp = Object.values(data).join('')
    
//     if (enteredOtp.length !== 6) {
//       setError('Please enter a valid 6-digit verification code')
//       setIsVerifying(false)
//       return
//     }
    
//     const encryptedOtp = encryptAES(enteredOtp)
    
//     if (!encryptedOtp) {
//       setError('Failed to encrypt verification code. Please try again.')
//       setIsVerifying(false)
//       return
//     }
    
//     const authToken = token as string
//     const payload = {
//       otp: encryptedOtp
//     }

//     try {
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.sendOtpForEmailEndpoint}/${authToken}`,
//         payload
//       )
      
//       if (response.data && response.data.code === 200) {
//         toast.success(response.data.content || 'Email verified successfully!')
        
//         // Redirect to login page after successful verification
//         setTimeout(() => {
//           router.push('/login')
//         }, 1500) // Small delay to show success message before redirect
//       } else {
//         const errorMsg = response.data?.message || 'Invalid verification code. Please try again.'
//         setError(errorMsg)
//         handleFailedAttempt()
//       }
//     } catch (error: any) {
//       console.error('Verification error:', error)
//       const errorMessage = error.response?.data?.content || error.response?.data?.message || 'Failed to verify email.'
//       setError(errorMessage)
//       handleFailedAttempt()
//     } finally {
//       setIsVerifying(false)
//     }
//   }

//   const handleResendOTP = async () => {
//     if (isResending) return

//     setIsResending(true)
//     setError('')
//     setSuccessMessage('')

//     try {
//       const authToken = token as string
//       // GET request with token in URL path
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A new verification code has been sent to your email.'
//         toast.success(message)
//         setSuccessMessage(message)
//         setAttempt(1)
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMessage = response.data?.content || 'Failed to resend OTP'
//         toast.error(errorMessage)
//         setError(errorMessage)
//       }
//     } catch (error: any) {
//       const errorMessage = error.response?.data?.content || 'Failed to resend OTP'
//       setError(errorMessage)
//       toast.error(errorMessage)
//     } finally {
//       setIsResending(false)
//     }
//   }

//   const handleCallOTP = async () => {
//     if (isCalling) return

//     setIsCalling(true)
//     setError('')
//     setSuccessMessage('')

//     try {
//       const authToken = token as string
//       // GET request with token in URL path
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpCallEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A verification code has been sent via call.'
//         toast.success(message)
//         setSuccessMessage(message)
//         setAttempt(2)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMessage = response.data?.content || 'Failed to send OTP via call'
//         toast.error(errorMessage)
//         setError(errorMessage)
//       }
//     } catch (error: any) {
//       const errorMessage = error.response?.data?.content || 'Failed to send OTP via call'
//       setError(errorMessage)
//       toast.error(errorMessage)
//     } finally {
//       setIsCalling(false)
//     }
//   }

//   const formatTime = (seconds: number): string => {
//     const mins = Math.floor(seconds / 60)
//     const secs = seconds % 60
//     return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
//   }

//   const imageSource = skin === 'bordered' ? 'auth-v2-two-steps-illustration-bordered' : 'auth-v2-two-steps-illustration'

//   // Show loading while router is not ready
//   if (!router.isReady || !pageLoaded) {
//     return (
//       <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
//         <CircularProgress />
//       </Box>
//     )
//   }

//   if (isVerifyingInitial) {
//     return (
//       <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//         <RightWrapper>
//           <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//             <Box sx={{ textAlign: 'center' }}>
//               <CircularProgress size={60} />
//               <Typography sx={{ mt: 4, color: 'text.secondary' }}>
//                 Verifying your email...
//               </Typography>
//             </Box>
//           </Box>
//         </RightWrapper>
//       </Box>
//     )
//   }

//   return (
//     <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//       {!hidden ? (
//         <Box
//           sx={{
//             flex: 1,
//             display: 'flex',
//             position: 'relative',
//             alignItems: 'center',
//             borderRadius: '20px',
//             justifyContent: 'center',
//             backgroundColor: 'customColors.bodyBg',
//             margin: theme => theme.spacing(8, 0, 8, 8)
//           }}
//         >
//           <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
//             <AnimatePresence mode='wait'>
//               <motion.div
//                 key='verify'
//                 initial={{ opacity: 0 }}
//                 animate={{ opacity: 1 }}
//                 exit={{ opacity: 0 }}
//                 transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
//                 style={{
//                   position: 'absolute',
//                   width: '100%',
//                   height: '100%',
//                   display: 'flex',
//                   justifyContent: 'center',
//                   alignItems: 'center'
//                 }}
//               >
//                 <TwoStepsIllustration 
//                   alt='two-steps-illustration' 
//                   src={`/images/pages/${imageSource}-${theme.palette.mode}.png`} 
//                 />
//               </motion.div>
//             </AnimatePresence>
//           </Box>
//         </Box>
//       ) : null}

//       <RightWrapper>
//         <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//           <AnimatePresence mode='wait'>
//             <motion.div
//               key='verify-form'
//               initial='hiddenRight'
//               animate='visible'
//               exit='exitLeft'
//               variants={slideVariants}
//               transition={{ duration: 0.5 }}
//               style={{ width: '100%', display: 'flex', justifyContent: 'center' }}
//             >
//               <Box sx={{ width: '100%', maxWidth: 400 }}>
//                 <img
//                   src='/images/website-logo/LockTrust-logo.png'
//                   alt='LockTrust Logo'
//                   style={{ height: '60px', width: 'auto', objectFit: 'contain' }}
//                 />

//                 <motion.div
//                   initial={{ y: -20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.3, duration: 0.5 }}
//                 >
//                   <Box sx={{ mb: 6 }}>
//                     <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//                       Verify Your Email 💬
//                     </Typography>
//                     <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//                       Enter the verification code sent to your email to verify your email address.
//                     </Typography>
                    
//                     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
//                       <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
//                         {emailAddress}
//                       </Typography>
//                       {userDetails?.emailVerified && (
//                         <Box sx={{ display: 'flex', alignItems: 'center', color: 'success.main' }}>
//                           <Icon icon='tabler:circle-check-filled' fontSize={20} />
//                           <Typography variant='caption' sx={{ ml: 0.5, color: 'success.main' }}>
//                             Verified
//                           </Typography>
//                         </Box>
//                       )}
//                     </Box>
//                   </Box>
//                 </motion.div>

//                 {userDetails && (
//                   <motion.div
//                     initial={{ y: 20, opacity: 0 }}
//                     animate={{ y: 0, opacity: 1 }}
//                     transition={{ delay: 0.35, duration: 0.5 }}
//                   >
//                     <Box sx={{ mb: 4, p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
//                       <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
//                         <Typography variant='body2' sx={{ fontWeight: 500, color: 'text.secondary' }}>
//                           Phone Number
//                         </Typography>
//                         {!isEditingPhone && (
//                           <IconButton size='small' onClick={handleEditPhone} sx={{ color: 'primary.main' }}>
//                             <Icon icon='tabler:edit' fontSize={20} />
//                           </IconButton>
//                         )}
//                       </Box>
                      
//                       {!isEditingPhone ? (
//                         <>
//                           <Typography variant='body1' sx={{ fontWeight: 500 }}>
//                             {userDetails.countryCode || '+91'} {userDetails.mobile}
//                           </Typography>
//                           {!userDetails.phoneVerified && (
//                             <Typography variant='caption' sx={{ color: 'warning.main', display: 'block', mt: 0.5 }}>
//                               Not verified yet
//                             </Typography>
//                           )}
//                         </>
//                       ) : (
//                         <Box sx={{ mt: 2 }}>
//                           <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
//                             <FormControl fullWidth sx={{ flex: 0.5 }}>
//                               <Autocomplete
//                                 id='country-select'
//                                 options={countries}
//                                 autoHighlight
//                                 getOptionLabel={(option: CountryOption) => {
//                                   if (!option) return ''
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   return dialCode ? `${name} (+${dialCode})` : name
//                                 }}
//                                 value={selectedCountryCode}
//                                 onChange={(event: any, newValue: CountryOption | null) => {
//                                   setSelectedCountryCode(newValue)
//                                 }}
//                                 renderOption={(props, option) => {
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   const countryCodeISO = option.code || option.iso2 || ''
//                                   return (
//                                     <Box component='li' sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                                       <img
//                                         loading='lazy'
//                                         width='24'
//                                         height='18'
//                                         src={`https://flagcdn.com/w40/${countryCodeISO?.toLowerCase()}.png`}
//                                         srcSet={`https://flagcdn.com/w80/${countryCodeISO?.toLowerCase()}.png 2x`}
//                                         alt=""
//                                         style={{ marginRight: '12px' }}
//                                       />
//                                       <span style={{ fontWeight: 500 }}>{name}</span>
//                                       {dialCode && (
//                                         <span style={{ marginLeft: '8px', color: '#666' }}>(+{dialCode})</span>
//                                       )}
//                                     </Box>
//                                   )
//                                 }}
//                                 renderInput={(params) => (
//                                   <TextField
//                                     {...params}
//                                     label='Country Code'
//                                     placeholder='Select country'
//                                     size='small'
//                                     InputProps={{
//                                       ...params.InputProps,
//                                       startAdornment: selectedCountryCode && (selectedCountryCode.code || selectedCountryCode.iso2) && (
//                                         <img
//                                           src={`https://flagcdn.com/w20/${(selectedCountryCode.code || selectedCountryCode.iso2)?.toLowerCase()}.png`}
//                                           style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                                           width='24'
//                                           height='18'
//                                           alt="flag"
//                                         />
//                                       ),
//                                     }}
//                                   />
//                                 )}
//                               />
//                             </FormControl>
                            
//                             <TextField
//                               fullWidth
//                               size='small'
//                               label='Phone Number'
//                               value={phoneNumber}
//                               onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ''))}
//                               placeholder='Enter phone number'
//                               inputProps={{ maxLength: 15 }}
//                               sx={{ flex: 0.5 }}
//                             />
//                           </Box>
                          
//                           <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
//                             <Button size='small' onClick={handleCancelEdit} disabled={isUpdatingPhone}>
//                               Cancel
//                             </Button>
//                             <Button 
//                               size='small' 
//                               variant='contained' 
//                               onClick={handleUpdatePhone} 
//                               disabled={isUpdatingPhone}
//                             >
//                               {isUpdatingPhone ? <CircularProgress size={20} /> : 'Save'}
//                             </Button>
//                           </Box>
//                         </Box>
//                       )}
//                     </Box>
//                   </motion.div>
//                 )}

//                 {/* Success Alert */}
//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.4, duration: 0.5 }}
//                 >
//                   {successMessage && (
//                     <Alert 
//                       severity='success' 
//                       sx={{ mb: 4 }}
//                       onClose={() => setSuccessMessage('')}
//                     >
//                       {successMessage}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 {/* Error Alert */}
//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.45, duration: 0.5 }}
//                 >
//                   {error && (
//                     <Alert severity='error' sx={{ mb: 4 }} onClose={() => setError('')}>
//                       {error}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.5, duration: 0.5 }}
//                 >
//                   <Typography sx={{ fontWeight: 500, color: 'text.secondary', mb: 2 }}>
//                     Type your 6-digit verification code
//                   </Typography>
//                 </motion.div>

//                 {/* Verification Form */}
//                 <motion.form
//                   onSubmit={handleSubmit(onSubmit)}
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.6, duration: 0.5 }}
//                 >
//                   <CleaveWrapper
//                     sx={{
//                       display: 'flex',
//                       alignItems: 'center',
//                       justifyContent: 'space-between',
//                       ...(errorsArray.length && {
//                         '& .invalid:focus': {
//                           borderColor: theme => `${theme.palette.error.main} !important`,
//                           boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//                         }
//                       })
//                     }}
//                   >
//                     {renderInputs()}
//                   </CleaveWrapper>
                  
//                   {errorsArray.length ? (
//                     <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid verification code</FormHelperText>
//                   ) : null}

//                   <Button 
//                     fullWidth 
//                     type='submit' 
//                     variant='contained' 
//                     disabled={isVerifying} 
//                     sx={{ mt: 4 }}
//                   >
//                     {isVerifying ? (
//                       <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                         <CircularProgress size={24} color='inherit' />
//                         Verifying...
//                       </Box>
//                     ) : (
//                       'Verify Email'
//                     )}
//                   </Button>
//                 </motion.form>

//                 {/* Clock and Options Section */}
//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.7, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}>
//                     {/* Clock/Watch Image with Countdown - Always show when countdown is active */}
//                     {countdownActive && countdown > 0 && (
//                       <Box sx={{ position: 'relative', display: 'inline-block', mb: 2 }}>
//                         <img 
//                           src='/images/clock.jpg'
//                           alt='Clock'
//                           style={{
//                             width: '100px',
//                             height: '100px',
//                             display: 'block',
//                             margin: '0 auto'
//                           }}
//                         />
//                         <Box
//                           sx={{
//                             position: 'absolute',
//                             top: '50%',
//                             left: '50%',
//                             transform: 'translate(-50%, -50%)',
//                             fontSize: '14px',
//                             fontWeight: 'bold',
//                             color: 'white'
//                           }}
//                         >
//                           {formatTime(countdown)}
//                         </Box>
//                       </Box>
//                     )}

//                     {/* Resend Button - Shows when resendVisible is true OR when countdown ends on attempt 0 */}
//                     {resendVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
//                         <LinkStyled 
//                           href='#' 
//                           onClick={handleResendOTP}
//                           sx={{ 
//                             pointerEvents: isResending ? 'none' : 'auto',
//                             opacity: isResending ? 0.6 : 1
//                           }}
//                         >
//                           {isResending ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Resend OTP'
//                           )}
//                         </LinkStyled>
//                       </Box>
//                     )}

//                     {/* Call Button - Shows when callVisible is true */}
//                     {callVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Still having trouble?</Typography>
//                         <CallLinkStyled 
//                           href='#' 
//                           onClick={handleCallOTP}
//                           sx={{ 
//                             pointerEvents: isCalling ? 'none' : 'auto',
//                             opacity: isCalling ? 0.6 : 1
//                           }}
//                         >
//                           {isCalling ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Call Me'
//                           )}
//                         </CallLinkStyled>
//                       </Box>
//                     )}
//                   </Box>
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.9, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                     <Button
//                       variant='text'
//                       onClick={() => router.push('/login')}
//                       sx={{ textTransform: 'none' }}
//                       startIcon={<Icon icon='tabler:arrow-left' />}
//                     >
//                       Back to Login
//                     </Button>
//                   </Box>
//                 </motion.div>
//               </Box>
//             </motion.div>
//           </AnimatePresence>
//         </Box>
//       </RightWrapper>
//     </Box>
//   )
// }

// EmailVerify.getLayout = page => <BlankLayout>{page}</BlankLayout>
// EmailVerify.guestGuard = true

// export default EmailVerify


// final ////////////////
// import { useState, useEffect } from 'react'

// // ** Next Imports
// import Link from 'next/link'
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import FormControl from '@mui/material/FormControl'
// import useMediaQuery from '@mui/material/useMediaQuery'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import TextField from '@mui/material/TextField'
// import IconButton from '@mui/material/IconButton'
// import Autocomplete from '@mui/material/Autocomplete'

// // ** Animation Imports
// import { AnimatePresence, motion } from 'framer-motion'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'
// import CryptoJS from 'crypto-js'

// // ** Hooks
// import { useSettings } from 'src/@core/hooks/useSettings'

// // ** Layout Import
// import BlankLayout from 'src/@core/layouts/BlankLayout'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Fake DB Import for countries
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios & Endpoints
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'
// import authConfig from 'src/configs/auth'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** Types
// interface UserDetails {
//   dialCountryCode?: string
//   firstName?: string
//   lastName?: string
//   emailVerified?: boolean
//   countryCode?: string
//   phoneVerified?: boolean
//   mobile?: string
//   emailId?: string
// }

// interface CountryOption {
//   code?: string
//   iso2?: string
//   dialCode?: string
//   phone?: string
//   name?: string
//   label?: string
// }

// interface ApiResponse {
//   code: number
//   content: string
//   message?: string
//   uid?: string | null
//   timestamp?: string
//   success?: boolean
//   isPlaid?: boolean
//   plaid?: boolean
//   access?: string
//   refresh?: string
//   expiresIn?: number
//   businessType?: string
//   profile?: {
//     firstName?: string
//     lastName?: string
//     uid?: string
//     mobileNum?: string
//     emailId?: string
//     applicationId?: string
//     isPinSetup?: boolean
//     isSubUser?: boolean
//     TwoNf?: boolean
//     businessType?: string
//     allPermissions?: Array<{
//       moduleName: string
//       action: string
//     }>
//     permissions?: Array<{
//       moduleName: string
//       action: string
//     }>
//   }
// }

// interface UpdatePhonePayload {
//   dialCountryCode: string
//   countryCode: string
//   mobile: string
// }

// interface OtpFormValues {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// // ** Animation Variants
// const slideVariants = {
//   hiddenLeft: { x: -400, opacity: 0 },
//   hiddenRight: { x: 400, opacity: 0 },
//   visible: { x: 0, opacity: 1 },
//   exitLeft: { x: -400, opacity: 0 },
//   exitRight: { x: 400, opacity: 0 }
// }

// // ** Styled Components
// const TwoStepsIllustration = styled('img')(({ theme }) => ({
//   zIndex: 2,
//   maxHeight: 650,
//   marginTop: theme.spacing(12),
//   marginBottom: theme.spacing(12),
//   [theme.breakpoints.down(1540)]: {
//     maxHeight: 550
//   },
//   [theme.breakpoints.down('lg')]: {
//     maxHeight: 500
//   }
// }))

// const RightWrapper = styled(Box)(({ theme }) => ({
//   width: '100%',
//   [theme.breakpoints.up('md')]: {
//     maxWidth: 450
//   },
//   [theme.breakpoints.up('lg')]: {
//     maxWidth: 600
//   },
//   [theme.breakpoints.up('xl')]: {
//     maxWidth: 750
//   }
// }))

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(2),
//   color: theme.palette.primary.main,
//   cursor: 'pointer'
// }))

// const CallLinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(1),
//   color: theme.palette.error.main,
//   cursor: 'pointer'
// }))

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   },
//   [theme.breakpoints.down('sm')]: {
//     maxWidth: 40,
//     height: '40px !important',
//     fontSize: '120% !important'
//   }
// }))

// const defaultValues: OtpFormValues = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// // Secret key for AES encryption
// const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

// const deriveAESKey = (): CryptoJS.lib.WordArray => {
//   const secretWordArray = CryptoJS.enc.Utf8.parse(SECRET_KEY)
//   const keyHash = CryptoJS.SHA256(secretWordArray)
//   return keyHash
// }

// const encryptAES = (plainText: string): string | null => {
//   try {
//     const iv = CryptoJS.lib.WordArray.random(16)
//     const key = deriveAESKey()
//     const encrypted = CryptoJS.AES.encrypt(plainText, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })
//     const combined = iv.concat(encrypted.ciphertext)
//     return CryptoJS.enc.Base64.stringify(combined)
//   } catch (error) {
//     console.error('Encryption error:', error)
//     return null
//   }
// }

// // Helper function to store user data
// const storeUserData = (access: string, refresh: string, profile: any, businessType?: string) => {
//   // Format permissions
//   let formattedPermissions = []
//   if (profile?.allPermissions && profile.allPermissions.length > 0) {
//     formattedPermissions = profile.allPermissions
//   } else if (profile?.permissions && profile.permissions.length > 0) {
//     formattedPermissions = profile.permissions.map((p: any) => ({
//       moduleName: p.moduleName,
//       action: p.action
//     }))
//   } else {
//     formattedPermissions = [
//       { moduleName: 'dashboard', action: 'CREATE' },
//       { moduleName: 'dashboard', action: 'UPDATE' },
//       { moduleName: 'dashboard', action: 'VIEW' },
//       { moduleName: 'dashboard', action: 'DELETE' }
//     ]
//   }

//   // Format user data with applicationId
//   const userData = {
//     id: profile?.uid || profile?.id,
//     role: profile?.isSubUser ? 'subUser' : 'merchant',
//     fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
//     firstName: profile?.firstName,
//     lastName: profile?.lastName,
//     mobileNum: profile?.mobileNum,
//     username: profile?.emailId,
//     email: profile?.emailId,
//     isSubUser: profile?.isSubUser || false,
//     TwoNf: profile?.TwoNf || false,
//     isPinSetup: profile?.isPinSetup || false,
//     allPermissions: formattedPermissions,
//     permissions: formattedPermissions,
//     applicationId: profile?.applicationId || null,
//     businessType: businessType || profile?.businessType || null
//   }
  
//   console.log('💼 Storing User Data with businessType:', userData.businessType)
  
//   // Store tokens and user data in localStorage
//   localStorage.setItem(authConfig.storageTokenKeyName, access)
//   localStorage.setItem('refreshToken', refresh)
//   localStorage.setItem('userData', JSON.stringify(userData))
//   localStorage.setItem('isAuthenticated', 'true')
  
//   // Also store businessType separately in sessionStorage for easy access
//   if (businessType || profile?.businessType) {
//     sessionStorage.setItem('businessType', businessType || profile?.businessType)
//   }
  
//   return userData
// }

// // Helper function to handle API errors
// const handleApiError = (error: any): string => {
//   console.error('API Error:', error)
  
//   // Check for response data
//   if (error.response?.data) {
//     const data = error.response.data
    
//     // Check for content field (your API uses this)
//     if (data.content) {
//       return data.content
//     }
    
//     // Check for message field
//     if (data.message) {
//       return data.message
//     }
    
//     // Check for detail field
//     if (data.detail) {
//       return data.detail
//     }
    
//     // Check for errors object
//     if (data.errors) {
//       if (typeof data.errors === 'string') {
//         return data.errors
//       }
//       if (Array.isArray(data.errors)) {
//         return data.errors.join(', ')
//       }
//       if (typeof data.errors === 'object') {
//         const errorMessages = Object.values(data.errors).flat()
//         return errorMessages.join(', ')
//       }
//     }
//   }
  
//   // Check for error message on the error object
//   if (error.message) {
//     return error.message
//   }
  
//   // Default error message
//   return 'An unexpected error occurred. Please try again.'
// }

// const EmailVerify = () => {
//   const [isVerifying, setIsVerifying] = useState(false)
//   const [isResending, setIsResending] = useState(false)
//   const [isCalling, setIsCalling] = useState(false)
//   const [error, setError] = useState('')
//   const [successMessage, setSuccessMessage] = useState('')
//   const [isBackspace, setIsBackspace] = useState(false)
//   const [isVerifyingInitial, setIsVerifyingInitial] = useState(true)
//   const [emailAddress, setEmailAddress] = useState('')
//   const [userDetails, setUserDetails] = useState<UserDetails | null>(null)
//   const [isEditingPhone, setIsEditingPhone] = useState(false)
//   const [selectedCountryCode, setSelectedCountryCode] = useState<CountryOption | null>(null)
//   const [phoneNumber, setPhoneNumber] = useState('')
//   const [isUpdatingPhone, setIsUpdatingPhone] = useState(false)
//   const [pageLoaded, setPageLoaded] = useState(false)
//   const [decryptError, setDecryptError] = useState(false)
//   const [verifyError, setVerifyError] = useState(false)
  
//   const [attempt, setAttempt] = useState(0)
//   const [resendVisible, setResendVisible] = useState(false)
//   const [callVisible, setCallVisible] = useState(false)
//   const [countdown, setCountdown] = useState(0)
//   const [countdownActive, setCountdownActive] = useState(false)

//   const router = useRouter()
//   const { token } = router.query

//   const theme = useTheme()
//   const { settings } = useSettings()
//   const hidden = useMediaQuery(theme.breakpoints.down('md'))
//   const { skin } = settings

//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors }
//   } = useForm<OtpFormValues>({ defaultValues })

//   const errorsArray = Object.keys(errors)

//   // Function to decrypt token and get user details - GET request with token in URL path
//   const decryptTokenAndGetUserDetails = async (authToken: string) => {
//     try {
//       setDecryptError(false)
//       // GET request with token as path parameter
//       const response = await axios.get<UserDetails>(
//         `${endpoints.auth.decryptTokenEndpoint}/${authToken}`
//       )
//       console.log('Decrypted user details:', response.data)
      
//       if (response.data) {
//         setUserDetails(response.data)
//         setEmailAddress(response.data.emailId || 'your email address')
        
//         // Find and set the country code object
//         if (response.data.dialCountryCode || response.data.countryCode) {
//           const countryCodeValue = response.data.dialCountryCode || response.data.countryCode
//           const foundCountry = countries.find(
//             country => country.code === countryCodeValue || country.iso2 === countryCodeValue
//           )
//           setSelectedCountryCode(foundCountry || null)
//         }
        
//         // Set phone number
//         if (response.data.mobile) {
//           setPhoneNumber(response.data.mobile)
//         }
//         return true
//       }
//       return false
//     } catch (error: any) {
//       console.error('Error decrypting token:', error)
//       setDecryptError(true)
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       setEmailAddress('your email address')
//       return false
//     }
//   }

//   // Verify token with backend - GET request with query parameter
//   const verifyTokenWithBackend = async (authToken: string) => {
//     try {
//       setIsVerifyingInitial(true)
//       setError('')
//       setVerifyError(false)

//       const response = await axios.get<ApiResponse>(
//         endpoints.auth.verifyEmailTokenEndpoint,
//         {
//           params: { token: authToken }
//         }
//       )

//       console.log('Verify Token Response:', response.data)

//       // Check for successful verification - handle both response formats
//       const isSuccess = 
//         response.data && (
//           response.data.code === 200 ||
//           response.data.isPlaid === true ||
//           response.data.plaid === true ||
//           response.data.success === true ||
//           response.data.access !== undefined // Check for access token
//         )

//       if (isSuccess) {
//         const message = response.data?.content || 'Email verified successfully!'
//         setSuccessMessage(message)
//         setIsVerifyingInitial(false)
        
//         // Store businessType from API response
//         if (response.data?.businessType) {
//           console.log('💼 Storing businessType from verifyToken response:', response.data.businessType)
//           sessionStorage.setItem('businessType', response.data.businessType)
//         }
        
//         // Check if it's a USA user (Plaid flow) - redirect immediately
//         if (response.data?.isPlaid === true || response.data?.plaid === true || response.data?.access) {
//           // If we have access token, it's a successful login for USA user
//           if (response.data?.access) {
//             const { access, refresh, profile } = response.data
//             storeUserData(access, refresh, profile, response.data?.businessType)
            
//             toast.success('Email verified! Redirecting to dashboard...')
            
//             setTimeout(() => {
//               window.location.href = '/dashboards/merchant'
//             }, 1500)
//           } else {
//             // Redirect to login for USA user to complete flow
//             setTimeout(() => {
//               router.push('/login')
//             }, 1500)
//           }
//           return true
//         }
        
//         return true
//       } else {
//         // Handle error response
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to verify email.'
//         setError(errorMsg)
//         toast.error(errorMsg)
//         setIsVerifyingInitial(false)
//         setVerifyError(true)
//         startCountdown(40)
//         return false
//       }
//     } catch (error: any) {
//       console.error('Verify token error:', error)
//       setIsVerifyingInitial(false)
//       setVerifyError(true)
      
//       // Handle error properly
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg)
//       startCountdown(40)
//       return false
//     }
//   }

//   // Main useEffect to handle the verification flow
//   useEffect(() => {
//     // Important: Wait for router to be ready and token to be available
//     if (!router.isReady) {
//       console.log('Router not ready yet...')
//       return
//     }

//     const authToken = token as string
    
//     if (!authToken) {
//       console.log('No token found in URL')
//       setError('Invalid verification link. No token provided.')
//       setPageLoaded(true)
//       setIsVerifyingInitial(false)
//       return
//     }

//     console.log('Token found in URL:', authToken)
//     setPageLoaded(true)

//     const initializeVerification = async () => {
//       // Try to decrypt token first
//       const decrypted = await decryptTokenAndGetUserDetails(authToken)
      
//       // Then verify email
//       await verifyTokenWithBackend(authToken)
//     }

//     initializeVerification()
//   }, [router.isReady, token])

//   // Handle countdown timer
//   useEffect(() => {
//     let timer: NodeJS.Timeout
//     if (countdown > 0 && countdownActive) {
//       timer = setTimeout(() => {
//         setCountdown(countdown - 1)
//       }, 1000)
//     } else if (countdown === 0 && countdownActive) {
//       setCountdownActive(false)
//       if (attempt === 0) {
//         setResendVisible(true)
//       } else if (attempt === 1) {
//         setCallVisible(true)
//       }
//     }
//     return () => clearTimeout(timer)
//   }, [countdown, countdownActive, attempt])

//   const startCountdown = (seconds: number) => {
//     setCountdown(seconds)
//     setCountdownActive(true)
//   }

//   const resetOtpInputs = () => {
//     reset(defaultValues)
//     setTimeout(() => {
//       const firstInput = document.querySelector('.CleaveInput') as HTMLInputElement
//       if (firstInput) firstInput.focus()
//     }, 100)
//   }

//   const handleFailedAttempt = () => {
//     setAttempt((prev) => {
//       const next = prev + 1
//       setCountdownActive(false)
      
//       if (next === 1) {
//         setResendVisible(true)
//         setCallVisible(false)
//       } else if (next === 2) {
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//       } else if (next >= 3) {
//         toast.error('Too many failed attempts. Please try again later.')
//         setTimeout(() => {
//           setAttempt(0)
//           setResendVisible(true)
//         }, 60000)
//       }
//       return next
//     })
//   }

//   const handleChange = (event: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
//     if (!isBackspace) {
//       onChange(event.target.value)
//       const form = event.target.form
//       if (form) {
//         const index = [...form].indexOf(event.target)
//         const formElements = [...form.elements] as HTMLInputElement[]
//         if (formElements[index].value && formElements[index].value.length) {
//           if (formElements[index + 1]) {
//             formElements[index + 1].focus()
//           }
//         }
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)
//       const form = event.currentTarget.form
//       if (form) {
//         const index = [...form.elements].indexOf(event.currentTarget)
//         if (index >= 1) {
//           const formElements = [...form.elements] as HTMLInputElement[]
//           if (!(formElements[index].value && formElements[index].value.length)) {
//             if (formElements[index - 1]) {
//               formElements[index - 1].focus()
//             }
//           }
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     const inputKeys: (keyof OtpFormValues)[] = ['val1', 'val2', 'val3', 'val4', 'val5', 'val6']
    
//     return inputKeys.map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <CleaveInput
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             onKeyDown={handleKeyDown}
//             onChange={(event: React.ChangeEvent<HTMLInputElement>) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ 
//               [theme.breakpoints.down('sm')]: { 
//                 px: `${theme.spacing(2)} !important`,
//                 marginRight: `${theme.spacing(1)} !important`
//               } 
//             }}
//           />
//         )}
//       />
//     ))
//   }

//   const handleEditPhone = () => {
//     setIsEditingPhone(true)
//   }

//   const handleCancelEdit = () => {
//     setIsEditingPhone(false)
//     if (userDetails) {
//       const foundCountry = countries.find(
//         country => country.code === (userDetails.dialCountryCode || userDetails.countryCode)
//       )
//       setSelectedCountryCode(foundCountry || null)
//       setPhoneNumber(userDetails.mobile || '')
//     }
//   }

//   const handleUpdatePhone = async () => {
//     if (!phoneNumber || phoneNumber.length < 6) {
//       toast.error('Please enter a valid phone number')
//       return
//     }

//     if (!selectedCountryCode) {
//       toast.error('Please select a country code')
//       return
//     }

//     setIsUpdatingPhone(true)
//     try {
//       const authToken = token as string
//       const payload: UpdatePhonePayload = {
//         dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2 || '',
//         countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//         mobile: phoneNumber
//       }
      
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.updatePhoneNumberEndpoint}/${authToken}`,
//         payload
//       )
      
//       if (response.data && response.data.code === 200) {
//         toast.success(response.data.content || 'Phone number updated successfully!')
//         setIsEditingPhone(false)
        
//         setUserDetails({
//           ...userDetails,
//           dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2,
//           countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//           mobile: phoneNumber
//         })
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to update phone number'
//         toast.error(errorMsg)
//       }
//     } catch (error: any) {
//       console.error('Error updating phone:', error)
//       const errorMsg = handleApiError(error)
//       toast.error(errorMsg)
//     } finally {
//       setIsUpdatingPhone(false)
//     }
//   }

//   const onSubmit = async (data: OtpFormValues) => {
//     if (isVerifying) return

//     setIsVerifying(true)
//     setError('')

//     const enteredOtp = Object.values(data).join('')
    
//     if (enteredOtp.length !== 6) {
//       setError('Please enter a valid 6-digit verification code')
//       setIsVerifying(false)
//       return
//     }
    
//     const encryptedOtp = encryptAES(enteredOtp)
    
//     if (!encryptedOtp) {
//       setError('Failed to encrypt verification code. Please try again.')
//       setIsVerifying(false)
//       return
//     }
    
//     const authToken = token as string
//     const payload = {
//       otp: encryptedOtp
//     }

//     const toastId = toast.loading('Verifying OTP...')

//     try {
//       console.log('=== Email OTP Verification Request ===')
//       console.log('Token:', authToken)
      
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.sendOtpForEmailEndpoint}/${authToken}`,
//         payload
//       )
      
//       console.log('=== Email OTP Verification Response ===')
//       console.log('Full Response:', response.data)
      
//       // Check for successful verification - handle both response formats
//       const isSuccess = 
//         response.data && (
//           response.data.code === 200 ||
//           response.data.isPlaid === true ||
//           response.data.plaid === true ||
//           response.data.success === true ||
//           response.data.access !== undefined // Check for access token
//         )

//       if (isSuccess) {
//         const message = response.data?.content || 'Email verified successfully!'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
        
//         // Store businessType from API response
//         if (response.data?.businessType) {
//           console.log('💼 Storing businessType from OTP response:', response.data.businessType)
//           sessionStorage.setItem('businessType', response.data.businessType)
//         }
        
//         // Check if it's a USA user (Plaid flow) with access token
//         if (response.data?.access) {
//           // Store user data and redirect to merchant dashboard
//           const { access, refresh, profile } = response.data
//           storeUserData(access, refresh, profile, response.data?.businessType)
          
//           console.log('Application ID:', profile?.applicationId)
          
//           setTimeout(() => {
//             window.location.href = '/dashboards/merchant'
//           }, 1500)
//         } 
//         // Check if it's a USA user but no access token yet
//         else if (response.data?.isPlaid === true || response.data?.plaid === true) {
//           // Redirect to login for USA user to complete flow
//           toast.success('Email verified! Please login to continue.', {
//             id: toastId,
//             duration: 3000
//           })
          
//           setTimeout(() => {
//             router.push('/login')
//           }, 1500)
//         } 
//         // India user - redirect to document verify
//         else {
//           setTimeout(() => {
//             router.push('/document-verify')
//           }, 1500)
//         }
//       } else {
//         // Handle error response
//         const errorMsg = response.data?.message || response.data?.content || 'Invalid verification code. Please try again.'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//         handleFailedAttempt()
//         resetOtpInputs()
//       }
//     } catch (error: any) {
//       console.error('=== Email OTP Verification Error ===')
//       console.error('Error:', error)
//       console.error('Error Response:', error.response?.data)
      
//       // Check if the response actually succeeded but went to catch
//       if (error.response?.data?.access) {
//         const { access, refresh, profile } = error.response.data
        
//         console.log('Application ID from catch block:', profile?.applicationId)
        
//         // Store businessType from API response
//         if (error.response?.data?.businessType) {
//           console.log('💼 Storing businessType from catch block:', error.response.data.businessType)
//           sessionStorage.setItem('businessType', error.response.data.businessType)
//         }
        
//         storeUserData(access, refresh, profile, error.response?.data?.businessType)
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 3000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//         return
//       }
      
//       // Check for alternative response structure in catch block
//       if (error.response?.data?.content?.access) {
//         const { access, refresh, profile } = error.response.data.content
        
//         console.log('Application ID from catch block (content):', profile?.applicationId)
        
//         // Store businessType from API response
//         if (error.response?.data?.businessType) {
//           console.log('💼 Storing businessType from catch block (content):', error.response.data.businessType)
//           sessionStorage.setItem('businessType', error.response.data.businessType)
//         }
        
//         storeUserData(access, refresh, profile, error.response?.data?.businessType)
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 3000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//         return
//       }
      
//       // Handle error properly using the helper function
//       let errorMessage = handleApiError(error)
      
//       // Override with specific messages for known error cases
//       if (error.response?.data?.content === 'Email and phone is already verified.') {
//         errorMessage = 'Email and phone is already verified. Please login to continue.'
//         toast.success('Email and phone already verified! Redirecting to login...', {
//           id: toastId,
//           duration: 3000
//         })
//         setTimeout(() => {
//           router.push('/login')
//         }, 2000)
//         return
//       }
      
//       if (error.response?.status === 400) {
//         errorMessage = error.response?.data?.content || 'Invalid OTP. Please check and try again.'
//       } else if (error.response?.status === 500) {
//         errorMessage = 'Server error. Please try again later.'
//       } else if (!error.response) {
//         errorMessage = 'Network error. Please check your connection.'
//       }
      
//       console.log('Error Message:', errorMessage)
      
//       toast.error(errorMessage, {
//         id: toastId,
//         duration: 5000
//       })
//       setError(errorMessage)
//       handleFailedAttempt()
//       resetOtpInputs()
//     } finally {
//       setIsVerifying(false)
//     }
//   }

//   const handleResendOTP = async () => {
//     if (isResending) return

//     setIsResending(true)
//     setError('')
//     setSuccessMessage('')

//     const toastId = toast.loading('Resending OTP...')

//     try {
//       const authToken = token as string
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A new verification code has been sent to your email.'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
//         setAttempt(1)
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to resend OTP'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//       }
//     } catch (error: any) {
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg, {
//         id: toastId,
//         duration: 5000
//       })
//     } finally {
//       setIsResending(false)
//     }
//   }

//   const handleCallOTP = async () => {
//     if (isCalling) return

//     setIsCalling(true)
//     setError('')
//     setSuccessMessage('')

//     const toastId = toast.loading('Sending OTP via call...')

//     try {
//       const authToken = token as string
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpCallEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A verification code has been sent via call.'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
//         setAttempt(2)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to send OTP via call'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//       }
//     } catch (error: any) {
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg, {
//         id: toastId,
//         duration: 5000
//       })
//     } finally {
//       setIsCalling(false)
//     }
//   }

//   const formatTime = (seconds: number): string => {
//     const mins = Math.floor(seconds / 60)
//     const secs = seconds % 60
//     return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
//   }

//   const imageSource = skin === 'bordered' ? 'auth-v2-two-steps-illustration-bordered' : 'auth-v2-two-steps-illustration'

//   // Show loading while router is not ready
//   if (!router.isReady || !pageLoaded) {
//     return (
//       <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
//         <CircularProgress />
//       </Box>
//     )
//   }

//   if (isVerifyingInitial) {
//     return (
//       <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//         <RightWrapper>
//           <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//             <Box sx={{ textAlign: 'center' }}>
//               <CircularProgress size={60} />
//               <Typography sx={{ mt: 4, color: 'text.secondary' }}>
//                 Verifying your email...
//               </Typography>
//             </Box>
//           </Box>
//         </RightWrapper>
//       </Box>
//     )
//   }

//   return (
//     <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//       {!hidden ? (
//         <Box
//           sx={{
//             flex: 1,
//             display: 'flex',
//             position: 'relative',
//             alignItems: 'center',
//             borderRadius: '20px',
//             justifyContent: 'center',
//             backgroundColor: 'customColors.bodyBg',
//             margin: theme => theme.spacing(8, 0, 8, 8)
//           }}
//         >
//           <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
//             <AnimatePresence mode='wait'>
//               <motion.div
//                 key='verify'
//                 initial={{ opacity: 0 }}
//                 animate={{ opacity: 1 }}
//                 exit={{ opacity: 0 }}
//                 transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
//                 style={{
//                   position: 'absolute',
//                   width: '100%',
//                   height: '100%',
//                   display: 'flex',
//                   justifyContent: 'center',
//                   alignItems: 'center'
//                 }}
//               >
//                 <TwoStepsIllustration 
//                   alt='two-steps-illustration' 
//                   src={`/images/pages/${imageSource}-${theme.palette.mode}.png`} 
//                 />
//               </motion.div>
//             </AnimatePresence>
//           </Box>
//         </Box>
//       ) : null}

//       <RightWrapper>
//         <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//           <AnimatePresence mode='wait'>
//             <motion.div
//               key='verify-form'
//               initial='hiddenRight'
//               animate='visible'
//               exit='exitLeft'
//               variants={slideVariants}
//               transition={{ duration: 0.5 }}
//               style={{ width: '100%', display: 'flex', justifyContent: 'center' }}
//             >
//               <Box sx={{ width: '100%', maxWidth: 400 }}>
//                 <img
//                   src='/images/website-logo/LockTrust-logo.png'
//                   alt='LockTrust Logo'
//                   style={{ height: '60px', width: 'auto', objectFit: 'contain' }}
//                 />

//                 <motion.div
//                   initial={{ y: -20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.3, duration: 0.5 }}
//                 >
//                   <Box sx={{ mb: 6 }}>
//                     <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//                       Verify Your Email 💬
//                     </Typography>
//                     <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//                       Enter the verification code sent to your email to verify your email address.
//                     </Typography>
                    
//                     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
//                       <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
//                         {emailAddress}
//                       </Typography>
//                       {userDetails?.emailVerified && (
//                         <Box sx={{ display: 'flex', alignItems: 'center', color: 'success.main' }}>
//                           <Icon icon='tabler:circle-check-filled' fontSize={20} />
//                           <Typography variant='caption' sx={{ ml: 0.5, color: 'success.main' }}>
//                             Verified
//                           </Typography>
//                         </Box>
//                       )}
//                     </Box>
//                   </Box>
//                 </motion.div>

//                 {userDetails && (
//                   <motion.div
//                     initial={{ y: 20, opacity: 0 }}
//                     animate={{ y: 0, opacity: 1 }}
//                     transition={{ delay: 0.35, duration: 0.5 }}
//                   >
//                     <Box sx={{ mb: 4, p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
//                       <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
//                         <Typography variant='body2' sx={{ fontWeight: 500, color: 'text.secondary' }}>
//                           Phone Number
//                         </Typography>
//                         {!isEditingPhone && (
//                           <IconButton size='small' onClick={handleEditPhone} sx={{ color: 'primary.main' }}>
//                             <Icon icon='tabler:edit' fontSize={20} />
//                           </IconButton>
//                         )}
//                       </Box>
                      
//                       {!isEditingPhone ? (
//                         <>
//                           <Typography variant='body1' sx={{ fontWeight: 500 }}>
//                             {userDetails.countryCode || '+91'} {userDetails.mobile}
//                           </Typography>
//                           {!userDetails.phoneVerified && (
//                             <Typography variant='caption' sx={{ color: 'warning.main', display: 'block', mt: 0.5 }}>
//                               Not verified yet
//                             </Typography>
//                           )}
//                         </>
//                       ) : (
//                         <Box sx={{ mt: 2 }}>
//                           <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
//                             <FormControl fullWidth sx={{ flex: 0.5 }}>
//                               <Autocomplete
//                                 id='country-select'
//                                 options={countries}
//                                 autoHighlight
//                                 getOptionLabel={(option: CountryOption) => {
//                                   if (!option) return ''
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   return dialCode ? `${name} (+${dialCode})` : name
//                                 }}
//                                 value={selectedCountryCode}
//                                 onChange={(event: any, newValue: CountryOption | null) => {
//                                   setSelectedCountryCode(newValue)
//                                 }}
//                                 renderOption={(props, option) => {
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   const countryCodeISO = option.code || option.iso2 || ''
//                                   return (
//                                     <Box component='li' sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                                       <img
//                                         loading='lazy'
//                                         width='24'
//                                         height='18'
//                                         src={`https://flagcdn.com/w40/${countryCodeISO?.toLowerCase()}.png`}
//                                         srcSet={`https://flagcdn.com/w80/${countryCodeISO?.toLowerCase()}.png 2x`}
//                                         alt=""
//                                         style={{ marginRight: '12px' }}
//                                       />
//                                       <span style={{ fontWeight: 500 }}>{name}</span>
//                                       {dialCode && (
//                                         <span style={{ marginLeft: '8px', color: '#666' }}>(+{dialCode})</span>
//                                       )}
//                                     </Box>
//                                   )
//                                 }}
//                                 renderInput={(params) => (
//                                   <TextField
//                                     {...params}
//                                     label='Country Code'
//                                     placeholder='Select country'
//                                     size='small'
//                                     InputProps={{
//                                       ...params.InputProps,
//                                       startAdornment: selectedCountryCode && (selectedCountryCode.code || selectedCountryCode.iso2) && (
//                                         <img
//                                           src={`https://flagcdn.com/w20/${(selectedCountryCode.code || selectedCountryCode.iso2)?.toLowerCase()}.png`}
//                                           style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                                           width='24'
//                                           height='18'
//                                           alt="flag"
//                                         />
//                                       ),
//                                     }}
//                                   />
//                                 )}
//                               />
//                             </FormControl>
                            
//                             <TextField
//                               fullWidth
//                               size='small'
//                               label='Phone Number'
//                               value={phoneNumber}
//                               onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ''))}
//                               placeholder='Enter phone number'
//                               inputProps={{ maxLength: 15 }}
//                               sx={{ flex: 0.5 }}
//                             />
//                           </Box>
                          
//                           <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
//                             <Button size='small' onClick={handleCancelEdit} disabled={isUpdatingPhone}>
//                               Cancel
//                             </Button>
//                             <Button 
//                               size='small' 
//                               variant='contained' 
//                               onClick={handleUpdatePhone} 
//                               disabled={isUpdatingPhone}
//                             >
//                               {isUpdatingPhone ? <CircularProgress size={20} /> : 'Save'}
//                             </Button>
//                           </Box>
//                         </Box>
//                       )}
//                     </Box>
//                   </motion.div>
//                 )}

//                 {/* Success Alert */}
//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.4, duration: 0.5 }}
//                 >
//                   {successMessage && (
//                     <Alert 
//                       severity='success' 
//                       sx={{ mb: 4 }}
//                       onClose={() => setSuccessMessage('')}
//                     >
//                       {successMessage}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 {/* Error Alert */}
//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.45, duration: 0.5 }}
//                 >
//                   {error && (
//                     <Alert severity='error' sx={{ mb: 4 }} onClose={() => setError('')}>
//                       {error}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.5, duration: 0.5 }}
//                 >
//                   <Typography sx={{ fontWeight: 500, color: 'text.secondary', mb: 2 }}>
//                     Type your 6-digit verification code
//                   </Typography>
//                 </motion.div>

//                 {/* Verification Form */}
//                 <motion.form
//                   onSubmit={handleSubmit(onSubmit)}
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.6, duration: 0.5 }}
//                 >
//                   <CleaveWrapper
//                     sx={{
//                       display: 'flex',
//                       alignItems: 'center',
//                       justifyContent: 'space-between',
//                       ...(errorsArray.length && {
//                         '& .invalid:focus': {
//                           borderColor: theme => `${theme.palette.error.main} !important`,
//                           boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//                         }
//                       })
//                     }}
//                   >
//                     {renderInputs()}
//                   </CleaveWrapper>
                  
//                   {errorsArray.length ? (
//                     <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid verification code</FormHelperText>
//                   ) : null}

//                   <Button 
//                     fullWidth 
//                     type='submit' 
//                     variant='contained' 
//                     disabled={isVerifying} 
//                     sx={{ mt: 4 }}
//                   >
//                     {isVerifying ? (
//                       <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                         <CircularProgress size={24} color='inherit' />
//                         Verifying...
//                       </Box>
//                     ) : (
//                       'Verify Email'
//                     )}
//                   </Button>
//                 </motion.form>

//                 {/* Clock and Options Section */}
//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.7, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}>
//                     {/* Clock/Watch Image with Countdown - Always show when countdown is active */}
//                     {countdownActive && countdown > 0 && (
//                       <Box sx={{ position: 'relative', display: 'inline-block', mb: 2 }}>
//                         <img 
//                           src='/images/clock.jpg'
//                           alt='Clock'
//                           style={{
//                             width: '100px',
//                             height: '100px',
//                             display: 'block',
//                             margin: '0 auto'
//                           }}
//                         />
//                         <Box
//                           sx={{
//                             position: 'absolute',
//                             top: '50%',
//                             left: '50%',
//                             transform: 'translate(-50%, -50%)',
//                             fontSize: '14px',
//                             fontWeight: 'bold',
//                             color: 'white'
//                           }}
//                         >
//                           {formatTime(countdown)}
//                         </Box>
//                       </Box>
//                     )}

//                     {/* Resend Button - Shows when resendVisible is true OR when countdown ends on attempt 0 */}
//                     {resendVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
//                         <LinkStyled 
//                           href='#' 
//                           onClick={handleResendOTP}
//                           sx={{ 
//                             pointerEvents: isResending ? 'none' : 'auto',
//                             opacity: isResending ? 0.6 : 1
//                           }}
//                         >
//                           {isResending ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Resend OTP'
//                           )}
//                         </LinkStyled>
//                       </Box>
//                     )}

//                     {/* Call Button - Shows when callVisible is true */}
//                     {callVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Still having trouble?</Typography>
//                         <CallLinkStyled 
//                           href='#' 
//                           onClick={handleCallOTP}
//                           sx={{ 
//                             pointerEvents: isCalling ? 'none' : 'auto',
//                             opacity: isCalling ? 0.6 : 1
//                           }}
//                         >
//                           {isCalling ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Call Me'
//                           )}
//                         </CallLinkStyled>
//                       </Box>
//                     )}
//                   </Box>
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.9, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                     <Button
//                       variant='text'
//                       onClick={() => router.push('/login')}
//                       sx={{ textTransform: 'none' }}
//                       startIcon={<Icon icon='tabler:arrow-left' />}
//                     >
//                       Back to Login
//                     </Button>
//                   </Box>
//                 </motion.div>
//               </Box>
//             </motion.div>
//           </AnimatePresence>
//         </Box>
//       </RightWrapper>
//     </Box>
//   )
// }

// EmailVerify.getLayout = page => <BlankLayout>{page}</BlankLayout>
// EmailVerify.guestGuard = true

// export default EmailVerify
 
// document page redirect //////////////////////////////////
// import { useState, useEffect } from 'react'

// // ** Next Imports
// import Link from 'next/link'
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import FormControl from '@mui/material/FormControl'
// import useMediaQuery from '@mui/material/useMediaQuery'
// import { styled, useTheme } from '@mui/material/styles'
// import FormHelperText from '@mui/material/FormHelperText'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import TextField from '@mui/material/TextField'
// import IconButton from '@mui/material/IconButton'
// import Autocomplete from '@mui/material/Autocomplete'

// // ** Animation Imports
// import { AnimatePresence, motion } from 'framer-motion'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Third Party Imports
// import Cleave from 'cleave.js/react'
// import { useForm, Controller } from 'react-hook-form'
// import CryptoJS from 'crypto-js'

// // ** Hooks
// import { useSettings } from 'src/@core/hooks/useSettings'

// // ** Layout Import
// import BlankLayout from 'src/@core/layouts/BlankLayout'

// // ** Custom Styled Component
// import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// // ** Util Import
// import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// // ** Fake DB Import for countries
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios & Endpoints
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'
// import authConfig from 'src/configs/auth'

// // ** Styles
// import 'cleave.js/dist/addons/cleave-phone.us'

// // ** Types
// interface UserDetails {
//   dialCountryCode?: string
//   firstName?: string
//   lastName?: string
//   emailVerified?: boolean
//   countryCode?: string
//   phoneVerified?: boolean
//   mobile?: string
//   emailId?: string
// }

// interface CountryOption {
//   code?: string
//   iso2?: string
//   dialCode?: string
//   phone?: string
//   name?: string
//   label?: string
// }

// interface ApiResponse {
//   code: number
//   content: string
//   message?: string
//   uid?: string | null
//   timestamp?: string
//   success?: boolean
//   isPlaid?: boolean
//   plaid?: boolean
//   access?: string
//   refresh?: string
//   expiresIn?: number
//   businessType?: string
//   token?: string // The token to use for document verification
//   profile?: {
//     firstName?: string
//     lastName?: string
//     uid?: string
//     mobileNum?: string
//     emailId?: string
//     applicationId?: string
//     isPinSetup?: boolean
//     isSubUser?: boolean
//     TwoNf?: boolean
//     businessType?: string
//     allPermissions?: Array<{
//       moduleName: string
//       action: string
//     }>
//     permissions?: Array<{
//       moduleName: string
//       action: string
//     }>
//   }
// }

// interface UpdatePhonePayload {
//   dialCountryCode: string
//   countryCode: string
//   mobile: string
// }

// interface OtpFormValues {
//   val1: string
//   val2: string
//   val3: string
//   val4: string
//   val5: string
//   val6: string
// }

// // ** Animation Variants
// const slideVariants = {
//   hiddenLeft: { x: -400, opacity: 0 },
//   hiddenRight: { x: 400, opacity: 0 },
//   visible: { x: 0, opacity: 1 },
//   exitLeft: { x: -400, opacity: 0 },
//   exitRight: { x: 400, opacity: 0 }
// }

// // ** Styled Components
// const TwoStepsIllustration = styled('img')(({ theme }) => ({
//   zIndex: 2,
//   maxHeight: 650,
//   marginTop: theme.spacing(12),
//   marginBottom: theme.spacing(12),
//   [theme.breakpoints.down(1540)]: {
//     maxHeight: 550
//   },
//   [theme.breakpoints.down('lg')]: {
//     maxHeight: 500
//   }
// }))

// const RightWrapper = styled(Box)(({ theme }) => ({
//   width: '100%',
//   [theme.breakpoints.up('md')]: {
//     maxWidth: 450
//   },
//   [theme.breakpoints.up('lg')]: {
//     maxWidth: 600
//   },
//   [theme.breakpoints.up('xl')]: {
//     maxWidth: 750
//   }
// }))

// const LinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(2),
//   color: theme.palette.primary.main,
//   cursor: 'pointer'
// }))

// const CallLinkStyled = styled(Link)(({ theme }) => ({
//   fontSize: '1rem',
//   textDecoration: 'none',
//   marginLeft: theme.spacing(1),
//   color: theme.palette.error.main,
//   cursor: 'pointer'
// }))

// const CleaveInput = styled(Cleave)(({ theme }) => ({
//   maxWidth: 48,
//   textAlign: 'center',
//   height: '48px !important',
//   fontSize: '150% !important',
//   marginTop: theme.spacing(2),
//   marginBottom: theme.spacing(2),
//   '&:not(:last-child)': {
//     marginRight: theme.spacing(2)
//   },
//   '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
//     margin: 0,
//     WebkitAppearance: 'none'
//   },
//   [theme.breakpoints.down('sm')]: {
//     maxWidth: 40,
//     height: '40px !important',
//     fontSize: '120% !important'
//   }
// }))

// const defaultValues: OtpFormValues = {
//   val1: '',
//   val2: '',
//   val3: '',
//   val4: '',
//   val5: '',
//   val6: ''
// }

// // Secret key for AES encryption
// const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

// const deriveAESKey = (): CryptoJS.lib.WordArray => {
//   const secretWordArray = CryptoJS.enc.Utf8.parse(SECRET_KEY)
//   const keyHash = CryptoJS.SHA256(secretWordArray)
//   return keyHash
// }

// const encryptAES = (plainText: string): string | null => {
//   try {
//     const iv = CryptoJS.lib.WordArray.random(16)
//     const key = deriveAESKey()
//     const encrypted = CryptoJS.AES.encrypt(plainText, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })
//     const combined = iv.concat(encrypted.ciphertext)
//     return CryptoJS.enc.Base64.stringify(combined)
//   } catch (error) {
//     console.error('Encryption error:', error)
//     return null
//   }
// }

// // Helper function to store user data
// const storeUserData = (access: string, refresh: string, profile: any, businessType?: string) => {
//   let formattedPermissions = []
//   if (profile?.allPermissions && profile.allPermissions.length > 0) {
//     formattedPermissions = profile.allPermissions
//   } else if (profile?.permissions && profile.permissions.length > 0) {
//     formattedPermissions = profile.permissions.map((p: any) => ({
//       moduleName: p.moduleName,
//       action: p.action
//     }))
//   } else {
//     formattedPermissions = [
//       { moduleName: 'dashboard', action: 'CREATE' },
//       { moduleName: 'dashboard', action: 'UPDATE' },
//       { moduleName: 'dashboard', action: 'VIEW' },
//       { moduleName: 'dashboard', action: 'DELETE' }
//     ]
//   }

//   const userData = {
//     id: profile?.uid || profile?.id,
//     role: profile?.isSubUser ? 'subUser' : 'merchant',
//     fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
//     firstName: profile?.firstName,
//     lastName: profile?.lastName,
//     mobileNum: profile?.mobileNum,
//     username: profile?.emailId,
//     email: profile?.emailId,
//     isSubUser: profile?.isSubUser || false,
//     TwoNf: profile?.TwoNf || false,
//     isPinSetup: profile?.isPinSetup || false,
//     allPermissions: formattedPermissions,
//     permissions: formattedPermissions,
//     applicationId: profile?.applicationId || null,
//     businessType: businessType || profile?.businessType || null
//   }
  
//   localStorage.setItem(authConfig.storageTokenKeyName, access)
//   localStorage.setItem('refreshToken', refresh)
//   localStorage.setItem('userData', JSON.stringify(userData))
//   localStorage.setItem('isAuthenticated', 'true')
  
//   return userData
// }

// // Helper function to handle API errors
// const handleApiError = (error: any): string => {
//   console.error('API Error:', error)
  
//   if (error.response?.data) {
//     const data = error.response.data
    
//     if (data.content) {
//       return data.content
//     }
    
//     if (data.message) {
//       return data.message
//     }
    
//     if (data.detail) {
//       return data.detail
//     }
    
//     if (data.errors) {
//       if (typeof data.errors === 'string') {
//         return data.errors
//       }
//       if (Array.isArray(data.errors)) {
//         return data.errors.join(', ')
//       }
//       if (typeof data.errors === 'object') {
//         const errorMessages = Object.values(data.errors).flat()
//         return errorMessages.join(', ')
//       }
//     }
//   }
  
//   if (error.message) {
//     return error.message
//   }
  
//   return 'An unexpected error occurred. Please try again.'
// }

// const EmailVerify = () => {
//   const [isVerifying, setIsVerifying] = useState(false)
//   const [isResending, setIsResending] = useState(false)
//   const [isCalling, setIsCalling] = useState(false)
//   const [error, setError] = useState('')
//   const [successMessage, setSuccessMessage] = useState('')
//   const [isBackspace, setIsBackspace] = useState(false)
//   const [isVerifyingInitial, setIsVerifyingInitial] = useState(true)
//   const [emailAddress, setEmailAddress] = useState('')
//   const [userDetails, setUserDetails] = useState<UserDetails | null>(null)
//   const [isEditingPhone, setIsEditingPhone] = useState(false)
//   const [selectedCountryCode, setSelectedCountryCode] = useState<CountryOption | null>(null)
//   const [phoneNumber, setPhoneNumber] = useState('')
//   const [isUpdatingPhone, setIsUpdatingPhone] = useState(false)
//   const [pageLoaded, setPageLoaded] = useState(false)
//   const [decryptError, setDecryptError] = useState(false)
//   const [verifyError, setVerifyError] = useState(false)
  
//   const [attempt, setAttempt] = useState(0)
//   const [resendVisible, setResendVisible] = useState(false)
//   const [callVisible, setCallVisible] = useState(false)
//   const [countdown, setCountdown] = useState(0)
//   const [countdownActive, setCountdownActive] = useState(false)

//   const router = useRouter()
//   const { token } = router.query

//   const theme = useTheme()
//   const { settings } = useSettings()
//   const hidden = useMediaQuery(theme.breakpoints.down('md'))
//   const { skin } = settings

//   const {
//     control,
//     handleSubmit,
//     reset,
//     formState: { errors }
//   } = useForm<OtpFormValues>({ defaultValues })

//   const errorsArray = Object.keys(errors)

//   const decryptTokenAndGetUserDetails = async (authToken: string) => {
//     try {
//       setDecryptError(false)
//       const response = await axios.get<UserDetails>(
//         `${endpoints.auth.decryptTokenEndpoint}/${authToken}`
//       )
//       console.log('Decrypted user details:', response.data)
      
//       if (response.data) {
//         setUserDetails(response.data)
//         setEmailAddress(response.data.emailId || 'your email address')
        
//         if (response.data.dialCountryCode || response.data.countryCode) {
//           const countryCodeValue = response.data.dialCountryCode || response.data.countryCode
//           const foundCountry = countries.find(
//             country => country.code === countryCodeValue || country.iso2 === countryCodeValue
//           )
//           setSelectedCountryCode(foundCountry || null)
//         }
        
//         if (response.data.mobile) {
//           setPhoneNumber(response.data.mobile)
//         }
//         return true
//       }
//       return false
//     } catch (error: any) {
//       console.error('Error decrypting token:', error)
//       setDecryptError(true)
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       setEmailAddress('your email address')
//       return false
//     }
//   }

//   const verifyTokenWithBackend = async (authToken: string) => {
//     try {
//       setIsVerifyingInitial(true)
//       setError('')
//       setVerifyError(false)

//       const response = await axios.get<ApiResponse>(
//         endpoints.auth.verifyEmailTokenEndpoint,
//         {
//           params: { token: authToken }
//         }
//       )

//       console.log('Verify Token Response:', response.data)

//       const isSuccess = 
//         response.data && (
//           response.data.code === 200 ||
//           response.data.isPlaid === true ||
//           response.data.plaid === true ||
//           response.data.success === true ||
//           response.data.access !== undefined
//         )

//       if (isSuccess) {
//         const message = response.data?.content || 'Email verified successfully!'
//         setSuccessMessage(message)
//         setIsVerifyingInitial(false)
        
//         // Store businessType and token for document verification
//         if (response.data?.businessType) {
//           sessionStorage.setItem('businessType', response.data.businessType)
//         }
//         if (response.data?.token) {
//           sessionStorage.setItem('verificationToken', response.data.token)
//         }
        
//         // Check if it's a USA user (Plaid flow) - redirect immediately
//         if (response.data?.isPlaid === true || response.data?.plaid === true || response.data?.access) {
//           if (response.data?.access) {
//             const { access, refresh, profile } = response.data
//             storeUserData(access, refresh, profile, response.data?.businessType)
            
//             toast.success('Email verified! Redirecting to dashboard...')
            
//             setTimeout(() => {
//               window.location.href = '/dashboards/merchant'
//             }, 1500)
//           } else {
//             setTimeout(() => {
//               router.push('/login')
//             }, 1500)
//           }
//           return true
//         }
        
//         return true
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to verify email.'
//         setError(errorMsg)
//         toast.error(errorMsg)
//         setIsVerifyingInitial(false)
//         setVerifyError(true)
//         startCountdown(40)
//         return false
//       }
//     } catch (error: any) {
//       console.error('Verify token error:', error)
//       setIsVerifyingInitial(false)
//       setVerifyError(true)
      
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg)
//       startCountdown(40)
//       return false
//     }
//   }

//   useEffect(() => {
//     if (!router.isReady) {
//       console.log('Router not ready yet...')
//       return
//     }

//     const authToken = token as string
    
//     if (!authToken) {
//       console.log('No token found in URL')
//       setError('Invalid verification link. No token provided.')
//       setPageLoaded(true)
//       setIsVerifyingInitial(false)
//       return
//     }

//     console.log('Token found in URL:', authToken)
//     setPageLoaded(true)

//     const initializeVerification = async () => {
//       await decryptTokenAndGetUserDetails(authToken)
//       await verifyTokenWithBackend(authToken)
//     }

//     initializeVerification()
//   }, [router.isReady, token])

//   useEffect(() => {
//     let timer: NodeJS.Timeout
//     if (countdown > 0 && countdownActive) {
//       timer = setTimeout(() => {
//         setCountdown(countdown - 1)
//       }, 1000)
//     } else if (countdown === 0 && countdownActive) {
//       setCountdownActive(false)
//       if (attempt === 0) {
//         setResendVisible(true)
//       } else if (attempt === 1) {
//         setCallVisible(true)
//       }
//     }
//     return () => clearTimeout(timer)
//   }, [countdown, countdownActive, attempt])

//   const startCountdown = (seconds: number) => {
//     setCountdown(seconds)
//     setCountdownActive(true)
//   }

//   const resetOtpInputs = () => {
//     reset(defaultValues)
//     setTimeout(() => {
//       const firstInput = document.querySelector('.CleaveInput') as HTMLInputElement
//       if (firstInput) firstInput.focus()
//     }, 100)
//   }

//   const handleFailedAttempt = () => {
//     setAttempt((prev) => {
//       const next = prev + 1
//       setCountdownActive(false)
      
//       if (next === 1) {
//         setResendVisible(true)
//         setCallVisible(false)
//       } else if (next === 2) {
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//       } else if (next >= 3) {
//         toast.error('Too many failed attempts. Please try again later.')
//         setTimeout(() => {
//           setAttempt(0)
//           setResendVisible(true)
//         }, 60000)
//       }
//       return next
//     })
//   }

//   const handleChange = (event: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
//     if (!isBackspace) {
//       onChange(event.target.value)
//       const form = event.target.form
//       if (form) {
//         const index = [...form].indexOf(event.target)
//         const formElements = [...form.elements] as HTMLInputElement[]
//         if (formElements[index].value && formElements[index].value.length) {
//           if (formElements[index + 1]) {
//             formElements[index + 1].focus()
//           }
//         }
//       }
//       event.preventDefault()
//     }
//   }

//   const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
//     if (event.key === 'Backspace') {
//       setIsBackspace(true)
//       const form = event.currentTarget.form
//       if (form) {
//         const index = [...form.elements].indexOf(event.currentTarget)
//         if (index >= 1) {
//           const formElements = [...form.elements] as HTMLInputElement[]
//           if (!(formElements[index].value && formElements[index].value.length)) {
//             if (formElements[index - 1]) {
//               formElements[index - 1].focus()
//             }
//           }
//         }
//       }
//     } else {
//       setIsBackspace(false)
//     }
//   }

//   const renderInputs = () => {
//     const inputKeys: (keyof OtpFormValues)[] = ['val1', 'val2', 'val3', 'val4', 'val5', 'val6']
    
//     return inputKeys.map((val, index) => (
//       <Controller
//         key={val}
//         name={val}
//         control={control}
//         rules={{ required: true }}
//         render={({ field: { value, onChange } }) => (
//           <CleaveInput
//             type='tel'
//             value={value}
//             autoFocus={index === 0}
//             onKeyDown={handleKeyDown}
//             onChange={(event: React.ChangeEvent<HTMLInputElement>) => handleChange(event, onChange)}
//             options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
//             sx={{ 
//               [theme.breakpoints.down('sm')]: { 
//                 px: `${theme.spacing(2)} !important`,
//                 marginRight: `${theme.spacing(1)} !important`
//               } 
//             }}
//           />
//         )}
//       />
//     ))
//   }

//   const handleEditPhone = () => {
//     setIsEditingPhone(true)
//   }

//   const handleCancelEdit = () => {
//     setIsEditingPhone(false)
//     if (userDetails) {
//       const foundCountry = countries.find(
//         country => country.code === (userDetails.dialCountryCode || userDetails.countryCode)
//       )
//       setSelectedCountryCode(foundCountry || null)
//       setPhoneNumber(userDetails.mobile || '')
//     }
//   }

//   const handleUpdatePhone = async () => {
//     if (!phoneNumber || phoneNumber.length < 6) {
//       toast.error('Please enter a valid phone number')
//       return
//     }

//     if (!selectedCountryCode) {
//       toast.error('Please select a country code')
//       return
//     }

//     setIsUpdatingPhone(true)
//     try {
//       const authToken = token as string
//       const payload: UpdatePhonePayload = {
//         dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2 || '',
//         countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//         mobile: phoneNumber
//       }
      
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.updatePhoneNumberEndpoint}/${authToken}`,
//         payload
//       )
      
//       if (response.data && response.data.code === 200) {
//         toast.success(response.data.content || 'Phone number updated successfully!')
//         setIsEditingPhone(false)
        
//         setUserDetails({
//           ...userDetails,
//           dialCountryCode: selectedCountryCode.code || selectedCountryCode.iso2,
//           countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone}`,
//           mobile: phoneNumber
//         })
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to update phone number'
//         toast.error(errorMsg)
//       }
//     } catch (error: any) {
//       console.error('Error updating phone:', error)
//       const errorMsg = handleApiError(error)
//       toast.error(errorMsg)
//     } finally {
//       setIsUpdatingPhone(false)
//     }
//   }

//   const onSubmit = async (data: OtpFormValues) => {
//     if (isVerifying) return

//     setIsVerifying(true)
//     setError('')

//     const enteredOtp = Object.values(data).join('')
    
//     if (enteredOtp.length !== 6) {
//       setError('Please enter a valid 6-digit verification code')
//       setIsVerifying(false)
//       return
//     }
    
//     const encryptedOtp = encryptAES(enteredOtp)
    
//     if (!encryptedOtp) {
//       setError('Failed to encrypt verification code. Please try again.')
//       setIsVerifying(false)
//       return
//     }
    
//     const authToken = token as string
//     const payload = {
//       otp: encryptedOtp
//     }

//     const toastId = toast.loading('Verifying OTP...')

//     try {
//       console.log('=== Email OTP Verification Request ===')
//       console.log('Token:', authToken)
      
//       const response = await axios.post<ApiResponse>(
//         `${endpoints.auth.sendOtpForEmailEndpoint}/${authToken}`,
//         payload
//       )
      
//       console.log('=== Email OTP Verification Response ===')
//       console.log('Full Response:', response.data)
      
//       const isSuccess = 
//         response.data && (
//           response.data.code === 200 ||
//           response.data.isPlaid === true ||
//           response.data.plaid === true ||
//           response.data.success === true ||
//           response.data.access !== undefined
//         )

//       if (isSuccess) {
//         const message = response.data?.content || 'Email verified successfully!'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
        
//         // Store businessType and token for document verification
//         if (response.data?.businessType) {
//           sessionStorage.setItem('businessType', response.data.businessType)
//         }
//         if (response.data?.token) {
//           sessionStorage.setItem('verificationToken', response.data.token)
//         }
        
//         // Check if it's a USA user (Plaid flow) with access token
//         if (response.data?.access) {
//           const { access, refresh, profile } = response.data
//           storeUserData(access, refresh, profile, response.data?.businessType)
          
//           setTimeout(() => {
//             window.location.href = '/dashboards/merchant'
//           }, 1500)
//         } 
//         // Check if it's a USA user but no access token yet
//         else if (response.data?.isPlaid === true || response.data?.plaid === true) {
//           toast.success('Email verified! Please login to continue.', {
//             id: toastId,
//             duration: 3000
//           })
          
//           setTimeout(() => {
//             router.push('/login')
//           }, 1500)
//         } 
//         // India user - redirect to document verify with token and businessType
//         else {
//           const verificationToken = response.data?.token || sessionStorage.getItem('verificationToken')
//           const businessType = response.data?.businessType || sessionStorage.getItem('businessType')
          
//           if (verificationToken && businessType) {
//             console.log('Navigating to document-verify with:', { verificationToken, businessType })
            
//             setTimeout(() => {
//               router.push({
//                 pathname: '/document-verify',
//                 query: {
//                   token: verificationToken,
//                   businessType: businessType
//                 }
//               })
//             }, 1500)
//           } else {
//             console.error('Missing token or businessType for document verification')
//             toast.error('Missing verification data. Please try again.')
//           }
//         }
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Invalid verification code. Please try again.'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//         handleFailedAttempt()
//         resetOtpInputs()
//       }
//     } catch (error: any) {
//       console.error('=== Email OTP Verification Error ===')
//       console.error('Error:', error)
//       console.error('Error Response:', error.response?.data)
      
//       if (error.response?.data?.access) {
//         const { access, refresh, profile } = error.response.data
        
//         if (error.response?.data?.businessType) {
//           sessionStorage.setItem('businessType', error.response.data.businessType)
//         }
//         if (error.response?.data?.token) {
//           sessionStorage.setItem('verificationToken', error.response.data.token)
//         }
        
//         storeUserData(access, refresh, profile, error.response?.data?.businessType)
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 3000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//         return
//       }
      
//       if (error.response?.data?.content?.access) {
//         const { access, refresh, profile } = error.response.data.content
        
//         if (error.response?.data?.businessType) {
//           sessionStorage.setItem('businessType', error.response.data.businessType)
//         }
//         if (error.response?.data?.token) {
//           sessionStorage.setItem('verificationToken', error.response.data.token)
//         }
        
//         storeUserData(access, refresh, profile, error.response?.data?.businessType)
        
//         toast.success('Verification successful! Redirecting to dashboard...', {
//           id: toastId,
//           duration: 3000
//         })
        
//         setTimeout(() => {
//           window.location.href = '/dashboards/merchant'
//         }, 1500)
//         return
//       }
      
//       let errorMessage = handleApiError(error)
      
//       if (error.response?.data?.content === 'Email and phone is already verified.') {
//         errorMessage = 'Email and phone is already verified. Please login to continue.'
//         toast.success('Email and phone already verified! Redirecting to login...', {
//           id: toastId,
//           duration: 3000
//         })
//         setTimeout(() => {
//           router.push('/login')
//         }, 2000)
//         return
//       }
      
//       if (error.response?.status === 400) {
//         errorMessage = error.response?.data?.content || 'Invalid OTP. Please check and try again.'
//       } else if (error.response?.status === 500) {
//         errorMessage = 'Server error. Please try again later.'
//       } else if (!error.response) {
//         errorMessage = 'Network error. Please check your connection.'
//       }
      
//       console.log('Error Message:', errorMessage)
      
//       toast.error(errorMessage, {
//         id: toastId,
//         duration: 5000
//       })
//       setError(errorMessage)
//       handleFailedAttempt()
//       resetOtpInputs()
//     } finally {
//       setIsVerifying(false)
//     }
//   }

//   const handleResendOTP = async () => {
//     if (isResending) return

//     setIsResending(true)
//     setError('')
//     setSuccessMessage('')

//     const toastId = toast.loading('Resending OTP...')

//     try {
//       const authToken = token as string
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A new verification code has been sent to your email.'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
//         setAttempt(1)
//         setResendVisible(false)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to resend OTP'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//       }
//     } catch (error: any) {
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg, {
//         id: toastId,
//         duration: 5000
//       })
//     } finally {
//       setIsResending(false)
//     }
//   }

//   const handleCallOTP = async () => {
//     if (isCalling) return

//     setIsCalling(true)
//     setError('')
//     setSuccessMessage('')

//     const toastId = toast.loading('Sending OTP via call...')

//     try {
//       const authToken = token as string
//       const response = await axios.get<ApiResponse>(
//         `${endpoints.auth.resendOtpCallEndpoint}/${authToken}`
//       )
      
//       if (response.data && response.data.code === 200) {
//         const message = response.data.content || 'A verification code has been sent via call.'
//         toast.success(message, {
//           id: toastId,
//           duration: 3000
//         })
//         setSuccessMessage(message)
//         setAttempt(2)
//         setCallVisible(false)
//         startCountdown(40)
//         resetOtpInputs()
        
//         setTimeout(() => {
//           setSuccessMessage('')
//         }, 5000)
//       } else {
//         const errorMsg = response.data?.message || response.data?.content || 'Failed to send OTP via call'
//         toast.error(errorMsg, {
//           id: toastId,
//           duration: 5000
//         })
//         setError(errorMsg)
//       }
//     } catch (error: any) {
//       const errorMsg = handleApiError(error)
//       setError(errorMsg)
//       toast.error(errorMsg, {
//         id: toastId,
//         duration: 5000
//       })
//     } finally {
//       setIsCalling(false)
//     }
//   }

//   const formatTime = (seconds: number): string => {
//     const mins = Math.floor(seconds / 60)
//     const secs = seconds % 60
//     return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
//   }

//   const imageSource = skin === 'bordered' ? 'auth-v2-two-steps-illustration-bordered' : 'auth-v2-two-steps-illustration'

//   if (!router.isReady || !pageLoaded) {
//     return (
//       <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
//         <CircularProgress />
//       </Box>
//     )
//   }

//   if (isVerifyingInitial) {
//     return (
//       <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//         <RightWrapper>
//           <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//             <Box sx={{ textAlign: 'center' }}>
//               <CircularProgress size={60} />
//               <Typography sx={{ mt: 4, color: 'text.secondary' }}>
//                 Verifying your email...
//               </Typography>
//             </Box>
//           </Box>
//         </RightWrapper>
//       </Box>
//     )
//   }

//   return (
//     <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
//       {!hidden ? (
//         <Box
//           sx={{
//             flex: 1,
//             display: 'flex',
//             position: 'relative',
//             alignItems: 'center',
//             borderRadius: '20px',
//             justifyContent: 'center',
//             backgroundColor: 'customColors.bodyBg',
//             margin: theme => theme.spacing(8, 0, 8, 8)
//           }}
//         >
//           <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
//             <AnimatePresence mode='wait'>
//               <motion.div
//                 key='verify'
//                 initial={{ opacity: 0 }}
//                 animate={{ opacity: 1 }}
//                 exit={{ opacity: 0 }}
//                 transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
//                 style={{
//                   position: 'absolute',
//                   width: '100%',
//                   height: '100%',
//                   display: 'flex',
//                   justifyContent: 'center',
//                   alignItems: 'center'
//                 }}
//               >
//                 <TwoStepsIllustration 
//                   alt='two-steps-illustration' 
//                   src={`/images/pages/${imageSource}-${theme.palette.mode}.png`} 
//                 />
//               </motion.div>
//             </AnimatePresence>
//           </Box>
//         </Box>
//       ) : null}

//       <RightWrapper>
//         <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//           <AnimatePresence mode='wait'>
//             <motion.div
//               key='verify-form'
//               initial='hiddenRight'
//               animate='visible'
//               exit='exitLeft'
//               variants={slideVariants}
//               transition={{ duration: 0.5 }}
//               style={{ width: '100%', display: 'flex', justifyContent: 'center' }}
//             >
//               <Box sx={{ width: '100%', maxWidth: 400 }}>
//                 <img
//                   src='/images/website-logo/LockTrust-logo.png'
//                   alt='LockTrust Logo'
//                   style={{ height: '60px', width: 'auto', objectFit: 'contain' }}
//                 />

//                 <motion.div
//                   initial={{ y: -20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.3, duration: 0.5 }}
//                 >
//                   <Box sx={{ mb: 6 }}>
//                     <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
//                       Verify Your Email 💬
//                     </Typography>
//                     <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
//                       Enter the verification code sent to your email to verify your email address.
//                     </Typography>
                    
//                     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
//                       <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
//                         {emailAddress}
//                       </Typography>
//                       {userDetails?.emailVerified && (
//                         <Box sx={{ display: 'flex', alignItems: 'center', color: 'success.main' }}>
//                           <Icon icon='tabler:circle-check-filled' fontSize={20} />
//                           <Typography variant='caption' sx={{ ml: 0.5, color: 'success.main' }}>
//                             Verified
//                           </Typography>
//                         </Box>
//                       )}
//                     </Box>
//                   </Box>
//                 </motion.div>

//                 {userDetails && (
//                   <motion.div
//                     initial={{ y: 20, opacity: 0 }}
//                     animate={{ y: 0, opacity: 1 }}
//                     transition={{ delay: 0.35, duration: 0.5 }}
//                   >
//                     <Box sx={{ mb: 4, p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
//                       <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
//                         <Typography variant='body2' sx={{ fontWeight: 500, color: 'text.secondary' }}>
//                           Phone Number
//                         </Typography>
//                         {!isEditingPhone && (
//                           <IconButton size='small' onClick={handleEditPhone} sx={{ color: 'primary.main' }}>
//                             <Icon icon='tabler:edit' fontSize={20} />
//                           </IconButton>
//                         )}
//                       </Box>
                      
//                       {!isEditingPhone ? (
//                         <>
//                           <Typography variant='body1' sx={{ fontWeight: 500 }}>
//                             {userDetails.countryCode || '+91'} {userDetails.mobile}
//                           </Typography>
//                           {!userDetails.phoneVerified && (
//                             <Typography variant='caption' sx={{ color: 'warning.main', display: 'block', mt: 0.5 }}>
//                               Not verified yet
//                             </Typography>
//                           )}
//                         </>
//                       ) : (
//                         <Box sx={{ mt: 2 }}>
//                           <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
//                             <FormControl fullWidth sx={{ flex: 0.5 }}>
//                               <Autocomplete
//                                 id='country-select'
//                                 options={countries}
//                                 autoHighlight
//                                 getOptionLabel={(option: CountryOption) => {
//                                   if (!option) return ''
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   return dialCode ? `${name} (+${dialCode})` : name
//                                 }}
//                                 value={selectedCountryCode}
//                                 onChange={(event: any, newValue: CountryOption | null) => {
//                                   setSelectedCountryCode(newValue)
//                                 }}
//                                 renderOption={(props, option) => {
//                                   const dialCode = option.dialCode || option.phone || ''
//                                   const name = option.name || option.label || ''
//                                   const countryCodeISO = option.code || option.iso2 || ''
//                                   return (
//                                     <Box component='li' sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                                       <img
//                                         loading='lazy'
//                                         width='24'
//                                         height='18'
//                                         src={`https://flagcdn.com/w40/${countryCodeISO?.toLowerCase()}.png`}
//                                         srcSet={`https://flagcdn.com/w80/${countryCodeISO?.toLowerCase()}.png 2x`}
//                                         alt=""
//                                         style={{ marginRight: '12px' }}
//                                       />
//                                       <span style={{ fontWeight: 500 }}>{name}</span>
//                                       {dialCode && (
//                                         <span style={{ marginLeft: '8px', color: '#666' }}>(+{dialCode})</span>
//                                       )}
//                                     </Box>
//                                   )
//                                 }}
//                                 renderInput={(params) => (
//                                   <TextField
//                                     {...params}
//                                     label='Country Code'
//                                     placeholder='Select country'
//                                     size='small'
//                                     InputProps={{
//                                       ...params.InputProps,
//                                       startAdornment: selectedCountryCode && (selectedCountryCode.code || selectedCountryCode.iso2) && (
//                                         <img
//                                           src={`https://flagcdn.com/w20/${(selectedCountryCode.code || selectedCountryCode.iso2)?.toLowerCase()}.png`}
//                                           style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                                           width='24'
//                                           height='18'
//                                           alt="flag"
//                                         />
//                                       ),
//                                     }}
//                                   />
//                                 )}
//                               />
//                             </FormControl>
                            
//                             <TextField
//                               fullWidth
//                               size='small'
//                               label='Phone Number'
//                               value={phoneNumber}
//                               onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ''))}
//                               placeholder='Enter phone number'
//                               inputProps={{ maxLength: 15 }}
//                               sx={{ flex: 0.5 }}
//                             />
//                           </Box>
                          
//                           <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
//                             <Button size='small' onClick={handleCancelEdit} disabled={isUpdatingPhone}>
//                               Cancel
//                             </Button>
//                             <Button 
//                               size='small' 
//                               variant='contained' 
//                               onClick={handleUpdatePhone} 
//                               disabled={isUpdatingPhone}
//                             >
//                               {isUpdatingPhone ? <CircularProgress size={20} /> : 'Save'}
//                             </Button>
//                           </Box>
//                         </Box>
//                       )}
//                     </Box>
//                   </motion.div>
//                 )}

//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.4, duration: 0.5 }}
//                 >
//                   {successMessage && (
//                     <Alert 
//                       severity='success' 
//                       sx={{ mb: 4 }}
//                       onClose={() => setSuccessMessage('')}
//                     >
//                       {successMessage}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 <motion.div
//                   initial={{ scale: 0.95, opacity: 0 }}
//                   animate={{ scale: 1, opacity: 1 }}
//                   transition={{ delay: 0.45, duration: 0.5 }}
//                 >
//                   {error && (
//                     <Alert severity='error' sx={{ mb: 4 }} onClose={() => setError('')}>
//                       {error}
//                     </Alert>
//                   )}
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.5, duration: 0.5 }}
//                 >
//                   <Typography sx={{ fontWeight: 500, color: 'text.secondary', mb: 2 }}>
//                     Type your 6-digit verification code
//                   </Typography>
//                 </motion.div>

//                 <motion.form
//                   onSubmit={handleSubmit(onSubmit)}
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.6, duration: 0.5 }}
//                 >
//                   <CleaveWrapper
//                     sx={{
//                       display: 'flex',
//                       alignItems: 'center',
//                       justifyContent: 'space-between',
//                       ...(errorsArray.length && {
//                         '& .invalid:focus': {
//                           borderColor: theme => `${theme.palette.error.main} !important`,
//                           boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
//                         }
//                       })
//                     }}
//                   >
//                     {renderInputs()}
//                   </CleaveWrapper>
                  
//                   {errorsArray.length ? (
//                     <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid verification code</FormHelperText>
//                   ) : null}

//                   <Button 
//                     fullWidth 
//                     type='submit' 
//                     variant='contained' 
//                     disabled={isVerifying} 
//                     sx={{ mt: 4 }}
//                   >
//                     {isVerifying ? (
//                       <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                         <CircularProgress size={24} color='inherit' />
//                         Verifying...
//                       </Box>
//                     ) : (
//                       'Verify Email'
//                     )}
//                   </Button>
//                 </motion.form>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.7, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}>
//                     {countdownActive && countdown > 0 && (
//                       <Box sx={{ position: 'relative', display: 'inline-block', mb: 2 }}>
//                         <img 
//                           src='/images/clock.jpg'
//                           alt='Clock'
//                           style={{
//                             width: '100px',
//                             height: '100px',
//                             display: 'block',
//                             margin: '0 auto'
//                           }}
//                         />
//                         <Box
//                           sx={{
//                             position: 'absolute',
//                             top: '50%',
//                             left: '50%',
//                             transform: 'translate(-50%, -50%)',
//                             fontSize: '14px',
//                             fontWeight: 'bold',
//                             color: 'white'
//                           }}
//                         >
//                           {formatTime(countdown)}
//                         </Box>
//                       </Box>
//                     )}

//                     {resendVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
//                         <LinkStyled 
//                           href='#' 
//                           onClick={handleResendOTP}
//                           sx={{ 
//                             pointerEvents: isResending ? 'none' : 'auto',
//                             opacity: isResending ? 0.6 : 1
//                           }}
//                         >
//                           {isResending ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Resend OTP'
//                           )}
//                         </LinkStyled>
//                       </Box>
//                     )}

//                     {callVisible && (
//                       <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                         <Typography sx={{ color: 'text.secondary' }}>Still having trouble?</Typography>
//                         <CallLinkStyled 
//                           href='#' 
//                           onClick={handleCallOTP}
//                           sx={{ 
//                             pointerEvents: isCalling ? 'none' : 'auto',
//                             opacity: isCalling ? 0.6 : 1
//                           }}
//                         >
//                           {isCalling ? (
//                             <CircularProgress size={20} />
//                           ) : (
//                             'Call Me'
//                           )}
//                         </CallLinkStyled>
//                       </Box>
//                     )}
//                   </Box>
//                 </motion.div>

//                 <motion.div
//                   initial={{ y: 20, opacity: 0 }}
//                   animate={{ y: 0, opacity: 1 }}
//                   transition={{ delay: 0.9, duration: 0.5 }}
//                 >
//                   <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//                     <Button
//                       variant='text'
//                       onClick={() => router.push('/login')}
//                       sx={{ textTransform: 'none' }}
//                       startIcon={<Icon icon='tabler:arrow-left' />}
//                     >
//                       Back to Login
//                     </Button>
//                   </Box>
//                 </motion.div>
//               </Box>
//             </motion.div>
//           </AnimatePresence>
//         </Box>
//       </RightWrapper>
//     </Box>
//   )
// }

// EmailVerify.getLayout = page => <BlankLayout>{page}</BlankLayout>
// EmailVerify.guestGuard = true

// export default EmailVerify



// // import React from 'react'
// // // ** Layout Import
// // import BlankLayout from 'src/@core/layouts/BlankLayout'

// // const EmailVerify = () => {
// //   return (
// //     <div>EmailVerify</div>
// //   )
// // }

// // EmailVerify.getLayout = page => <BlankLayout>{page}</BlankLayout>
// // EmailVerify.guestGuard = true

// // export default EmailVerify


// iso issue 
import { useState, useEffect } from 'react'

// ** Next Imports
import Link from 'next/link'
import { useRouter } from 'next/router'

// ** MUI Components
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import FormControl from '@mui/material/FormControl'
import useMediaQuery from '@mui/material/useMediaQuery'
import { styled, useTheme } from '@mui/material/styles'
import FormHelperText from '@mui/material/FormHelperText'
import Alert from '@mui/material/Alert'
import CircularProgress from '@mui/material/CircularProgress'
import TextField from '@mui/material/TextField'
import IconButton from '@mui/material/IconButton'
import Autocomplete from '@mui/material/Autocomplete'

// ** Animation Imports
import { AnimatePresence, motion } from 'framer-motion'

// ** Icon Imports
import Icon from 'src/@core/components/icon'

// ** Third Party Imports
import Cleave from 'cleave.js/react'
import { useForm, Controller } from 'react-hook-form'
import CryptoJS from 'crypto-js'

// ** Hooks
import { useSettings } from 'src/@core/hooks/useSettings'

// ** Layout Import
import BlankLayout from 'src/@core/layouts/BlankLayout'

// ** Custom Styled Component
import CleaveWrapper from 'src/@core/styles/libs/react-cleave'

// ** Util Import
import { hexToRGBA } from 'src/@core/utils/hex-to-rgba'

// ** Fake DB Import for countries
import { countries } from 'src/@fake-db/autocomplete'

// ** Toast
import toast from 'react-hot-toast'

// ** Axios & Endpoints
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'
import authConfig from 'src/configs/auth'

// ** Styles
import 'cleave.js/dist/addons/cleave-phone.us'

// ** Types
interface UserDetails {
  dialCountryCode?: string
  firstName?: string
  lastName?: string
  emailVerified?: boolean
  countryCode?: string
  phoneVerified?: boolean
  mobile?: string
  emailId?: string
}

interface CountryOption {
  code?: string
  dialCode?: string
  phone?: string
  name?: string
  label?: string
}

interface ApiResponse {
  code: number
  content: string
  message?: string
  uid?: string | null
  timestamp?: string
  success?: boolean
  isPlaid?: boolean
  plaid?: boolean
  access?: string
  refresh?: string
  expiresIn?: number
  businessType?: string
  token?: string
  profile?: {
    firstName?: string
    lastName?: string
    uid?: string
    mobileNum?: string
    emailId?: string
    applicationId?: string
    isPinSetup?: boolean
    isSubUser?: boolean
    TwoNf?: boolean
    businessType?: string
    allPermissions?: Array<{
      moduleName: string
      action: string
    }>
    permissions?: Array<{
      moduleName: string
      action: string
    }>
  }
}

interface UpdatePhonePayload {
  dialCountryCode: string
  countryCode: string
  mobile: string
}

interface OtpFormValues {
  val1: string
  val2: string
  val3: string
  val4: string
  val5: string
  val6: string
}

// ** Animation Variants
const slideVariants = {
  hiddenLeft: { x: -400, opacity: 0 },
  hiddenRight: { x: 400, opacity: 0 },
  visible: { x: 0, opacity: 1 },
  exitLeft: { x: -400, opacity: 0 },
  exitRight: { x: 400, opacity: 0 }
}

// ** Styled Components
const TwoStepsIllustration = styled('img')(({ theme }) => ({
  zIndex: 2,
  maxHeight: 650,
  marginTop: theme.spacing(12),
  marginBottom: theme.spacing(12),
  [theme.breakpoints.down(1540)]: {
    maxHeight: 550
  },
  [theme.breakpoints.down('lg')]: {
    maxHeight: 500
  }
}))

const RightWrapper = styled(Box)(({ theme }) => ({
  width: '100%',
  [theme.breakpoints.up('md')]: {
    maxWidth: 450
  },
  [theme.breakpoints.up('lg')]: {
    maxWidth: 600
  },
  [theme.breakpoints.up('xl')]: {
    maxWidth: 750
  }
}))

const LinkStyled = styled(Link)(({ theme }) => ({
  fontSize: '1rem',
  textDecoration: 'none',
  marginLeft: theme.spacing(2),
  color: theme.palette.primary.main,
  cursor: 'pointer'
}))

const CallLinkStyled = styled(Link)(({ theme }) => ({
  fontSize: '1rem',
  textDecoration: 'none',
  marginLeft: theme.spacing(1),
  color: theme.palette.error.main,
  cursor: 'pointer'
}))

const CleaveInput = styled(Cleave)(({ theme }) => ({
  maxWidth: 48,
  textAlign: 'center',
  height: '48px !important',
  fontSize: '150% !important',
  marginTop: theme.spacing(2),
  marginBottom: theme.spacing(2),
  '&:not(:last-child)': {
    marginRight: theme.spacing(2)
  },
  '&::-webkit-outer-spin-button, &::-webkit-inner-spin-button': {
    margin: 0,
    WebkitAppearance: 'none'
  },
  [theme.breakpoints.down('sm')]: {
    maxWidth: 40,
    height: '40px !important',
    fontSize: '120% !important'
  }
}))

const defaultValues: OtpFormValues = {
  val1: '',
  val2: '',
  val3: '',
  val4: '',
  val5: '',
  val6: ''
}

// Secret key for AES encryption
const SECRET_KEY = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

const deriveAESKey = (): CryptoJS.lib.WordArray => {
  const secretWordArray = CryptoJS.enc.Utf8.parse(SECRET_KEY)
  const keyHash = CryptoJS.SHA256(secretWordArray)
  return keyHash
}

const encryptAES = (plainText: string): string | null => {
  try {
    const iv = CryptoJS.lib.WordArray.random(16)
    const key = deriveAESKey()
    const encrypted = CryptoJS.AES.encrypt(plainText, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    const combined = iv.concat(encrypted.ciphertext)
    return CryptoJS.enc.Base64.stringify(combined)
  } catch (error) {
    console.error('Encryption error:', error)
    return null
  }
}

// Helper function to store user data
const storeUserData = (access: string, refresh: string, profile: any, businessType?: string) => {
  let formattedPermissions = []
  if (profile?.allPermissions && profile.allPermissions.length > 0) {
    formattedPermissions = profile.allPermissions
  } else if (profile?.permissions && profile.permissions.length > 0) {
    formattedPermissions = profile.permissions.map((p: any) => ({
      moduleName: p.moduleName,
      action: p.action
    }))
  } else {
    formattedPermissions = [
      { moduleName: 'dashboard', action: 'CREATE' },
      { moduleName: 'dashboard', action: 'UPDATE' },
      { moduleName: 'dashboard', action: 'VIEW' },
      { moduleName: 'dashboard', action: 'DELETE' }
    ]
  }

  const userData = {
    id: profile?.uid || profile?.id,
    role: profile?.isSubUser ? 'subUser' : 'merchant',
    fullName: `${profile?.firstName || ''} ${profile?.lastName || ''}`.trim(),
    firstName: profile?.firstName,
    lastName: profile?.lastName,
    mobileNum: profile?.mobileNum,
    username: profile?.emailId,
    email: profile?.emailId,
    isSubUser: profile?.isSubUser || false,
    TwoNf: profile?.TwoNf || false,
    isPinSetup: profile?.isPinSetup || false,
    allPermissions: formattedPermissions,
    permissions: formattedPermissions,
    applicationId: profile?.applicationId || null,
    businessType: businessType || profile?.businessType || null
  }
  
  localStorage.setItem(authConfig.storageTokenKeyName, access)
  localStorage.setItem('refreshToken', refresh)
  localStorage.setItem('userData', JSON.stringify(userData))
  localStorage.setItem('isAuthenticated', 'true')
  
  return userData
}

// Helper function to handle API errors
const handleApiError = (error: any): string => {
  console.error('API Error:', error)
  
  if (error.response?.data) {
    const data = error.response.data
    
    if (data.content) {
      return data.content
    }
    
    if (data.message) {
      return data.message
    }
    
    if (data.detail) {
      return data.detail
    }
    
    if (data.errors) {
      if (typeof data.errors === 'string') {
        return data.errors
      }
      if (Array.isArray(data.errors)) {
        return data.errors.join(', ')
      }
      if (typeof data.errors === 'object') {
        const errorMessages = Object.values(data.errors).flat()
        return errorMessages.join(', ')
      }
    }
  }
  
  if (error.message) {
    return error.message
  }
  
  return 'An unexpected error occurred. Please try again.'
}

const EmailVerify = () => {
  const [isVerifying, setIsVerifying] = useState(false)
  const [isResending, setIsResending] = useState(false)
  const [isCalling, setIsCalling] = useState(false)
  const [error, setError] = useState('')
  const [successMessage, setSuccessMessage] = useState('')
  const [isBackspace, setIsBackspace] = useState(false)
  const [isVerifyingInitial, setIsVerifyingInitial] = useState(true)
  const [emailAddress, setEmailAddress] = useState('')
  const [userDetails, setUserDetails] = useState<UserDetails | null>(null)
  const [isEditingPhone, setIsEditingPhone] = useState(false)
  const [selectedCountryCode, setSelectedCountryCode] = useState<CountryOption | null>(null)
  const [phoneNumber, setPhoneNumber] = useState('')
  const [isUpdatingPhone, setIsUpdatingPhone] = useState(false)
  const [pageLoaded, setPageLoaded] = useState(false)
  const [decryptError, setDecryptError] = useState(false)
  const [verifyError, setVerifyError] = useState(false)
  
  const [attempt, setAttempt] = useState(0)
  const [resendVisible, setResendVisible] = useState(false)
  const [callVisible, setCallVisible] = useState(false)
  const [countdown, setCountdown] = useState(0)
  const [countdownActive, setCountdownActive] = useState(false)

  const router = useRouter()
  const { token } = router.query

  const theme = useTheme()
  const { settings } = useSettings()
  const hidden = useMediaQuery(theme.breakpoints.down('md'))
  const { skin } = settings

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors }
  } = useForm<OtpFormValues>({ defaultValues })

  const errorsArray = Object.keys(errors)

  const decryptTokenAndGetUserDetails = async (authToken: string) => {
    try {
      setDecryptError(false)
      const response = await axios.get<UserDetails>(
        `${endpoints.auth.decryptTokenEndpoint}/${authToken}`
      )
      console.log('Decrypted user details:', response.data)
      
      if (response.data) {
        setUserDetails(response.data)
        setEmailAddress(response.data.emailId || 'your email address')
        
        if (response.data.dialCountryCode || response.data.countryCode) {
          const countryCodeValue = response.data.dialCountryCode || response.data.countryCode
          const foundCountry = countries.find(
            country => country.code === countryCodeValue
          )
          setSelectedCountryCode(foundCountry || null)
        }
        
        if (response.data.mobile) {
          setPhoneNumber(response.data.mobile)
        }
        return true
      }
      return false
    } catch (error: any) {
      console.error('Error decrypting token:', error)
      setDecryptError(true)
      const errorMsg = handleApiError(error)
      setError(errorMsg)
      setEmailAddress('your email address')
      return false
    }
  }

  const verifyTokenWithBackend = async (authToken: string) => {
    try {
      setIsVerifyingInitial(true)
      setError('')
      setVerifyError(false)

      const response = await axios.get<ApiResponse>(
        endpoints.auth.verifyEmailTokenEndpoint,
        {
          params: { token: authToken }
        }
      )

      console.log('Verify Token Response:', response.data)

      const isSuccess = 
        response.data && (
          response.data.code === 200 ||
          response.data.isPlaid === true ||
          response.data.plaid === true ||
          response.data.success === true ||
          response.data.access !== undefined
        )

      if (isSuccess) {
        const message = response.data?.content || 'Email verified successfully!'
        setSuccessMessage(message)
        setIsVerifyingInitial(false)
        
        if (response.data?.businessType) {
          sessionStorage.setItem('businessType', response.data.businessType)
        }
        if (response.data?.token) {
          sessionStorage.setItem('verificationToken', response.data.token)
        }
        
        if (response.data?.isPlaid === true || response.data?.plaid === true || response.data?.access) {
          if (response.data?.access) {
            const { access, refresh, profile } = response.data
            if (refresh) {
              storeUserData(access, refresh, profile, response.data?.businessType)
            }
            
            toast.success('Email verified! Redirecting to dashboard...')
            
            setTimeout(() => {
              window.location.href = '/dashboards/merchant'
            }, 1500)
          } else {
            setTimeout(() => {
              router.push('/login')
            }, 1500)
          }
          return true
        }
        
        return true
      } else {
        const errorMsg = response.data?.message || response.data?.content || 'Failed to verify email.'
        setError(errorMsg)
        toast.error(errorMsg)
        setIsVerifyingInitial(false)
        setVerifyError(true)
        startCountdown(40)
        return false
      }
    } catch (error: any) {
      console.error('Verify token error:', error)
      setIsVerifyingInitial(false)
      setVerifyError(true)
      
      const errorMsg = handleApiError(error)
      setError(errorMsg)
      toast.error(errorMsg)
      startCountdown(40)
      return false
    }
  }

  useEffect(() => {
    if (!router.isReady) {
      console.log('Router not ready yet...')
      return
    }

    const authToken = token as string
    
    if (!authToken) {
      console.log('No token found in URL')
      setError('Invalid verification link. No token provided.')
      setPageLoaded(true)
      setIsVerifyingInitial(false)
      return
    }

    console.log('Token found in URL:', authToken)
    setPageLoaded(true)

    const initializeVerification = async () => {
      await decryptTokenAndGetUserDetails(authToken)
      await verifyTokenWithBackend(authToken)
    }

    initializeVerification()
  }, [router.isReady, token])

  useEffect(() => {
    let timer: NodeJS.Timeout
    if (countdown > 0 && countdownActive) {
      timer = setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)
    } else if (countdown === 0 && countdownActive) {
      setCountdownActive(false)
      if (attempt === 0) {
        setResendVisible(true)
      } else if (attempt === 1) {
        setCallVisible(true)
      }
    }
    return () => clearTimeout(timer)
  }, [countdown, countdownActive, attempt])

  const startCountdown = (seconds: number) => {
    setCountdown(seconds)
    setCountdownActive(true)
  }

  const resetOtpInputs = () => {
    reset(defaultValues)
    setTimeout(() => {
      const firstInput = document.querySelector('.CleaveInput') as HTMLInputElement
      if (firstInput) firstInput.focus()
    }, 100)
  }

  const handleFailedAttempt = () => {
    setAttempt((prev) => {
      const next = prev + 1
      setCountdownActive(false)
      
      if (next === 1) {
        setResendVisible(true)
        setCallVisible(false)
      } else if (next === 2) {
        setResendVisible(false)
        setCallVisible(false)
        startCountdown(40)
      } else if (next >= 3) {
        toast.error('Too many failed attempts. Please try again later.')
        setTimeout(() => {
          setAttempt(0)
          setResendVisible(true)
        }, 60000)
      }
      return next
    })
  }

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
    if (!isBackspace) {
      onChange(event.target.value)
      const form = event.target.form
      if (form) {
        const index = [...form].indexOf(event.target)
        const formElements = [...form.elements] as HTMLInputElement[]
        if (formElements[index].value && formElements[index].value.length) {
          if (formElements[index + 1]) {
            formElements[index + 1].focus()
          }
        }
      }
      event.preventDefault()
    }
  }

  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Backspace') {
      setIsBackspace(true)
      const form = event.currentTarget.form
      if (form) {
        const index = [...form.elements].indexOf(event.currentTarget)
        if (index >= 1) {
          const formElements = [...form.elements] as HTMLInputElement[]
          if (!(formElements[index].value && formElements[index].value.length)) {
            if (formElements[index - 1]) {
              formElements[index - 1].focus()
            }
          }
        }
      }
    } else {
      setIsBackspace(false)
    }
  }

  const renderInputs = () => {
    const inputKeys: (keyof OtpFormValues)[] = ['val1', 'val2', 'val3', 'val4', 'val5', 'val6']
    
    return inputKeys.map((val, index) => (
      <Controller
        key={val}
        name={val}
        control={control}
        rules={{ required: true }}
        render={({ field: { value, onChange } }) => (
          <CleaveInput
            type='tel'
            value={value}
            autoFocus={index === 0}
            onKeyDown={handleKeyDown}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => handleChange(event, onChange)}
            options={{ blocks: [1], numeral: true, numeralPositiveOnly: true }}
            sx={{ 
              [theme.breakpoints.down('sm')]: { 
                px: `${theme.spacing(2)} !important`,
                marginRight: `${theme.spacing(1)} !important`
              } 
            }}
          />
        )}
      />
    ))
  }

  const handleEditPhone = () => {
    setIsEditingPhone(true)
  }

  const handleCancelEdit = () => {
    setIsEditingPhone(false)
    if (userDetails) {
      const foundCountry = countries.find(
        country => country.code === (userDetails.dialCountryCode || userDetails.countryCode)
      )
      setSelectedCountryCode(foundCountry || null)
      setPhoneNumber(userDetails.mobile || '')
    }
  }

  const handleUpdatePhone = async () => {
    if (!phoneNumber || phoneNumber.length < 6) {
      toast.error('Please enter a valid phone number')
      return
    }

    if (!selectedCountryCode) {
      toast.error('Please select a country code')
      return
    }

    setIsUpdatingPhone(true)
    try {
      const authToken = token as string
      const payload: UpdatePhonePayload = {
        dialCountryCode: selectedCountryCode.code || '',
        countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone || ''}`,
        mobile: phoneNumber
      }
      
      const response = await axios.post<ApiResponse>(
        `${endpoints.auth.updatePhoneNumberEndpoint}/${authToken}`,
        payload
      )
      
      if (response.data && response.data.code === 200) {
        toast.success(response.data.content || 'Phone number updated successfully!')
        setIsEditingPhone(false)
        
        setUserDetails({
          ...userDetails,
          dialCountryCode: selectedCountryCode.code || '',
          countryCode: `+${selectedCountryCode.dialCode || selectedCountryCode.phone || ''}`,
          mobile: phoneNumber
        })
      } else {
        const errorMsg = response.data?.message || response.data?.content || 'Failed to update phone number'
        toast.error(errorMsg)
      }
    } catch (error: any) {
      console.error('Error updating phone:', error)
      const errorMsg = handleApiError(error)
      toast.error(errorMsg)
    } finally {
      setIsUpdatingPhone(false)
    }
  }

  const onSubmit = async (data: OtpFormValues) => {
    if (isVerifying) return

    setIsVerifying(true)
    setError('')

    const enteredOtp = Object.values(data).join('')
    
    if (enteredOtp.length !== 6) {
      setError('Please enter a valid 6-digit verification code')
      setIsVerifying(false)
      return
    }
    
    const encryptedOtp = encryptAES(enteredOtp)
    
    if (!encryptedOtp) {
      setError('Failed to encrypt verification code. Please try again.')
      setIsVerifying(false)
      return
    }
    
    const authToken = token as string
    const payload = {
      otp: encryptedOtp
    }

    const toastId = toast.loading('Verifying OTP...')

    try {
      console.log('=== Email OTP Verification Request ===')
      console.log('Token:', authToken)
      
      const response = await axios.post<ApiResponse>(
        `${endpoints.auth.sendOtpForEmailEndpoint}/${authToken}`,
        payload
      )
      
      console.log('=== Email OTP Verification Response ===')
      console.log('Full Response:', response.data)
      
      const isSuccess = 
        response.data && (
          response.data.code === 200 ||
          response.data.isPlaid === true ||
          response.data.plaid === true ||
          response.data.success === true ||
          response.data.access !== undefined
        )

      if (isSuccess) {
        const message = response.data?.content || 'Email verified successfully!'
        toast.success(message, {
          id: toastId,
          duration: 3000
        })
        setSuccessMessage(message)
        
        if (response.data?.businessType) {
          sessionStorage.setItem('businessType', response.data.businessType)
        }
        if (response.data?.token) {
          sessionStorage.setItem('verificationToken', response.data.token)
        }
        
        if (response.data?.access) {
          const { access, refresh, profile } = response.data
          if (refresh) {
            storeUserData(access, refresh, profile, response.data?.businessType)
          }
          
          setTimeout(() => {
            window.location.href = '/dashboards/merchant'
          }, 1500)
        } 
        else if (response.data?.isPlaid === true || response.data?.plaid === true) {
          toast.success('Email verified! Please login to continue.', {
            id: toastId,
            duration: 3000
          })
          
          setTimeout(() => {
            router.push('/login')
          }, 1500)
        } 
        else {
          const verificationToken = response.data?.token || sessionStorage.getItem('verificationToken')
          const businessType = response.data?.businessType || sessionStorage.getItem('businessType')
          
          if (verificationToken && businessType) {
            console.log('Navigating to document-verify with:', { verificationToken, businessType })
            
            setTimeout(() => {
              router.push({
                pathname: '/document-verify',
                query: {
                  token: verificationToken,
                  businessType: businessType
                }
              })
            }, 1500)
          } else {
            console.error('Missing token or businessType for document verification')
            toast.error('Missing verification data. Please try again.')
          }
        }
      } else {
        const errorMsg = response.data?.message || response.data?.content || 'Invalid verification code. Please try again.'
        toast.error(errorMsg, {
          id: toastId,
          duration: 5000
        })
        setError(errorMsg)
        handleFailedAttempt()
        resetOtpInputs()
      }
    } catch (error: any) {
      console.error('=== Email OTP Verification Error ===')
      console.error('Error:', error)
      console.error('Error Response:', error.response?.data)
      
      if (error.response?.data?.access) {
        const { access, refresh, profile } = error.response.data
        
        if (error.response?.data?.businessType) {
          sessionStorage.setItem('businessType', error.response.data.businessType)
        }
        if (error.response?.data?.token) {
          sessionStorage.setItem('verificationToken', error.response.data.token)
        }
        
        if (refresh) {
          storeUserData(access, refresh, profile, error.response?.data?.businessType)
        }
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 3000
        })
        
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
        return
      }
      
      if (error.response?.data?.content?.access) {
        const { access, refresh, profile } = error.response.data.content
        
        if (error.response?.data?.businessType) {
          sessionStorage.setItem('businessType', error.response.data.businessType)
        }
        if (error.response?.data?.token) {
          sessionStorage.setItem('verificationToken', error.response.data.token)
        }
        
        if (refresh) {
          storeUserData(access, refresh, profile, error.response?.data?.businessType)
        }
        
        toast.success('Verification successful! Redirecting to dashboard...', {
          id: toastId,
          duration: 3000
        })
        
        setTimeout(() => {
          window.location.href = '/dashboards/merchant'
        }, 1500)
        return
      }
      
      let errorMessage = handleApiError(error)
      
      if (error.response?.data?.content === 'Email and phone is already verified.') {
        errorMessage = 'Email and phone is already verified. Please login to continue.'
        toast.success('Email and phone already verified! Redirecting to login...', {
          id: toastId,
          duration: 3000
        })
        setTimeout(() => {
          router.push('/login')
        }, 2000)
        return
      }
      
      if (error.response?.status === 400) {
        errorMessage = error.response?.data?.content || 'Invalid OTP. Please check and try again.'
      } else if (error.response?.status === 500) {
        errorMessage = 'Server error. Please try again later.'
      } else if (!error.response) {
        errorMessage = 'Network error. Please check your connection.'
      }
      
      console.log('Error Message:', errorMessage)
      
      toast.error(errorMessage, {
        id: toastId,
        duration: 5000
      })
      setError(errorMessage)
      handleFailedAttempt()
      resetOtpInputs()
    } finally {
      setIsVerifying(false)
    }
  }

  const handleResendOTP = async () => {
    if (isResending) return

    setIsResending(true)
    setError('')
    setSuccessMessage('')

    const toastId = toast.loading('Resending OTP...')

    try {
      const authToken = token as string
      const response = await axios.get<ApiResponse>(
        `${endpoints.auth.resendOtpEndpoint}/${authToken}`
      )
      
      if (response.data && response.data.code === 200) {
        const message = response.data.content || 'A new verification code has been sent to your email.'
        toast.success(message, {
          id: toastId,
          duration: 3000
        })
        setSuccessMessage(message)
        setAttempt(1)
        setResendVisible(false)
        setCallVisible(false)
        startCountdown(40)
        resetOtpInputs()
        
        setTimeout(() => {
          setSuccessMessage('')
        }, 5000)
      } else {
        const errorMsg = response.data?.message || response.data?.content || 'Failed to resend OTP'
        toast.error(errorMsg, {
          id: toastId,
          duration: 5000
        })
        setError(errorMsg)
      }
    } catch (error: any) {
      const errorMsg = handleApiError(error)
      setError(errorMsg)
      toast.error(errorMsg, {
        id: toastId,
        duration: 5000
      })
    } finally {
      setIsResending(false)
    }
  }

  const handleCallOTP = async () => {
    if (isCalling) return

    setIsCalling(true)
    setError('')
    setSuccessMessage('')

    const toastId = toast.loading('Sending OTP via call...')

    try {
      const authToken = token as string
      const response = await axios.get<ApiResponse>(
        `${endpoints.auth.resendOtpCallEndpoint}/${authToken}`
      )
      
      if (response.data && response.data.code === 200) {
        const message = response.data.content || 'A verification code has been sent via call.'
        toast.success(message, {
          id: toastId,
          duration: 3000
        })
        setSuccessMessage(message)
        setAttempt(2)
        setCallVisible(false)
        startCountdown(40)
        resetOtpInputs()
        
        setTimeout(() => {
          setSuccessMessage('')
        }, 5000)
      } else {
        const errorMsg = response.data?.message || response.data?.content || 'Failed to send OTP via call'
        toast.error(errorMsg, {
          id: toastId,
          duration: 5000
        })
        setError(errorMsg)
      }
    } catch (error: any) {
      const errorMsg = handleApiError(error)
      setError(errorMsg)
      toast.error(errorMsg, {
        id: toastId,
        duration: 5000
      })
    } finally {
      setIsCalling(false)
    }
  }

  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
  }

  const imageSource = skin === 'bordered' ? 'auth-v2-two-steps-illustration-bordered' : 'auth-v2-two-steps-illustration'

  if (!router.isReady || !pageLoaded) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <CircularProgress />
      </Box>
    )
  }

  if (isVerifyingInitial) {
    return (
      <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
        <RightWrapper>
          <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress size={60} />
              <Typography sx={{ mt: 4, color: 'text.secondary' }}>
                Verifying your email...
              </Typography>
            </Box>
          </Box>
        </RightWrapper>
      </Box>
    )
  }

  return (
    <Box className='content-right' sx={{ backgroundColor: 'background.paper' }}>
      {!hidden ? (
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            position: 'relative',
            alignItems: 'center',
            borderRadius: '20px',
            justifyContent: 'center',
            backgroundColor: 'customColors.bodyBg',
            margin: theme => theme.spacing(8, 0, 8, 8)
          }}
        >
          <Box sx={{ position: 'relative', width: '100%', height: '100%' }}>
            <AnimatePresence mode='wait'>
              <motion.div
                key='verify'
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ delay: 0.3, duration: 0.5, ease: 'easeInOut' }}
                style={{
                  position: 'absolute',
                  width: '100%',
                  height: '100%',
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center'
                }}
              >
                <TwoStepsIllustration 
                  alt='two-steps-illustration' 
                  src={`/images/pages/${imageSource}-${theme.palette.mode}.png`} 
                />
              </motion.div>
            </AnimatePresence>
          </Box>
        </Box>
      ) : null}

      <RightWrapper>
        <Box sx={{ p: [6, 12], height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <AnimatePresence mode='wait'>
            <motion.div
              key='verify-form'
              initial='hiddenRight'
              animate='visible'
              exit='exitLeft'
              variants={slideVariants}
              transition={{ duration: 0.5 }}
              style={{ width: '100%', display: 'flex', justifyContent: 'center' }}
            >
              <Box sx={{ width: '100%', maxWidth: 400 }}>
                <img
                  src='/images/website-logo/locktrust-logo.png'
                  alt='LockTrust Logo'
                  style={{ height: '60px', width: 'auto', objectFit: 'contain' }}
                />

                <motion.div
                  initial={{ y: -20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.3, duration: 0.5 }}
                >
                  <Box sx={{ mb: 6 }}>
                    <Typography sx={{ mb: 1.5, fontWeight: 500, fontSize: '1.625rem', lineHeight: 1.385 }}>
                      Verify Your Email 💬
                    </Typography>
                    <Typography sx={{ mb: 1.5, color: 'text.secondary' }}>
                      Enter the verification code sent to your email to verify your email address.
                    </Typography>
                    
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
                      <Typography sx={{ fontWeight: 500, color: theme.palette.primary.main }}>
                        {emailAddress}
                      </Typography>
                      {userDetails?.emailVerified && (
                        <Box sx={{ display: 'flex', alignItems: 'center', color: 'success.main' }}>
                          <Icon icon='tabler:circle-check-filled' fontSize={20} />
                          <Typography variant='caption' sx={{ ml: 0.5, color: 'success.main' }}>
                            Verified
                          </Typography>
                        </Box>
                      )}
                    </Box>
                  </Box>
                </motion.div>

                {userDetails && (
                  <motion.div
                    initial={{ y: 20, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    transition={{ delay: 0.35, duration: 0.5 }}
                  >
                    <Box sx={{ mb: 4, p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                        <Typography variant='body2' sx={{ fontWeight: 500, color: 'text.secondary' }}>
                          Phone Number
                        </Typography>
                        {!isEditingPhone && (
                          <IconButton size='small' onClick={handleEditPhone} sx={{ color: 'primary.main' }}>
                            <Icon icon='tabler:edit' fontSize={20} />
                          </IconButton>
                        )}
                      </Box>
                      
                      {!isEditingPhone ? (
                        <>
                          <Typography variant='body1' sx={{ fontWeight: 500 }}>
                            {userDetails.countryCode || '+91'} {userDetails.mobile}
                          </Typography>
                          {!userDetails.phoneVerified && (
                            <Typography variant='caption' sx={{ color: 'warning.main', display: 'block', mt: 0.5 }}>
                              Not verified yet
                            </Typography>
                          )}
                        </>
                      ) : (
                        <Box sx={{ mt: 2 }}>
                          <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
                            <FormControl fullWidth sx={{ flex: 0.5 }}>
                              <Autocomplete
                                id='country-select'
                                options={countries}
                                autoHighlight
                                getOptionLabel={(option: CountryOption) => {
                                  if (!option) return ''
                                  const dialCode = option.dialCode || option.phone || ''
                                  const name = option.name || option.label || ''
                                  return dialCode ? `${name} (+${dialCode})` : name
                                }}
                                value={selectedCountryCode}
                                onChange={(event: any, newValue: CountryOption | null) => {
                                  setSelectedCountryCode(newValue)
                                }}
                                renderOption={(props, option) => {
                                  const dialCode = option.dialCode || option.phone || ''
                                  const name = option.name || option.label || ''
                                  const countryCodeISO = option.code || ''
                                  return (
                                    <Box component='li' sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
                                      <img
                                        loading='lazy'
                                        width='24'
                                        height='18'
                                        src={`https://flagcdn.com/w40/${countryCodeISO?.toLowerCase()}.png`}
                                        srcSet={`https://flagcdn.com/w80/${countryCodeISO?.toLowerCase()}.png 2x`}
                                        alt=""
                                        style={{ marginRight: '12px' }}
                                      />
                                      <span style={{ fontWeight: 500 }}>{name}</span>
                                      {dialCode && (
                                        <span style={{ marginLeft: '8px', color: '#666' }}>(+{dialCode})</span>
                                      )}
                                    </Box>
                                  )
                                }}
                                renderInput={(params) => (
                                  <TextField
                                    {...params}
                                    label='Country Code'
                                    placeholder='Select country'
                                    size='small'
                                    InputProps={{
                                      ...params.InputProps,
                                      startAdornment: selectedCountryCode && selectedCountryCode.code && (
                                        <img
                                          src={`https://flagcdn.com/w20/${selectedCountryCode.code?.toLowerCase()}.png`}
                                          style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
                                          width='24'
                                          height='18'
                                          alt="flag"
                                        />
                                      ),
                                    }}
                                  />
                                )}
                              />
                            </FormControl>
                            
                            <TextField
                              fullWidth
                              size='small'
                              label='Phone Number'
                              value={phoneNumber}
                              onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ''))}
                              placeholder='Enter phone number'
                              inputProps={{ maxLength: 15 }}
                              sx={{ flex: 0.5 }}
                            />
                          </Box>
                          
                          <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
                            <Button size='small' onClick={handleCancelEdit} disabled={isUpdatingPhone}>
                              Cancel
                            </Button>
                            <Button 
                              size='small' 
                              variant='contained' 
                              onClick={handleUpdatePhone} 
                              disabled={isUpdatingPhone}
                            >
                              {isUpdatingPhone ? <CircularProgress size={20} /> : 'Save'}
                            </Button>
                          </Box>
                        </Box>
                      )}
                    </Box>
                  </motion.div>
                )}

                <motion.div
                  initial={{ scale: 0.95, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ delay: 0.4, duration: 0.5 }}
                >
                  {successMessage && (
                    <Alert 
                      severity='success' 
                      sx={{ mb: 4 }}
                      onClose={() => setSuccessMessage('')}
                    >
                      {successMessage}
                    </Alert>
                  )}
                </motion.div>

                <motion.div
                  initial={{ scale: 0.95, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ delay: 0.45, duration: 0.5 }}
                >
                  {error && (
                    <Alert severity='error' sx={{ mb: 4 }} onClose={() => setError('')}>
                      {error}
                    </Alert>
                  )}
                </motion.div>

                <motion.div
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.5, duration: 0.5 }}
                >
                  <Typography sx={{ fontWeight: 500, color: 'text.secondary', mb: 2 }}>
                    Type your 6-digit verification code
                  </Typography>
                </motion.div>

                <motion.form
                  onSubmit={handleSubmit(onSubmit)}
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.6, duration: 0.5 }}
                >
                  <CleaveWrapper
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      ...(errorsArray.length && {
                        '& .invalid:focus': {
                          borderColor: theme => `${theme.palette.error.main} !important`,
                          boxShadow: theme => `0 1px 3px 0 ${hexToRGBA(theme.palette.error.main, 0.4)}`
                        }
                      })
                    }}
                  >
                    {renderInputs()}
                  </CleaveWrapper>
                  
                  {errorsArray.length ? (
                    <FormHelperText sx={{ color: 'error.main' }}>Please enter a valid verification code</FormHelperText>
                  ) : null}

                  <Button 
                    fullWidth 
                    type='submit' 
                    variant='contained' 
                    disabled={isVerifying} 
                    sx={{ mt: 4 }}
                  >
                    {isVerifying ? (
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <CircularProgress size={24} color='inherit' />
                        Verifying...
                      </Box>
                    ) : (
                      'Verify Email'
                    )}
                  </Button>
                </motion.form>

                <motion.div
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.7, duration: 0.5 }}
                >
                  <Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1 }}>
                    {countdownActive && countdown > 0 && (
                      <Box sx={{ position: 'relative', display: 'inline-block', mb: 2 }}>
                        <img 
                          src='/images/clock.jpg'
                          alt='Clock'
                          style={{
                            width: '100px',
                            height: '100px',
                            display: 'block',
                            margin: '0 auto'
                          }}
                        />
                        <Box
                          sx={{
                            position: 'absolute',
                            top: '50%',
                            left: '50%',
                            transform: 'translate(-50%, -50%)',
                            fontSize: '14px',
                            fontWeight: 'bold',
                            color: 'white'
                          }}
                        >
                          {formatTime(countdown)}
                        </Box>
                      </Box>
                    )}

                    {resendVisible && (
                      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Typography sx={{ color: 'text.secondary' }}>Didn't get the code?</Typography>
                        <LinkStyled 
                          href='#' 
                          onClick={handleResendOTP}
                          sx={{ 
                            pointerEvents: isResending ? 'none' : 'auto',
                            opacity: isResending ? 0.6 : 1
                          }}
                        >
                          {isResending ? (
                            <CircularProgress size={20} />
                          ) : (
                            'Resend OTP'
                          )}
                        </LinkStyled>
                      </Box>
                    )}

                    {callVisible && (
                      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Typography sx={{ color: 'text.secondary' }}>Still having trouble?</Typography>
                        <CallLinkStyled 
                          href='#' 
                          onClick={handleCallOTP}
                          sx={{ 
                            pointerEvents: isCalling ? 'none' : 'auto',
                            opacity: isCalling ? 0.6 : 1
                          }}
                        >
                          {isCalling ? (
                            <CircularProgress size={20} />
                          ) : (
                            'Call Me'
                          )}
                        </CallLinkStyled>
                      </Box>
                    )}
                  </Box>
                </motion.div>

                <motion.div
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.9, duration: 0.5 }}
                >
                  <Box sx={{ mt: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Button
                      variant='text'
                      onClick={() => router.push('/login')}
                      sx={{ textTransform: 'none' }}
                      startIcon={<Icon icon='tabler:arrow-left' />}
                    >
                      Back to Login
                    </Button>
                  </Box>
                </motion.div>
              </Box>
            </motion.div>
          </AnimatePresence>
        </Box>
      </RightWrapper>
    </Box>
  )
}

// Fix: Add proper typing for the page parameter
EmailVerify.getLayout = (page: React.ReactNode) => <BlankLayout>{page}</BlankLayout>
EmailVerify.guestGuard = true

export default EmailVerify