// import { useState } from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Switch from '@mui/material/Switch'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'

// const countries = [
//   'India',
//   'United States',
//   'United Kingdom',
//   'Nauru',
//   'Canada'
// ]

// const currencies = ['USD', 'INR', 'EUR', 'GBP']

// const CompanyProfile = () => {
//   const [isParentCompany, setIsParentCompany] =
//     useState<boolean>(false)

//   const [isBillingAddressDifferent, setIsBillingAddressDifferent] =
//     useState<boolean>(false)

//   const renderCompanyFields = (title: string) => {
//     return (
//       <Card
//         sx={{
//           p: 6,
//           borderRadius: 3,
//           boxShadow: 'none',
//           border: theme => `1px solid ${theme.palette.divider}`
//         }}
//       >
//         <Typography
//           variant='h6'
//           sx={{
//             mb: 5,
//             fontWeight: 700
//           }}
//         >
//           {title}
//         </Typography>

//         <Grid container spacing={5}>
//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Company registration number'
//               placeholder='124456'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Legal name of company'
//               placeholder='Logic'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Registered DBA/trade name'
//               placeholder='fdtrg'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               select
//               fullWidth
//               label='Type of business'
//               defaultValue=''
//             >
//               <MenuItem value='benefit'>
//                 Benefit corporation
//               </MenuItem>

//               <MenuItem value='private'>
//                 Private Limited
//               </MenuItem>

//               <MenuItem value='llc'>LLC</MenuItem>
//             </TextField>
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Business Email'
//               placeholder='fh'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Address 1'
//               placeholder='mmn'
//             />
//           </Grid>

//           <Grid item xs={12}>
//             <Typography
//               variant='body2'
//               sx={{
//                 color: 'error.main',
//                 fontWeight: 500,
//                 mt: -2
//               }}
//             >
//               PO Boxes are not acceptable for onboarding
//             </Typography>
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Address 2'
//               placeholder='bmmn'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='City'
//               placeholder='gm'
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               select
//               fullWidth
//               label='Country'
//               defaultValue='Nauru'
//             >
//               {countries.map(country => (
//                 <MenuItem
//                   key={country}
//                   value={country}
//                 >
//                   {country}
//                 </MenuItem>
//               ))}
//             </TextField>
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='State'
//               placeholder='mv'
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Postcode / zip code'
//               placeholder='nvvnv'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Telephone number'
//               placeholder='8888888888'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               select
//               fullWidth
//               label='Currency'
//               defaultValue=''
//             >
//               {currencies.map(currency => (
//                 <MenuItem
//                   key={currency}
//                   value={currency}
//                 >
//                   {currency}
//                 </MenuItem>
//               ))}
//             </TextField>
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Turnover last year (Annual Sales)'
//               placeholder='n'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               type='date'
//               label='Incorporation Date'
//               InputLabelProps={{ shrink: true }}
//             />
//           </Grid>

//           <Grid item xs={12}>
//             <TextField
//               fullWidth
//               label='VAT / Tax Identification number'
//               placeholder='hfh'
//             />
//           </Grid>

//           <Grid item xs={12}>
//             <Stack spacing={2}>
//               <FormControlLabel
//                 control={<Switch />}
//                 label='Is company publicly listed on a stock exchange?'
//               />

//               <FormControlLabel
//                 control={<Switch />}
//                 label='Is company a registered not-for-profit organization?'
//               />
//             </Stack>
//           </Grid>
//         </Grid>
//       </Card>
//     )
//   }

//   return (
//     <Box>
//       {/* Parent Company Toggle */}
//       <Card
//         sx={{
//           p: 5,
//           mb: 6,
//           borderRadius: 3,
//           boxShadow: 'none',
//           border: theme => `1px solid ${theme.palette.divider}`
//         }}
//       >
//         <FormControlLabel
//           control={
//             <Switch
//               checked={isParentCompany}
//               onChange={e =>
//                 setIsParentCompany(e.target.checked)
//               }
//             />
//           }
//           label='Is Applying Company owned by a Parent Company?'
//         />
//       </Card>

//       {/* Applying Company */}
//       {renderCompanyFields('Applying Company Details')}

//       {/* Parent Company */}
//       {isParentCompany && (
//         <Box sx={{ mt: 6 }}>
//           {renderCompanyFields('Parent Company Details')}
//         </Box>
//       )}

//       {/* Billing Address */}
//       <Card
//         sx={{
//           mt: 6,
//           p: 6,
//           borderRadius: 3,
//           boxShadow: 'none',
//           border: theme => `1px solid ${theme.palette.divider}`
//         }}
//       >
//         <FormControlLabel
//           control={
//             <Switch
//               checked={isBillingAddressDifferent}
//               onChange={e =>
//                 setIsBillingAddressDifferent(
//                   e.target.checked
//                 )
//               }
//             />
//           }
//           label='Is billing address different from registered address?'
//         />

//         {isBillingAddressDifferent && (
//           <>
//             <Divider sx={{ my: 5 }} />

//             <Typography
//               variant='h6'
//               sx={{
//                 mb: 5,
//                 fontWeight: 700
//               }}
//             >
//               Billing Address
//             </Typography>

//             <Grid container spacing={5}>
//               <Grid item xs={12}>
//                 <Typography
//                   variant='body2'
//                   sx={{
//                     color: 'error.main',
//                     fontWeight: 500
//                   }}
//                 >
//                   PO Boxes are not acceptable for onboarding
//                 </Typography>
//               </Grid>

//               <Grid item xs={12} md={6}>
//                 <TextField
//                   fullWidth
//                   label='Street address'
//                 />
//               </Grid>

//               <Grid item xs={12} md={6}>
//                 <TextField
//                   fullWidth
//                   label='Address 2'
//                 />
//               </Grid>

//               <Grid item xs={12} md={4}>
//                 <TextField
//                   fullWidth
//                   label='Postcode / zip code'
//                 />
//               </Grid>

//               <Grid item xs={12} md={4}>
//                 <TextField fullWidth label='City' />
//               </Grid>

//               <Grid item xs={12} md={4}>
//                 <TextField
//                   select
//                   fullWidth
//                   label='Country'
//                   defaultValue=''
//                 >
//                   {countries.map(country => (
//                     <MenuItem
//                       key={country}
//                       value={country}
//                     >
//                       {country}
//                     </MenuItem>
//                   ))}
//                 </TextField>
//               </Grid>

//               <Grid item xs={12}>
//                 <TextField fullWidth label='State' />
//               </Grid>
//             </Grid>
//           </>
//         )}
//       </Card>
//     </Box>
//   )
// }

// export default CompanyProfile


// previous corrected //////////////

// import React, { useState } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import Autocomplete from '@mui/material/Autocomplete'
// import Paper from '@mui/material/Paper'
// import { countries } from 'src/@fake-db/autocomplete'

// const CompanyProfile = () => {
//   // Main company state
//   const [company, setCompany] = useState({
//     registrationNumber: '124456',
//     legalName: 'Logic',
//     dbaName: 'fdtrg',
//     businessType: 'Benefit corporation',
//     businessEmail: 'fh',
//     address1: 'mmn',
//     address2: 'bmmn',
//     city: 'gm',
//     country: null,
//     state: 'mv',
//     postcode: 'nvvnv',
//     telephone: '8888888888',
//     currency: '',
//     turnover: 'n',
//     incorporationDate: '2026-05-14',
//     vatNumber: 'fhfh',
//     publiclyListed: false,
//     notForProfit: false,
//   })

//   // Parent company state
//   const [hasParentCompany, setHasParentCompany] = useState(false)
//   const [parentCompany, setParentCompany] = useState({
//     registrationNumber: '',
//     legalName: '',
//     dbaName: '',
//     businessType: '',
//     businessEmail: '',
//     address1: '',
//     address2: '',
//     city: '',
//     country: null,
//     state: '',
//     postcode: '',
//   })

//   // Billing address state
//   const [billingDifferent, setBillingDifferent] = useState(false)
//   const [billingAddress, setBillingAddress] = useState({
//     street: '',
//     address2: '',
//     city: '',
//     state: '',
//     country: null,
//     postcode: '',
//   })

//   // Handle main company input changes
//   const handleCompanyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setCompany(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
//   }

//   // Handle main company autocomplete (country)
//   const handleCompanyCountryChange = (newValue: any) => {
//     setCompany(prev => ({ ...prev, country: newValue }))
//   }

//   // Handle parent company input changes
//   const handleParentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value } = e.target
//     setParentCompany(prev => ({ ...prev, [name]: value }))
//   }

//   // Handle parent company autocomplete (country)
//   const handleParentCountryChange = (newValue: any) => {
//     setParentCompany(prev => ({ ...prev, country: newValue }))
//   }

//   // Handle billing address input changes
//   const handleBillingChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value } = e.target
//     setBillingAddress(prev => ({ ...prev, [name]: value }))
//   }

//   // Handle billing address autocomplete (country)
//   const handleBillingCountryChange = (newValue: any) => {
//     setBillingAddress(prev => ({ ...prev, country: newValue }))
//   }

//   const handleSubmit = (e: React.FormEvent) => {
//     e.preventDefault()
//     const formData = {
//       company,
//       hasParentCompany,
//       parentCompany: hasParentCompany ? parentCompany : null,
//       billingDifferent,
//       billingAddress: billingDifferent ? billingAddress : null,
//     }
//     console.log('Form submitted:', formData)
//     alert('Form submitted successfully! Check console for data.')
//   }

//   // Business types
//   const businessTypes = [
//     'Sole Proprietorship',
//     'Partnership',
//     'Limited Liability Company (LLC)',
//     'Corporation',
//     'Benefit corporation',
//     'Non-profit Organization',
//     'Cooperative',
//     'Trust',
//     'Other'
//   ]

//   // Currencies
//   const currencies = [
//     'USD - US Dollar',
//     'EUR - Euro',
//     'GBP - British Pound',
//     'JPY - Japanese Yen',
//     'CAD - Canadian Dollar',
//     'AUD - Australian Dollar',
//     'CHF - Swiss Franc',
//     'CNY - Chinese Yuan',
//     'INR - Indian Rupee',
//     'BRL - Brazilian Real',
//     'ZAR - South African Rand',
//     'NZD - New Zealand Dollar',
//     'SGD - Singapore Dollar'
//   ]

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>
//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Applying Company Details
//               </Typography>
//               <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                 Please provide your company information accurately
//               </Typography>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Main Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                 <Box sx={{ width: 4, height: 24, bgcolor: 'primary.main', borderRadius: 2 }} />
//                 <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                   Company Information
//                 </Typography>
//               </Box>
              
//               <Grid container spacing={3}>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="registrationNumber"
//                     label="Company registration number"
//                     value={company.registrationNumber}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="Enter registration number"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="legalName"
//                     label="Legal name of company"
//                     value={company.legalName}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="Legal name"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="dbaName"
//                     label="Registered DBA/trade name"
//                     value={company.dbaName}
//                     onChange={handleCompanyChange}
//                     placeholder="Doing business as (if any)"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="businessType"
//                     label="Type of business"
//                     value={company.businessType}
//                     onChange={handleCompanyChange}
//                     required
//                   >
//                     {businessTypes.map(type => (
//                       <MenuItem key={type} value={type}>{type}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="businessEmail"
//                     label="Business Email"
//                     type="email"
//                     value={company.businessEmail}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="contact@company.com"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="telephone"
//                     label="Telephone number"
//                     value={company.telephone}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="+1 234 567 8900"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="address1"
//                     label="Address 1"
//                     value={company.address1}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="Street address"
//                     helperText="PO Boxes are not acceptable for onboarding"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="address2"
//                     label="Address 2"
//                     value={company.address2}
//                     onChange={handleCompanyChange}
//                     placeholder="Apartment, suite, unit, etc."
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="city"
//                     label="City"
//                     value={company.city}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="City"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="state"
//                     label="State / Province"
//                     value={company.state}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="State"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <Autocomplete
//                     id="company-country-select"
//                     options={countries}
//                     autoHighlight
//                     getOptionLabel={(option) => {
//                       if (!option) return ''
//                       if (typeof option === 'string') return option
//                       const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                       const name = option.name || option.label || ''
//                       return dialCode ? `${name} (+${dialCode})` : name
//                     }}
//                     value={company.country}
//                     onChange={(event, newValue) => handleCompanyCountryChange(newValue)}
//                     renderOption={(props, option) => {
//                       const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                       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"
//                         placeholder="Select country"
//                         required
//                         InputProps={{
//                           ...params.InputProps,
//                           startAdornment: company.country && (company.country.code || company.country.iso2) && (
//                             <img
//                               src={`https://flagcdn.com/w20/${(company.country.code || company.country.iso2)?.toLowerCase()}.png`}
//                               style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                               width="24"
//                               height="18"
//                               alt="flag"
//                             />
//                           ),
//                         }}
//                       />
//                     )}
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="postcode"
//                     label="Postcode / Zip code"
//                     value={company.postcode}
//                     onChange={handleCompanyChange}
//                     required
//                     placeholder="Postcode"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="currency"
//                     label="Currency"
//                     value={company.currency}
//                     onChange={handleCompanyChange}
//                     required
//                   >
//                     <MenuItem value="" disabled>-- Select Currency --</MenuItem>
//                     {currencies.map(currency => (
//                       <MenuItem key={currency} value={currency}>{currency}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="turnover"
//                     label="Turnover last year (Annual Sales)"
//                     value={company.turnover}
//                     onChange={handleCompanyChange}
//                     placeholder="e.g., $1,000,000"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="incorporationDate"
//                     label="Incorporation Date"
//                     type="date"
//                     value={company.incorporationDate}
//                     onChange={handleCompanyChange}
//                     required
//                     InputLabelProps={{ shrink: true }}
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="vatNumber"
//                     label="VAT / Tax Identification number"
//                     value={company.vatNumber}
//                     onChange={handleCompanyChange}
//                     placeholder="VAT/Tax ID"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.publiclyListed}
//                           onChange={handleCompanyChange}
//                           name="publiclyListed"
//                         />
//                       }
//                       label="Is company publicly listed on a stock exchange?"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.notForProfit}
//                           onChange={handleCompanyChange}
//                           name="notForProfit"
//                         />
//                       }
//                       label="Is company a registered 'not-for-profit' organization?"
//                     />
//                   </Stack>
//                 </Grid>
//               </Grid>
//             </Paper>

//             {/* Parent Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={hasParentCompany}
//                     onChange={(e) => setHasParentCompany(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Has Parent Company
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if this company is owned or controlled by another entity
//               </Typography>

//               {hasParentCompany && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#4caf50', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Parent Company Details
//                     </Typography>
//                   </Box>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="registrationNumber"
//                         label="Company registration number"
//                         value={parentCompany.registrationNumber}
//                         onChange={handleParentChange}
//                         placeholder="Parent registration number"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="legalName"
//                         label="Legal name of company"
//                         value={parentCompany.legalName}
//                         onChange={handleParentChange}
//                         placeholder="Parent legal name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="dbaName"
//                         label="Registered DBA/trade name"
//                         value={parentCompany.dbaName}
//                         onChange={handleParentChange}
//                         placeholder="Parent DBA name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         select
//                         name="businessType"
//                         label="Type of business"
//                         value={parentCompany.businessType}
//                         onChange={handleParentChange}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {businessTypes.map(type => (
//                           <MenuItem key={type} value={type}>{type}</MenuItem>
//                         ))}
//                       </TextField>
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="businessEmail"
//                         label="Business Email"
//                         type="email"
//                         value={parentCompany.businessEmail}
//                         onChange={handleParentChange}
//                         placeholder="parent@company.com"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="address1"
//                         label="Address 1"
//                         value={parentCompany.address1}
//                         onChange={handleParentChange}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="address2"
//                         label="Address 2"
//                         value={parentCompany.address2}
//                         onChange={handleParentChange}
//                         placeholder="Apartment, suite, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="city"
//                         label="City"
//                         value={parentCompany.city}
//                         onChange={handleParentChange}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="state"
//                         label="State / Province"
//                         value={parentCompany.state}
//                         onChange={handleParentChange}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <Autocomplete
//                         id="parent-country-select"
//                         options={countries}
//                         autoHighlight
//                         getOptionLabel={(option) => {
//                           if (!option) return ''
//                           if (typeof option === 'string') return option
//                           const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                           const name = option.name || option.label || ''
//                           return dialCode ? `${name} (+${dialCode})` : name
//                         }}
//                         value={parentCompany.country}
//                         onChange={(event, newValue) => handleParentCountryChange(newValue)}
//                         renderOption={(props, option) => {
//                           const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                           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"
//                             placeholder="Select country"
//                             InputProps={{
//                               ...params.InputProps,
//                               startAdornment: parentCompany.country && (parentCompany.country.code || parentCompany.country.iso2) && (
//                                 <img
//                                   src={`https://flagcdn.com/w20/${(parentCompany.country.code || parentCompany.country.iso2)?.toLowerCase()}.png`}
//                                   style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                                   width="24"
//                                   height="18"
//                                   alt="flag"
//                                 />
//                               ),
//                             }}
//                           />
//                         )}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="postcode"
//                         label="Postcode / Zip code"
//                         value={parentCompany.postcode}
//                         onChange={handleParentChange}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             {/* Billing Address Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={billingDifferent}
//                     onChange={(e) => setBillingDifferent(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Is billing address different from registered address?
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if your billing address is different from the company's registered address
//               </Typography>

//               {billingDifferent && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#ff9800', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Billing Address
//                     </Typography>
//                   </Box>
//                   <Typography variant="caption" sx={{ color: 'error.main', mb: 2, display: 'block' }}>
//                     PO Boxes are not acceptable for onboarding
//                   </Typography>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="street"
//                         label="Street address"
//                         value={billingAddress.street}
//                         onChange={handleBillingChange}
//                         required={billingDifferent}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="address2"
//                         label="Address 2"
//                         value={billingAddress.address2}
//                         onChange={handleBillingChange}
//                         placeholder="Apartment, suite, unit, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="city"
//                         label="City"
//                         value={billingAddress.city}
//                         onChange={handleBillingChange}
//                         required={billingDifferent}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="state"
//                         label="State / Province"
//                         value={billingAddress.state}
//                         onChange={handleBillingChange}
//                         required={billingDifferent}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <Autocomplete
//                         id="billing-country-select"
//                         options={countries}
//                         autoHighlight
//                         getOptionLabel={(option) => {
//                           if (!option) return ''
//                           if (typeof option === 'string') return option
//                           const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                           const name = option.name || option.label || ''
//                           return dialCode ? `${name} (+${dialCode})` : name
//                         }}
//                         value={billingAddress.country}
//                         onChange={(event, newValue) => handleBillingCountryChange(newValue)}
//                         renderOption={(props, option) => {
//                           const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//                           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"
//                             placeholder="Select country"
//                             required={billingDifferent}
//                             InputProps={{
//                               ...params.InputProps,
//                               startAdornment: billingAddress.country && (billingAddress.country.code || billingAddress.country.iso2) && (
//                                 <img
//                                   src={`https://flagcdn.com/w20/${(billingAddress.country.code || billingAddress.country.iso2)?.toLowerCase()}.png`}
//                                   style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                                   width="24"
//                                   height="18"
//                                   alt="flag"
//                                 />
//                               ),
//                             }}
//                           />
//                         )}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="postcode"
//                         label="Postcode / Zip code"
//                         value={billingAddress.postcode}
//                         onChange={handleBillingChange}
//                         required={billingDifferent}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             <Divider sx={{ my: 3 }} />

//             {/* Submit Button */}
//             <Button
//               type="submit"
//               fullWidth
//               variant="contained"
//               size="large"
//               sx={{
//                 py: 1.5,
//                 borderRadius: 2,
//                 textTransform: 'none',
//                 fontSize: '1rem',
//                 fontWeight: 600,
//                 boxShadow: 2,
//                 '&:hover': { boxShadow: 4 }
//               }}
//             >
//               Register Company Profile
//             </Button>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default CompanyProfile


// api integrated full updated code //////////////////////////////////
// import React, { useState, useEffect } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import Autocomplete from '@mui/material/Autocomplete'
// import Paper from '@mui/material/Paper'
// import CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import Skeleton from '@mui/material/Skeleton'
// import toast, { Toaster } from 'react-hot-toast'

// // ** Data
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Endpoints
// import endpoints from 'src/configs/endpoints'

// // ** Axios Instance
// import axiosInstance from 'src/configs/axios'

// // ** Types
// interface CountryType {
//   name: string
//   code: string
//   dialCode?: string
//   label?: string
//   phone?: string
//   iso2?: string
// }

// interface ValidationErrors {
//   [key: string]: string
// }

// const CompanyProfile = () => {
//   // Loading state
//   const [loading, setLoading] = useState<boolean>(false)
//   const [fetchingData, setFetchingData] = useState<boolean>(true)
//   const [error, setError] = useState<string | null>(null)
//   const [isEditMode, setIsEditMode] = useState<boolean>(false)
  
//   // Store parent company ID from backend if exists
//   const [parentCompanyId, setParentCompanyId] = useState<number>(0)

//   // Static Application ID
//   const STATIC_APPLICATION_ID = 84686078

//   // Main company state
//   const [company, setCompany] = useState({
//     companyRegistrationNo: '',
//     legalCompanyName: '',
//     tradeName: '',
//     businessType: '',
//     otherBusinessType: '',
//     registeredBusinessEmail: '',
//     registeredStreetAddress: '',
//     address2: '',
//     city: '',
//     country: null as CountryType | null,
//     state: '',
//     zipCode: '',
//     phone: '',
//     currency: '',
//     turnoverLastYear: '',
//     incorporationDate: '',
//     taxIdentificationNumber: '',
//     notForProfit: false,
//     stockExchange: false,
//   })

//   // Parent company state
//   const [hasParentCompany, setHasParentCompany] = useState<boolean>(false)
//   const [parentCompany, setParentCompany] = useState({
//     parentLegalCompanyName: '',
//     parentCompanyRegistrationNo: '',
//     parentTradeName: '',
//     parentBusinessType: '',
//     parentOtherBusinessType: '',
//     parentRegisteredBusinessEmail: '',
//     parentRegisteredStreetAddress: '',
//     parentAddress2: '',
//     parentCity: '',
//     parentCountry: null as CountryType | null,
//     parentState: '',
//     parentZipCode: '',
//     parentPhone: '',
//     parentCurrency: '',
//     parentTurnoverLastYear: '',
//     parentIncorporationDate: '',
//     parentTaxIdentificationNumber: '',
//     parentNotForProfit: false,
//     parentStockExchange: false,
//   })

//   // Billing address state
//   const [billingDifferent, setBillingDifferent] = useState<boolean>(false)
//   const [billingAddress, setBillingAddress] = useState({
//     billingStreetAddress: '',
//     billingAddress2: '',
//     billingCity: '',
//     billingState: '',
//     billingCountry: null as CountryType | null,
//     billingPostCode: '',
//   })

//   // Validation errors
//   const [errors, setErrors] = useState<ValidationErrors>({})

//   // Helper function to find country object from country name
//   const findCountryByName = (countryName: string): CountryType | null => {
//     if (!countryName) return null
//     const found = countries.find(
//       c => c.name === countryName || c.label === countryName || c.name?.toLowerCase() === countryName?.toLowerCase()
//     )
//     return found || null
//   }

//   // Fetch existing application data
//   const fetchApplicationData = async () => {
//     setFetchingData(true)
//     setError(null)
    
//     try {
//       const response = await axiosInstance.get(
//         `${endpoints.merchantApplication.getApplicationDetails}${STATIC_APPLICATION_ID}`
//       )
      
//       console.log('GET Response:', response.data)
      
//       // Check if response has companyProfile array
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         // Find the main company profile (where isparent is false or null)
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         // Find the parent company profile (where isparent is true)
//         const parentCompanyData = response.data.companyProfile.find((item: any) => item.isparent === true)
        
//         console.log('Main Company:', mainCompany)
//         console.log('Parent Company:', parentCompanyData)
        
//         if (mainCompany) {
//           console.log('Existing record found, prefilling data:', mainCompany)
//           setIsEditMode(true)
          
//           // Store parent company ID if exists
//           if (mainCompany.parentCompanyId && mainCompany.parentCompanyId > 0) {
//             setParentCompanyId(mainCompany.parentCompanyId)
//             console.log('Found existing parent company ID:', mainCompany.parentCompanyId)
//           } else {
//             setParentCompanyId(0)
//           }
          
