// Component for registering, editing, and listing customer profiles, driving license info, and passport documents.
import React, { useState, useEffect, useCallback } from "react";
import DateTimePicker from "./DateTimePicker";
import * as XLSX from 'xlsx';
import * as htmlToImage from 'html-to-image';
import { 
  User, MapPin, Shield, CheckCircle, Save, X, ChevronRight, ArrowLeft, 
  Image as ImageIcon, Edit2, Plus, Users, Trash2, Sparkles, List, ChevronLeft, 
  Phone, AlertCircle, Download, Upload, Clock, BarChart3, Filter, 
  RefreshCw, Loader2, Bell, FileSpreadsheet, Eye, EyeOff, Camera, Search, Mail
} from 'lucide-react';
import api from "../api";

// Helper function for debouncing
const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

// Toast notification system
const Toast = ({ message, type, onClose }) => {
  useEffect(() => {
    const timer = setTimeout(onClose, 5000);
    return () => clearTimeout(timer);
  }, [onClose]);

  const colors = {
    success: 'border-emerald-500 bg-emerald-500/10 text-emerald-400',
    error: 'border-red-500 bg-red-500/10 text-red-400',
    warning: 'border-yellow-500 bg-yellow-500/10 text-yellow-400',
    info: 'border-blue-500 bg-blue-500/10 text-blue-400'
  };

  return (
<div className={`toast-notification ${colors[type]}`}>
<span className="toast-icon">
        {type === 'success' &&<CheckCircle size={18} />}
        {type === 'error' &&<AlertCircle size={18} />}
        {type === 'warning' &&<AlertCircle size={18} />}
        {type === 'info' &&<Bell size={18} />}
</span>
<span className="toast-message">{message}</span>
<button onClick={onClose} className="toast-close">×</button>
</div>
  );
};

// Progress Bar Component
const ProgressBar = ({ percentage }) => (
<div className="progress-bar-container">
<div className="progress-bar-fill" style={{ width: `${Math.min(100, percentage)}%` }} />
</div>
);

