"use client"
import { Button } from '@/components/ui/button';
import { createRegistration } from '@/lib/api/registration';
import { Eye, EyeOff } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { BsShopWindow } from 'react-icons/bs';
import { sendOtp, verifyOtp } from '@/lib/api/otp';
import { toast, Toaster } from 'sonner';

type IconName = 'user' | 'phone' | 'mail' | 'location' | 'briefcase' | 'check' | 'arrow' | 'grid';
type AccentKey = 'lime'|'amber'|'sky' | 'violet' | 'emerald' | 'rose';
type LocationValue = { division?: string; district?: string; upazila?: string };
type DropdownValue = { option?: string; text?: string };
type FormValue = string | string[] | LocationValue | DropdownValue | undefined;
type FormData = Record<string, FormValue>;
type ErrorMap = Record<string, string>;

type RegistrationField =
  | { id: string; label: string; type: 'text' | 'email' | 'mobile'| 'password'; placeholder?: string; required: boolean; hasOTP?: boolean }
  | { id: string; label: string; type: 'select'; options: string[]; required: boolean }
  | { id: string; label: string; type: 'multiselect'; options: string[]; required: boolean }
  | { id: string; label: string; type: 'location'; required: boolean }
  | { id: string; label: string; type: 'dropdownWithText'; options: string[]; required: boolean };

type RegistrationConfig = Record<string, {
  label: string,
  icon: string,
  color: string,
  accent: AccentKey,
  description: string,
  fields: RegistrationField[],
}>;

// --- Configuration Data ---
const registrationConfig: RegistrationConfig = {
  guest: {
    label: 'Guest',
    icon: '👤',
    color: 'from-lime-400 to-lime-500',
    accent: 'lime',
    description: 'Register as a sq user or customer',
    fields: [
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'email', label: 'Email', type: 'email', placeholder: 'optional@example.com', required: false},
      { id: 'workType', label: 'Work Type', type: 'select', options: ['Residential', 'Commercial', 'Industrial'], required: true },
      { id: 'location', label: 'Location', type: 'location', required: true },
      { id: 'products', label: 'Products of Interest', type: 'multiselect', options: ['Cables','Super Anamel', 'Busbar', 'LED Light', 'Acessories', 'Fan', 'Meter', 'Transformer','Switchgear','Sub Stations'], required: true },
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
      
    ],
  },
   corporate: {
    label: 'Corporate Client',
    icon: '🏢',
    color: 'from-violet-400 to-purple-600',
    accent: 'violet',
    description: 'Register your company as a client',
    fields: [
      { id: 'companyName', label: 'Company Name', type: 'text', placeholder: 'ABC Company', required: true },
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'designation', label: 'Designation', type: 'text', placeholder: 'General Manager', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'email', label: 'Email', type: 'email', placeholder: 'company@example.com', required: true },
      // { id: 'businessType', label: 'Business Type', type: 'select', options: ['Retail', 'Manufacturing', 'Service', 'Construction', 'Other'], required: true },
       { id: 'businessType', label: 'Business Type', type: 'dropdownWithText', options: ['Retail', 'Manufacturing', 'Service', 'Construction', 'Other'], required: true },
      { id: 'location', label: 'Location', type: 'location', required: true },
      { id: 'products', label: 'Products of Interest', type: 'multiselect', options: ['Cables','Super Anamel', 'Busbar', 'LED Light', 'Acessories', 'Fan', 'Meter', 'Transformer','Switchgear','Sub Stations'], required: false },
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
    ],
  },
   distributor: {
    label: 'Distributor',
    icon: '📦',
    color: 'from-emerald-400 to-teal-600',
    accent: 'emerald',
    description: 'Distributor registration portal',
    fields: [
      { id: 'dbName', label: 'Distributor Name', type: 'text', placeholder: 'Enter distributor name', required: true },
      { id: 'dbCode', label: 'DB Code', type: 'text', placeholder: 'Enter DB code', required: true },
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'email', label: 'Email', type: 'email', placeholder: 'optional@example.com', required: false },
      { id: 'location', label: 'Location', type: 'location', required: true },
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
    ],
  },
   franchiseSalesCentre: {
    label: 'Franchise Sales Centre',
    icon: '🏪',
    color: 'from-rose-400 to-pink-600',
    accent: 'rose',
    description: 'Field Service Center registration',
    fields: [
      { id: 'fscName', label: 'FSC Name', type: 'text', placeholder: 'Enter FSC name', required: true },
      { id: 'fscCode', label: 'FSC Code', type: 'text', placeholder: 'Enter FSC code', required: true },
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'email', label: 'Email', type: 'email', placeholder: 'optional@example.com', required: false },
      { id: 'location', label: 'Location', type: 'location', required: true },
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
    ],
  },
  engineer: {
    label: 'Engineer',
    icon: '🎓',
    color: 'from-sky-400 to-blue-600',
    accent: 'sky',
    description: 'Join as a professional engineer',
    fields: [
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'email', label: 'Email', type: 'email', placeholder: 'you@example.com', required: true },
      { id: 'companyName', label: 'Company Name', type: 'text', placeholder: 'ABC Company', required: true },
      { id: 'designation', label: 'Designation', type: 'text', placeholder: 'General Manager', required: true },
      { id: 'engineeringField', label: 'Engineering Field', type: 'dropdownWithText', options: ['Civil', 'Electrical', 'Mechanical', 'Computer', 'Other'], required: true },
      { id: 'location', label: 'Location', type: 'location', required: true },
      { id: 'institute', label: 'Institute Name', type: 'text', placeholder: 'Institute Name', required: true },
      { id: 'professionalId', label: 'Professional ID / Membership', type: 'text', placeholder: 'Optional', required: false },
      { id: 'products', label: 'Products of Interest', type: 'multiselect', options: ['Cables','Super Anamel', 'Busbar', 'LED Light', 'Acessories', 'Fan', 'Meter', 'Transformer','Switchgear','Sub Stations'], required: true },
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
    ],
  },
  electrician: {
    label: 'Electrician',
    icon: '⚡',
    color: 'from-amber-400 to-orange-500',
    accent: 'amber',
    description: 'Register as a certified electrician',
    fields: [
      { id: 'name', label: 'Full Name', type: 'text', placeholder: 'Ashikur Rahman', required: true },
      { id: 'mobile', label: 'Mobile Number', type: 'mobile', placeholder: '01XXXXXXXXX', required: true, hasOTP: true },
      { id: 'location', label: 'Location', type: 'location', required: true },
      { id: 'workType', label: 'Work Type', type: 'select', options: ['Residential', 'Commercial', 'Industrial'], required: true },
       { id: 'shamityName', label: 'Shamity Name', type: 'text', placeholder: 'Gazipur Electricin Shomity', required: false },
      { id: 'shamityId', label: 'Shamity ID', type: 'text', placeholder: '456', required: false },
      { id: 'products', label: 'Products of Interest', type: 'multiselect', options: ['Cables','Super Anamel', 'Busbar', 'LED Light', 'Acessories', 'Fan', 'Meter', 'Transformer','Switchgear','Sub Stations'], required: true },
     
      {id:'password', label: 'Password', type:'password', placeholder: 'Enter your password', required:true}
    ],
  },
};