//           prefillFormData(mainCompany, parentCompanyData)
//           // No toast message - data is visibly prefilled
//         } else {
//           console.log('No existing record found, will create new record on submit')
//           setIsEditMode(false)
//           setParentCompanyId(0)
//         }
//       } else {
//         console.log('No existing record found, will create new record on submit')
//         setIsEditMode(false)
//         setParentCompanyId(0)
//       }
//     } catch (err: any) {
//       console.error('Error fetching application data:', err)
//       // Only show error for genuine failures (500, network errors, etc.)
//       if (err.response?.status === 404) {
//         console.log('No record found (404), will create new record on submit')
//         setIsEditMode(false)
//         setParentCompanyId(0)
//       } else {
//         toast.error('Failed to load data. Please try again.')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   // Prefill form with existing data
//   const prefillFormData = (mainData: any, parentData: any) => {
//     console.log('Prefilling form with main data:', mainData)
//     console.log('Prefilling form with parent data:', parentData)
    
//     // Prefill main company data
//     if (mainData.companyRegistrationNo) {
//       setCompany(prev => ({ ...prev, companyRegistrationNo: mainData.companyRegistrationNo }))
//     }
//     if (mainData.legalCompanyName) {
//       setCompany(prev => ({ ...prev, legalCompanyName: mainData.legalCompanyName }))
//     }
//     if (mainData.tradeName && mainData.tradeName !== '') {
//       setCompany(prev => ({ ...prev, tradeName: mainData.tradeName }))
//     }
//     if (mainData.businessType && mainData.businessType !== '') {
//       // Check if business type is in the list, if not it's "other"
//       const validTypes = [
//         'SOLE_PROPRIETORSHIP',
//         'GENERAL_PARTNERSHIP',
//         'LIMITED_PARTNERSHIP',
//         'LIMITED_LIABILITY_PARTNERSHIP',
//         'C_CORPORATION',
//         'S_CORPORATION',
//         'BENEFIT_CORPORATION',
//         'LIMITED_LIABILITY_COMPANY',
//         'OTHER'
//       ]
//       if (validTypes.includes(mainData.businessType)) {
//         setCompany(prev => ({ ...prev, businessType: mainData.businessType }))
//       } else {
//         // If not in list, it's "other"
//         setCompany(prev => ({ ...prev, businessType: 'OTHER', otherBusinessType: mainData.businessType }))
//       }
//     }
//     if (mainData.registeredBusinessEmail) {
//       setCompany(prev => ({ ...prev, registeredBusinessEmail: mainData.registeredBusinessEmail }))
//     }
//     if (mainData.registeredStreetAddress) {
//       setCompany(prev => ({ ...prev, registeredStreetAddress: mainData.registeredStreetAddress }))
//     }
//     if (mainData.address2 && mainData.address2 !== '' && mainData.address2 !== 'NA') {
//       setCompany(prev => ({ ...prev, address2: mainData.address2 }))
//     }
//     if (mainData.city && mainData.city !== '' && mainData.city !== 'NA') {
//       setCompany(prev => ({ ...prev, city: mainData.city }))
//     }
//     if (mainData.country && mainData.country !== '' && mainData.country !== 'NA') {
//       const countryObj = findCountryByName(mainData.country)
//       setCompany(prev => ({ ...prev, country: countryObj }))
//     }
//     if (mainData.state && mainData.state !== '' && mainData.state !== 'NA') {
//       setCompany(prev => ({ ...prev, state: mainData.state }))
//     }
//     if (mainData.zipCode && mainData.zipCode !== '' && mainData.zipCode !== 'NA') {
//       setCompany(prev => ({ ...prev, zipCode: mainData.zipCode }))
//     }
//     if (mainData.phone) {
//       setCompany(prev => ({ ...prev, phone: mainData.phone }))
//     }
//     if (mainData.currency && mainData.currency !== '') {
//       setCompany(prev => ({ ...prev, currency: mainData.currency }))
//     }
//     if (mainData.turnoverLastYear && mainData.turnoverLastYear !== '') {
//       setCompany(prev => ({ ...prev, turnoverLastYear: mainData.turnoverLastYear }))
//     }
//     if (mainData.incorporationDate) {
//       setCompany(prev => ({ ...prev, incorporationDate: mainData.incorporationDate }))
//     }
//     if (mainData.taxIdentificationNumber && mainData.taxIdentificationNumber !== '') {
//       setCompany(prev => ({ ...prev, taxIdentificationNumber: mainData.taxIdentificationNumber }))
//     }
//     if (mainData.notForProfit !== undefined) {
//       setCompany(prev => ({ ...prev, notForProfit: mainData.notForProfit }))
//     }
//     if (mainData.stockExchange !== undefined) {
//       setCompany(prev => ({ ...prev, stockExchange: mainData.stockExchange }))
//     }
    
//     // Parent company data - boolean value from main company
//     if (mainData.havingParentCompany !== undefined) {
//       setHasParentCompany(mainData.havingParentCompany === true || mainData.havingParentCompany === 'true')
//     }
    
//     // Prefill parent company details if parent data exists
//     if (parentData) {
//       if (parentData.legalCompanyName) {
//         setParentCompany(prev => ({ ...prev, parentLegalCompanyName: parentData.legalCompanyName }))
//       }
//       if (parentData.companyRegistrationNo) {
//         setParentCompany(prev => ({ ...prev, parentCompanyRegistrationNo: parentData.companyRegistrationNo }))
//       }
//       if (parentData.tradeName && parentData.tradeName !== '' && parentData.tradeName !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentTradeName: parentData.tradeName }))
//       }
//       if (parentData.businessType && parentData.businessType !== '') {
//         const validTypes = [
//           'SOLE_PROPRIETORSHIP',
//           'GENERAL_PARTNERSHIP',
//           'LIMITED_PARTNERSHIP',
//           'LIMITED_LIABILITY_PARTNERSHIP',
//           'C_CORPORATION',
//           'S_CORPORATION',
//           'BENEFIT_CORPORATION',
//           'LIMITED_LIABILITY_COMPANY',
//           'OTHER'
//         ]
//         if (validTypes.includes(parentData.businessType)) {
//           setParentCompany(prev => ({ ...prev, parentBusinessType: parentData.businessType }))
//         } else {
//           setParentCompany(prev => ({ ...prev, parentBusinessType: 'OTHER', parentOtherBusinessType: parentData.businessType }))
//         }
//       }
//       if (parentData.registeredBusinessEmail) {
//         setParentCompany(prev => ({ ...prev, parentRegisteredBusinessEmail: parentData.registeredBusinessEmail }))
//       }
//       if (parentData.registeredStreetAddress) {
//         setParentCompany(prev => ({ ...prev, parentRegisteredStreetAddress: parentData.registeredStreetAddress }))
//       }
//       if (parentData.address2 && parentData.address2 !== '' && parentData.address2 !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentAddress2: parentData.address2 }))
//       }
//       if (parentData.city && parentData.city !== '' && parentData.city !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentCity: parentData.city }))
//       }
//       if (parentData.country && parentData.country !== '' && parentData.country !== 'NA') {
//         const countryObj = findCountryByName(parentData.country)
//         setParentCompany(prev => ({ ...prev, parentCountry: countryObj }))
//       }
//       if (parentData.state && parentData.state !== '' && parentData.state !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentState: parentData.state }))
//       }
//       if (parentData.zipCode && parentData.zipCode !== '' && parentData.zipCode !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentZipCode: parentData.zipCode }))
//       }
//       if (parentData.phone) {
//         setParentCompany(prev => ({ ...prev, parentPhone: parentData.phone }))
//       }
//       if (parentData.currency && parentData.currency !== '') {
//         setParentCompany(prev => ({ ...prev, parentCurrency: parentData.currency }))
//       }
//       if (parentData.turnoverLastYear && parentData.turnoverLastYear !== '') {
//         setParentCompany(prev => ({ ...prev, parentTurnoverLastYear: parentData.turnoverLastYear }))
//       }
//       if (parentData.incorporationDate) {
//         setParentCompany(prev => ({ ...prev, parentIncorporationDate: parentData.incorporationDate }))
//       }
//       if (parentData.taxIdentificationNumber && parentData.taxIdentificationNumber !== '') {
//         setParentCompany(prev => ({ ...prev, parentTaxIdentificationNumber: parentData.taxIdentificationNumber }))
//       }
//       if (parentData.notForProfit !== undefined) {
//         setParentCompany(prev => ({ ...prev, parentNotForProfit: parentData.notForProfit }))
//       }
//       if (parentData.stockExchange !== undefined) {
//         setParentCompany(prev => ({ ...prev, parentStockExchange: parentData.stockExchange }))
//       }
//     }
    
//     // Billing data from main company
//     if (mainData.billingRegisteredAddress !== undefined) {
//       setBillingDifferent(mainData.billingRegisteredAddress === true || mainData.billingRegisteredAddress === 'true')
//     }
    
//     if (mainData.billingRegisteredAddress === true) {
//       if (mainData.billingStreetAddress && mainData.billingStreetAddress !== '' && mainData.billingStreetAddress !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingStreetAddress: mainData.billingStreetAddress }))
//       }
//       if (mainData.billingAddress2 && mainData.billingAddress2 !== '' && mainData.billingAddress2 !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingAddress2: mainData.billingAddress2 }))
//       }
//       if (mainData.billingCity && mainData.billingCity !== '' && mainData.billingCity !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingCity: mainData.billingCity }))
//       }
//       if (mainData.billingState && mainData.billingState !== '' && mainData.billingState !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingState: mainData.billingState }))
//       }
//       if (mainData.billingCountry && mainData.billingCountry !== '' && mainData.billingCountry !== 'NA') {
//         const countryObj = findCountryByName(mainData.billingCountry)
//         setBillingAddress(prev => ({ ...prev, billingCountry: countryObj }))
//       }
//       if (mainData.billingPostCode && mainData.billingPostCode !== '' && mainData.billingPostCode !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingPostCode: mainData.billingPostCode }))
//       }
//     }
//   }

//   // Load data on component mount
//   useEffect(() => {
//     fetchApplicationData()
//   }, [])

//   // Handle main company input changes
//   const handleCompanyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setCompany(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle main company autocomplete (country)
//   const handleCompanyCountryChange = (newValue: CountryType | null) => {
//     setCompany(prev => ({ ...prev, country: newValue }))
//     if (errors.country) {
//       setErrors(prev => ({ ...prev, country: '' }))
//     }
//   }

//   // Handle parent company input changes
//   const handleParentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setParentCompany(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }))
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle parent company autocomplete (country)
//   const handleParentCountryChange = (newValue: CountryType | null) => {
//     setParentCompany(prev => ({ ...prev, parentCountry: newValue }))
//     if (errors.parentCountry) {
//       setErrors(prev => ({ ...prev, parentCountry: '' }))
//     }
//   }

//   // Handle billing address input changes
//   const handleBillingChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value } = e.target
//     setBillingAddress(prev => ({ ...prev, [name]: value }))
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle billing address autocomplete (country)
//   const handleBillingCountryChange = (newValue: CountryType | null) => {
//     setBillingAddress(prev => ({ ...prev, billingCountry: newValue }))
//     if (errors.billingCountry) {
//       setErrors(prev => ({ ...prev, billingCountry: '' }))
//     }
//   }

//   // Build request body for API
//   const buildRequestBody = () => {
//     // Determine the business type to send
//     let businessTypeToSend = company.businessType
//     if (company.businessType === 'OTHER' && company.otherBusinessType) {
//       businessTypeToSend = company.otherBusinessType
//     }

//     const requestBody: any = {
//       applicationId: STATIC_APPLICATION_ID,
      
//       // Company fields - always include with proper values
//       companyRegistrationNo: company.companyRegistrationNo || '',
//       legalCompanyName: company.legalCompanyName || '',
//       tradeName: company.tradeName || '',
//       businessType: businessTypeToSend || '',
//       registeredBusinessEmail: company.registeredBusinessEmail || '',
//       registeredStreetAddress: company.registeredStreetAddress || '',
//       address2: company.address2 || '',
//       city: company.city || '',
//       country: company.country?.name || company.country?.label || '',
//       state: company.state || '',
//       zipCode: company.zipCode || '',
//       phone: company.phone || '',
//       currency: company.currency || '',
//       turnoverLastYear: company.turnoverLastYear || '',
//       incorporationDate: company.incorporationDate || '',
//       taxIdentificationNumber: company.taxIdentificationNumber || '',
//       notForProfit: company.notForProfit,
//       stockExchange: company.stockExchange,
      
//       // Parent company flags - send as boolean true/false
//       havingParentCompany: hasParentCompany,
//       billingRegisteredAddress: billingDifferent,
//     }

//     // Handle parent company based on hasParentCompany flag
//     if (hasParentCompany === true) {
//       // Determine parent business type
//       let parentBusinessTypeToSend = parentCompany.parentBusinessType
//       if (parentCompany.parentBusinessType === 'OTHER' && parentCompany.parentOtherBusinessType) {
//         parentBusinessTypeToSend = parentCompany.parentOtherBusinessType
//       }

//       // Include all parent fields when parent company exists
//       requestBody.parentLegalCompanyName = parentCompany.parentLegalCompanyName || ''
//       requestBody.parentCompanyRegistrationNo = parentCompany.parentCompanyRegistrationNo || ''
//       requestBody.parentTradeName = parentCompany.parentTradeName || ''
//       requestBody.parentBusinessType = parentBusinessTypeToSend || ''
//       requestBody.parentRegisteredBusinessEmail = parentCompany.parentRegisteredBusinessEmail || ''
//       requestBody.parentRegisteredStreetAddress = parentCompany.parentRegisteredStreetAddress || ''
//       requestBody.parentAddress2 = parentCompany.parentAddress2 || ''
//       requestBody.parentCity = parentCompany.parentCity || ''
//       requestBody.parentCountry = parentCompany.parentCountry?.name || parentCompany.parentCountry?.label || ''
//       requestBody.parentState = parentCompany.parentState || ''
//       requestBody.parentZipCode = parentCompany.parentZipCode || ''
//       requestBody.parentPhone = parentCompany.parentPhone || ''
//       requestBody.parentCurrency = parentCompany.parentCurrency || ''
//       requestBody.parentTurnoverLastYear = parentCompany.parentTurnoverLastYear || ''
//       requestBody.parentIncorporationDate = parentCompany.parentIncorporationDate || ''
//       requestBody.parentTaxIdentificationNumber = parentCompany.parentTaxIdentificationNumber || ''
//       requestBody.parentNotForProfit = parentCompany.parentNotForProfit
//       requestBody.parentStockExchange = parentCompany.parentStockExchange
      
//       // Only send parentCompanyId if we're editing an EXISTING parent company
//       if (parentCompanyId > 0) {
//         requestBody.parentCompanyId = parentCompanyId
//         console.log('Updating existing parent company with ID:', parentCompanyId)
//       } else {
//         console.log('Creating new parent company (no ID sent)')
//       }
//     } else {
//       // When no parent company, send empty strings for all parent fields
//       requestBody.parentLegalCompanyName = ''
//       requestBody.parentCompanyRegistrationNo = ''
//       requestBody.parentTradeName = ''
//       requestBody.parentBusinessType = ''
//       requestBody.parentRegisteredBusinessEmail = ''
//       requestBody.parentRegisteredStreetAddress = ''
//       requestBody.parentAddress2 = ''
//       requestBody.parentCity = ''
//       requestBody.parentCountry = ''
//       requestBody.parentState = ''
//       requestBody.parentZipCode = ''
//       requestBody.parentPhone = ''
//       requestBody.parentCurrency = ''
//       requestBody.parentTurnoverLastYear = ''
//       requestBody.parentIncorporationDate = ''
//       requestBody.parentTaxIdentificationNumber = ''
//       requestBody.parentNotForProfit = false
//       requestBody.parentStockExchange = false
//       // When removing parent company, send 0 to delete/remove it
//       if (isEditMode) {
//         requestBody.parentCompanyId = 0
//         console.log('Removing parent company, sending ID 0')
//       }
//     }

//     // Handle billing address based on billingDifferent flag
//     if (billingDifferent === true) {
//       requestBody.billingStreetAddress = billingAddress.billingStreetAddress || ''
//       requestBody.billingAddress2 = billingAddress.billingAddress2 || ''
//       requestBody.billingCity = billingAddress.billingCity || ''
//       requestBody.billingState = billingAddress.billingState || ''
//       requestBody.billingCountry = billingAddress.billingCountry?.name || billingAddress.billingCountry?.label || ''
//       requestBody.billingPostCode = billingAddress.billingPostCode || ''
//     } else {
//       requestBody.billingStreetAddress = ''
//       requestBody.billingAddress2 = ''
//       requestBody.billingCity = ''
//       requestBody.billingState = ''
//       requestBody.billingCountry = ''
//       requestBody.billingPostCode = ''
//     }

//     return requestBody
//   }

//   // Handle form submission - Create or Update based on mode
//   const handleSubmit = async (e: React.FormEvent) => {
//     e.preventDefault()
    
//     setLoading(true)
//     setError(null)

//     const requestBody = buildRequestBody()
    
//     console.log('=== SUBMIT DEBUG INFO ===')
//     console.log('Submit Mode:', isEditMode ? 'UPDATE (PUT)' : 'CREATE (POST)')
//     console.log('Has Parent Company:', hasParentCompany)
//     console.log('Parent Company ID in state:', parentCompanyId)
//     console.log('Is Edit Mode:', isEditMode)
//     console.log('Request Body:', JSON.stringify(requestBody, null, 2))

//     try {
//       let response
      
//       if (isEditMode) {
//         // UPDATE existing record using PUT
//         response = await axiosInstance.put(
//           `${endpoints.merchantApplication.companyProfile}${STATIC_APPLICATION_ID}`,
//           requestBody
//         )
//         console.log('PUT Response:', response.data)
//         toast.success('Company profile updated successfully!')
        
//         setTimeout(() => {
//           fetchApplicationData()
//         }, 1000)
//       } else {
//         // CREATE new record using POST
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.companyProfile,
//           requestBody
//         )
//         console.log('POST Response:', response.data)
//         toast.success('Company profile created successfully!')
//         setIsEditMode(true)
        
//         if (response.data && response.data.parentCompanyId) {
//           setParentCompanyId(response.data.parentCompanyId)
//           console.log('New parent company created with ID:', response.data.parentCompanyId)
//         }
//       }

//       if (response.data) {
//         setTimeout(() => {
//           fetchApplicationData()
//         }, 1000)
//       }
//     } catch (err: any) {
//       console.error('API Error:', err)
//       console.error('Error Response:', err.response?.data)
      
//       let errorMessage = isEditMode 
//         ? 'Failed to update company profile. Please try again.'
//         : 'Failed to create company profile. Please try again.'
      
//       if (err.response?.data) {
//         if (err.response.data.content) {
//           if (typeof err.response.data.content === 'object') {
//             const errorObj = err.response.data.content
//             const errorMessages = Object.entries(errorObj).map(([key, value]) => {
//               return `${key}: ${value}`
//             }).join(', ')
//             errorMessage = errorMessages
//             toast.error(errorMessages)
            
//             const fieldErrors: ValidationErrors = {}
//             Object.entries(errorObj).forEach(([key, value]) => {
//               fieldErrors[key] = Array.isArray(value) ? value[0] : String(value)
//             })
//             setErrors(fieldErrors)
//           } else {
//             errorMessage = err.response.data.content
//             toast.error(errorMessage)
//           }
//         } else if (err.response.data.message) {
//           errorMessage = err.response.data.message
//           toast.error(errorMessage)
//         } else {
//           toast.error(errorMessage)
//         }
//       } else {
//         toast.error(errorMessage)
//       }
      
//       setError(errorMessage)
//     } finally {
//       setLoading(false)
//     }
//   }

//   // Business types - Updated list
//   const businessTypes = [
//     'SOLE_PROPRIETORSHIP',
//     'GENERAL_PARTNERSHIP',
//     'LIMITED_PARTNERSHIP',
//     'LIMITED_LIABILITY_PARTNERSHIP',
//     'C_CORPORATION',
//     'S_CORPORATION',
//     'BENEFIT_CORPORATION',
//     'LIMITED_LIABILITY_COMPANY',
//     'OTHER'
//   ]

//   const businessTypeLabels: Record<string, string> = {
//     SOLE_PROPRIETORSHIP: 'Sole Proprietorship',
//     GENERAL_PARTNERSHIP: 'General Partnership',
//     LIMITED_PARTNERSHIP: 'Limited Partnership',
//     LIMITED_LIABILITY_PARTNERSHIP: 'Limited Liability Partnership (LLP)',
//     C_CORPORATION: 'C Corporation',
//     S_CORPORATION: 'S Corporation',
//     BENEFIT_CORPORATION: 'Benefit Corporation',
//     LIMITED_LIABILITY_COMPANY: 'Limited Liability Company (LLC)',
//     OTHER: 'Other'
//   }

//   const currencies = ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CHF', 'CNY', 'INR', 'BRL', 'ZAR', 'NZD', 'SGD']

//   // Helper to render Autocomplete with flag
//   const renderCountryAutocomplete = (
//     id: string,
//     value: CountryType | null,
//     onChange: (value: CountryType | null) => void,
//     label: string,
//     error?: string,
//     required?: boolean
//   ) => (
//     <Autocomplete
//       id={id}
//       options={countries}
//       autoHighlight
//       getOptionLabel={(option) => {
//         if (!option) return ''
//         if (typeof option === 'string') return option
//         const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//         const name = option.name || option.label || ''
//         return dialCode ? `${name} (+${dialCode})` : name
//       }}
//       value={value}
//       onChange={(event, newValue) => onChange(newValue)}
//       renderOption={(props, option) => {
//         const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//         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={label}
//           placeholder="Select country"
//           required={required}
//           error={!!error}
//           helperText={error}
//           InputProps={{
//             ...params.InputProps,
//             startAdornment: value && (value.code || value.iso2) && (
//               <img
//                 src={`https://flagcdn.com/w20/${(value.code || value.iso2)?.toLowerCase()}.png`}
//                 style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                 width="24"
//                 height="18"
//                 alt="flag"
//               />
//             ),
//           }}
//         />
//       )}
//     />
//   )

//   if (fetchingData) {
//     return (
//       <Box sx={{ p: 6 }}>
//         <Card sx={{ p: 6 }}>
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={400} />
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={200} />
//         </Card>
//       </Box>
//     )
//   }

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Toaster position="top-right" />
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>
//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Applying Company Details
//               </Typography>
//               <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                 Application ID: <strong>{STATIC_APPLICATION_ID}</strong>
//                 {isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#4caf50' }}>
//                     (Editing existing record)
//                   </span>
//                 )}
//                 {!isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#ff9800' }}>
//                     (Creating new record)
//                   </span>
//                 )}
//               </Typography>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Info Alert */}
//             <Alert severity="info" sx={{ mb: 3 }}>
//               <Typography variant="body2">
//                 {isEditMode 
//                   ? 'You can edit any field. All changes will be updated via PUT request.'
//                   : 'Fill the form to create a new record. You can edit later.'}
//               </Typography>
//             </Alert>

//             {/* Error Alert */}
//             {error && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )}

//             {/* Main Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                 <Box sx={{ width: 4, height: 24, bgcolor: 'primary.main', borderRadius: 2 }} />
//                 <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                   Company Information
//                 </Typography>
//               </Box>
              