const AddCustomer = ({ 
  onSuccess, 
  onCancel, 
  initialData, 
  isBookingMode = false, 
  isModalView = false 
}) => {
  // State Management
  const [customers, setCustomers] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentId, setCurrentId] = useState(null);
  const [formError, setFormError] = useState("");
  const [activeStep, setActiveStep] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [toasts, setToasts] = useState([]);

  // Search and Filter States
  const [searchTerm, setSearchTerm] = useState("");
  const [isSearching, setIsSearching] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [showSearchModal, setShowSearchModal] = useState(false);
  const [filteredCustomers, setFilteredCustomers] = useState([]);
  const rowsPerPage = 8;

  // View States - Tab based
  const [activeTab, setActiveTab] = useState('all'); // 'all' | 'alerts'
  const [showListView, setShowListView] = useState(false);
  const [listFilter, setListFilter] = useState("");

  // Filters - only city and state (no date filters)
  const [filters, setFilters] = useState({ city: '', state: '' });

  // Screenshot state
  const [isCapturing, setIsCapturing] = useState(false);
  const directoryRef = React.useRef(null);

  // ── NEW FEATURE: License Expiry Alerts ──
  const [showExpiryAlerts, setShowExpiryAlerts] = useState(false);

  // Form State
  const initialFormState = {
    full_name: "", dob: "", gender: "", mobile: "", email: "", nationality: "", occupation: "",
    house_no: "", street_name: "", area: "", city: "", district: "", state: "", pincode: "", country_id: "",
    license_number: "", license_issued_date: "", license_expiry_date: "", license_state: "", license_country: "India",
    id_type: "", id_number: "", license_file: "", id_file: ""
  };

  const [form, setForm] = useState(initialFormState);
  const [licenseFiles, setLicenseFiles] = useState([]);
  const [licensePreviews, setLicensePreviews] = useState([]);
  const [idFiles, setIdFiles] = useState([]);
  const [idPreviews, setIdPreviews] = useState([]);
  const [countryMaster, setCountryMaster] = useState([]);

  // Auto-save draft
  const [draftKey] = useState(`customer_draft_${Date.now()}`);
  const debouncedForm = useDebounce(form, 1000);

  // Toast management
  const showToast = useCallback((message, type = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 5000);
  }, []);

  // Fetch Countries
  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const token = localStorage.getItem("token");
        const response = await api.get("/customers/countries", {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (Array.isArray(response.data)) {
          setCountryMaster(response.data);
        }
      } catch (error) {
        console.error("Error fetching countries:", error);
        showToast("Failed to load countries", "error");
      }
    };
    fetchCountries();
  }, [showToast]);

  // Load draft on mount
  useEffect(() => {
    const savedDraft = localStorage.getItem(draftKey);
    if (savedDraft && !isEdit) {
      try {
        const parsed = JSON.parse(savedDraft);
        setForm(prev => ({ ...prev, ...parsed }));
      } catch (e) {
        console.error("Failed to load draft");
      }
    }
  }, [draftKey, isEdit, showToast]);

  // Save draft on change
  useEffect(() => {
    if (!isEdit && form !== initialFormState) {
      localStorage.setItem(draftKey, JSON.stringify(form));
    }
  }, [debouncedForm, isEdit, draftKey, form, initialFormState]);

  // Fetch Customers
  const fetchCustomers = useCallback(async () => {
    try {
      const token = localStorage.getItem("token");
      const response = await api.get("/customers", {
        headers: { Authorization: `Bearer ${token}` }
      });
      if (Array.isArray(response.data)) {
        setCustomers(response.data);
      }
    } catch (error) {
      console.error("Fetch error:", error);
      showToast("Failed to fetch customers", "error");
    }
  }, [showToast]);

  useEffect(() => {
    fetchCustomers();
  }, [fetchCustomers]);

  // Handle Booking Mode
  useEffect(() => {
    if (isBookingMode) {
      setShowModal(true);
    }
  }, [isBookingMode]);

  // Pagination
  useEffect(() => {
    setCurrentPage(1);
  }, [listFilter, activeTab, filters]);

  // ── Required fields for completeness ──
  const REQUIRED_FIELDS = [
    'full_name', 'mobile', 'email', 'dob', 'gender', 'nationality',
    'city', 'state', 'country_id',
    'license_number', 'license_expiry_date',
    'id_type', 'id_number'
  ];

  const filledCount = REQUIRED_FIELDS.filter(f => (form[f] || "").toString().trim() !== "").length;
  const completeness = Math.round((filledCount / REQUIRED_FIELDS.length) * 100);
  const initials = (form.full_name || "?").trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase();

  // ── Directory list with search filter ──
  const directoryList = customers.filter(c => {
    if (!listFilter.trim()) return true;
    const q = listFilter.trim().toLowerCase();
    return (c.full_name || "").toLowerCase().includes(q) || 
           (c.mobile || "").includes(q) ||
           (c.email || "").toLowerCase().includes(q);
  });

  // ── Apply advanced filters (city & state only) ──
  const filteredDirectoryList = directoryList.filter(c => {
    if (filters.city && !c.city?.toLowerCase().includes(filters.city.toLowerCase())) return false;
    if (filters.state && !c.state?.toLowerCase().includes(filters.state.toLowerCase())) return false;
    return true;
  });

  // ── License Expiry Alerts (expired or expiring within 30 days) ──
  const licenseAlerts = customers
    .map(c => {
      if (!c.license_expiry_date) return null;
      const expiry = new Date(c.license_expiry_date);
      if (isNaN(expiry)) return null;
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const diffDays = Math.ceil((expiry - today) / (1000 * 60 * 60 * 24));
      if (diffDays > 30) return null;
      return { ...c, diffDays, isExpired: diffDays < 0 };
    })
    .filter(Boolean)
    .sort((a, b) => a.diffDays - b.diffDays);

  const expiredCount = licenseAlerts.filter(c => c.isExpired).length;

  // ── Screenshot Handler ──
  const handleScreenshot = async () => {
    if (!directoryRef.current) {
      showToast("Table not ready for screenshot", "error");
      return;
    }

    setIsCapturing(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 200));

      const dataUrl = await htmlToImage.toPng(directoryRef.current, {
        quality: 1.0,
        backgroundColor: '#0f172a',
        pixelRatio: 2,
      });

      const link = document.createElement('a');
      link.download = `customers_${activeTab === 'all' ? 'all' : 'alerts'}_${new Date().toISOString().split('T')[0]}.png`;
      link.href = dataUrl;
      link.click();

      showToast("Screenshot captured successfully!", "success");
    } catch (error) {
      console.error("Screenshot error:", error);
      showToast("Failed to capture screenshot. Please try again.", "error");
    } finally {
      setIsCapturing(false);
    }
  };

  // ── Handlers ──
  const handleAddNew = () => {
    setForm(initialFormState);
    setLicenseFiles([]);
    setLicensePreviews([]);
    setIdFiles([]);
    setIdPreviews([]);
    setIsEdit(false);
    setCurrentId(null);
    setActiveStep(1);
    setShowModal(true);
    localStorage.removeItem(draftKey);
  };

  const handleEdit = (customer) => {
    const formatDate = (dateStr) => {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return date.toISOString().split('T')[0];
    };

    const baseUrl = "http://127.0.0.1:5000/uploads/";
    setForm({
      ...customer,
      full_name: customer.full_name || "",
      dob: formatDate(customer.dob),
      gender: customer.gender || "",
      mobile: customer.mobile || "",
      email: customer.email || "",
      nationality: customer.nationality || "",
      occupation: customer.occupation || "",
      house_no: customer.house_no || "",
      street_name: customer.street_name || "",
      area: customer.area || "",
      city: customer.city || "",
      district: customer.district || "",
      state: customer.state || "",
      pincode: customer.pincode || "",
      country_id: customer.country_id || "",
      license_number: customer.license_number || "",
      license_issued_date: formatDate(customer.license_issued_date),
      license_expiry_date: formatDate(customer.license_expiry_date),
      license_state: customer.license_state || "",
      license_country: customer.license_country || "India",
      id_type: customer.id_type || "",
      id_number: customer.id_number || ""
    });

    setCurrentId(customer.cus_id);
    setIsEdit(true);
    setActiveStep(1);
    setShowModal(true);

    const createImageUrls = (fileString) => {
      if (!fileString) return [];
      return fileString.split(',').map(img => {
        const trimmed = img.trim();
        if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
          return trimmed;
        }
        const encoded = trimmed
          .replace(/ /g, '%20')
          .replace(/\(/g, '%28')
          .replace(/\)/g, '%29');
        return baseUrl + encoded;
      });
    };

    setLicensePreviews(customer.license_file ? createImageUrls(customer.license_file) : []);
    setIdPreviews(customer.id_file ? createImageUrls(customer.id_file) : []);
    setLicenseFiles([]);
    setIdFiles([]);
  };

  const handleFileChange = (e, type) => {
    const files = Array.from(e.target.files);
    files.forEach(file => {
      if (file.size > 5 * 1024 * 1024) {
        showToast(`File ${file.name} exceeds 5MB limit`, "error");
        return;
      }
      const reader = new FileReader();
      reader.onloadend = () => {
        if (type === "license") {
          setLicenseFiles(prev => [...prev, file]);
          setLicensePreviews(prev => [...prev, reader.result]);
        } else {
          setIdFiles(prev => [...prev, file]);
          setIdPreviews(prev => [...prev, reader.result]);
        }
      };
      reader.readAsDataURL(file);
    });
  };

  const removeFile = (index, type) => {
    if (type === "license") {
      setLicenseFiles(prev => prev.filter((_, i) => i !== index));
      setLicensePreviews(prev => prev.filter((_, i) => i !== index));
    } else {
      setIdFiles(prev => prev.filter((_, i) => i !== index));
      setIdPreviews(prev => prev.filter((_, i) => i !== index));
    }
  };

  // ── Enhanced Validation ──
  const validateStep = (step) => {
    if (isBookingMode) return null;

    const errors = [];
    if (step === 1) {
      if (!form.full_name?.trim()) errors.push("Full Name is required.");
      if (!form.mobile?.trim()) errors.push("Mobile Number is required.");
      if (!/^\d{7,15}$/.test(form.mobile.trim())) errors.push("Mobile Number must be 7-15 digits.");
      const existingCustomer = customers.find(c => c.mobile === form.mobile.trim());
      if (existingCustomer) {
        if (!isEdit || (isEdit && String(existingCustomer.cus_id) !== String(currentId))) {
          errors.push("Phone number already exists");
        }
      }
      if (!form.email?.trim()) errors.push("Email Address is required.");
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) errors.push("Please enter a valid email address.");
    }
    return errors.length > 0 ? errors[0] : null;
  };

  // ── Save/Submit Handlers ──
  const handleNextOnly = () => {
    const error = validateStep(activeStep);
    if (error) {
      setFormError(error);
      showToast(error, "error");
      setTimeout(() => setFormError(""), 5000);
      return;
    }
    setFormError("");
    if (activeStep < 4) setActiveStep(activeStep + 1);
  };

  const handleUpdateOnly = async (e) => {
    if (e) e.preventDefault();

    for (let i = 1; i <= activeStep; i++) {
      const err = validateStep(i);
      if (err) {
        setActiveStep(i);
        setFormError(`Step ${i}: ${err}`);
        showToast(`Step ${i}: ${err}`, "error");
        setTimeout(() => setFormError(""), 5000);
        return;
      }
    }
    setFormError("");

    if (!currentId) {
      showToast("Customer ID missing. Cannot update.", "error");
      return;
    }

    setIsLoading(true);
    try {
      const formData = new FormData();
      Object.keys(form).forEach(key => {
        if (key !== 'license_file' && key !== 'id_file') {
          formData.append(key, form[key] === "" ? "" : form[key]);
        }
      });

      const existingLicense = licensePreviews
        .filter(src => !src.startsWith('data:'))
        .map(src => src.split('/').pop());
      formData.append('existing_license_files', existingLicense.join(','));

      const existingId = idPreviews
        .filter(src => !src.startsWith('data:'))
        .map(src => src.split('/').pop());
      formData.append('existing_id_files', existingId.join(','));

      licenseFiles.forEach(file => { 
        if (file instanceof File) formData.append('license_file', file); 
      });
      idFiles.forEach(file => { 
        if (file instanceof File) formData.append('id_file', file); 
      });

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${localStorage.getItem("token")}`
        }
      };

      const response = await api.put(`/customers/${currentId}`, formData, config);

      if (response.status === 200) {
        fetchCustomers();
        showToast("Customer updated successfully!", "success");
        if (activeStep < 4) setActiveStep(activeStep + 1);
      }
    } catch (error) {
      console.error("Update error:", error);
      showToast("Error: " + (error.response?.data?.message || "Check your backend"), "error");
    } finally {
      setIsLoading(false);
    }
  };

 /* const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);

    try {
      const error = validateStep(activeStep);
      if (error) {
        setFormError(error);
        showToast(error, "error");
        setTimeout(() => setFormError(""), 5000);
        return;
      }

      if (!isEdit && activeStep < 4) {
        setFormError("");
        setActiveStep(activeStep + 1);
        return;
      }

      for (let i = 1; i <= 4; i++) {
        const err = validateStep(i);
        if (err) {
          setActiveStep(i);
          setFormError(`Step ${i}: ${err}`);
          showToast(`Step ${i}: ${err}`, "error");
          setTimeout(() => setFormError(""), 5000);
          return;
        }
      }
      setFormError("");

      const formData = new FormData();
      Object.keys(form).forEach(key => {
        if (key !== 'license_file' && key !== 'id_file') {
          formData.append(key, form[key] || "");
        }
      });

      if (licenseFiles && licenseFiles.length > 0) {
        licenseFiles.forEach(file => {
          if (file instanceof File) formData.append('license_file', file);
        });
      }

      if (idFiles && idFiles.length > 0) {
        idFiles.forEach(file => {
          if (file instanceof File) formData.append('id_file', file);
        });
      }

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${localStorage.getItem("token")}`
        }
      };

      let response;
      if (isEdit) {
        response = await api.put(`/customers/${currentId}`, formData, config);
      } else {
        response = await api.post("/customers", formData, config);
      }

      if (response.status === 200 || response.status === 201) {
        if (isEdit && activeStep < 4) {
          setActiveStep(activeStep + 1);
        } else {
          showToast(isEdit ? "Customer updated successfully!" : "Customer registered successfully!", "success");
          setShowModal(false);
          setForm(initialFormState);
          setLicenseFiles([]);
          setLicensePreviews([]);
          setIdFiles([]);
          setIdPreviews([]);
          fetchCustomers();
          localStorage.removeItem(draftKey);
          if (onSuccess) onSuccess();
        }
      }
    } catch (error) {
      console.error("SAVE ERROR:", error);
      const errorMsg = error.response?.data?.message || "Something went wrong!";
      showToast("Action Failed: " + errorMsg, "error");
    } finally {
      setIsLoading(false);
    }
  };
