import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { toast } from 'react-toastify';
import { useTranslation } from 'react-i18next';
import { useSearchWorker } from '../../hooks/useSearchWorker';
import logger from '../../utils/logger';
import { Map, MapMarker, MarkerContent, MapControls } from '../../components/ui/map';
import PageHeader from '../../components/PageHeader';
import { useAuth } from '../../contexts/AuthContext';
import { format } from 'date-fns';
import SignaturePad from '../../components/SignaturePad';
import { useSocket } from '../../contexts/SocketContext';
import { addContactOffline, updateContactOffline, deleteContactOffline } from '../../utils/offlineActions';
import { formatPhoneForTel } from '../../utils/phoneUtils';
import Pagination from '../../components/ui/Pagination';
import { shouldProtectContactData, formatProtectedPhone, formatProtectedAddress, shouldDisableField } from '../../utils/contactDataProtection';
import GPSLocationModal from '../../components/ui/GPSLocationModal';
import { useGPSLocation } from '../../hooks/useGPSLocation';
import {
  UserIcon, UsersIcon, PhoneIcon, BuildingOffice2Icon, EnvelopeIcon,
  MapPinIcon, MapIcon, XMarkIcon, PlusIcon, XCircleIcon, ChevronDownIcon,
  FaceSmileIcon, FaceFrownIcon, CalendarIcon, AdjustmentsHorizontalIcon,
  PencilIcon, TrashIcon, ArrowRightIcon, CheckIcon, ClipboardDocumentCheckIcon,
  ClipboardDocumentListIcon, UserCircleIcon, DevicePhoneMobileIcon, FunnelIcon,
  ArrowDownTrayIcon, ClockIcon, BuildingOfficeIcon, CloudArrowUpIcon,
  ShoppingBagIcon, EyeIcon, ExclamationTriangleIcon, CogIcon, KeyIcon,
  BanknotesIcon, DocumentDuplicateIcon, CurrencyEuroIcon, HomeIcon,
  PhoneArrowUpRightIcon, ArrowUpRightIcon, ChevronUpIcon, MagnifyingGlassIcon,
  UserPlusIcon, ChevronRightIcon, ChevronLeftIcon, HashtagIcon, UserGroupIcon, TagIcon, DocumentArrowDownIcon,
  BellIcon, DocumentTextIcon, PhoneArrowDownLeftIcon, SignalSlashIcon, SpeakerWaveIcon, EllipsisHorizontalIcon, NoSymbolIcon,
  WrenchScrewdriverIcon, CheckCircleIcon, MinusCircleIcon, QuestionMarkCircleIcon, BriefcaseIcon, 
  CurrencyDollarIcon, InformationCircleIcon, BookmarkIcon, ShieldCheckIcon
} from '@heroicons/react/24/outline';
import { useConfirmDialog } from '../../hooks/useDialog';
import { ConfirmDialog, ResponsiveTable, ErrorBoundary } from '../../components/ui';
import { Modal } from '../../components/ui';
import PhoneInput from '../../components/ui/PhoneInput';
import { getPositionWithProgress } from '../../utils/geolocation';
import offlineApi from '../../services/offlineApi';
import { capitalizeWords, createCapitalizedChangeHandler } from '../../utils/textUtils';
import { debounce } from '../../lib/utils';
import { getCurrentAlbanianTime, formatAlbanianTime, formatAlbanianDate, formatAlbanianDateTime, isToday, isFuture, isPast, safeFormatDate, safeFormatTime, safeFormatNumber, getTodayAlbanianDateString } from '../../utils/timezone';
import RboPartHistory from '../../components/RboPartHistory';
import MobileContactsList from '../../components/MobileContactsList';
import MeetingHistoryModal from '../../components/contacts/MeetingHistoryModal';
import * as meetingArchiveApi from '../../services/meetingArchiveApi';
import api from '../../services/api';

const reverseGeocode = async (lat, lng) => {
  // Add Albania country filter to restrict results to Albania only
  const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}&countrycodes=al&addressdetails=1`;
  const res = await fetch(url);
  const data = await res.json();
  return data.display_name || '';
};

export function LocationPicker({ open, onClose, onPick, initialLat, initialLng }) {
  const { t } = useTranslation();
  const [position, setPosition] = React.useState({ lat: initialLat, lng: initialLng });
  const [address, setAddress] = React.useState('');
  const mapRef = React.useRef(null);

  React.useEffect(() => {
    setPosition({ lat: initialLat, lng: initialLng });
  }, [initialLat, initialLng]);

  React.useEffect(() => {
    if (position.lat && position.lng) {
      reverseGeocode(position.lat, position.lng).then(setAddress);
    }
  }, [position]);

  // Handle map click to place marker
  React.useEffect(() => {
    const map = mapRef.current;
    if (!map) return;

    const handleClick = (e) => {
      setPosition({ lat: e.lngLat.lat, lng: e.lngLat.lng });
    };

    map.on('click', handleClick);
    return () => {
      map.off('click', handleClick);
    };
  }, [mapRef.current]);

  return (
    <Modal
      isOpen={open}
      onClose={onClose}
      title={
        <div className="flex items-center gap-2">
          <MapPinIcon className="h-6 w-6" aria-hidden="true" />
          {t('contacts.form.pickLocation')}
        </div>
      }
      size="lg"
    >
      <div className="h-[400px] w-full rounded-lg overflow-hidden mb-3">
        <Map
          ref={mapRef}
          center={[position.lng, position.lat]}
          zoom={16}
          theme="light"
        >
          {position.lat && position.lng && (
            <MapMarker
              longitude={position.lng}
              latitude={position.lat}
              draggable
              onDragEnd={({ lng, lat }) => setPosition({ lat, lng })}
            >
              <MarkerContent>
                <div className="w-6 h-6 bg-[#253988] rounded-full border-2 border-white shadow-lg flex items-center justify-center">
                  <MapPinIcon className="w-4 h-4 text-white" />
                </div>
              </MarkerContent>
            </MapMarker>
          )}
          <MapControls position="bottom-right" showZoom showLocate onLocate={({ latitude, longitude }) => {
            setPosition({ lat: latitude, lng: longitude });
            mapRef.current?.flyTo({ center: [longitude, latitude], zoom: 16 });
          }} />
        </Map>
      </div>
      <div className="mb-4 text-base text-gray-700 dark:text-gray-300">{address}</div>
      <div className="flex justify-end gap-2">
        <button
          onClick={onClose}
          className="px-6 py-2 rounded font-bold text-base text-[#253988] border border-[#253988] bg-white hover:bg-[#253988]/10 transition-colors"
        >
          {t('common.cancel')}
        </button>
        <button
          onClick={() => onPick([position.lat, position.lng], address)}
          className="px-6 py-2 rounded font-bold text-base text-white bg-[#253988] hover:bg-[#253988]/90 transition-colors"
        >
          {t('contacts.selectLocation')}
        </button>
      </div>
    </Modal>
  );
}

// MultiSelect component for associates
export function MultiSelect({ options, value, onChange, placeholder }) {
  const { t } = useTranslation();
  const [isOpen, setIsOpen] = useState(false);
  const [search, setSearch] = useState('');
  const ref = useRef();
  useEffect(() => {
    const handleClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setIsOpen(false);
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);
  const filtered = options.filter(o => `${o.firstName} ${o.lastName}`.toLowerCase().includes(search.toLowerCase()));
  // Keyboard navigation for dropdown
  const handleKeyDown = (e) => {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      setIsOpen(true);
    } else if (e.key === 'Escape') {
      setIsOpen(false);
    }
  };
  return (
    <div className="relative" ref={ref} aria-label={placeholder} onKeyDown={handleKeyDown}>
      <div className="flex flex-wrap gap-1 mb-1">
        {value.map(id => {
          const user = options.find(o => o.id === id);
          if (!user) return null;
          return (
            <span key={id} className="inline-flex items-center px-2 py-1 rounded bg-aura-blue-50 text-aura-blue-700 text-sm font-medium mr-1">
              {user.firstName} {user.lastName}
              <button type="button" className="ml-1 text-aura-blue-400 hover:text-aura-blue-700" onClick={() => onChange(value.filter(v => v !== id))} aria-label={t('common.delete')}><XCircleIcon className="h-4 w-4" aria-hidden="true" /></button>
            </span>
          );
        })}
      </div>
      <button type="button" className="w-full flex items-center justify-between px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-aura-blue focus:border-aura-blue text-left" onClick={() => setIsOpen(v => !v)} aria-haspopup="listbox" aria-expanded={isOpen} aria-label={placeholder}>
        <span className="text-gray-700">{value.length === 0 ? placeholder : ''}</span>
        <ChevronDownIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
      </button>
      {isOpen && (
        <div className="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-auto" role="listbox">
          <input
            className="w-full px-3 py-2 border-b border-gray-100 focus:outline-hidden"
            placeholder={t('common.search')}
            value={search}
            onChange={e => setSearch(e.target.value)}
            autoFocus
            aria-label={t('common.search')}
          />
          {filtered.length === 0 && <div className="p-2 text-gray-400 text-sm">{t('common.noResults')}</div>}
          {filtered.map(u => (
            <div
              key={u.id}
              className={`px-3 py-2 cursor-pointer hover:bg-aura-blue-50 ${value.includes(u.id) ? 'bg-aura-blue-100 text-aura-blue-700' : ''}`}
              onClick={() => {
                if (!value.includes(u.id)) onChange([...value, u.id]);
                setIsOpen(false);
                setSearch('');
              }}
              role="option"
              aria-selected={value.includes(u.id)}
              tabIndex={0}
            >
              {u.firstName} {u.lastName} <span className="text-sm text-gray-400">({u.email})</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

const BRAND_PRIMARY = '#253988';
const BRAND_ACCENT = '#00b0ae';

// Move filterContact to top-level
const filterContact = (contact, includeParent = false, overrideFilter = null, filters, user, searchInContact, regionFilter = null) => {
  if (!user) return false;
  const useFilters = overrideFilter || filters;
  
  // Region filtering (if provided)
  if (regionFilter && contact.region !== regionFilter) return false;
  
  // Date filtering
  if (useFilters.startDate) {
    const startDate = new Date(useFilters.startDate);
    startDate.setHours(0, 0, 0, 0);
    const contactDate = new Date(contact.createdAt);
    if (contactDate < startDate) return false;
  }
  if (useFilters.endDate) {
    const endDate = new Date(useFilters.endDate);
    endDate.setHours(23, 59, 59, 999);
    const contactDate = new Date(contact.createdAt);
    if (contactDate > endDate) return false;
  }
  // Role-based filtering
  if (user.role === 'user') {
    // Allow agents to see contacts where they are assigned OR notified
    if (contact.assignedAgentId !== user.id && contact.notifiedUserId !== user.id) return false;
  } else if (useFilters.agentId && contact.assignedAgentId !== useFilters.agentId) {
    return false;
  }
  // Other filters
  if (useFilters.status) {
    const hasPurchases = contact.purchases && contact.purchases.length > 0;
    const hasReservations = contact.reservations && contact.reservations.length > 0;
    
    let contactStatus;
    if (hasPurchases) {
      contactStatus = 'RBO';
    } else if (hasReservations) {
      contactStatus = 'REZ';
    } else {
      contactStatus = 'NO';
    }
    
    if (contactStatus !== useFilters.status) return false;
  }
  if (useFilters.contacted && String(contact.contacted) !== useFilters.contacted) return false;
  if (useFilters.response && contact.meetingStatus !== useFilters.response) return false;
  if (useFilters.hasUpcomingMeeting) {
    const hasMeeting = contact.meetingDateTime && isFuture(contact.meetingDateTime);
    if (String(hasMeeting) !== useFilters.hasUpcomingMeeting) return false;
  }
  // Search query filtering - should be checked in combination with other filters, not replace them
  if (useFilters.searchQuery && !includeParent) {
    if (!searchInContact(contact, useFilters.searchQuery)) return false;
  }
  return true;
};

// Helper functions for referral status
const getReferralStatus = (referral) => {
  const hasActivePurchases = referral.purchases && referral.purchases.length > 0;
  const hasActiveReservations = referral.reservations && referral.reservations.filter(r => r.status === 'active').length > 0;
  
  if (hasActivePurchases) {
    return 'RBO';
  } else if (hasActiveReservations) {
    return 'REZ';
  } else {
    return 'NO';
  }
};

const getReferralStatusBadgeStyle = (referral) => {
  const status = getReferralStatus(referral);
  switch (status) {
    case 'RBO':
      return 'bg-[#253988] text-white';
    case 'REZ':
      return 'bg-blue-100 text-blue-800';
    case 'NO':
    default:
      return 'bg-gray-200 text-gray-700';
  }
};

// Legend component
const Legend = ({ activeFilter, onFilterClick, contacts, filters, user, searchInContact, legendItems, regionFilter, filterCounts, expiredCount }) => {
  const { t } = useTranslation();

  // Helper to get filtered count for legend items - now uses API counts instead of paginated data
  const getFilteredCount = (filterCriteria) => {
    if (!filterCriteria || !filterCounts) return 0;
    
    // Handle expired filter (client-side only since it needs rental data)
    if (filterCriteria.hasExpired === 'true') {
      return expiredCount || 0;
    }
    
    // Map legend filter criteria to API count keys
    if (filterCriteria.contacted === 'false') {
      return filterCounts.not_contacted || 0;
    }
    
    if (filterCriteria.contacted === 'true' && filterCriteria.response === 'held') {
      return filterCounts.contacted_held || 0;
    }
    
    if (filterCriteria.contacted === 'true' && filterCriteria.response === 'reschedule') {
      return filterCounts.contacted_reschedule || 0;
    }
    
    if (filterCriteria.contacted === 'true' && filterCriteria.response === 'failed') {
      return filterCounts.contacted_failed || 0;
    }
    
    if (filterCriteria.contacted === 'true' && filterCriteria.response === 'do_not_contact') {
      return filterCounts.contacted_do_not_contact || 0;
    }
    
    if (filterCriteria.hasUpcomingMeeting === 'true') {
      return filterCounts.has_upcoming_meeting || 0;
    }
    
    if (filterCriteria.hasUpcomingMeeting === 'false') {
      return filterCounts.no_upcoming_meeting || 0;
    }
    
    // For status-based filters
    if (filterCriteria.status === 'RBO') {
      return filterCounts.rbo || 0;
    }
    
    if (filterCriteria.status === 'REZ') {
      return filterCounts.rez || 0;
    }
    
    if (filterCriteria.status === 'NO') {
      return filterCounts.no || 0;
    }
    
    // Fallback to old method for any unmapped criteria
    return contacts.filter(contact => filterContact(contact, false, filterCriteria, filters, user, searchInContact, regionFilter)).length;
  };

  return (
    <div className="mb-6 bg-white shadow-lg rounded-xl overflow-hidden border border-gray-100">
      <div className="px-6 py-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-medium text-gray-700 flex items-center gap-2">
            <AdjustmentsHorizontalIcon className="h-5 w-5" />
            {t('contacts.legend.title')}
          </h3>
          {activeFilter && (
            <button
              onClick={() => onFilterClick(null)}
              className="text-sm text-gray-500 hover:text-gray-700 flex items-center gap-1"
            >
              <XMarkIcon className="h-4 w-4" />
              {t('common.clearFilters')}
            </button>
          )}
        </div>
        <div className="flex flex-wrap gap-2">
          {legendItems.map(item => (
            <button
              key={item.id}
              onClick={() => onFilterClick(item.filter, item.id)}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-all ${
                activeFilter === item.id 
                ? 'ring-2 ring-offset-2 ring-blue-500' 
                : 'hover:ring-2 hover:ring-offset-2 hover:ring-blue-200'
              } ${item.bgColor} ${item.textColor} ${
                item.id === 'not_contacted' ? 'border border-gray-300' : ''
              }`}
            >
              {item.icon}
              <span className="text-sm font-medium">{item.label}</span>
              <span className="text-sm text-gray-500">
                ({getFilteredCount(item.filter)})
              </span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

// Add this helper function near the top of the file, after imports
const formatDateLocalized = (date, locale) => {
  const options = { 
    weekday: 'long', 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric' 
  };
  
  // Convert string to Date if needed
  const dateObj = typeof date === 'string' ? new Date(date) : date;
  
  // Check if date is valid
  if (!dateObj || isNaN(dateObj.getTime())) {
    logger.warn('Invalid date provided to formatDateLocalized:', date);
    return '';
  }
  
  try {
    return dateObj.toLocaleDateString(locale === 'sq' ? 'sq-AL' : 'en-GB', options);
  } catch (e) {
    // Fallback to en-GB if locale is not supported
    try {
      return dateObj.toLocaleDateString('en-GB', options);
    } catch (fallbackError) {
      logger.warn('Date formatting failed:', fallbackError);
      return '';
    }
  }
};

const ContactDetails = ({ contact, onClose, onEdit }) => {
  const { t } = useTranslation();
  const [products, setProducts] = useState([]);

  // Helper function to determine if contact is RBO
  const isContactRBO = (contact) => {
    if (!contact) return false;
    // Multi-product system: Check for active purchases
    const hasActivePurchases = contact.purchases && contact.purchases.length > 0;
    return hasActivePurchases;
  };

  useEffect(() => {
    if (isContactRBO(contact)) {
      fetch('/api/products', { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } })
        .then(res => res.json())
        .then(data => setProducts(Array.isArray(data) ? data : []))
        .catch(() => setProducts([]));
    }
  }, [contact]);

  const product = isContactRBO(contact) ? products.find(p => p.id === contact.rboProductId) : null;

  return (
    <div className="bg-white rounded-lg shadow-lg p-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-xl font-semibold text-gray-900">
          {contact.name} {contact.surname}
        </h2>
        <div className="flex space-x-2">
          <button
            onClick={onEdit}
            className="p-2 text-aura-blue hover:bg-aura-blue-50 rounded-lg"
          >
            <PencilIcon className="h-5 w-5" aria-hidden="true" />
          </button>
          <button
            onClick={onClose}
            className="p-2 text-gray-500 hover:bg-gray-100 rounded-lg"
          >
            <XMarkIcon className="h-5 w-5" aria-hidden="true" />
          </button>
        </div>
      </div>

      <div className="space-y-4">
        {/* ... existing contact details ... */}

        {/* RBO Section */}
        {isContactRBO(contact) && (
          <div className="border-t border-gray-100 pt-4">
            <h3 className="text-sm font-medium text-gray-900 mb-2">
              {t('contacts.rboInfo', 'RBO Information')}
            </h3>
            {product ? (
              <div className="bg-aura-blue-50 rounded-lg p-4">
                <div className="flex items-start space-x-4">
                  <div className="flex-1">
                    <h4 className="text-sm font-medium text-gray-900">{product.name}</h4>
                    <p className="text-sm text-gray-500 mt-1">#{product.number}</p>
                    {contact.rboStartDate && (
                      <div className="mt-3 space-y-1">
                        <p className="text-sm text-gray-600">
                          📅 <span className="font-medium">{t('contacts.installationDate', 'Installation Date')}:</span> {
                            formatAlbanianDate(contact.rboStartDate)
                          }
                        </p>
                        {contact.rboInstallmentMonths && (
                          <p className="text-sm text-gray-600">
                            🔧 <span className="font-medium">{t('contacts.nextFilterReplacement', 'Next Filter Replacement')}:</span> {
                              (() => {
                                const startDate = new Date(contact.rboStartDate);
                                // Calculate the due date (1 year from installation)
                                const dueDate = new Date(startDate);
                                dueDate.setFullYear(dueDate.getFullYear() + 1);
                                // Subtract 15 days to get the replacement reminder date
                                const replacementDate = new Date(dueDate);
                                replacementDate.setDate(replacementDate.getDate() - 15);
                                return formatAlbanianDate(replacementDate);
                              })()
                            }
                          </p>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <p className="text-sm text-gray-500">
                {t('contacts.noProductSelected', 'No product selected')}
              </p>
            )}
            
            {/* RBO Part History Section */}
            {contact.rboStartDate && (
              <div className="mt-6">
                <RboPartHistory contactId={contact.id} isAdmin={isAdmin} />
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};



// Geocode address using Nominatim
async function geocodeAddress(address) {
  if (!address) return null;
  // Add Albania country filter and bounding box to restrict results to Albania only
  const albanianBounds = '19.2,39.6,21.1,42.7'; // min_lon,min_lat,max_lon,max_lat for Albania
  const url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}&countrycodes=al&viewbox=${albanianBounds}&bounded=1&addressdetails=1`;
  try {
    const res = await fetch(url);
    const data = await res.json();
    if (data && data.length > 0) {
      // Additional validation: ensure the result is actually in Albania
      const lat = parseFloat(data[0].lat);
      const lng = parseFloat(data[0].lon);
      
      // Albania bounding box validation
      if (lat >= 39.6 && lat <= 42.7 && lng >= 19.2 && lng <= 21.1) {
        return {
          lat: lat,
          lng: lng,
          displayName: data[0].display_name
        };
      }
    }
  } catch {}
  return null;
}

// Helper to format Albanian phone numbers as '067 123 4567'
function formatPhoneNumber(phone) {
  if (!phone) return '';
  // Only format if 10 digits and starts with 067/068/069
  if (/^(067|068|069)\d{7}$/.test(phone)) {
    return `${phone.slice(0, 3)} ${phone.slice(3, 6)} ${phone.slice(6)}`;
  }
  return phone;
}

// Product Form Component
const ProductForm = ({ type, editingProduct, products, users, onSubmit, onCancel, isSubmitting }) => {
  const { t } = useTranslation();
  const [formData, setFormData] = useState({
    productId: editingProduct?.productId || '',
    sellerId: editingProduct?.sellerId || '',
    serialNumber: editingProduct?.serialNumber || '',
    amount: editingProduct?.amount || '',
    currency: editingProduct?.currency || 'EUR',
    paymentType: editingProduct?.paymentType || 'cash',
    installmentMonths: editingProduct?.installmentMonths || 1,
    notes: editingProduct?.notes || '',
    date: editingProduct 
      ? (type === 'purchase' ? editingProduct.purchaseDate : editingProduct.reservationDate)
      : new Date().toISOString().split('T')[0]
  });

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

  const handleSubmit = (e) => {
    e.preventDefault();
    
    const productData = {
      productId: formData.productId,
      sellerId: formData.sellerId,
      amount: parseFloat(formData.amount) || null,
      currency: formData.currency,
      notes: formData.notes || null
    };

    if (type === 'purchase') {
      productData.serialNumber = formData.serialNumber;
      productData.purchaseDate = formData.date;
      productData.paymentType = formData.paymentType;
      if (formData.paymentType === 'bank') {
        productData.installmentMonths = parseInt(formData.installmentMonths, 10);
      }
    } else {
      productData.reservationDate = formData.date;
    }

    if (editingProduct) {
      onSubmit(editingProduct.id, productData);
    } else {
      onSubmit(productData);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Product Selection */}
      <div>
        <label className="block text-sm font-semibold mb-2 text-gray-700">
          <ShoppingBagIcon className="h-4 w-4 inline mr-2" />
          {t('contacts.rboProduct')} <span className="text-red-500">*</span>
        </label>
        <select
          name="productId"
          value={formData.productId}
          onChange={handleChange}
          className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
          required
        >
          <option value="">{t('common.select')}</option>
          {products.map(product => (
            <option key={product.id} value={product.id}>
              {product.name}
            </option>
          ))}
        </select>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Seller */}
        <div>
          <label className="block text-sm font-semibold mb-2 text-gray-700">
            <UserIcon className="h-4 w-4 inline mr-2" />
            {t('contacts.rboSeller')} <span className="text-red-500">*</span>
          </label>
          <select
            name="sellerId"
            value={formData.sellerId}
            onChange={handleChange}
            className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
            required
          >
            <option value="">{t('common.select')}</option>
            {users.map(user => {
              const isInactive = user.isActive === false;
              return (
                <option key={user.id} value={user.id}>
                  {user.firstName} {user.lastName}{isInactive ? ` (${t('common.statusOptions.inactive')})` : ''}
                </option>
              );
            })}
          </select>
        </div>

        {/* Date */}
        <div>
          <label className="block text-sm font-semibold mb-2 text-gray-700">
            <CalendarIcon className="h-4 w-4 inline mr-2" />
            {type === 'purchase' ? t('contacts.rboStartDate') : t('contacts.rezDate')} <span className="text-red-500">*</span>
          </label>
          <input
            type="date"
            name="date"
            value={formData.date}
            onChange={handleChange}
            className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
            required
          />
        </div>

        {/* Serial Number (only for purchases) */}
        {type === 'purchase' && (
          <div>
            <label className="block text-sm font-semibold mb-2 text-gray-700">
              <HashtagIcon className="h-4 w-4 inline mr-2" />
              {t('contacts.rboSerialNumber')} <span className="text-red-500">*</span>
            </label>
            <input
              name="serialNumber"
              value={formData.serialNumber}
              onChange={handleChange}
              className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
              required
              placeholder={t('contacts.rboSerialNumberPlaceholder')}
            />
          </div>
        )}

        {/* Currency */}
        <div>
          <label className="block text-sm font-semibold mb-2 text-gray-700">
            {t('contacts.rboPayment.currency')} <span className="text-red-500">*</span>
          </label>
          <select
            name="currency"
            value={formData.currency}
            onChange={handleChange}
            className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
          >
            <option value="EUR">EUR</option>
            <option value="ALL">ALL</option>
          </select>
        </div>

        {/* Amount */}
        <div>
          <label className="block text-sm font-semibold mb-2 text-gray-700">
            {type === 'purchase' ? t('contacts.rboPayment.amount') : t('contacts.rezAmount')} <span className="text-red-500">*</span>
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <span className="text-gray-500 text-sm">
                {formData.currency === 'EUR' ? '€' : 'L'}
              </span>
            </div>
            <input
              type="number"
              name="amount"
              value={formData.amount}
              onChange={handleChange}
              placeholder="0.00"
              className="block w-full pl-8 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
              step="0.01"
              required
            />
          </div>
        </div>

        {/* Payment Type (only for purchases) */}
        {type === 'purchase' && (
          <>
            <div>
              <label className="block text-sm font-semibold mb-2 text-gray-700">
                {t('contacts.rboPayment.paymentType')} <span className="text-red-500">*</span>
              </label>
              <select
                name="paymentType"
                value={formData.paymentType}
                onChange={handleChange}
                className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
              >
                <option value="cash">{t('contacts.rboPayment.cash')}</option>
                <option value="bank">{t('contacts.rboPayment.bank')}</option>
              </select>
            </div>

            {/* Installment Months (only for bank payments) */}
            {formData.paymentType === 'bank' && (
              <div>
                <label className="block text-sm font-semibold mb-2 text-gray-700">
                  {t('contacts.rboPayment.installmentMonths')} <span className="text-red-500">*</span>
                </label>
                <input
                  type="number"
                  name="installmentMonths"
                  value={formData.installmentMonths}
                  onChange={handleChange}
                  min="1"
                  max="24"
                  step="1"
                  className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                />
              </div>
            )}
          </>
        )}
      </div>

      {/* Notes */}
      <div>
        <label className="block text-sm font-semibold mb-2 text-gray-700">
          <DocumentTextIcon className="h-4 w-4 inline mr-2" />
          {t('common.notes')}
        </label>
        <textarea
          name="notes"
          value={formData.notes}
          onChange={handleChange}
          rows={3}
          className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
          placeholder={t('contacts.notesPlaceholder')}
        />
      </div>

      {/* Form Actions */}
      <div className="flex justify-end space-x-3 pt-4 border-t border-gray-200">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500"
        >
          {t('common.cancel')}
        </button>
        <button
          type="submit"
          disabled={isSubmitting}
          className="px-4 py-2 text-sm font-medium text-white bg-[#253988] border border-transparent rounded-lg hover:bg-[#253988]/90 focus:outline-none focus:ring-2 focus:ring-[#253988] disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isSubmitting ? t('common.saving', 'Saving...') : (editingProduct ? t('common.save') : t('common.add'))}
        </button>
      </div>
    </form>
  );
};

// ========================================
// MEMOIZED CONTACT ROW COMPONENT
// ========================================
// This component prevents unnecessary re-renders by only updating
// when the contact data actually changes, resulting in 10-20x better performance
const ContactRow = React.memo(({ 
  contact,
  user,
  isAgent,
  isAdmin,
  isOperator,
  canEditDelete,
  showAgentColumn,
  getRowBackgroundColor,
  formatPhoneForTel,
  getAgent,
  hasRental,
  getGoogleMapsUrl,
  truncate,
  hasReferralActivity,
  showReferralsInfo,
  startAddReferrals,
  startEdit,
  setShowEditModal,
  deleteContact,
  contactsWithHistory,
  setHistoryContact,
  setShowMeetingHistoryModal,
  t
}) => {
  return (
    <tr className={getRowBackgroundColor(contact)}>
      {/* Name */}
      <td className="px-3 py-3 whitespace-nowrap text-sm font-medium text-gray-900 max-w-[150px] truncate">
        {contact.name} {contact.surname}
      </td>

      {/* Phone */}
      <td className="px-3 py-3 whitespace-nowrap max-w-[110px]">
        <div className="flex flex-col gap-1 items-start">
          {contact._dataMasked || !contact.phone ? (
            <span 
              className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-amber-50 text-amber-700"
              title={t('contacts.dataProtectedInfo')}
            >
              {t('contacts.phoneProtected')}
            </span>
          ) : (
            <>
              <a href={`tel:${formatPhoneForTel(contact.phone)}`} className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-gray-100 text-gray-800 hover:bg-gray-200 transition-colors">
                {contact.phone}
              </a>
              {contact.secondaryPhone && (
                <a href={`tel:${formatPhoneForTel(contact.secondaryPhone)}`} className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-gray-100 text-gray-800 hover:bg-gray-200 transition-colors">
                  {contact.secondaryPhone}
                </a>
              )}
            </>
          )}
        </div>
      </td>

      {/* Address */}
      <td className="px-3 py-3 whitespace-nowrap text-sm text-gray-900 max-w-[180px]">
        {contact._dataMasked ? (
          <span 
            className="text-amber-700 text-sm"
            title={t('contacts.dataProtectedInfo')}
          >
            {t('contacts.addressProtected')}
          </span>
        ) : contact.address ? (
          <a
            href={getGoogleMapsUrl(contact)}
            target="_blank"
            rel="noopener noreferrer"
            className="text-aura-blue hover:underline flex items-center"
            title={contact.address}
            aria-label={t('contacts.openInMaps', { address: contact.address })}
          >
            <MapPinIcon className="h-3 w-3 mr-1 shrink-0" />
            <span className="truncate">{truncate(contact.address, 18)}</span>
          </a>
        ) : '-'}
      </td>

      {/* Profession */}
      <td className="px-3 py-3 whitespace-nowrap text-sm text-gray-900 max-w-[120px] truncate">
        {contact.profession || '-'}
      </td>

      {/* Status (RBO/REZ/NO) - Only for non-agents */}
      {!isAgent && (
        <>
          <td className="px-3 py-3 whitespace-nowrap w-[80px]">
            <div className="flex flex-col gap-1.5 items-center">
              {(() => {
                const hasPurchases = contact.purchases && contact.purchases.length > 0;
                const hasReservations = contact.reservations && contact.reservations.length > 0;
                
                if (hasPurchases) {
                  return (
                    <span className="inline-flex items-center justify-center px-2.5 py-1 rounded-full text-xs font-semibold bg-[#253988] text-white min-w-[50px] shadow-sm">
                      RBO
                    </span>
                  );
                } else if (hasReservations) {
                  return (
                    <span className="inline-flex items-center justify-center px-2.5 py-1 rounded-full text-xs font-semibold bg-orange-500 text-white min-w-[50px] shadow-sm">
                      REZ
                    </span>
                  );
                } else {
                  return (
                    <span className="inline-flex items-center justify-center px-2.5 py-1 rounded-full text-xs font-semibold bg-gray-400 text-white min-w-[50px] shadow-sm">
                      NO
                    </span>
                  );
                }
              })()}
            </div>
          </td>

          {/* Rental */}
          <td className="px-3 py-3 whitespace-nowrap max-w-[50px]">
            <span className={`inline-block px-1.5 py-0.5 rounded text-xs font-medium ${hasRental(contact.id) ? 'bg-green-100 text-green-800' : 'bg-gray-200 text-gray-700'}`}>
              {hasRental(contact.id) ? t('common.yes', 'YES') : t('common.no', 'NO')}
            </span>
          </td>
        </>
      )}

      {/* Agent Column */}
      {showAgentColumn && (
        <td className="px-3 py-3 whitespace-nowrap text-sm text-gray-500 max-w-[100px] truncate">
          {getAgent(contact)}
        </td>
      )}

      {/* Contact Attempt Reason */}
      {(isAdmin || isOperator) && (
        <td className="px-3 py-3 whitespace-nowrap max-w-[120px]">
          {contact.contactAttemptReason ? (
            <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold shadow-sm truncate ${
              contact.contactAttemptReason === 'no_answer' || contact.contactAttemptReason === 'disconnected' 
                ? 'bg-gray-500 text-white' :
              contact.contactAttemptReason === 'busy' 
                ? 'bg-aura-blue text-white' :
              contact.contactAttemptReason === 'not_interested' 
                ? 'bg-red-500 text-white' :
              contact.contactAttemptReason === 'callback_requested' 
                ? 'bg-green-500 text-white' :
              contact.contactAttemptReason === 'wrong_number' 
                ? 'bg-yellow-500 text-white' :
              contact.contactAttemptReason === 'voicemail' 
                ? 'bg-purple-500 text-white' :
              contact.contactAttemptReason === 'other' 
                ? 'bg-slate-500 text-white' :
              'bg-gray-500 text-white'
            }`}>
              {t(`contactAttempt.reason.${contact.contactAttemptReason}`)}
            </span>
          ) : (
            <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-200 text-gray-500">
              -
            </span>
          )}
        </td>
      )}

      {/* Actions */}
      {(canEditDelete || isAgent) && (
        <td className="px-3 py-3 whitespace-nowrap text-right text-sm font-medium max-w-[150px]">
          {/* Meeting History Icon - Show if contact has archived meetings */}
          {contactsWithHistory && contactsWithHistory.has(contact.id) && (
            <button
              onClick={() => {
                setHistoryContact(contact);
                setShowMeetingHistoryModal(true);
              }}
              className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
              aria-label={t('meetings.viewHistory')}
              title={t('meetings.viewHistory')}
            >
              <ClockIcon className="h-5 w-5" aria-hidden="true" />
            </button>
          )}
          
          {/* Referrals info button */}
          {hasReferralActivity(contact) && (
            <button
              onClick={() => showReferralsInfo(contact)}
              className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
              aria-label={t('contacts.viewReferrals')}
            >
              <UserGroupIcon className="h-5 w-5" aria-hidden="true" />
            </button>
          )}

          {isAgent ? (
            // Agent sees edit and referral buttons
            <>
              <button
                onClick={() => startAddReferrals(contact)}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
                aria-label={t('contacts.addReferral')}
              >
                <UserPlusIcon className="h-5 w-5" aria-hidden="true" />
              </button>
              <button
                onClick={() => { startEdit(contact); setShowEditModal(true); }}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 transition-colors"
                aria-label={t('common.edit')}
              >
                <PencilIcon className="h-5 w-5" aria-hidden="true" />
              </button>
            </>
          ) : isOperator ? (
            // Operator sees add referral, edit, and delete buttons
            <>
              <button
                onClick={() => startAddReferrals(contact)}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
                aria-label={t('contacts.addReferral')}
              >
                <UserPlusIcon className="h-5 w-5" aria-hidden="true" />
              </button>
              <button
                onClick={() => { startEdit(contact); setShowEditModal(true); }}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
                aria-label={t('common.edit')}
              >
                <PencilIcon className="h-5 w-5" aria-hidden="true" />
              </button>
              <button
                onClick={() => deleteContact(contact.id)}
                className="inline-flex items-center text-red-600 hover:text-red-900 transition-colors"
                aria-label={t('common.delete')}
              >
                <TrashIcon className="h-5 w-5" aria-hidden="true" />
              </button>
            </>
          ) : (
            // Admin/Owner see all buttons
            <>
              <button
                onClick={() => startAddReferrals(contact)}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
                aria-label={t('contacts.addReferral')}
              >
                <UserPlusIcon className="h-5 w-5" aria-hidden="true" />
              </button>
              <button
                onClick={() => { startEdit(contact); setShowEditModal(true); }}
                className="inline-flex items-center text-aura-blue hover:text-aura-blue-700 mr-2 transition-colors"
                aria-label={t('common.edit')}
              >
                <PencilIcon className="h-5 w-5" aria-hidden="true" />
              </button>
              <button
                onClick={() => deleteContact(contact.id)}
                className="inline-flex items-center text-red-600 hover:text-red-900 transition-colors"
                aria-label={t('common.delete')}
              >
                <TrashIcon className="h-5 w-5" aria-hidden="true" />
              </button>
            </>
          )}
        </td>
      )}
    </tr>
  );
}, (prevProps, nextProps) => {
  // Custom comparison function - only re-render if contact data actually changed
  // This is the key to performance: React will skip re-rendering if this returns true
  return (
    prevProps.contact.id === nextProps.contact.id &&
    prevProps.contact.updatedAt === nextProps.contact.updatedAt &&
    prevProps.contact._dataMasked === nextProps.contact._dataMasked &&
    prevProps.contact.name === nextProps.contact.name &&
    prevProps.contact.surname === nextProps.contact.surname &&
    prevProps.contact.phone === nextProps.contact.phone &&
    prevProps.contact.secondaryPhone === nextProps.contact.secondaryPhone &&
    prevProps.contact.address === nextProps.contact.address &&
    prevProps.contact.profession === nextProps.contact.profession &&
    prevProps.contact.status === nextProps.contact.status &&
    prevProps.contact.contacted === nextProps.contact.contacted &&
    prevProps.contact.contactAttemptReason === nextProps.contact.contactAttemptReason &&
    prevProps.contact.meetingStatus === nextProps.contact.meetingStatus &&
    prevProps.contact.meetingDateTime === nextProps.contact.meetingDateTime &&
    prevProps.isAgent === nextProps.isAgent &&
    prevProps.canEditDelete === nextProps.canEditDelete &&
    prevProps.showAgentColumn === nextProps.showAgentColumn
  );
});