//               <Grid container spacing={3}>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="companyRegistrationNo"
//                     label="Company registration number"
//                     value={company.companyRegistrationNo}
//                     onChange={handleCompanyChange}
//                     error={!!errors.companyRegistrationNo}
//                     helperText={errors.companyRegistrationNo}
//                     placeholder="Enter registration number"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="legalCompanyName"
//                     label="Legal name of company"
//                     value={company.legalCompanyName}
//                     onChange={handleCompanyChange}
//                     error={!!errors.legalCompanyName}
//                     helperText={errors.legalCompanyName}
//                     placeholder="Legal name"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="tradeName"
//                     label="Registered DBA/trade name"
//                     value={company.tradeName}
//                     onChange={handleCompanyChange}
//                     error={!!errors.tradeName}
//                     helperText={errors.tradeName}
//                     placeholder="Doing business as (if any)"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="businessType"
//                     label="Type of business"
//                     value={company.businessType}
//                     onChange={handleCompanyChange}
//                     error={!!errors.businessType}
//                     helperText={errors.businessType}
//                   >
//                     <MenuItem value="" disabled>-- Select Business Type --</MenuItem>
//                     {businessTypes.map(type => (
//                       <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 {company.businessType === 'OTHER' && (
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       name="otherBusinessType"
//                       label="Please specify your business type"
//                       value={company.otherBusinessType}
//                       onChange={handleCompanyChange}
//                       placeholder="Enter your business type"
//                       error={!!errors.otherBusinessType}
//                       helperText={errors.otherBusinessType}
//                     />
//                   </Grid>
//                 )}
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="registeredBusinessEmail"
//                     label="Business Email"
//                     type="email"
//                     value={company.registeredBusinessEmail}
//                     onChange={handleCompanyChange}
//                     error={!!errors.registeredBusinessEmail}
//                     helperText={errors.registeredBusinessEmail}
//                     placeholder="contact@company.com"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="phone"
//                     label="Telephone number"
//                     value={company.phone}
//                     onChange={handleCompanyChange}
//                     error={!!errors.phone}
//                     helperText={errors.phone}
//                     placeholder="+1 234 567 8900"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="registeredStreetAddress"
//                     label="Address 1"
//                     value={company.registeredStreetAddress}
//                     onChange={handleCompanyChange}
//                     error={!!errors.registeredStreetAddress}
//                     helperText={errors.registeredStreetAddress || "PO Boxes are not acceptable for onboarding"}
//                     placeholder="Street address"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="address2"
//                     label="Address 2"
//                     value={company.address2}
//                     onChange={handleCompanyChange}
//                     error={!!errors.address2}
//                     helperText={errors.address2}
//                     placeholder="Apartment, suite, unit, etc."
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="city"
//                     label="City"
//                     value={company.city}
//                     onChange={handleCompanyChange}
//                     error={!!errors.city}
//                     helperText={errors.city}
//                     placeholder="City"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="state"
//                     label="State / Province"
//                     value={company.state}
//                     onChange={handleCompanyChange}
//                     error={!!errors.state}
//                     helperText={errors.state}
//                     placeholder="State"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   {renderCountryAutocomplete(
//                     'company-country-select',
//                     company.country,
//                     handleCompanyCountryChange,
//                     'Country',
//                     errors.country
//                   )}
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="zipCode"
//                     label="Postcode / Zip code"
//                     value={company.zipCode}
//                     onChange={handleCompanyChange}
//                     error={!!errors.zipCode}
//                     helperText={errors.zipCode}
//                     placeholder="Postcode"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="currency"
//                     label="Currency"
//                     value={company.currency}
//                     onChange={handleCompanyChange}
//                     error={!!errors.currency}
//                     helperText={errors.currency}
//                   >
//                     <MenuItem value="" disabled>-- Select Currency --</MenuItem>
//                     {currencies.map(currency => (
//                       <MenuItem key={currency} value={currency}>{currency}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="turnoverLastYear"
//                     label="Turnover last year (Annual Sales)"
//                     value={company.turnoverLastYear}
//                     onChange={handleCompanyChange}
//                     error={!!errors.turnoverLastYear}
//                     helperText={errors.turnoverLastYear}
//                     placeholder="e.g., 1000000"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="incorporationDate"
//                     label="Incorporation Date"
//                     type="date"
//                     value={company.incorporationDate}
//                     onChange={handleCompanyChange}
//                     error={!!errors.incorporationDate}
//                     helperText={errors.incorporationDate}
//                     InputLabelProps={{ shrink: true }}
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="taxIdentificationNumber"
//                     label="VAT / Tax Identification number"
//                     value={company.taxIdentificationNumber}
//                     onChange={handleCompanyChange}
//                     error={!!errors.taxIdentificationNumber}
//                     helperText={errors.taxIdentificationNumber}
//                     placeholder="VAT/Tax ID"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.stockExchange}
//                           onChange={handleCompanyChange}
//                           name="stockExchange"
//                         />
//                       }
//                       label="Is company publicly listed on a stock exchange?"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.notForProfit}
//                           onChange={handleCompanyChange}
//                           name="notForProfit"
//                         />
//                       }
//                       label="Is company a registered 'not-for-profit' organization?"
//                     />
//                   </Stack>
//                 </Grid>
//               </Grid>
//             </Paper>

//             {/* Parent Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={hasParentCompany}
//                     onChange={(e) => setHasParentCompany(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Has Parent Company
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if this company is owned or controlled by another entity
//               </Typography>

//               {hasParentCompany && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#4caf50', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Parent Company Details
//                     </Typography>
//                   </Box>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentCompanyRegistrationNo"
//                         label="Company registration number"
//                         value={parentCompany.parentCompanyRegistrationNo}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCompanyRegistrationNo}
//                         helperText={errors.parentCompanyRegistrationNo}
//                         placeholder="Parent registration number"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentLegalCompanyName"
//                         label="Legal name of company"
//                         value={parentCompany.parentLegalCompanyName}
//                         onChange={handleParentChange}
//                         error={!!errors.parentLegalCompanyName}
//                         helperText={errors.parentLegalCompanyName}
//                         placeholder="Parent legal name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTradeName"
//                         label="Registered DBA/trade name"
//                         value={parentCompany.parentTradeName}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTradeName}
//                         helperText={errors.parentTradeName}
//                         placeholder="Parent DBA name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         select
//                         name="parentBusinessType"
//                         label="Type of business"
//                         value={parentCompany.parentBusinessType}
//                         onChange={handleParentChange}
//                         error={!!errors.parentBusinessType}
//                         helperText={errors.parentBusinessType}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {businessTypes.map(type => (
//                           <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                         ))}
//                       </TextField>
//                     </Grid>
//                     {parentCompany.parentBusinessType === 'OTHER' && (
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           name="parentOtherBusinessType"
//                           label="Please specify parent business type"
//                           value={parentCompany.parentOtherBusinessType}
//                           onChange={handleParentChange}
//                           placeholder="Enter parent business type"
//                           error={!!errors.parentOtherBusinessType}
//                           helperText={errors.parentOtherBusinessType}
//                         />
//                       </Grid>
//                     )}
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentRegisteredBusinessEmail"
//                         label="Business Email"
//                         type="email"
//                         value={parentCompany.parentRegisteredBusinessEmail}
//                         onChange={handleParentChange}
//                         error={!!errors.parentRegisteredBusinessEmail}
//                         helperText={errors.parentRegisteredBusinessEmail}
//                         placeholder="parent@company.com"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentPhone"
//                         label="Telephone number"
//                         value={parentCompany.parentPhone}
//                         onChange={handleParentChange}
//                         error={!!errors.parentPhone}
//                         helperText={errors.parentPhone}
//                         placeholder="Parent phone number"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="parentRegisteredStreetAddress"
//                         label="Address 1"
//                         value={parentCompany.parentRegisteredStreetAddress}
//                         onChange={handleParentChange}
//                         error={!!errors.parentRegisteredStreetAddress}
//                         helperText={errors.parentRegisteredStreetAddress}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="parentAddress2"
//                         label="Address 2"
//                         value={parentCompany.parentAddress2}
//                         onChange={handleParentChange}
//                         error={!!errors.parentAddress2}
//                         helperText={errors.parentAddress2}
//                         placeholder="Apartment, suite, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentCity"
//                         label="City"
//                         value={parentCompany.parentCity}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCity}
//                         helperText={errors.parentCity}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentState"
//                         label="State / Province"
//                         value={parentCompany.parentState}
//                         onChange={handleParentChange}
//                         error={!!errors.parentState}
//                         helperText={errors.parentState}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       {renderCountryAutocomplete(
//                         'parent-country-select',
//                         parentCompany.parentCountry,
//                         handleParentCountryChange,
//                         'Country',
//                         errors.parentCountry
//                       )}
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentZipCode"
//                         label="Postcode / Zip code"
//                         value={parentCompany.parentZipCode}
//                         onChange={handleParentChange}
//                         error={!!errors.parentZipCode}
//                         helperText={errors.parentZipCode}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         select
//                         name="parentCurrency"
//                         label="Currency"
//                         value={parentCompany.parentCurrency}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCurrency}
//                         helperText={errors.parentCurrency}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {currencies.map(currency => (
//                           <MenuItem key={currency} value={currency}>{currency}</MenuItem>
//                         ))}
//                       </TextField>
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTurnoverLastYear"
//                         label="Turnover last year"
//                         value={parentCompany.parentTurnoverLastYear}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTurnoverLastYear}
//                         helperText={errors.parentTurnoverLastYear}
//                         placeholder="e.g., 10000000"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentIncorporationDate"
//                         label="Incorporation Date"
//                         type="date"
//                         value={parentCompany.parentIncorporationDate}
//                         onChange={handleParentChange}
//                         error={!!errors.parentIncorporationDate}
//                         helperText={errors.parentIncorporationDate}
//                         InputLabelProps={{ shrink: true }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTaxIdentificationNumber"
//                         label="VAT / Tax Identification number"
//                         value={parentCompany.parentTaxIdentificationNumber}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTaxIdentificationNumber}
//                         helperText={errors.parentTaxIdentificationNumber}
//                         placeholder="Parent VAT/Tax ID"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={parentCompany.parentStockExchange}
//                               onChange={handleParentChange}
//                               name="parentStockExchange"
//                             />
//                           }
//                           label="Is parent company publicly listed on a stock exchange?"
//                         />
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={parentCompany.parentNotForProfit}
//                               onChange={handleParentChange}
//                               name="parentNotForProfit"
//                             />
//                           }
//                           label="Is parent company a registered 'not-for-profit' organization?"
//                         />
//                       </Stack>
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             {/* Billing Address Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={billingDifferent}
//                     onChange={(e) => setBillingDifferent(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Is billing address different from registered address?
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if your billing address is different from the company's registered address
//               </Typography>

//               {billingDifferent && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#ff9800', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Billing Address
//                     </Typography>
//                   </Box>
//                   <Typography variant="caption" sx={{ color: 'error.main', mb: 2, display: 'block' }}>
//                     PO Boxes are not acceptable for onboarding
//                   </Typography>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="billingStreetAddress"
//                         label="Street address"
//                         value={billingAddress.billingStreetAddress}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingStreetAddress}
//                         helperText={errors.billingStreetAddress}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="billingAddress2"
//                         label="Address 2"
//                         value={billingAddress.billingAddress2}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingAddress2}
//                         helperText={errors.billingAddress2}
//                         placeholder="Apartment, suite, unit, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingCity"
//                         label="City"
//                         value={billingAddress.billingCity}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingCity}
//                         helperText={errors.billingCity}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingState"
//                         label="State / Province"
//                         value={billingAddress.billingState}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingState}
//                         helperText={errors.billingState}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       {renderCountryAutocomplete(
//                         'billing-country-select',
//                         billingAddress.billingCountry,
//                         handleBillingCountryChange,
//                         'Country',
//                         errors.billingCountry
//                       )}
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingPostCode"
//                         label="Postcode / Zip code"
//                         value={billingAddress.billingPostCode}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingPostCode}
//                         helperText={errors.billingPostCode}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             <Divider sx={{ my: 3 }} />

//             {/* Submit Button */}
//             <Button
//               type="submit"
//               fullWidth
//               variant="contained"
//               size="large"
//               disabled={loading}
//               sx={{
//                 py: 1.5,
//                 borderRadius: 2,
//                 textTransform: 'none',
//                 fontSize: '1rem',
//                 fontWeight: 600,
//                 boxShadow: 2,
//                 '&:hover': { boxShadow: 4 }
//               }}
//             >
//               {loading ? (
//                 <CircularProgress size={24} color="inherit" />
//               ) : (
//                 isEditMode ? 'Update Company Profile' : 'Create Company Profile'
//               )}
//             </Button>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default CompanyProfile



// incorporation date calculate ///////
// import React, { useState, useEffect } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import Autocomplete from '@mui/material/Autocomplete'
// import Paper from '@mui/material/Paper'
// import CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import Skeleton from '@mui/material/Skeleton'
// import toast, { Toaster } from 'react-hot-toast'

// // ** Data
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Endpoints
// import endpoints from 'src/configs/endpoints'

// // ** Axios Instance
// import axiosInstance from 'src/configs/axios'

// // ** Types
// interface CountryType {
//   name: string
//   code: string
//   dialCode?: string
//   label?: string
//   phone?: string
//   iso2?: string
// }

// interface ValidationErrors {
//   [key: string]: string
// }

// interface CompanyProfileProps {
//   onNext?: () => void
//   applicationId: string
// }

// const CompanyProfile = ({ onNext, applicationId }: CompanyProfileProps) => {
//   // Loading state
//   const [loading, setLoading] = useState<boolean>(false)
//   const [fetchingData, setFetchingData] = useState<boolean>(true)
//   const [error, setError] = useState<string | null>(null)
//   const [isEditMode, setIsEditMode] = useState<boolean>(false)
  
//   // Store parent company ID from backend if exists
//   const [parentCompanyId, setParentCompanyId] = useState<number>(0)

//   // Main company state
//   const [company, setCompany] = useState({
//     companyRegistrationNo: '',
//     legalCompanyName: '',
//     tradeName: '',
//     businessType: '',
//     otherBusinessType: '',
//     registeredBusinessEmail: '',
//     registeredStreetAddress: '',
//     address2: '',
//     city: '',
//     country: null as CountryType | null,
//     state: '',
//     zipCode: '',
//     phone: '',
//     currency: '',
//     turnoverLastYear: '',
//     incorporationDate: '',
//     taxIdentificationNumber: '',
//     notForProfit: false,
//     stockExchange: false,
//   })

//   // Parent company state
//   const [hasParentCompany, setHasParentCompany] = useState<boolean>(false)
//   const [parentCompany, setParentCompany] = useState({
//     parentLegalCompanyName: '',
//     parentCompanyRegistrationNo: '',
//     parentTradeName: '',
//     parentBusinessType: '',
//     parentOtherBusinessType: '',
//     parentRegisteredBusinessEmail: '',
//     parentRegisteredStreetAddress: '',
//     parentAddress2: '',
//     parentCity: '',
//     parentCountry: null as CountryType | null,
//     parentState: '',
//     parentZipCode: '',
//     parentPhone: '',
//     parentCurrency: '',
//     parentTurnoverLastYear: '',
//     parentIncorporationDate: '',
//     parentTaxIdentificationNumber: '',
//     parentNotForProfit: false,
//     parentStockExchange: false,
//   })

//   // Billing address state
//   const [billingDifferent, setBillingDifferent] = useState<boolean>(false)
//   const [billingAddress, setBillingAddress] = useState({
//     billingStreetAddress: '',
//     billingAddress2: '',
//     billingCity: '',
//     billingState: '',
//     billingCountry: null as CountryType | null,
//     billingPostCode: '',
//   })

//   // Validation errors
//   const [errors, setErrors] = useState<ValidationErrors>({})

//   // Helper function to find country object from country name
//   const findCountryByName = (countryName: string): CountryType | null => {
//     if (!countryName) return null
//     const found = countries.find(
//       c => c.name === countryName || c.label === countryName || c.name?.toLowerCase() === countryName?.toLowerCase()
//     )
//     return found || null
//   }

//   // Fetch existing application data
//   const fetchApplicationData = async () => {
//     if (!applicationId) {
//       console.log('No applicationId provided')
//       setFetchingData(false)
//       return
//     }

//     setFetchingData(true)
//     setError(null)
    
//     try {
//       const response = await axiosInstance.get(
//         `${endpoints.merchantApplication.getApplicationDetails}${applicationId}`
//       )
      
//       console.log('GET Response:', response.data)
      
//       // Check if response has companyProfile array
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         // Find the main company profile (where isparent is false or null)
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         // Find the parent company profile (where isparent is true)
//         const parentCompanyData = response.data.companyProfile.find((item: any) => item.isparent === true)
        
//         console.log('Main Company:', mainCompany)
//         console.log('Parent Company:', parentCompanyData)
        
//         if (mainCompany) {
//           console.log('Existing record found, prefilling data:', mainCompany)
//           setIsEditMode(true)
          
//           // Store parent company ID if exists
//           if (mainCompany.parentCompanyId && mainCompany.parentCompanyId > 0) {
//             setParentCompanyId(mainCompany.parentCompanyId)
//             console.log('Found existing parent company ID:', mainCompany.parentCompanyId)
//           } else {
//             setParentCompanyId(0)
//           }
          
//           prefillFormData(mainCompany, parentCompanyData)
//         } else {
//           console.log('No existing record found, will create new record on submit')
//           setIsEditMode(false)
//           setParentCompanyId(0)
//         }
//       } else {
//         console.log('No existing record found, will create new record on submit')
//         setIsEditMode(false)
//         setParentCompanyId(0)
//       }
//     } catch (err: any) {
//       console.error('Error fetching application data:', err)
//       if (err.response?.status === 404) {
//         console.log('No record found (404), will create new record on submit')
//         setIsEditMode(false)
//         setParentCompanyId(0)
//       } else {
//         toast.error('Failed to load data. Please try again.')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   // Prefill form with existing data
//   const prefillFormData = (mainData: any, parentData: any) => {
//     console.log('Prefilling form with main data:', mainData)
//     console.log('Prefilling form with parent data:', parentData)
    
//     // Prefill main company data
//     if (mainData.companyRegistrationNo) {
//       setCompany(prev => ({ ...prev, companyRegistrationNo: mainData.companyRegistrationNo }))
//     }
//     if (mainData.legalCompanyName) {
//       setCompany(prev => ({ ...prev, legalCompanyName: mainData.legalCompanyName }))
//     }
//     if (mainData.tradeName && mainData.tradeName !== '') {
//       setCompany(prev => ({ ...prev, tradeName: mainData.tradeName }))
//     }
//     if (mainData.businessType && mainData.businessType !== '') {
//       const validTypes = [
//         'SOLE_PROPRIETORSHIP',
//         'GENERAL_PARTNERSHIP',
//         'LIMITED_PARTNERSHIP',
//         'LIMITED_LIABILITY_PARTNERSHIP',
//         'C_CORPORATION',
//         'S_CORPORATION',
//         'BENEFIT_CORPORATION',
//         'LIMITED_LIABILITY_COMPANY',
//         'OTHER'
//       ]
//       if (validTypes.includes(mainData.businessType)) {
//         setCompany(prev => ({ ...prev, businessType: mainData.businessType }))
//       } else {
//         setCompany(prev => ({ ...prev, businessType: 'OTHER', otherBusinessType: mainData.businessType }))
//       }
//     }
//     if (mainData.registeredBusinessEmail) {
//       setCompany(prev => ({ ...prev, registeredBusinessEmail: mainData.registeredBusinessEmail }))
//     }
//     if (mainData.registeredStreetAddress) {
//       setCompany(prev => ({ ...prev, registeredStreetAddress: mainData.registeredStreetAddress }))
//     }
//     if (mainData.address2 && mainData.address2 !== '' && mainData.address2 !== 'NA') {
//       setCompany(prev => ({ ...prev, address2: mainData.address2 }))
//     }
//     if (mainData.city && mainData.city !== '' && mainData.city !== 'NA') {
//       setCompany(prev => ({ ...prev, city: mainData.city }))
//     }
//     if (mainData.country && mainData.country !== '' && mainData.country !== 'NA') {
//       const countryObj = findCountryByName(mainData.country)
//       setCompany(prev => ({ ...prev, country: countryObj }))
//     }
//     if (mainData.state && mainData.state !== '' && mainData.state !== 'NA') {
//       setCompany(prev => ({ ...prev, state: mainData.state }))
//     }
//     if (mainData.zipCode && mainData.zipCode !== '' && mainData.zipCode !== 'NA') {
//       setCompany(prev => ({ ...prev, zipCode: mainData.zipCode }))
//     }
//     if (mainData.phone) {
//       setCompany(prev => ({ ...prev, phone: mainData.phone }))
//     }
//     if (mainData.currency && mainData.currency !== '') {
//       setCompany(prev => ({ ...prev, currency: mainData.currency }))
//     }
//     if (mainData.turnoverLastYear && mainData.turnoverLastYear !== '') {
//       setCompany(prev => ({ ...prev, turnoverLastYear: mainData.turnoverLastYear }))
//     }
//     if (mainData.incorporationDate) {
//       setCompany(prev => ({ 
//         ...prev, 
//         incorporationDate: mainData.incorporationDate
//       }))
//     }
//     if (mainData.taxIdentificationNumber && mainData.taxIdentificationNumber !== '') {
//       setCompany(prev => ({ ...prev, taxIdentificationNumber: mainData.taxIdentificationNumber }))
//     }
//     if (mainData.notForProfit !== undefined) {
//       setCompany(prev => ({ ...prev, notForProfit: mainData.notForProfit }))
//     }
//     if (mainData.stockExchange !== undefined) {
//       setCompany(prev => ({ ...prev, stockExchange: mainData.stockExchange }))
//     }
    
//     // Parent company data - boolean value from main company
//     if (mainData.havingParentCompany !== undefined) {
//       setHasParentCompany(mainData.havingParentCompany === true || mainData.havingParentCompany === 'true')
//     }
    
//     // Prefill parent company details if parent data exists
//     if (parentData) {
//       if (parentData.legalCompanyName) {
//         setParentCompany(prev => ({ ...prev, parentLegalCompanyName: parentData.legalCompanyName }))
//       }
//       if (parentData.companyRegistrationNo) {
//         setParentCompany(prev => ({ ...prev, parentCompanyRegistrationNo: parentData.companyRegistrationNo }))
//       }
//       if (parentData.tradeName && parentData.tradeName !== '' && parentData.tradeName !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentTradeName: parentData.tradeName }))
//       }
//       if (parentData.businessType && parentData.businessType !== '') {
//         const validTypes = [
//           'SOLE_PROPRIETORSHIP',
//           'GENERAL_PARTNERSHIP',
//           'LIMITED_PARTNERSHIP',
//           'LIMITED_LIABILITY_PARTNERSHIP',
//           'C_CORPORATION',
//           'S_CORPORATION',
//           'BENEFIT_CORPORATION',
//           'LIMITED_LIABILITY_COMPANY',
//           'OTHER'
//         ]
//         if (validTypes.includes(parentData.businessType)) {
//           setParentCompany(prev => ({ ...prev, parentBusinessType: parentData.businessType }))
//         } else {
//           setParentCompany(prev => ({ ...prev, parentBusinessType: 'OTHER', parentOtherBusinessType: parentData.businessType }))
//         }
//       }
//       if (parentData.registeredBusinessEmail) {
//         setParentCompany(prev => ({ ...prev, parentRegisteredBusinessEmail: parentData.registeredBusinessEmail }))
//       }
//       if (parentData.registeredStreetAddress) {
//         setParentCompany(prev => ({ ...prev, parentRegisteredStreetAddress: parentData.registeredStreetAddress }))
//       }
//       if (parentData.address2 && parentData.address2 !== '' && parentData.address2 !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentAddress2: parentData.address2 }))
//       }
//       if (parentData.city && parentData.city !== '' && parentData.city !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentCity: parentData.city }))
//       }
//       if (parentData.country && parentData.country !== '' && parentData.country !== 'NA') {
//         const countryObj = findCountryByName(parentData.country)
//         setParentCompany(prev => ({ ...prev, parentCountry: countryObj }))
//       }
//       if (parentData.state && parentData.state !== '' && parentData.state !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentState: parentData.state }))
//       }
//       if (parentData.zipCode && parentData.zipCode !== '' && parentData.zipCode !== 'NA') {
//         setParentCompany(prev => ({ ...prev, parentZipCode: parentData.zipCode }))
//       }
//       if (parentData.phone) {
//         setParentCompany(prev => ({ ...prev, parentPhone: parentData.phone }))
//       }
//       if (parentData.currency && parentData.currency !== '') {
//         setParentCompany(prev => ({ ...prev, parentCurrency: parentData.currency }))
//       }
//       if (parentData.turnoverLastYear && parentData.turnoverLastYear !== '') {
//         setParentCompany(prev => ({ ...prev, parentTurnoverLastYear: parentData.turnoverLastYear }))
//       }
//       if (parentData.incorporationDate) {
//         setParentCompany(prev => ({ ...prev, parentIncorporationDate: parentData.incorporationDate }))
//       }
//       if (parentData.taxIdentificationNumber && parentData.taxIdentificationNumber !== '') {
//         setParentCompany(prev => ({ ...prev, parentTaxIdentificationNumber: parentData.taxIdentificationNumber }))
//       }
//       if (parentData.notForProfit !== undefined) {
//         setParentCompany(prev => ({ ...prev, parentNotForProfit: parentData.notForProfit }))
//       }
//       if (parentData.stockExchange !== undefined) {
//         setParentCompany(prev => ({ ...prev, parentStockExchange: parentData.stockExchange }))
//       }
//     }
    
//     // Billing data from main company
//     if (mainData.billingRegisteredAddress !== undefined) {
//       setBillingDifferent(mainData.billingRegisteredAddress === true || mainData.billingRegisteredAddress === 'true')
//     }
    