// --- Accent Color Map ---
const accentMap: Record<AccentKey, { text: string; bg: string; border: string; ring: string; btn: string; chip: string }> = {
  lime: { text: 'text-lime-600', bg: 'bg-lime-50', border: 'border-lime-300', ring: 'focus:ring-lime-400', btn: 'bg-lime-500 hover:bg-lime-600', chip: 'bg-lime-500 border-lime-500' },
  amber: { text: 'text-amber-600', bg: 'bg-amber-50', border: 'border-orange-300', ring: 'focus:ring-amber-400', btn: 'bg-amber-500 hover:bg-amber-600', chip: 'bg-amber-500 border-amber-500' },
  sky: { text: 'text-sky-600', bg: 'bg-sky-50', border: 'border-sky-300', ring: 'focus:ring-sky-400', btn: 'bg-sky-500 hover:bg-sky-600', chip: 'bg-sky-500 border-sky-500' },
  violet: { text: 'text-violet-600', bg: 'bg-violet-50', border: 'border-violet-300', ring: 'focus:ring-violet-400', btn: 'bg-violet-500 hover:bg-violet-600', chip: 'bg-violet-500 border-violet-500' },
  emerald: { text: 'text-emerald-600', bg: 'bg-emerald-50', border: 'border-emerald-300', ring: 'focus:ring-emerald-400', btn: 'bg-emerald-500 hover:bg-emerald-600', chip: 'bg-emerald-500 border-emerald-500' },
  rose: { text: 'text-rose-600', bg: 'bg-rose-50', border: 'border-rose-300', ring: 'focus:ring-rose-400', btn: 'bg-rose-500 hover:bg-rose-600', chip: 'bg-rose-500 border-rose-500' },
};

// --- Custom SVG Icons ---
const icons: Record<IconName, React.ReactNode> = {
  user: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />,
  phone: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />,
  mail: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />,
  location: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />,
  briefcase: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />,
  check: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />,
  arrow: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />,
  grid: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />,
};

const Icon = ({ name, className = 'w-5 h-5' }: { name: IconName; className?: string }) => {
  return (
    <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      {icons[name]}
    </svg>
  );
};