// Add display name for React DevTools
ContactRow.displayName = 'ContactRow';

// Memoized Mobile Contact Card
const ContactMobileCard = React.memo(({
  contact,
  highlightId,
  highlightRef,
  isAgent,
  user,
  getAgent,
  getGoogleMapsUrl,
  getRowBackgroundColor,
  hasRental,
  formatPhoneForTel,
  truncate,
  hasReferralActivity,
  showReferralsInfo,
  startAddReferrals,
  startEdit,
  deleteContact,
  renderStatusIcons,
  isOperator,
  isAdmin,
  contacts,
  contactsWithHistory,
  setHistoryContact,
  setShowMeetingHistoryModal,
  t
}) => {
  if (!contact || typeof contact !== 'object' || !contact.id) {
    return null;
  }

  const agentName = getAgent(contact);
  const mapsUrl = getGoogleMapsUrl(contact);
  const rowColor = getRowBackgroundColor(contact);
  const isHighlighted = highlightId === String(contact.id);

  return (
    <div
      key={contact.id}
      ref={isHighlighted ? highlightRef : null}
      data-highlighted={isHighlighted ? "true" : "false"}
      className={isHighlighted
        ? "p-4 mb-3 rounded-lg shadow-lg border-2 border-yellow-400 bg-yellow-200 ring-2 ring-yellow-400 ring-opacity-50"
        : `p-4 mb-3 rounded-lg shadow-md border border-gray-200 ${rowColor}`
      }
    >
      <div className="flex justify-between items-start mb-2">
        <div className="flex items-center gap-2">
          <h3 className="text-lg font-semibold text-aura-blue-700">
            {contact.name} {contact.surname} {isHighlighted && "🔥 HIGHLIGHTED! 🔥"}
          </h3>
        </div>
        {!isAgent && (
          <div className="flex gap-2 flex-wrap">
            {(() => {
              const hasPurchases = contact.purchases && contact.purchases.length > 0;
              const hasReservations = contact.reservations && contact.reservations.length > 0;

              if (hasPurchases) {
                return (
                  <span className="px-2.5 py-1 text-sm font-semibold bg-[#253988] text-white rounded-full shadow-sm">
                    RBO
                  </span>
                );
              } else if (hasReservations) {
                return (
                  <span className="px-2.5 py-1 text-sm font-semibold bg-orange-500 text-white rounded-full shadow-sm">
                    REZ
                  </span>
                );
              } else {
                return (
                  <span className="px-2.5 py-1 text-sm font-semibold bg-gray-400 text-white rounded-full shadow-sm">
                    NO
                  </span>
                );
              }
            })()}

            {hasRental(contact.id) && (
              <span className="px-2.5 py-1 text-sm font-semibold bg-purple-500 text-white rounded-full shadow-sm">
                {t('common.rental')}
              </span>
            )}
            {contact.contactAttemptReason && (
              <span className={`px-2.5 py-1 text-sm font-semibold rounded-full shadow-sm ${
                contact.contactAttemptReason === 'no_answer' || contact.contactAttemptReason === 'disconnected'
                  ? 'bg-gray-500 text-white' :
                contact.contactAttemptReason === 'busy'
                  ? 'bg-aura-blue text-white' :
                contact.contactAttemptReason === 'not_interested'
                  ? 'bg-red-500 text-white' :
                contact.contactAttemptReason === 'callback_requested'
                  ? 'bg-green-500 text-white' :
                contact.contactAttemptReason === 'wrong_number'
                  ? 'bg-yellow-500 text-white' :
                contact.contactAttemptReason === 'voicemail'
                  ? 'bg-purple-500 text-white' :
                contact.contactAttemptReason === 'other'
                  ? 'bg-slate-500 text-white' :
                'bg-gray-500 text-white'
              }`}>
                {t(`contactAttempt.reason.${contact.contactAttemptReason}`)}
              </span>
            )}
          </div>
        )}
      </div>

      <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm text-gray-700 mb-3">
        <div className="flex items-center gap-2">
          <DevicePhoneMobileIcon className="h-5 w-5 text-green-600 shrink-0" />
          <div className="flex flex-col gap-1">
            {contact._dataMasked || !contact.phone ? (
              <span
                className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-amber-50 text-amber-700"
                title={t('contacts.dataProtectedInfo')}
              >
                {t('contacts.phoneProtected')}
              </span>
            ) : (
              <>
                <span className="text-sm text-gray-900 font-mono">{contact.phone}</span>
                {contact.secondaryPhone && (
                  <span className="text-sm text-gray-900 font-mono">{contact.secondaryPhone}</span>
                )}
              </>
            )}
          </div>
        </div>
        {(contact.address || contact._dataMasked) && (
          <div className="col-span-2 flex items-center gap-2">
            <MapPinIcon className="h-5 w-5 text-red-500 shrink-0" />
            {contact._dataMasked || !contact.address ? (
              <span
                className="text-amber-700 text-sm"
                title={t('contacts.dataProtectedInfo')}
              >
                {t('contacts.addressProtected')}
              </span>
            ) : (
              <span>{truncate(contact.address, 40)}</span>
            )}
          </div>
        )}
        {contact.profession && (
          <div className="col-span-2 flex items-center gap-2">
            <BriefcaseIcon className="h-5 w-5 text-purple-600 shrink-0" />
            <span>{contact.profession}</span>
          </div>
        )}
        <div className="flex items-center gap-2 col-span-2">
          <UserCircleIcon className="h-5 w-5 text-blue-600 shrink-0" />
          <span>{agentName}</span>
        </div>
      </div>

      {(contact.referredByContactId || contact.referrer) && (
        <div className="mt-3 pt-3 border-t border-gray-100">
          <div className="text-sm text-gray-600">
            <span className="font-medium">{t('contacts.referredBy')}: </span>
            {contact.referrer ? (
              <span className="text-gray-900">{contact.referrer.name} {contact.referrer.surname}</span>
            ) : (
              (() => {
                const referrer = contacts.find(c => c.id === contact.referredByContactId);
                return referrer ? (
                  <span className="text-gray-900">{referrer.name} {referrer.surname}</span>
                ) : (
                  <span className="text-gray-500">{t('contacts.unknownReferrer')}</span>
                );
              })()
            )}
          </div>
        </div>
      )}

      <div className="mt-4 pt-3 border-t border-gray-200 flex justify-between items-center">
        <div className="flex items-center gap-2">
          {renderStatusIcons(contact)}
        </div>

        <div className="flex items-center">
          <div className="flex items-center gap-2">
            {contact.phone && !contact._dataMasked && (
              <a
                href={`tel:${formatPhoneForTel(contact.phone)}`}
                className="p-2 text-gray-500 hover:text-aura-blue-600 transition-colors rounded-full hover:bg-aura-blue-50"
                aria-label={t('contacts.callNumber', { number: contact.phone })}
              >
                <PhoneArrowUpRightIcon className="h-5 w-5" />
              </a>
            )}
            {contact.secondaryPhone && !contact._dataMasked && (
              <a
                href={`tel:${formatPhoneForTel(contact.secondaryPhone)}`}
                className="p-2 text-gray-500 hover:text-aura-blue-600 transition-colors rounded-full hover:bg-aura-blue-50"
                aria-label={t('contacts.callSecondaryNumber', { number: contact.secondaryPhone })}
              >
                <PhoneArrowUpRightIcon className="h-5 w-5" />
              </a>
            )}
            {mapsUrl && !contact._dataMasked && (
              <a
                href={mapsUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2 text-gray-500 hover:text-aura-green-600 transition-colors rounded-full hover:bg-aura-green-100"
                aria-label={t('contacts.openInMaps', { address: contact.address })}
              >
                <MapPinIcon className="h-5 w-5" />
              </a>
            )}
          </div>

          <div className="flex items-center gap-2 ml-4">
            {/* Meeting History indicator - Show for contacts with archived meetings */}
            {contactsWithHistory && contactsWithHistory.has(contact.id) && (
              <button
                onClick={() => {
                  setHistoryContact(contact);
                  setShowMeetingHistoryModal(true);
                }}
                className="p-2 text-aura-blue hover:text-aura-blue-700 transition-colors rounded-full hover:bg-aura-blue-50"
                aria-label={t('meetings.viewHistory')}
                title={t('meetings.viewHistory')}
              >
                <ClockIcon className="h-5 w-5" />
              </button>
            )}

            {hasReferralActivity(contact) && (
              <button
                onClick={() => showReferralsInfo(contact)}
                className="p-2 text-gray-500 hover:text-blue-600 transition-colors rounded-full hover:bg-blue-50"
                aria-label={t('contacts.viewReferrals')}
              >
                <UserGroupIcon className="h-5 w-5" />
              </button>
            )}

            {isAgent ? (
              <>
                <button
                  onClick={() => startAddReferrals(contact)}
                  className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                  aria-label={t('contacts.addReferral')}
                >
                  <UserPlusIcon className="h-5 w-5" />
                </button>
                <button
                  onClick={() => startEdit(contact)}
                  className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                  aria-label={t('common.edit')}
                >
                  <PencilIcon className="h-5 w-5" />
                </button>
              </>
            ) : isOperator ? (
              <>
                <button
                  onClick={() => startAddReferrals(contact)}
                  className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                  aria-label={t('contacts.addReferral')}
                >
                  <UserPlusIcon className="h-5 w-5" />
                </button>
                <button
                  onClick={() => startEdit(contact)}
                  className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                  aria-label={t('common.edit')}
                >
                  <PencilIcon className="h-5 w-5" />
                </button>
                <button
                  onClick={() => deleteContact(contact.id)}
                  className="p-2 text-red-500 hover:text-red-700 transition-colors rounded-full hover:bg-red-50"
                  aria-label={t('common.delete')}
                >
                  <TrashIcon className="h-5 w-5" />
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={() => startAddReferrals(contact)}
                  className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                  aria-label={t('contacts.addReferral')}
                >
                  <UserPlusIcon className="h-5 w-5" />
                </button>
                <button
                  onClick={() => startEdit(contact)}
                  className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                  aria-label={t('common.edit')}
                >
                  <PencilIcon className="h-5 w-5" />
                </button>
                <button
                  onClick={() => deleteContact(contact.id)}
                  className="p-2 text-red-500 hover:text-red-700 transition-colors rounded-full hover:bg-red-50"
                  aria-label={t('common.delete')}
                >
                  <TrashIcon className="h-5 w-5" />
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}, (prevProps, nextProps) => {
  return (
    prevProps.contact.id === nextProps.contact.id &&
    prevProps.contact.updatedAt === nextProps.contact.updatedAt &&
    prevProps.contact._dataMasked === nextProps.contact._dataMasked &&
    prevProps.contact.name === nextProps.contact.name &&
    prevProps.contact.surname === nextProps.contact.surname &&
    prevProps.contact.phone === nextProps.contact.phone &&
    prevProps.contact.secondaryPhone === nextProps.contact.secondaryPhone &&
    prevProps.contact.address === nextProps.contact.address &&
    prevProps.contact.profession === nextProps.contact.profession &&
    prevProps.contact.status === nextProps.contact.status &&
    prevProps.contact.contacted === nextProps.contact.contacted &&
    prevProps.contact.contactAttemptReason === nextProps.contact.contactAttemptReason &&
    prevProps.contact.meetingStatus === nextProps.contact.meetingStatus &&
    prevProps.contact.meetingDateTime === nextProps.contact.meetingDateTime &&
    prevProps.highlightId === nextProps.highlightId &&
    prevProps.isAgent === nextProps.isAgent
  );
});

ContactMobileCard.displayName = 'ContactMobileCard';

// ========================================
// MAIN CONTACTS COMPONENT
// ========================================
const Contacts = () => {
  const { t, i18n } = useTranslation();
  const { user } = useAuth();
  const { isConnected, addEventListener } = useSocket();
  const { isOpen: isConfirmOpen, config: confirmConfig, confirm, closeDialog: closeConfirm } = useConfirmDialog();
  const [step, setStep] = useState(1); // 1: client, 2: referrals
  const [client, setClient] = useState({
    date: getTodayAlbanianDateString(),
    name: '',
    surname: '',
    phone: '',
    secondaryPhone: '',
    address: '',
    addressLat: '',
    addressLng: '',
    associateIds: [],
    isRBO: false,
    notes: '',
    gifts: '',
    signature: null
  });
  const [referrals, setReferrals] = useState([]);
  const [currentReferral, setCurrentReferral] = useState(null);
  const [isSaving, setIsSaving] = useState(false);
  const [sessionId, setSessionId] = useState(null);
  const [showReferralForm, setShowReferralForm] = useState(false);
  const navigate = useNavigate();
  const isDirty = useRef(false);
  const [showMap, setShowMap] = React.useState(false);
  const [mapInit, setMapInit] = React.useState([41.3275, 19.8187]); // Default: Tirana
  const [allUsers, setAllUsers] = useState([]);
  const [contacts, setContacts] = useState([]);

  // GPS Location hook for client form
  const clientGPS = useGPSLocation();
  
  // GPS Location hook for edit form  
  const editGPS = useGPSLocation();

  const [editingContact, setEditingContact] = useState(null);
  const [editForm, setEditForm] = useState({
    name: '',
    surname: '',
    phone: '',
    secondaryPhone: '',
    address: '',
    addressLat: '',
    addressLng: '',
    profession: '',
    personalId: '',
    birthday: '',
    email: '',
    notes: '',
    meetingNotes: '',
    gifts: '',
    signature: null,
    isExpress: false
  });
  const editSignaturePadRef = useRef(null);
  const signaturePadRef = useRef(null);
  const [signature, setSignature] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showReferralMap, setShowReferralMap] = useState(false);
  const [referralMapInit, setReferralMapInit] = useState([41.3275, 19.8187]); // Default: Tirana
  
  // Multi-product management state
  const [contactProducts, setContactProducts] = useState({ purchases: [], reservations: [] });
  const [isLoadingProducts, setIsLoadingProducts] = useState(false);
  const [showAddProductModal, setShowAddProductModal] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [productModalType, setProductModalType] = useState('purchase'); // 'purchase' or 'reservation'
  const [isAddingProduct, setIsAddingProduct] = useState(false);
  const [showEditMap, setShowEditMap] = useState(false);
  const [editMapInit, setEditMapInit] = useState([41.3275, 19.8187]);
  const [filters, setFilters] = useState({
    startDate: '',
    endDate: '',
    agentId: '',
    isRBO: '', // Keep for backwards compatibility
    status: '', // New 3-way status filter
    contacted: '',
    response: '',
    hasUpcomingMeeting: '',
    searchQuery: ''
  });
  const [showFilters, setShowFilters] = useState(false);
  const [activeLegendFilter, setActiveLegendFilter] = useState(null);
  const [expiredFilterActive, setExpiredFilterActive] = useState(false); // Client-side filter for expired contacts
  const [showAddReferralsModal, setShowAddReferralsModal] = useState(false);
  const [selectedContactForReferrals, setSelectedContactForReferrals] = useState(null);
  const [showReferralsModal, setShowReferralsModal] = useState(false);
  const [selectedContactForReferralsView, setSelectedContactForReferralsView] = useState(null);
  const [contactReferrals, setContactReferrals] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [products, setProducts] = useState([]);
  const [filterCounts, setFilterCounts] = useState({});
  const [loadingFilterCounts, setLoadingFilterCounts] = useState(false);
  const location = useLocation();
  // Extract region from URL once so it is available to all hooks below
  const regionFilter = React.useMemo(() => {
    const urlParams = new URLSearchParams(location.search);
    return urlParams.get('region');
  }, [location.search]);
  // Highlighting functionality
  const [highlightId, setHighlightId] = useState(null);
  const highlightRef = useRef(null);
  
  // Add at the top, after other useState hooks
  const [rentals, setRentals] = useState([]);
  // Add this state near the top of the Contacts component
  const [downloadingPdfPurchaseId, setDownloadingPdfPurchaseId] = useState(null);
  const [deletingId, setDeletingId] = useState(null);
  const [signatureTouched, setSignatureTouched] = useState(false);
  const [signaturePadKeySuffix, setSignaturePadKeySuffix] = useState(0); // New state for forcing remount
  
  // Pagination and filtering state
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalContacts, setTotalContacts] = useState(0);
  const [pageSize, setPageSize] = useState(50);
  const [searchQuery, setSearchQuery] = useState('');
  const [serverFilters, setServerFilters] = useState({
    search: '',
    isRBO: '', // Keep for backwards compatibility
    status: '', // New 3-way status filter
    contacted: '',
    agentId: '',
    startDate: '',
    endDate: ''
  });

  const isAdmin = user?.role === 'admin' || user?.role === 'owner';
  const isOperator = user?.role === 'operator';
  const isAgent = user?.role === 'user'; // "user" role = agent in the UI
  const canEditDelete = isAdmin || isOperator;
  const canDelete = isAdmin || isOperator; // Operators can now delete contacts
  const showAgentColumn = isAdmin || isOperator;
  
  // Role-based field visibility for edit modal
  const showExtendedFieldsInEdit = isAdmin; // Only admin/owner see extended fields in edit modal
  const canManageProductStatusInEdit = isAdmin; // Only admin/owner can manage NO/RBO/REZ status in edit modal
  
  // Function to check if agent has access to see signature (only for agents)
  const hasAgentSignatureAccess = useCallback((contact) => {
    if (!isAgent || !contact) return false;
    
    // Agent has access if contact has RBO/REZ status AND agent is involved
    const hasRboRezStatus = contact.status === 'RBO' || contact.status === 'REZ';
    if (!hasRboRezStatus) return false;
    
    // Check if agent is assigned to a meeting with this contact
    const hasAssignedMeeting = contact.assignedAgentId === user.id;
    
    // Check if agent is assigned as seller in RBO process
    const isRboSeller = contact.rboSellerId === user.id;
    
    return hasAssignedMeeting || isRboSeller;
  }, [isAgent, user?.id]);
  
  // Function to determine if signature section should be shown
  const shouldShowSignatureSection = useCallback((contact) => {
    if (isAdmin) return true; // Admins always see signature
    if (isOperator) return false; // Operators never see signature
    if (isAgent) return hasAgentSignatureAccess(contact); // Agents see only if they have access
    return false;
  }, [isAdmin, isOperator, isAgent, hasAgentSignatureAccess]);

  // RBO Part History Modal state
  const [showRboHistoryModal, setShowRboHistoryModal] = useState(false);
  const [selectedPurchaseForRboHistory, setSelectedPurchaseForRboHistory] = useState(null);

  // Meeting History Modal state
  const [showMeetingHistoryModal, setShowMeetingHistoryModal] = useState(false);
  const [historyContact, setHistoryContact] = useState(null); // Contact for viewing history
  
  // Archive status state
  const [archiveStatus, setArchiveStatus] = useState(null);
  const [loadingArchiveStatus, setLoadingArchiveStatus] = useState(false);
  const [archivingMeeting, setArchivingMeeting] = useState(false);
  const [previousMeetingUsers, setPreviousMeetingUsers] = useState({ usedAgentIds: [], usedNotifiedIds: [] });
  const [contactsWithHistory, setContactsWithHistory] = useState(new Set());
  const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);

  // Add REGION_NAMES for code-to-name mapping
  const REGION_NAMES = {
    'AL-01': 'Berat',
    'AL-02': 'Durrës',
    'AL-03': 'Elbasan',
    'AL-04': 'Fier',
    'AL-05': 'Gjirokastër',
    'AL-06': 'Korçë',
    'AL-07': 'Kukës',
    'AL-08': 'Lezhë',
    'AL-09': 'Dibër',
    'AL-10': 'Shkodër',
    'AL-11': 'Tiranë',
    'AL-12': 'Vlorë',
  };

  const legendItems = [
    {
      id: 'not_contacted',
      label: t('contacts.management.notContacted'),
      bgColor: 'bg-white',
      textColor: 'text-gray-800',
      icon: <XCircleIcon className="h-5 w-5 text-gray-400" />,
      filter: { contacted: 'false' }
    },
    {
      id: 'held',
      label: t('contacts.management.meetingStatus.held'),
      bgColor: 'bg-green-100',
      textColor: 'text-green-800',
      icon: <FaceSmileIcon className="h-5 w-5 text-green-800" />,
      filter: { contacted: 'true', response: 'held' }
    },
    {
      id: 'reschedule',
      label: t('contacts.management.meetingStatus.reschedule'),
      bgColor: 'bg-orange-100',
      textColor: 'text-orange-800',
      icon: <FaceSmileIcon className="h-5 w-5 text-orange-800 transform rotate-180" />,
      filter: { contacted: 'true', response: 'reschedule' }
    },
    {
      id: 'failed',
      label: t('contacts.management.meetingStatus.failed'),
      bgColor: 'bg-purple-100',
      textColor: 'text-purple-800',
      icon: <FaceFrownIcon className="h-5 w-5 text-purple-800" />,
      filter: { contacted: 'true', response: 'failed' }
    },
    {
      id: 'do_not_contact',
      label: t('contacts.management.meetingStatus.do_not_contact'),
      bgColor: 'bg-rose-200',
      textColor: 'text-rose-900',
      icon: <XMarkIcon className="h-5 w-5 text-rose-900" />,
      filter: { contacted: 'true', response: 'do_not_contact' }
    },
    {
      id: 'upcoming_meeting',
      label: t('contacts.management.meeting.hasUpcoming'),
      bgColor: 'bg-blue-100',
      textColor: 'text-blue-800',
      icon: <CalendarIcon className="h-5 w-5 text-blue-800" />,
      filter: { hasUpcomingMeeting: 'true' }
    },
    {
      id: 'expired',
      label: t('contacts.management.expired', 'Expired'),
      bgColor: 'bg-lime-100',
      textColor: 'text-lime-800',
      icon: <ExclamationTriangleIcon className="h-5 w-5 text-lime-700" />,
      filter: { hasExpired: 'true' }
    }
  ];

  // Fetch all users for dropdown (including inactive - needed for displaying historical sellers)
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        // First get the current user's profile to verify auth is working
        const profileResponse = await fetch('/api/users/profile', {
          headers: { 
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (!profileResponse.ok) {
          throw new Error(`Failed to fetch profile: ${profileResponse.status}`);
        }

        // Then get all users
        const response = await fetch('/api/users', {
          headers: { 
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (!response.ok) {
          throw new Error(`Failed to fetch users: ${response.status}`);
        }

        const data = await response.json();
        if (Array.isArray(data)) {
          // Keep ALL users (including inactive) for display and historical data
          // Sort active users first, then inactive
          const sortedUsers = [...data].sort((a, b) => {
            if (a.isActive === b.isActive) {
              return `${a.firstName} ${a.lastName}`.localeCompare(`${b.firstName} ${b.lastName}`);
            }
            return a.isActive ? -1 : 1;
          });
          setAllUsers(sortedUsers);
        } else {
          setAllUsers([]);
        }
      } catch (error) {
        toast.error(t('common.error.fetchFailed'));
        setAllUsers([]);
      }
    };

    fetchUsers();
  }, [t]);

  // Fetch archive status and previous users when editing a contact
  useEffect(() => {
    const fetchArchiveData = async () => {
      if (!editingContact || !editingContact.id) {
        setArchiveStatus(null);
        setPreviousMeetingUsers({ usedAgentIds: [], usedNotifiedIds: [] });
        return;
      }
      
      setLoadingArchiveStatus(true);
      try {
        // Fetch previous meeting users (for disabling in dropdowns)
        const prevUsersResponse = await fetch(`/api/contacts/${editingContact.id}/previous-meeting-users`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (prevUsersResponse.ok) {
          const prevUsersData = await prevUsersResponse.json();
          setPreviousMeetingUsers(prevUsersData.data);
        }
        
        // Only fetch archive status if meeting status is 'held'
        if (editingContact.meetingStatus === 'held') {
          const response = await meetingArchiveApi.getArchiveStatus(editingContact.id);
          setArchiveStatus(response.data);
        } else {
          setArchiveStatus(null);
        }
      } catch (error) {
        logger.error('Failed to fetch archive data:', error);
        setArchiveStatus(null);
        setPreviousMeetingUsers({ usedAgentIds: [], usedNotifiedIds: [] });
      } finally {
        setLoadingArchiveStatus(false);
      }
    };
    
    fetchArchiveData();
  }, [editingContact?.id, editingContact?.meetingStatus]);

  // Prevent tab close if not saved
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      if (isDirty.current) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, []);

  // Auto-save client info
  // useEffect(() => {
  //   if (step === 1 && (client.name || client.surname || client.phone)) {
  //     isDirty.current = true;
  //     setIsSaving(true);
  //     fetch('/api/contacts', {
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'application/json',
  //         'Authorization': `Bearer ${localStorage.getItem('token')}`
  //       },
  //       body: JSON.stringify(client)
  //     })
  //       .then(res => res.json())
  //       .then(data => {
  //         if (data.id) setSessionId(data.id);
  //         setIsSaving(false);
  //       })
  //       .catch(() => setIsSaving(false));
  //   }
  // }, [client, step]);

  // Auto-save referrals
  useEffect(() => {
    if (sessionId && referrals.length > 0) {
      isDirty.current = true;
      setIsSaving(true);
      const last = referrals[referrals.length - 1];
      fetch(`/api/contacts/${sessionId}/referrals`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(last)
      })
        .then(res => res.json())
        .then(() => setIsSaving(false))
        .catch(() => setIsSaving(false));
    }
  }, [referrals, sessionId]);

  // Check which contacts have archived meetings (using batch endpoint for performance)
  const checkContactsMeetingHistory = useCallback(async (contactsList) => {
    try {
      if (!contactsList || !Array.isArray(contactsList) || contactsList.length === 0) {
        logger.debug('checkContactsMeetingHistory: No contacts to check');
        return;
      }

      const contactIds = contactsList.map(c => c?.id).filter(Boolean);
      
      if (contactIds.length === 0) {
        logger.debug('checkContactsMeetingHistory: No valid contact IDs');
        return;
      }

      logger.info(`📊 Checking archived meetings for ${contactIds.length} contacts...`);

      // Use batch endpoint - single API call instead of N calls
      const response = await api.post('/api/contacts/batch-archived-meetings-check', {
        contactIds
      });
      
      logger.debug('📊 Batch archive check response:', response.data);
      
      if (response.data?.success && response.data?.data) {
        const archiveMap = response.data.data;
        const withArchives = Object.entries(archiveMap).filter(([_, hasArchive]) => hasArchive).length;
        
        logger.info(`📊 Found ${withArchives} contacts with archived meetings out of ${contactIds.length}`);
        
        // Update state with all contacts that have archives
        setContactsWithHistory(prev => {
          const newSet = new Set(prev);
          Object.entries(archiveMap).forEach(([contactId, hasArchive]) => {
            if (hasArchive) {
              newSet.add(contactId);
            } else {
              // Remove if no longer has archive (edge case)
              newSet.delete(contactId);
            }
          });
          logger.debug(`📊 Updated contactsWithHistory, now has ${newSet.size} contacts`);
          return newSet;
        });
      } else {
        logger.warn('📊 Batch archive check returned unexpected response:', response.data);
      }
    } catch (error) {
      logger.error('Failed to check meeting history:', error);
      // Don't show error toast - this is non-critical
    }
  }, []); // No dependencies - stable function

  // Combined initial data load - much more efficient than multiple API calls
  const fetchInitialPageData = useCallback(async (page = 1) => {
    try {
      setLoading(true);
      
      const params = {
        page,
        limit: pageSize,
        // Include region filter if present
        ...(regionFilter ? { region: regionFilter } : {}),
        _timestamp: Date.now() // Force cache bypass
      };
      
      const response = await offlineApi.getContactsPageData(params);
      
      if (response.data && response.data.success) {
        const { contacts, pagination, filterCounts, users, rentals } = response.data.data;
        
        // Set all data from single API call
        setContacts(contacts || []);
        setTotalContacts(pagination?.total || 0);
        setTotalPages(pagination?.totalPages || 1);
        setCurrentPage(pagination?.page || 1);
        setFilterCounts(filterCounts || {});
        setAllUsers(Array.isArray(users) ? users : []);
        setRentals(Array.isArray(rentals) ? rentals : []);
        
        // Check which contacts have archived meetings (await to ensure icons render)
        if (contacts && contacts.length > 0) {
          await checkContactsMeetingHistory(contacts);
        }
        
        // Products will be loaded separately when needed (they're not used in table view)
        if (products.length === 0) {
          loadProducts();
        }
      }
    } catch (error) {
      logger.error('Error fetching page data:', error);
      toast.error(t('common.error.fetchFailed'));
      setContacts([]);
      setTotalContacts(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [pageSize, regionFilter, offlineApi, t, products.length, checkContactsMeetingHistory]);

  // Separate products loading (only when needed)
  const loadProducts = useCallback(async () => {
    try {
      const response = await fetch('/api/products', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      const productsData = await response.json();
      setProducts(productsData?.data || []);
    } catch (err) {
      logger.error('Error loading products:', err);
      setProducts([]);
    }
  }, []);

  const handleClientChange = (e) => {
    const { name, value, type, checked } = e.target;
    if (name === 'address') {
      setClient(prev => ({
        ...prev,
        address: value,
        addressLat: '',
        addressLng: ''
      }));
    } else if (name === 'phone' || name === 'secondaryPhone') {
      // Handle phone number formatting
      const phoneValue = value.replace(/\D/g, '').slice(0, 10);
      setClient(prev => ({
        ...prev,
        [name]: phoneValue
      }));
    } else {
      // Apply automatic capitalization for name fields
      const shouldCapitalize = ['name', 'surname', 'profession'].includes(name);
      const processedValue = shouldCapitalize ? capitalizeWords(value) : value;
      setClient(prev => ({
        ...prev,
        [name]: type === 'checkbox' ? checked : processedValue
      }));
    }
  };

  const handleAssociateChange = (ids) => {
    setClient(prev => ({ ...prev, associateIds: ids }));
  };

  const handleLocation = (lat, lng, address) => {
    setClient(prev => ({ ...prev, address, addressLat: lat, addressLng: lng }));
  };

  const handleReferralChange = (e) => {
    const { name, value } = e.target;
    setCurrentReferral(prev => ({ ...prev, [name]: value }));
  };

  const handleReferralLocation = (lat, lng, address) => {
    setCurrentReferral(prev => ({ ...prev, address, addressLat: lat, addressLng: lng }));
  };

  const handleSaveClient = async () => {
    // Save signature before submitting
    let signatureData = null;
    if (signaturePadRef.current) {
      signatureData = signaturePadRef.current.saveSignature();
    }

    const isOnline = navigator.onLine;
    
    // Address is always required, but geocoding validation only happens when online
    if (
      !client.name ||
      !client.surname ||
      !client.phone ||
      !/^(067|068|069)\d{7}$/.test(client.phone) ||
      !client.address
    ) {
      toast.error(t('contacts.errorFillAllFields'));
      return;
    }

    // Validate secondary phone if provided
    if (client.secondaryPhone && !/^(067|068|069)\d{7}$/.test(client.secondaryPhone)) {
      toast.error(t('contacts.phoneFormatError'));
      return;
    }

    setIsSaving(true);

    const submitData = {
      ...client,
      signature: signatureData !== null ? signatureData : client.signature || null,
      // Skip geocoding when offline
      addressLat: isOnline ? client.addressLat : null,
      addressLng: isOnline ? client.addressLng : null
      // Let the database set createdAt and updatedAt automatically to current timestamp
    };

    if (!isOnline) {
      // Offline: save locally and queue action
      try {
        const newContact = await addContactOffline(submitData);
        setContacts(prev => [{ ...newContact, referrals: [] }, ...prev]);
        setClient({
          date: getTodayAlbanianDateString(),
          name: '',
          surname: '',
          phone: '',
          secondaryPhone: '',
          address: '',
          addressLat: '',
          addressLng: '',
          associateIds: [],
          isRBO: false,
          notes: '',
          gifts: '',
          signature: null
        });
        setIsSaving(false);
        toast.success(t('contacts.contactAddedOffline'));
        navigate('/contacts');
        return;
      } catch (error) {
        setIsSaving(false);
        if (error.message === 'PHONE_DUPLICATE') {
          toast.error(t('contacts.errorPhoneAlreadyAdded'));
        } else {
          toast.error(t('contacts.errorAddingContact'));
        }
        return;
      }
    }

    // Online mode - try geocoding if coordinates are missing, but don't fail if geocoding fails  
    if (isOnline && client.address && (!client.addressLat || !client.addressLng)) {
      try {
        const geo = await geocodeAddress(client.address);
        if (geo) {
          submitData.addressLat = geo.lat;
          submitData.addressLng = geo.lng;
          submitData.address = geo.displayName || client.address;
        }
        // If geocoding fails, continue anyway with manual address
      } catch (error) {

        // Continue anyway - manual address is acceptable
      }
    }

    // Online: proceed as before
    fetch('/api/contacts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(submitData)
    })
      .then(async res => {
        if (!res.ok) {
          const data = await res.json();
          if (res.status === 409 && data.error?.toLowerCase().includes('phone')) {
            toast.error(t('contacts.errorPhoneAlreadyAdded'));
            setIsSaving(false);
            return;
          }
          throw new Error(data.error || 'Failed to add contact');
        }
        return res.json();
      })
      .then(data => {
        if (!data) return;
        // Add the new contact to the list
        setContacts(prev => [{
          ...data,
          referrals: []
        }, ...prev]);
        // Reset the form
        setClient({
          date: getTodayAlbanianDateString(),
          name: '',
          surname: '',
          phone: '',
          secondaryPhone: '',
          address: '',
          addressLat: '',
          addressLng: '',
          associateIds: [],
          isRBO: false,
          notes: '',
          gifts: '',
          signature: null
        });
        setIsSaving(false);
        toast.success(t('contacts.contactAdded'));
        navigate('/contacts');
      })
      .catch((error) => {
        setIsSaving(false);
        toast.error(t('contacts.errorAddingContact'));
      });
  };

  const handleUseMyLocation = () => {
    clientGPS.startLocationRequest(
      (result) => {
        setClient(prev => ({ 
          ...prev, 
          address: result.address, 
          addressLat: result.latitude, 
          addressLng: result.longitude 
        }));
      },
      (error) => {

      }
    );
  };

  const handlePickFromMap = () => {
    setMapInit([
      client.addressLat || 41.3275,
      client.addressLng || 19.8187
    ]);
    setShowMap(true);
  };

  const handleMapPick = (pos, address) => {
    setClient(prev => ({ ...prev, address, addressLat: pos[0], addressLng: pos[1] }));
    setShowMap(false);
    toast.success(t('contacts.locationSet'));
  };

  // Archive meeting handler
  const handleArchiveMeeting = async () => {
    if (!editingContact || !editingContact.id) return;
    setShowArchiveConfirm(true);
  };

  const confirmArchiveMeeting = async () => {
    if (!editingContact || !editingContact.id) return;
    
    setArchivingMeeting(true);
    try {
      await meetingArchiveApi.archiveMeeting(editingContact.id);
      toast.success(t('meetings.archive.archiveSuccess'));
      
      // Add this contact to contactsWithHistory immediately
      setContactsWithHistory(prev => {
        const newSet = new Set(prev);
        newSet.add(editingContact.id);
        return newSet;
      });
      
      // Reset archive status
      setArchiveStatus(null);
      
      // Refresh contacts list
      fetchInitialPageData(currentPage);
      
      // Close modals
      setShowArchiveConfirm(false);
      setEditingContact(null);
      setEditForm({});
      
    } catch (error) {
      logger.error('Failed to archive meeting:', error);
      toast.error(t('meetings.archive.archiveError'));
      setShowArchiveConfirm(false);
    } finally {
      setArchivingMeeting(false);
    }
  };

  // Edit logic
  const startEdit = (contact) => {
    // Use a callback to ensure we're reading from the absolute latest state
    setContacts(currentContacts => {
      const freshContact = currentContacts.find(c => c.id === contact.id) || contact;
      
      setEditingContact(freshContact);
      setSignatureTouched(false);
      setSignaturePadKeySuffix(prevSuffix => prevSuffix + 1); // Increment key suffix to force remount
      
      // Load contact products for multi-product management
      loadContactProducts(freshContact.id);
      
      // Populate edit form with fresh data
      setEditForm({
        date: freshContact.date ? format(new Date(freshContact.date), "yyyy-MM-dd") : getTodayAlbanianDateString(),
        name: freshContact.name,
        surname: freshContact.surname,
        phone: freshContact.phone || '',
        secondaryPhone: freshContact.secondaryPhone || '',
        address: freshContact.address || '',
        addressLat: freshContact.addressLat,
        addressLng: freshContact.addressLng,
        profession: freshContact.profession || '',
        personalId: freshContact.personalId || '',
        birthday: freshContact.birthday || '',
        email: freshContact.email || '',
        isRBO: freshContact.isRBO || false, // For backwards compatibility
        status: freshContact.status || (freshContact.isRBO ? 'RBO' : 'NO'), // New 3-way status field
        rboProductId: freshContact.rboProductId || null,
        rboSerialNumber: freshContact.rboSerialNumber || '',
        rboSellerId: freshContact.rboSellerId || null,
        // Initialize new RBO payment fields
        rboPaymentType: freshContact.rboPaymentType || 'cash', // Default to cash
        rboCurrency: freshContact.rboCurrency || 'EUR',        // Default to EUR
        rboAmount: freshContact.rboAmount || '',
        rboInstallmentMonths: freshContact.rboInstallmentMonths || 1,
        rboStartDate: freshContact.rboStartDate || '',
        // rboMonthlyPayment is calculated, not stored directly in editForm state for editing
        contacted: freshContact.contacted || false,
        response: freshContact.meetingStatus || null,
        meetingDateTime: freshContact.meetingDateTime ? format(new Date(freshContact.meetingDateTime), "yyyy-MM-dd'T'HH:mm") : '',
        notes: freshContact.notes || '',
        meetingNotes: freshContact.meetingNotes || '',
        gifts: freshContact.gifts || '',
        assignedAgentId: freshContact.assignedAgentId || null,
        notifiedUserId: freshContact.notifiedUserId || null,
        contactAttemptReason: freshContact.contactAttemptReason || '',
        contactAttemptOtherReason: freshContact.contactAttemptOtherReason || '',
        signature: freshContact.signature || null,
        isExpress: freshContact.isExpress || false
      });
      
      setShowEditModal(true);
      
      // Return unchanged state
      return currentContacts;
    });
  };

  const handleEditFormChange = (e) => {
    const { name, value, type, checked } = e.target;
    
    let newEditFormState = { ...editForm };

    if (name === 'phone' || name === 'secondaryPhone') {
      // Let PhoneInput component handle phone validation internally
      newEditFormState[name] = value;
    } else if (name === 'isRBO') {
      newEditFormState.isRBO = checked;
      // Update status field for backwards compatibility
      newEditFormState.status = checked ? 'RBO' : 'NO';
      if (!checked) { // If unchecking RBO, clear RBO specific fields
        newEditFormState.rboProductId = '';
        newEditFormState.rboSerialNumber = '';
        newEditFormState.rboSellerId = '';
        newEditFormState.rboPaymentType = 'cash';
        newEditFormState.rboCurrency = 'EUR';
        newEditFormState.rboAmount = '';
        newEditFormState.rboInstallmentMonths = 1;
        newEditFormState.rboStartDate = '';
      }
    } else if (name === 'status') {
      newEditFormState.status = value;
      // Update isRBO for backwards compatibility
      newEditFormState.isRBO = value === 'RBO';
      if (value !== 'RBO') { // If not RBO, clear RBO specific fields
        newEditFormState.rboProductId = '';
        newEditFormState.rboSerialNumber = '';
        newEditFormState.rboSellerId = '';
        newEditFormState.rboPaymentType = 'cash';
        newEditFormState.rboCurrency = 'EUR';
        newEditFormState.rboAmount = '';
        newEditFormState.rboInstallmentMonths = 1;
        newEditFormState.rboStartDate = '';
      }
    } else if (name === 'contacted' && type === 'checkbox') {
      if (!checked) {
        newEditFormState = {
          ...newEditFormState,
          contacted: false,
          response: null,
          meetingDateTime: '',
          assignedAgentId: null,
          notifiedUserId: null,
        };
      } else {
        // When enabling meeting status, reset contact outcome fields
        // as it doesn't make sense to have an outcome like "not answered" when scheduling a meeting
        newEditFormState = {
          ...newEditFormState,
          contacted: true,
          contactAttemptReason: null,
          contactAttemptOtherReason: '',
        };
      }
    } else if (name === 'rboPaymentType') {
      newEditFormState.rboPaymentType = value;
      if (value === 'cash') {
        newEditFormState.rboInstallmentMonths = 1; // Reset months if cash
      }
    } else if (name === 'contactAttemptReason') {
      // Handle contact attempt reason specifically to allow null values for deselection
      newEditFormState.contactAttemptReason = value;
      // Clear other reason when deselecting or selecting non-other option
      if (!value || value !== 'other') {
        newEditFormState.contactAttemptOtherReason = '';
      }
    } else if (name === 'isExpress' && type === 'checkbox') {
      newEditFormState.isExpress = checked;
      // If checking express meeting, set it as held with current date/time
      if (checked) {
        const now = new Date();
        const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        
        newEditFormState.contacted = true;
        newEditFormState.response = 'held';
        newEditFormState.meetingDateTime = localDateTime;
        newEditFormState.assignedAgentId = newEditFormState.assignedAgentId || user?.id;
        // Clear "must reschedule" or other non-held responses
        newEditFormState.contactAttemptReason = null;
        newEditFormState.contactAttemptOtherReason = '';
      }
      // If unchecking express meeting, completely reset/cancel the meeting
      else {
        newEditFormState.contacted = false;
        newEditFormState.response = null;
        newEditFormState.meetingDateTime = '';
        newEditFormState.assignedAgentId = null;
        newEditFormState.notifiedUserId = null;
      }
    } else {
      // Apply automatic capitalization for name fields
      const shouldCapitalize = ['name', 'surname', 'profession'].includes(name);
      const processedValue = shouldCapitalize ? capitalizeWords(value) : value;
      newEditFormState[name] = type === 'checkbox' ? checked : processedValue;
    }
    setEditForm(newEditFormState);
  };

  const validateEditForm = () => {
    // Basic validation for required fields
    if (
      !editForm.name ||
      !editForm.surname ||
      !editForm.phone ||
      !/^(067|068|069)\d{7}$/.test(editForm.phone) ||
      !editForm.address
    ) {
      toast.error(t('contacts.errorFillAllFields'));
      return false;
    }

    // Validate secondary phone if provided
    if (editForm.secondaryPhone && !/^(067|068|069)\d{7}$/.test(editForm.secondaryPhone)) {
      toast.error(t('contacts.phoneFormatError'));
      return false;
    }

    // Validate personalId if provided
    if (editForm.personalId && !/^[A-Z][0-9]{8}[A-Z]$/.test(editForm.personalId)) {
      toast.error(t('users.invalidPersonalId'));
      return false;
    }

    // Legacy RBO fields validation (multi-product: only validate if user is filling legacy fields)
    if (isAdmin) {
      const legacyRequired = ['rboProductId', 'rboSerialNumber', 'rboSellerId'];
      const anyLegacyFilled = legacyRequired.some((f) => !!editForm[f]);
      const allLegacyFilled = legacyRequired.every((f) => !!editForm[f]);
      if (anyLegacyFilled && !allLegacyFilled) {
        toast.error(t('contacts.errorFillRBOFields'));
        return false;
      }
    }

    // Meeting validation - Skip for agents since they can't see/edit meeting fields
    if (!isAgent) {
      // Additional validation for contacted status and meeting
      if (editForm.contacted && editForm.meetingDateTime && isPast(editForm.meetingDateTime)) {
        if (!editForm.response) {
          toast.error(t('contacts.management.errorResponseRequired'));
          return false;
        }
      }

      // Meeting scheduling validation (future date, agent) only if not do_not_contact
      if (editForm.contacted && (!editForm.response || editForm.response !== 'do_not_contact')) {
        if (!editForm.meetingDateTime) {
          toast.error(t('contacts.management.errorMeetingDateRequired'));
          return false;
        }
        if (!editForm.assignedAgentId) {
          toast.error(t('contacts.management.errorAgentRequired'));
          return false;
        }
        const meetingDate = new Date(editForm.meetingDateTime);
        // Only block past dates if this is a new meeting or the original meeting was not in the past
        const originalMeetingDate = editingContact?.meetingDateTime ? new Date(editingContact.meetingDateTime) : null;
        const isEditingPastMeeting = originalMeetingDate && isPast(originalMeetingDate);
        if (!isEditingPastMeeting && meetingDate <= getCurrentAlbanianTime()) {
          toast.error(t('contacts.management.errorMeetingDateFuture'));
          return false;
        }
      }
    }

    // Legacy RBO payment validation removed - using multi-product system instead

    return true;
  };

  const saveEdit = async () => {
    if (!validateEditForm()) {
      return;
    }

    setIsSaving(true);
    let signatureToSave = editForm.signature; // Default to current form state

    if (editSignaturePadRef.current) {
      // This call MIGHT trigger the onSave prop in Contacts.jsx if pad is not empty internally,
      // which would update editForm.signature and set signatureTouched = true.
      const padDataFromSaveMethod = editSignaturePadRef.current.saveSignature();


      // After saveSignature() call, check signatureTouched status.
      // signatureTouched is managed by the onSave prop of the SignaturePad component.
      // onSave is called by SignaturePad.saveSignature() if !isEmpty, or by fullscreen exit, or (previously) by inline onEnd.
      if (signatureTouched) {
        // If signatureTouched is true, it implies an interaction occurred in this session 
        // (drawing, clearing, or fullscreen sync) that updated editForm.signature via the onSave prop.
        // So, editForm.signature should be the most current state.
        signatureToSave = editForm.signature; 
      } else {
        // If signatureTouched is false, no interaction (that triggers onSave) happened in this session.
        // In this case, padDataFromSaveMethod holds the value from SignaturePad's internal state 
        // (i.e., the loaded signature if no new drawing occurred and pad was considered empty).
        signatureToSave = padDataFromSaveMethod;
      }
    }

    // Ensure signatureToSave is not undefined if it started as such and padData was also undefined.
    if (signatureToSave === undefined) {
      signatureToSave = null;
    }

    try {
      const meetingDateTime = editForm.contacted && editForm.meetingDateTime && editForm.assignedAgentId
        ? new Date(editForm.meetingDateTime).toISOString()
        : null;

      // Don't update timestamp to prevent position changes in the list
      const shouldUpdateTimestamp = false;

      const updateData = {
        name: editForm.name,
        surname: editForm.surname,
        phone: editForm.phone,
        secondaryPhone: editForm.secondaryPhone || null,
        address: editForm.address,
        addressLat: editForm.addressLat,
        addressLng: editForm.addressLng,
        profession: editForm.profession || null,
        personalId: editForm.personalId || null,
        birthday: editForm.birthday || null,
        email: editForm.email || null,
        signature: signatureToSave, // Use the determined signatureToSave
        isRBO: editForm.isRBO || false, // For backwards compatibility
        status: editForm.status || 'NO', // New 3-way status field
        rboProductId: editForm.status === 'RBO' && editForm.rboProductId ? editForm.rboProductId : null,
        rboSerialNumber: editForm.status === 'RBO' ? editForm.rboSerialNumber : null,
        rboSellerId: editForm.status === 'RBO' && editForm.rboSellerId ? editForm.rboSellerId : null,
        // Add RBO Payment Fields here
        rboPaymentType: editForm.status === 'RBO' ? editForm.rboPaymentType : null,
        rboCurrency: editForm.status === 'RBO' ? editForm.rboCurrency : null,
        rboAmount: editForm.status === 'RBO' && editForm.rboAmount ? parseFloat(editForm.rboAmount) : null,
        rboInstallmentMonths: editForm.status === 'RBO' && editForm.rboPaymentType === 'bank' && editForm.rboInstallmentMonths ? parseInt(editForm.rboInstallmentMonths, 10) : null,
        rboStartDate: editForm.status === 'RBO' && editForm.rboStartDate ? editForm.rboStartDate : null,
        contacted: editForm.contacted || false,
        meetingStatus: editForm.contacted ? editForm.response : null,
        meetingDateTime: meetingDateTime,
        contactAttemptReason: editForm.contactAttemptReason || null,
        contactAttemptOtherReason: editForm.contactAttemptReason === 'other' ? editForm.contactAttemptOtherReason || null : null,
        notes: editForm.notes || null,
        meetingNotes: editForm.meetingNotes || null,
        gifts: editForm.gifts || null,
        assignedAgentId: editForm.contacted && meetingDateTime ? (editForm.assignedAgentId || null) : null,
        notifiedUserId: editForm.contacted && meetingDateTime && editForm.notifiedUserId ? editForm.notifiedUserId : null,
        updateTimestamp: shouldUpdateTimestamp,
        isExpress: editForm.isExpress || false
      };

      if (!navigator.onLine) {
        // Offline: update locally and queue action
        await updateContactOffline(editingContact.id, updateData);
        setContacts(prev => prev.map(contact =>
          contact.id === editingContact.id ? { ...contact, ...updateData, offline: true } : contact
        ));
        setShowEditModal(false);
        setEditingContact(null);
        setIsSaving(false);
        setSignatureTouched(false);
        toast.success(t('contacts.contactUpdated'));
        return;
      }

      const response = await fetch(`/api/contacts/${editingContact.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(updateData)
      });

      if (!response.ok) {
        const errorData = await response.json();
        if (response.status === 409 && errorData.error?.toLowerCase().includes('phone')) {
          toast.error(t('contacts.errorPhoneAlreadyAdded'));
          setIsSaving(false);
          return;
        }
        throw new Error(errorData.error || 'Failed to update contact');
      }

      const updatedContact = await response.json();
      
      setContacts(prev => {
        const contactExists = prev.some(c => c.id === editingContact.id);
        
        if (!contactExists) {
          return prev; // No change needed
        }
        
        const updated = prev.map(contact => {
          if (contact.id === editingContact.id) {
            // Create a completely new object reference to trigger React re-render
            return { ...updatedContact };
          }
          return contact;
        });
        return updated;
      });
      
      // Re-check for archived meetings for this contact
      await checkContactsMeetingHistory([updatedContact]);
      
      // Refresh filter counts since contact status may have changed
      fetchFilterCounts();
      
      setShowEditModal(false);
      setEditingContact(null);
      setIsSaving(false);
      setSignatureTouched(false);
      toast.success(t('contacts.contactUpdated'));
    } catch (error) {
      setIsSaving(false);
      toast.error(t('contacts.errorUpdatingContact'));
    }
  };

  const handleEditUseMyLocation = () => {
    editGPS.startLocationRequest(
      (result) => {
        setEditForm(prev => ({ 
          ...prev, 
          address: result.address, 
          addressLat: result.latitude, 
          addressLng: result.longitude 
        }));
      },
      (error) => {

      }
    );
  };

  // ================================
  // MULTI-PRODUCT MANAGEMENT FUNCTIONS
  // ================================

  // Load contact products (purchases and reservations)
  const loadContactProducts = async (contactId) => {
    if (!contactId) return;
    
    setIsLoadingProducts(true);
    try {
      const response = await fetch(`/api/contacts/${contactId}/products`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (response.ok) {
        const products = await response.json();
        setContactProducts(products);
      } else {
        logger.error('Failed to load contact products');
      }
    } catch (error) {
      logger.error('Error loading contact products:', error);
    } finally {
      setIsLoadingProducts(false);
    }
  };

  // Add a new product (purchase or reservation)
  const addProduct = async (productData) => {
    if (!editingContact || isAddingProduct) return;
    
    setIsAddingProduct(true);
    try {
      const endpoint = productModalType === 'purchase' 
        ? `/api/contacts/${editingContact.id}/purchases`
        : `/api/contacts/${editingContact.id}/reservations`;
        
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(productData)
      });
      
      if (response.ok) {
        const newProduct = await response.json();
        setContactProducts(prev => ({
          ...prev,
          [productModalType === 'purchase' ? 'purchases' : 'reservations']: [
            ...prev[productModalType === 'purchase' ? 'purchases' : 'reservations'],
            newProduct
          ]
        }));
        toast.success(t(`contacts.${productModalType}Added`));
        setShowAddProductModal(false);
      } else {
        const errorData = await response.json();
        toast.error(errorData.error || `Failed to add ${productModalType}`);
      }
    } catch (error) {
      logger.error(`Error adding ${productModalType}:`, error);
      toast.error(`Failed to add ${productModalType}`);
    } finally {
      setIsAddingProduct(false);
    }
  };

  // Update an existing product
  const updateProduct = async (productId, productData) => {
    if (!editingContact || isAddingProduct) return;
    
    setIsAddingProduct(true);
    try {
      const endpoint = editingProduct.type === 'purchase'
        ? `/api/contacts/${editingContact.id}/purchases/${productId}`
        : `/api/contacts/${editingContact.id}/reservations/${productId}`;
        
      const response = await fetch(endpoint, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(productData)
      });
      
      if (response.ok) {
        const updatedProduct = await response.json();
        setContactProducts(prev => ({
          ...prev,
          [editingProduct.type === 'purchase' ? 'purchases' : 'reservations']: 
            prev[editingProduct.type === 'purchase' ? 'purchases' : 'reservations'].map(p => 
              p.id === productId ? updatedProduct : p
            )
        }));
        toast.success(t(`contacts.${editingProduct.type}Updated`));
        setEditingProduct(null);
        setShowAddProductModal(false);
      } else {
        const errorData = await response.json();
        toast.error(errorData.error || `Failed to update ${editingProduct.type}`);
      }
    } catch (error) {
      logger.error(`Error updating ${editingProduct.type}:`, error);
      toast.error(`Failed to update ${editingProduct.type}`);
    } finally {
      setIsAddingProduct(false);
    }
  };

  // Delete a product
  const deleteProduct = async (productId, type) => {
    if (!editingContact) return;
    
    const confirmed = await confirm({
      title: t('common.confirmDelete'),
      message: t(`contacts.confirm${type === 'purchase' ? 'Purchase' : 'Reservation'}Delete`),
      confirmText: t('common.delete'),
      cancelText: t('common.cancel'),
      type: 'danger'
    });
    
    if (!confirmed) return;
    
    try {
      const endpoint = type === 'purchase'
        ? `/api/contacts/${editingContact.id}/purchases/${productId}`
        : `/api/contacts/${editingContact.id}/reservations/${productId}`;
        
      const response = await fetch(endpoint, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (response.ok) {
        setContactProducts(prev => ({
          ...prev,
          [type === 'purchase' ? 'purchases' : 'reservations']: 
            prev[type === 'purchase' ? 'purchases' : 'reservations'].filter(p => p.id !== productId)
        }));
        toast.success(t(`contacts.${type}Deleted`));
      } else {
        const errorData = await response.json();
        toast.error(errorData.error || `Failed to delete ${type}`);
      }
    } catch (error) {
      logger.error(`Error deleting ${type}:`, error);
      toast.error(`Failed to delete ${type}`);
    }
  };

  // Convert REZ to RBO
  const convertReservationToPurchase = async (reservationId) => {
    if (!editingContact) return;
    
    const confirmed = await confirm({
      title: t('contacts.confirmConversion'),
      message: t('contacts.confirmConversionMessage'),
      confirmText: t('contacts.convert'),
      cancelText: t('common.cancel')
    });
    
    if (!confirmed) return;
    
    try {
      const response = await fetch(`/api/contacts/${editingContact.id}/reservations/${reservationId}/convert`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
          // Use default values for conversion - can be enhanced later to ask user for these
          serialNumber: '',
          purchaseDate: new Date().toISOString(),
          paymentType: 'cash',
          notes: ''
        })
      });
      
      if (response.ok) {
        const { purchase } = await response.json();
        setContactProducts(prev => ({
          purchases: [...prev.purchases, purchase],
          reservations: prev.reservations.filter(r => r.id !== reservationId)
        }));
        toast.success(t('contacts.reservationConverted'));
      } else {
        const errorData = await response.json();
        toast.error(errorData.error || 'Failed to convert reservation');
      }
    } catch (error) {
      logger.error('Error converting reservation:', error);
      toast.error('Failed to convert reservation');
    }
  };

  const handleEditMapPick = (pos, address) => {
    setEditForm(prev => ({ ...prev, address, addressLat: pos[0], addressLng: pos[1] }));
    setShowEditMap(false);
    toast.success(t('contacts.locationSet'));
  };

  // Helper to truncate text
  const truncate = (str, n) => (str && str.length > n ? str.slice(0, n) + '…' : str);

  // Helper to get assigned agent name/email
  const getAgent = (contact) => {
    if (!contact) return t('common.unknown');

    // Attempt 1: Use createdByUserId to find in allUsers (most reliable for consistent data)
    if (contact.createdByUserId && allUsers && allUsers.length > 0) {
      const userFromList = allUsers.find(u => u.id === contact.createdByUserId);
      if (userFromList) {
        return userFromList.firstName ? `${userFromList.firstName} ${userFromList.lastName}` : userFromList.email || t('common.unknown');
      }
    }

    // Attempt 2: Use pre-populated createdBy or createdByUser object (might come from API include)
    const prePopulatedUser = contact.createdBy || contact.createdByUser;
    if (prePopulatedUser) {
      return prePopulatedUser.firstName ? `${prePopulatedUser.firstName} ${prePopulatedUser.lastName}` : prePopulatedUser.email || t('common.unknown');
    }
    
    return t('common.unknown');
  };

  const handleFilterChange = (e) => {
    try {
      const { name, value } = e.target;

      // Clear legend filter if using regular filters
      if (activeLegendFilter) {
        setActiveLegendFilter(null);
      }

      // Update client filters for UI display
      setFilters(prev => ({ ...prev, [name]: value }));

      // Map ALL relevant filters to server filters
      const newServerFilters = { ...serverFilters };

      switch (name) {
        case 'isRBO':
        case 'contacted':
        case 'agentId':
        case 'startDate':
        case 'endDate':
        case 'response':
        case 'hasUpcomingMeeting':
        case 'status':
          newServerFilters[name] = value;
          break;
        case 'searchQuery':
          newServerFilters.search = value;
          break;
        default:
  
      }

      // Update server filters – the dedicated useEffect will perform the fetch
      setServerFilters(newServerFilters);
      setCurrentPage(1);
    } catch (error) {

      toast.error(t('common.error.filterFailed') || 'Filter error occurred');
    }
  };

  const clearFilters = () => {
    // Reset client-side filter state
    setFilters({
      startDate: '',
      endDate: '',
      agentId: '',
      isRBO: '',
      contacted: '',
      response: '',
      hasUpcomingMeeting: '',
      searchQuery: '',
      status: ''
    });

    // Reset server-side filters – the watcher useEffect will refetch once
    const clearedServerFilters = {
      search: '',
      isRBO: '',
      contacted: '',
      agentId: '',
      startDate: '',
      endDate: '',
      response: '',
      hasUpcomingMeeting: '',
      status: ''
    };
    setServerFilters(clearedServerFilters);

    setSearchQuery('');
    setActiveLegendFilter(null);
    setExpiredFilterActive(false);
    setCurrentPage(1);
    // Refresh filter counts when clearing filters
    fetchFilterCounts();
  };

  // Helper: search in contact fields
  const searchInContact = (contact, query) => {
    if (!query) return true;
    
    const searchStr = query.toLowerCase().trim();
    const searchWords = searchStr.split(/\s+/);
    
    // If searching with multiple words, try to match full name exactly first
    if (searchWords.length > 1) {
      const fullName = `${contact.name} ${contact.surname}`.toLowerCase();
      const reversedFullName = `${contact.surname} ${contact.name}`.toLowerCase();
      
      // Check for exact full name match first
      if (fullName === searchStr || reversedFullName === searchStr) {
        return true;
      }
      
      // Check if the search words match the beginning of name and surname
      const [firstWord, secondWord] = searchWords;
      if ((contact.name.toLowerCase().startsWith(firstWord) && contact.surname.toLowerCase().startsWith(secondWord)) ||
          (contact.surname.toLowerCase().startsWith(firstWord) && contact.name.toLowerCase().startsWith(secondWord))) {
        return true;
      }
    }

    // For single word searches or if full name match failed, check individual fields
    const fieldsToSearch = [
      contact.name,
      contact.surname,
      contact.phone,
      contact.secondaryPhone,
      contact.address,
      contact.profession,
      contact.notes
    ].filter(Boolean).map(field => field.toLowerCase().trim());

    // For single words, match from the start of each field
    if (searchWords.length === 1) {
      return fieldsToSearch.some(field => field.startsWith(searchStr));
    }

    // For multiple words that didn't match the full name, require all words to be present
    // and at least one word should be at the start of name or surname
    return searchWords.every(word => 
      fieldsToSearch.some(field => field.includes(word))
    ) && (
      contact.name.toLowerCase().startsWith(searchWords[0]) ||
      contact.surname.toLowerCase().startsWith(searchWords[0]) ||
      contact.name.toLowerCase().startsWith(searchWords[1]) ||
      contact.surname.toLowerCase().startsWith(searchWords[1])
    );
  };

  // Process contacts for agent display (simplified structure) - MOVED BEFORE useMemo
  const processAgentContacts = useCallback((agentContacts) => {
    // Sort contacts by meeting date, upcoming first (null dates at the end)
    const sortedContacts = [...agentContacts].sort((a, b) => {
      // Handle null/undefined meetingDateTime
      if (!a.meetingDateTime && !b.meetingDateTime) return 0;
      if (!a.meetingDateTime) return 1; // a goes to end
      if (!b.meetingDateTime) return -1; // b goes to end
      
      const dateA = new Date(a.meetingDateTime);
      const dateB = new Date(b.meetingDateTime);
      return dateA - dateB;
    });

    // Group contacts by date (or "No Meeting" for contacts without meetings)
    const groupedByDate = sortedContacts.reduce((acc, contact) => {
      let dateKey;
      if (contact.meetingDateTime) {
        const date = new Date(contact.meetingDateTime);
        dateKey = date.toISOString().split('T')[0];
      } else {
        // Contacts without meetings go to a special group
        dateKey = 'no-meeting';
      }
      
      if (!acc[dateKey]) {
        acc[dateKey] = [];
      }
      acc[dateKey].push({
        ...contact,
        referrals: [] // Agents don't see referrals structure
      });
      return acc;
    }, {});

    return groupedByDate;
  }, []); // Empty deps - this logic doesn't depend on external state

  // Memoized processContactsForDisplay for paginated data - recalculates only when dependencies change
  const processContactsForDisplay = useMemo(() => {
    try {
      // Enhanced safety checks for iOS devices
      if (!Array.isArray(contacts)) {

        return {};
      }

      // For agents, the backend already applies the correct filtering with 12-hour window
      // Backend filters by: assignedAgentId/notifiedUserId AND (meetingDateTime is null OR >= now - 12 hours)
      // No additional client-side filtering needed - trust the backend!
      if (isAgent && user?.id) {
        // Just use the contacts as-is from the backend
        return processAgentContacts(contacts);
      }
      
      // Memory-efficient filtering without creating unnecessary copies
      let displayContacts = contacts;
      
      // Region filtering is now handled server-side in the API
      // No need for client-side region filtering since backend properly filters by region
      
      // Apply legend filter if active (legend filters override other filters)
      if (activeLegendFilter) {
        displayContacts = displayContacts.filter(contact => {
          try {
            if (!contact) return false;
            return filterContact(contact, false, activeLegendFilter, filters, user, searchInContact, regionFilter);
          } catch (error) {

            return false;
          }
        });
      }

      // Group by date for display with enhanced error handling
      const groupedByDate = {};
      
      for (let i = 0; i < displayContacts.length; i++) {
        const contact = displayContacts[i];
        
        try {
          if (!contact || !contact.createdAt) {

            continue;
          }
          
          const date = new Date(contact.createdAt);
          
          // Validate date
          if (isNaN(date.getTime())) {

            continue;
          }
          
          const dateKey = date.toISOString().split('T')[0];
          
          if (!groupedByDate[dateKey]) {
            groupedByDate[dateKey] = [];
          }
          
          groupedByDate[dateKey].push(contact);
        } catch (error) {

          continue;
        }
      }

      return groupedByDate;
    } catch (error) {

      // Return empty object as safe fallback
      return {};
    }
  }, [contacts, isAgent, user, activeLegendFilter, filters, regionFilter, processAgentContacts]); // Added processAgentContacts to deps

  // Get filtered contacts
  // const filteredContacts = processContactsForDisplay();

  // Helper to check if a contact has an expired rental (1 year from start date)
  const hasExpiredRental = (contactId) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    return rentals.some(r => {
      if (r.contactId !== contactId || !r.startDate) return false;
      const startDate = new Date(r.startDate);
      // Rental expires 1 year after start date
      const expiryDate = new Date(startDate);
      expiryDate.setFullYear(expiryDate.getFullYear() + 1);
      expiryDate.setHours(0, 0, 0, 0);
      return expiryDate < today;
    });
  };

  // Helper to check if a contact has expired RBO
  // Uses expirationDate field which is set to purchaseDate + 1 year initially,
  // and extended when parts are replaced.
  // Only considers products that have hasExpirationTracking enabled (or null, which defaults to true)
  const hasExpiredRBO = (contact) => {
    if (!contact?.purchases || contact.purchases.length === 0) return false;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // Check if any purchase is expired (expirationDate < today)
    // Only for products with expiration tracking enabled
    return contact.purchases.some(purchase => {
      // Check if the product has expiration tracking enabled
      // Default to true if not explicitly set to false
      const product = purchase.Product || purchase.product;
      if (product && product.hasExpirationTracking === false) {
        return false; // Skip this purchase - product doesn't have expiration tracking
      }
      
      // Use expirationDate if available, otherwise fallback to purchaseDate + 1 year
      if (purchase.expirationDate) {
        const expirationDate = new Date(purchase.expirationDate);
        expirationDate.setHours(0, 0, 0, 0);
        return expirationDate < today;
      }
      // Fallback for purchases without expirationDate (shouldn't happen after migration)
      if (!purchase.purchaseDate) return false;
      const purchaseDate = new Date(purchase.purchaseDate);
      const expiryDate = new Date(purchaseDate);
      expiryDate.setFullYear(expiryDate.getFullYear() + 1);
      expiryDate.setHours(0, 0, 0, 0);
      return expiryDate < today;
    });
  };

  // Helper to check if a contact has reservations past their expiry date
  // Skips reservations already marked as expired/cancelled/converted, and products without expiration tracking
  const hasExpiredReservation = (contact) => {
    if (!contact?.reservations || contact.reservations.length === 0) return false;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    return contact.reservations.some(reservation => {
      if (reservation.status === 'expired' || reservation.status === 'cancelled' || reservation.status === 'converted_to_purchase') return false;
      const product = reservation.Product || reservation.product;
      if (product && product.hasExpirationTracking === false) return false;
      if (!reservation.expiryDate) return false;
      const expiryDate = new Date(reservation.expiryDate);
      expiryDate.setHours(0, 0, 0, 0);
      return expiryDate < today;
    });
  };

  // Helper to check if a contact has any expired status (rental, RBO, or reservation)
  const hasAnyExpired = (contact) => {
    return hasExpiredRental(contact.id) || hasExpiredRBO(contact) || hasExpiredReservation(contact);
  };

  // displayContacts - now server-side filtering handles expired filter
  // This useMemo is kept for potential future client-side filtering needs
  const displayContacts = useMemo(() => {
    return contacts;
  }, [contacts]);

  // Helper to get Google Maps URL
  const getGoogleMapsUrl = (contact) => {
    if (contact.addressLat && contact.addressLng) {
      return `https://www.google.com/maps/search/?api=1&query=${contact.addressLat},${contact.addressLng}`;
    }
    return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(contact.address)}`;
  };

  // Render status icons
  const renderStatusIcons = (contact) => {
    const isExpired = hasAnyExpired(contact);
    
    if (!contact.contacted) {
      return (
        <div className="flex items-center gap-2">
          <XCircleIcon className="h-5 w-5 text-gray-400" />
          {isExpired && (
            <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-semibold bg-lime-600 text-white" title={t('contacts.management.expiredTooltip', 'Has expired rental, RBO warranty, or reservation')}>
              <ExclamationTriangleIcon className="h-3.5 w-3.5" />
            </span>
          )}
        </div>
      );
    }
    return (
      <div className="flex items-center gap-2">
        <CheckIcon className="h-5 w-5 text-green-800" />
        {/* Only show meetingStatus if meetingDateTime exists and is in the past */}
        {contact.meetingDateTime && isPast(contact.meetingDateTime) && contact.meetingStatus && (
          <div className="flex items-center">
            {contact.meetingStatus === 'held' && (
              <FaceSmileIcon className="h-5 w-5 text-green-800" />
            )}
            {contact.meetingStatus === 'reschedule' && (
              <FaceSmileIcon className="h-5 w-5 text-orange-800 transform rotate-180" />
            )}
            {contact.meetingStatus === 'failed' && (
              <FaceFrownIcon className="h-5 w-5 text-purple-800" />
            )}
            {contact.meetingStatus === 'do_not_contact' && (
              <XMarkIcon className="h-5 w-5 text-rose-900" />
            )}
          </div>
        )}
        {contact.meetingDateTime && isFuture(contact.meetingDateTime) && (
          <CalendarIcon className="h-5 w-5 text-blue-800" />
        )}
        {isExpired && (
          <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-semibold bg-lime-600 text-white" title={t('contacts.management.expiredTooltip', 'Has expired rental, RBO warranty, or reservation')}>
            <ExclamationTriangleIcon className="h-3.5 w-3.5" />
          </span>
        )}
      </div>
    );
  };

  // Handle legend filter click
  const handleLegendFilterClick = (filterCriteria, filterId = null) => {
    try {
      // If clicking the same filter again or clearing filters
      if (!filterCriteria || filterId === activeLegendFilter) {
        setActiveLegendFilter(null);
        setExpiredFilterActive(false);
        // Clear all filters and refetch
        clearFilters();
        return;
      }

      // Set the active legend filter
      setActiveLegendFilter(filterId);
      
      // For expired filter, use server-side filtering
      if (filterCriteria.hasExpired === 'true') {
        setExpiredFilterActive(true);
        // Clear other filters and set hasExpired for server-side filtering
        const legendFilters = {
          startDate: '',
          endDate: '',
          agentId: '',
          isRBO: '',
          searchQuery: '',
          contacted: '',
          response: '',
          hasUpcomingMeeting: ''
        };
        setFilters(legendFilters);
        // Map to server filters including hasExpired
        const legendServerFilters = {
          search: '',
          isRBO: '',
          agentId: '',
          startDate: '',
          endDate: '',
          contacted: '',
          response: '',
          hasUpcomingMeeting: '',
          hasExpired: 'true'
        };
        setServerFilters(legendServerFilters);
        setCurrentPage(1);
        fetchPaginatedContacts(1, legendServerFilters);
        setShowFilters(false);
        return;
      }
      
      // For other filters, disable expired filter and proceed normally
      setExpiredFilterActive(false);
      
      // When applying a legend filter, reset ALL other filters and apply only the legend filter
      const legendFilters = {
        startDate: '',
        endDate: '',
        agentId: '',
        isRBO: '',
        searchQuery: '',
        // Apply only the legend filter criteria
        contacted: filterCriteria.contacted || '',
        response: filterCriteria.response || '',
        hasUpcomingMeeting: filterCriteria.hasUpcomingMeeting || ''
      };
      setFilters(legendFilters);

      // Map legend filters to server filters
      const legendServerFilters = {
        search: '',
        isRBO: '',
        agentId: '',
        startDate: '',
        endDate: '',
        contacted: filterCriteria.contacted || '',
        response: filterCriteria.response || '',
        hasUpcomingMeeting: filterCriteria.hasUpcomingMeeting || ''
      };
      setServerFilters(legendServerFilters);
      setCurrentPage(1);
      fetchPaginatedContacts(1, legendServerFilters);

      // Also reset the show filters panel when using legend filters
      setShowFilters(false);
    } catch (error) {

      toast.error(t('common.error.filterFailed') || 'Legend filter error occurred');
      // Reset to safe state on error
      setActiveLegendFilter(null);
      setExpiredFilterActive(false);
      clearFilters();
    }
  };

  // Get row background color based on contact status
  const getRowBackgroundColor = (contact) => {
    // Simplified hover helper - safer for mobile
    const getHover = (base) => {
      try {
        if (base === 'bg-white') return 'hover:bg-gray-100';
        if (base.includes('green-')) return 'hover:bg-green-200';
        if (base.includes('orange-')) return 'hover:bg-orange-200';
        if (base.includes('purple-')) return 'hover:bg-purple-200';
        if (base.includes('rose-')) return 'hover:bg-rose-300';
        if (base.includes('red-')) return 'hover:bg-red-200';
        if (base.includes('lime-')) return 'hover:bg-lime-200';
        if (base.includes('blue-')) return 'hover:bg-blue-200';
        if (base.includes('yellow-')) return 'hover:bg-yellow-100';
        return 'hover:bg-gray-100'; // Safe fallback
      } catch (error) {
  
        return 'hover:bg-gray-100';
      }
    };

    try {
      // If an activeLegendFilter is set, prioritize it.
      if (activeLegendFilter) {
        // Use safer comparison instead of JSON.stringify
        const matchesLegendFilter = (() => {
          try {
            return filterContact(contact, false, activeLegendFilter, filters, user, searchInContact);
          } catch (error) {
      
            return false;
          }
        })();
        
        if (matchesLegendFilter) {
          // Find matching legend item more safely
          const legendItem = legendItems.find(item => {
            try {
              if (!item || !item.filter || !activeLegendFilter) return false;
              
              // Compare filter properties directly instead of JSON.stringify
              const itemFilter = item.filter;
              const activeFilter = activeLegendFilter;
              
              return Object.keys(activeFilter).every(key => 
                itemFilter[key] === activeFilter[key]
              );
            } catch (error) {
        
              return false;
            }
          });
          
          if (legendItem && legendItem.bgColor) {
            return `${legendItem.bgColor} ${getHover(legendItem.bgColor)}`;
          }
        }
        return `bg-white ${getHover('bg-white')}`; // Neutral if not matching active legend
      }

      // If no activeLegendFilter, apply coloring based on contact status
      
      // PRIORITY 1: "do_not_contact" - highest priority status
      try {
        const doNotContactLegend = legendItems.find(item => item && item.id === 'do_not_contact');
        if (doNotContactLegend && doNotContactLegend.filter) {
          const matchesFilter = filterContact(contact, false, doNotContactLegend.filter, filters, user, searchInContact);
          if (matchesFilter && doNotContactLegend.bgColor) {
            return `${doNotContactLegend.bgColor} ${getHover(doNotContactLegend.bgColor)}`;
          }
        }
      } catch (error) {
        // Silently continue
      }

      // PRIORITY 2: "Expired" - contacts with expired RBO/rentals/reservations
      try {
        if (hasAnyExpired(contact)) {
          return `bg-lime-100 ${getHover('bg-lime-100')}`;
        }
      } catch (error) {
        // Silently handle errors in expired check
      }

      // PRIORITY 3-6: Other statuses
      const statusPriorities = ['held', 'failed', 'reschedule', 'upcoming_meeting'];
      
      for (const statusId of statusPriorities) {
        try {
          const legendItem = legendItems.find(item => item && item.id === statusId);
          if (legendItem && legendItem.filter) {
            const matchesFilter = filterContact(contact, false, legendItem.filter, filters, user, searchInContact);
            if (matchesFilter && legendItem.bgColor) {
              return `${legendItem.bgColor} ${getHover(legendItem.bgColor)}`;
            }
          }
        } catch (error) {
  
          continue;
        }
      }
      
      // Special case for "contacted, no specific outcome / past meeting, and not upcoming"
      try {
        if (contact.contacted && 
            (!contact.meetingDateTime || isPast(contact.meetingDateTime)) && 
            !contact.meetingStatus) {
          return `bg-yellow-50 ${getHover('bg-yellow-50')}`;
        }
      } catch (error) {
  
      }

      // Case for "Not Contacted"
      try {
        const notContactedLegend = legendItems.find(item => item && item.id === 'not_contacted');
        if (notContactedLegend && notContactedLegend.filter) {
          const matchesFilter = filterContact(contact, false, notContactedLegend.filter, filters, user, searchInContact);
          if (matchesFilter && notContactedLegend.bgColor) {
            return `${notContactedLegend.bgColor} ${getHover(notContactedLegend.bgColor)}`;
          }
        }
      } catch (error) {
  
      }

      return `bg-white ${getHover('bg-white')}`; // Default fallback
    } catch (error) {
  
      return 'bg-white hover:bg-gray-100'; // Safe fallback
    }
  };

  // Referral form component
  const ReferralForm = ({ onSave, onCancel }) => {
    const { t } = useTranslation();
    const [referral, setReferral] = useState({
      name: '',
      surname: '',
      phone: '',
      secondaryPhone: '',
      address: '',
      addressLat: '',
      addressLng: '',
      profession: '',
      personalId: '',
      birthday: '',
      email: '',
      notes: '',
      gifts: ''
    });
    const [showMap, setShowMap] = useState(false);
    const [mapInit, setMapInit] = useState([41.3275, 19.8187]);
    const [isSaving, setIsSaving] = useState(false);

    const handleChange = (e) => {
      const { name, value } = e.target;
      if (name === 'phone' || name === 'secondaryPhone') {
        // Let PhoneInput component handle phone validation internally
        setReferral(prev => ({ ...prev, [name]: value }));
      } else if (name === 'address') {
        setReferral(prev => ({ ...prev, address: value, addressLat: '', addressLng: '' }));
      } else if (name === 'personalId') {
        // Convert to uppercase for personal ID
        const processedValue = value.toUpperCase();
        setReferral(prev => ({ ...prev, [name]: processedValue }));
      } else {
        // Apply automatic capitalization for name fields
        const shouldCapitalize = ['name', 'surname', 'profession'].includes(name);
        const processedValue = shouldCapitalize ? capitalizeWords(value) : value;
        setReferral(prev => ({ ...prev, [name]: processedValue }));
      }
    };

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

      if (!referral.name || !referral.surname || !referral.phone || !/^(067|068|069)\d{7}$/.test(referral.phone) || !referral.address) {
        toast.error(t('contacts.errorFillAllFields'));
        return;
      }

      // Validate secondary phone if provided
      if (referral.secondaryPhone && !/^(067|068|069)\d{7}$/.test(referral.secondaryPhone)) {
        toast.error(t('contacts.phoneFormatError'));
        return;
      }

      setIsSaving(true);
      try {
        await onSave(referral);
      } catch (error) {
        toast.error(t('contacts.errorAddingReferral'));
      } finally {
        setIsSaving(false);
      }
    };

    const handleMapPick = (pos, address) => {
      setReferral(prev => ({
        ...prev,
        address,
        addressLat: pos[0],
        addressLng: pos[1]
      }));
      setShowMap(false);
      toast.success(t('contacts.locationSet'));
    };

    const handleUseMyLocation = async () => {
      if (!navigator.geolocation) {
        toast.error(t('contacts.errorGeolocationNotSupported'));
        return;
      }

      try {
        const position = await getPositionWithProgress(
          {
            desiredAccuracy: 20, // 20 meters for good accuracy
            maxWait: 15000, // Wait up to 15 seconds
            enableHighAccuracy: true
          },
          (progress) => {
            // Show progress messages
            if (progress.status === 'requesting') {
              toast.loading(t('contacts.locationRequesting'), { toastId: 'referral-location-toast' });
            } else if (progress.status === 'improving') {
              toast.loading(t('contacts.locationImproving'), { toastId: 'referral-location-toast' });
            } else if (progress.status === 'completed') {
              toast.dismiss('referral-location-toast');
            } else if (progress.status === 'timeout') {
              toast.dismiss('referral-location-toast');
            } else if (progress.status === 'error' || progress.status === 'failed') {
              toast.dismiss('referral-location-toast');
            }
          }
        );

        const { latitude, longitude, accuracy } = position.coords;
        const address = await reverseGeocode(latitude, longitude);
        
        setReferral(prev => ({ 
          ...prev, 
          address, 
          addressLat: latitude, 
          addressLng: longitude 
        }));
        toast.success(`${t('contacts.locationSet')} (±${Math.round(accuracy)}m)`, { toastId: 'referral-location-toast', autoClose: 3000 });
        
      } catch (error) {

        toast.error(t('contacts.errorGettingLocation'), { toastId: 'referral-location-toast', autoClose: 5000 });
      }
    };

    return (
      <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Personal Information */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-4 flex items-center gap-2">
              <UserIcon className="h-5 w-5 text-gray-400" />
              {t('contacts.personalInfo')}
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.name')} <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    name="name"
                    value={referral.name}
                    onChange={handleChange}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                    required
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.surname')} <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    name="surname"
                    value={referral.surname}
                    onChange={handleChange}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                    required
                  />
                </div>
              </div>
              <div>
                <PhoneInput
                    value={referral.phone}
                    onChange={handleChange}
                  name="phone"
                  label={t('contacts.phone')}
                    required
                  placeholder="0671234567"
                  otherPhone={referral.secondaryPhone}
                  />
              </div>
              <div>
                <PhoneInput
                  value={referral.secondaryPhone}
                  onChange={handleChange}
                  name="secondaryPhone"
                  label={`${t('contacts.secondaryPhone')} (${t('common.optional')})`}
                  placeholder={t('contacts.secondaryPhonePlaceholder')}
                  otherPhone={referral.phone}
                />
              </div>
              <div>
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.profession')}
                </label>
                <div className="relative">
                  <BuildingOffice2Icon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    name="profession"
                    value={referral.profession || ''}
                    onChange={handleChange}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                  />
                </div>
              </div>
              {showExtendedFieldsInEdit && (
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('users.personalId')} <span className="text-gray-400">({t('common.optional')})</span>
                  </label>
                  <div className="relative">
                    <HashtagIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      name="personalId"
                      value={referral.personalId || ''}
                      onChange={handleChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      pattern="^[A-Z][0-9]{8}[A-Z]$"
                      minLength={10}
                      maxLength={10}
                      placeholder={t('users.personalIdFormatHelper', { example: 'A12345678B' })}
                    />
                  </div>
                  <p className="mt-1 text-sm text-gray-500">{t('users.personalIdFormatHelper', { example: 'A12345678B' })}</p>
                </div>
              )}
              {showExtendedFieldsInEdit && (
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('users.birthday')} <span className="text-gray-400">({t('common.optional')})</span>
                  </label>
                  <div className="relative">
                    <CalendarIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="date"
                      name="birthday"
                      value={referral.birthday || ''}
                      onChange={handleChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                    />
                  </div>
                </div>
              )}
              {showExtendedFieldsInEdit && (
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('users.email')} <span className="text-gray-400">({t('common.optional')})</span>
                  </label>
                  <div className="relative">
                    <EnvelopeIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="email"
                      name="email"
                      value={referral.email || ''}
                      onChange={handleChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      placeholder="example@email.com"
                    />
                  </div>
                </div>
              )}
              <div className="md:col-span-2">
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.notes')} <span className="text-gray-400">({t('common.optional')})</span>
                </label>
                <div className="relative">
                  <DocumentTextIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                  <textarea
                    name="notes"
                    value={referral.notes || ''}
                    onChange={handleChange}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none"
                    rows="3"
                    placeholder={t('contacts.notesPlaceholder')}
                  />
                </div>
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.gifts')} <span className="text-gray-400">({t('common.optional')})</span>
                </label>
                <div className="relative">
                  <TagIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                  <textarea
                    name="gifts"
                    value={referral.gifts || ''}
                    onChange={handleChange}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none"
                    rows="3"
                    placeholder={t('contacts.giftsPlaceholder')}
                  />
                </div>
              </div>



            </div>
          </div>

          {/* Location */}
          <div>
            <h4 className="text-sm font-medium text-gray-700 mb-4 flex items-center gap-2">
              <MapPinIcon className="h-5 w-5 text-gray-400" />
              {t('contacts.location')}
            </h4>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('contacts.address')} <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <MapPinIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    name="address"
                    value={referral.address}
                    onChange={handleChange}
                    onBlur={async (e) => {
                      if (!referral.addressLat || !referral.addressLng) {
                        const geo = await geocodeAddress(e.target.value);
                        if (geo) {
                          setReferral(prev => ({ ...prev, addressLat: geo.lat, addressLng: geo.lng, address: geo.displayName || prev.address }));
                          toast.success(t('contacts.locationSet'));
                        } else {
                          toast.warn(t('contacts.geocodeNotFound', 'Could not find location for this address.'));
                        }
                      }
                    }}
                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                    placeholder={t('contacts.addressPlaceholder')}
                    required
                  />
                </div>
              </div>
              <div className="flex flex-col sm:flex-row gap-2">
                <button
                  type="button"
                  className="flex-1 flex items-center justify-center gap-1 px-4 py-2 text-sm font-medium text-[#253988] border border-[#253988] rounded hover:bg-[#253988]/10 transition-colors"
                  onClick={() => {
                    setMapInit([
                      referral.addressLat || 41.3275,
                      referral.addressLng || 19.8187
                    ]);
                    setShowMap(true);
                  }}
                >
                  <MapPinIcon className="h-4 w-4" />
                  {t('contacts.pickFromMap')}
                </button>
                                  <button
                    type="button"
                    className="flex-1 flex items-center justify-center gap-1 px-4 py-2 text-sm font-medium text-[#253988] border border-[#253988] rounded hover:bg-[#253988]/10 transition-colors disabled:opacity-50"
                    onClick={handleUseMyLocation}
                    disabled={clientGPS.isLocating}
                  >
                    {clientGPS.isLocating ? (
                      <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                    ) : (
                      <MapIcon className="h-4 w-4" />
                    )}
                    {clientGPS.isLocating ? t('common.loading') : t('contacts.useMyLocation')}
                  </button>
              </div>
            </div>
          </div>



          <div className="flex justify-end gap-2 pt-6 border-t border-gray-100">
            <button
              type="button"
              onClick={onCancel}
              className="px-6 py-2 rounded font-bold text-base text-[#253988] border border-[#253988] bg-white hover:bg-[#253988]/10 transition-colors"
            >
              {t('common.cancel')}
            </button>
            <button
              type="submit"
              disabled={isSaving}
              className="px-6 py-2 rounded font-bold text-base text-white bg-[#253988] hover:bg-[#253988]/90 transition-colors disabled:opacity-50 flex items-center gap-2"
            >
              {isSaving ? (
                <>
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t('common.saving')}
                </>
              ) : (
                t('contacts.saveReferral')
              )}
            </button>
          </div>
        </form>

        {showMap && (
          <LocationPicker
            open={showMap}
            onClose={() => setShowMap(false)}
            onPick={handleMapPick}
            initialLat={mapInit[0]}
            initialLng={mapInit[1]}
          />
        )}
      </div>
    );
  };

  // Update the referrals section in the new contact form
  function renderReferralsSection() {
    return (
      <div className="mt-8">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-gray-900">{t('contacts.referrals')}</h2>
          <button
            onClick={() => setShowReferralForm(true)}
            className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium shadow-xs text-white bg-[#253988] hover:bg-[#253988]/90 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-[#253988] transition-all duration-200"
          >
            <PlusIcon className="h-5 w-5 mr-2" aria-hidden="true" />
            {t('contacts.addReferral')}
          </button>
        </div>

        {showReferralForm ? (
          <ReferralForm
            onSave={(referral) => {
              setReferrals([...referrals, referral]);
              setShowReferralForm(false);
              toast.success(t('contacts.referralAdded'));
            }}
            onCancel={() => setShowReferralForm(false)}
          />
        ) : referrals.length > 0 ? (
          <div className="grid grid-cols-1 gap-4">
            {referrals.map((referral, index) => (
              <div
                key={index}
                className="bg-white rounded-lg shadow border border-gray-100 p-4 hover:shadow-md transition-shadow"
              >
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div>
                    <span className="text-sm text-gray-500">{t('contacts.name')}</span>
                    <p className="font-medium">{referral.name} {referral.surname}</p>
                  </div>
                  <div>
                    <span className="text-sm text-gray-500">{t('contacts.phone')}</span>
                    <p className="font-medium">{referral.phone}</p>
                  </div>
                  <div className="md:col-span-2">
                    <span className="text-sm text-gray-500">{t('contacts.address')}</span>
                    <p className="font-medium">{referral.address}</p>
                  </div>
                </div>
                <button
                  onClick={() => {
                    setReferrals(referrals.filter((_, i) => i !== index));
                    toast.success(t('contacts.referralDeleted'));
                  }}
                  className="mt-2 text-red-600 hover:text-red-800 text-sm font-medium"
                >
                  {t('common.delete')}
                </button>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 text-center py-8">{t('contacts.noReferrals')}</p>
        )}
      </div>
    );
  }

  // Add new function to handle adding referrals to existing contact
  const startAddReferrals = (contact) => {
    setSelectedContactForReferrals(contact);
    setShowAddReferralsModal(true);
  };

  const hasReferralActivity = (contact) => {
    // Check if contact has been referred by someone OR has referred others
    const hasBeenReferred = contact.referredByContactId || contact.referrer;
    // Use the referrals array from the backend response instead of searching through current contacts
    const hasReferredOthers = contact.referrals && contact.referrals.length > 0;
    return hasBeenReferred || hasReferredOthers;
  };

  const showReferralsInfo = async (contact) => {
    setSelectedContactForReferralsView(contact);
    
    try {
      // Load complete contact details with full referrals data for the modal
      const response = await offlineApi.getContactDetails(contact.id);
      if (response.data && response.data.success) {
        const fullContact = response.data.data;
        
        // Use full referrals data from detailed API call
        const referralsList = (fullContact.referrals || [])
          .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
        
        // Update the selected contact with full data including all referrals
        setSelectedContactForReferralsView(fullContact);
        setContactReferrals(referralsList);
      } else {
        // Fallback to existing data if API fails
        const referralsList = (contact.referrals || [])
          .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
        
        setContactReferrals(referralsList);
      }
    } catch (error) {
      logger.error('Failed to load complete referrals data:', error);
      // Fallback to existing data if API fails
      const referralsList = (contact.referrals || [])
        .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
      
      setContactReferrals(referralsList);
    }
    
    setShowReferralsModal(true);
  };

  const handleReferralCardClick = async (referralContact) => {
    try {
      // Fetch the complete referral contact data from the server
      const response = await offlineApi.getContact(referralContact.id);
      const fullReferralContact = response.data;
      
      // Close the referrals modal and open edit modal for the referral
      setShowReferralsModal(false);
      setTimeout(() => {
        startEdit(fullReferralContact);
        setShowEditModal(true);
      }, 100);
    } catch (error) {
      
      toast.error(t('contacts.errorContactNotFound'));
    }
  };

  // Add new function to handle saving a new referral
  const handleAddReferral = async (referralData) => {
    if (!selectedContactForReferrals) return;

    const isOnline = navigator.onLine;

    // Address is always required, but geocoding validation only happens when online
    if (
      !referralData?.name ||
      !referralData?.surname ||
      !referralData?.phone ||
      !/^(067|068|069)\d{7}$/.test(referralData.phone) ||
      !referralData?.address
    ) {
      toast.error(t('contacts.errorFillAllFieldsForReferral'));
      return;
    }

    const data = {
      ...referralData,
      referredByContactId: selectedContactForReferrals.id,
      associateIds: referralData?.associateIds && referralData.associateIds.length > 0 ? referralData.associateIds : selectedContactForReferrals.associateIds,
      email: referralData.email || null,
      signature: referralData.signature || null,
      // Skip geocoding when offline
      addressLat: isOnline ? referralData.addressLat : null,
      addressLng: isOnline ? referralData.addressLng : null
    };

    // Handle offline mode
    if (!isOnline) {
      try {
        const newReferral = await addContactOffline(data);
        
        // Update the contacts state to include the new referral
        setContacts(prev => prev.map(contact => {
          if (contact.id === selectedContactForReferrals.id) {
            return {
              ...contact,
              referrals: [...(contact.referrals || []), newReferral]
            };
          }
          return contact;
        }));

        toast.success(t('contacts.referralAddedOffline', 'Referral added while offline.'));
        setShowAddReferralsModal(false);
        setSelectedContactForReferrals(null);
        return;
      } catch (error) {
        if (error.message === 'PHONE_DUPLICATE') {
          toast.error(t('contacts.errorPhoneAlreadyAdded'));
        } else {
          toast.error(t('contacts.errorAddingReferral'));
        }
        return;
      }
    }

    // Online mode - proceed with existing API call
    try {
      const response = await fetch('/api/contacts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(data)
      });

      if (!response.ok) {
        const errorData = await response.json();
        if (response.status === 409 && errorData.error?.toLowerCase().includes('phone')) {
          toast.error(t('contacts.errorPhoneAlreadyAdded'));
          return;
        }
        throw new Error(errorData.error || t('contacts.errorAddingReferral'));
      }

      const newReferral = await response.json();
      
      // Update the contacts state to include the new referral
      setContacts(prev => prev.map(contact => {
        if (contact.id === selectedContactForReferrals.id) {
          return {
            ...contact,
            referrals: [...(contact.referrals || []), newReferral]
          };
        }
        return contact;
      }));

      toast.success(t('contacts.referralAdded'));
      setShowAddReferralsModal(false);
      setSelectedContactForReferrals(null);
    } catch (error) {
      toast.error(t('contacts.errorAddingReferral'));
      setIsSaving(false);
    }
  };

  // Add deleteContact function
  const deleteContact = async (contactId) => {
    const confirmed = await confirm({
      title: t('contacts.deleteContact', 'Delete Contact'),
      message: t('contacts.confirmDeleteContact'),
      confirmText: t('common.delete', 'Delete'),
      cancelText: t('common.cancel', 'Cancel'),
      type: 'danger'
    });

    if (!confirmed) {
      return;
    }

    setDeletingId(contactId);

    if (!navigator.onLine) {
      try {
        // Offline: delete locally and queue action
        await deleteContactOffline(contactId);
        setContacts(prev => prev.filter(contact => {
          // Remove the contact if it's the deleted one
          if (contact.id === contactId) return false;
          // If this contact has the deleted contact as a referral, remove it from referrals
          if (contact.referrals?.some(ref => ref.id === contactId)) {
            contact.referrals = contact.referrals.filter(ref => ref.id !== contactId);
          }
          return true;
        }));
        toast.success(t('contacts.contactDeletedOffline'));
      } catch (error) {
        toast.error(t('contacts.errorDeletingContact'));
      } finally {
        setDeletingId(null);
      }
      return;
    }

    try {
      const response = await fetch(`/api/contacts/${contactId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        
        // Handle specific error cases
        if (response.status === 404) {
          // Contact already deleted - remove from frontend state

          setContacts(prev => prev.filter(contact => {
            if (contact.id === contactId) return false;
            if (contact.referrals?.some(ref => ref.id === contactId)) {
              contact.referrals = contact.referrals.filter(ref => ref.id !== contactId);
            }
            return true;
          }));
          toast.info(t('contacts.contactAlreadyDeleted', 'Contact was already deleted'));
          return;
        }
        
        throw new Error(errorData.message || errorData.error || 'Failed to delete contact');
      }

      // Update the contacts state to remove the deleted contact
      setContacts(prev => prev.filter(contact => {
        // Remove the contact if it's the deleted one
        if (contact.id === contactId) return false;
        // If this contact has the deleted contact as a referral, remove it from referrals
        if (contact.referrals?.some(ref => ref.id === contactId)) {
          contact.referrals = contact.referrals.filter(ref => ref.id !== contactId);
        }
        return true;
      }));

      toast.success(t('contacts.contactDeleted'));
    } catch (error) {

      
      // Don't show error for 404 cases (already handled above)
      if (!error.message?.includes('already deleted')) {
        toast.error(t('contacts.errorDeletingContact'));
      }
    } finally {
      setDeletingId(null);
    }
  };

  // Add cancelEdit function
  const cancelEdit = () => {
    setShowEditModal(false);
    setEditingContact(null);
    setEditForm({});
  };

  // RBO Part History Modal handlers
  const handleOpenRboHistoryModal = (purchase) => {
    setSelectedPurchaseForRboHistory(purchase);
    setShowRboHistoryModal(true);
  };

  const handleCloseRboHistoryModal = () => {
    setShowRboHistoryModal(false);
    setSelectedPurchaseForRboHistory(null);
  };

  // Add this useEffect to log the products when they change
  useEffect(() => {
  }, [products]);

  const handleDownloadPurchasePdf = async (purchase) => {
    setDownloadingPdfPurchaseId(purchase.id);
    try {
      // Use the new purchase-specific PDF endpoint
      const response = await fetch(`/api/contacts/purchases/${purchase.id}/pdf?notify=true`, {
        headers: { 
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          Accept: 'application/pdf'
        }
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to generate PDF');
      }
      // Get the blob from the response
      const blob = await response.blob();
      // Create a download link
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `rbo-garanci-${purchase.serialNumber || purchase.id}.pdf`;
      // Append to body, click, and remove
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // Clean up the URL object
      window.URL.revokeObjectURL(url);
      toast.success(t('contacts.pdfDownloaded'));
    } catch (err) {
      logger.error('PDF download error:', err);
      toast.error(t('contacts.errorDownloadingPdf'));
    } finally {
      setDownloadingPdfPurchaseId(null);
    }
  };

  useEffect(() => {
    document.title = t('contacts.title', 'Contacts');
  }, [t, i18n?.language]);

  // Server-side contacts fetching with pagination
  const fetchPaginatedContacts = useCallback(async (page = 1, newFilters = null) => {
    try {
      setLoading(true);
      
      const filtersToUse = newFilters || serverFilters;
      const params = {
        page,
        limit: pageSize,
        // Include region filter if present to ensure server-side filtering & correct pagination
        ...(regionFilter ? { region: regionFilter } : {}),
        ...filtersToUse
      };
      
      // Remove empty filters
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });
      
      // Try to force fresh data by bypassing cache
      const response = await offlineApi.getContacts({ ...params, _timestamp: Date.now() });
      
      if (response.data) {
        const contactsData = response.data.data || response.data;
        const pagination = response.data.pagination;
        
        setContacts(contactsData);
        
        // Update rentals if included in response
        if (response.data.rentals) {
          setRentals(Array.isArray(response.data.rentals) ? response.data.rentals : []);
        }
        
        if (pagination) {
          setTotalContacts(pagination.total);
          setTotalPages(pagination.totalPages);
          setCurrentPage(pagination.page);
        } else {
          // Fallback for non-paginated response
          setTotalContacts(contactsData.length);
          setTotalPages(1);
          setCurrentPage(1);
        }
        
        // Check which contacts have archived meetings (await to ensure icons render)
        if (contactsData && contactsData.length > 0) {
          await checkContactsMeetingHistory(contactsData);
        }
      }
    } catch (error) {

      toast.error(t('common.error.fetchFailed'));
      setContacts([]);
      setTotalContacts(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [pageSize, serverFilters, offlineApi, t, regionFilter, checkContactsMeetingHistory]);

  // Fetch filter counts for legend
  const fetchFilterCounts = useCallback(async () => {
    try {
      setLoadingFilterCounts(true);
      const response = await fetch('/api/contacts/filter-counts', {
        headers: { 
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error('Failed to fetch filter counts');
      }
      
      const data = await response.json();
      if (data.success) {
        setFilterCounts(data.data);
      }
    } catch (error) {
      logger.error('Error fetching filter counts:', error);
      // Don't show error to user, just set empty counts as fallback
      setFilterCounts({});
    } finally {
      setLoadingFilterCounts(false);
    }
  }, []);

  // Initial load using combined API
  useEffect(() => {
    fetchInitialPageData(1);
  }, [fetchInitialPageData]);

  // Refetch when region filter in URL changes
  useEffect(() => {
    setCurrentPage(1);
    fetchInitialPageData(1);
  }, [regionFilter, fetchInitialPageData]);

  // Handle server filter changes
  const handleServerFilterChange = (filterName, value) => {
    const newFilters = { ...serverFilters, [filterName]: value };
    setServerFilters(newFilters);
    setCurrentPage(1);
    fetchPaginatedContacts(1, newFilters);
    // Also refresh filter counts when filters change
    fetchFilterCounts();
  };

  // Handle search input
  const handleSearchInputChange = (e) => {
    const query = e.target.value;
    setSearchQuery(query);
    setFilters(prev => ({ ...prev, searchQuery: query }));
    debouncedSearch(query);
  };

  // Handle pagination change
  const handlePageChange = (page) => {
    setCurrentPage(page);
    // For pagination, we still need to use the original contacts API with filters
    fetchPaginatedContacts(page);
  };



  // Update filters when server filters change
  useEffect(() => {
    fetchPaginatedContacts(currentPage);
    // Also refresh filter counts when server filters change to keep legend numbers accurate
    fetchFilterCounts();
  }, [serverFilters, fetchFilterCounts]);



  // Debounced refetch - only when not actively editing a contact
  const debouncedRefetch = React.useMemo(() => debounce(() => {
    if (!loading && !showEditModal) { // Don't refresh when edit form is open
      fetchPaginatedContacts(currentPage);
    }
  }, 250), [loading, fetchPaginatedContacts, currentPage, showEditModal]);

  // Smart real-time update handlers
  const handleContactCreated = useCallback((newContact) => {
    // If user is editing a contact, just show a toast notification instead of refreshing
    if (showEditModal) {
      toast.info(t('contacts.newContactCreatedByOther', 'Another user created a new contact'), {
        autoClose: 3000,
        position: 'bottom-right'
      });
      return;
    }
    
    // If not creating, check if we should add to current list or refresh
    const shouldAddToCurrentList = () => {
      // Add to list if it would fit current filters
      const matchesFilters = filterContact(newContact, false, null, serverFilters, user, searchInContact);
      
      // Only add if on first page to maintain pagination integrity
      return matchesFilters && currentPage === 1;
    };

    if (shouldAddToCurrentList()) {
      // Add to beginning of current list
      setContacts(prev => [newContact, ...prev]);
      // Update total count
      setTotalContacts(prev => prev + 1);
    } else {
      // Otherwise just update the count and show notification
      setTotalContacts(prev => prev + 1);
      toast.info(t('contacts.newContactAdded', 'A new contact was added'), {
        autoClose: 2000,
        position: 'bottom-right'
      });
    }
    // Refresh filter counts to keep legend accurate
    fetchFilterCounts();
  }, [showEditModal, serverFilters, user, searchInContact, currentPage, filterContact, t, fetchFilterCounts]);

  const handleContactUpdated = useCallback(async (updatedContact) => {
    // Check if this contact is in the current view
    const contactExists = contacts.some(c => c.id === updatedContact.id);
    
    if (contactExists) {
      // Update the contact in the current list if it exists
      setContacts(prev => {
        const updated = prev.map(contact => {
          if (contact.id === updatedContact.id) {
            // Create completely new object reference to ensure React detects the change
            return { ...updatedContact };
          }
          return contact;
        });
        return updated;
      });
      
      // Check if updated contact has archived meetings
      await checkContactsMeetingHistory([updatedContact]);
    } else if (!showEditModal) {
      // If contact not in current list and modal not open, might need to refresh to show it
      // This handles cases where a contact's status changed making it match current filters
      const matchesFilters = filterContact(updatedContact, false, null, serverFilters, user, searchInContact);
      if (matchesFilters && currentPage === 1) {
        // Refresh to include this contact
        fetchPaginatedContacts(currentPage);
      }
    }
    
    // Refresh filter counts since contact status may have changed
    fetchFilterCounts();
  }, [fetchFilterCounts, contacts, showEditModal, filterContact, serverFilters, user, searchInContact, currentPage, fetchPaginatedContacts, checkContactsMeetingHistory]);

  const handleContactDeleted = useCallback(({ id }) => {
    // Remove from current list and update count
    setContacts(prev => {
      const filtered = prev.filter(contact => contact.id !== id);
      if (filtered.length !== prev.length) {
        // Contact was in current list, update total count
        setTotalContacts(prev => Math.max(0, prev - 1));
      }
      return filtered;
    });
    // Refresh filter counts since a contact was deleted
    fetchFilterCounts();
  }, [fetchFilterCounts]);

  useEffect(() => {
    // Add socket listeners for real-time updates with smart handlers
    const unsubscribes = [
      addEventListener('contact:created', handleContactCreated),
      addEventListener('contact:updated', handleContactUpdated), 
      addEventListener('contact:deleted', handleContactDeleted),
    ];
    return () => {
      unsubscribes.forEach(unsub => unsub && unsub());
    };
  }, [addEventListener, handleContactCreated, handleContactUpdated, handleContactDeleted]);

  // Function to search for contact across all pages
  const searchForContactAcrossPages = async (contactId) => {
    try {
      // First, try to get the contact directly
      const response = await fetch(`/api/contacts/${contactId}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      
      if (response.ok) {
        const contact = await response.json();
        
        // Now search through pages to find which page contains this contact
        // We'll search by clearing filters and searching by name
        const searchQuery = `${contact.name} ${contact.surname}`;
        
        // Clear current filters and search for the contact
        setServerFilters({
          search: searchQuery,
          isRBO: '',
          contacted: '',
          agentId: '',
          startDate: '',
          endDate: ''
        });
        
        // Fetch with the search query
        fetchPaginatedContacts(1, {
          search: searchQuery,
          isRBO: '',
          contacted: '',
          agentId: '',
          startDate: '',
          endDate: ''
        });
        
      } else {
        toast.error(t('contacts.contactNotFound', 'Contact not found'));
        setHighlightId(null);
      }
    } catch (error) {

      toast.error(t('contacts.errorSearchingContact', 'Error searching for contact'));
      setHighlightId(null);
    }
  };

  // Simplified function to render contact without referral hierarchy - now uses memoized component
  const renderContactRow = (contact) => {
    return (
      <ContactMobileCard
        key={contact.id}
        contact={contact}
        highlightId={highlightId}
        highlightRef={highlightRef}
        isAgent={isAgent}
        user={user}
        getAgent={getAgent}
        getGoogleMapsUrl={getGoogleMapsUrl}
        getRowBackgroundColor={getRowBackgroundColor}
        hasRental={hasRental}
        formatPhoneForTel={formatPhoneForTel}
        truncate={truncate}
        hasReferralActivity={hasReferralActivity}
        showReferralsInfo={showReferralsInfo}
        startAddReferrals={startAddReferrals}
        startEdit={startEdit}
        deleteContact={deleteContact}
        renderStatusIcons={renderStatusIcons}
        isOperator={isOperator}
        isAdmin={isAdmin}
        contacts={contacts}
        contactsWithHistory={contactsWithHistory}
        setHistoryContact={setHistoryContact}
        setShowMeetingHistoryModal={setShowMeetingHistoryModal}
        t={t}
      />
    );
  };

  // OLD renderContactRow code kept for reference
  const _OLD_renderContactRow = (contact) => {
    // Enhanced safety checks for iOS compatibility
    if (!contact || typeof contact !== 'object' || !contact.id) {
      return null;
    }

    try {
      const agentName = getAgent(contact); // Get agent name as a string
      const mapsUrl = getGoogleMapsUrl(contact);
      const rowColor = getRowBackgroundColor(contact); 
      const isHighlighted = highlightId === String(contact.id);
  
    return (
      <div 
        key={contact.id} 
        ref={isHighlighted ? highlightRef : null} 
        data-highlighted={isHighlighted ? "true" : "false"}
        className={isHighlighted 
          ? "p-4 mb-3 rounded-lg shadow-lg border-2 border-yellow-400 bg-yellow-200 ring-2 ring-yellow-400 ring-opacity-50" 
          : `p-4 mb-3 rounded-lg shadow-md border border-gray-200 ${rowColor}`
        }
        style={{}}
      >
        <div className="flex justify-between items-start mb-2">
          <div className="flex items-center gap-2">
            <h3 className="text-lg font-semibold text-aura-blue-700">
              {contact.name} {contact.surname} {isHighlighted && "🔥 HIGHLIGHTED! 🔥"}
            </h3>
          </div>
          {!isAgent && (
            <div className="flex gap-2 flex-wrap">
              {/* Contact Status Badge - improved display */}
              {(() => {
                const hasPurchases = contact.purchases && contact.purchases.length > 0;
                const hasReservations = contact.reservations && contact.reservations.length > 0;
                
                if (hasPurchases) {
                  return (
                    <span className="px-2.5 py-1 text-sm font-semibold bg-[#253988] text-white rounded-full shadow-sm">
                      RBO
                    </span>
                  );
                } else if (hasReservations) {
                  return (
                    <span className="px-2.5 py-1 text-sm font-semibold bg-orange-500 text-white rounded-full shadow-sm">
                      REZ
                    </span>
                  );
                } else {
                  return (
                    <span className="px-2.5 py-1 text-sm font-semibold bg-gray-400 text-white rounded-full shadow-sm">
                      NO
                    </span>
                  );
                }
              })()}
              
              {/* Rental Status */}
              {hasRental(contact.id) && (
                 <span className="px-2.5 py-1 text-sm font-semibold bg-purple-500 text-white rounded-full shadow-sm">
                   {t('common.rental')}
                 </span>
              )}
              {contact.contactAttemptReason && (
                <span className={`px-2.5 py-1 text-sm font-semibold rounded-full shadow-sm ${
                  contact.contactAttemptReason === 'no_answer' || contact.contactAttemptReason === 'disconnected' 
                    ? 'bg-gray-500 text-white' :
                  contact.contactAttemptReason === 'busy' 
                    ? 'bg-aura-blue text-white' :
                  contact.contactAttemptReason === 'not_interested' 
                    ? 'bg-red-500 text-white' :
                  contact.contactAttemptReason === 'callback_requested' 
                    ? 'bg-green-500 text-white' :
                  contact.contactAttemptReason === 'wrong_number' 
                    ? 'bg-yellow-500 text-white' :
                  contact.contactAttemptReason === 'voicemail' 
                    ? 'bg-purple-500 text-white' :
                  contact.contactAttemptReason === 'other' 
                    ? 'bg-slate-500 text-white' :
                  'bg-gray-500 text-white'
                }`}>
                  {t(`contactAttempt.reason.${contact.contactAttemptReason}`)}
                </span>
              )}
            </div>
          )}
        </div>

        <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm text-gray-700 mb-3">
          <div className="flex items-center gap-2"> {/* Textual Phone */}
            <PhoneIcon className="h-5 w-5 text-gray-400 shrink-0" />
            <div className="flex flex-col gap-1">
              {contact._dataMasked || !contact.phone ? (
                <span 
                  className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-amber-50 text-amber-700"
                  title={t('contacts.dataProtectedInfo')}
                >
                  {t('contacts.phoneProtected')}
                </span>
              ) : (
                <a 
                  href={`tel:${formatPhoneForTel(contact.phone)}`} 
                  className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-gray-100 text-gray-800 hover:bg-gray-200 transition-colors"
                  aria-label={t('contacts.callNumber', { number: contact.phone })}
                >
                  {contact.phone}
                </a>
              )}
              {contact.secondaryPhone && (
                <a 
                  href={`tel:${formatPhoneForTel(contact.secondaryPhone)}`} 
                  className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium font-mono bg-gray-100 text-gray-800 hover:bg-gray-200 transition-colors"
                  aria-label={t('contacts.callSecondaryNumber', { number: contact.secondaryPhone })}
                >
                  {contact.secondaryPhone}
                </a>
              )}
            </div>
          </div>
          {(contact.address || contact._dataMasked) && ( /* Textual Address */
            <div className="col-span-2 flex items-center gap-2">
              <MapPinIcon className="h-5 w-5 text-gray-400 shrink-0" />
              {contact._dataMasked || !contact.address ? (
                <span 
                  className="text-amber-700 text-sm"
                  title={t('contacts.dataProtectedInfo')}
                >
                  {t('contacts.addressProtected')}
                </span>
              ) : (
                <span>{truncate(contact.address, 40)}</span>
              )}
            </div>
          )}
          {contact.profession && ( /* Profession */
            <div className="col-span-2 flex items-center gap-2">
              <BriefcaseIcon className="h-5 w-5 text-gray-400 shrink-0" />
              <span>{contact.profession}</span>
            </div>
          )}
          <div className="flex items-center gap-2 col-span-2">
            <UserCircleIcon className="h-5 w-5 text-gray-400 shrink-0" />
            <span>{agentName}</span>
          </div>
        </div>
        
        {/* Referrer Information - Show if this contact was referred by someone */}
        {(contact.referredByContactId || contact.referrer) && (
          <div className="mt-3 pt-3 border-t border-gray-100">
            <div className="text-sm text-gray-600">
              <span className="font-medium">{t('contacts.referredBy')}: </span>
              {contact.referrer ? (
                <span className="text-gray-900">{contact.referrer.name} {contact.referrer.surname}</span>
              ) : (
                (() => {
                  const referrer = contacts.find(c => c.id === contact.referredByContactId);
                  return referrer ? (
                    <span className="text-gray-900">{referrer.name} {referrer.surname}</span>
                  ) : (
                    <span className="text-gray-500">{t('contacts.unknownReferrer')}</span>
                  );
                })()
              )}
            </div>
          </div>
        )}
        
        {/* Action Buttons Row */}
        <div className="mt-4 pt-3 border-t border-gray-200 flex justify-between items-center">
          {/* Status Icons on the left */}
          <div className="flex items-center gap-2">
            {renderStatusIcons(contact)}
          </div>

          {/* Action Icons on the right - Structured in two groups */}
          <div className="flex items-center"> {/* Parent container for right-side icon groups */}
            <div className="flex items-center gap-2"> {/* Group 1: Phone and Map */}
              {contact.phone && !contact._dataMasked && (
                <a 
                  href={`tel:${formatPhoneForTel(contact.phone)}`}
                  className="p-2 text-gray-500 hover:text-aura-blue-600 transition-colors rounded-full hover:bg-aura-blue-50"
                  aria-label={t('contacts.callNumber', { number: contact.phone })}
                >
                  <PhoneArrowUpRightIcon className="h-5 w-5" />
                </a>
              )}
              {contact.secondaryPhone && !contact._dataMasked && (
                <a 
                  href={`tel:${formatPhoneForTel(contact.secondaryPhone)}`}
                  className="p-2 text-gray-500 hover:text-aura-blue-600 transition-colors rounded-full hover:bg-aura-blue-50"
                  aria-label={t('contacts.callSecondaryNumber', { number: contact.secondaryPhone })}
                >
                  <PhoneArrowUpRightIcon className="h-5 w-5" />
                </a>
              )}
              {mapsUrl && !contact._dataMasked && (
                <a 
                  href={mapsUrl} 
                  target="_blank" 
                  rel="noopener noreferrer"
                  className="p-2 text-gray-500 hover:text-aura-green-600 transition-colors rounded-full hover:bg-aura-green-100"
                  aria-label={t('contacts.openInMaps', { address: contact.address })}
                >
                  <MapPinIcon className="h-5 w-5" />
                </a>
              )}
            </div>

            <div className="flex items-center gap-2 ml-4"> {/* Group 2: Original Actions, with ml-4 for separation */}
              {/* Meeting History indicator - Show for contacts with archived meetings */}
              {contactsWithHistory && contactsWithHistory.has(contact.id) && (
                <button 
                  onClick={() => {
                    setHistoryContact(contact);
                    setShowMeetingHistoryModal(true);
                  }}
                  className="p-2 text-gray-500 hover:text-purple-600 transition-colors rounded-full hover:bg-purple-50"
                  aria-label={t('meetings.viewHistory')}
                  title={t('meetings.viewHistory')}
                >
                  <ClockIcon className="h-5 w-5" />
                </button>
              )}
              
              {/* Referrals info button - Show for contacts with referral activity */}
              {hasReferralActivity(contact) && (
                <button 
                  onClick={() => showReferralsInfo(contact)} 
                  className="p-2 text-gray-500 hover:text-blue-600 transition-colors rounded-full hover:bg-blue-50"
                  aria-label={t('contacts.viewReferrals')}
                >
                  <UserGroupIcon className="h-5 w-5" />
                </button>
              )}

              {/* For agents, show edit and referral buttons */}
              {isAgent ? (
                <>
                  <button 
                    onClick={() => startAddReferrals(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                    aria-label={t('contacts.addReferral')}
                  >
                    <UserPlusIcon className="h-5 w-5" />
                  </button>
                  <button 
                    onClick={() => startEdit(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                    aria-label={t('common.edit')}
                  >
                    <PencilIcon className="h-5 w-5" />
                  </button>
                </>
              ) : isOperator ? (
                // Operator sees add referral, edit, and delete buttons (no PDF download)
                <>
                  <button 
                    onClick={() => startAddReferrals(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                    aria-label={t('contacts.addReferral')}
                  >
                    <UserPlusIcon className="h-5 w-5" />
                  </button>
                  <button 
                    onClick={() => startEdit(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                    aria-label={t('common.edit')}
                  >
                    <PencilIcon className="h-5 w-5" />
                  </button>
                  <button 
                    onClick={() => deleteContact(contact.id)} 
                    className="p-2 text-gray-500 hover:text-red-600 transition-colors rounded-full hover:bg-red-50"
                    aria-label={t('common.delete')}
                  >
                    <TrashIcon className="h-5 w-5" />
                  </button>
                </>
              ) : (
                // Admin/Owner see all buttons in desktop order: Add Referral, PDF Download, Edit, Delete
                <>
                  <button 
                    onClick={() => startAddReferrals(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-teal-600 transition-colors rounded-full hover:bg-aura-teal-50"
                    aria-label={t('contacts.addReferral')}
                  >
                    <UserPlusIcon className="h-5 w-5" />
                  </button>


                  <button 
                    onClick={() => startEdit(contact)} 
                    className="p-2 text-gray-500 hover:text-aura-accent-600 transition-colors rounded-full hover:bg-aura-accent-100"
                    aria-label={t('common.edit')}
                  >
                    <PencilIcon className="h-5 w-5" />
                  </button>
                  <button 
                    onClick={() => deleteContact(contact.id)} 
                    className="p-2 text-gray-500 hover:text-red-600 transition-colors rounded-full hover:bg-red-50"
                    aria-label={t('common.delete')}
                  >
                    <TrashIcon className="h-5 w-5" />
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
         );
    } catch (error) {

      return (
        <div key={contact.id} className="p-4 mb-3 rounded-lg border border-red-200 bg-red-50">
          <div className="text-red-600 text-sm">
            {t('contacts.errorRenderingContact', 'Error displaying contact')} {contact.name || contact.id}
          </div>
        </div>
      );
    }
   };

  // Debounced search
  const debouncedSearch = useMemo(
    () => debounce((query) => {
      setServerFilters(prev => ({ ...prev, search: query }));
      setCurrentPage(1);
    }, 500),
    []
  );

  const formatDate = (dateString, locale = 'en') => {
    if (!dateString) return '';
    return formatAlbanianDate(dateString);
  };

  const formatDateForDisplay = (dateString) => {
    if (!dateString) return '';
    return formatAlbanianDate(dateString);
  };


  // Get region filter from query param
  const params = new URLSearchParams(location.search);
  const regionFilterParam = params.get('region'); // legacy variable; not used

  // Helper to check if a contact/referral has a rental
  const hasRental = (contactId) => rentals.some(r => r.contactId === contactId);

  // Handle highlighting from URL parameter
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const highlightParam = params.get('highlight');
    if (highlightParam) {
      // Add 2-second delay to ensure DOM is fully rendered
      setTimeout(() => {
        setHighlightId(highlightParam);
        
        // Scroll to highlighted contact after another short delay
        setTimeout(() => {
          if (highlightRef.current) {
            highlightRef.current.scrollIntoView({ 
              behavior: 'smooth', 
              block: 'center' 
            });
          }
        }, 500);
        
        // Clear highlight after 3 seconds
        setTimeout(() => {
          setHighlightId(null);
        }, 3000);
      }, 0); // No delay - set immediately
    } else {
      setHighlightId(null);
    }
  }, [location.search, contacts]);

  return (
    <ErrorBoundary>
      <div role="region" aria-label={t('contacts.title')}>
        <PageHeader
        title={t('contacts.title')}
        description={t('contacts.description')}
        action={
          <div className="flex flex-col md:flex-row gap-2 w-full md:w-auto">
            <Link
              to="/contacts/new"
              className="order-1 md:order-3 inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium shadow-xs text-white bg-aura-blue hover:bg-aura-blue-600 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-aura-blue transition-all duration-200"
              aria-label={t('contacts.addNewContact')}
            >
              <PlusIcon className="h-5 w-5 mr-2" aria-hidden="true" />
              {t('contacts.addNewContact')}
            </Link>
            {(isAdmin || isOperator) && (
              <button
                type="button"
                className="order-2 md:order-1 inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium shadow-xs text-white bg-aura-blue hover:bg-aura-blue-600 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-aura-blue transition-all duration-200"
                onClick={() => navigate('/contacts/regions')}
                aria-label="View Contacts by Region"
              >
                <MapIcon className="h-5 w-5 mr-2" />
                {t('contacts.viewByRegion', 'View by Region')}
              </button>
            )}
            {(isAdmin || isOperator) && (
              <button
                onClick={() => setShowFilters(v => !v)}
                className="order-3 md:order-2 inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium shadow-xs text-white bg-aura-blue hover:bg-aura-blue-600 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-aura-blue transition-all duration-200"
                aria-expanded={showFilters}
                aria-controls="filters-panel"
                aria-label={showFilters ? t('checkins.hideFilters') : t('checkins.showFilters')}
              >
                <FunnelIcon className="h-5 w-5 mr-2" aria-hidden="true" />
                {showFilters ? t('checkins.hideFilters') : t('checkins.showFilters')}
                {showFilters ? (
                  <ChevronUpIcon className="h-4 w-4 ml-2" aria-hidden="true" />
                ) : (
                  <ChevronDownIcon className="h-4 w-4 ml-2" aria-hidden="true" />
                )}
              </button>
            )}
          </div>
        }
      />

      {/* Legend */}
      {(isAdmin || isOperator) && (
        <Legend 
          activeFilter={activeLegendFilter} 
          onFilterClick={handleLegendFilterClick}
          contacts={contacts}
          user={user}
          filters={filters}
          searchInContact={searchInContact}
          legendItems={legendItems} // Pass legendItems as a prop
          regionFilter={regionFilter}
          filterCounts={filterCounts} // Pass filter counts for accurate legend display
          expiredCount={filterCounts.expired || 0} // Server-side expired count
        />
      )}

      {/* Filters */}
      {showFilters && (
        <div 
          id="filters-panel"
          role="region" 
          aria-label={t('contacts.filters.title')}
          className="bg-white shadow-lg rounded-xl overflow-hidden border border-gray-100 transition-all duration-200 hover:shadow-xl mb-6"
        >
          <div className="px-6 py-6">
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
              {/* Search field for admin/owner/operator */}
              {(isAdmin || isOperator) && (
                <div className="md:col-span-2">
                  <label htmlFor="searchQuery" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('contacts.search')}
                  </label>
                  <div className="mt-1 relative">
                    <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      id="searchQuery"
                      name="searchQuery"
                      value={searchQuery}
                      onChange={handleSearchInputChange}
                      placeholder={t('contacts.searchPlaceholder')}
                      className="block w-full pl-10 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                    />
                  </div>
                </div>
              )}

              {/* Date filters */}
              <div>
                <label htmlFor="startDate" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('checkins.filters.startDate')}
                </label>
                <div className="mt-1 relative">
                  <CalendarIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400 pointer-events-none" />
                  <input
                    type="date"
                    id="startDate"
                    name="startDate"
                    value={filters.startDate}
                    onChange={handleFilterChange}
                    className="block w-full pl-10 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                  />
                </div>
              </div>

              <div>
                <label htmlFor="endDate" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                  {t('checkins.filters.endDate')}
                </label>
                <div className="mt-1 relative">
                  <CalendarIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400 pointer-events-none" />
                  <input
                    type="date"
                    id="endDate"
                    name="endDate"
                    value={filters.endDate}
                    onChange={handleFilterChange}
                    className="block w-full pl-10 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                  />
                </div>
              </div>

              {/* Agent filter (only for admin/owner/operator) */}
              {(isAdmin || isOperator) && (
                <div>
                  <label htmlFor="agentId" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('contacts.agent')}
                  </label>
                  <select
                    id="agentId"
                    name="agentId"
                    value={filters.agentId}
                    onChange={handleFilterChange}
                    className="mt-1 block w-full px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                  >
                    <option value="">{t('common.all')}</option>
                    {allUsers.map(user => {
                      const isInactive = user.isActive === false;
                      return (
                        <option key={user.id} value={user.id}>
                          {user.firstName} {user.lastName} ({user.email}){isInactive ? ` - ${t('common.statusOptions.inactive')}` : ''}
                        </option>
                      );
                    })}
                  </select>
                </div>
              )}

              {/* Contact Status Filter - 3-way */}
              <div>
                <label htmlFor="status" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.status')}</label>
                <select
                  id="status"
                  name="status"
                  value={filters.status}
                  onChange={handleFilterChange}
                  className="block w-full px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                >
                  <option value="">{t('common.all')}</option>
                  <option value="NO">{t('contacts.statusNo')}</option>
                  <option value="REZ">{t('contacts.statusRez')}</option>
                  <option value="RBO">{t('contacts.statusRbo')}</option>
                </select>
              </div>
              {/* Contacted Filter */}
              <div>
                <label htmlFor="contacted" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.management.status')}</label>
                <select
                  id="contacted"
                  name="contacted"
                  value={filters.contacted}
                  onChange={handleFilterChange}
                  className="block w-full px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                >
                  <option value="">{t('common.all')}</option>
                  <option value="true">{t('contacts.management.contacted')}</option>
                  <option value="false">{t('contacts.management.notContacted')}</option>
                </select>
              </div>
              {/* Response Filter */}
              <div>
                <label htmlFor="response" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.management.response.title')}</label>
                <select
                  id="response"
                  name="response"
                  value={filters.response}
                  onChange={handleFilterChange}
                  className="block w-full px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                >
                  <option value="">{t('common.all')}</option>
                  <option value="held">{t('contacts.management.meetingStatus.held')}</option>
                  <option value="reschedule">{t('contacts.management.meetingStatus.reschedule')}</option>
                  <option value="failed">{t('contacts.management.meetingStatus.failed')}</option>
                  <option value="do_not_contact">{t('contacts.management.meetingStatus.do_not_contact')}</option>
                </select>
              </div>
              {/* Upcoming Meeting Filter */}
              <div>
                <label htmlFor="hasUpcomingMeeting" className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.management.meeting.title')}</label>
                <select
                  id="hasUpcomingMeeting"
                  name="hasUpcomingMeeting"
                  value={filters.hasUpcomingMeeting}
                  onChange={handleFilterChange}
                  className="block w-full px-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                >
                  <option value="">{t('common.all')}</option>
                  <option value="true">{t('contacts.management.meeting.hasUpcoming')}</option>
                  <option value="false">{t('contacts.management.meeting.noUpcoming')}</option>
                </select>
              </div>
            </div>
            <div className="flex justify-between items-center mt-4">
              {/* Results Counter */}
              <div className="text-sm text-gray-600">
                {!loading && (
                  <span>
                    {totalContacts > 0 ? (
                      <>
                        {t('common.showingResults', { count: totalContacts })}
                      </>
                    ) : (
                      t('common.noResults', 'No results found')
                    )}
                  </span>
                )}
                {loading && (
                  <span>{t('common.loading')}</span>
                )}
              </div>

              {/* Clear Filters Button */}
              <button
                onClick={clearFilters}
                className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium shadow-xs text-gray-700 bg-white hover:bg-gray-100 focus:outline-hidden focus:ring-2 focus:ring-offset-2 focus:ring-aura-blue transition-all duration-200"
              >
                <XMarkIcon className="h-4 w-4 mr-2" />
                {t('common.clearFilters')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Optionally show active region filter */}
      {regionFilter && (
        <div className="mb-2 text-blue-700 font-semibold">
          {t('contacts.showingForRegion', { region: REGION_NAMES[regionFilter] || regionFilter })}
          <button
            className="ml-2 text-sm text-blue-500 underline"
            onClick={() => {
              const newParams = new URLSearchParams(location.search);
              newParams.delete('region');
              navigate({ search: newParams.toString() });
            }}
          >
            {t('common.clear')}
          </button>
        </div>
      )}

      {/* Contacts Table */}
      <div 
        className="hidden md:block complex-table-wrapper bg-white shadow overflow-hidden sm:rounded-lg"
        role="region" 
        aria-label={t('contacts.tableTitle')}
      >
        <table 
          className="min-w-full divide-y divide-gray-200 mobile-table tablet-compact desktop-table contact-table-mobile table-fixed"
          role="grid"
          aria-label={t('contacts.tableTitle')}
        >
          <thead className="bg-gray-50">
            <tr>
              <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[150px]">{t('contacts.name')}</th>
              <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[110px]">{t('contacts.phone')}</th>
              <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider mobile-hide-sm max-w-[180px]">{t('contacts.address')}</th>
              <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider mobile-hide-sm max-w-[120px]">{t('contacts.profession')}</th>
              {!isAgent && (
                <>
                  <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider w-[70px]">{t('contacts.sold')}</th>
                  <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[50px]">{t('contacts.rent')}</th>
                </>
              )}
              {showAgentColumn && (
                <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[100px]">{t('contacts.agent')}</th>
              )}
              {(isAdmin || isOperator) && (
                <th scope="col" className="px-3 py-2 text-left text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[120px]">{t('contactAttempt.columnTitle')}</th>
              )}
              {(canEditDelete || isAgent) && (
                <th scope="col" className="px-3 py-2 text-right text-sm font-medium text-gray-500 uppercase tracking-wider max-w-[120px]">{t('common.actions')}</th>
              )}
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-100">
            {loading ? (
              <tr>
                <td 
                  colSpan={isAgent ? 5 : (canEditDelete || isAgent) ? (isAdmin || isOperator ? 8 : 7) : (isAdmin || isOperator ? 7 : 6)} 
                  className="px-3 py-3 text-center text-sm text-gray-500"
                  role="status"
                  aria-live="polite"
                >
                  {t('common.loading')}
                </td>
              </tr>
            ) : Object.keys(processContactsForDisplay).length === 0 ? (
              <tr>
                <td 
                  colSpan={isAgent ? 5 : (canEditDelete || isAgent) ? (isAdmin || isOperator ? 8 : 7) : (isAdmin || isOperator ? 7 : 6)} 
                  className="px-3 py-3 text-center text-sm text-gray-500"
                  role="status"
                  aria-live="polite"
                >
                  {t('contacts.noContacts')}
                </td>
              </tr>
            ) : (
              Object.entries(processContactsForDisplay)
                .sort(([dateA], [dateB]) => new Date(dateB) - new Date(dateA))
                .map(([date, dateContacts]) => (
                  <React.Fragment key={date}>
                    {/* Date header row */}
                    <tr className="bg-gray-50">
                      <td colSpan={isAgent ? 6 : (canEditDelete || isAgent) ? (isAdmin || isOperator ? 9 : 8) : (isAdmin || isOperator ? 8 : 7)} className="px-3 py-2">
                        <div className="flex items-center">
                          <CalendarIcon className="h-4 w-4 text-gray-400 mr-2" />
                          <span className="text-sm font-medium text-gray-900">
                            {formatDateLocalized(date, i18n?.language || 'en')}
                          </span>
                        </div>
                      </td>
                    </tr>

                    {/* Using memoized ContactRow for 10-20x better performance */}
                    {dateContacts.map((contact) => (
                      <ContactRow
                        key={contact.id}
                        contact={contact}
                        user={user}
                        isAgent={isAgent}
                        isAdmin={isAdmin}
                        isOperator={isOperator}
                        canEditDelete={canEditDelete}
                        showAgentColumn={showAgentColumn}
                        getRowBackgroundColor={getRowBackgroundColor}
                        formatPhoneForTel={formatPhoneForTel}
                        getAgent={getAgent}
                        hasRental={hasRental}
                        getGoogleMapsUrl={getGoogleMapsUrl}
                        truncate={truncate}
                        hasReferralActivity={hasReferralActivity}
                        showReferralsInfo={showReferralsInfo}
                        startAddReferrals={startAddReferrals}
                        startEdit={startEdit}
                        setShowEditModal={setShowEditModal}
                        deleteContact={deleteContact}
                        contactsWithHistory={contactsWithHistory}
                        setHistoryContact={setHistoryContact}
                        setShowMeetingHistoryModal={setShowMeetingHistoryModal}
                        t={t}
                      />
                    ))}
                  </React.Fragment>
                ))
            )}
          </tbody>
        </table>
      </div> {/* End Desktop Table Wrapper */}

      {/* Contacts List - Mobile View */}
      <div className="md:hidden space-y-4 mt-4">
        <MobileContactsList
          loading={loading}
          contacts={displayContacts}
          processContactsForDisplay={processContactsForDisplay}
          renderContactRow={renderContactRow}
          formatDateLocalized={formatDateLocalized}
          i18n={i18n || { language: 'en' }}
          t={t}
        />
      </div> {/* End Mobile Card View */}

      {/* Pagination Controls */}
      {!loading && totalPages > 1 && (
        <div className="mt-6">
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalCount={totalContacts}
            pageSize={pageSize}
            onPageChange={handlePageChange}
            loading={loading}
          />
        </div>
      )}

      {/* Edit Modal */}
      {showEditModal && editingContact && (
        <Modal
          isOpen={showEditModal}
          onClose={cancelEdit}
          title={t('contacts.editReferral')}
          size="xl"
        >
          <form className="space-y-8" onSubmit={e => { e.preventDefault(); saveEdit(); }}>
            {/* Referral Information Section - Show if this contact was referred by someone */}
            {editingContact.referredByContactId && (() => {
              const referrer = contacts.find(c => c.id === editingContact.referredByContactId);
              return referrer ? (
                <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="shrink-0">
                        <UserGroupIcon className="h-6 w-6 text-blue-600" />
                      </div>
                      <div>
                        <h3 className="text-sm font-semibold text-blue-800">
                          {t('contacts.referredBy')}
                        </h3>
                        <p className="text-sm text-blue-700">
                          <span className="font-medium">{referrer.name} {referrer.surname}</span>
                          {referrer.phone && (
                            <span className="ml-2 text-blue-600">({referrer.phone})</span>
                          )}
                        </p>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        setShowEditModal(false);
                        setTimeout(() => startEdit(referrer), 100);
                      }}
                      className="px-3 py-1.5 text-sm font-medium text-blue-700 bg-blue-100 hover:bg-blue-200 border border-blue-300 rounded-md transition-colors"
                    >
                      {t('contacts.viewReferrer')}
                    </button>
                  </div>
                </div>
              ) : editingContact.referrer ? (
                <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="shrink-0">
                        <UserGroupIcon className="h-6 w-6 text-blue-600" />
                      </div>
                      <div>
                        <h3 className="text-sm font-semibold text-blue-800">
                          {t('contacts.referredBy')}
                        </h3>
                        <p className="text-sm text-blue-700">
                          <span className="font-medium">{editingContact.referrer.name} {editingContact.referrer.surname}</span>
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ) : null;
            })()}
            
            {/* Personal Info Section */}
            <div className="mb-2">
              <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2 mb-4">
                <UserCircleIcon className="h-5 w-5 text-gray-400" />
                {t('contacts.personalInfo')}
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Basic Info */}
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.name')}</label>
                  <div className="relative">
                    <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      name="name"
                      value={editForm.name}
                      onChange={handleEditFormChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      required
                      aria-label={t('contacts.name')}
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.surname')}</label>
                  <div className="relative">
                    <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      name="surname"
                      value={editForm.surname}
                      onChange={handleEditFormChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      required
                      aria-label={t('contacts.surname')}
                    />
                  </div>
                </div>
                <div>
                  <PhoneInput
                      value={editForm.phone}
                      onChange={handleEditFormChange}
                    name="phone"
                    label={t('contacts.phone')}
                    contactId={editingContact?.id}
                    otherPhone={editForm.secondaryPhone}
                    disabled={editingContact?._dataMasked || shouldDisableField(editingContact, user)}
                    />
                  {(editingContact?._dataMasked || shouldDisableField(editingContact, user)) && (
                    <p className="mt-1 text-sm text-amber-600 flex items-center gap-1">
                      <InformationCircleIcon className="h-4 w-4" />
                      {t('contacts.fieldDisabled')}
                    </p>
                  )}
                </div>
                <div>
                  <PhoneInput
                    value={editForm.secondaryPhone}
                    onChange={handleEditFormChange}
                    name="secondaryPhone"
                    label={`${t('contacts.secondaryPhone')} (${t('common.optional')})`}
                    placeholder={t('contacts.secondaryPhonePlaceholder')}
                    contactId={editingContact?.id}
                    otherPhone={editForm.phone}
                    disabled={editingContact?._dataMasked || shouldDisableField(editingContact, user)}
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.profession')}</label>
                  <div className="relative">
                    <BuildingOffice2Icon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      name="profession"
                      value={editForm.profession}
                      onChange={handleEditFormChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      aria-label={t('contacts.profession')}
                    />
                  </div>
                </div>
                {showExtendedFieldsInEdit && (
                  <div>
                    <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                      {t('users.personalId')} <span className="text-gray-400">({t('common.optional')})</span>
                    </label>
                    <div className="relative">
                      <HashtagIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                      <input
                        type="text"
                        name="personalId"
                        value={editForm.personalId || ''}
                        onChange={(e) => {
                          const value = e.target.value.toUpperCase();
                          setEditForm(prev => ({ ...prev, personalId: value }));
                        }}
                        className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                        pattern="^[A-Z][0-9]{8}[A-Z]$"
                        minLength={10}
                        maxLength={10}
                        placeholder={t('users.personalIdFormatHelper', { example: 'A12345678B' })}
                      />
                    </div>
                    <p className="mt-1 text-sm text-gray-500">{t('users.personalIdFormatHelper', { example: 'A12345678B' })}</p>
                  </div>
                )}
                {showExtendedFieldsInEdit && (
                  <div>
                    <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                      {t('users.birthday')} <span className="text-gray-400">({t('common.optional')})</span>
                    </label>
                    <div className="relative">
                      <CalendarIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                      <input
                        type="date"
                        name="birthday"
                        value={editForm.birthday || ''}
                        onChange={(e) => setEditForm(prev => ({ ...prev, birthday: e.target.value }))}
                        className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                      />
                    </div>
                  </div>
                )}
                {showExtendedFieldsInEdit && (
                  <div>
                    <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                      {t('users.email')} <span className="text-gray-400">({t('common.optional')})</span>
                    </label>
                    <div className="relative">
                      <EnvelopeIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                      <input
                        type="email"
                        name="email"
                        value={editForm.email || ''}
                        onChange={(e) => setEditForm(prev => ({ ...prev, email: e.target.value }))}
                        className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                        placeholder="example@email.com"
                      />
                    </div>
                  </div>
                )}
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('contacts.notes')} <span className="text-gray-400">({t('common.optional')})</span>
                  </label>
                  <div className="relative">
                    <DocumentTextIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <textarea
                      name="notes"
                      value={editForm.notes || ''}
                      onChange={handleEditFormChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none"
                      rows="3"
                      placeholder={t('contacts.notesPlaceholder')}
                      aria-label={t('contacts.notes')}
                    />
                  </div>
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                    {t('contacts.gifts')} <span className="text-gray-400">({t('common.optional')})</span>
                  </label>
                  <div className="relative">
                    <TagIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                    <textarea
                      name="gifts"
                      value={editForm.gifts || ''}
                      onChange={handleEditFormChange}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none"
                      rows="3"
                      placeholder={t('contacts.giftsPlaceholder')}
                      aria-label={t('contacts.gifts')}
                    />
                  </div>
                </div>

              </div>
            </div>
            <div className="border-b border-gray-100 my-4" />
            {/* Address Section */}
            <div className="mb-2">
              <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2 mb-4">
                <MapPinIcon className="h-5 w-5 text-gray-400" />
                {t('contacts.addressInfo') || t('contacts.address')}
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>{t('contacts.address')}</label>
                  <div className="relative">
                    <MapPinIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                    <input
                      type="text"
                      name="address"
                      value={editForm.address || ''}
                      onChange={e => {
                        setEditForm(prev => ({ ...prev, address: e.target.value, addressLat: '', addressLng: '' }));
                      }}
                      onBlur={async (e) => {
                        if (!editForm.addressLat || !editForm.addressLng) {
                          const geo = await geocodeAddress(e.target.value);
                          if (geo) {
                            setEditForm(prev => ({ ...prev, addressLat: geo.lat, addressLng: geo.lng, address: geo.displayName || prev.address }));
                            toast.success(t('contacts.locationSet'));
                          } else {
                            toast.warn(t('contacts.geocodeNotFound', 'Could not find location for this address.'));
                          }
                        }
                      }}
                      className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm disabled:bg-gray-100 disabled:cursor-not-allowed"
                      required
                      disabled={editingContact?._dataMasked || shouldDisableField(editingContact, user)}
                      title={(editingContact?._dataMasked || shouldDisableField(editingContact, user)) ? t('contacts.fieldDisabled') : ''}
                    />
                  </div>
                  {(editingContact?._dataMasked || shouldDisableField(editingContact, user)) && (
                    <p className="mt-1 text-sm text-amber-600 flex items-center gap-1">
                      <InformationCircleIcon className="h-4 w-4" />
                      {t('contacts.fieldDisabled')}
                    </p>
                  )}
                </div>
                <div className="md:col-span-2 flex flex-col sm:flex-row gap-2">
                  <button type="button" className="btn btn-secondary flex-1 flex items-center justify-center gap-1 px-2 py-2 text-sm" onClick={() => {
                    setEditMapInit([
                      editForm.addressLat || 41.3275,
                      editForm.addressLng || 19.8187
                    ]);
                    setShowEditMap(true);
                  }}><MapPinIcon className="h-4 w-4" />{t('contacts.pickFromMap')}</button>
                  <button 
                    type="button" 
                    className="btn btn-secondary flex-1 flex items-center justify-center gap-1 px-2 py-2 text-sm disabled:opacity-50" 
                    onClick={handleEditUseMyLocation}
                    disabled={editGPS.isLocating}
                  >
                    {editGPS.isLocating ? (
                      <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                    ) : (
                      <MapIcon className="h-4 w-4" />
                    )}
                    {editGPS.isLocating ? t('common.loading') : t('contacts.useMyLocation')}
                  </button>
                </div>
              </div>
            </div>
            {shouldShowSignatureSection(editingContact) && (
              <>
                <div className="border-b border-gray-100 my-4" />
                {/* Signature Section */}
                <div className="mb-2">
                  <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2 mb-4">
                    <span className="h-5 w-5 text-gray-400">✍️</span>
                    {t('contacts.signature')}
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="md:col-span-2">
                      <label className="block text-sm font-semibold mb-1" style={{ color: '#253988' }}>
                        {t('contacts.signature')}
                      </label>
                      <SignaturePad
                        ref={editSignaturePadRef} // Assign the ref here
                        key={`${editingContact?.id || 'new'}-${signaturePadKeySuffix}`} // Modified key
                        onSave={(value) => {
                          setEditForm({ ...editForm, signature: value });
                          setSignatureTouched(true);
                        }}
                        value={editForm.signature}
                      />
                    </div>
                  </div>
                </div>
              </>
            )}
            {/* Contact Outcome Section - Only show when meeting is not scheduled */}
            {!editForm.contacted && (
              <>
                <div className="border-b border-gray-100 my-6" />
                <div className="mb-6">
                  <div className="bg-white rounded-xl border border-gray-200 shadow-xs overflow-hidden">
                    <div className="bg-linear-to-r from-amber-50 to-orange-50 px-6 py-4 border-b border-amber-100">
                      <div className="flex items-center space-x-3">
                        <div className="shrink-0">
                          <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center">
                            <PhoneIcon className="h-6 w-6 text-amber-600" />
                          </div>
                        </div>
                        <div>
                          <h3 className="text-lg font-semibold text-gray-900">{t('contactOutcome.title', 'Contact Outcome')}</h3>
                          <p className="text-sm text-gray-600">{t('contactOutcome.subtitle', 'Record the outcome of your contact attempt')}</p>
                        </div>
                      </div>
                    </div>
                    
                    <div className="p-6">
                      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
                        {[
                          { value: 'no_answer', icon: 'PhoneXMarkIcon', color: 'gray' },
                          { value: 'busy', icon: 'ClockIcon', color: 'blue' },
                          { value: 'not_interested', icon: 'XCircleIcon', color: 'red' },
                          { value: 'callback_requested', icon: 'PhoneArrowDownLeftIcon', color: 'green' },
                          { value: 'wrong_number', icon: 'ExclamationTriangleIcon', color: 'yellow' },
                          { value: 'disconnected', icon: 'SignalSlashIcon', color: 'gray' },
                          { value: 'voicemail', icon: 'SpeakerWaveIcon', color: 'purple' },
                          { value: 'other', icon: 'EllipsisHorizontalIcon', color: 'slate' }
                        ].map((outcome) => (
                          <button
                            key={outcome.value}
                            type="button"
                            onClick={() => {
                              const newValue = editForm.contactAttemptReason === outcome.value ? null : outcome.value;
                              setEditForm(prev => ({
                                ...prev,
                                contactAttemptReason: newValue,
                                contactAttemptOtherReason: (!newValue || newValue !== 'other') ? '' : prev.contactAttemptOtherReason
                              }));
                            }}
                            className={`relative p-4 rounded-lg border-2 transition-all duration-200 ${
                              editForm.contactAttemptReason === outcome.value
                                ? `border-${outcome.color}-200 bg-${outcome.color}-50 text-${outcome.color}-700`
                                : 'border-gray-200 bg-gray-50 text-gray-500 hover:border-gray-300 hover:bg-white'
                            }`}
                          >
                            <div className="flex flex-col items-center space-y-2">
                              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                                editForm.contactAttemptReason === outcome.value 
                                  ? `bg-${outcome.color}-100` 
                                  : 'bg-gray-100'
                              }`}>
                                {outcome.icon === 'PhoneXMarkIcon' && <PhoneIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'ExclamationTriangleIcon' && <ExclamationTriangleIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'XCircleIcon' && <XCircleIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'ClockIcon' && <ClockIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'PhoneArrowDownLeftIcon' && <PhoneIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'SignalSlashIcon' && <NoSymbolIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'SpeakerWaveIcon' && <SpeakerWaveIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                                {outcome.icon === 'EllipsisHorizontalIcon' && <EllipsisHorizontalIcon className={`h-5 w-5 ${editForm.contactAttemptReason === outcome.value ? `text-${outcome.color}-600` : 'text-gray-400'}`} />}
                              </div>
                              <span className="text-sm font-medium text-center leading-tight">
                                {t(`contactOutcome.${outcome.value}`, outcome.value.replace('_', ' '))}
                              </span>
                            </div>
                            {editForm.contactAttemptReason === outcome.value && (
                              <div className="absolute top-2 right-2">
                                <CheckIcon className={`h-4 w-4 text-${outcome.color}-600`} />
                              </div>
                            )}
                          </button>
                        ))}
                      </div>
                      
                      {/* Show textarea when "other" is selected */}
                      {editForm.contactAttemptReason === 'other' && (
                        <div className="border-t border-gray-200 pt-6">
                          <label className="block text-sm font-semibold mb-3 text-gray-700">
                            <DocumentTextIcon className="h-4 w-4 inline mr-2" />
                            {t('contactOutcome.otherDescription', 'Please specify the reason')}
                          </label>
                          <textarea
                            name="contactAttemptOtherReason"
                            value={editForm.contactAttemptOtherReason || ''}
                            onChange={handleEditFormChange}
                            rows={3}
                            maxLength={500}
                            placeholder={t('contactOutcome.otherPlaceholder', 'Enter custom reason...')}
                            className="block w-full pl-3 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none"
                          />
                          <div className="mt-2 text-sm text-gray-500 text-right">
                            {(editForm.contactAttemptOtherReason || '').length}/500 {t('common.characters')}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </>
            )}

            {/* RBO Section - Only visible to admin/owner users */}
            {canManageProductStatusInEdit && (
              <>
                <div className="border-b border-gray-100 my-6" />
                <div className="mb-6">
                  <div className="bg-white rounded-xl border border-gray-200 shadow-xs overflow-hidden">
                    <div className="bg-linear-to-r from-blue-50 to-indigo-50 px-6 py-4 border-b border-blue-100">
                      <div className="flex items-center space-x-3">
                        <div className="shrink-0">
                          <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                            <ShoppingBagIcon className="h-6 w-6 text-blue-600" />
                          </div>
                        </div>
                        <div>
                          <h3 className="text-lg font-semibold text-gray-900">{t('contacts.rboSection', 'Sales Information')}</h3>
                          <p className="text-sm text-gray-600">{t('contacts.rboSubtitle', 'Manage sales and product information')}</p>
                        </div>
                      </div>
                    </div>
                    
                    <div className="p-6">
                      {/* Multi-Product Management Section */}
                      <div className="mb-6">
                        <div className="mb-4">
                          {/* Title on its own row */}
                          <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2 mb-3">
                            <ShoppingBagIcon className="h-5 w-5 text-blue-600" />
                            {t('contacts.productManagement')}
                          </h3>
                          
                          {/* Buttons together on their own row, responsive layout */}
                          <div className="flex flex-col sm:flex-row gap-2">
                            <button
                              type="button"
                              onClick={() => {
                                // Ensure products are loaded before opening modal
                                if (products.length === 0) {
                                  loadProducts();
                                }
                                setProductModalType('reservation');
                                setEditingProduct(null);
                                setShowAddProductModal(true);
                              }}
                              className="flex-1 sm:flex-none inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-orange-700 bg-orange-50 hover:bg-orange-100 border border-orange-200 rounded-lg transition-colors"
                            >
                              <BookmarkIcon className="h-4 w-4 mr-1" />
                              {t('contacts.addReservation')}
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                // Ensure products are loaded before opening modal
                                if (products.length === 0) {
                                  loadProducts();
                                }
                                setProductModalType('purchase');
                                setEditingProduct(null);
                                setShowAddProductModal(true);
                              }}
                              className="flex-1 sm:flex-none inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-blue-700 bg-blue-50 hover:bg-blue-100 border border-blue-200 rounded-lg transition-colors"
                            >
                              <ShoppingBagIcon className="h-4 w-4 mr-1" />
                              {t('contacts.addPurchase')}
                            </button>
                          </div>
                        </div>

                        {isLoadingProducts ? (
                          <div className="flex justify-center py-8">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                          </div>
                        ) : user.role === 'owner' ? (
                          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            {/* Purchases Section */}
                            <div>
                              <h4 className="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                                <ShoppingBagIcon className="h-4 w-4 text-blue-600" />
                                {t('contacts.purchases')} ({contactProducts.purchases.length})
                              </h4>
                              <div className="space-y-3 max-h-64 overflow-y-auto">
                                {contactProducts.purchases.length === 0 ? (
                                  <div className="text-sm text-gray-500 italic p-4 bg-gray-50 rounded-lg text-center">
                                    {t('contacts.noPurchases')}
                                  </div>
                                ) : (
                                  contactProducts.purchases.map((purchase) => (
                                    <div key={purchase.id} className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                                      <div className="flex justify-between items-start mb-2">
                                        <div className="flex-1">
                                          <p className="font-medium text-blue-900">{purchase.Product?.name || 'Unknown Product'}</p>
                                          <p className="text-sm text-blue-700">Serial: {purchase.serialNumber}</p>
                                          <p className="text-sm text-blue-600">
                                            {formatAlbanianDate(new Date(purchase.purchaseDate))} • {purchase.amount} {purchase.currency}
                                          </p>
                                          {purchase.Seller && (
                                            <p className="text-sm text-blue-500">
                                              {t('contacts.rboSeller')}: {purchase.Seller.firstName} {purchase.Seller.lastName}
                                            </p>
                                          )}
                                        </div>
                                        <div className="flex gap-1">
                                          <button
                                            type="button"
                                            onClick={() => handleDownloadPurchasePdf(purchase)}
                                            disabled={downloadingPdfPurchaseId === purchase.id}
                                            className="p-1 text-green-600 hover:bg-green-100 rounded disabled:opacity-50"
                                            title={t('contacts.downloadRboPdf')}
                                          >
                                            {downloadingPdfPurchaseId === purchase.id ? (
                                              <div className="w-4 h-4 border-2 border-green-600 border-t-transparent rounded-full animate-spin"></div>
                                            ) : (
                                              <DocumentArrowDownIcon className="h-4 w-4" />
                                            )}
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => handleOpenRboHistoryModal(purchase)}
                                            className="p-1 text-purple-600 hover:bg-purple-100 rounded"
                                            title={t('contacts.viewReplacementHistory')}
                                          >
                                            <WrenchScrewdriverIcon className="h-4 w-4" />
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => {
                                              // Ensure products are loaded before opening modal
                                              if (products.length === 0) {
                                                loadProducts();
                                              }
                                              setEditingProduct({ ...purchase, type: 'purchase' });
                                              setProductModalType('purchase');
                                              setShowAddProductModal(true);
                                            }}
                                            className="p-1 text-blue-600 hover:bg-blue-100 rounded"
                                          >
                                            <PencilIcon className="h-4 w-4" />
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => deleteProduct(purchase.id, 'purchase')}
                                            className="p-1 text-red-600 hover:bg-red-100 rounded"
                                          >
                                            <TrashIcon className="h-4 w-4" />
                                          </button>
                                        </div>
                                      </div>
                                    </div>
                                  ))
                                )}
                              </div>
                            </div>

                            {/* Reservations Section */}
                            <div>
                              <h4 className="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                                <BookmarkIcon className="h-4 w-4 text-orange-600" />
                                {t('contacts.reservations')} ({contactProducts.reservations.length})
                              </h4>
                              <div className="space-y-3 max-h-64 overflow-y-auto">
                                {contactProducts.reservations.length === 0 ? (
                                  <div className="text-sm text-gray-500 italic p-4 bg-gray-50 rounded-lg text-center">
                                    {t('contacts.noReservations')}
                                  </div>
                                ) : (
                                  contactProducts.reservations.map((reservation) => (
                                    <div key={reservation.id} className="p-3 bg-orange-50 border border-orange-200 rounded-lg">
                                      <div className="flex justify-between items-start mb-2">
                                        <div className="flex-1">
                                          <p className="font-medium text-orange-900">{reservation.Product?.name || 'Unknown Product'}</p>
                                          <p className="text-sm text-orange-600">
                                            {formatAlbanianDate(new Date(reservation.reservationDate))} • {reservation.amount} {reservation.currency}
                                          </p>
                                          {reservation.Seller && (
                                            <p className="text-sm text-orange-500">
                                              {t('contacts.rboSeller')}: {reservation.Seller.firstName} {reservation.Seller.lastName}
                                            </p>
                                          )}
                                        </div>
                                        <div className="flex gap-1">
                                          <button
                                            type="button"
                                            onClick={() => convertReservationToPurchase(reservation.id)}
                                            className="p-1 text-green-600 hover:bg-green-100 rounded"
                                            title={t('contacts.convertToRBO')}
                                          >
                                            <ArrowRightIcon className="h-4 w-4" />
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => {
                                              // Ensure products are loaded before opening modal
                                              if (products.length === 0) {
                                                loadProducts();
                                              }
                                              setEditingProduct({ ...reservation, type: 'reservation' });
                                              setProductModalType('reservation');
                                              setShowAddProductModal(true);
                                            }}
                                            className="p-1 text-orange-600 hover:bg-orange-100 rounded"
                                          >
                                            <PencilIcon className="h-4 w-4" />
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => deleteProduct(reservation.id, 'reservation')}
                                            className="p-1 text-red-600 hover:bg-red-100 rounded"
                                          >
                                            <TrashIcon className="h-4 w-4" />
                                          </button>
                                        </div>
                                      </div>
                                    </div>
                                  ))
                                )}
                              </div>
                            </div>
                          </div>
                        ) : (
                          <div className="text-center py-8">
                            <div className="inline-flex items-center justify-center w-16 h-16 bg-amber-100 rounded-full mb-4">
                              <ShieldCheckIcon className="h-8 w-8 text-amber-600" />
                            </div>
                            <h4 className="text-lg font-medium text-gray-900 mb-2">
                              {t('contacts.dataProtected', 'Data Protected')}
                            </h4>
                            <p className="text-sm text-gray-600 max-w-md mx-auto">
                              {t('contacts.dataProtectedInfo', 'Individual purchase and reservation details are protected. Only the owner can view this information.')}
                            </p>
                          </div>
                        )}
                      </div>

                    </div>
                  </div>
                </div>
              </>
            )}

            {/* Meeting Status Section - Hidden for agents */}
            {!isAgent && (
              <>
                <div className="border-b border-gray-100 my-6" />
                <div className="mb-6">
                  <div className="bg-white rounded-xl border border-gray-200 shadow-xs overflow-hidden">
                    <div className="bg-linear-to-r from-purple-50 to-indigo-50 px-6 py-4 border-b border-purple-100">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="shrink-0">
                            <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                              <CalendarIcon className="h-6 w-6 text-purple-600" />
                            </div>
                          </div>
                          <div>
                            <h3 className="text-lg font-semibold text-gray-900">{t('contacts.meetingStatus.title', 'Meeting Status')}</h3>
                            <p className="text-sm text-gray-600">{t('contacts.meetingStatus.subtitle', 'Manage meeting scheduling status')}</p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => {
                            setHistoryContact(editingContact);
                            setShowMeetingHistoryModal(true);
                          }}
                          className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-purple-700 bg-purple-50 hover:bg-purple-100 rounded-lg border border-purple-200 hover:border-purple-300 transition-all duration-200 shadow-sm hover:shadow"
                          title={t('meetings.viewHistory')}
                        >
                          <ClockIcon className="size-5" />
                          <span className="hidden sm:inline">{t('meetings.viewHistory')}</span>
                        </button>
                      </div>
                    </div>
                    
                    <div className="p-6">
                      
                      <div className="grid grid-cols-2 gap-4 mb-6">
                        <button
                          type="button"
                          onClick={() => handleEditFormChange({ target: { name: 'contacted', type: 'checkbox', checked: false } })}
                          className={`relative p-4 rounded-lg border-2 transition-all duration-200 ${
                            !editForm.contacted 
                              ? 'border-gray-300 bg-gray-50 text-gray-700' 
                              : 'border-gray-200 bg-gray-50 text-gray-500 hover:border-gray-300'
                          }`}
                        >
                          <div className="flex flex-col items-center space-y-2">
                            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                              !editForm.contacted ? 'bg-gray-100' : 'bg-gray-100'
                            }`}>
                              <XCircleIcon className={`h-5 w-5 ${!editForm.contacted ? 'text-gray-600' : 'text-gray-400'}`} />
                            </div>
                            <span className="text-sm font-medium">{t('contacts.meetingStatus.notScheduled', 'Not Scheduled')}</span>
                          </div>
                          {!editForm.contacted && (
                            <div className="absolute top-2 right-2">
                              <CheckIcon className="h-4 w-4 text-gray-600" />
                            </div>
                          )}
                        </button>
                        
                        <button
                          type="button"
                          onClick={() => handleEditFormChange({ target: { name: 'contacted', type: 'checkbox', checked: true } })}
                          className={`relative p-4 rounded-lg border-2 transition-all duration-200 ${
                            editForm.contacted 
                              ? 'border-purple-200 bg-purple-50 text-purple-700' 
                              : 'border-gray-200 bg-gray-50 text-gray-500 hover:border-gray-300'
                          }`}
                        >
                          <div className="flex flex-col items-center space-y-2">
                            <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                              editForm.contacted ? 'bg-purple-100' : 'bg-gray-100'
                            }`}>
                              <CalendarIcon className={`h-5 w-5 ${editForm.contacted ? 'text-purple-600' : 'text-gray-400'}`} />
                            </div>
                            <span className="text-sm font-medium">{t('contacts.meetingStatus.scheduled', 'Scheduled')}</span>
                          </div>
                          {editForm.contacted && (
                            <div className="absolute top-2 right-2">
                              <CheckIcon className="h-4 w-4 text-purple-600" />
                            </div>
                          )}
                        </button>
                      </div>
                    </div>

                      {/* Meeting Details (only shown when meeting is scheduled) */}
                      {editForm.contacted && (
                        <div className="border-t border-gray-200 p-6">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          {/* Only show meetingStatus (response) if meetingDateTime exists and is in the past */}
                          {editForm.meetingDateTime && isPast(editForm.meetingDateTime) && (
                            <div className="md:col-span-2">
                              <label className="block text-sm font-semibold mb-2 text-gray-700">
                                <CheckIcon className="h-4 w-4 inline mr-1" />
                                {t('contacts.management.response.title')} <span className="text-red-500">*</span>
                              </label>
                              <div className="relative">
                                <CheckIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                                <select
                                  name="response"
                                  value={editForm.response || ''}
                                  onChange={e => setEditForm(prev => ({ ...prev, response: e.target.value }))}
                                  className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm bg-white"
                                  required
                                >
                                  <option value="">{t('contacts.management.response.null')}</option>
                                  <option value="held">{t('contacts.management.meetingStatus.held')}</option>
                                  <option value="reschedule">{t('contacts.management.meetingStatus.reschedule')}</option>
                                  <option value="failed">{t('contacts.management.meetingStatus.failed')}</option>
                                  <option value="do_not_contact">{t('contacts.management.meetingStatus.do_not_contact')}</option>
                                </select>
                              </div>
                            </div>
                          )}
                          
                          {/* Archive Status Indicator - Show when meeting is "held" */}
                          {editForm.response === 'held' && archiveStatus && (
                            <div className="md:col-span-2">
                              <div className={`rounded-xl border-2 p-4 sm:p-5 transition-all duration-300 ${
                                archiveStatus.isReadyForArchiving 
                                  ? 'border-green-200 bg-green-50' 
                                  : 'border-blue-200 bg-blue-50'
                              }`}>
                                <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
                                  <div className="flex-1">
                                    <div className="flex items-center gap-3 mb-2">
                                      <div className={`shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${
                                        archiveStatus.isReadyForArchiving 
                                          ? 'bg-green-100' 
                                          : 'bg-blue-100'
                                      }`}>
                                        <ClockIcon className={`h-5 w-5 ${
                                          archiveStatus.isReadyForArchiving 
                                            ? 'text-green-600' 
                                            : 'text-blue-600'
                                        }`} />
                                      </div>
                                      <div>
                                        <h4 className={`text-sm font-semibold ${
                                          archiveStatus.isReadyForArchiving 
                                            ? 'text-green-900' 
                                            : 'text-blue-900'
                                        }`}>
                                          {archiveStatus.isReadyForArchiving 
                                            ? t('meetings.archive.readyToArchive') 
                                            : t('meetings.archive.willArchiveIn')}
                                        </h4>
                                        <p className={`text-sm ${
                                          archiveStatus.isReadyForArchiving 
                                            ? 'text-green-700' 
                                            : 'text-blue-700'
                                        }`}>
                                          {archiveStatus.isReadyForArchiving 
                                            ? t('meetings.archive.autoArchiveIn', { time: t('meetings.archive.readyToArchive') })
                                            : (() => {
                                                const timeInfo = meetingArchiveApi.formatRemainingTime(archiveStatus.daysUntilArchiving);
                                                if (timeInfo && timeInfo.months > 0) {
                                                  return t('meetings.archive.monthsRemaining', { months: timeInfo.months, days: timeInfo.days });
                                                } else if (timeInfo) {
                                                  return t('meetings.archive.daysRemaining', { days: timeInfo.totalDays });
                                                }
                                                return '';
                                              })()
                                          }
                                        </p>
                                      </div>
                                    </div>
                                    {archiveStatus.meetingCompletedAt && (
                                      <p className={`text-xs mt-2 ${
                                        archiveStatus.isReadyForArchiving 
                                          ? 'text-green-600' 
                                          : 'text-blue-600'
                                      }`}>
                                        {t('meetings.archive.completed')}: {formatAlbanianDateTime(archiveStatus.meetingCompletedAt)}
                                      </p>
                                    )}
                                  </div>
                                  
                                  {archiveStatus.canArchiveManually && (
                                    <button
                                      type="button"
                                      onClick={handleArchiveMeeting}
                                      disabled={archivingMeeting}
                                      className={`w-full sm:w-auto shrink-0 inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium rounded-lg transition-all duration-200 shadow-sm hover:shadow ${
                                        archivingMeeting 
                                          ? 'bg-gray-100 text-gray-400 cursor-not-allowed' 
                                          : 'bg-orange-600 hover:bg-orange-700 text-white active:scale-95'
                                      }`}
                                    >
                                      {archivingMeeting ? (
                                        <>
                                          <div className="animate-spin rounded-full h-4 w-4 border-2 border-gray-300 border-t-transparent" />
                                          <span>{t('common.loading')}</span>
                                        </>
                                      ) : (
                                        <>
                                          <DocumentArrowDownIcon className="h-5 w-5" />
                                          <span>{t('meetings.archive.archiveNow')}</span>
                                        </>
                                      )}
                                    </button>
                                  )}
                                </div>
                              </div>
                            </div>
                          )}

                          {editForm.response !== 'do_not_contact' && (
                            <>
                              <div>
                                <label className="block text-sm font-semibold mb-2 text-gray-700">
                                  <ClockIcon className="h-4 w-4 inline mr-1" />
                                  {t('contacts.management.meetingDateTime')}
                                </label>
                                <div className="relative">
                                  <ClockIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                                  <input
                                    type="datetime-local"
                                    name="meetingDateTime"
                                    value={editForm.meetingDateTime || ''}
                                    onChange={handleEditFormChange}
                                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm"
                                  />
                                </div>
                              </div>
                              
                              <div>
                                <label className="block text-sm font-semibold mb-2 text-gray-700">
                                  <UserIcon className="h-4 w-4 inline mr-1" />
                                  {t('contacts.management.assignedAgent')}
                                </label>
                                <div className="relative">
                                  <UserIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                                  <select
                                    name="assignedAgentId"
                                    value={editForm.assignedAgentId || ''}
                                    onChange={handleEditFormChange}
                                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm bg-white"
                                  >
                                    <option value="">{t('common.select')}</option>
                                    {allUsers.map(user => {
                                      const wasUsedBefore = previousMeetingUsers.usedAgentIds?.includes(user.id);
                                      return (
                                        <option 
                                          key={user.id} 
                                          value={user.id}
                                          disabled={wasUsedBefore}
                                          className={wasUsedBefore ? 'text-gray-400 bg-gray-100' : ''}
                                        >
                                          {user.firstName} {user.lastName} {wasUsedBefore ? `(${t('meetings.usedInPreviousMeeting')})` : ''}
                                        </option>
                                      );
                                    })}
                                  </select>
                                </div>
                              </div>
                              
                              <div>
                                <label className="block text-sm font-semibold mb-2 text-gray-700">
                                  <BellIcon className="h-4 w-4 inline mr-1" />
                                  {t('contacts.management.notifiedUser')}
                                </label>
                                <div className="relative">
                                  <BellIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                                  <select
                                    name="notifiedUserId"
                                    value={editForm.notifiedUserId || ''}
                                    onChange={handleEditFormChange}
                                    className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm bg-white"
                                  >
                                    <option value="">{t('common.select')}</option>
                                    {allUsers.map(user => {
                                      const wasUsedBefore = previousMeetingUsers.usedNotifiedIds?.includes(user.id);
                                      return (
                                        <option 
                                          key={user.id} 
                                          value={user.id}
                                          disabled={wasUsedBefore}
                                          className={wasUsedBefore ? 'text-gray-400 bg-gray-100' : ''}
                                        >
                                          {user.firstName} {user.lastName} {wasUsedBefore ? `(${t('meetings.usedInPreviousMeeting')})` : ''}
                                        </option>
                                      );
                                    })}
                                  </select>
                                </div>
                              </div>
                            </>
                          )}

                          <div className="md:col-span-2">
                            <label className="block text-sm font-semibold mb-2 text-gray-700">
                              <DocumentTextIcon className="h-4 w-4 inline mr-1" />
                              {t('contacts.meetingNotes')}
                            </label>
                            <div className="relative">
                              <DocumentTextIcon className="absolute left-3 top-3 h-5 w-5 text-gray-400" />
                              <textarea
                                name="meetingNotes"
                                value={editForm.meetingNotes || ''}
                                onChange={handleEditFormChange}
                                rows={3}
                                className="block w-full pl-9 pr-3 py-2 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-aura-blue focus:border-transparent text-sm resize-none bg-white"
                                placeholder={t('contacts.meetingNotesPlaceholder')}
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                    
                    {/* Express Meeting Section */}
                    <div className="pb-6 pl-6 pr-6">
                    <div className="pt-6 border-t border-gray-200">
                      <div className="flex items-start gap-3">
                        <input
                          type="checkbox"
                          id="editIsExpress"
                          name="isExpress"
                          checked={editForm.isExpress || false}
                          onChange={handleEditFormChange}
                          className="mt-1 h-4 w-4 text-green-600 bg-gray-100 border-gray-300 rounded focus:ring-green-500 focus:ring-2"
                        />
                        <label htmlFor="editIsExpress" className="flex-1 cursor-pointer">
                          <div className="flex items-center gap-2 mb-1">
                            <CalendarIcon className="h-5 w-5 text-green-600" />
                            <span className="text-sm font-semibold text-gray-700">
                              {t('contacts.expressMeeting', 'Express Meeting')}
                            </span>
                          </div>
                          <p className="text-xs text-gray-500 leading-relaxed">
                            {t('contacts.expressMeetingDesc', 'This was an in-person meeting that already happened')}
                          </p>
                        </label>
                      </div>
                    </div>
                    </div>
                  </div>
                </div>
              </>
            )}

            <div className="w-full flex justify-end gap-2 mt-8 pt-4 border-t border-gray-100">
              <button 
                type="button" 
                disabled={isSaving}
                className="px-6 py-2 rounded font-bold text-base text-[#253988] border border-[#253988] bg-white hover:bg-[#253988]/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" 
                onClick={cancelEdit}
              >
                {t('common.cancel')}
              </button>
              <button 
                type="submit" 
                disabled={isSaving}
                className="px-6 py-2 rounded font-bold text-base text-white flex items-center gap-2 hover:bg-[#253988]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed" 
                style={{ background: '#253988' }}
              >
                {isSaving ? (
                  <>
                    <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                    {t('common.saving')}
                  </>
                ) : (
                  <>
                    <CheckIcon className="h-5 w-5" />
                    {t('common.save')}
                  </>
                )}
              </button>
            </div>
          </form>
        </Modal>
      )}

      {/* Product Add/Edit Modal */}
      {showAddProductModal && (
        <Modal
          isOpen={showAddProductModal}
          onClose={() => {
            setShowAddProductModal(false);
            setEditingProduct(null);
          }}
          title={editingProduct 
            ? t(`contacts.edit${productModalType === 'purchase' ? 'Purchase' : 'Reservation'}`)
            : t(`contacts.add${productModalType === 'purchase' ? 'Purchase' : 'Reservation'}`)
          }
          size="lg"
        >
          <ProductForm
            type={productModalType}
            editingProduct={editingProduct}
            products={products}
            users={allUsers}
            isSubmitting={isAddingProduct}
            onSubmit={editingProduct ? updateProduct : addProduct}
            onCancel={() => {
              setShowAddProductModal(false);
              setEditingProduct(null);
            }}
          />
        </Modal>
      )}

      {/* Add the new modal for referrals */}
      {showAddReferralsModal && selectedContactForReferrals && (
        <Modal
          isOpen={showAddReferralsModal}
          onClose={() => {
            setShowAddReferralsModal(false);
            setSelectedContactForReferrals(null);
          }}
          title={
            <div className="flex items-center gap-2">
              <UsersIcon className="h-5 w-5" aria-hidden="true" />
              {t('contacts.addReferral')}
              <span className="ml-2 text-sm opacity-75">
                {t('contacts.referredBy')}: {selectedContactForReferrals.name} {selectedContactForReferrals.surname}
              </span>
            </div>
          }
          size="xl"
        >
          <ReferralForm
            onSave={handleAddReferral}
            onCancel={() => {
              setShowAddReferralsModal(false);
              setSelectedContactForReferrals(null);
            }}
          />
        </Modal>
      )}

      {/* Comprehensive Referrals Modal */}
      {showReferralsModal && selectedContactForReferralsView && (
        <Modal
          isOpen={showReferralsModal}
          onClose={() => {
            setShowReferralsModal(false);
            setSelectedContactForReferralsView(null);
            setContactReferrals([]);
          }}
          title={
            <div className="flex items-center gap-2">
              <UserGroupIcon className="h-5 w-5" aria-hidden="true" />
              {t('contacts.viewReferrals')}
            </div>
          }
          size="lg"
        >
          <div className="space-y-6">
            {/* Contact Info Header */}
            <div className="bg-white p-6 rounded-lg border border-gray-200 shadow-xs">
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
                  <UserIcon className="h-6 w-6 text-gray-600" />
                </div>
                <div className="flex-1">
                  <div className="text-lg font-semibold text-gray-900">
                    {selectedContactForReferralsView.name} {selectedContactForReferralsView.surname}
                  </div>
                  {selectedContactForReferralsView.phone && (
                    <div className="flex items-center gap-2 text-sm text-gray-600 mt-1">
                      <PhoneIcon className="h-4 w-4" />
                      <span>{selectedContactForReferralsView.phone}</span>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Section 1: Who referred this contact (if applicable) */}
            {(selectedContactForReferralsView.referredByContactId || selectedContactForReferralsView.referrer) && (() => {
              let referrer = null;
              let referralDate = null;

              if (selectedContactForReferralsView.referrer) {
                referrer = selectedContactForReferralsView.referrer;
                referralDate = selectedContactForReferralsView.createdAt;
              } else if (selectedContactForReferralsView.referredByContactId) {
                referrer = contacts.find(c => c.id === selectedContactForReferralsView.referredByContactId);
                referralDate = selectedContactForReferralsView.createdAt;
              }

              return referrer ? (
                <div className="bg-white p-6 rounded-lg border-l-4 border-l-blue-500 border border-gray-200 shadow-xs">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                        <UserGroupIcon className="h-5 w-5 text-blue-600" />
                      </div>
                      <div>
                        <div className="text-sm font-medium text-blue-600 uppercase tracking-wide mb-1">{t('contacts.referredBy')}</div>
                        <div className="text-lg font-semibold text-gray-900">
                          {referrer.name} {referrer.surname}
                        </div>
                        <div className="flex flex-wrap gap-4 mt-3 text-sm text-gray-600">
                          {referrer.phone && (
                            <div className="flex items-center gap-1">
                              <PhoneIcon className="h-4 w-4" />
                              <span>{referrer.phone}</span>
                            </div>
                          )}
                          {referrer.address && (
                            <div className="flex items-center gap-1">
                              <MapPinIcon className="h-4 w-4" />
                              <span className="truncate max-w-32">{referrer.address}</span>
                            </div>
                          )}
                          {referralDate && (
                            <div className="flex items-center gap-1">
                              <CalendarIcon className="h-4 w-4" />
                              <span>{safeFormatDate(referralDate, {}, 'en-GB')}</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={async () => {
                        try {
                          const response = await offlineApi.getContact(referrer.id);
                          const fullReferrerContact = response.data;
                          
                          setShowReferralsModal(false);
                          setTimeout(() => {
                            startEdit(fullReferrerContact);
                            setShowEditModal(true);
                          }, 100);
                        } catch (error) {
                  
                          toast.error(t('contacts.errorContactNotFound'));
                        }
                      }}
                      className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-50 border border-gray-300 rounded-md hover:bg-gray-100 transition-colors"
                    >
                      <PencilIcon className="h-4 w-4" />
                      {t('common.edit')}
                    </button>
                  </div>
                </div>
              ) : null;
            })()}

            {/* Section 2: List of contacts this contact has referred */}
            {contactReferrals.length > 0 && (
              <div className="bg-white p-6 rounded-lg border border-gray-200 shadow-xs">
                <div className="flex items-center gap-3 mb-6">
                  <div className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center">
                    <UsersIcon className="h-5 w-5 text-gray-600" />
                  </div>
                  <div>
                    <div className="text-sm font-medium text-gray-600 uppercase tracking-wide">{t('contacts.hasReferred')}</div>
                    <div className="text-lg font-semibold text-gray-900">
                      {contactReferrals.length} {contactReferrals.length === 1 ? t('contacts.contact') : t('contacts.contacts')}
                    </div>
                  </div>
                </div>
                
                <div className="space-y-4 max-h-96 overflow-y-auto">
                  {contactReferrals.map((referral) => (
                    <div
                      key={referral.id}
                      onClick={() => handleReferralCardClick(referral)}
                      className="p-5 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 hover:border-gray-300 transition-all cursor-pointer group"
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex items-start gap-4 flex-1 min-w-0">
                          <div className="w-10 h-10 bg-white rounded-full flex items-center justify-center border border-gray-200 group-hover:border-gray-300 shrink-0">
                            <UserIcon className="h-5 w-5 text-gray-600" />
                          </div>
                          <div className="flex-1 min-w-0">
                            {/* Name and Phone */}
                            <div className="flex items-center gap-3 mb-2">
                              <div className="font-semibold text-gray-900">
                                {referral.name} {referral.surname}
                              </div>
                              {referral.phone && (
                                <div className="flex items-center gap-1 text-sm text-gray-600">
                                  <PhoneIcon className="h-3 w-3" />
                                  <span>{referral.phone}</span>
                                </div>
                              )}
                            </div>

                            {/* Status Badges Row */}
                            <div className="flex flex-wrap gap-2 mb-3">
                              {/* Status Badge */}
                              <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                getReferralStatusBadgeStyle(referral)
                              }`}>
                                {getReferralStatus(referral)}
                              </span>

                              {/* Contact Outcome Badge - matches main table styling */}
                              {referral.contactAttemptReason && (
                                <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                  referral.contactAttemptReason === 'no_answer' || referral.contactAttemptReason === 'disconnected' ? 'bg-gray-100 text-gray-700' :
                                  referral.contactAttemptReason === 'busy' ? 'bg-blue-100 text-blue-700' :
                                  referral.contactAttemptReason === 'not_interested' ? 'bg-red-100 text-red-700' :
                                  referral.contactAttemptReason === 'callback_requested' ? 'bg-green-100 text-green-700' :
                                  referral.contactAttemptReason === 'wrong_number' ? 'bg-yellow-100 text-yellow-700' :
                                  referral.contactAttemptReason === 'voicemail' ? 'bg-purple-100 text-purple-700' :
                                  referral.contactAttemptReason === 'other' ? 'bg-slate-100 text-slate-700' :
                                  'bg-gray-100 text-gray-700'
                                }`}>
                                  {t(`contactOutcome.${referral.contactAttemptReason}`, referral.contactAttemptReason.replace(/_/g, ' '))}
                                </span>
                              )}

                              {/* Meeting Status Badges */}
                              {/* Show meeting outcome if meeting is in the past */}
                              {referral.meetingDateTime && isPast(referral.meetingDateTime) && referral.meetingStatus && (
                                <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                  referral.meetingStatus === 'held' ? 'bg-green-100 text-green-800' :
                                  referral.meetingStatus === 'reschedule' ? 'bg-orange-100 text-orange-800' :
                                  referral.meetingStatus === 'failed' ? 'bg-purple-100 text-purple-800' :
                                  referral.meetingStatus === 'do_not_contact' ? 'bg-rose-200 text-rose-900' :
                                  'bg-gray-100 text-gray-600'
                                }`}>
                                  {referral.meetingStatus === 'held' && <FaceSmileIcon className="h-3 w-3 mr-1" />}
                                  {referral.meetingStatus === 'reschedule' && <FaceSmileIcon className="h-3 w-3 mr-1 transform rotate-180" />}
                                  {referral.meetingStatus === 'failed' && <FaceFrownIcon className="h-3 w-3 mr-1" />}
                                  {referral.meetingStatus === 'do_not_contact' && <XMarkIcon className="h-3 w-3 mr-1" />}
                                  {t(`contacts.management.meetingStatus.${referral.meetingStatus}`)}
                                </span>
                              )}
                              
                              {/* Show upcoming meeting if meeting is in the future */}
                              {referral.meetingDateTime && isFuture(referral.meetingDateTime) && (
                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                  <CalendarIcon className="h-3 w-3 mr-1" />
                                  {t('contacts.management.meeting.hasUpcoming')}
                                </span>
                              )}
                            </div>

                            {/* Details Grid */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm text-gray-600">
                              {/* Address */}
                              {referral.address && (
                                <div className="flex items-center gap-2">
                                  <MapPinIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <span className="truncate">{referral.address}</span>
                                </div>
                              )}

                              {/* Profession */}
                              {referral.profession && (
                                <div className="flex items-center gap-2">
                                  <BriefcaseIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <span className="truncate">{referral.profession}</span>
                                </div>
                              )}

                              {/* Meeting Information */}
                              {referral.meetingDateTime && (
                                <div className="flex items-center gap-2">
                                  <CalendarIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <div className="flex flex-col">
                                    <span className="font-medium">
                                      {formatAlbanianDate(referral.meetingDateTime)} {t('common.at')} {safeFormatTime(referral.meetingDateTime)}
                                    </span>
                                    <span className="text-xs text-gray-500">
                                      {isFuture(referral.meetingDateTime) ? t('contacts.upcomingMeeting', 'Upcoming meeting') : 
                                       isPast(referral.meetingDateTime) ? t('contacts.pastMeeting', 'Past meeting') : t('common.today', 'Today')}
                                    </span>
                                  </div>
                                </div>
                              )}

                              {/* Assigned Agent */}
                              {referral.assignedAgent && (
                                <div className="flex items-center gap-2">
                                  <UserCircleIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <div className="flex flex-col">
                                    <span className="truncate">{referral.assignedAgent.firstName} {referral.assignedAgent.lastName}</span>
                                    <span className="text-xs text-gray-500">{t('contacts.management.assignedAgent')}</span>
                                  </div>
                                </div>
                              )}

                              {/* RBO Amount */}
                              {getReferralStatus(referral) === 'RBO' && referral.rboAmount && (
                                <div className="flex items-center gap-2">
                                  <CurrencyDollarIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <div className="flex flex-col">
                                    <span className="font-medium">{referral.rboAmount} {referral.rboCurrency || 'EUR'}</span>
                                    <span className="text-xs text-gray-500">{t('contacts.rboPayment.amount')}</span>
                                  </div>
                                </div>
                              )}

                              {/* Meeting Scheduling Status */}
                              {!referral.meetingDateTime && referral.contacted && (
                                <div className="flex items-center gap-2">
                                  <CalendarIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                  <div className="flex flex-col">
                                    <span className="text-gray-600">{t('contacts.management.meeting.noUpcoming')}</span>
                                    <span className="text-xs text-gray-500">{t('contacts.management.contacted')}</span>
                                  </div>
                                </div>
                              )}

                              {/* Creation Date */}
                              <div className="flex items-center gap-2">
                                <ClockIcon className="h-4 w-4 text-gray-400 shrink-0" />
                                <span>{t('contacts.addedOn', 'Added on')} {formatAlbanianDate(referral.createdAt)}</span>
                              </div>
                            </div>

                            {/* Notes and Additional Information */}
                            {(referral.notes || referral.contactAttemptOtherReason) && (
                              <div className="mt-3 space-y-2">
                                {referral.notes && (
                                  <div className="p-3 bg-white rounded-md border border-gray-200">
                                    <div className="flex items-start gap-2">
                                      <DocumentTextIcon className="h-4 w-4 text-gray-400 shrink-0 mt-0.5" />
                                      <div>
                                        <span className="text-xs font-medium text-gray-500 uppercase tracking-wide">{t('contacts.notes')}</span>
                                        <p className="text-sm text-gray-700 mt-1">{referral.notes}</p>
                                      </div>
                                    </div>
                                  </div>
                                )}
                                
                                {referral.contactAttemptOtherReason && (
                                  <div className="p-3 bg-amber-50 rounded-md border border-amber-200">
                                    <div className="flex items-start gap-2">
                                      <InformationCircleIcon className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
                                      <div>
                                        <span className="text-xs font-medium text-amber-700 uppercase tracking-wide">{t('contactAttempt.otherReason.title')}</span>
                                        <p className="text-sm text-amber-800 mt-1">{referral.contactAttemptOtherReason}</p>
                                      </div>
                                    </div>
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                        <div className="shrink-0 ml-3">
                          <PencilIcon className="h-5 w-5 text-gray-400 group-hover:text-gray-600 transition-colors" />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Message when no referral activity */}
            {!selectedContactForReferralsView.referredByContactId && !selectedContactForReferralsView.referrer && contactReferrals.length === 0 && (
              <div className="bg-white p-8 rounded-lg border border-gray-200 shadow-xs text-center">
                <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <UserGroupIcon className="h-8 w-8 text-gray-400" />
                </div>
                <h4 className="text-lg font-medium text-gray-900 mb-2">{t('contacts.noReferralActivity')}</h4>
                <p className="text-gray-600 max-w-md mx-auto">{t('contacts.noReferralActivityDescription')}</p>
              </div>
            )}

            {/* Action Buttons */}
            <div className="flex justify-end pt-6 border-t border-gray-200">
              <button
                type="button"
                onClick={() => {
                  setShowReferralsModal(false);
                  setSelectedContactForReferralsView(null);
                  setContactReferrals([]);
                }}
                className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
              >
                {t('common.close')}
              </button>
            </div>
          </div>
        </Modal>
      )}

      {/* RBO Part History Modal */}
      {showRboHistoryModal && selectedPurchaseForRboHistory && (
        <Modal
          isOpen={showRboHistoryModal}
          onClose={handleCloseRboHistoryModal}
          title={
            <div className="flex items-center justify-between w-full">
              <span>{t('contacts.replacementHistory')} - {selectedPurchaseForRboHistory.Product?.name}</span>
              {isAdmin && (
                <button
                  onClick={() => {
                    // We need to pass this action to the RboPartHistory component
                    const event = new CustomEvent('openAddModal');
                    document.dispatchEvent(event);
                  }}
                  className="inline-flex items-center px-3 py-1.5 border border-transparent rounded-lg text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500 ml-4"
                >
                  <PlusIcon className="h-4 w-4 mr-1" />
                  {t('contacts.rboPartHistory.add', 'Add Record')}
                </button>
              )}
            </div>
          }
          size="lg"
          showCloseButton={true}
        >
          <RboPartHistory 
            purchaseId={selectedPurchaseForRboHistory.id}
            contactId={selectedPurchaseForRboHistory.contactId || selectedPurchaseForRboHistory.Contact?.id}
            isAdmin={isAdmin} 
          />
        </Modal>
      )}

      {/* Meeting History Modal */}
      {historyContact && (
        <MeetingHistoryModal
          contactId={historyContact.id}
          contactName={`${historyContact.name} ${historyContact.surname}`}
          isOpen={showMeetingHistoryModal}
          onClose={() => {
            setShowMeetingHistoryModal(false);
            setHistoryContact(null);
          }}
        />
      )}
      
      {/* Confirm Dialog */}
      <ConfirmDialog
        isOpen={isConfirmOpen}
        onClose={closeConfirm}
        onConfirm={confirmConfig.onConfirm}
        title={confirmConfig.title}
        message={confirmConfig.message}
        confirmText={confirmConfig.confirmText}
        cancelText={confirmConfig.cancelText}
        type={confirmConfig.type}
      />
      
      {/* GPS Location Modals */}
      <GPSLocationModal {...clientGPS.gpsModalProps} />
      <GPSLocationModal {...editGPS.gpsModalProps} />

      {showEditMap && (
        <LocationPicker
          open={showEditMap}
          onClose={() => setShowEditMap(false)}
          onPick={handleEditMapPick}
          initialLat={editMapInit[0]}
          initialLng={editMapInit[1]}
        />
      )}

      {/* Archive Confirmation Dialog */}
      <ConfirmDialog
        isOpen={showArchiveConfirm}
        onClose={() => setShowArchiveConfirm(false)}
        onConfirm={confirmArchiveMeeting}
        title={t('meetings.archive.archiveConfirm')}
        message={t('meetings.archive.archiveConfirmMessage', 'This will archive the current meeting and reset the contact for a new meeting. This action cannot be undone.')}
        confirmText={t('meetings.archive.archiveNow')}
        cancelText={t('common.cancel')}
        type="warning"
        loading={archivingMeeting}
      />
      </div>
    </ErrorBoundary>
  );
};

export default Contacts; 