//     if (mainData.billingRegisteredAddress === true) {
//       if (mainData.billingStreetAddress && mainData.billingStreetAddress !== '' && mainData.billingStreetAddress !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingStreetAddress: mainData.billingStreetAddress }))
//       }
//       if (mainData.billingAddress2 && mainData.billingAddress2 !== '' && mainData.billingAddress2 !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingAddress2: mainData.billingAddress2 }))
//       }
//       if (mainData.billingCity && mainData.billingCity !== '' && mainData.billingCity !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingCity: mainData.billingCity }))
//       }
//       if (mainData.billingState && mainData.billingState !== '' && mainData.billingState !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingState: mainData.billingState }))
//       }
//       if (mainData.billingCountry && mainData.billingCountry !== '' && mainData.billingCountry !== 'NA') {
//         const countryObj = findCountryByName(mainData.billingCountry)
//         setBillingAddress(prev => ({ ...prev, billingCountry: countryObj }))
//       }
//       if (mainData.billingPostCode && mainData.billingPostCode !== '' && mainData.billingPostCode !== 'NA') {
//         setBillingAddress(prev => ({ ...prev, billingPostCode: mainData.billingPostCode }))
//       }
//     }
//   }

//   // Load data on component mount
//   useEffect(() => {
//     if (applicationId) {
//       fetchApplicationData()
//     }
//   }, [applicationId])

//   // Handle main company input changes
//   const handleCompanyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
    
//     setCompany(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
    
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle main company autocomplete (country)
//   const handleCompanyCountryChange = (newValue: CountryType | null) => {
//     setCompany(prev => ({ ...prev, country: newValue }))
//     if (errors.country) {
//       setErrors(prev => ({ ...prev, country: '' }))
//     }
//   }

//   // Handle parent company input changes
//   const handleParentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setParentCompany(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }))
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle parent company autocomplete (country)
//   const handleParentCountryChange = (newValue: CountryType | null) => {
//     setParentCompany(prev => ({ ...prev, parentCountry: newValue }))
//     if (errors.parentCountry) {
//       setErrors(prev => ({ ...prev, parentCountry: '' }))
//     }
//   }

//   // Handle billing address input changes
//   const handleBillingChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value } = e.target
//     setBillingAddress(prev => ({ ...prev, [name]: value }))
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   // Handle billing address autocomplete (country)
//   const handleBillingCountryChange = (newValue: CountryType | null) => {
//     setBillingAddress(prev => ({ ...prev, billingCountry: newValue }))
//     if (errors.billingCountry) {
//       setErrors(prev => ({ ...prev, billingCountry: '' }))
//     }
//   }

//   // Build request body for API
//   const buildRequestBody = () => {
//     // Determine the business type to send
//     let businessTypeToSend = company.businessType
//     if (company.businessType === 'OTHER' && company.otherBusinessType) {
//       businessTypeToSend = company.otherBusinessType
//     }

//     const requestBody: any = {
//       applicationId: parseInt(applicationId),
      
//       // Company fields - always include with proper values
//       companyRegistrationNo: company.companyRegistrationNo || '',
//       legalCompanyName: company.legalCompanyName || '',
//       tradeName: company.tradeName || '',
//       businessType: businessTypeToSend || '',
//       registeredBusinessEmail: company.registeredBusinessEmail || '',
//       registeredStreetAddress: company.registeredStreetAddress || '',
//       address2: company.address2 || '',
//       city: company.city || '',
//       country: company.country?.name || company.country?.label || '',
//       state: company.state || '',
//       zipCode: company.zipCode || '',
//       phone: company.phone || '',
//       currency: company.currency || '',
//       turnoverLastYear: company.turnoverLastYear || '',
//       incorporationDate: company.incorporationDate || '',
//       taxIdentificationNumber: company.taxIdentificationNumber || '',
//       notForProfit: company.notForProfit,
//       stockExchange: company.stockExchange,
      
//       // Parent company flags - send as boolean true/false
//       havingParentCompany: hasParentCompany,
//       billingRegisteredAddress: billingDifferent,
//     }

//     // Handle parent company based on hasParentCompany flag
//     if (hasParentCompany === true) {
//       // Determine parent business type
//       let parentBusinessTypeToSend = parentCompany.parentBusinessType
//       if (parentCompany.parentBusinessType === 'OTHER' && parentCompany.parentOtherBusinessType) {
//         parentBusinessTypeToSend = parentCompany.parentOtherBusinessType
//       }

//       // Include all parent fields when parent company exists
//       requestBody.parentLegalCompanyName = parentCompany.parentLegalCompanyName || ''
//       requestBody.parentCompanyRegistrationNo = parentCompany.parentCompanyRegistrationNo || ''
//       requestBody.parentTradeName = parentCompany.parentTradeName || ''
//       requestBody.parentBusinessType = parentBusinessTypeToSend || ''
//       requestBody.parentRegisteredBusinessEmail = parentCompany.parentRegisteredBusinessEmail || ''
//       requestBody.parentRegisteredStreetAddress = parentCompany.parentRegisteredStreetAddress || ''
//       requestBody.parentAddress2 = parentCompany.parentAddress2 || ''
//       requestBody.parentCity = parentCompany.parentCity || ''
//       requestBody.parentCountry = parentCompany.parentCountry?.name || parentCompany.parentCountry?.label || ''
//       requestBody.parentState = parentCompany.parentState || ''
//       requestBody.parentZipCode = parentCompany.parentZipCode || ''
//       requestBody.parentPhone = parentCompany.parentPhone || ''
//       requestBody.parentCurrency = parentCompany.parentCurrency || ''
//       requestBody.parentTurnoverLastYear = parentCompany.parentTurnoverLastYear || ''
//       requestBody.parentIncorporationDate = parentCompany.parentIncorporationDate || ''
//       requestBody.parentTaxIdentificationNumber = parentCompany.parentTaxIdentificationNumber || ''
//       requestBody.parentNotForProfit = parentCompany.parentNotForProfit
//       requestBody.parentStockExchange = parentCompany.parentStockExchange
      
//       // Only send parentCompanyId if we're editing an EXISTING parent company
//       if (parentCompanyId > 0) {
//         requestBody.parentCompanyId = parentCompanyId
//         console.log('Updating existing parent company with ID:', parentCompanyId)
//       } else {
//         console.log('Creating new parent company (no ID sent)')
//       }
//     } else {
//       // When no parent company, send empty strings for all parent fields
//       requestBody.parentLegalCompanyName = ''
//       requestBody.parentCompanyRegistrationNo = ''
//       requestBody.parentTradeName = ''
//       requestBody.parentBusinessType = ''
//       requestBody.parentRegisteredBusinessEmail = ''
//       requestBody.parentRegisteredStreetAddress = ''
//       requestBody.parentAddress2 = ''
//       requestBody.parentCity = ''
//       requestBody.parentCountry = ''
//       requestBody.parentState = ''
//       requestBody.parentZipCode = ''
//       requestBody.parentPhone = ''
//       requestBody.parentCurrency = ''
//       requestBody.parentTurnoverLastYear = ''
//       requestBody.parentIncorporationDate = ''
//       requestBody.parentTaxIdentificationNumber = ''
//       requestBody.parentNotForProfit = false
//       requestBody.parentStockExchange = false
//       // When removing parent company, send 0 to delete/remove it
//       if (isEditMode) {
//         requestBody.parentCompanyId = 0
//         console.log('Removing parent company, sending ID 0')
//       }
//     }

//     // Handle billing address based on billingDifferent flag
//     if (billingDifferent === true) {
//       requestBody.billingStreetAddress = billingAddress.billingStreetAddress || ''
//       requestBody.billingAddress2 = billingAddress.billingAddress2 || ''
//       requestBody.billingCity = billingAddress.billingCity || ''
//       requestBody.billingState = billingAddress.billingState || ''
//       requestBody.billingCountry = billingAddress.billingCountry?.name || billingAddress.billingCountry?.label || ''
//       requestBody.billingPostCode = billingAddress.billingPostCode || ''
//     } else {
//       requestBody.billingStreetAddress = ''
//       requestBody.billingAddress2 = ''
//       requestBody.billingCity = ''
//       requestBody.billingState = ''
//       requestBody.billingCountry = ''
//       requestBody.billingPostCode = ''
//     }

//     return requestBody
//   }

//   // Handle form submission - Create or Update based on mode
//   const handleSubmit = async (e: React.FormEvent) => {
//     e.preventDefault()
    
//     setLoading(true)
//     setError(null)

//     const requestBody = buildRequestBody()
    
//     console.log('=== SUBMIT DEBUG INFO ===')
//     console.log('Submit Mode:', isEditMode ? 'UPDATE (PUT)' : 'CREATE (POST)')
//     console.log('Application ID:', applicationId)
//     console.log('Has Parent Company:', hasParentCompany)
//     console.log('Parent Company ID in state:', parentCompanyId)
//     console.log('Is Edit Mode:', isEditMode)
//     console.log('Request Body:', JSON.stringify(requestBody, null, 2))

//     try {
//       let response
      
//       if (isEditMode) {
//         // UPDATE existing record using PUT
//         response = await axiosInstance.put(
//           `${endpoints.merchantApplication.companyProfile}${applicationId}`,
//           requestBody
//         )
//         console.log('PUT Response:', response.data)
//         toast.success('Company profile updated successfully!')
        
//         setTimeout(() => {
//           fetchApplicationData()
//         }, 1000)
//       } else {
//         // CREATE new record using POST
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.companyProfile,
//           requestBody
//         )
//         console.log('POST Response:', response.data)
//         toast.success('Company profile created successfully!')
//         setIsEditMode(true)
        
//         if (response.data && response.data.parentCompanyId) {
//           setParentCompanyId(response.data.parentCompanyId)
//           console.log('New parent company created with ID:', response.data.parentCompanyId)
//         }
//       }

//       if (response.data) {
//         setTimeout(() => {
//           fetchApplicationData()
//         }, 1000)
        
//         if (onNext) {
//           setTimeout(() => {
//             onNext()
//           }, 1500)
//         }
//       }
//     } catch (err: any) {
//       console.error('API Error:', err)
//       console.error('Error Response:', err.response?.data)
      
//       let errorMessage = isEditMode 
//         ? 'Failed to update company profile. Please try again.'
//         : 'Failed to create company profile. Please try again.'
      
//       if (err.response?.data) {
//         if (err.response.data.content) {
//           if (typeof err.response.data.content === 'object') {
//             const errorObj = err.response.data.content
//             const errorMessages = Object.entries(errorObj).map(([key, value]) => {
//               return `${key}: ${value}`
//             }).join(', ')
//             errorMessage = errorMessages
//             toast.error(errorMessages)
            
//             const fieldErrors: ValidationErrors = {}
//             Object.entries(errorObj).forEach(([key, value]) => {
//               fieldErrors[key] = Array.isArray(value) ? value[0] : String(value)
//             })
//             setErrors(fieldErrors)
//           } else {
//             errorMessage = err.response.data.content
//             toast.error(errorMessage)
//           }
//         } else if (err.response.data.message) {
//           errorMessage = err.response.data.message
//           toast.error(errorMessage)
//         } else {
//           toast.error(errorMessage)
//         }
//       } else {
//         toast.error(errorMessage)
//       }
      
//       setError(errorMessage)
//     } finally {
//       setLoading(false)
//     }
//   }

//   // Business types - Updated list
//   const businessTypes = [
//     'SOLE_PROPRIETORSHIP',
//     'GENERAL_PARTNERSHIP',
//     'LIMITED_PARTNERSHIP',
//     'LIMITED_LIABILITY_PARTNERSHIP',
//     'C_CORPORATION',
//     'S_CORPORATION',
//     'BENEFIT_CORPORATION',
//     'LIMITED_LIABILITY_COMPANY',
//     'OTHER'
//   ]

//   const businessTypeLabels: Record<string, string> = {
//     SOLE_PROPRIETORSHIP: 'Sole Proprietorship',
//     GENERAL_PARTNERSHIP: 'General Partnership',
//     LIMITED_PARTNERSHIP: 'Limited Partnership',
//     LIMITED_LIABILITY_PARTNERSHIP: 'Limited Liability Partnership (LLP)',
//     C_CORPORATION: 'C Corporation',
//     S_CORPORATION: 'S Corporation',
//     BENEFIT_CORPORATION: 'Benefit Corporation',
//     LIMITED_LIABILITY_COMPANY: 'Limited Liability Company (LLC)',
//     OTHER: 'Other'
//   }

//   const currencies = ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CHF', 'CNY', 'INR', 'BRL', 'ZAR', 'NZD', 'SGD']

//   // Helper to render Autocomplete with flag
//   const renderCountryAutocomplete = (
//     id: string,
//     value: CountryType | null,
//     onChange: (value: CountryType | null) => void,
//     label: string,
//     error?: string,
//     required?: boolean
//   ) => (
//     <Autocomplete
//       id={id}
//       options={countries}
//       autoHighlight
//       getOptionLabel={(option) => {
//         if (!option) return ''
//         if (typeof option === 'string') return option
//         const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//         const name = option.name || option.label || ''
//         return dialCode ? `${name} (+${dialCode})` : name
//       }}
//       value={value}
//       onChange={(event, newValue) => onChange(newValue)}
//       renderOption={(props, option) => {
//         const dialCode = option.dialCode || option.phone || option.phoneCode || ''
//         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={label}
//           placeholder="Select country"
//           required={required}
//           error={!!error}
//           helperText={error}
//           InputProps={{
//             ...params.InputProps,
//             startAdornment: value && (value.code || value.iso2) && (
//               <img
//                 src={`https://flagcdn.com/w20/${(value.code || value.iso2)?.toLowerCase()}.png`}
//                 style={{ marginLeft: '8px', marginRight: '8px', width: '24px', height: '18px' }}
//                 width="24"
//                 height="18"
//                 alt="flag"
//               />
//             ),
//           }}
//         />
//       )}
//     />
//   )

//   if (fetchingData) {
//     return (
//       <Box sx={{ p: 6 }}>
//         <Card sx={{ p: 6 }}>
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={400} />
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={200} />
//         </Card>
//       </Box>
//     )
//   }

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       {/* <Toaster position="top-right" /> */}
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>
//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Applying Company Details
//               </Typography>
//               <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                 Application ID: <strong>{applicationId}</strong>
//                 {isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#4caf50' }}>
//                     (Editing existing record)
//                   </span>
//                 )}
//                 {!isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#ff9800' }}>
//                     (Creating new record)
//                   </span>
//                 )}
//               </Typography>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Info Alert */}
//             <Alert severity="info" sx={{ mb: 3 }}>
//               <Typography variant="body2">
//                 {isEditMode 
//                   ? 'You can edit any field. All changes will be updated via PUT request.'
//                   : 'Fill the form to create a new record. You can edit later.'}
//               </Typography>
//             </Alert>

//             {/* Error Alert */}
//             {error && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )}

//             {/* Main Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                 <Box sx={{ width: 4, height: 24, bgcolor: 'primary.main', borderRadius: 2 }} />
//                 <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                   Company Information
//                 </Typography>
//               </Box>
              
//               <Grid container spacing={3}>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="companyRegistrationNo"
//                     label="Company registration number"
//                     value={company.companyRegistrationNo}
//                     onChange={handleCompanyChange}
//                     error={!!errors.companyRegistrationNo}
//                     helperText={errors.companyRegistrationNo}
//                     placeholder="Enter registration number"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="legalCompanyName"
//                     label="Legal name of company"
//                     value={company.legalCompanyName}
//                     onChange={handleCompanyChange}
//                     error={!!errors.legalCompanyName}
//                     helperText={errors.legalCompanyName}
//                     placeholder="Legal name"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="tradeName"
//                     label="Registered DBA/trade name"
//                     value={company.tradeName}
//                     onChange={handleCompanyChange}
//                     error={!!errors.tradeName}
//                     helperText={errors.tradeName}
//                     placeholder="Doing business as (if any)"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="businessType"
//                     label="Type of business"
//                     value={company.businessType}
//                     onChange={handleCompanyChange}
//                     error={!!errors.businessType}
//                     helperText={errors.businessType}
//                   >
//                     <MenuItem value="" disabled>-- Select Business Type --</MenuItem>
//                     {businessTypes.map(type => (
//                       <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 {company.businessType === 'OTHER' && (
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       name="otherBusinessType"
//                       label="Please specify your business type"
//                       value={company.otherBusinessType}
//                       onChange={handleCompanyChange}
//                       placeholder="Enter your business type"
//                       error={!!errors.otherBusinessType}
//                       helperText={errors.otherBusinessType}
//                     />
//                   </Grid>
//                 )}
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="registeredBusinessEmail"
//                     label="Business Email"
//                     type="email"
//                     value={company.registeredBusinessEmail}
//                     onChange={handleCompanyChange}
//                     error={!!errors.registeredBusinessEmail}
//                     helperText={errors.registeredBusinessEmail}
//                     placeholder="contact@company.com"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="phone"
//                     label="Telephone number"
//                     value={company.phone}
//                     onChange={handleCompanyChange}
//                     error={!!errors.phone}
//                     helperText={errors.phone}
//                     placeholder="+1 234 567 8900"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="registeredStreetAddress"
//                     label="Address 1"
//                     value={company.registeredStreetAddress}
//                     onChange={handleCompanyChange}
//                     error={!!errors.registeredStreetAddress}
//                     helperText={errors.registeredStreetAddress || "PO Boxes are not acceptable for onboarding"}
//                     placeholder="Street address"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <TextField
//                     fullWidth
//                     name="address2"
//                     label="Address 2"
//                     value={company.address2}
//                     onChange={handleCompanyChange}
//                     error={!!errors.address2}
//                     helperText={errors.address2}
//                     placeholder="Apartment, suite, unit, etc."
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="city"
//                     label="City"
//                     value={company.city}
//                     onChange={handleCompanyChange}
//                     error={!!errors.city}
//                     helperText={errors.city}
//                     placeholder="City"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="state"
//                     label="State / Province"
//                     value={company.state}
//                     onChange={handleCompanyChange}
//                     error={!!errors.state}
//                     helperText={errors.state}
//                     placeholder="State"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   {renderCountryAutocomplete(
//                     'company-country-select',
//                     company.country,
//                     handleCompanyCountryChange,
//                     'Country',
//                     errors.country
//                   )}
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="zipCode"
//                     label="Postcode / Zip code"
//                     value={company.zipCode}
//                     onChange={handleCompanyChange}
//                     error={!!errors.zipCode}
//                     helperText={errors.zipCode}
//                     placeholder="Postcode"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     select
//                     name="currency"
//                     label="Currency"
//                     value={company.currency}
//                     onChange={handleCompanyChange}
//                     error={!!errors.currency}
//                     helperText={errors.currency}
//                   >
//                     <MenuItem value="" disabled>-- Select Currency --</MenuItem>
//                     {currencies.map(currency => (
//                       <MenuItem key={currency} value={currency}>{currency}</MenuItem>
//                     ))}
//                   </TextField>
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="turnoverLastYear"
//                     label="Turnover last year (Annual Sales)"
//                     value={company.turnoverLastYear}
//                     onChange={handleCompanyChange}
//                     error={!!errors.turnoverLastYear}
//                     helperText={errors.turnoverLastYear}
//                     placeholder="e.g., 1000000"
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="incorporationDate"
//                     label="Incorporation Date"
//                     type="date"
//                     value={company.incorporationDate}
//                     onChange={handleCompanyChange}
//                     error={!!errors.incorporationDate}
//                     helperText={errors.incorporationDate}
//                     InputLabelProps={{ shrink: true }}
//                   />
//                 </Grid>
//                 <Grid item xs={12} sm={6}>
//                   <TextField
//                     fullWidth
//                     name="taxIdentificationNumber"
//                     label="VAT / Tax Identification number"
//                     value={company.taxIdentificationNumber}
//                     onChange={handleCompanyChange}
//                     error={!!errors.taxIdentificationNumber}
//                     helperText={errors.taxIdentificationNumber}
//                     placeholder="VAT/Tax ID"
//                   />
//                 </Grid>
//                 <Grid item xs={12}>
//                   <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.stockExchange}
//                           onChange={handleCompanyChange}
//                           name="stockExchange"
//                         />
//                       }
//                       label="Is company publicly listed on a stock exchange?"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={company.notForProfit}
//                           onChange={handleCompanyChange}
//                           name="notForProfit"
//                         />
//                       }
//                       label="Is company a registered 'not-for-profit' organization?"
//                     />
//                   </Stack>
//                 </Grid>
//               </Grid>
//             </Paper>

//             {/* Parent Company Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={hasParentCompany}
//                     onChange={(e) => setHasParentCompany(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Has Parent Company
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if this company is owned or controlled by another entity
//               </Typography>