// --- Location Selector ---
const LocationInput = ({ value, onChange, required, accent }: { value?: LocationValue; onChange: (next: LocationValue) => void; required?: boolean; accent: AccentKey }) => {
  const a = accentMap[accent];

 const divisions = ["Dhaka", "Chattogram", "Rajshahi", "Khulna", "Barishal", "Sylhet", "Rangpur", "Mymensingh"];

const districtsByDivision: Record<string, string[]> = {
  Dhaka: ["Dhaka", "Faridpur", "Gazipur", "Gopalganj", "Kishoreganj", "Madaripur", "Manikganj", "Munshiganj", "Narayanganj", "Narsingdi", "Rajbari", "Shariatpur", "Tangail"],
  Chattogram: ["Chattogram", "Bandarban", "Brahmanbaria", "Chandpur", "Cumilla", "Cox's Bazar", "Feni", "Khagrachhari", "Lakshmipur", "Noakhali", "Rangamati"],
  Rajshahi: ["Rajshahi", "Bogura", "Joypurhat", "Naogaon", "Natore", "Chapainawabganj", "Pabna", "Sirajganj"],
  Khulna: ["Khulna", "Bagerhat", "Chuadanga", "Jashore", "Jhenaidah", "Kushtia", "Magura", "Meherpur", "Narail", "Satkhira"],
  Barishal: ["Barishal", "Barguna", "Bhola", "Jhalokathi", "Patuakhali", "Pirojpur"],
  Sylhet: ["Sylhet", "Habiganj", "Moulvibazar", "Sunamganj"],
  Rangpur: ["Rangpur", "Dinajpur", "Gaibandha", "Kurigram", "Lalmonirhat", "Nilphamari", "Panchagarh", "Thakurgaon"],
  Mymensingh: ["Mymensingh", "Jamalpur", "Netrokona", "Sherpur"],
};

 const upazilaByDistrict: Record<string, string[]> = {
  Dhaka: ["Dhamrai", "Dohar", "Keraniganj", "Nawabganj", "Savar"],
  Faridpur: ["Faridpur Sadar", "Boalmari", "Alfadanga", "Madhukhali", "Bhanga", "Nagarkanda", "Sadarpur", "Charbhadrasan", "Saltha"],
  Gazipur: ["Gazipur Sadar", "Kaliakair", "Kaliganj", "Kapasia", "Sreepur"],
  Gopalganj: ["Gopalganj Sadar", "Kashiani", "Kotalipara", "Muksudpur", "Tungipara"],
  Kishoreganj: ["Kishoreganj Sadar", "Bajitpur", "Bhairab", "Hossainpur", "Itna", "Karimganj", "Katiadi", "Kuliarchar", "Mithamoin", "Nikli", "Pakundia", "Tarail"],
  Madaripur: ["Madaripur Sadar", "Kalkini", "Rajoir", "Shibchar"],
  Manikganj: ["Manikganj Sadar", "Daulatpur", "Ghior", "Harirampur", "Saturia", "Shibalaya", "Singair"],
  Munshiganj: ["Munshiganj Sadar", "Gazaria", "Lohajang", "Sirajdikhan", "Sreenagar", "Tongibari"],
  Narayanganj: ["Narayanganj Sadar", "Araihazar", "Bandar", "Rupganj", "Sonargaon"],
  Narsingdi: ["Narsingdi Sadar", "Belabo", "Monohardi", "Palash", "Raipura", "Shibpur"],
  Rajbari: ["Rajbari Sadar", "Baliakandi", "Goalandaghat", "Kalukhali", "Pangsha"],
  Shariatpur: ["Shariatpur Sadar", "Bhedarganj", "Damudya", "Gosairhat", "Naria", "Zajira"],
  Tangail: ["Tangail Sadar", "Basail", "Bhuapur", "Delduar", "Dhanbari", "Ghatail", "Gopalpur", "Kalihati", "Madhupur", "Mirzapur", "Nagarpur", "Sakhipur"],

  Chattogram: ["Anwara", "Banshkhali", "Boalkhali", "Chandanaish", "Fatikchhari", "Hathazari", "Lohagara", "Mirsharai", "Patiya", "Rangunia", "Raozan", "Sandwip", "Satkania", "Sitakunda"],
  Bandarban: ["Bandarban Sadar", "Alikadam", "Lama", "Naikhongchhari", "Rowangchhari", "Ruma", "Thanchi"],
  Brahmanbaria: ["Brahmanbaria Sadar", "Akhaura", "Ashuganj", "Bancharampur", "Bijoynagar", "Kasba", "Nabinagar", "Nasirnagar", "Sarail"],
  Chandpur: ["Chandpur Sadar", "Faridganj", "Haimchar", "Haziganj", "Kachua", "Matlab North", "Matlab South", "Shahrasti"],
  Cumilla: ["Cumilla Adarsha Sadar", "Barura", "Brahmanpara", "Burichang", "Chandina", "Chauddagram", "Daudkandi", "Debidwar", "Homna", "Laksam", "Meghna", "Monohargonj", "Muradnagar", "Nangalkot", "Titas"],
  "Cox's Bazar": ["Cox's Bazar Sadar", "Chakaria", "Kutubdia", "Maheshkhali", "Pekua", "Ramu", "Teknaf", "Ukhia"],
  Feni: ["Feni Sadar", "Chhagalnaiya", "Daganbhuiyan", "Fulgazi", "Parshuram", "Sonagazi"],
  Khagrachhari: ["Khagrachhari Sadar", "Dighinala", "Lakshmichhari", "Mahalchhari", "Manikchhari", "Matiranga", "Panchhari", "Ramgarh"],
  Lakshmipur: ["Lakshmipur Sadar", "Kamalnagar", "Raipur", "Ramganj", "Ramgati"],
  Noakhali: ["Noakhali Sadar", "Begumganj", "Chatkhil", "Companiganj", "Hatiya", "Kabirhat", "Senbagh", "Sonaimuri", "Subarnachar"],
  Rangamati: ["Rangamati Sadar", "Baghaichhari", "Barkal", "Belaichhari", "Juraichhari", "Kaptai", "Kaukhali", "Langadu", "Naniarchar", "Rajasthali"],

  Rajshahi: ["Bagha", "Bagmara", "Charghat", "Durgapur", "Godagari", "Mohanpur", "Paba", "Puthia", "Tanore"],
  Bogura: ["Bogura Sadar", "Adamdighi", "Dhunat", "Dhupchanchia", "Gabtali", "Kahaloo", "Nandigram", "Sariakandi", "Shajahanpur", "Sherpur", "Shibganj", "Sonatala"],
  Joypurhat: ["Joypurhat Sadar", "Akkelpur", "Kalai", "Khetlal", "Panchbibi"],
  Naogaon: ["Naogaon Sadar", "Atrai", "Badalgachhi", "Dhamoirhat", "Manda", "Mahadebpur", "Niamatpur", "Patnitala", "Porsha", "Raninagar", "Sapahar"],
  Natore: ["Natore Sadar", "Bagatipara", "Baraigram", "Gurudaspur", "Lalpur", "Singra"],
  Chapainawabganj: ["Chapainawabganj Sadar", "Bholahat", "Gomastapur", "Nachole", "Shibganj"],
  Pabna: ["Pabna Sadar", "Atgharia", "Bera", "Bhangura", "Chatmohar", "Faridpur", "Ishwardi", "Santhia", "Sujanagar"],
  Sirajganj: ["Sirajganj Sadar", "Belkuchi", "Chauhali", "Kamarkhanda", "Kazipur", "Raiganj", "Shahjadpur", "Tarash", "Ullahpara"],

  Khulna: ["Batiaghata", "Dacope", "Dighalia", "Dumuria", "Koyra", "Paikgachha", "Phultala", "Rupsa", "Terokhada"],
  Bagerhat: ["Bagerhat Sadar", "Chitalmari", "Fakirhat", "Kachua", "Mollahat", "Mongla", "Morrelganj", "Rampal", "Sarankhola"],
  Chuadanga: ["Chuadanga Sadar", "Alamdanga", "Damurhuda", "Jibannagar"],
  Jashore: ["Jashore Sadar", "Abhaynagar", "Bagherpara", "Chaugachha", "Jhikargachha", "Keshabpur", "Manirampur", "Sharsha"],
  Jhenaidah: ["Jhenaidah Sadar", "Harinakunda", "Kaliganj", "Kotchandpur", "Maheshpur", "Shailkupa"],
  Kushtia: ["Kushtia Sadar", "Bheramara", "Daulatpur", "Khoksa", "Kumarkhali", "Mirpur"],
  Magura: ["Magura Sadar", "Mohammadpur", "Shalikha", "Sreepur"],
  Meherpur: ["Meherpur Sadar", "Gangni", "Mujibnagar"],
  Narail: ["Narail Sadar", "Kalia", "Lohagara"],
  Satkhira: ["Satkhira Sadar", "Assasuni", "Debhata", "Kalaroa", "Kaliganj", "Shyamnagar", "Tala"],

  Barishal: ["Barishal Sadar", "Agailjhara", "Babuganj", "Bakerganj", "Banaripara", "Gaurnadi", "Hizla", "Mehendiganj", "Muladi", "Wazirpur"],
  Barguna: ["Barguna Sadar", "Amtali", "Bamna", "Betagi", "Patharghata", "Taltali"],
  Bhola: ["Bhola Sadar", "Borhanuddin", "Char Fasson", "Daulatkhan", "Lalmohan", "Manpura", "Tazumuddin"],
  Jhalokathi: ["Jhalokathi Sadar", "Kathalia", "Nalchity", "Rajapur"],
  Patuakhali: ["Patuakhali Sadar", "Bauphal", "Dashmina", "Dumki", "Galachipa", "Kalapara", "Mirzaganj", "Rangabali"],
  Pirojpur: ["Pirojpur Sadar", "Bhandaria", "Kawkhali", "Mathbaria", "Nazirpur", "Nesarabad", "Zianagar"],

  Sylhet: ["Sylhet Sadar", "Balaganj", "Beanibazar", "Bishwanath", "Companiganj", "Fenchuganj", "Golapganj", "Gowainghat", "Jaintiapur", "Kanaighat", "Osmani Nagar", "South Surma", "Zakiganj"],
  Habiganj: ["Habiganj Sadar", "Ajmiriganj", "Bahubal", "Baniachong", "Chunarughat", "Lakhai", "Madhabpur", "Nabiganj", "Shayestaganj"],
  Moulvibazar: ["Moulvibazar Sadar", "Barlekha", "Juri", "Kamalganj", "Kulaura", "Rajnagar", "Sreemangal"],
  Sunamganj: ["Sunamganj Sadar", "Bishwambharpur", "Chhatak", "Derai", "Dharampasha", "Dowarabazar", "Jagannathpur", "Jamalganj", "Madhyanagar", "Shalla", "Shantiganj", "Tahirpur"],

  Rangpur: ["Rangpur Sadar", "Badarganj", "Gangachara", "Kaunia", "Mithapukur", "Pirgachha", "Pirganj", "Taraganj"],
  Dinajpur: ["Dinajpur Sadar", "Birampur", "Birganj", "Biral", "Bochaganj", "Chirirbandar", "Phulbari", "Ghoraghat", "Hakimpur", "Kaharole", "Khansama", "Nawabganj", "Parbatipur"],
  Gaibandha: ["Gaibandha Sadar", "Fulchhari", "Gobindaganj", "Palashbari", "Sadullapur", "Saghata", "Sundarganj"],
  Kurigram: ["Kurigram Sadar", "Bhurungamari", "Char Rajibpur", "Chilmari", "Phulbari", "Nageshwari", "Rajarhat", "Raumari", "Ulipur"],
  Lalmonirhat: ["Lalmonirhat Sadar", "Aditmari", "Hatibandha", "Kaliganj", "Patgram"],
  Nilphamari: ["Nilphamari Sadar", "Dimla", "Domar", "Jaldhaka", "Kishoreganj", "Saidpur"],
  Panchagarh: ["Panchagarh Sadar", "Atwari", "Boda", "Debiganj", "Tetulia"],
  Thakurgaon: ["Thakurgaon Sadar", "Baliadangi", "Haripur", "Pirganj", "Ranisankail"],

  Mymensingh: ["Mymensingh Sadar", "Bhaluka", "Dhobaura", "Fulbaria", "Gaffargaon", "Gauripur", "Haluaghat", "Ishwarganj", "Muktagachha", "Nandail", "Phulpur", "Tarakanda", "Trishal"],
  Jamalpur: ["Jamalpur Sadar", "Baksiganj", "Dewanganj", "Islampur", "Madarganj", "Melandaha", "Sarishabari"],
  Netrokona: ["Netrokona Sadar", "Atpara", "Barhatta", "Durgapur", "Kalmakanda", "Kendua", "Khaliajuri", "Madan", "Mohanganj", "Purbadhala"],
  Sherpur: ["Sherpur Sadar", "Jhenaigati", "Nakla", "Nalitabari", "Sreebardi"],
  };

  const currentDivision = value?.division || '';
  const currentDistrict = value?.district || '';
  const currentUpazila = value?.upazila || '';
  const availableDistrict = currentDivision ? districtsByDivision[currentDivision] || [] : [];
  const availableUpazila = currentDistrict ?  upazilaByDistrict[currentDistrict] || [] : [];

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
      <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <Icon name="location" className="w-4 h-4 text-gray-400" />
        </div>
        <select
          value={currentDivision}
          onChange={(e) => onChange({ division: e.target.value, district: '' })}
          required={required}
          className={`w-full pl-9 pr-8 py-3 bg-white border-2 rounded-xl text-sm font-medium text-gray-700 outline-none transition-all appearance-none cursor-pointer ${a.border} focus:ring-2 ${a.ring} focus:border-transparent`}
        >
          <option value="">Division</option>
          {divisions.map((d) => <option key={d} value={d}>{d}</option>)}
        </select>
        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
        </div>
      </div>
      <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>
        </div>
        <select
          value={currentDistrict}
          onChange={(e) => onChange({ ...(value || {}), division: currentDivision, district: e.target.value })}
          required={required}
          disabled={!currentDivision}
          className={`w-full pl-9 pr-8 py-3 bg-white border-2 rounded-xl text-sm font-medium text-gray-700 outline-none transition-all appearance-none cursor-pointer ${a.border} focus:ring-2 ${a.ring} focus:border-transparent disabled:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-60`}
        >
          <option value="">District</option>
          {availableDistrict.map((district: string) => <option key={district} value={district}>{district}</option>)}
        </select>
        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
        </div>
      </div>
      <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>
        </div>
        <select
          value={currentUpazila}
          onChange={(e) => onChange({ ...(value || {}), district: currentDistrict, upazila: e.target.value })}
          required={required}
          disabled={!currentDistrict}
          className={`w-full pl-9 pr-8 py-3 bg-white border-2 rounded-xl text-sm font-medium text-gray-700 outline-none transition-all appearance-none cursor-pointer ${a.border} focus:ring-2 ${a.ring} focus:border-transparent disabled:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-60`}
        >
          <option value="">Upazila</option>
          {availableUpazila.map((upazila: string) => <option key={upazila} value={upazila}>{upazila}</option>)}
        </select>
        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
        </div>
      </div>
    </div>
  );
};