*/



const handleSubmit = async (e) => {
  e.preventDefault();
  setIsLoading(true);

  try {
    const error = validateStep(activeStep);
    if (error) {
      setFormError(error);
      showToast(error, "error");
      setTimeout(() => setFormError(""), 5000);
      return;
    }

    if (!isEdit && activeStep < 4) {
      setFormError("");
      setActiveStep(activeStep + 1);
      return;
    }

    for (let i = 1; i <= 4; i++) {
      const err = validateStep(i);
      if (err) {
        setActiveStep(i);
        setFormError(`Step ${i}: ${err}`);
        showToast(`Step ${i}: ${err}`, "error");
        setTimeout(() => setFormError(""), 5000);
        return;
      }
    }
    setFormError("");

    const formData = new FormData();
    Object.keys(form).forEach(key => {
      if (key !== 'license_file' && key !== 'id_file') {
        formData.append(key, form[key] || "");
      }
    });

    if (licenseFiles && licenseFiles.length > 0) {
      licenseFiles.forEach(file => {
        if (file instanceof File) formData.append('license_file', file);
      });
    }

    if (idFiles && idFiles.length > 0) {
      idFiles.forEach(file => {
        if (file instanceof File) formData.append('id_file', file);
      });
    }

    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${localStorage.getItem("token")}`
      }
    };

    let response;
    if (isEdit) {
      response = await api.put(`/customers/${currentId}`, formData, config);
    } else {
      response = await api.post("/customers", formData, config);
    }

    if (response.status === 200 || response.status === 201) {
      // ✅ Get customer data from response
      const customerData = response.data;

      if (isEdit && activeStep < 4) {
        setActiveStep(activeStep + 1);
      } else {
        showToast(isEdit ? "Customer updated successfully!" : "Customer registered successfully!", "success");
        setShowModal(false);
        setForm(initialFormState);
        setLicenseFiles([]);
        setLicensePreviews([]);
        setIdFiles([]);
        setIdPreviews([]);
        fetchCustomers();
        localStorage.removeItem(draftKey);

        // ✅ FIX: Pass customer data to onSuccess
        if (onSuccess) {
          onSuccess({
            cus_id: customerData.cus_id || customerData.id,
            full_name: form.full_name,
            email: form.email,
            mobile: form.mobile,
            license_number: form.license_number
          });
        }
      }
    }
  } catch (error) {
    console.error("SAVE ERROR:", error);
    const errorMsg = error.response?.data?.message || "Something went wrong!";
    showToast("Action Failed: " + errorMsg, "error");
  } finally {
    setIsLoading(false);
  }
};
  // ── Search Handler ──
  const handleSearch = async () => {
    if (!searchTerm) {
      showToast("Please enter Mobile or Name", "warning");
      return;
    }
    setIsSearching(true);
    try {
      const token = localStorage.getItem("token");
      const response = await api.get(`/customers/search?q=${searchTerm}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      const results = response.data;
      setIsSearching(false);
      if (results.length === 0) {
        showToast("No customer found!", "warning");
      } else if (results.length === 1) {
        handleEdit(results[0]);
        setSearchTerm("");
      } else {
        setFilteredCustomers(results);
        setShowSearchModal(true);
      }
    } catch (error) {
      console.error("Search error:", error);
      setIsSearching(false);
      showToast("Search failed. Please try again.", "error");
    }
  };

  // ── FIXED: Excel Export Handler - Exports FILTERED data ──
  const handleExportExcel = () => {
    // Get the current filtered data based on active tab
    let dataToExport;

    if (activeTab === 'alerts') {
      // For alerts tab, export filtered alerts (if any filter applied)
      dataToExport = licenseAlerts;
    } else {
      // For all customers tab, export FILTERED directory list
      dataToExport = filteredDirectoryList;
    }

    if (dataToExport.length === 0) {
      showToast(activeTab === 'alerts' ? "No alerts to export" : "No customers match the current filters", "warning");
      return;
    }

    try {
      let exportData;
      if (activeTab === 'alerts') {
        exportData = dataToExport.map(c => ({
          'Full Name': c.full_name || '',
          'Mobile': c.mobile || '',
          'Email': c.email || '',
          'License Number': c.license_number || '',
          'License Expiry': c.license_expiry_date ? new Date(c.license_expiry_date).toLocaleDateString() : '',
          'Status': c.isExpired ? `Expired ${Math.abs(c.diffDays)} day(s) ago` : `Expires in ${c.diffDays} day(s)`
        }));
      } else {
        exportData = dataToExport.map(c => ({
          'Full Name': c.full_name || '',
          'Mobile': c.mobile || '',
          'Email': c.email || '',
          'Date of Birth': c.dob ? new Date(c.dob).toLocaleDateString() : '',
          'Gender': c.gender || '',
          'Nationality': c.nationality || '',
          'Occupation': c.occupation || '',
          'House No': c.house_no || '',
          'Street': c.street_name || '',
          'Area': c.area || '',
          'City': c.city || '',
          'District': c.district || '',
          'State': c.state || '',
          'Pincode': c.pincode || '',
          'Country': c.country_name || '',
          'License Number': c.license_number || '',
          'License Issued': c.license_issued_date ? new Date(c.license_issued_date).toLocaleDateString() : '',
          'License Expiry': c.license_expiry_date ? new Date(c.license_expiry_date).toLocaleDateString() : '',
          'License State': c.license_state || '',
          'License Country': c.license_country || '',
          'ID Type': c.id_type || '',
          'ID Number': c.id_number || '',
          'Status': c.status || 'active',
          'Created At': c.created_at ? new Date(c.created_at).toLocaleString() : '',
          'Updated At': c.updated_at ? new Date(c.updated_at).toLocaleString() : ''
        }));
      }

      const ws = XLSX.utils.json_to_sheet(exportData);

      const colWidths = Object.keys(exportData[0] || {}).map(key => ({ wch: Math.max(key.length * 1.5, 15) }));
      ws['!cols'] = colWidths;

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, activeTab === 'alerts' ? 'License Alerts' : 'Customers');

      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

      const blob = new Blob([wbout], { type: 'application/octet-stream' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;

      // Include filter info in filename if filters are applied
      let fileName = activeTab === 'alerts' ? 'license_alerts' : 'customers';
      if (activeTab === 'all' && (filters.city || filters.state || listFilter)) {
        fileName += '_filtered';
      }
      link.download = `${fileName}_${new Date().toISOString().split('T')[0]}.xlsx`;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      showToast(`Exported ${dataToExport.length} filtered records to Excel successfully!`, "success");
    } catch (error) {
      console.error("Export error:", error);
      showToast("Export failed: " + error.message, "error");
    }
  };

  // ── Clear Draft ──
  const handleClearDraft = () => {
    localStorage.removeItem(draftKey);
    showToast("Draft cleared", "info");
  };

  // ── Reset Filters ──
  const handleResetFilters = () => {
    setFilters({ city: '', state: '' });
    setListFilter('');
    showToast("Filters reset", "info");
  };

  // ── Tab switching ──
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    setCurrentPage(1);
    setListFilter('');
  };

  const steps = [
    { id: 1, label: "Personal", icon: <User size={20} />, hint: "Who they are" },
    { id: 2, label: "Address", icon: <MapPin size={20} />, hint: "Where they live" },
    { id: 3, label: "License", icon: <Shield size={20} />, hint: "Driving credentials" },
    { id: 4, label: "Identity", icon: <CheckCircle size={20} />, hint: "Proof of ID" }
  ];

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value || "" }));
  };

  // Get current data based on active tab
  const getCurrentData = () => {
    if (activeTab === 'alerts') {
      return licenseAlerts;
    }
    return filteredDirectoryList;
  };

  const currentData = getCurrentData();
  const totalPages = Math.max(1, Math.ceil(currentData.length / rowsPerPage));
  const currentPageData = currentData.slice(
    (currentPage - 1) * rowsPerPage,
    currentPage * rowsPerPage
  );

  return (
<div className="main-wrapper bg-dark min-vh-100 text-white">
      {/* Toast Container */}
      {toasts.length > 0 && (
<div className="toast-container">
          {toasts.map(({ id, message, type }) => (
<Toast 
              key={id} 
              message={message} 
              type={type} 
              onClose={() => setToasts(prev => prev.filter(t => t.id !== id))}
            />
          ))}
</div>
      )}

      {!isBookingMode && (
<div className="container py-5">
<div className="row justify-content-center animate">
<div className="col-12 col-md-6 col-lg-5">
<div className="lookup-shell p-5 shadow-lg text-center">
<Users size={44} className="lookup-icon mb-3" />
<h2 className="fw-bold h3 mb-2">Quick Customer Lookup</h2>
<p className="text-secondary mb-4 small">Search by Name or Mobile Number to update details instantly.</p>

<div className="d-flex gap-2 mb-3">
<input
                    type="text"
                    className="form-control custom-input flex-grow-1"
                    placeholder="Ex: 9876543210 or Gowtham..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                    style={{ height: '48px' }}
                  />
<button 
                    className="btn-search-main flex-shrink-0" 
                    onClick={handleSearch} 
                    disabled={isSearching}
                    style={{ 
                      whiteSpace: 'nowrap',
                      height: '48px',
                      padding: '0 24px',
                      fontSize: '15px',
                      fontWeight: '700',
                      borderRadius: '10px',
                      background: 'linear-gradient(135deg, #7c3aed 0%, #a855f7 100%)',
                      color: 'white',
                      border: 'none',
                      cursor: 'pointer',
                      transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                      boxShadow: '0 4px 15px rgba(124, 58, 237, 0.3)'
                    }}
                    onMouseEnter={e => { if(!isSearching) { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 20px rgba(124, 58, 237, 0.4)'; } }}
                    onMouseLeave={e => { if(!isSearching) { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 4px 15px rgba(124, 58, 237, 0.3)'; } }}
>
                    {isSearching ? "Searching…" : "Find & Edit"}
</button>
</div>

<div className="divider-custom mb-4"><span>OR</span></div>

<button className="btn btn-outline-add w-100 mb-3" onClick={handleAddNew}>
<Plus size={18} /> Register New Customer
</button>

<button className="btn-view-directory w-100 mb-3" onClick={() => setShowListView(true)}>
<List size={16} /> View All Customers
<span className="directory-count-chip">{customers.length}</span>
</button>
</div>
</div>
</div>
</div>
      )}

      {/* Search Results Modal */}
      {showSearchModal && (
<div className="modal-overlay">
<div className="search-result-container animate">
<div className="form-header">
<div>
<h2 style={{ fontSize: '1.2rem' }}>Multiple matches found</h2>
<p style={{ fontSize: '0.8rem', color: '#94a3b8', margin: '5px 0 0' }}>
                  {filteredCustomers.length} customers found
</p>
</div>
<X className="close-icon" onClick={() => setShowSearchModal(false)} />
</div>

<div className="results-body">
              {filteredCustomers.map((cust) => (
<div
                  key={cust.id || cust.cus_id}
                  className="result-row"
                  onClick={() => {
                    handleEdit(cust);
                    setShowSearchModal(false);
                    setSearchTerm("");
                  }}
>
<div className="res-avatar">{cust.full_name.charAt(0)}</div>
<div className="res-details">
<span className="res-name">{cust.full_name}</span>
<span className="res-meta">{cust.mobile} • {cust.city || 'No City'}</span>
</div>
<button className="btn-select-res">Select <ChevronRight size={10} /></button>
</div>
              ))}
</div>
</div>
</div>
      )}

      {/* Directory List View with Tabs */}
      {showListView && (
<div className="modal-overlay">
<div className="directory-container animate" ref={directoryRef}>
<div className="form-header">
<div>
<h2 style={{ fontSize: '1.2rem' }}>Customer Management</h2>
<p style={{ fontSize: '0.8rem', color: '#94a3b8', margin: '5px 0 0' }}>
                  {activeTab === 'alerts' 
                    ? `${licenseAlerts.length} license alert${licenseAlerts.length === 1 ? '' : 's'}`
                    : `${filteredDirectoryList.length} record${filteredDirectoryList.length === 1 ? '' : 's'} on file`
                  }
</p>
</div>
<div className="d-flex gap-2 align-items-center flex-wrap">
                {/* Tab Buttons */}
<button 
                  className={`tab-btn ${activeTab === 'all' ? 'active' : ''}`}
                  onClick={() => handleTabChange('all')}
>
<Users size={14} /> All Customers
<span className="tab-count">{customers.length}</span>
</button>
<button 
                  className={`tab-btn ${activeTab === 'alerts' ? 'active' : ''}`}
                  onClick={() => handleTabChange('alerts')}
>
<Bell size={14} /> Expiry Alerts
<span 
                    className="tab-count"
                    style={{
                      backgroundColor: expiredCount > 0 ? 'rgba(239,68,68,0.2)' : 'rgba(234,179,8,0.2)',
                      color: expiredCount > 0 ? '#ef4444' : '#eab308'
                    }}
>
                    {licenseAlerts.length}
</span>
</button>

                {/* Action Buttons */}
<button className="btn-export-sm" onClick={handleExportExcel} title="Export filtered data to Excel">
<FileSpreadsheet size={14} />
</button>

<X className="close-icon" onClick={() => { 
                  setShowListView(false); 
                  setListFilter("");
                  setFilters({ city: '', state: '' });
                  setActiveTab('all');
                }} />
</div>
</div>

            {/* Filter and Search in one line */}
<div className="directory-filter-row">
<div className="filter-search-wrapper">
<input
                  type="text"
                  className="form-control custom-input filter-search-input"
                  placeholder={activeTab === 'alerts' ? "Filter alerts by name or mobile..." : "Filter by name, mobile, or email..."}
                  value={listFilter}
                  onChange={(e) => setListFilter(e.target.value)}
                />

<div className="filter-select-group">
<input
                    type="text"
                    className="form-control custom-input filter-select"
                    placeholder="City"
                    value={filters.city}
                    onChange={(e) => setFilters(prev => ({ ...prev, city: e.target.value }))}
                  />
<input
                    type="text"
                    className="form-control custom-input filter-select"
                    placeholder="State"
                    value={filters.state}
                    onChange={(e) => setFilters(prev => ({ ...prev, state: e.target.value }))}
                  />
<button className="btn-reset-filters" onClick={handleResetFilters}>
<RefreshCw size={14} /> Reset
</button>
</div>
</div>
</div>

<div className="directory-body">
              {currentPageData.length === 0 ? (
<p className="directory-empty">
                  {activeTab === 'alerts' 
                    ? 'No license expiry alerts. All licenses are valid! 🎉' 
                    : 'No customers match these filters.'
                  }
</p>
              ) : (
              <div className="directory-row-list">
                {currentPageData.map((cust) => (
                  <div key={cust.id || cust.cus_id} className="directory-row-card animate">
                    {/* Left Section: Avatar & Name */}
                    <div className="row-card-left">
                      <div className="res-avatar sm">{(cust.full_name || "?").charAt(0)}</div>
                      <div className="row-card-identity">
                        <span className="row-card-name">{cust.full_name}</span>
                        <span className="row-card-subtext">{cust.email || 'No Email'}</span>
                      </div>
                    </div>

                    {/* Center Section: Contact & City Details */}
                    <div className="row-card-center">
                      <div className="row-card-detail">
                        <Phone size={13} />
                        <span>{cust.mobile}</span>
                      </div>
                      
                      {activeTab === 'alerts' ? (
                        <div className="row-card-detail">
                          <Shield size={13} />
                          <span>License: {cust.license_number || '—'}</span>
                        </div>
                      ) : (
                        <div className="row-card-detail">
                          <MapPin size={13} />
                          <span>{cust.city || '—'}{cust.state ? `, ${cust.state}` : ''}</span>
                        </div>
                      )}
                    </div>

                    {/* Right Section: Status & Edit Button */}
                    <div className="row-card-right">
                      {activeTab === 'alerts' ? (
                        <span
                          className={`status-badge ${cust.isExpired ? 'inactive' : ''}`}
                          style={!cust.isExpired ? { background: 'rgba(234,179,8,0.1)', color: '#eab308', border: '1px solid rgba(234,179,8,0.25)' } : {}}
                        >
                          {cust.isExpired
                            ? `Expired ${Math.abs(cust.diffDays)}d`
                            : `Expires in ${cust.diffDays}d`}
                        </span>
                      ) : (
                        <span className={`status-badge ${cust.status === 'active' ? 'active' : 'inactive'}`}>
                          {cust.status || 'active'}
                        </span>
                      )}
                      
                      <button
                        className="btn-select-res"
                        style={{ height: '36px', borderRadius: '10px', padding: '0 16px' }}
                        onClick={() => { 
                          handleEdit(cust); 
                          setShowListView(false); 
                          setListFilter("");
                          setActiveTab('all');
                        }}
                      >
                        Edit Profile <ChevronRight size={12} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
              )}
</div>

            {currentData.length > 0 && (
<div className="directory-pagination">
<button
                  className="page-btn"
                  disabled={currentPage <= 1}
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
>
<ChevronLeft size={14} /> Prev
</button>
<span className="page-status">
                  Page {currentPage} of {totalPages}
<span className="page-total ms-2">
                    ({currentData.length} total)
</span>
</span>
<button
                  className="page-btn"
                  disabled={currentPage >= totalPages}
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
>
                  Next <ChevronRight size={14} />
</button>
</div>
            )}
</div>
</div>
      )}

      {/* Main Modal/Wizard */}
      {(showModal || isModalView) && (
<div className={isModalView ? "modal-static" : "modal-overlay-custom"}>
<div className="wizard-shell-v2 animate shadow-2xl">

            {/* Header */}
<div className="wizard-v2-header">
<h2>{isEdit ? "Update Customer" : "New Customer Registration"}</h2>
<X className="close-icon-custom pointer" onClick={() => { setShowModal(false); onCancel?.(); }} />
</div>

            {/* Horizontal Stepper */}
<div className="wizard-v2-stepper">
              {steps.map((step, idx) => (
<React.Fragment key={step.id}>
<button
                    type="button"
                    className={`stepper-item ${activeStep === step.id ? 'active' : ''} ${activeStep > step.id ? 'done' : ''}`}
                    onClick={() => setActiveStep(step.id)}
>
<span className="stepper-circle">
                      {activeStep > step.id ? <CheckCircle size={20} /> : step.icon}
</span>
<span className="stepper-label">{step.label}</span>
</button>
                  {idx < steps.length - 1 && (
<div className={`stepper-line ${activeStep > step.id ? 'done' : ''}`} />
                  )}
</React.Fragment>
              ))}
</div>

            {/* Main Panel */}
<div className="wizard-v2-main">
<form onSubmit={handleSubmit}>
                {formError && (
<div className="form-error-banner animate">
<AlertCircle size={16} />
                    {formError}
</div>
                )}

<div className="wizard-v2-body">
                  {/* Step 1: Personal */}
                  {activeStep === 1 && (
<div className="row g-4 animate">
<div className="col-md-4">
<label className="field-label">Full Name <span className="required-star">*</span></label>
<input 
                          className="form-control custom-input" 
                          name="full_name" 
                          value={form.full_name} 
                          onChange={handleChange} 
                          required 
                          placeholder="Enter full name" 
                        />
</div>
<div className="col-md-4">
<label className="field-label">Mobile Number <span className="required-star">*</span></label>
<input 
                          className="form-control custom-input" 
                          name="mobile" 
                          value={form.mobile} 
                          onChange={handleChange} 
                          required 
                          placeholder="98765XXXXX" 
                        />
</div>
<div className="col-md-4">
<label className="field-label">Email Address <span className="required-star">*</span></label>
<input 
                          type="email" 
                          className="form-control custom-input" 
                          name="email" 
                          value={form.email} 
                          onChange={handleChange} 
                          placeholder="example@mail.com" 
                        />
</div>
<div className="col-md-4">
<label className="field-label">Date of Birth</label>
<DateTimePicker
                          name="dob"
                          value={form.dob || ""}
                          onChange={(iso) => handleChange({ target: { name: "dob", value: iso } })}
                          placeholder="DD-MM-YYYY hh:mm AM/PM"
                        />
</div>
<div className="col-md-4">
<label className="field-label">Gender</label>
<select className="form-select custom-input" name="gender" value={form.gender} onChange={handleChange}>
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>
<div className="col-md-4">
<label className="field-label">Nationality</label>
<select className="form-select custom-input" name="nationality" value={form.nationality} onChange={handleChange}>
<option value="">Select Nationality</option>
                          {countryMaster.map((c) => (
<option key={c.country_id} value={c.nationality}>{c.nationality}</option>
                          ))}
</select>
</div>
<div className="col-md-4">
<label className="field-label">Occupation</label>
<input className="form-control custom-input" name="occupation" value={form.occupation} onChange={handleChange} placeholder="e.g. Software Engineer" />
</div>
</div>
                  )}

                  {/* Step 2: Address */}
                  {activeStep === 2 && (
<div className="row g-4 animate">
<div className="col-md-4">
<label className="field-label">House / Flat No</label>
<input className="form-control custom-input" name="house_no" value={form.house_no} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Street Name</label>
<input className="form-control custom-input" name="street_name" value={form.street_name} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Area</label>
<input className="form-control custom-input" name="area" value={form.area} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">City <span className="required-star">*</span></label>
<input className="form-control custom-input" name="city" value={form.city} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">State</label>
<input className="form-control custom-input" name="state" value={form.state} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Pincode</label>
<input className="form-control custom-input" name="pincode" value={form.pincode} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Country</label>
<select className="form-select custom-input" name="country_id" value={form.country_id} onChange={handleChange}>
<option value="">Select Country</option>
                          {countryMaster.map((c) => (
<option key={c.country_id} value={c.country_id}>{c.name}</option>
                          ))}
</select>
</div>
</div>
                  )}

                  {/* Step 3: License */}
                  {activeStep === 3 && (
<div className="row g-4 animate">
<div className="col-md-4">
<label className="field-label">License Number <span className="required-star">*</span></label>
<input className="form-control custom-input" name="license_number" value={form.license_number} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Issued Date</label>
<DateTimePicker
                          name="license_issued_date"
                          value={form.license_issued_date || ""}
                          onChange={(iso) => handleChange({ target: { name: "license_issued_date", value: iso } })}
                          placeholder="DD-MM-YYYY hh:mm AM/PM"
                        />
</div>
<div className="col-md-4">
<label className="field-label">Expiry Date <span className="required-star">*</span></label>
<DateTimePicker
                          name="license_expiry_date"
                          value={form.license_expiry_date || ""}
                          onChange={(iso) => handleChange({ target: { name: "license_expiry_date", value: iso } })}
                          placeholder="DD-MM-YYYY hh:mm AM/PM"
                          minDate={form.license_issued_date || ""}
                        />
</div>
<div className="col-md-4">
<label className="field-label">Issuing State</label>
<input className="form-control custom-input" name="license_state" value={form.license_state} onChange={handleChange} />
</div>
<div className="col-md-4">
<label className="field-label">Issuing Country</label>
<input className="form-control custom-input" name="license_country" value={form.license_country} onChange={handleChange} />
</div>

<div className="col-12 mt-4">
<label className="field-label d-block mb-3">License Documents (Front & Back)</label>
<div className="multi-upload-grid d-flex flex-wrap gap-3">
<label className="upload-box-mini-custom">
<Plus size={24} />
<span>Add</span>
<input type="file" hidden multiple accept="image/*" onChange={(e) => handleFileChange(e, "license")} />
</label>
                          {licensePreviews.map((src, index) => (
<div key={index} className="preview-card-custom position-relative">
<img src={src} className="w-100 h-100 object-fit-cover" alt="license-preview" />
<div className="delete-badge-custom" onClick={() => removeFile(index, "license")}>
<Trash2 size={12} />
</div>
</div>
                          ))}
</div>
<p className="file-hint">Max file size: 5MB per file</p>
</div>
</div>
                  )}

                  {/* Step 4: Identity */}
                  {activeStep === 4 && (
<div className="row g-4 animate">
<div className="col-md-6">
<label className="field-label">ID Type <span className="required-star">*</span></label>
<select className="form-select custom-input" name="id_type" value={form.id_type} onChange={handleChange}>
<option value="">Select ID Type</option>
<option value="Aadhaar">Aadhaar Card</option>
<option value="Passport">Passport</option>
<option value="Emirates ID">Emirates ID</option>
<option value="PAN">PAN Card</option>
</select>
</div>
<div className="col-md-6">
<label className="field-label">ID Number <span className="required-star">*</span></label>
<input className="form-control custom-input" name="id_number" value={form.id_number} onChange={handleChange} placeholder="Enter ID number" />
</div>

<div className="col-12 mt-4">
<label className="field-label d-block mb-3">Identity Proof Documents</label>
<div className="multi-upload-grid d-flex flex-wrap gap-3">
<label className="upload-box-mini-custom">
<Plus size={24} />
<span>Add</span>
<input type="file" hidden multiple accept="image/*" onChange={(e) => handleFileChange(e, "id")} />
</label>
                          {idPreviews.map((src, index) => (
<div key={index} className="preview-card-custom position-relative">
<img src={src} className="w-100 h-100 object-fit-cover" alt="id-preview" />
<div className="delete-badge-custom" onClick={() => removeFile(index, "id")}>
<Trash2 size={12} />
</div>
</div>
                          ))}
</div>
<p className="file-hint">Max file size: 5MB per file</p>
</div>
</div>
                  )}
</div>

                {/* Footer */}
<div className="wizard-v2-footer">
<div>
                    {activeStep > 1 && (
<button 
                        type="button" 
                        className="btn-prev-v2" 
                        onClick={() => setActiveStep(activeStep - 1)}
>
<ArrowLeft size={18} /> Previous
</button>
                    )}
</div>
<div className="d-flex gap-2">
                    {isEdit ? (
<>
<button 
                          type="button" 
                          className="btn-save-update" 
                          onClick={handleUpdateOnly}
                          disabled={isLoading}
>
                          {isLoading ? <Loader2 size={16} className="spinning" /> : <Save size={16} />} 
                          Update
</button>
                        {activeStep < 4 ? (
<button type="button" className="btn-next-v2" onClick={handleNextOnly}>
                            Next Step <ChevronRight size={18} />
</button>
                        ) : (
<button type="button" className="btn-close-modal" onClick={() => setShowModal(false)}>
                            Close
</button>
                        )}
</>
                    ) : (
<button 
                        type="submit" 
                        className="btn-next-v2"
                        disabled={isLoading}
>
                        {isLoading ? (
<Loader2 size={16} className="spinning" />
                        ) : activeStep === 4 ? (
<><Save size={16} /> Save Customer</>
                        ) : (
<>Next Step <ChevronRight size={18} /></>
                        )}
</button>
                    )}
</div>
</div>
</form>
</div>
</div>
</div>
      )}

<style>{`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

        .main-wrapper {
          font-family: 'Inter', sans-serif !important;
          background-color: #0f172a !important;
          min-height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        /* Toast Notifications */
        .toast-container {
          position: fixed;
          top: 20px;
          right: 20px;
          z-index: 999999;
          display: flex;
          flex-direction: column;
          gap: 10px;
          max-width: 380px;
        }

        .toast-notification {
          padding: 12px 18px;
          border-radius: 12px;
          border: 1px solid;
          backdrop-filter: blur(10px);
          display: flex;
          align-items: center;
          gap: 12px;
          animation: slideInRight 0.4s ease-out;
          background: rgba(17, 24, 39, 0.95);
          box-shadow: 0 8px 24px rgba(0,0,0,0.4);
        }

        .toast-icon { display: flex; align-items: center; flex-shrink: 0; }
        .toast-message { flex: 1; font-size: 0.85rem; font-weight: 500; }
        .toast-close {
          background: none; border: none; color: #94a3b8;
          font-size: 1.2rem; cursor: pointer; padding: 0 4px;
          transition: 0.2s;
        }
        .toast-close:hover { color: #f1f5f9; }

        @keyframes slideInRight {
          from { transform: translateX(100px); opacity: 0; }
          to { transform: translateX(0); opacity: 1; }
        }

        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        .spinning { animation: spin 0.8s linear infinite; }

        /* Lookup Shell - Styled as New Bookings (This Month) Card */
        .lookup-shell {
          background: linear-gradient(150deg, rgba(30,41,59,0.75) 0%, rgba(15,23,42,0.88) 100%);
          border: 1px solid rgba(255,255,255,0.07);
          border-radius: 14px;
          backdrop-filter: blur(20px);
          -webkit-backdrop-filter: blur(20px);
          box-shadow: 0 2px 0 0 rgba(255,255,255,0.04) inset, 0 6px 28px -4px rgba(0,0,0,0.3);
          transition: transform 0.28s ease, box-shadow 0.28s ease;
        }
        .lookup-shell:hover {
          transform: translateY(-3px);
          box-shadow: 0 2px 0 0 rgba(255,255,255,0.04) inset, 0 14px 36px -6px rgba(0,0,0,0.45);
        }
        .lookup-icon { color: #c084fc; filter: drop-shadow(0 0 10px rgba(192, 132, 252, 0.4)); }

        .custom-input {
          background: #0f172a !important;
          border: 1px solid #334155 !important;
          color: white !important;
          padding: 12px 16px !important;
          border-radius: 10px !important;
          width: 100%;
        }
        .custom-input::placeholder { color: #94a3b8 !important; }
        .custom-input:focus {
          border-color: #a855f7 !important;
          box-shadow: 0 0 0 3px rgba(168, 85, 247, 0.15) !important;
        }
        .custom-input:disabled { opacity: 0.6; cursor: not-allowed; }

        .btn-search-main {
          background: #e14eca;
          color: white;
          border: none;
          border-radius: 10px;
          font-weight: 600;
          cursor: pointer;
          transition: 0.2s;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
        }
        .btn-search-main:hover:not(:disabled) { background: #ba54f5; }
        .btn-search-main:disabled { opacity: 0.6; cursor: default; }

        .btn-outline-add {
          border: 1px dashed rgba(168, 85, 247, 0.5);
          color: #c084fc;
          background: rgba(168, 85, 247, 0.05);
          padding: 10px 12px;
          border-radius: 10px;
          font-weight: 600;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: pointer;
        }
        .btn-outline-add:hover { 
          background: rgba(168, 85, 247, 0.15);
          border-color: rgba(168, 85, 247, 0.8);
          transform: translateY(-1px);
        }

        .btn-view-directory {
          background: transparent;
          color: #94a3b8;
          border: 1px solid #334155;
          border-radius: 10px;
          padding: 10px 12px;
          font-weight: 600;
          font-size: 0.85rem;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          cursor: pointer;
          transition: 0.2s;
        }
        .btn-view-directory:hover { 
          color: white; 
          background: rgba(255, 255, 255, 0.08); 
          border-color: rgba(255, 255, 255, 0.2);
        }

        .directory-count-chip {
          background: rgba(148,163,184,0.15);
          color: #cbd5e1;
          font-size: 0.7rem;
          font-weight: 800;
          padding: 2px 8px;
          border-radius: 999px;
        }

        /* Modal Overlay */
        .modal-overlay {
          position: fixed;
          top: 0; left: 0;
          width: 100%; height: 100%;
          background: rgba(2, 6, 23, 0.65);
          backdrop-filter: blur(16px);
          -webkit-backdrop-filter: blur(16px);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 99999;
          padding: 24px;
        }

        .modal-overlay-custom {
          position: fixed;
          top: 0; left: 0;
          width: 100%; height: 100%;
          background: rgba(2, 6, 23, 0.65);
          backdrop-filter: blur(16px);
          -webkit-backdrop-filter: blur(16px);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 99999;
          padding: 24px;
        }

        /* Search Results */
        .search-result-container {
          background: linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(15, 23, 42, 0.95) 100%);
          width: 500px;
          max-width: 92vw;
          border-radius: 20px;
          border: 1px solid rgba(255, 255, 255, 0.1);
          overflow: hidden;
          box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.05);
        }
        .results-body {
          padding: 15px;
          max-height: 400px;
          overflow-y: auto;
        }
        .result-row {
          display: flex;
          align-items: center;
          padding: 12px;
          gap: 15px;
          border-radius: 10px;
          cursor: pointer;
          transition: 0.2s;
          border: 1px solid transparent;
          margin-bottom: 8px;
          background: #0f172a;
        }
        .result-row:hover {
          background: rgba(168, 85, 247, 0.08);
          border-color: rgba(168, 85, 247, 0.3);
          transform: translateY(-1px);
        }
        .res-avatar {
          width: 40px;
          height: 40px;
          background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
          box-shadow: 0 4px 10px rgba(124, 58, 237, 0.3);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bold;
          color: white;
          flex-shrink: 0;
        }
        .res-details { display: flex; flex-direction: column; flex: 1; }
        .res-name { font-weight: 600; font-size: 1rem; color: #f1f5f9; }
        .res-meta { font-size: 0.8rem; color: #94a3b8; }

        .btn-select-res {
          background: rgba(168, 85, 247, 0.1);
          color: #c084fc;
          border: 1px solid rgba(168, 85, 247, 0.3);
          border-radius: 8px;
          padding: 6px 12px;
          font-size: 0.75rem;
          font-weight: 700;
          display: flex;
          align-items: center;
          gap: 4px;
          cursor: pointer;
          transition: all 0.2s;
        }
        .btn-select-res:hover { color: white; background: #a855f7; border-color: #c084fc; box-shadow: 0 4px 12px rgba(168, 85, 247, 0.3); }

        /* Directory Panel */
        .directory-container {
          background: linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(15, 23, 42, 0.95) 100%);
          width: 1180px;
          max-width: 94vw;
          max-height: 85vh;
          border-radius: 20px;
          border: 1px solid rgba(255, 255, 255, 0.1);
          overflow: hidden;
          display: flex;
          flex-direction: column;
          box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.05);
        }

        .form-header {
          padding: 20px 24px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.08);
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: transparent;
          flex-wrap: wrap;
          gap: 10px;
        }
        .form-header h2 {
          font-size: 1.25rem;
          font-weight: 800;
          margin: 0;
          background: linear-gradient(135deg, #f8fafc 0%, #c084fc 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          letter-spacing: -0.5px;
        }
        .close-icon { cursor: pointer; color: #64748b; transition: all 0.2s; }
        .close-icon:hover { color: #ef4444; transform: scale(1.1); }

        /* Tab Buttons */
        .tab-btn {
          background: transparent;
          color: #94a3b8;
          border: 1px solid #334155;
          border-radius: 8px;
          padding: 6px 12px;
          font-size: 0.75rem;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 6px;
          cursor: pointer;
          transition: 0.2s;
        }
        .tab-btn:hover { border-color: rgba(255, 255, 255, 0.3); color: #f1f5f9; }
        .tab-btn.active {
          background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
          border-color: transparent;
          color: white;
          box-shadow: 0 4px 15px rgba(124, 58, 237, 0.3);
        }
        .tab-count {
          background: rgba(148,163,184,0.15);
          padding: 0px 6px;
          border-radius: 999px;
          font-size: 0.65rem;
          font-weight: 700;
        }

        .btn-export-sm {
          background: rgba(34, 197, 94, 0.05);
          color: #4ade80;
          border: 1px solid rgba(34, 197, 94, 0.2);
          border-radius: 8px;
          padding: 8px 12px;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          display: flex;
          align-items: center;
        }
        .btn-export-sm:hover {
          background: rgba(34, 197, 94, 0.15);
          border-color: rgba(34, 197, 94, 0.6);
          color: white;
          transform: translateY(-1px);
        }

        .directory-filter-row {
          padding: 16px 20px;
        }

        .filter-search-wrapper {
          display: flex;
          gap: 12px;
          align-items: center;
          flex-wrap: wrap;
        }

        .filter-search-input {
          flex: 2;
          min-width: 200px;
        }

        .filter-select-group {
          display: flex;
          gap: 12px;
          align-items: center;
          flex: 1;
          flex-wrap: wrap;
        }

        .filter-select {
          min-width: 120px;
          flex: 1;
        }

        .btn-reset-filters {
          background: rgba(239, 68, 68, 0.05);
          color: #fca5a5;
          border: 1px solid rgba(239, 68, 68, 0.2);
          border-radius: 10px;
          padding: 10px 16px;
          font-size: 0.8rem;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          white-space: nowrap;
          display: flex;
          align-items: center;
          gap: 6px;
          margin-top: -15px;
        }
        .btn-reset-filters:hover {
          background: rgba(239, 68, 68, 0.15);
          border-color: rgba(239, 68, 68, 0.5);
          color: white;
          transform: translateY(-1px);
        }

        .directory-body {
          padding: 16px 20px;
          overflow-y: auto;
          flex: 1;
        }
        .directory-empty {
          color: #64748b;
          text-align: center;
          padding: 30px 0;
          font-size: 0.85rem;
        }

        /* Directory Row Cards */
        .directory-row-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
          padding: 10px 0;
        }
        .directory-row-card {
          background: rgba(15, 23, 42, 0.45);
          border: 1px solid rgba(255, 255, 255, 0.06);
          border-radius: 14px;
          padding: 16px 24px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        .directory-row-card:hover {
          transform: translateY(-2px);
          border-color: rgba(168, 85, 247, 0.4);
          background: rgba(15, 23, 42, 0.65);
          box-shadow: 0 8px 25px rgba(168, 85, 247, 0.1);
        }
        .row-card-left {
          display: flex;
          align-items: center;
          gap: 16px;
          flex: 1;
          min-width: 220px;
        }
        .row-card-identity {
          display: flex;
          flex-direction: column;
          gap: 2px;
        }
        .row-card-name {
          font-size: 1rem;
          font-weight: 700;
          color: #f8fafc;
        }
        .row-card-subtext {
          font-size: 0.75rem;
          color: #64748b;
        }
        .row-card-center {
          display: flex;
          align-items: center;
          gap: 24px;
          flex: 1.5;
          justify-content: flex-start;
          flex-wrap: wrap;
        }
        .row-card-detail {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 0.8rem;
          color: #94a3b8;
          flex: 1;
        }
        .row-card-detail svg {
          color: #a855f7;
          flex-shrink: 0;
        }
        .row-card-right {
          display: flex;
          align-items: center;
          gap: 16px;
          justify-content: flex-end;
          flex-shrink: 0;
        }

        .res-avatar.sm { width: 30px; height: 30px; font-size: 0.8rem; }

        .status-badge {
          font-size: 0.65rem;
          padding: 3px 10px;
          border-radius: 999px;
          font-weight: 700;
          text-transform: capitalize;
          letter-spacing: 0.03em;
        }
        .status-badge.active {
          background: rgba(34, 197, 94, 0.1);
          color: #4ade80;
          border: 1px solid rgba(34, 197, 94, 0.25);
        }
        .status-badge.inactive {
          background: rgba(239, 68, 68, 0.1);
          color: #f87171;
          border: 1px solid rgba(239, 68, 68, 0.25);
        }

        .directory-pagination {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 14px 20px;
          border-top: 1px solid rgba(255, 255, 255, 0.08);
          background: rgba(15, 23, 42, 0.45);
          backdrop-filter: blur(10px);
          flex-wrap: wrap;
          gap: 10px;
        }
        .page-status {
          font-size: 0.75rem;
          color: #94a3b8;
          font-weight: 600;
        }
        .page-total { color: #64748b; font-weight: 400; }
        .page-btn {
          background: rgba(255, 255, 255, 0.03);
          color: #cbd5e1;
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 8px;
          padding: 6px 12px;
          font-size: 0.75rem;
          font-weight: 700;
          display: flex;
          align-items: center;
          gap: 4px;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .page-btn:hover:not(:disabled) {
          background: rgba(168, 85, 247, 0.1);
          border-color: #a855f7;
          color: #c084fc;
          transform: translateY(-1px);
        }
        .page-btn:disabled { opacity: 0.3; cursor: default; transform: none; box-shadow: none; }

        /* Wizard V2 */
        .wizard-shell-v2 {
          background: linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(15, 23, 42, 0.95) 100%);
          width: 980px;
          max-width: 100%;
          max-height: 92vh;
          border-radius: 20px;
          border: 1px solid rgba(255, 255, 255, 0.1);
          overflow: hidden;
          display: flex;
          flex-direction: column;
          backdrop-filter: blur(20px);
          -webkit-backdrop-filter: blur(20px);
          box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.05);
        }

        .wizard-v2-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 22px 32px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.08);
          background: transparent;
        }
        .wizard-v2-header h2 {
          font-size: 1.35rem;
          font-weight: 800;
          margin: 0;
          background: linear-gradient(135deg, #f8fafc 0%, #c084fc 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          letter-spacing: -0.5px;
        }

        .wizard-v2-stepper {
          display: flex;
          align-items: flex-start;
          padding: 28px 48px 24px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.08);
        }
        .stepper-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 10px;
          background: transparent !important;
          border: none;
          cursor: pointer;
          padding: 0;
          flex-shrink: 0;
          outline: none !important;
          box-shadow: none !important;
        }
        .stepper-item:focus,
        .stepper-item:active,
        .stepper-item:focus-visible,
        .stepper-item:hover {
          outline: none !important;
          background: transparent !important;
          box-shadow: none !important;
        }
        .stepper-circle {
          width: 56px;
          height: 56px;
          border-radius: 50%;
          border: 2px solid rgba(255, 255, 255, 0.1);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #64748b;
          background: rgba(15, 23, 42, 0.55);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .stepper-item.active .stepper-circle {
          border-color: #c084fc;
          color: white;
          background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
          box-shadow: 0 0 0 5px rgba(168, 85, 247, 0.15);
        }
        .stepper-item.done .stepper-circle {
          border-color: #a855f7;
          color: #c084fc;
          background: rgba(168, 85, 247, 0.1);
        }
        .stepper-label {
          font-size: 0.7rem;
          font-weight: 800;
          letter-spacing: 0.08em;
          color: #64748b;
          text-transform: uppercase;
          white-space: nowrap;
          transition: all 0.3s;
        }
        .stepper-item.active .stepper-label { color: #c084fc; }
        .stepper-item.done .stepper-label { color: #a855f7; }
        .stepper-line {
          flex: 1;
          height: 2px;
          background: rgba(255, 255, 255, 0.08);
          margin-top: 27px;
          min-width: 24px;
          transition: all 0.3s;
        }
        .stepper-line.done { background: #a855f7; }

        .wizard-v2-main { flex: 1; display: flex; flex-direction: column; min-width: 0; overflow-y: auto; }

        .wizard-v2-body { padding: 32px 48px; flex: 1; overflow-y: auto; }

        .wizard-v2-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px 32px;
          background: transparent;
          border-top: 1px solid rgba(255, 255, 255, 0.08);
          flex-wrap: wrap;
          gap: 10px;
        }

        .btn-next-v2 {
          background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
          color: white;
          border: none;
          border-radius: 10px;
          padding: 12px 26px;
          font-weight: 700;
          display: flex;
          align-items: center;
          gap: 8px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: pointer;
          box-shadow: 0 4px 15px rgba(124, 58, 237, 0.3);
        }
        .btn-next-v2:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(124, 58, 237, 0.4);
        }
        .btn-next-v2:disabled { opacity: 0.6; cursor: default; transform: none; box-shadow: none; }

        .btn-prev-v2 {
          background: rgba(255, 255, 255, 0.05);
          color: #c084fc;
          border: 1px solid rgba(168, 85, 247, 0.3);
          border-radius: 10px;
          padding: 12px 20px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 8px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: pointer;
        }
        .btn-prev-v2:hover { 
          background: rgba(168, 85, 247, 0.15);
          border-color: rgba(168, 85, 247, 0.8);
        }

        .field-label {
          font-size: 0.75rem;
          font-weight: 700;
          color: #94a3b8;
          text-transform: uppercase;
          letter-spacing: 0.05em;
          margin-bottom: 8px;
          display: block;
        }
        .required-star { color: #ef4444; margin-left: 2px; }

        .file-hint {
          font-size: 0.7rem;
          color: #64748b;
          margin-top: 6px;
        }

        .close-icon-custom { color: #64748b; transition: 0.2s; cursor: pointer; }
        .close-icon-custom:hover { color: #f1f5f9; }

        .form-error-banner {
          margin: 20px 32px 0;
          padding: 10px 16px;
          background: rgba(239,68,68,0.1);
          border: 1px solid rgba(239,68,68,0.4);
          border-radius: 8px;
          color: #fca5a5;
          font-size: 13px;
          font-weight: 500;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .btn-save-update {
          background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
          color: white;
          border: none;
          border-radius: 10px;
          padding: 12px 26px;
          font-weight: 700;
          display: flex;
          align-items: center;
          gap: 6px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: pointer;
          box-shadow: 0 4px 15px rgba(124, 58, 237, 0.3);
        }
        .btn-save-update:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 6px 20px rgba(124, 58, 237, 0.4);
        }
        .btn-save-update:disabled { opacity: 0.6; cursor: default; transform: none; box-shadow: none; }

        .btn-close-modal {
          background: rgba(255, 255, 255, 0.05);
          color: #c084fc;
          border: 1px solid rgba(168, 85, 247, 0.3);
          border-radius: 10px;
          padding: 12px 20px;
          font-weight: 600;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          cursor: pointer;
        }
        .btn-close-modal:hover {
          background: rgba(168, 85, 247, 0.15);
          border-color: rgba(168, 85, 247, 0.8);
        }

        .upload-box-mini-custom {
          width: 80px;
          height: 80px;
          border: 2px dashed rgba(168, 85, 247, 0.3);
          background: rgba(168, 85, 247, 0.02);
          border-radius: 12px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #94a3b8;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .upload-box-mini-custom:hover { 
          border-color: #c084fc; 
          color: #c084fc; 
          background: rgba(168, 85, 247, 0.08);
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(168, 85, 247, 0.15);
        }
        .upload-box-mini-custom span {
          font-size: 0.65rem;
          font-weight: 700;
          text-transform: uppercase;
          letter-spacing: 0.05em;
          margin-top: 4px;
        }

        .preview-card-custom {
          width: 80px;
          height: 80px;
          position: relative;
          border: 1px solid rgba(168, 85, 247, 0.3) !important;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
          border-radius: 12px;
          overflow: hidden;
          transition: all 0.3s ease;
        }
        .preview-card-custom:hover {
          transform: scale(1.05);
          border-color: #c084fc !important;
          box-shadow: 0 6px 20px rgba(168, 85, 247, 0.25);
        }
        .preview-card-custom img { object-fit: cover; }

        .delete-badge-custom {
          position: absolute;
          top: 2px;
          right: 2px;
          background: #ef4444;
          color: white;
          border-radius: 50%;
          width: 18px;
          height: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: 0.2s;
        }
        .delete-badge-custom:hover { transform: scale(1.1); }

        .animate { animation: slideUp 0.4s ease-out; }
        @keyframes slideUp {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }

        @media (max-width: 992px) {
          .directory-container { max-width: 98vw; }
          .directory-table { font-size: 0.75rem; }
          .directory-table td, .directory-table th { padding: 8px 6px; }
          .filter-search-wrapper { flex-direction: column; align-items: stretch; }
          .filter-select-group { flex-wrap: wrap; }
        }

        @media (max-width: 768px) {
          .wizard-v2-stepper { padding: 20px 20px 16px; overflow-x: auto; }
          .stepper-label { font-size: 0.6rem; }
          .stepper-circle { width: 44px; height: 44px; }
          .stepper-line { margin-top: 21px; min-width: 12px; }
          .wizard-v2-body { padding: 20px; }
          .wizard-v2-header { padding: 16px 20px; }
          .wizard-v2-footer { padding: 16px 20px; }
          .form-header { flex-direction: column; align-items: stretch; }
          .form-header .d-flex { flex-wrap: wrap; justify-content: center; }
          .filter-select-group { flex-direction: column; }
          .filter-select { min-width: 100%; }
        }

        @media (max-width: 576px) {
          .lookup-shell { padding: 20px !important; }
          .action-row { flex-direction: column; }
          .wizard-v2-footer { flex-direction: column; }
          .wizard-v2-footer > div { width: 100%; }
          .wizard-v2-footer > div:last-child { flex-direction: column; gap: 6px; }
          .wizard-v2-footer .d-flex { flex-direction: column; width: 100%; }
          .wizard-v2-footer .d-flex button { width: 100%; justify-content: center; }
          .directory-filter-row .d-flex { flex-direction: column; }
          .directory-pagination { flex-direction: column; align-items: stretch; }
          .toast-container { max-width: 90vw; right: 5vw; top: 10px; }
          .tab-btn { font-size: 0.65rem; padding: 4px 8px; }
        }
      `}</style>
</div>
  );
};

export default AddCustomer;