//               {hasParentCompany && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#4caf50', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Parent Company Details
//                     </Typography>
//                   </Box>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentCompanyRegistrationNo"
//                         label="Company registration number"
//                         value={parentCompany.parentCompanyRegistrationNo}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCompanyRegistrationNo}
//                         helperText={errors.parentCompanyRegistrationNo}
//                         placeholder="Parent registration number"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentLegalCompanyName"
//                         label="Legal name of company"
//                         value={parentCompany.parentLegalCompanyName}
//                         onChange={handleParentChange}
//                         error={!!errors.parentLegalCompanyName}
//                         helperText={errors.parentLegalCompanyName}
//                         placeholder="Parent legal name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTradeName"
//                         label="Registered DBA/trade name"
//                         value={parentCompany.parentTradeName}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTradeName}
//                         helperText={errors.parentTradeName}
//                         placeholder="Parent DBA name"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         select
//                         name="parentBusinessType"
//                         label="Type of business"
//                         value={parentCompany.parentBusinessType}
//                         onChange={handleParentChange}
//                         error={!!errors.parentBusinessType}
//                         helperText={errors.parentBusinessType}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {businessTypes.map(type => (
//                           <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                         ))}
//                       </TextField>
//                     </Grid>
//                     {parentCompany.parentBusinessType === 'OTHER' && (
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           name="parentOtherBusinessType"
//                           label="Please specify parent business type"
//                           value={parentCompany.parentOtherBusinessType}
//                           onChange={handleParentChange}
//                           placeholder="Enter parent business type"
//                           error={!!errors.parentOtherBusinessType}
//                           helperText={errors.parentOtherBusinessType}
//                         />
//                       </Grid>
//                     )}
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentRegisteredBusinessEmail"
//                         label="Business Email"
//                         type="email"
//                         value={parentCompany.parentRegisteredBusinessEmail}
//                         onChange={handleParentChange}
//                         error={!!errors.parentRegisteredBusinessEmail}
//                         helperText={errors.parentRegisteredBusinessEmail}
//                         placeholder="parent@company.com"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentPhone"
//                         label="Telephone number"
//                         value={parentCompany.parentPhone}
//                         onChange={handleParentChange}
//                         error={!!errors.parentPhone}
//                         helperText={errors.parentPhone}
//                         placeholder="Parent phone number"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="parentRegisteredStreetAddress"
//                         label="Address 1"
//                         value={parentCompany.parentRegisteredStreetAddress}
//                         onChange={handleParentChange}
//                         error={!!errors.parentRegisteredStreetAddress}
//                         helperText={errors.parentRegisteredStreetAddress}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="parentAddress2"
//                         label="Address 2"
//                         value={parentCompany.parentAddress2}
//                         onChange={handleParentChange}
//                         error={!!errors.parentAddress2}
//                         helperText={errors.parentAddress2}
//                         placeholder="Apartment, suite, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentCity"
//                         label="City"
//                         value={parentCompany.parentCity}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCity}
//                         helperText={errors.parentCity}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentState"
//                         label="State / Province"
//                         value={parentCompany.parentState}
//                         onChange={handleParentChange}
//                         error={!!errors.parentState}
//                         helperText={errors.parentState}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       {renderCountryAutocomplete(
//                         'parent-country-select',
//                         parentCompany.parentCountry,
//                         handleParentCountryChange,
//                         'Country',
//                         errors.parentCountry
//                       )}
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentZipCode"
//                         label="Postcode / Zip code"
//                         value={parentCompany.parentZipCode}
//                         onChange={handleParentChange}
//                         error={!!errors.parentZipCode}
//                         helperText={errors.parentZipCode}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         select
//                         name="parentCurrency"
//                         label="Currency"
//                         value={parentCompany.parentCurrency}
//                         onChange={handleParentChange}
//                         error={!!errors.parentCurrency}
//                         helperText={errors.parentCurrency}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {currencies.map(currency => (
//                           <MenuItem key={currency} value={currency}>{currency}</MenuItem>
//                         ))}
//                       </TextField>
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTurnoverLastYear"
//                         label="Turnover last year"
//                         value={parentCompany.parentTurnoverLastYear}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTurnoverLastYear}
//                         helperText={errors.parentTurnoverLastYear}
//                         placeholder="e.g., 10000000"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentIncorporationDate"
//                         label="Incorporation Date"
//                         type="date"
//                         value={parentCompany.parentIncorporationDate}
//                         onChange={handleParentChange}
//                         error={!!errors.parentIncorporationDate}
//                         helperText={errors.parentIncorporationDate}
//                         InputLabelProps={{ shrink: true }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="parentTaxIdentificationNumber"
//                         label="VAT / Tax Identification number"
//                         value={parentCompany.parentTaxIdentificationNumber}
//                         onChange={handleParentChange}
//                         error={!!errors.parentTaxIdentificationNumber}
//                         helperText={errors.parentTaxIdentificationNumber}
//                         placeholder="Parent VAT/Tax ID"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={parentCompany.parentStockExchange}
//                               onChange={handleParentChange}
//                               name="parentStockExchange"
//                             />
//                           }
//                           label="Is parent company publicly listed on a stock exchange?"
//                         />
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={parentCompany.parentNotForProfit}
//                               onChange={handleParentChange}
//                               name="parentNotForProfit"
//                             />
//                           }
//                           label="Is parent company a registered 'not-for-profit' organization?"
//                         />
//                       </Stack>
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             {/* Billing Address Section */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={billingDifferent}
//                     onChange={(e) => setBillingDifferent(e.target.checked)}
//                     color="primary"
//                   />
//                 }
//                 label={
//                   <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
//                     Is billing address different from registered address?
//                   </Typography>
//                 }
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if your billing address is different from the company's registered address
//               </Typography>

//               {billingDifferent && (
//                 <Box sx={{ mt: 3 }}>
//                   <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//                     <Box sx={{ width: 4, height: 24, bgcolor: '#ff9800', borderRadius: 2 }} />
//                     <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>
//                       Billing Address
//                     </Typography>
//                   </Box>
//                   <Typography variant="caption" sx={{ color: 'error.main', mb: 2, display: 'block' }}>
//                     PO Boxes are not acceptable for onboarding
//                   </Typography>
//                   <Grid container spacing={3}>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="billingStreetAddress"
//                         label="Street address"
//                         value={billingAddress.billingStreetAddress}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingStreetAddress}
//                         helperText={errors.billingStreetAddress}
//                         placeholder="Street address"
//                       />
//                     </Grid>
//                     <Grid item xs={12}>
//                       <TextField
//                         fullWidth
//                         name="billingAddress2"
//                         label="Address 2"
//                         value={billingAddress.billingAddress2}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingAddress2}
//                         helperText={errors.billingAddress2}
//                         placeholder="Apartment, suite, unit, etc."
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingCity"
//                         label="City"
//                         value={billingAddress.billingCity}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingCity}
//                         helperText={errors.billingCity}
//                         placeholder="City"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingState"
//                         label="State / Province"
//                         value={billingAddress.billingState}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingState}
//                         helperText={errors.billingState}
//                         placeholder="State"
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       {renderCountryAutocomplete(
//                         'billing-country-select',
//                         billingAddress.billingCountry,
//                         handleBillingCountryChange,
//                         'Country',
//                         errors.billingCountry
//                       )}
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <TextField
//                         fullWidth
//                         name="billingPostCode"
//                         label="Postcode / Zip code"
//                         value={billingAddress.billingPostCode}
//                         onChange={handleBillingChange}
//                         error={!!errors.billingPostCode}
//                         helperText={errors.billingPostCode}
//                         placeholder="Postcode"
//                       />
//                     </Grid>
//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             {/* Submit Button */}
//             <Button
//               type="submit"
//               fullWidth
//               variant="contained"
//               size="large"
//               disabled={loading}
//               sx={{
//                 py: 1.5,
//                 borderRadius: 2,
//                 textTransform: 'none',
//                 fontSize: '1rem',
//                 fontWeight: 600,
//                 boxShadow: 2,
//                 '&:hover': { boxShadow: 4 }
//               }}
//             >
//               {loading ? (
//                 <CircularProgress size={24} color="inherit" />
//               ) : (
//                 isEditMode ? 'Update Company Profile' : 'Create Company Profile'
//               )}
//             </Button>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default CompanyProfile


// empty filled show /////////////////////////////////////////
// import React, { useState, useEffect } from 'react'

// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import Autocomplete from '@mui/material/Autocomplete'
// import Paper from '@mui/material/Paper'
// import CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import Skeleton from '@mui/material/Skeleton'
// import Chip from '@mui/material/Chip'
// import toast, { Toaster } from 'react-hot-toast'

// // ** Data
// import { countries } from 'src/@fake-db/autocomplete'

// // ** Endpoints
// import endpoints from 'src/configs/endpoints'

// // ** Axios Instance
// import axiosInstance from 'src/configs/axios'

// // ** Types
// interface CountryType {
//   name: string
//   code: string
//   dialCode?: string
//   label?: string
//   phone?: string
//   iso2?: string
// }

// interface CurrencyType {
//   uid?: string | number
//   currencyName?: string
//   currencyCode?: string
//   code?: string
//   name?: string
//   value?: string
//   label?: string
// }

// interface ValidationErrors {
//   [key: string]: string
// }

// interface CompanyProfileProps {
//   onNext?: () => void
//   applicationId: string
// }

// // ─── Live Validators ──────────────────────────────────────────────────────────
// // Every error message includes the example so user sees it only when needed.

// const validateEmail = (email: string): string => {
//   if (!email) return ''
//   if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
//     return 'Please enter a valid email address. e.g. contact@company.com'
//   return ''
// }

// const validatePhone = (phone: string): string => {
//   if (!phone) return ''
//   if (!/^[+]?[\d\s\-().]{7,20}$/.test(phone.trim()))
//     return 'Please enter a valid phone number. e.g. +1 234 567 8900 or 022-2345-6789'
//   return ''
// }

// const validateZip = (zip: string): string => {
//   if (!zip) return ''
//   const trimmed = zip.trim()
//   if (trimmed.length < 3)
//     return 'Postcode must be at least 3 characters. e.g. 400001 or SW1A 1AA'
//   if (trimmed.length > 10)
//     return 'Postcode must not exceed 10 characters. e.g. 400001 or SW1A 1AA'
//   if (!/^[A-Za-z0-9\s\-]+$/.test(trimmed))
//     return 'Postcode can only contain letters, numbers, spaces and hyphens. e.g. 400001 or SW1A 1AA'
//   return ''
// }

// const validateTurnover = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
//     return 'Please enter a valid numeric amount. e.g. 1000000 or 250000.50 (no commas or symbols)'
//   if (parseFloat(val) <= 0)
//     return 'Turnover must be greater than 0. e.g. 1000000 or 250000.50'
//   return ''
// }

// const validateRegistrationNo = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 3)
//     return 'Registration number must be at least 3 characters. e.g. U12345MH2001PTC123456 or 12-3456789'
//   if (!/^[A-Za-z0-9\s\-/]+$/.test(val.trim()))
//     return 'Only letters, numbers, hyphens and slashes are allowed. e.g. U12345MH2001PTC123456 or CIN/2020/01'
//   return ''
// }

// const validateCompanyName = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 2)
//     return 'Name must be at least 2 characters. e.g. Acme Corp or O\'Brien & Sons Ltd'
//   if (val.trim().length > 200)
//     return 'Name must not exceed 200 characters.'
//   if (/[<>/@#\\]/.test(val))
//     return 'Special characters like < > @ # / \\ are not allowed. e.g. Acme Corp or Tech-X Ltd'
//   return ''
// }

// const validateTaxId = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 3)
//     return 'Tax ID must be at least 3 characters. e.g. 27AAACR5055K1ZV or GB123456789'
//   if (!/^[A-Za-z0-9\-]+$/.test(val.trim()))
//     return 'Only letters, digits and hyphens are allowed. e.g. 27AAACR5055K1ZV or GB123456789'
//   return ''
// }

// const validateCityOrState = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 2)
//     return 'Must be at least 2 characters. e.g. Mumbai or New York'
//   if (val.trim().length > 100)
//     return 'Must not exceed 100 characters.'
//   if (!/^[A-Za-zÀ-ÿ\s'\-]+$/.test(val.trim()))
//     return 'Only letters, spaces, hyphens and apostrophes are allowed. e.g. New York or Île-de-France'
//   return ''
// }

// const validateAddress = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 5)
//     return 'Address must be at least 5 characters. e.g. 123 Main Street, Bandra West'
//   if (val.trim().length > 300)
//     return 'Address must not exceed 300 characters.'
//   if (/\bP\.?\s*O\.?\s*Box\b/i.test(val))
//     return 'PO Boxes are not acceptable for onboarding. e.g. please use a physical street address like 123 Main Street'
//   return ''
// }

// const validateAddress2 = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length > 200)
//     return 'Must not exceed 200 characters. e.g. Apt 4B, Suite 100 or Floor 3'
//   if (/\bP\.?\s*O\.?\s*Box\b/i.test(val))
//     return 'PO Boxes are not acceptable for onboarding. e.g. please use a unit or floor number like Suite 100'
//   return ''
// }

// const validateOtherBusinessType = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 2)
//     return 'Please provide at least 2 characters. e.g. Cooperative or Trust'
//   if (val.trim().length > 100)
//     return 'Must not exceed 100 characters. e.g. Cooperative or Foundation'
//   if (/[<>@#\\]/.test(val))
//     return 'Special characters like < > @ # \\ are not allowed. e.g. Cooperative or Foundation'
//   return ''
// }

// const validateIncorporationDate = (val: string): string => {
//   if (!val) return ''
//   const date = new Date(val)
//   if (isNaN(date.getTime()))
//     return 'Please enter a valid date. e.g. 2010-06-15'
//   const today = new Date()
//   today.setHours(0, 0, 0, 0)
//   if (date > today)
//     return 'Incorporation date cannot be in the future. e.g. 2010-06-15'
//   if (date.getFullYear() < 1800)
//     return 'Please enter a realistic incorporation date. e.g. 1995-03-20'
//   return ''
// }

// // ─── Helper: "Not Provided" Chip ─────────────────────────────────────────────────
// const NotAddedChip = () => (
//   <Chip
//     label="Not Provided"
//     size="small"
//     sx={{
//       height: 20,
//       fontSize: '0.625rem',
//       fontWeight: 500,
//       backgroundColor: '#fff3e0',
//       color: '#e65100',
//       border: '1px solid',
//       borderColor: '#ffb74d',
//       '& .MuiChip-label': { px: 1, py: 0.25 },
//     }}
//   />
// )

// // ─── Helper: Green Tick Chip ──────────────────────────────────────────────────
// const GreenTickChip = () => (
//   <Chip
//     label="✓"
//     size="small"
//     sx={{
//       height: 20,
//       minWidth: 20,
//       fontSize: '0.75rem',
//       fontWeight: 600,
//       backgroundColor: '#e8f5e9',
//       color: '#2e7d32',
//       borderRadius: '50%',
//       '& .MuiChip-label': { px: 0.75, display: 'flex', alignItems: 'center', justifyContent: 'center' },
//     }}
//   />
// )

// // ─── Field Label with status indicator ───────────────────────────────────────
// const FieldLabel = ({
//   label,
//   value,
//   isEditMode,
// }: {
//   label: string
//   value: string | null | undefined
//   isEditMode: boolean
// }) => {
//   const filled = value !== null && value !== undefined && String(value).trim() !== ''
//   return (
//     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
//       <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary' }}>
//         {label}
//       </Typography>
//       {isEditMode && filled && <GreenTickChip />}
//       {isEditMode && !filled && <NotAddedChip />}
//     </Box>
//   )
// }

// // ─── SmartTextField ───────────────────────────────────────────────────────────
// const SmartTextField = ({
//   label,
//   name,
//   value,
//   onChange,
//   error,
//   helperText,
//   placeholder,
//   type,
//   select,
//   children,
//   InputLabelProps,
//   multiline,
//   rows,
//   isEditMode,
//   disabled,
// }: any) => {
//   const filled = value !== null && value !== undefined && String(value).trim() !== ''
//   return (
//     <Box>
//       <FieldLabel label={label} value={value} isEditMode={isEditMode} />
//       <TextField
//         fullWidth
//         name={name}
//         value={value}
//         onChange={onChange}
//         error={!!error}
//         helperText={helperText}
//         placeholder={placeholder}
//         type={type}
//         select={select}
//         InputLabelProps={InputLabelProps}
//         multiline={multiline}
//         rows={rows}
//         disabled={disabled}
//         sx={{
//           '& .MuiOutlinedInput-root': {
//             '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
//             '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
//           },
//         }}
//       >
//         {children}
//       </TextField>
//     </Box>
//   )
// }

// // ─── Main Component ───────────────────────────────────────────────────────────
// const CompanyProfile = ({ onNext, applicationId }: CompanyProfileProps) => {
//   const [loading, setLoading] = useState<boolean>(false)
//   const [fetchingData, setFetchingData] = useState<boolean>(true)
//   const [fetchingCurrencies, setFetchingCurrencies] = useState<boolean>(true)
//   const [error, setError] = useState<string | null>(null)
//   const [isEditMode, setIsEditMode] = useState<boolean>(false)
//   const [parentCompanyId, setParentCompanyId] = useState<number>(0)
//   const [currencyList, setCurrencyList] = useState<CurrencyType[]>([])
//   const [currencyError, setCurrencyError] = useState<string | null>(null)

//   const [company, setCompany] = useState({
//     companyRegistrationNo: '',
//     legalCompanyName: '',
//     tradeName: '',
//     businessType: '',
//     otherBusinessType: '',
//     registeredBusinessEmail: '',
//     registeredStreetAddress: '',
//     address2: '',
//     city: '',
//     country: null as CountryType | null,
//     state: '',
//     zipCode: '',
//     phone: '',
//     currency: '',
//     turnoverLastYear: '',
//     incorporationDate: '',
//     taxIdentificationNumber: '',
//     notForProfit: false,
//     stockExchange: false,
//   })

//   const [hasParentCompany, setHasParentCompany] = useState<boolean>(false)
//   const [parentCompany, setParentCompany] = useState({
//     parentLegalCompanyName: '',
//     parentCompanyRegistrationNo: '',
//     parentTradeName: '',
//     parentBusinessType: '',
//     parentOtherBusinessType: '',
//     parentRegisteredBusinessEmail: '',
//     parentRegisteredStreetAddress: '',
//     parentAddress2: '',
//     parentCity: '',
//     parentCountry: null as CountryType | null,
//     parentState: '',
//     parentZipCode: '',
//     parentPhone: '',
//     parentCurrency: '',
//     parentTurnoverLastYear: '',
//     parentIncorporationDate: '',
//     parentTaxIdentificationNumber: '',
//     parentNotForProfit: false,
//     parentStockExchange: false,
//   })

//   const [billingDifferent, setBillingDifferent] = useState<boolean>(false)
//   const [billingAddress, setBillingAddress] = useState({
//     billingStreetAddress: '',
//     billingAddress2: '',
//     billingCity: '',
//     billingState: '',
//     billingCountry: null as CountryType | null,
//     billingPostCode: '',
//   })

//   const [errors, setErrors] = useState<ValidationErrors>({})

//   // ─── Business types ──────────────────────────────────────────────────────────
//   const businessTypes = [
//     'SOLE_PROPRIETORSHIP',
//     'GENERAL_PARTNERSHIP',
//     'LIMITED_PARTNERSHIP',
//     'LIMITED_LIABILITY_PARTNERSHIP',
//     'C_CORPORATION',
//     'S_CORPORATION',
//     'BENEFIT_CORPORATION',
//     'LIMITED_LIABILITY_COMPANY',
//     'OTHER',
//   ]

//   const businessTypeLabels: Record<string, string> = {
//     SOLE_PROPRIETORSHIP: 'Sole Proprietorship',
//     GENERAL_PARTNERSHIP: 'General Partnership',
//     LIMITED_PARTNERSHIP: 'Limited Partnership',
//     LIMITED_LIABILITY_PARTNERSHIP: 'Limited Liability Partnership (LLP)',
//     C_CORPORATION: 'C Corporation',
//     S_CORPORATION: 'S Corporation',
//     BENEFIT_CORPORATION: 'Benefit Corporation',
//     LIMITED_LIABILITY_COMPANY: 'Limited Liability Company (LLC)',
//     OTHER: 'Other',
//   }

//   // ─── Fetch currencies ─────────────────────────────────────────────────────
//   const fetchCurrencies = async () => {
//     setFetchingCurrencies(true)
//     setCurrencyError(null)
//     try {
//       const response = await axiosInstance.get(endpoints.merchantApplication.currency)
//       if (response.data) {
//         let currencies: CurrencyType[] = []
//         if (Array.isArray(response.data)) {
//           currencies = response.data
//         } else if (response.data.data && Array.isArray(response.data.data)) {
//           currencies = response.data.data
//         } else if (response.data.content && Array.isArray(response.data.content)) {
//           currencies = response.data.content
//         } else if (response.data.items && Array.isArray(response.data.items)) {
//           currencies = response.data.items
//         } else if (typeof response.data === 'object' && response.data !== null) {
//           if (response.data.currencyCode || response.data.currencyName) {
//             currencies = [response.data]
//           } else {
//             const arrayValue = Object.values(response.data).find(val => Array.isArray(val))
//             if (arrayValue) currencies = arrayValue as CurrencyType[]
//             else { setCurrencyList([]); setCurrencyError('No currency data available from API'); return }
//           }
//         }
//         if (currencies.length > 0) setCurrencyList(currencies)
//         else { setCurrencyList([]); setCurrencyError('No currency data available from API') }
//       } else { setCurrencyList([]); setCurrencyError('No currency data available from API') }
//     } catch (err: any) {
//       console.error('Error fetching currencies:', err)
//       setCurrencyError('Failed to load currency list from API')
//       setCurrencyList([])
//       toast.error('Failed to load currency list from API')
//     } finally {
//       setFetchingCurrencies(false)
//     }
//   }

//   const findCountryByName = (countryName: string): CountryType | null => {
//     if (!countryName) return null
//     return countries.find(c =>
//       c.name === countryName || c.label === countryName ||
//       c.name?.toLowerCase() === countryName?.toLowerCase()
//     ) || null
//   }

//   const normalizeBusinessType = (raw: string): { type: string; other: string } => {
//     if (!raw) return { type: '', other: '' }
//     const valid = [
//       'SOLE_PROPRIETORSHIP', 'GENERAL_PARTNERSHIP', 'LIMITED_PARTNERSHIP',
//       'LIMITED_LIABILITY_PARTNERSHIP', 'C_CORPORATION', 'S_CORPORATION',
//       'BENEFIT_CORPORATION', 'LIMITED_LIABILITY_COMPANY', 'OTHER',
//     ]
//     if (valid.includes(raw)) return { type: raw, other: '' }
//     return { type: 'OTHER', other: raw }
//   }

//   const fetchApplicationData = async () => {
//     if (!applicationId) { setFetchingData(false); return }
//     setFetchingData(true)
//     setError(null)
//     try {
//       const response = await axiosInstance.get(`${endpoints.merchantApplication.getApplicationDetails}${applicationId}`)
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         const parentCompanyData = response.data.companyProfile.find((item: any) => item.isparent === true)
//         if (mainCompany) {
//           setIsEditMode(true)
//           setParentCompanyId(mainCompany.parentCompanyId > 0 ? mainCompany.parentCompanyId : 0)
//           prefillFormData(mainCompany, parentCompanyData)
//         } else { setIsEditMode(false); setParentCompanyId(0) }
//       } else { setIsEditMode(false); setParentCompanyId(0) }
//     } catch (err: any) {
//       if (err.response?.status === 404) { setIsEditMode(false); setParentCompanyId(0) }
//       else toast.error('Failed to load data. Please try again.')
//     } finally { setFetchingData(false) }
//   }

//   const prefillFormData = (mainData: any, parentData: any) => {
//     const safeStr = (v: any) => (v && v !== 'NA' ? String(v) : '')
//     const bizMain = normalizeBusinessType(safeStr(mainData.businessType))
//     setCompany({
//       companyRegistrationNo: safeStr(mainData.companyRegistrationNo),
//       legalCompanyName: safeStr(mainData.legalCompanyName),
//       tradeName: safeStr(mainData.tradeName),
//       businessType: bizMain.type,
//       otherBusinessType: bizMain.other,
//       registeredBusinessEmail: safeStr(mainData.registeredBusinessEmail),
//       registeredStreetAddress: safeStr(mainData.registeredStreetAddress),
//       address2: safeStr(mainData.address2),
//       city: safeStr(mainData.city),
//       country: mainData.country ? findCountryByName(safeStr(mainData.country)) : null,
//       state: safeStr(mainData.state),
//       zipCode: safeStr(mainData.zipCode),
//       phone: safeStr(mainData.phone),
//       currency: safeStr(mainData.currency),
//       turnoverLastYear: safeStr(mainData.turnoverLastYear),
//       incorporationDate: safeStr(mainData.incorporationDate),
//       taxIdentificationNumber: safeStr(mainData.taxIdentificationNumber),
//       notForProfit: mainData.notForProfit === true || mainData.notForProfit === 'true',
//       stockExchange: mainData.stockExchange === true || mainData.stockExchange === 'true',
//     })
//     setHasParentCompany(mainData.havingParentCompany === true || mainData.havingParentCompany === 'true')
//     if (parentData) {
//       const bizParent = normalizeBusinessType(safeStr(parentData.businessType))
//       setParentCompany({
//         parentCompanyRegistrationNo: safeStr(parentData.companyRegistrationNo),
//         parentLegalCompanyName: safeStr(parentData.legalCompanyName),
//         parentTradeName: safeStr(parentData.tradeName),
//         parentBusinessType: bizParent.type,
//         parentOtherBusinessType: bizParent.other,
//         parentRegisteredBusinessEmail: safeStr(parentData.registeredBusinessEmail),
//         parentRegisteredStreetAddress: safeStr(parentData.registeredStreetAddress),
//         parentAddress2: safeStr(parentData.address2),
//         parentCity: safeStr(parentData.city),
//         parentCountry: parentData.country ? findCountryByName(safeStr(parentData.country)) : null,
//         parentState: safeStr(parentData.state),
//         parentZipCode: safeStr(parentData.zipCode),
//         parentPhone: safeStr(parentData.phone),
//         parentCurrency: safeStr(parentData.currency),
//         parentTurnoverLastYear: safeStr(parentData.turnoverLastYear),
//         parentIncorporationDate: safeStr(parentData.incorporationDate),
//         parentTaxIdentificationNumber: safeStr(parentData.taxIdentificationNumber),
//         parentNotForProfit: parentData.notForProfit === true || parentData.notForProfit === 'true',
//         parentStockExchange: parentData.stockExchange === true || parentData.stockExchange === 'true',
//       })
//     }
//     setBillingDifferent(mainData.billingRegisteredAddress === true || mainData.billingRegisteredAddress === 'true')
//     if (mainData.billingRegisteredAddress === true) {
//       setBillingAddress({
//         billingStreetAddress: safeStr(mainData.billingStreetAddress),
//         billingAddress2: safeStr(mainData.billingAddress2),
//         billingCity: safeStr(mainData.billingCity),
//         billingState: safeStr(mainData.billingState),
//         billingCountry: mainData.billingCountry ? findCountryByName(safeStr(mainData.billingCountry)) : null,
//         billingPostCode: safeStr(mainData.billingPostCode),
//       })
//     }
//   }

//   useEffect(() => {
//     if (applicationId) fetchApplicationData()
//     fetchCurrencies()
//   }, [applicationId])

//   // ─── Live validation router ───────────────────────────────────────────────
//   const runLiveValidation = (name: string, value: string): string => {
//     switch (name) {
//       case 'registeredBusinessEmail':
//       case 'parentRegisteredBusinessEmail':
//         return validateEmail(value)

//       case 'phone':
//       case 'parentPhone':
//         return validatePhone(value)

//       case 'zipCode':
//       case 'parentZipCode':
//       case 'billingPostCode':
//         return validateZip(value)

//       case 'turnoverLastYear':
//       case 'parentTurnoverLastYear':
//         return validateTurnover(value)

//       case 'companyRegistrationNo':
//       case 'parentCompanyRegistrationNo':
//         return validateRegistrationNo(value)

//       case 'legalCompanyName':
//       case 'tradeName':
//       case 'parentLegalCompanyName':
//       case 'parentTradeName':
//         return validateCompanyName(value)

//       case 'taxIdentificationNumber':
//       case 'parentTaxIdentificationNumber':
//         return validateTaxId(value)

//       case 'city':
//       case 'parentCity':
//       case 'billingCity':
//         return validateCityOrState(value)

//       case 'state':
//       case 'parentState':
//       case 'billingState':
//         return validateCityOrState(value)

//       case 'registeredStreetAddress':
//       case 'parentRegisteredStreetAddress':
//       case 'billingStreetAddress':
//         return validateAddress(value)

//       case 'address2':
//       case 'parentAddress2':
//       case 'billingAddress2':
//         return validateAddress2(value)

//       case 'otherBusinessType':
//       case 'parentOtherBusinessType':
//         return validateOtherBusinessType(value)

//       case 'incorporationDate':
//       case 'parentIncorporationDate':
//         return validateIncorporationDate(value)

//       default:
//         return ''
//     }
//   }

//   // ─── Handlers ─────────────────────────────────────────────────────────────
//   const handleCompanyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     const newVal = type === 'checkbox' ? checked : value
//     setCompany(prev => ({ ...prev, [name]: newVal }))
//     if (type !== 'checkbox') {
//       setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
//     }
//   }

//   const handleCompanyCountryChange = (newValue: CountryType | null) => {
//     setCompany(prev => ({ ...prev, country: newValue }))
//     if (errors.country) setErrors(prev => ({ ...prev, country: '' }))
//   }

//   const handleParentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     const newVal = type === 'checkbox' ? checked : value
//     setParentCompany(prev => ({ ...prev, [name]: newVal }))
//     if (type !== 'checkbox') {
//       setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
//     }
//   }

//   const handleParentCountryChange = (newValue: CountryType | null) => {
//     setParentCompany(prev => ({ ...prev, parentCountry: newValue }))
//     if (errors.parentCountry) setErrors(prev => ({ ...prev, parentCountry: '' }))
//   }

//   const handleBillingChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value } = e.target
//     setBillingAddress(prev => ({ ...prev, [name]: value }))
//     setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
//   }

//   const handleBillingCountryChange = (newValue: CountryType | null) => {
//     setBillingAddress(prev => ({ ...prev, billingCountry: newValue }))
//     if (errors.billingCountry) setErrors(prev => ({ ...prev, billingCountry: '' }))
//   }

//   // ─── Block submit if any live error exists ────────────────────────────────
//   const hasAnyError = Object.values(errors).some(msg => msg !== '')

//   // ─── Build request body ───────────────────────────────────────────────────
//   const buildRequestBody = () => {
//     let businessTypeToSend = company.businessType
//     if (company.businessType === 'OTHER' && company.otherBusinessType) {
//       businessTypeToSend = company.otherBusinessType
//     }
//     const requestBody: any = {
//       applicationId: parseInt(applicationId),
//       companyRegistrationNo: company.companyRegistrationNo || '',
//       legalCompanyName: company.legalCompanyName || '',
//       tradeName: company.tradeName || '',
//       businessType: businessTypeToSend || '',
//       registeredBusinessEmail: company.registeredBusinessEmail || '',
//       registeredStreetAddress: company.registeredStreetAddress || '',
//       address2: company.address2 || '',
//       city: company.city || '',
//       country: company.country?.name || company.country?.label || '',
//       state: company.state || '',
//       zipCode: company.zipCode || '',
//       phone: company.phone || '',
//       currency: company.currency || '',
//       turnoverLastYear: company.turnoverLastYear || '',
//       incorporationDate: company.incorporationDate || '',
//       taxIdentificationNumber: company.taxIdentificationNumber || '',
//       notForProfit: company.notForProfit,
//       stockExchange: company.stockExchange,
//       havingParentCompany: hasParentCompany,
//       billingRegisteredAddress: billingDifferent,
//     }

//     if (hasParentCompany) {
//       let parentBusinessTypeToSend = parentCompany.parentBusinessType
//       if (parentCompany.parentBusinessType === 'OTHER' && parentCompany.parentOtherBusinessType) {
//         parentBusinessTypeToSend = parentCompany.parentOtherBusinessType
//       }
//       Object.assign(requestBody, {
//         parentLegalCompanyName: parentCompany.parentLegalCompanyName || '',
//         parentCompanyRegistrationNo: parentCompany.parentCompanyRegistrationNo || '',
//         parentTradeName: parentCompany.parentTradeName || '',
//         parentBusinessType: parentBusinessTypeToSend || '',
//         parentRegisteredBusinessEmail: parentCompany.parentRegisteredBusinessEmail || '',
//         parentRegisteredStreetAddress: parentCompany.parentRegisteredStreetAddress || '',
//         parentAddress2: parentCompany.parentAddress2 || '',
//         parentCity: parentCompany.parentCity || '',
//         parentCountry: parentCompany.parentCountry?.name || parentCompany.parentCountry?.label || '',
//         parentState: parentCompany.parentState || '',
//         parentZipCode: parentCompany.parentZipCode || '',
//         parentPhone: parentCompany.parentPhone || '',
//         parentCurrency: parentCompany.parentCurrency || '',
//         parentTurnoverLastYear: parentCompany.parentTurnoverLastYear || '',
//         parentIncorporationDate: parentCompany.parentIncorporationDate || '',
//         parentTaxIdentificationNumber: parentCompany.parentTaxIdentificationNumber || '',
//         parentNotForProfit: parentCompany.parentNotForProfit,
//         parentStockExchange: parentCompany.parentStockExchange,
//       })
//       if (parentCompanyId > 0) requestBody.parentCompanyId = parentCompanyId
//     } else {
//       Object.assign(requestBody, {
//         parentLegalCompanyName: '', parentCompanyRegistrationNo: '', parentTradeName: '',
//         parentBusinessType: '', parentRegisteredBusinessEmail: '', parentRegisteredStreetAddress: '',
//         parentAddress2: '', parentCity: '', parentCountry: '', parentState: '',
//         parentZipCode: '', parentPhone: '', parentCurrency: '', parentTurnoverLastYear: '',
//         parentIncorporationDate: '', parentTaxIdentificationNumber: '',
//         parentNotForProfit: false, parentStockExchange: false,
//       })
//       if (isEditMode) requestBody.parentCompanyId = 0
//     }

//     if (billingDifferent) {
//       Object.assign(requestBody, {
//         billingStreetAddress: billingAddress.billingStreetAddress || '',
//         billingAddress2: billingAddress.billingAddress2 || '',
//         billingCity: billingAddress.billingCity || '',
//         billingState: billingAddress.billingState || '',
//         billingCountry: billingAddress.billingCountry?.name || billingAddress.billingCountry?.label || '',
//         billingPostCode: billingAddress.billingPostCode || '',
//       })
//     } else {
//       Object.assign(requestBody, {
//         billingStreetAddress: '', billingAddress2: '', billingCity: '',
//         billingState: '', billingCountry: '', billingPostCode: '',
//       })
//     }
//     return requestBody
//   }

//   // ─── Submit ───────────────────────────────────────────────────────────────
//   const handleSubmit = async (e: React.FormEvent) => {
//     e.preventDefault()
//     if (hasAnyError) {
//       toast.error('Please fix the validation errors before submitting.')
//       return
//     }
//     setLoading(true)
//     setError(null)
//     const requestBody = buildRequestBody()
//     try {
//       let response
//       if (isEditMode) {
//         response = await axiosInstance.put(`${endpoints.merchantApplication.companyProfile}${applicationId}`, requestBody)
//         toast.success('Company profile updated successfully!')
//         setTimeout(() => fetchApplicationData(), 1000)
//       } else {
//         response = await axiosInstance.post(endpoints.merchantApplication.companyProfile, requestBody)
//         toast.success('Company profile created successfully!')
//         setIsEditMode(true)
//         if (response.data?.parentCompanyId) setParentCompanyId(response.data.parentCompanyId)
//       }
//       if (response.data) {
//         setTimeout(() => fetchApplicationData(), 1000)
//         if (onNext) setTimeout(() => onNext(), 1500)
//       }
//     } catch (err: any) {
//       let errorMessage = isEditMode
//         ? 'Failed to update company profile. Please try again.'
//         : 'Failed to create company profile. Please try again.'
//       if (err.response?.data) {
//         if (err.response.data.content) {
//           if (typeof err.response.data.content === 'object') {
//             const errorMessages = Object.entries(err.response.data.content).map(([k, v]) => `${k}: ${v}`).join(', ')
//             errorMessage = errorMessages
//             toast.error(errorMessages)
//           } else { errorMessage = err.response.data.content; toast.error(errorMessage) }
//         } else if (err.response.data.message) { errorMessage = err.response.data.message; toast.error(errorMessage) }
//         else toast.error(errorMessage)
//       } else toast.error(errorMessage)
//       setError(errorMessage)
//     } finally { setLoading(false) }
//   }

//   // ─── Country Autocomplete ─────────────────────────────────────────────────
//   const renderCountryAutocomplete = (
//     id: string,
//     value: CountryType | null,
//     onChange: (value: CountryType | null) => void,
//     label: string,
//     error?: string
//   ) => {
//     const filled = value !== null && value !== undefined
//     return (
//       <Grid item xs={12} sm={6}>
//         <Box>
//           <FieldLabel label={label} value={filled ? 'filled' : ''} isEditMode={isEditMode} />
//           <Autocomplete
//             id={id}
//             options={countries}
//             autoHighlight
//             getOptionLabel={(option) => {
//               if (!option) return ''
//               if (typeof option === 'string') return option
//               const dialCode = option.dialCode || option.phone || ''
//               const name = option.name || option.label || ''
//               return dialCode ? `${name} (+${dialCode})` : name
//             }}
//             value={value}
//             onChange={(event, newValue) => onChange(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}
//                 placeholder="Select country"
//                 error={!!error}
//                 helperText={error}
//                 sx={{
//                   '& .MuiOutlinedInput-root': {
//                     '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
//                     '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
//                   },
//                 }}
//               />
//             )}
//           />
//         </Box>
//       </Grid>
//     )
//   }

//   // ─── Currency select ──────────────────────────────────────────────────────
//   const renderSelectField = (
//     name: string,
//     label: string,
//     value: string,
//     onChange: (e: React.ChangeEvent<HTMLInputElement>) => void,
//     options: { value: string; label: string }[],
//     errorMsg?: string,
//     loadingCur?: boolean
//   ) => {
//     const filled = value !== null && value !== undefined && String(value).trim() !== ''
//     return (
//       <Grid item xs={12} sm={6}>
//         <Box>
//           <FieldLabel label={label} value={value} isEditMode={isEditMode} />
//           <TextField
//             fullWidth select name={name} value={value} onChange={onChange}
//             error={!!errorMsg}
//             helperText={errorMsg || (loadingCur ? 'Loading currencies...' : '')}
//             disabled={loadingCur}
//             sx={{
//               '& .MuiOutlinedInput-root': {
//                 '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
//                 '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
//               },
//             }}
//           >
//             <MenuItem value="" disabled>{loadingCur ? 'Loading...' : '-- Select --'}</MenuItem>
//             {options.map(opt => <MenuItem key={opt.value} value={opt.value}>{opt.label}</MenuItem>)}
//           </TextField>
//         </Box>
//       </Grid>
//     )
//   }

//   // ─── Skeleton ─────────────────────────────────────────────────────────────
//   if (fetchingData) {
//     return (
//       <Box sx={{ p: 6 }}>
//         <Card sx={{ p: 6 }}>
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={400} />
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={200} />
//         </Card>
//       </Box>
//     )
//   }

//   // ─── Section header ───────────────────────────────────────────────────────
//   const SectionHeader = ({ color, title }: { color: string; title: string }) => (
//     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
//       <Box sx={{ width: 4, height: 24, bgcolor: color, borderRadius: 2 }} />
//       <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>{title}</Typography>
//     </Box>
//   )

//   const currencyOptions = currencyList.map(currency => {
//     let value = '', label = ''
//     if (typeof currency === 'object' && currency !== null) {
//       value = currency.currencyCode || currency.code || currency.value || currency.uid?.toString() || ''
//       const name = currency.currencyName || currency.name || currency.label || ''
//       label = value && name ? `${value} - ${name}` : value || name || 'Unknown Currency'
//       if (!value) value = 'UNKNOWN'
//     } else if (typeof currency === 'string') { value = currency; label = currency }
//     else { value = ''; label = 'Unknown' }
//     return { value, label }
//   })

//   // ─── Date field helper ────────────────────────────────────────────────────
//   const renderDateField = (
//     name: string,
//     label: string,
//     value: string,
//     onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
//   ) => (
//     <Grid item xs={12} sm={6}>
//       <Box>
//         <FieldLabel label={label} value={value} isEditMode={isEditMode} />
//         <TextField
//           fullWidth
//           name={name}
//           type="date"
//           value={value}
//           onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
//             onChange(e)
//             setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, e.target.value) }))
//           }}
//           error={!!errors[name]}
//           helperText={errors[name]}
//           InputLabelProps={{ shrink: true }}
//           inputProps={{ max: new Date().toISOString().split('T')[0] }}
//           sx={{
//             '& .MuiOutlinedInput-root': {
//               '& fieldset': { borderColor: isEditMode && value ? '#A5D6A7' : undefined },
//             },
//           }}
//         />
//       </Box>
//     </Grid>
//   )

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>

//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Applying Company Details
//               </Typography>
//               <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
//                 <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                   Application ID: <strong>{applicationId}</strong>
//                 </Typography>
//                 <Chip
//                   label={isEditMode ? 'Editing Existing Record' : 'Creating New Record'}
//                   size="small"
//                   sx={{
//                     backgroundColor: isEditMode ? '#e8f5e9' : '#fff3e0',
//                     color: isEditMode ? '#2e7d32' : '#e65100',
//                     fontWeight: 500,
//                   }}
//                 />
//               </Box>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Info Alert */}
//             <Alert severity="info" sx={{ mb: 3 }}>
//               <Typography variant="body2">
//                 {isEditMode
//                   ? 'You can edit any field. Green ✓ indicates filled fields, orange "Not Provided" indicates missing information.'
//                   : 'Fill the form to create a new record.'}
//               </Typography>
//             </Alert>

//             {/* Validation error banner */}
//             {/* {hasAnyError && (
//               <Alert severity="warning" sx={{ mb: 3 }}>
//                 Some fields have invalid values. Please review and correct them before saving.
//               </Alert>
//             )} */}
// {/* 
//             {currencyError && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setCurrencyError(null)}>
//                 {currencyError}. Please contact support.
//               </Alert>
//             )}
//             {error && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )} */}

//             {/* ── Main Company Section ── */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <SectionHeader color="primary.main" title="Company Information" />
//               <Grid container spacing={3}>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Company Registration Number"
//                     name="companyRegistrationNo"
//                     value={company.companyRegistrationNo}
//                     onChange={handleCompanyChange}
//                     error={errors.companyRegistrationNo}
//                     helperText={errors.companyRegistrationNo}
//                     placeholder="Enter registration number"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Legal Name of Company"
//                     name="legalCompanyName"
//                     value={company.legalCompanyName}
//                     onChange={handleCompanyChange}
//                     error={errors.legalCompanyName}
//                     helperText={errors.legalCompanyName}
//                     placeholder="Legal name"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Registered DBA / Trade Name"
//                     name="tradeName"
//                     value={company.tradeName}
//                     onChange={handleCompanyChange}
//                     error={errors.tradeName}
//                     helperText={errors.tradeName}
//                     placeholder="Doing business as (if any)"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Type of Business"
//                     name="businessType"
//                     value={company.businessType}
//                     onChange={handleCompanyChange}
//                     error={errors.businessType}
//                     helperText={errors.businessType}
//                     placeholder="-- Select Business Type --"
//                     select
//                     isEditMode={isEditMode}
//                   >
//                     <MenuItem value="" disabled>-- Select Business Type --</MenuItem>
//                     {businessTypes.map(type => (
//                       <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                     ))}
//                   </SmartTextField>
//                 </Grid>

//                 {company.businessType === 'OTHER' && (
//                   <Grid item xs={12} sm={6}>
//                     <SmartTextField
//                       label="Please Specify Your Business Type"
//                       name="otherBusinessType"
//                       value={company.otherBusinessType}
//                       onChange={handleCompanyChange}
//                       error={errors.otherBusinessType}
//                       helperText={errors.otherBusinessType}
//                       placeholder="Enter your business type"
//                       isEditMode={isEditMode}
//                     />
//                   </Grid>
//                 )}

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Business Email"
//                     name="registeredBusinessEmail"
//                     value={company.registeredBusinessEmail}
//                     onChange={handleCompanyChange}
//                     error={errors.registeredBusinessEmail}
//                     helperText={errors.registeredBusinessEmail}
//                     placeholder="contact@company.com"
//                     type="email"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Telephone Number"
//                     name="phone"
//                     value={company.phone}
//                     onChange={handleCompanyChange}
//                     error={errors.phone}
//                     helperText={errors.phone}
//                     placeholder="+1 234 567 8900"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartTextField
//                     label="Address 1"
//                     name="registeredStreetAddress"
//                     value={company.registeredStreetAddress}
//                     onChange={handleCompanyChange}
//                     error={errors.registeredStreetAddress}
//                     helperText={errors.registeredStreetAddress}
//                     placeholder="Street address"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartTextField
//                     label="Address 2"
//                     name="address2"
//                     value={company.address2}
//                     onChange={handleCompanyChange}
//                     error={errors.address2}
//                     helperText={errors.address2}
//                     placeholder="Apartment, suite, unit, etc."
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="City"
//                     name="city"
//                     value={company.city}
//                     onChange={handleCompanyChange}
//                     error={errors.city}
//                     helperText={errors.city}
//                     placeholder="City"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="State / Province"
//                     name="state"
//                     value={company.state}
//                     onChange={handleCompanyChange}
//                     error={errors.state}
//                     helperText={errors.state}
//                     placeholder="State"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 {renderCountryAutocomplete('company-country-select', company.country, handleCompanyCountryChange, 'Country', errors.country)}

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Postcode / Zip Code"
//                     name="zipCode"
//                     value={company.zipCode}
//                     onChange={handleCompanyChange}
//                     error={errors.zipCode}
//                     helperText={errors.zipCode}
//                     placeholder="Postcode"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 {renderSelectField('currency', 'Currency', company.currency, handleCompanyChange, currencyOptions, errors.currency, fetchingCurrencies)}

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Turnover Last Year (Annual Sales)"
//                     name="turnoverLastYear"
//                     value={company.turnoverLastYear}
//                     onChange={handleCompanyChange}
//                     error={errors.turnoverLastYear}
//                     helperText={errors.turnoverLastYear}
//                     placeholder="e.g., 1000000"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 {renderDateField('incorporationDate', 'Incorporation Date', company.incorporationDate, handleCompanyChange)}

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="VAT / Tax Identification Number"
//                     name="taxIdentificationNumber"
//                     value={company.taxIdentificationNumber}
//                     onChange={handleCompanyChange}
//                     error={errors.taxIdentificationNumber}
//                     helperText={errors.taxIdentificationNumber}
//                     placeholder="VAT/Tax ID"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={company.stockExchange} onChange={handleCompanyChange} name="stockExchange" />}
//                       label="Is company publicly listed on a stock exchange?"
//                     />
//                     <FormControlLabel
//                       control={<Checkbox checked={company.notForProfit} onChange={handleCompanyChange} name="notForProfit" />}
//                       label="Is company a registered 'not-for-profit' organization?"
//                     />
//                   </Stack>
//                 </Grid>

//               </Grid>
//             </Paper>

//             {/* ── Parent Company Section ── */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={<Switch checked={hasParentCompany} onChange={(e) => setHasParentCompany(e.target.checked)} color="primary" />}
//                 label={<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>Has Parent Company</Typography>}
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if this company is owned or controlled by another entity
//               </Typography>

//               {hasParentCompany && (
//                 <Box sx={{ mt: 3 }}>
//                   <SectionHeader color="#4caf50" title="Parent Company Details" />
//                   <Grid container spacing={3}>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Company Registration Number"
//                         name="parentCompanyRegistrationNo"
//                         value={parentCompany.parentCompanyRegistrationNo}
//                         onChange={handleParentChange}
//                         error={errors.parentCompanyRegistrationNo}
//                         helperText={errors.parentCompanyRegistrationNo}
//                         placeholder="Parent registration number"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Legal Name of Company"
//                         name="parentLegalCompanyName"
//                         value={parentCompany.parentLegalCompanyName}
//                         onChange={handleParentChange}
//                         error={errors.parentLegalCompanyName}
//                         helperText={errors.parentLegalCompanyName}
//                         placeholder="Parent legal name"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Registered DBA / Trade Name"
//                         name="parentTradeName"
//                         value={parentCompany.parentTradeName}
//                         onChange={handleParentChange}
//                         error={errors.parentTradeName}
//                         helperText={errors.parentTradeName}
//                         placeholder="Parent DBA name"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Type of Business"
//                         name="parentBusinessType"
//                         value={parentCompany.parentBusinessType}
//                         onChange={handleParentChange}
//                         error={errors.parentBusinessType}
//                         helperText={errors.parentBusinessType}
//                         placeholder="Select"
//                         select
//                         isEditMode={isEditMode}
//                       >
//                         <MenuItem value="" disabled>Select</MenuItem>
//                         {businessTypes.map(type => (
//                           <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
//                         ))}
//                       </SmartTextField>
//                     </Grid>

//                     {parentCompany.parentBusinessType === 'OTHER' && (
//                       <Grid item xs={12} sm={6}>
//                         <SmartTextField
//                           label="Please Specify Parent Business Type"
//                           name="parentOtherBusinessType"
//                           value={parentCompany.parentOtherBusinessType}
//                           onChange={handleParentChange}
//                           error={errors.parentOtherBusinessType}
//                           helperText={errors.parentOtherBusinessType}
//                           placeholder="Enter parent business type"
//                           isEditMode={isEditMode}
//                         />
//                       </Grid>
//                     )}

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Business Email"
//                         name="parentRegisteredBusinessEmail"
//                         value={parentCompany.parentRegisteredBusinessEmail}
//                         onChange={handleParentChange}
//                         error={errors.parentRegisteredBusinessEmail}
//                         helperText={errors.parentRegisteredBusinessEmail}
//                         placeholder="parent@company.com"
//                         type="email"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Telephone Number"
//                         name="parentPhone"
//                         value={parentCompany.parentPhone}
//                         onChange={handleParentChange}
//                         error={errors.parentPhone}
//                         helperText={errors.parentPhone}
//                         placeholder="Parent phone number"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12}>
//                       <SmartTextField
//                         label="Address 1"
//                         name="parentRegisteredStreetAddress"
//                         value={parentCompany.parentRegisteredStreetAddress}
//                         onChange={handleParentChange}
//                         error={errors.parentRegisteredStreetAddress}
//                         helperText={errors.parentRegisteredStreetAddress}
//                         placeholder="Street address"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12}>
//                       <SmartTextField
//                         label="Address 2"
//                         name="parentAddress2"
//                         value={parentCompany.parentAddress2}
//                         onChange={handleParentChange}
//                         error={errors.parentAddress2}
//                         helperText={errors.parentAddress2}
//                         placeholder="Apartment, suite, etc."
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="City"
//                         name="parentCity"
//                         value={parentCompany.parentCity}
//                         onChange={handleParentChange}
//                         error={errors.parentCity}
//                         helperText={errors.parentCity}
//                         placeholder="City"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="State / Province"
//                         name="parentState"
//                         value={parentCompany.parentState}
//                         onChange={handleParentChange}
//                         error={errors.parentState}
//                         helperText={errors.parentState}
//                         placeholder="State"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     {renderCountryAutocomplete('parent-country-select', parentCompany.parentCountry, handleParentCountryChange, 'Country', errors.parentCountry)}

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Postcode / Zip Code"
//                         name="parentZipCode"
//                         value={parentCompany.parentZipCode}
//                         onChange={handleParentChange}
//                         error={errors.parentZipCode}
//                         helperText={errors.parentZipCode}
//                         placeholder="Postcode"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     {renderSelectField('parentCurrency', 'Currency', parentCompany.parentCurrency, handleParentChange, currencyOptions, errors.parentCurrency, fetchingCurrencies)}

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Turnover Last Year"
//                         name="parentTurnoverLastYear"
//                         value={parentCompany.parentTurnoverLastYear}
//                         onChange={handleParentChange}
//                         error={errors.parentTurnoverLastYear}
//                         helperText={errors.parentTurnoverLastYear}
//                         placeholder="e.g., 10000000"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     {renderDateField('parentIncorporationDate', 'Incorporation Date', parentCompany.parentIncorporationDate, handleParentChange)}

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="VAT / Tax Identification Number"
//                         name="parentTaxIdentificationNumber"
//                         value={parentCompany.parentTaxIdentificationNumber}
//                         onChange={handleParentChange}
//                         error={errors.parentTaxIdentificationNumber}
//                         helperText={errors.parentTaxIdentificationNumber}
//                         placeholder="Parent VAT/Tax ID"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12}>
//                       <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
//                         <FormControlLabel
//                           control={<Checkbox checked={parentCompany.parentStockExchange} onChange={handleParentChange} name="parentStockExchange" />}
//                           label="Is parent company publicly listed on a stock exchange?"
//                         />
//                         <FormControlLabel
//                           control={<Checkbox checked={parentCompany.parentNotForProfit} onChange={handleParentChange} name="parentNotForProfit" />}
//                           label="Is parent company a registered 'not-for-profit' organization?"
//                         />
//                       </Stack>
//                     </Grid>

//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             {/* ── Billing Address Section ── */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <FormControlLabel
//                 control={<Switch checked={billingDifferent} onChange={(e) => setBillingDifferent(e.target.checked)} color="primary" />}
//                 label={<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>Is billing address different from registered address?</Typography>}
//               />
//               <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                 Toggle on if your billing address is different from the company's registered address
//               </Typography>

//               {billingDifferent && (
//                 <Box sx={{ mt: 3 }}>
//                   <SectionHeader color="#ff9800" title="Billing Address" />
//                   <Typography variant="caption" sx={{ color: 'text.secondary', mb: 2, display: 'block' }}>
//                     PO Boxes are not acceptable for onboarding
//                   </Typography>
//                   <Grid container spacing={3}>

//                     <Grid item xs={12}>
//                       <SmartTextField
//                         label="Street Address"
//                         name="billingStreetAddress"
//                         value={billingAddress.billingStreetAddress}
//                         onChange={handleBillingChange}
//                         error={errors.billingStreetAddress}
//                         helperText={errors.billingStreetAddress}
//                         placeholder="Street address"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12}>
//                       <SmartTextField
//                         label="Address 2"
//                         name="billingAddress2"
//                         value={billingAddress.billingAddress2}
//                         onChange={handleBillingChange}
//                         error={errors.billingAddress2}
//                         helperText={errors.billingAddress2}
//                         placeholder="Apartment, suite, unit, etc."
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="City"
//                         name="billingCity"
//                         value={billingAddress.billingCity}
//                         onChange={handleBillingChange}
//                         error={errors.billingCity}
//                         helperText={errors.billingCity}
//                         placeholder="City"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="State / Province"
//                         name="billingState"
//                         value={billingAddress.billingState}
//                         onChange={handleBillingChange}
//                         error={errors.billingState}
//                         helperText={errors.billingState}
//                         placeholder="State"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     {renderCountryAutocomplete('billing-country-select', billingAddress.billingCountry, handleBillingCountryChange, 'Country', errors.billingCountry)}

//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Postcode / Zip Code"
//                         name="billingPostCode"
//                         value={billingAddress.billingPostCode}
//                         onChange={handleBillingChange}
//                         error={errors.billingPostCode}
//                         helperText={errors.billingPostCode}
//                         placeholder="Postcode"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                   </Grid>
//                 </Box>
//               )}
//             </Paper>

//             <Divider sx={{ my: 3 }} />

//             {/* Submit */}
//             <Button
//               type="submit"
//               fullWidth
//               variant="contained"
//               size="large"
//               disabled={loading || fetchingCurrencies || currencyList.length === 0 || hasAnyError}
//               sx={{
//                 py: 1.5,
//                 borderRadius: 2,
//                 textTransform: 'none',
//                 fontSize: '1rem',
//                 fontWeight: 600,
//                 boxShadow: 2,
//                 '&:hover': { boxShadow: 4 },
//               }}
//             >
//               {loading ? (
//                 <CircularProgress size={24} color="inherit" />
//               ) : isEditMode ? (
//                 'Update Company Profile'
//               ) : (
//                 'Create Company Profile'
//               )}
//             </Button>

//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default CompanyProfile

// tyscript issue 
import React, { useState, useEffect } from 'react'

import Grid from '@mui/material/Grid'
import Card from '@mui/material/Card'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Divider from '@mui/material/Divider'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import MenuItem from '@mui/material/MenuItem'
import FormControlLabel from '@mui/material/FormControlLabel'
import Checkbox from '@mui/material/Checkbox'
import Switch from '@mui/material/Switch'
import Button from '@mui/material/Button'
import Autocomplete from '@mui/material/Autocomplete'
import Paper from '@mui/material/Paper'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import Skeleton from '@mui/material/Skeleton'
import Chip from '@mui/material/Chip'
import toast from 'react-hot-toast'

// ** Data
import { countries } from 'src/@fake-db/autocomplete'

// ** Endpoints
import endpoints from 'src/configs/endpoints'

// ** Axios Instance
import axiosInstance from 'src/configs/axios'

// ** Types
interface CountryType {
  code: string
  label: string
  phone: string
  suggested?: boolean
}

interface CurrencyType {
  uid?: string | number
  currencyName?: string
  currencyCode?: string
  code?: string
  name?: string
  value?: string
  label?: string
}

interface ValidationErrors {
  [key: string]: string
}

interface CompanyProfileProps {
  onNext?: () => void
  applicationId: string
}

// ─── Live Validators ──────────────────────────────────────────────────────────
// Every error message includes the example so user sees it only when needed.

const validateEmail = (email: string): string => {
  if (!email) return ''
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
    return 'Please enter a valid email address. e.g. contact@company.com'
  return ''
}

const validatePhone = (phone: string): string => {
  if (!phone) return ''
  if (!/^[+]?[\d\s\-().]{7,20}$/.test(phone.trim()))
    return 'Please enter a valid phone number. e.g. +1 234 567 8900 or 022-2345-6789'
  return ''
}

const validateZip = (zip: string): string => {
  if (!zip) return ''
  const trimmed = zip.trim()
  if (trimmed.length < 3)
    return 'Postcode must be at least 3 characters. e.g. 400001 or SW1A 1AA'
  if (trimmed.length > 10)
    return 'Postcode must not exceed 10 characters. e.g. 400001 or SW1A 1AA'
  if (!/^[A-Za-z0-9\s\-]+$/.test(trimmed))
    return 'Postcode can only contain letters, numbers, spaces and hyphens. e.g. 400001 or SW1A 1AA'
  return ''
}

const validateTurnover = (val: string): string => {
  if (!val) return ''
  if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
    return 'Please enter a valid numeric amount. e.g. 1000000 or 250000.50 (no commas or symbols)'
  if (parseFloat(val) <= 0)
    return 'Turnover must be greater than 0. e.g. 1000000 or 250000.50'
  return ''
}

const validateRegistrationNo = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 3)
    return 'Registration number must be at least 3 characters. e.g. U12345MH2001PTC123456 or 12-3456789'
  if (!/^[A-Za-z0-9\s\-/]+$/.test(val.trim()))
    return 'Only letters, numbers, hyphens and slashes are allowed. e.g. U12345MH2001PTC123456 or CIN/2020/01'
  return ''
}

const validateCompanyName = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 2)
    return 'Name must be at least 2 characters. e.g. Acme Corp or O\'Brien & Sons Ltd'
  if (val.trim().length > 200)
    return 'Name must not exceed 200 characters.'
  if (/[<>/@#\\]/.test(val))
    return 'Special characters like < > @ # / \\ are not allowed. e.g. Acme Corp or Tech-X Ltd'
  return ''
}

const validateTaxId = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 3)
    return 'Tax ID must be at least 3 characters. e.g. 27AAACR5055K1ZV or GB123456789'
  if (!/^[A-Za-z0-9\-]+$/.test(val.trim()))
    return 'Only letters, digits and hyphens are allowed. e.g. 27AAACR5055K1ZV or GB123456789'
  return ''
}