// --- Multi-select Chips ---
const MultiSelect = ({ options, value = [], onChange, accent }: { options: string[]; value?: string[]; onChange: (value: string[]) => void; accent: AccentKey }) => {
  const a = accentMap[accent];
  const toggle = (opt: string) => onChange(value.includes(opt) ? value.filter((v: string) => v !== opt) : [...value, opt]);
  return (
    <div className="flex flex-wrap gap-2">
      {options.map((opt: string) => {
        const selected = value.includes(opt);
        return (
          <button
            key={opt}
            type="button"
            onClick={() => toggle(opt)}
            className={`group relative px-4 py-2.5 rounded-xl text-sm font-semibold border-2 transition-all duration-200 flex items-center gap-2 ${
              selected
                ? `${a.chip} text-white shadow-lg scale-105`
                : 'bg-white border-gray-200 text-gray-600 hover:border-gray-300 hover:shadow-sm'
            }`}
          >
            {selected && <Icon name="check" className="w-4 h-4" />}
            {opt}
          </button>
        );
      })}
    </div>
  );
};

// --- OTP Verification ---
// const OTPInput = ({ onVerify, verified, accent }: { onVerify: (value: boolean) => void; verified: boolean; accent: AccentKey }) => {
//   const a = accentMap[accent];
//   const [otp, setOtp] = useState<string>('');
//   const [showOtp, setShowOtp] = useState<boolean>(false);
//   const [generatedOtp] = useState<string>('123456');