const validateCityOrState = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 2)
    return 'Must be at least 2 characters. e.g. Mumbai or New York'
  if (val.trim().length > 100)
    return 'Must not exceed 100 characters.'
  if (!/^[A-Za-zÀ-ÿ\s'\-]+$/.test(val.trim()))
    return 'Only letters, spaces, hyphens and apostrophes are allowed. e.g. New York or Île-de-France'
  return ''
}

const validateAddress = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 5)
    return 'Address must be at least 5 characters. e.g. 123 Main Street, Bandra West'
  if (val.trim().length > 300)
    return 'Address must not exceed 300 characters.'
  if (/\bP\.?\s*O\.?\s*Box\b/i.test(val))
    return 'PO Boxes are not acceptable for onboarding. e.g. please use a physical street address like 123 Main Street'
  return ''
}

const validateAddress2 = (val: string): string => {
  if (!val) return ''
  if (val.trim().length > 200)
    return 'Must not exceed 200 characters. e.g. Apt 4B, Suite 100 or Floor 3'
  if (/\bP\.?\s*O\.?\s*Box\b/i.test(val))
    return 'PO Boxes are not acceptable for onboarding. e.g. please use a unit or floor number like Suite 100'
  return ''
}

const validateOtherBusinessType = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 2)
    return 'Please provide at least 2 characters. e.g. Cooperative or Trust'
  if (val.trim().length > 100)
    return 'Must not exceed 100 characters. e.g. Cooperative or Foundation'
  if (/[<>@#\\]/.test(val))
    return 'Special characters like < > @ # \\ are not allowed. e.g. Cooperative or Foundation'
  return ''
}

const validateIncorporationDate = (val: string): string => {
  if (!val) return ''
  const date = new Date(val)
  if (isNaN(date.getTime()))
    return 'Please enter a valid date. e.g. 2010-06-15'
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  if (date > today)
    return 'Incorporation date cannot be in the future. e.g. 2010-06-15'
  if (date.getFullYear() < 1800)
    return 'Please enter a realistic incorporation date. e.g. 1995-03-20'
  return ''
}

// ─── Helper: "Not Provided" Chip ─────────────────────────────────────────────────
const NotAddedChip = () => (
  <Chip
    label="Not Provided"
    size="small"
    sx={{
      height: 20,
      fontSize: '0.625rem',
      fontWeight: 500,
      backgroundColor: '#fff3e0',
      color: '#e65100',
      border: '1px solid',
      borderColor: '#ffb74d',
      '& .MuiChip-label': { px: 1, py: 0.25 },
    }}
  />
)

// ─── Helper: Green Tick Chip ──────────────────────────────────────────────────
const GreenTickChip = () => (
  <Chip
    label="✓"
    size="small"
    sx={{
      height: 20,
      minWidth: 20,
      fontSize: '0.75rem',
      fontWeight: 600,
      backgroundColor: '#e8f5e9',
      color: '#2e7d32',
      borderRadius: '50%',
      '& .MuiChip-label': { px: 0.75, display: 'flex', alignItems: 'center', justifyContent: 'center' },
    }}
  />
)

// ─── Field Label with status indicator ───────────────────────────────────────
const FieldLabel = ({
  label,
  value,
  isEditMode,
}: {
  label: string
  value: string | null | undefined
  isEditMode: boolean
}) => {
  const filled = value !== null && value !== undefined && String(value).trim() !== ''
  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
      <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary' }}>
        {label}
      </Typography>
      {isEditMode && filled && <GreenTickChip />}
      {isEditMode && !filled && <NotAddedChip />}
    </Box>
  )
}