//   if (verified) {
//     return (
//       <div className="flex items-center gap-2 mt-3 px-3 py-2 bg-green-50 border border-green-200 rounded-lg">
//         <div className="w-5 h-5 bg-green-500 rounded-full flex items-center justify-center shrink-0">
//           <Icon name="check" className="w-3 h-3 text-white" />
//         </div>
//         <span className="text-sm font-semibold text-green-700">Mobile number verified</span>
//       </div>
//     );
//   }

//   return (
//     <div className="mt-3">
//       {!showOtp ? (
//         <button
//           type="button"
//           onClick={() => { setShowOtp(true); alert(`OTP sent! (Demo: ${generatedOtp})`); }}
//           className={`text-sm font-semibold ${a.text} hover:underline flex items-center gap-1`}
//         >
//           Send OTP <Icon name="arrow" className="w-3 h-3" />
//         </button>
//       ) : (
//         <div className="flex gap-2 items-center">
//           <input
//             type="text"
//             value={otp}
//             onChange={(e) => setOtp(e.target.value)}
//             placeholder="6-digit OTP"
//             maxLength={6}
//             className={`w-32 px-3 py-2 border-2 ${a.border} rounded-lg focus:ring-2 ${a.ring} outline-none text-sm font-mono tracking-widest text-center`}
//           />
//           <button
//             type="button"
//             onClick={() => otp === generatedOtp ? (onVerify(true), alert('Verified!')) : alert('Invalid OTP')}
//             className={`px-4 py-2 ${a.btn} text-white text-sm font-semibold rounded-lg transition shadow-sm`}
//           >
//             Verify
//           </button>
//         </div>
//       )}
//     </div>
//   );
// };


const OTPInput = ({
  mobile,
  onVerify,
  verified,
  accent,
}: {
  mobile: string;
  onVerify: (value: boolean) => void;
  verified: boolean;
  accent: AccentKey;
}) => {
  const a = accentMap[accent];

  const [otp, setOtp] = useState<string>('');
  const [otpSent, setOtpSent] = useState<boolean>(false);
  const [otpLoading, setOtpLoading] = useState<boolean>(false);
  const [otpTimeLeft, setOtpTimeLeft] = useState(0);
  const [otpExpiresAt, setOtpExpiresAt] = useState<number | null>(null);

  // const handleSendOtp = async () => {
  //   if (!mobile) {
  //     toast("Please enter your mobile number.", {
  //       position: "top-right",
  //       className: "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
  //     });
  //     return;
  //   }

  //   setOtpLoading(true);

  //   try {
  //     await sendOtp(mobile);
  //     setOtpSent(true);
  //     onVerify(false);
  //     toast("OTP sent successfully.", {
  //       position: "top-right",
  //       className: "!bg-gradient-to-r !from-lime-600 !via-lime-500 !to-lime-400 !text-white !border-none !text-base !py-3",
  //       });
  //   } catch (error: any) {
  //     toast(error?.message || 'Failed to send OTP.', {
  //       position: "top-right",
  //       className: "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
  //     });
  //   } finally {
  //     setOtpLoading(false);
  //   }
  // };


  const handleSendOtp = async () => {
  if (!mobile) {
    toast("Please enter your mobile number.", {
      position: "top-right",
      className:
        "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
    });
    return;
  }

  setOtpLoading(true);

  try {
    const result = await sendOtp(mobile);
    const expiresAt = Date.parse(result.expiresAt);

    setOtpSent(true);
    setOtp('');
    onVerify(false);
    setOtpExpiresAt(expiresAt);
    setOtpTimeLeft(Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000)));

    toast("OTP sent successfully.", {
      position: "top-right",
      className:
        "!bg-gradient-to-r !from-lime-600 !via-lime-500 !to-lime-400 !text-white !border-none !text-base !py-3",
    });
  } catch (error: unknown) {
    toast(error instanceof Error ? error.message : "Failed to send OTP.", {
      position: "top-right",
      className:
        "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
    });
  } finally {
    setOtpLoading(false);
  }
};
  useEffect(() => {
    if (otpExpiresAt === null) return;

    const updateTimeLeft = () => {
      const remaining = Math.max(
        0,
        Math.ceil((otpExpiresAt - Date.now()) / 1000),
      );
      setOtpTimeLeft(remaining);
      return remaining;
    };

    updateTimeLeft();

    const timer = setInterval(() => {
      if (updateTimeLeft() === 0) {
        clearInterval(timer);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [otpExpiresAt]);

const formatOtpTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  return `${minutes}:${remainingSeconds
    .toString()
    .padStart(2, "0")}`;
};

const handleResendOtp = async () => {
  await handleSendOtp();
};

  const handleVerifyOtp = async () => {
    if (!otp) {
      alert('Please enter OTP.');
      return;
    }

    if (otp.length !== 6) {
      alert('Please enter a valid 6 digit OTP.');
      return;
    }

    setOtpLoading(true);

    try {
      const result = await verifyOtp(mobile, otp);

      if (result.verified) {
        onVerify(true);
        setOtpSent(true);
        toast("Mobile number verified successfully.", {
        position: "top-right",
        className: "!bg-gradient-to-r !from-lime-600 !via-lime-500 !to-lime-400 !text-white !border-none !text-base !py-3",
      });
      } else {
        onVerify(false);
        
        alert('Invalid OTP.');
      }
    } catch (error: any) {
      onVerify(false);
      toast(error?.message || 'OTP verification failed.', {
        position: "top-right",
        className: "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
      });
    } finally {
      setOtpLoading(false);
    }
  };

  if (verified) {
    return (
      <div className="flex items-center gap-2 mt-3 px-3 py-2 bg-green-50 border border-green-200 rounded-lg">
        <div className="w-5 h-5 bg-green-500 rounded-full flex items-center justify-center shrink-0">
          <Icon name="check" className="w-3 h-3 text-white" />
        </div>

        <span className="text-sm font-semibold text-green-700">
          Mobile number verified
        </span>
      </div>
    );
  }

  return (
    <div className="mt-3 space-y-3">
      {!otpSent ? (
        <button
          type="button"
          onClick={handleSendOtp}
          disabled={otpLoading}
          className={`text-sm font-semibold ${a.text} hover:underline flex items-center gap-1 disabled:opacity-50 disabled:cursor-not-allowed`}
        >
          {otpLoading ? (
            'Sending...'
          ) : (
            <>
              Send OTP
              <Icon name="arrow" className="w-3 h-3" />
            </>
          )}
        </button>
      ) : (
        <>
        <div className="flex gap-2 items-center">
          <input
            type="text"
            inputMode="numeric"
            value={otp}
            onChange={(e) => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
            placeholder="6-digit OTP"
            maxLength={6}
            disabled={otpLoading}
            className={`w-32 px-3 py-2 border-2 ${a.border} rounded-lg focus:ring-2 ${a.ring} outline-none text-sm font-mono tracking-widest text-center disabled:bg-gray-100 disabled:cursor-not-allowed`}
          />

          <button
            type="button"
            onClick={handleVerifyOtp}
            disabled={otpLoading || otp.length !== 6}
            className={`px-4 py-2 ${a.btn} text-white text-sm font-semibold rounded-lg transition shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`}
          >
            {otpLoading ? 'Verifying...' : 'Verify'}
          </button>
        </div>

        <div className="flex items-center justify-between mt-2">
          {otpTimeLeft > 0 ? (
            <span className="text-sm text-gray-500">
              OTP expires in{" "}
              <span className={`font-semibold ${a.text}`}>
                {formatOtpTime(otpTimeLeft)}
              </span>
            </span>
          ) : (
            <span className="text-sm text-red-500 font-medium">
              OTP expired
            </span>
          )}

          {otpTimeLeft === 0 && (
            <button
              type="button"
              onClick={handleResendOtp}
              disabled={otpLoading}
              className={`text-sm font-semibold ${a.text} hover:underline disabled:opacity-50`}
            >
              {otpLoading ? "Sending..." : "Resend OTP"}
            </button>
          )}
        </div>
        
        </>
        
        
      )}
    </div>
  );
};


// --- Dropdown + Text ---
const DropdownWithText = ({ options, value, onChange, required, accent }: { options: string[]; value?: DropdownValue; onChange: (next: DropdownValue) => void; required?: boolean; accent: AccentKey }) => {
  const a = accentMap[accent];
  const selectedOption = value?.option || '';
  const customText = value?.text || '';

  return (
    <div className="space-y-3">
      <div className="relative">
        <select
          value={selectedOption}
          onChange={(e) => onChange({ option: e.target.value, text: e.target.value === 'Other' ? customText : '' })}
          required={required}
          className={`w-full px-4 py-3 bg-white border-2 ${a.border} rounded-xl text-sm font-medium text-gray-700 outline-none focus:ring-2 ${a.ring} focus:border-transparent transition-all appearance-none cursor-pointer`}
        >
          <option value="">Select Field</option>
          {options.map((opt: string) => <option key={opt} value={opt}>{opt}</option>)}
        </select>
        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
          <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
        </div>
      </div>
      {selectedOption === 'Other' && (
        <input
          type="text"
          value={customText}
          onChange={(e) => onChange({ option: selectedOption, text: e.target.value })}
          placeholder="Please specify your field"
          required={required}
          className={`w-full px-4 py-3 bg-white border-2 ${a.border} rounded-xl text-sm text-gray-700 outline-none focus:ring-2 ${a.ring} focus:border-transparent transition-all`}
        />
      )}
    </div>
  );
};

// --- Field Wrapper with Icon ---
const FieldWrapper = ({ icon, label, required = false, children, error }: { icon?: React.ReactNode; label: string; required?: boolean; children: React.ReactNode; error?: string }) => (
  <div className="space-y-2">
    <label className="flex items-center gap-2 text-sm font-bold text-gray-700">
      {icon && <span className="text-gray-400">{icon}</span>}
      {label}
      {required && <span className="text-red-500">*</span>}
    </label>
    {children}
    {error && (
      <p className="text-xs font-semibold text-red-500 flex items-center gap-1">
        <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" /></svg>
        {error}
      </p>
    )}

  </div>
);

// --- Main Form ---
const EmployeeRegistrationForm = () => {
  const [selectedRole, setSelectedRole] = useState<string>('guest');
  const [formData, setFormData] = useState<FormData>({});
  const [errors, setErrors] = useState<ErrorMap>({});
  const [submitted, setSubmitted] = useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [otpVerified, setOtpVerified] = useState<boolean>(false);

  const currentConfig = registrationConfig[selectedRole];
  const a = accentMap[currentConfig.accent];

  const normalizeRegistrationRole = (role: string) => {
    if (role === 'franchiseSalesCentre') return 'fsc';
    return role;
  };

  const handleRoleChange = (role: string) => {
    setSelectedRole(role);
    setFormData({});
    setErrors({});
    setOtpVerified(false);
    setSubmitted(false);
  };

  const handleInputChange = (fieldId: string, value: FormValue) => {
    setFormData((prev) => ({ ...prev, [fieldId]: value }));
    if (errors[fieldId]) setErrors((prev) => ({ ...prev, [fieldId]: '' }));
  };
  

  const validateForm = () => {
    const newErrors: ErrorMap = {};
    currentConfig.fields.forEach((field: RegistrationField) => {
      if (field.required) {
        const val = formData[field.id];
        if (field.type === 'location') {
          const locationValue =
            val && typeof val === 'object'
              ? (val as LocationValue)
              : {};

          if (
            !locationValue.division ||
            !locationValue.district ||
            !locationValue.upazila
          ) {
            newErrors[field.id] =
              'Please select division, district and upazila.';
          }
        }else if (field.type === 'multiselect') {
          if (!val || !Array.isArray(val) || val.length === 0) newErrors[field.id] = 'Select at least one option.';
        } else if (field.type === 'dropdownWithText') {
          const dropdownValue = val && typeof val === 'object' ? val as DropdownValue : {};
          if (!dropdownValue.option || (dropdownValue.option === 'Other' && !dropdownValue.text)) newErrors[field.id] = 'Please complete this field.';
        } else if (!val || (typeof val === 'string' && val.trim() === '')) {
          newErrors[field.id] = 'This field is required.';
        }
      }
    });
    if (currentConfig.fields.some((f: RegistrationField) => f.id === 'mobile' && f.type === 'mobile' && f.hasOTP) && !otpVerified) {
      newErrors['otp'] = 'Please verify your mobile number.';
    }
     if (currentConfig.fields.some((f: RegistrationField) => f.id === 'password' && f.type === 'password' && f.hasOTP) && !otpVerified) {
      newErrors['otp'] = 'Please verify your mobile number.';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (
    e: React.FormEvent<HTMLFormElement>,
  ) => {
    e.preventDefault();

    if (isSubmitting) return;

    const isValid = validateForm();

    if (!isValid) {
      return;
    }

    setIsSubmitting(true);

    try {
      const engineeringField = formData.engineeringField;

      const engineeringFieldValue =
        engineeringField &&
        typeof engineeringField === 'object' &&
        !Array.isArray(engineeringField)
          ? (engineeringField as DropdownValue)
          : undefined;

      const businessType = formData.businessType;

      const businessTypeValue = businessType && typeof businessType === 'object' && 
      !Array.isArray(businessType)
      ? (businessType as DropdownValue)
      : undefined;

      const locationValue = formData.location && typeof formData.location === 'object' && !Array.isArray(formData.location)
      ? (formData.location as LocationValue) 
      : {};

      const nameValue =
        typeof formData.name === 'string' && formData.name.trim()
          ? formData.name.trim()
          : typeof formData.contactPerson === 'string' && formData.contactPerson.trim()
            ? formData.contactPerson.trim()
            : typeof formData.companyName === 'string' && formData.companyName.trim()
              ? formData.companyName.trim()
              : typeof formData.dbName === 'string' && formData.dbName.trim()
                ? formData.dbName.trim()
                : typeof formData.fscName === 'string' && formData.fscName.trim()
                  ? formData.fscName.trim()
                  : '';

      

      const payload = {
        ...formData,
        registrationType: normalizeRegistrationRole(selectedRole),
        name: nameValue,

        division: locationValue.division,
        district: locationValue.district,
        upazila: locationValue.upazila,

        engineeringField:
          engineeringFieldValue?.option === 'Other'
            ? engineeringFieldValue.text
            : engineeringFieldValue?.option,

        businessType: 
          businessTypeValue?.option === 'Other'
          ? businessTypeValue.text
          : businessTypeValue?.option,
      };

      console.log('Registration payload:', payload);

      console.log(
        'Division',
        payload.division,

        'District',
        payload.district,

        'Upazila',
        payload.upazila
      )

      console.log(
        'engineeringField:',
        payload.engineeringField,
        'type:',
        typeof payload.engineeringField,
      );

      console.log(
        'businessType:',
        payload.businessType,
        'type:',
        typeof payload.businessType,
      );

      const result = await createRegistration(payload);

      console.log('Registration Success:', result);

      setSubmitted(true);
    } catch (error: unknown) {
      console.error('Registration Error:', error);

      const message =
        error instanceof Error
          ? error.message
          : 'Something went wrong';

      toast(message , {
        position: "top-right",
        className: "!bg-gradient-to-r !from-orange-600 !via-orange-600 !to-orange-500 !text-white !border-none !text-base !py-3",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const getFieldIcon = (field: RegistrationField) => {
    if (field.type === 'mobile') return <Icon name="phone" className="w-4 h-4" />;
    if (field.type === 'email') return <Icon name="mail" className="w-4 h-4" />;
    if (field.type === 'location') return <Icon name="location" className="w-4 h-4" />;
    if (field.id.toLowerCase().includes('name')) return <Icon name="user" className="w-4 h-4" />;
    if (field.id.toLowerCase().includes('company') || field.id.toLowerCase().includes('designation')) return <Icon name="briefcase" className="w-4 h-4" />;
    if (field.type === 'multiselect') return <Icon name="grid" className="w-4 h-4" />;
    return null;
  };

  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({});

  const togglePassword = (fieldId: string) => {
    setShowPasswords(prev => ({ ...prev, [fieldId]: !prev[fieldId] }));
  };


  const renderField = (field: RegistrationField) => {
    const value = formData[field.id];
    const error = errors[field.id];
    const stringValue = typeof value === 'string' ? value : '';

    const inputClass = `w-full px-4 py-3 bg-white border-2 rounded-xl text-sm font-medium text-gray-700 outline-none transition-all placeholder-gray-400 ${
      error ? 'border-red-300 focus:ring-2 focus:ring-red-400' : `${a.border} focus:ring-2 ${a.ring} focus:border-transparent`
    }`;

    switch (field.type) {
      case 'text':
      case 'email':
      case 'password':
      const show = showPasswords[field.id] || false;
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <div className='relative'>
              <input
              type={field.type ==='password' ? show ? 'text' : 'password' : field.type }
              value={stringValue}
              onChange={(e) => handleInputChange(field.id, e.target.value)}
              placeholder={field.placeholder}
              className={`${inputClass} ${field.type === 'password' ? 'pr-11' : ''}`}
              />

              {field.type === 'password' && (
                <button type='button' onClick={()=> togglePassword(field.id)} className='absolute px-2 py-1.5 cursor-pointer rounded-md bg-gray-100 right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-500 transition-color' aria-label={show ? 'Hide password' : 'Show password'}>
                  {
                    show ? (
                      <EyeOff className='w-4 h-4'></EyeOff>
                    ) :
                    <Eye className='w-4 h-4'/>
                  }
                </button>
              )}

            </div>
          </FieldWrapper>
        );
      case 'mobile':
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <input
              type="tel"
              value={stringValue}
              onChange={(e) => handleInputChange(field.id, e.target.value)}
              placeholder={field.placeholder}
              className={inputClass}
            />
            {field.hasOTP && (
              <OTPInput
                mobile={typeof formData.mobile === 'string' ? formData.mobile : ''}
                onVerify={setOtpVerified}
                verified={otpVerified}
                accent={currentConfig.accent}
              />
            )}
            {errors['otp'] && <p className="text-xs font-semibold text-red-500 mt-1">{errors['otp']}</p>}
          </FieldWrapper>
        );
      case 'select':
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <div className="relative">
              <select
                value={stringValue}
                onChange={(e) => handleInputChange(field.id, e.target.value)}
                className={`${inputClass} appearance-none cursor-pointer pr-10`}
              >
                <option value="">Select {field.label}</option>
                {field.options.map((opt: string) => <option key={opt} value={opt}>{opt}</option>)}
              </select>
              <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
              </div>
            </div>
          </FieldWrapper>
        );
      case 'multiselect':
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <MultiSelect
              options={field.options}
              value={Array.isArray(value) ? value : []}
              onChange={(v) => handleInputChange(field.id, v)}
              accent={currentConfig.accent}
            />
          </FieldWrapper>
        );
      case 'location':
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <LocationInput
              value={value && typeof value === 'object' ? value as LocationValue : {}}
              onChange={(v) => handleInputChange(field.id, v)}
              required={field.required}
              accent={currentConfig.accent}
            />
          </FieldWrapper>
        );
      case 'dropdownWithText':
        return (
          <FieldWrapper icon={getFieldIcon(field)} label={field.label} required={field.required} error={error}>
            <DropdownWithText
              options={field.options}
              value={value && typeof value === 'object' ? value as DropdownValue : {}}
              onChange={(v) => handleInputChange(field.id, v)}
              required={field.required}
              accent={currentConfig.accent}
            />
          </FieldWrapper>
        );
      default:
        return null;
    }
  };

  // Success screen
  if (submitted) {
    return (
      <div className="min-h-screen bg-slate-100 flex items-center justify-center p-4">
        <div className="max-w-md w-full bg-white rounded-3xl shadow-2xl shadow-slate-300/50 border border-slate-200 p-10 text-center">
          <div className={`w-20 h-20 mx-auto rounded-full bg-linear-to-br ${currentConfig.color} flex items-center justify-center mb-6 shadow-lg`}>
            <Icon name="check" className="w-10 h-10 text-white" />
          </div>
          <h2 className="text-2xl font-bold text-slate-800 mb-2">Registration Complete!</h2>
          <p className="text-slate-500 mb-8">
            You've successfully registered as a <span className={`font-bold ${a.text}`}>{currentConfig.label}</span>.
          </p>
          <button
            onClick={() => { setSubmitted(false); setFormData({}); setOtpVerified(false); }}
            className={`px-8 py-3 ${a.btn} text-white font-semibold rounded-xl transition shadow-lg hover:shadow-xl`}
          >
            Register Another
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="py-8 lg:px-4 bg-slate-100">
      <div className="max-w-7xl mx-auto bg-linear-to-br from-lime-600 via-green-800 to-lime-600 lg:px-15 px-3 py-20 rounded-3xl">
        {/* Header */}
        <div className="text-center mb-10">
          <div className="inline-flex items-center gap-3 px-4 py-2 bg-white/10 backdrop-blur-md rounded-full shadow-sm border border-white/20 mb-4">
            <span className="w-2 h-2 bg-emerald-400 rounded-full animate-pulse"></span>
            <span className="text-xs font-bold text-slate-200 uppercase tracking-wider">Registration Portal</span>
          </div>
          <h1 className="text-4xl md:text-5xl font-black text-white tracking-tight">
            Join <span className={`bg-linear-to-r ${currentConfig.color} bg-clip-text text-transparent`}>SQ Group</span>
          </h1>
          <p className="text-slate-300 mt-3 text-lg">Select your role and complete the registration</p>
        </div>

        <div className="grid lg:grid-cols-12 gap-6">
          {/* Left: Role Selector */}
          <div className="lg:col-span-4 space-y-3">
            <p className="text-xs font-bold text-slate-300 uppercase tracking-wider px-2 mb-2">Select Role</p>
            {Object.entries(registrationConfig).map(([key, config]) => {
              const isActive = selectedRole === key;
              return (
                <button
                  key={key}
                  onClick={() => handleRoleChange(key)}
                  className={`w-full text-left lg:p-4 p-2 rounded-2xl transition-all duration-300 group relative overflow-hidden ${
                    isActive
                      ? 'bg-slate-700/60 backdrop-blur-xl shadow-xl shadow-slate-900/40 ring-2 ring-slate-500/50 scale-[1.02]'
                      : 'bg-slate-800/40 backdrop-blur-md hover:bg-slate-700/50 hover:shadow-md border border-slate-700/50'
                  }`}
                >
                  {isActive && (
                    <div className={`absolute left-0 top-0 bottom-0 w-1.5 bg-linear-to-b ${config.color}`}></div>
                  )}
                  <div className="flex items-center lg:gap-4 gap-3 pl-2">
                    <div className={`lg:w-12 lg:h-12 w-8 h-8 rounded-xl flex items-center justify-center text-2xl transition-all ${
                      isActive ? `bg-linear-to-br ${config.color} shadow-lg scale-110` : 'bg-slate-700/60 group-hover:bg-slate-600/60'
                    }`}>
                      <span className={isActive ? 'drop-shadow text-base' : 'grayscale opacity-60 text-base'}>{config.icon}</span>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`font-bold text-base ${isActive ? 'text-white' : 'text-slate-300'}`}>{config.label}</p>
                      <p className="text-xs text-slate-400 truncate">{config.description}</p>
                    </div>
                    {isActive && (
                      <div className={`w-6 h-6 rounded-full bg-linear-to-br ${config.color} flex items-center justify-center shrink-0`}>
                        <Icon name="check" className="w-3.5 h-3.5 text-white" />
                      </div>
                    )}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Right: Form */}
          <div className="lg:col-span-8">
            <div className="bg-white/95 backdrop-blur-xl rounded-3xl shadow-xl shadow-slate-900/20 lg:p-6 p-3 md:p-8 border border-slate-200/60 w-full">
              {/* Form Header */}
              <div className="flex items-center gap-4 pb-6 mb-6 border-b border-slate-200">
                <div className={`w-14 h-14 rounded-2xl bg-linear-to-br ${currentConfig.color} flex items-center justify-center text-3xl shadow-lg`}>
                  {currentConfig.icon}
                </div>
                <div>
                  <h2 className="text-xl font-bold text-slate-800">{currentConfig.label} Registration</h2>
                  <p className="text-sm text-slate-400">{currentConfig.description}</p>
                </div>
              </div>

              {/* Form Fields */}
              <form onSubmit={handleSubmit} className="space-y-5">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                  {currentConfig.fields.map((field) => {
                    const spanFull = field.type === 'location' || field.type === 'multiselect' || field.type === 'dropdownWithText';
                    return (
                      <div key={field.id} className={`${spanFull ? 'md:col-span-1' : ''} last:md:col-span-2`}>
                        {renderField(field)}
                      </div>
                    );
                  })}
                </div>

                {/* Submit */}
                <div className="pt-6 mt-6 border-t border-slate-200">
              
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className={`w-full bg-linear-to-r ${currentConfig.color}
                      text-white py-4 rounded-2xl font-bold text-base
                      shadow-lg hover:shadow-xl active:scale-[0.98]
                      transition-all duration-200
                      flex items-center justify-center gap-2
                      group
                      disabled:opacity-60
                      disabled:cursor-not-allowed
                      disabled:active:scale-100`}
                  >
                    {isSubmitting ? (
                      <>
                        <svg
                          className="w-5 h-5 animate-spin"
                          viewBox="0 0 24 24"
                          fill="none"
                        >
                          <circle
                            cx="12"
                            cy="12"
                            r="9"
                            stroke="currentColor"
                            strokeWidth="3"
                            className="opacity-30"
                          />

                          <path
                            d="M21 12a9 9 0 0 0-9-9"
                            stroke="currentColor"
                            strokeWidth="3"
                            strokeLinecap="round"
                          />
                        </svg>

                        Submitting...
                      </>
                    ) : (
                      <>
                        Complete Registration

                        <Icon
                          name="arrow"
                          className="w-5 h-5 group-hover:translate-x-1 transition-transform"
                        />
                      </>
                    )}
                  </button>
                  <p className="text-center text-xs text-slate-400 mt-4">
                    <span className="text-red-500 font-bold">*</span> Required fields must be completed
                  </p>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EmployeeRegistrationForm;