// ─── SmartTextField ───────────────────────────────────────────────────────────
const SmartTextField = ({
  label,
  name,
  value,
  onChange,
  error,
  helperText,
  placeholder,
  type,
  select,
  children,
  InputLabelProps,
  multiline,
  rows,
  isEditMode,
  disabled,
}: any) => {
  const filled = value !== null && value !== undefined && String(value).trim() !== ''
  return (
    <Box>
      <FieldLabel label={label} value={value} isEditMode={isEditMode} />
      <TextField
        fullWidth
        name={name}
        value={value}
        onChange={onChange}
        error={!!error}
        helperText={helperText}
        placeholder={placeholder}
        type={type}
        select={select}
        InputLabelProps={InputLabelProps}
        multiline={multiline}
        rows={rows}
        disabled={disabled}
        sx={{
          '& .MuiOutlinedInput-root': {
            '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
            '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
          },
        }}
      >
        {children}
      </TextField>
    </Box>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────
const CompanyProfile = ({ onNext, applicationId }: CompanyProfileProps) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [fetchingData, setFetchingData] = useState<boolean>(true)
  const [fetchingCurrencies, setFetchingCurrencies] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)
  const [isEditMode, setIsEditMode] = useState<boolean>(false)
  const [parentCompanyId, setParentCompanyId] = useState<number>(0)
  const [currencyList, setCurrencyList] = useState<CurrencyType[]>([])
  const [currencyError, setCurrencyError] = useState<string | null>(null)

  const [company, setCompany] = useState({
    companyRegistrationNo: '',
    legalCompanyName: '',
    tradeName: '',
    businessType: '',
    otherBusinessType: '',
    registeredBusinessEmail: '',
    registeredStreetAddress: '',
    address2: '',
    city: '',
    country: null as CountryType | null,
    state: '',
    zipCode: '',
    phone: '',
    currency: '',
    turnoverLastYear: '',
    incorporationDate: '',
    taxIdentificationNumber: '',
    notForProfit: false,
    stockExchange: false,
  })

  const [hasParentCompany, setHasParentCompany] = useState<boolean>(false)
  const [parentCompany, setParentCompany] = useState({
    parentLegalCompanyName: '',
    parentCompanyRegistrationNo: '',
    parentTradeName: '',
    parentBusinessType: '',
    parentOtherBusinessType: '',
    parentRegisteredBusinessEmail: '',
    parentRegisteredStreetAddress: '',
    parentAddress2: '',
    parentCity: '',
    parentCountry: null as CountryType | null,
    parentState: '',
    parentZipCode: '',
    parentPhone: '',
    parentCurrency: '',
    parentTurnoverLastYear: '',
    parentIncorporationDate: '',
    parentTaxIdentificationNumber: '',
    parentNotForProfit: false,
    parentStockExchange: false,
  })

  const [billingDifferent, setBillingDifferent] = useState<boolean>(false)
  const [billingAddress, setBillingAddress] = useState({
    billingStreetAddress: '',
    billingAddress2: '',
    billingCity: '',
    billingState: '',
    billingCountry: null as CountryType | null,
    billingPostCode: '',
  })

  const [errors, setErrors] = useState<ValidationErrors>({})

  // ─── Business types ──────────────────────────────────────────────────────────
  const businessTypes = [
    'SOLE_PROPRIETORSHIP',
    'GENERAL_PARTNERSHIP',
    'LIMITED_PARTNERSHIP',
    'LIMITED_LIABILITY_PARTNERSHIP',
    'C_CORPORATION',
    'S_CORPORATION',
    'BENEFIT_CORPORATION',
    'LIMITED_LIABILITY_COMPANY',
    'OTHER',
  ]

  const businessTypeLabels: Record<string, string> = {
    SOLE_PROPRIETORSHIP: 'Sole Proprietorship',
    GENERAL_PARTNERSHIP: 'General Partnership',
    LIMITED_PARTNERSHIP: 'Limited Partnership',
    LIMITED_LIABILITY_PARTNERSHIP: 'Limited Liability Partnership (LLP)',
    C_CORPORATION: 'C Corporation',
    S_CORPORATION: 'S Corporation',
    BENEFIT_CORPORATION: 'Benefit Corporation',
    LIMITED_LIABILITY_COMPANY: 'Limited Liability Company (LLC)',
    OTHER: 'Other',
  }

  // ─── Fetch currencies ─────────────────────────────────────────────────────
  const fetchCurrencies = async () => {
    setFetchingCurrencies(true)
    setCurrencyError(null)
    try {
      const response = await axiosInstance.get(endpoints.merchantApplication.currency)
      if (response.data) {
        let currencies: CurrencyType[] = []
        if (Array.isArray(response.data)) {
          currencies = response.data
        } else if (response.data.data && Array.isArray(response.data.data)) {
          currencies = response.data.data
        } else if (response.data.content && Array.isArray(response.data.content)) {
          currencies = response.data.content
        } else if (response.data.items && Array.isArray(response.data.items)) {
          currencies = response.data.items
        } else if (typeof response.data === 'object' && response.data !== null) {
          if (response.data.currencyCode || response.data.currencyName) {
            currencies = [response.data]
          } else {
            const arrayValue = Object.values(response.data).find(val => Array.isArray(val))
            if (arrayValue) currencies = arrayValue as CurrencyType[]
            else { setCurrencyList([]); setCurrencyError('No currency data available from API'); return }
          }
        }
        if (currencies.length > 0) setCurrencyList(currencies)
        else { setCurrencyList([]); setCurrencyError('No currency data available from API') }
      } else { setCurrencyList([]); setCurrencyError('No currency data available from API') }
    } catch (err: any) {
      console.error('Error fetching currencies:', err)
      setCurrencyError('Failed to load currency list from API')
      setCurrencyList([])
      toast.error('Failed to load currency list from API')
    } finally {
      setFetchingCurrencies(false)
    }
  }

  const findCountryByName = (countryName: string): CountryType | null => {
    if (!countryName) return null

    // Use label instead of name since the countries data uses label
    const found = countries.find((c: any) => 
      c.label === countryName || 
      c.label?.toLowerCase() === countryName?.toLowerCase()
    )
    return found || null
  }

  const normalizeBusinessType = (raw: string): { type: string; other: string } => {
    if (!raw) return { type: '', other: '' }
    const valid = [
      'SOLE_PROPRIETORSHIP', 'GENERAL_PARTNERSHIP', 'LIMITED_PARTNERSHIP',
      'LIMITED_LIABILITY_PARTNERSHIP', 'C_CORPORATION', 'S_CORPORATION',
      'BENEFIT_CORPORATION', 'LIMITED_LIABILITY_COMPANY', 'OTHER',
    ]
    if (valid.includes(raw)) return { type: raw, other: '' }
    return { type: 'OTHER', other: raw }
  }

  const fetchApplicationData = async () => {
    if (!applicationId) { setFetchingData(false); return }
    setFetchingData(true)
    setError(null)
    try {
      const response = await axiosInstance.get(`${endpoints.merchantApplication.getApplicationDetails}${applicationId}`)
      if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
        const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
        const parentCompanyData = response.data.companyProfile.find((item: any) => item.isparent === true)
        if (mainCompany) {
          setIsEditMode(true)
          setParentCompanyId(mainCompany.parentCompanyId > 0 ? mainCompany.parentCompanyId : 0)
          prefillFormData(mainCompany, parentCompanyData)
        } else { setIsEditMode(false); setParentCompanyId(0) }
      } else { setIsEditMode(false); setParentCompanyId(0) }
    } catch (err: any) {
      if (err.response?.status === 404) { setIsEditMode(false); setParentCompanyId(0) }
      else toast.error('Failed to load data. Please try again.')
    } finally { setFetchingData(false) }
  }

  const prefillFormData = (mainData: any, parentData: any) => {
    const safeStr = (v: any) => (v && v !== 'NA' ? String(v) : '')
    const bizMain = normalizeBusinessType(safeStr(mainData.businessType))
    setCompany({
      companyRegistrationNo: safeStr(mainData.companyRegistrationNo),
      legalCompanyName: safeStr(mainData.legalCompanyName),
      tradeName: safeStr(mainData.tradeName),
      businessType: bizMain.type,
      otherBusinessType: bizMain.other,
      registeredBusinessEmail: safeStr(mainData.registeredBusinessEmail),
      registeredStreetAddress: safeStr(mainData.registeredStreetAddress),
      address2: safeStr(mainData.address2),
      city: safeStr(mainData.city),
      country: mainData.country ? findCountryByName(safeStr(mainData.country)) : null,
      state: safeStr(mainData.state),
      zipCode: safeStr(mainData.zipCode),
      phone: safeStr(mainData.phone),
      currency: safeStr(mainData.currency),
      turnoverLastYear: safeStr(mainData.turnoverLastYear),
      incorporationDate: safeStr(mainData.incorporationDate),
      taxIdentificationNumber: safeStr(mainData.taxIdentificationNumber),
      notForProfit: mainData.notForProfit === true || mainData.notForProfit === 'true',
      stockExchange: mainData.stockExchange === true || mainData.stockExchange === 'true',
    })
    setHasParentCompany(mainData.havingParentCompany === true || mainData.havingParentCompany === 'true')
    if (parentData) {
      const bizParent = normalizeBusinessType(safeStr(parentData.businessType))
      setParentCompany({
        parentCompanyRegistrationNo: safeStr(parentData.companyRegistrationNo),
        parentLegalCompanyName: safeStr(parentData.legalCompanyName),
        parentTradeName: safeStr(parentData.tradeName),
        parentBusinessType: bizParent.type,
        parentOtherBusinessType: bizParent.other,
        parentRegisteredBusinessEmail: safeStr(parentData.registeredBusinessEmail),
        parentRegisteredStreetAddress: safeStr(parentData.registeredStreetAddress),
        parentAddress2: safeStr(parentData.address2),
        parentCity: safeStr(parentData.city),
        parentCountry: parentData.country ? findCountryByName(safeStr(parentData.country)) : null,
        parentState: safeStr(parentData.state),
        parentZipCode: safeStr(parentData.zipCode),
        parentPhone: safeStr(parentData.phone),
        parentCurrency: safeStr(parentData.currency),
        parentTurnoverLastYear: safeStr(parentData.turnoverLastYear),
        parentIncorporationDate: safeStr(parentData.incorporationDate),
        parentTaxIdentificationNumber: safeStr(parentData.taxIdentificationNumber),
        parentNotForProfit: parentData.notForProfit === true || parentData.notForProfit === 'true',
        parentStockExchange: parentData.stockExchange === true || parentData.stockExchange === 'true',
      })
    }
    setBillingDifferent(mainData.billingRegisteredAddress === true || mainData.billingRegisteredAddress === 'true')
    if (mainData.billingRegisteredAddress === true) {
      setBillingAddress({
        billingStreetAddress: safeStr(mainData.billingStreetAddress),
        billingAddress2: safeStr(mainData.billingAddress2),
        billingCity: safeStr(mainData.billingCity),
        billingState: safeStr(mainData.billingState),
        billingCountry: mainData.billingCountry ? findCountryByName(safeStr(mainData.billingCountry)) : null,
        billingPostCode: safeStr(mainData.billingPostCode),
      })
    }
  }

  useEffect(() => {
    if (applicationId) fetchApplicationData()
    fetchCurrencies()
  }, [applicationId])

  // ─── Live validation router ───────────────────────────────────────────────
  const runLiveValidation = (name: string, value: string): string => {
    switch (name) {
      case 'registeredBusinessEmail':
      case 'parentRegisteredBusinessEmail':
        return validateEmail(value)

      case 'phone':
      case 'parentPhone':
        return validatePhone(value)

      case 'zipCode':
      case 'parentZipCode':
      case 'billingPostCode':
        return validateZip(value)

      case 'turnoverLastYear':
      case 'parentTurnoverLastYear':
        return validateTurnover(value)

      case 'companyRegistrationNo':
      case 'parentCompanyRegistrationNo':
        return validateRegistrationNo(value)

      case 'legalCompanyName':
      case 'tradeName':
      case 'parentLegalCompanyName':
      case 'parentTradeName':
        return validateCompanyName(value)

      case 'taxIdentificationNumber':
      case 'parentTaxIdentificationNumber':
        return validateTaxId(value)

      case 'city':
      case 'parentCity':
      case 'billingCity':
        return validateCityOrState(value)

      case 'state':
      case 'parentState':
      case 'billingState':
        return validateCityOrState(value)

      case 'registeredStreetAddress':
      case 'parentRegisteredStreetAddress':
      case 'billingStreetAddress':
        return validateAddress(value)

      case 'address2':
      case 'parentAddress2':
      case 'billingAddress2':
        return validateAddress2(value)

      case 'otherBusinessType':
      case 'parentOtherBusinessType':
        return validateOtherBusinessType(value)

      case 'incorporationDate':
      case 'parentIncorporationDate':
        return validateIncorporationDate(value)

      default:
        return ''
    }
  }

  // ─── Handlers ─────────────────────────────────────────────────────────────
  const handleCompanyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    const newVal = type === 'checkbox' ? checked : value
    setCompany(prev => ({ ...prev, [name]: newVal }))
    if (type !== 'checkbox') {
      setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
    }
  }

  const handleCompanyCountryChange = (newValue: CountryType | null) => {
    setCompany(prev => ({ ...prev, country: newValue }))
    if (errors.country) setErrors(prev => ({ ...prev, country: '' }))
  }

  const handleParentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    const newVal = type === 'checkbox' ? checked : value
    setParentCompany(prev => ({ ...prev, [name]: newVal }))
    if (type !== 'checkbox') {
      setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
    }
  }

  const handleParentCountryChange = (newValue: CountryType | null) => {
    setParentCompany(prev => ({ ...prev, parentCountry: newValue }))
    if (errors.parentCountry) setErrors(prev => ({ ...prev, parentCountry: '' }))
  }

  const handleBillingChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setBillingAddress(prev => ({ ...prev, [name]: value }))
    setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, value) }))
  }

  const handleBillingCountryChange = (newValue: CountryType | null) => {
    setBillingAddress(prev => ({ ...prev, billingCountry: newValue }))
    if (errors.billingCountry) setErrors(prev => ({ ...prev, billingCountry: '' }))
  }

  // ─── Block submit if any live error exists ────────────────────────────────
  const hasAnyError = Object.values(errors).some(msg => msg !== '')

  // ─── Build request body ───────────────────────────────────────────────────
  const buildRequestBody = () => {
    let businessTypeToSend = company.businessType
    if (company.businessType === 'OTHER' && company.otherBusinessType) {
      businessTypeToSend = company.otherBusinessType
    }
    const requestBody: any = {
      applicationId: parseInt(applicationId),
      companyRegistrationNo: company.companyRegistrationNo || '',
      legalCompanyName: company.legalCompanyName || '',
      tradeName: company.tradeName || '',
      businessType: businessTypeToSend || '',
      registeredBusinessEmail: company.registeredBusinessEmail || '',
      registeredStreetAddress: company.registeredStreetAddress || '',
      address2: company.address2 || '',
      city: company.city || '',
      country: company.country?.label || '',
      state: company.state || '',
      zipCode: company.zipCode || '',
      phone: company.phone || '',
      currency: company.currency || '',
      turnoverLastYear: company.turnoverLastYear || '',
      incorporationDate: company.incorporationDate || '',
      taxIdentificationNumber: company.taxIdentificationNumber || '',
      notForProfit: company.notForProfit,
      stockExchange: company.stockExchange,
      havingParentCompany: hasParentCompany,
      billingRegisteredAddress: billingDifferent,
    }

    if (hasParentCompany) {
      let parentBusinessTypeToSend = parentCompany.parentBusinessType
      if (parentCompany.parentBusinessType === 'OTHER' && parentCompany.parentOtherBusinessType) {
        parentBusinessTypeToSend = parentCompany.parentOtherBusinessType
      }
      Object.assign(requestBody, {
        parentLegalCompanyName: parentCompany.parentLegalCompanyName || '',
        parentCompanyRegistrationNo: parentCompany.parentCompanyRegistrationNo || '',
        parentTradeName: parentCompany.parentTradeName || '',
        parentBusinessType: parentBusinessTypeToSend || '',
        parentRegisteredBusinessEmail: parentCompany.parentRegisteredBusinessEmail || '',
        parentRegisteredStreetAddress: parentCompany.parentRegisteredStreetAddress || '',
        parentAddress2: parentCompany.parentAddress2 || '',
        parentCity: parentCompany.parentCity || '',
        parentCountry: parentCompany.parentCountry?.label || '',
        parentState: parentCompany.parentState || '',
        parentZipCode: parentCompany.parentZipCode || '',
        parentPhone: parentCompany.parentPhone || '',
        parentCurrency: parentCompany.parentCurrency || '',
        parentTurnoverLastYear: parentCompany.parentTurnoverLastYear || '',
        parentIncorporationDate: parentCompany.parentIncorporationDate || '',
        parentTaxIdentificationNumber: parentCompany.parentTaxIdentificationNumber || '',
        parentNotForProfit: parentCompany.parentNotForProfit,
        parentStockExchange: parentCompany.parentStockExchange,
      })
      if (parentCompanyId > 0) requestBody.parentCompanyId = parentCompanyId
    } else {
      Object.assign(requestBody, {
        parentLegalCompanyName: '', parentCompanyRegistrationNo: '', parentTradeName: '',
        parentBusinessType: '', parentRegisteredBusinessEmail: '', parentRegisteredStreetAddress: '',
        parentAddress2: '', parentCity: '', parentCountry: '', parentState: '',
        parentZipCode: '', parentPhone: '', parentCurrency: '', parentTurnoverLastYear: '',
        parentIncorporationDate: '', parentTaxIdentificationNumber: '',
        parentNotForProfit: false, parentStockExchange: false,
      })
      if (isEditMode) requestBody.parentCompanyId = 0
    }

    if (billingDifferent) {
      Object.assign(requestBody, {
        billingStreetAddress: billingAddress.billingStreetAddress || '',
        billingAddress2: billingAddress.billingAddress2 || '',
        billingCity: billingAddress.billingCity || '',
        billingState: billingAddress.billingState || '',
        billingCountry: billingAddress.billingCountry?.label || '',
        billingPostCode: billingAddress.billingPostCode || '',
      })
    } else {
      Object.assign(requestBody, {
        billingStreetAddress: '', billingAddress2: '', billingCity: '',
        billingState: '', billingCountry: '', billingPostCode: '',
      })
    }
    return requestBody
  }

  // ─── Submit ───────────────────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (hasAnyError) {
      toast.error('Please fix the validation errors before submitting.')
      return
    }
    setLoading(true)
    setError(null)
    const requestBody = buildRequestBody()
    try {
      let response
      if (isEditMode) {
        response = await axiosInstance.put(`${endpoints.merchantApplication.companyProfile}${applicationId}`, requestBody)
        toast.success('Company profile updated successfully!')
        setTimeout(() => fetchApplicationData(), 1000)
      } else {
        response = await axiosInstance.post(endpoints.merchantApplication.companyProfile, requestBody)
        toast.success('Company profile created successfully!')
        setIsEditMode(true)
        if (response.data?.parentCompanyId) setParentCompanyId(response.data.parentCompanyId)
      }
      if (response.data) {
        setTimeout(() => fetchApplicationData(), 1000)
        if (onNext) setTimeout(() => onNext(), 1500)
      }
    } catch (err: any) {
      let errorMessage = isEditMode
        ? 'Failed to update company profile. Please try again.'
        : 'Failed to create company profile. Please try again.'
      if (err.response?.data) {
        if (err.response.data.content) {
          if (typeof err.response.data.content === 'object') {
            const errorMessages = Object.entries(err.response.data.content).map(([k, v]) => `${k}: ${v}`).join(', ')
            errorMessage = errorMessages
            toast.error(errorMessages)
          } else { errorMessage = err.response.data.content; toast.error(errorMessage) }
        } else if (err.response.data.message) { errorMessage = err.response.data.message; toast.error(errorMessage) }
        else toast.error(errorMessage)
      } else toast.error(errorMessage)
      setError(errorMessage)
    } finally { setLoading(false) }
  }

  // ─── Country Autocomplete ─────────────────────────────────────────────────
  const renderCountryAutocomplete = (
    id: string,
    value: CountryType | null,
    onChange: (value: CountryType | null) => void,
    label: string,
    error?: string
  ) => {
    const filled = value !== null && value !== undefined
    return (
      <Grid item xs={12} sm={6}>
        <Box>
          <FieldLabel label={label} value={filled ? 'filled' : ''} isEditMode={isEditMode} />
          <Autocomplete
            id={id}
            options={countries}
            autoHighlight
            getOptionLabel={(option) => {
              if (!option) return ''
              if (typeof option === 'string') return option

              // Use phone for dial code (the data uses 'phone')
              const dialCode = option.phone || ''
              const name = option.label || ''
              return dialCode ? `${name} (+${dialCode})` : name
            }}
            value={value}
            onChange={(event, newValue) => onChange(newValue)}
            renderOption={(props, option) => {
              const dialCode = option.phone || ''
              const 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}
                placeholder="Select country"
                error={!!error}
                helperText={error}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
                    '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
                  },
                }}
              />
            )}
          />
        </Box>
      </Grid>
    )
  }

  // ─── Currency select ──────────────────────────────────────────────────────
  const renderSelectField = (
    name: string,
    label: string,
    value: string,
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void,
    options: { value: string; label: string }[],
    errorMsg?: string,
    loadingCur?: boolean
  ) => {
    const filled = value !== null && value !== undefined && String(value).trim() !== ''
    return (
      <Grid item xs={12} sm={6}>
        <Box>
          <FieldLabel label={label} value={value} isEditMode={isEditMode} />
          <TextField
            fullWidth select name={name} value={value} onChange={onChange}
            error={!!errorMsg}
            helperText={errorMsg || (loadingCur ? 'Loading currencies...' : '')}
            disabled={loadingCur}
            sx={{
              '& .MuiOutlinedInput-root': {
                '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
                '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
              },
            }}
          >
            <MenuItem value="" disabled>{loadingCur ? 'Loading...' : '-- Select --'}</MenuItem>
            {options.map(opt => <MenuItem key={opt.value} value={opt.value}>{opt.label}</MenuItem>)}
          </TextField>
        </Box>
      </Grid>
    )
  }

  // ─── Skeleton ─────────────────────────────────────────────────────────────
  if (fetchingData) {
    return (
      <Box sx={{ p: 6 }}>
        <Card sx={{ p: 6 }}>
          <Skeleton variant="text" height={60} />
          <Skeleton variant="rectangular" height={400} />
          <Skeleton variant="text" height={60} />
          <Skeleton variant="rectangular" height={200} />
        </Card>
      </Box>
    )
  }

  // ─── Section header ───────────────────────────────────────────────────────
  const SectionHeader = ({ color, title }: { color: string; title: string }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
      <Box sx={{ width: 4, height: 24, bgcolor: color, borderRadius: 2 }} />
      <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>{title}</Typography>
    </Box>
  )

  const currencyOptions = currencyList.map(currency => {
    let value = '', label = ''
    if (typeof currency === 'object' && currency !== null) {
      value = currency.currencyCode || currency.code || currency.value || currency.uid?.toString() || ''
      const name = currency.currencyName || currency.name || currency.label || ''
      label = value && name ? `${value} - ${name}` : value || name || 'Unknown Currency'
      if (!value) value = 'UNKNOWN'
    } else if (typeof currency === 'string') { value = currency; label = currency }
    else { value = ''; label = 'Unknown' }
    return { value, label }
  })

  // ─── Date field helper ────────────────────────────────────────────────────
  const renderDateField = (
    name: string,
    label: string,
    value: string,
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
  ) => (
    <Grid item xs={12} sm={6}>
      <Box>
        <FieldLabel label={label} value={value} isEditMode={isEditMode} />
        <TextField
          fullWidth
          name={name}
          type="date"
          value={value}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
            onChange(e)
            setErrors(prev => ({ ...prev, [name]: runLiveValidation(name, e.target.value) }))
          }}
          error={!!errors[name]}
          helperText={errors[name]}
          InputLabelProps={{ shrink: true }}
          inputProps={{ max: new Date().toISOString().split('T')[0] }}
          sx={{
            '& .MuiOutlinedInput-root': {
              '& fieldset': { borderColor: isEditMode && value ? '#A5D6A7' : undefined },
            },
          }}
        />
      </Box>
    </Grid>
  )

  return (
    <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
      <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
        <form onSubmit={handleSubmit}>
          <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>

            {/* Header */}
            <Box sx={{ mb: 4 }}>
              <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
                Applying Company Details
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Application ID: <strong>{applicationId}</strong>
                </Typography>
                <Chip
                  label={isEditMode ? 'Editing Existing Record' : 'Creating New Record'}
                  size="small"
                  sx={{
                    backgroundColor: isEditMode ? '#e8f5e9' : '#fff3e0',
                    color: isEditMode ? '#2e7d32' : '#e65100',
                    fontWeight: 500,
                  }}
                />
              </Box>
              <Divider sx={{ mt: 2 }} />
            </Box>

            {/* Info Alert */}
            <Alert severity="info" sx={{ mb: 3 }}>
              <Typography variant="body2">
                {isEditMode
                  ? 'You can edit any field. Green ✓ indicates filled fields, orange "Not Provided" indicates missing information.'
                  : 'Fill the form to create a new record.'}
              </Typography>
            </Alert>

            {/* ── Main Company Section ── */}
            <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
              <SectionHeader color="primary.main" title="Company Information" />
              <Grid container spacing={3}>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Company Registration Number"
                    name="companyRegistrationNo"
                    value={company.companyRegistrationNo}
                    onChange={handleCompanyChange}
                    error={errors.companyRegistrationNo}
                    helperText={errors.companyRegistrationNo}
                    placeholder="Enter registration number"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Legal Name of Company"
                    name="legalCompanyName"
                    value={company.legalCompanyName}
                    onChange={handleCompanyChange}
                    error={errors.legalCompanyName}
                    helperText={errors.legalCompanyName}
                    placeholder="Legal name"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Registered DBA / Trade Name"
                    name="tradeName"
                    value={company.tradeName}
                    onChange={handleCompanyChange}
                    error={errors.tradeName}
                    helperText={errors.tradeName}
                    placeholder="Doing business as (if any)"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Type of Business"
                    name="businessType"
                    value={company.businessType}
                    onChange={handleCompanyChange}
                    error={errors.businessType}
                    helperText={errors.businessType}
                    placeholder="-- Select Business Type --"
                    select
                    isEditMode={isEditMode}
                  >
                    <MenuItem value="" disabled>-- Select Business Type --</MenuItem>
                    {businessTypes.map(type => (
                      <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
                    ))}
                  </SmartTextField>
                </Grid>

                {company.businessType === 'OTHER' && (
                  <Grid item xs={12} sm={6}>
                    <SmartTextField
                      label="Please Specify Your Business Type"
                      name="otherBusinessType"
                      value={company.otherBusinessType}
                      onChange={handleCompanyChange}
                      error={errors.otherBusinessType}
                      helperText={errors.otherBusinessType}
                      placeholder="Enter your business type"
                      isEditMode={isEditMode}
                    />
                  </Grid>
                )}

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Business Email"
                    name="registeredBusinessEmail"
                    value={company.registeredBusinessEmail}
                    onChange={handleCompanyChange}
                    error={errors.registeredBusinessEmail}
                    helperText={errors.registeredBusinessEmail}
                    placeholder="contact@company.com"
                    type="email"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Telephone Number"
                    name="phone"
                    value={company.phone}
                    onChange={handleCompanyChange}
                    error={errors.phone}
                    helperText={errors.phone}
                    placeholder="+1 234 567 8900"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12}>
                  <SmartTextField
                    label="Address 1"
                    name="registeredStreetAddress"
                    value={company.registeredStreetAddress}
                    onChange={handleCompanyChange}
                    error={errors.registeredStreetAddress}
                    helperText={errors.registeredStreetAddress}
                    placeholder="Street address"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12}>
                  <SmartTextField
                    label="Address 2"
                    name="address2"
                    value={company.address2}
                    onChange={handleCompanyChange}
                    error={errors.address2}
                    helperText={errors.address2}
                    placeholder="Apartment, suite, unit, etc."
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="City"
                    name="city"
                    value={company.city}
                    onChange={handleCompanyChange}
                    error={errors.city}
                    helperText={errors.city}
                    placeholder="City"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="State / Province"
                    name="state"
                    value={company.state}
                    onChange={handleCompanyChange}
                    error={errors.state}
                    helperText={errors.state}
                    placeholder="State"
                    isEditMode={isEditMode}
                  />
                </Grid>

                {renderCountryAutocomplete('company-country-select', company.country, handleCompanyCountryChange, 'Country', errors.country)}

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Postcode / Zip Code"
                    name="zipCode"
                    value={company.zipCode}
                    onChange={handleCompanyChange}
                    error={errors.zipCode}
                    helperText={errors.zipCode}
                    placeholder="Postcode"
                    isEditMode={isEditMode}
                  />
                </Grid>

                {renderSelectField('currency', 'Currency', company.currency, handleCompanyChange, currencyOptions, errors.currency, fetchingCurrencies)}

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Turnover Last Year (Annual Sales)"
                    name="turnoverLastYear"
                    value={company.turnoverLastYear}
                    onChange={handleCompanyChange}
                    error={errors.turnoverLastYear}
                    helperText={errors.turnoverLastYear}
                    placeholder="e.g., 1000000"
                    isEditMode={isEditMode}
                  />
                </Grid>

                {renderDateField('incorporationDate', 'Incorporation Date', company.incorporationDate, handleCompanyChange)}

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="VAT / Tax Identification Number"
                    name="taxIdentificationNumber"
                    value={company.taxIdentificationNumber}
                    onChange={handleCompanyChange}
                    error={errors.taxIdentificationNumber}
                    helperText={errors.taxIdentificationNumber}
                    placeholder="VAT/Tax ID"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12}>
                  <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
                    <FormControlLabel
                      control={<Checkbox checked={company.stockExchange} onChange={handleCompanyChange} name="stockExchange" />}
                      label="Is company publicly listed on a stock exchange?"
                    />
                    <FormControlLabel
                      control={<Checkbox checked={company.notForProfit} onChange={handleCompanyChange} name="notForProfit" />}
                      label="Is company a registered 'not-for-profit' organization?"
                    />
                  </Stack>
                </Grid>

              </Grid>
            </Paper>

            {/* ── Parent Company Section ── */}
            <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
              <FormControlLabel
                control={<Switch checked={hasParentCompany} onChange={(e) => setHasParentCompany(e.target.checked)} color="primary" />}
                label={<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>Has Parent Company</Typography>}
              />
              <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
                Toggle on if this company is owned or controlled by another entity
              </Typography>

              {hasParentCompany && (
                <Box sx={{ mt: 3 }}>
                  <SectionHeader color="#4caf50" title="Parent Company Details" />
                  <Grid container spacing={3}>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Company Registration Number"
                        name="parentCompanyRegistrationNo"
                        value={parentCompany.parentCompanyRegistrationNo}
                        onChange={handleParentChange}
                        error={errors.parentCompanyRegistrationNo}
                        helperText={errors.parentCompanyRegistrationNo}
                        placeholder="Parent registration number"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Legal Name of Company"
                        name="parentLegalCompanyName"
                        value={parentCompany.parentLegalCompanyName}
                        onChange={handleParentChange}
                        error={errors.parentLegalCompanyName}
                        helperText={errors.parentLegalCompanyName}
                        placeholder="Parent legal name"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Registered DBA / Trade Name"
                        name="parentTradeName"
                        value={parentCompany.parentTradeName}
                        onChange={handleParentChange}
                        error={errors.parentTradeName}
                        helperText={errors.parentTradeName}
                        placeholder="Parent DBA name"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Type of Business"
                        name="parentBusinessType"
                        value={parentCompany.parentBusinessType}
                        onChange={handleParentChange}
                        error={errors.parentBusinessType}
                        helperText={errors.parentBusinessType}
                        placeholder="Select"
                        select
                        isEditMode={isEditMode}
                      >
                        <MenuItem value="" disabled>Select</MenuItem>
                        {businessTypes.map(type => (
                          <MenuItem key={type} value={type}>{businessTypeLabels[type] || type}</MenuItem>
                        ))}
                      </SmartTextField>
                    </Grid>

                    {parentCompany.parentBusinessType === 'OTHER' && (
                      <Grid item xs={12} sm={6}>
                        <SmartTextField
                          label="Please Specify Parent Business Type"
                          name="parentOtherBusinessType"
                          value={parentCompany.parentOtherBusinessType}
                          onChange={handleParentChange}
                          error={errors.parentOtherBusinessType}
                          helperText={errors.parentOtherBusinessType}
                          placeholder="Enter parent business type"
                          isEditMode={isEditMode}
                        />
                      </Grid>
                    )}

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Business Email"
                        name="parentRegisteredBusinessEmail"
                        value={parentCompany.parentRegisteredBusinessEmail}
                        onChange={handleParentChange}
                        error={errors.parentRegisteredBusinessEmail}
                        helperText={errors.parentRegisteredBusinessEmail}
                        placeholder="parent@company.com"
                        type="email"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Telephone Number"
                        name="parentPhone"
                        value={parentCompany.parentPhone}
                        onChange={handleParentChange}
                        error={errors.parentPhone}
                        helperText={errors.parentPhone}
                        placeholder="Parent phone number"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12}>
                      <SmartTextField
                        label="Address 1"
                        name="parentRegisteredStreetAddress"
                        value={parentCompany.parentRegisteredStreetAddress}
                        onChange={handleParentChange}
                        error={errors.parentRegisteredStreetAddress}
                        helperText={errors.parentRegisteredStreetAddress}
                        placeholder="Street address"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12}>
                      <SmartTextField
                        label="Address 2"
                        name="parentAddress2"
                        value={parentCompany.parentAddress2}
                        onChange={handleParentChange}
                        error={errors.parentAddress2}
                        helperText={errors.parentAddress2}
                        placeholder="Apartment, suite, etc."
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="City"
                        name="parentCity"
                        value={parentCompany.parentCity}
                        onChange={handleParentChange}
                        error={errors.parentCity}
                        helperText={errors.parentCity}
                        placeholder="City"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="State / Province"
                        name="parentState"
                        value={parentCompany.parentState}
                        onChange={handleParentChange}
                        error={errors.parentState}
                        helperText={errors.parentState}
                        placeholder="State"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    {renderCountryAutocomplete('parent-country-select', parentCompany.parentCountry, handleParentCountryChange, 'Country', errors.parentCountry)}

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Postcode / Zip Code"
                        name="parentZipCode"
                        value={parentCompany.parentZipCode}
                        onChange={handleParentChange}
                        error={errors.parentZipCode}
                        helperText={errors.parentZipCode}
                        placeholder="Postcode"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    {renderSelectField('parentCurrency', 'Currency', parentCompany.parentCurrency, handleParentChange, currencyOptions, errors.parentCurrency, fetchingCurrencies)}

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Turnover Last Year"
                        name="parentTurnoverLastYear"
                        value={parentCompany.parentTurnoverLastYear}
                        onChange={handleParentChange}
                        error={errors.parentTurnoverLastYear}
                        helperText={errors.parentTurnoverLastYear}
                        placeholder="e.g., 10000000"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    {renderDateField('parentIncorporationDate', 'Incorporation Date', parentCompany.parentIncorporationDate, handleParentChange)}

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="VAT / Tax Identification Number"
                        name="parentTaxIdentificationNumber"
                        value={parentCompany.parentTaxIdentificationNumber}
                        onChange={handleParentChange}
                        error={errors.parentTaxIdentificationNumber}
                        helperText={errors.parentTaxIdentificationNumber}
                        placeholder="Parent VAT/Tax ID"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12}>
                      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3}>
                        <FormControlLabel
                          control={<Checkbox checked={parentCompany.parentStockExchange} onChange={handleParentChange} name="parentStockExchange" />}
                          label="Is parent company publicly listed on a stock exchange?"
                        />
                        <FormControlLabel
                          control={<Checkbox checked={parentCompany.parentNotForProfit} onChange={handleParentChange} name="parentNotForProfit" />}
                          label="Is parent company a registered 'not-for-profit' organization?"
                        />
                      </Stack>
                    </Grid>

                  </Grid>
                </Box>
              )}
            </Paper>

            {/* ── Billing Address Section ── */}
            <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
              <FormControlLabel
                control={<Switch checked={billingDifferent} onChange={(e) => setBillingDifferent(e.target.checked)} color="primary" />}
                label={<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>Is billing address different from registered address?</Typography>}
              />
              <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
                Toggle on if your billing address is different from the company's registered address
              </Typography>

              {billingDifferent && (
                <Box sx={{ mt: 3 }}>
                  <SectionHeader color="#ff9800" title="Billing Address" />
                  <Typography variant="caption" sx={{ color: 'text.secondary', mb: 2, display: 'block' }}>
                    PO Boxes are not acceptable for onboarding
                  </Typography>
                  <Grid container spacing={3}>

                    <Grid item xs={12}>
                      <SmartTextField
                        label="Street Address"
                        name="billingStreetAddress"
                        value={billingAddress.billingStreetAddress}
                        onChange={handleBillingChange}
                        error={errors.billingStreetAddress}
                        helperText={errors.billingStreetAddress}
                        placeholder="Street address"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12}>
                      <SmartTextField
                        label="Address 2"
                        name="billingAddress2"
                        value={billingAddress.billingAddress2}
                        onChange={handleBillingChange}
                        error={errors.billingAddress2}
                        helperText={errors.billingAddress2}
                        placeholder="Apartment, suite, unit, etc."
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="City"
                        name="billingCity"
                        value={billingAddress.billingCity}
                        onChange={handleBillingChange}
                        error={errors.billingCity}
                        helperText={errors.billingCity}
                        placeholder="City"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="State / Province"
                        name="billingState"
                        value={billingAddress.billingState}
                        onChange={handleBillingChange}
                        error={errors.billingState}
                        helperText={errors.billingState}
                        placeholder="State"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    {renderCountryAutocomplete('billing-country-select', billingAddress.billingCountry, handleBillingCountryChange, 'Country', errors.billingCountry)}

                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Postcode / Zip Code"
                        name="billingPostCode"
                        value={billingAddress.billingPostCode}
                        onChange={handleBillingChange}
                        error={errors.billingPostCode}
                        helperText={errors.billingPostCode}
                        placeholder="Postcode"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                  </Grid>
                </Box>
              )}
            </Paper>

            <Divider sx={{ my: 3 }} />

            {/* Submit */}
            <Button
              type="submit"
              fullWidth
              variant="contained"
              size="large"
              disabled={loading || fetchingCurrencies || currencyList.length === 0 || hasAnyError}
              sx={{
                py: 1.5,
                borderRadius: 2,
                textTransform: 'none',
                fontSize: '1rem',
                fontWeight: 600,
                boxShadow: 2,
                '&:hover': { boxShadow: 4 },
              }}
            >
              {loading ? (
                <CircularProgress size={24} color="inherit" />
              ) : isEditMode ? (
                'Update Company Profile'
              ) : (
                'Create Company Profile'
              )}
            </Button>

          </Box>
        </form>
      </Card>
    </Box>
  )
}

export default CompanyProfile