import React, { useState, useEffect, useCallback, useRef } from 'react';
import { createPortal } from 'react-dom';
import {
  Building2, MapPin, Phone, Plus, Search, MoreVertical,
  Edit, Users, Truck, ShieldCheck, Globe, X, Loader2,
  CheckCircle, AlertCircle, Navigation
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { fleetApi } from '../../api/fleet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

// Fix default marker icons for Leaflet bundled via Vite
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
});

interface Station {
  id: string;
  name: string;
  address: string;
  gps_lat?: number;
  gps_lon?: number;
  incharge_name?: string;
  phone?: string;
  vehiclesAssigned?: number;
  staffAssigned?: number;
  status?: 'ACTIVE' | 'INACTIVE';
}

interface StationForm {
  name: string;
  address: string;
  incharge_name: string;
  phone: string;
}

const cardStyle: React.CSSProperties = {
  background: '#FFFFFF',
  border: '1px solid rgba(15, 23, 42, 0.08)',
  borderRadius: '16px',
  padding: '24px',
  boxShadow: '0 4px 20px rgba(15, 23, 42, 0.02)',
};

const labelStyle: React.CSSProperties = {
  fontSize: '0.7rem',
  color: '#475569',
  textTransform: 'uppercase',
  letterSpacing: '1px',
  marginBottom: '6px',
  display: 'block',
};

const inputStyle: React.CSSProperties = {
  background: '#FFFFFF',
  border: '1px solid #CBD5E1',
  padding: '11px 14px',
  borderRadius: '10px',
  color: '#0F172A',
  fontSize: '0.875rem',
  outline: 'none',
  width: '100%',
  boxSizing: 'border-box',
  transition: 'border-color 0.2s',
};

const EMPTY_FORM: StationForm = {
  name: '',
  address: '',
  incharge_name: '',
  phone: '',
};

export const FleetOrganization: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'stations' | 'profile'>('stations');
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [stations, setStations] = useState<Station[]>([]);
  const [selectedStationForManifest, setSelectedStationForManifest] = useState<Station | null>(null);
  const [loading, setLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [editingStationId, setEditingStationId] = useState<string | null>(null);
  const [loadingDetailsId, setLoadingDetailsId] = useState<string | null>(null);
  const [form, setForm] = useState<StationForm>(EMPTY_FORM);
  const [gpsCoords, setGpsCoords] = useState<{ lat: number; lon: number } | null>(null);
  const [gpsLoading, setGpsLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [fetchError, setFetchError] = useState('');
  const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);
  const markerRef = useRef<L.Marker | null>(null);

  const token = localStorage.getItem('teleems_token') || '';

  // Get organisationId from stored user
  const user = (() => {
    try { return JSON.parse(localStorage.getItem('teleems_user') || '{}'); } catch { return {}; }
  })();
  const organisationId: string = user?.metadata?.organisation?.id || user?.organisationId || '';

  const fetchStations = useCallback(async () => {
    setLoading(true);
    setFetchError('');
    try {
      const authToken = localStorage.getItem('teleems_token') || '';
      if (!authToken) {
        setFetchError('Session expired — no auth token found. Please log out and log in again.');
        return;
      }

      const url = 'https://teleems-api-gateway.onrender.com/v1/fleet/stations';

      console.log('[Stations] Calling:', url, '| token starts with:', authToken.substring(0, 15));

      const res = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`,
        },
      });

      console.log('[Stations] HTTP status:', res.status);
      const json = await res.json();
      console.log('[Stations] Response:', json);

      if (res.status === 401 || res.status === 403) {
        setFetchError(`Session expired (${res.status}). Please log out and log in again to refresh your token.`);
        return;
      }

      if (!res.ok) {
        setFetchError(`API error ${res.status}: ${json?.message || 'Unknown error'}`);
        return;
      }

      let list: Station[] = [];
      if (json?.data?.data && Array.isArray(json.data.data)) list = json.data.data;
      else if (json?.data && Array.isArray(json.data)) list = json.data;
      else if (Array.isArray(json)) list = json;

      // 2. Fetch Vehicles for each station in parallel using the specific URL: /v1/fleet/vehicles?station_id=...
      const mergedList = await Promise.all(
        list.map(async (s) => {
          let stationVehicles: any[] = [];
          try {
            const vehiclesUrl = `https://teleems-api-gateway.onrender.com/v1/fleet/vehicles?station_id=${s.id}`;
            const vehiclesRes = await fetch(vehiclesUrl, {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`,
              }
            });
            if (vehiclesRes.ok) {
              const vJson = await vehiclesRes.json();
              stationVehicles = vJson?.data?.data || vJson?.data || (Array.isArray(vJson) ? vJson : []);
            }
          } catch (err) {
            console.error(`Failed to fetch vehicles for station ${s.id}:`, err);
          }

          let staffSet = new Set<string>();
          stationVehicles.forEach((v: any) => {
            if (v.activeRoster) {
              const r = v.activeRoster;
              if (r.driver?.user?.name) staffSet.add(r.driver.user.name);
              if (r.staff?.user?.name) staffSet.add(r.staff.user.name);
            }
            if (v.activeShift) {
              const sh = v.activeShift;
              if (sh.driver?.user?.name) staffSet.add(sh.driver.user.name);
              if (sh.staff?.user?.name) staffSet.add(sh.staff.user.name);
            }
          });

          return {
            ...s,
            vehiclesAssigned: stationVehicles.length,
            staffAssigned: staffSet.size
          };
        })
      );

      // Normalize field names: API may return station_name instead of name
      const normalizedList = mergedList.map((s: any) => ({
        ...s,
        name: s.name || s.station_name || '',
        address: s.address || s.station_address || '',
        incharge_name: s.incharge_name || s.incharge || '',
        phone: s.phone || s.contact_phone || s.contact || '',
      }));

      setStations(normalizedList);
    } catch (e) {
      setFetchError('Network error — unable to reach the server. Check your connection.');
      console.error('Failed to fetch stations:', e);
    } finally {
      setLoading(false);
    }
  }, [organisationId]);

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

  // Refetch when user navigates back to the tab
  useEffect(() => {
    const onVisible = () => { if (document.visibilityState === 'visible') fetchStations(); };
    document.addEventListener('visibilitychange', onVisible);
    return () => document.removeEventListener('visibilitychange', onVisible);
  }, [fetchStations]);





  // Initialize Leaflet map when modal opens
  useEffect(() => {
    if (!showModal) {
      // Destroy map on close
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
        markerRef.current = null;
      }
      return;
    }
    // Wait for DOM
    const timer = setTimeout(() => {
      if (!mapContainerRef.current || mapInstanceRef.current) return;
      const initialLat = gpsCoords ? gpsCoords.lat : 20.5937;
      const initialLon = gpsCoords ? gpsCoords.lon : 78.9629;
      const initialZoom = gpsCoords ? 14 : 5;

      const map = L.map(mapContainerRef.current, { zoomControl: true }).setView([initialLat, initialLon], initialZoom);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
      }).addTo(map);

      if (gpsCoords) {
        markerRef.current = L.marker([initialLat, initialLon]).addTo(map)
          .bindPopup(`📍 ${initialLat.toFixed(6)}, ${initialLon.toFixed(6)}`).openPopup();
      }

      map.on('click', (e: L.LeafletMouseEvent) => {
        const { lat, lng } = e.latlng;
        setGpsCoords({ lat, lon: lng });
        if (markerRef.current) {
          markerRef.current.setLatLng([lat, lng]);
        } else {
          markerRef.current = L.marker([lat, lng]).addTo(map)
            .bindPopup(`📍 ${lat.toFixed(6)}, ${lng.toFixed(6)}`).openPopup();
        }
      });

      mapInstanceRef.current = map;
    }, 200);
    return () => clearTimeout(timer);
  }, [showModal, gpsCoords]);

  const flyToCurrentLocation = () => {
    setGpsLoading(true);
    if (!navigator.geolocation) { setGpsLoading(false); return; }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { latitude: lat, longitude: lon } = pos.coords;
        setGpsCoords({ lat, lon });
        setGpsLoading(false);
        if (mapInstanceRef.current) {
          mapInstanceRef.current.flyTo([lat, lon], 15);
          if (markerRef.current) {
            markerRef.current.setLatLng([lat, lon]);
          } else {
            markerRef.current = L.marker([lat, lon]).addTo(mapInstanceRef.current!)
              .bindPopup(`📍 ${lat.toFixed(6)}, ${lon.toFixed(6)}`).openPopup();
          }
        }
      },
      () => setGpsLoading(false),
      { enableHighAccuracy: true, timeout: 10000 }
    );
  };

  const openCreateModal = () => {
    setEditingStationId(null);
    setForm(EMPTY_FORM);
    setGpsCoords(null);
    setShowModal(true);
  };

  const openEditModal = async (station: Station) => {
    setLoadingDetailsId(station.id);
    try {
      const res = await fleetApi.getStationDetails(station.id, token);
      console.log('[Stations] Fetched single station details:', res);

      const details = res?.data || res?.station || res || station;

      setEditingStationId(station.id);
      setForm({
        name: details.name || station.name,
        address: details.address || station.address,
        incharge_name: details.incharge_name || station.incharge_name || '',
        phone: details.phone || station.phone || '',
      });

      const lat = details.gps_lat !== undefined ? details.gps_lat : station.gps_lat;
      const lon = details.gps_lon !== undefined ? details.gps_lon : station.gps_lon;

      if (lat && lon) {
        setGpsCoords({ lat: Number(lat), lon: Number(lon) });
      } else {
        setGpsCoords(null);
      }
      setShowModal(true);
    } catch (err: any) {
      console.error('Failed to fetch station details, falling back to card data:', err);
      // Fallback to local card data so the UI doesn't break
      setEditingStationId(station.id);
      setForm({
        name: station.name,
        address: station.address,
        incharge_name: station.incharge_name || '',
        phone: station.phone || '',
      });
      if (station.gps_lat && station.gps_lon) {
        setGpsCoords({ lat: Number(station.gps_lat), lon: Number(station.gps_lon) });
      } else {
        setGpsCoords(null);
      }
      setShowModal(true);
    } finally {
      setLoadingDetailsId(null);
    }
  };

  const showToast = (type: 'success' | 'error', message: string) => {
    setToast({ type, message });
    setTimeout(() => setToast(null), 4000);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const payload = {
        name: form.name,
        address: form.address,
        gps_lat: gpsCoords?.lat ?? 0,
        gps_lon: gpsCoords?.lon ?? 0,
        incharge_name: form.incharge_name,
        phone: form.phone,
      };

      let res;
      if (editingStationId) {
        res = await fleetApi.updateStation(editingStationId, payload, token);
      } else {
        res = await fleetApi.createStation(payload, token);
      }

      if (res && (res.status === 200 || res.status === 201 || res.id || res.success || res.data)) {
        showToast('success', editingStationId ? `Station "${form.name}" updated successfully!` : `Station "${form.name}" created successfully!`);
        setShowModal(false);
        setForm(EMPTY_FORM);
        setGpsCoords(null);
        setEditingStationId(null);
        fetchStations();
      } else {
        showToast('error', res?.message || `Failed to ${editingStationId ? 'update' : 'create'} station. Please try again.`);
      }
    } catch (err: any) {
      showToast('error', err?.message || 'Network error. Please check your connection.');
    } finally {
      setSubmitting(false);
    }
  };

  const filteredStations = stations.filter(s =>
    s.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    s.incharge_name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div style={{ color: '#F8FAFC', position: 'relative' }}>
      {/* Toast Notification */}
      <AnimatePresence>
        {toast && (
          <motion.div
            initial={{ opacity: 0, y: -20, x: '-50%' }}
            animate={{ opacity: 1, y: 0, x: '-50%' }}
            exit={{ opacity: 0, y: -20, x: '-50%' }}
            style={{
              position: 'fixed', top: '24px', left: '50%', zIndex: 9999,
              padding: '14px 24px', borderRadius: '12px', display: 'flex', alignItems: 'center', gap: '10px',
              background: toast.type === 'success' ? 'rgba(16, 185, 129, 0.15)' : 'rgba(239, 68, 68, 0.15)',
              border: `1px solid ${toast.type === 'success' ? 'rgba(16,185,129,0.4)' : 'rgba(239,68,68,0.4)'}`,
              color: toast.type === 'success' ? '#10B981' : '#EF4444',
              fontWeight: 600, fontSize: '0.875rem',
              backdropFilter: 'blur(12px)',
              boxShadow: '0 8px 32px rgba(0,0,0,0.4)',
            }}
          >
            {toast.type === 'success' ? <CheckCircle size={18} /> : <AlertCircle size={18} />}
            {toast.message}
          </motion.div>
        )}
      </AnimatePresence>

      {/* Add Station Modal */}
      {createPortal(
        <AnimatePresence>
          {showModal && (
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              style={{ position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.3)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}
              onClick={(e) => { if (e.target === e.currentTarget) setShowModal(false); }}
            >
              <motion.div
                initial={{ scale: 0.92, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.92, opacity: 0 }}
                style={{ background: '#FFFFFF', border: '1px solid rgba(15, 23, 42, 0.08)', borderRadius: '20px', padding: '24px 32px', width: '880px', maxWidth: '95vw', maxHeight: '96vh', overflowY: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 20px 50px rgba(15, 23, 42, 0.12)' }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', flexShrink: 0 }}>
                  <div>
                    <h2 style={{ fontSize: '1.3rem', fontWeight: 900, color: '#0F172A', margin: 0 }}>{editingStationId ? 'Edit Station' : 'Add New Station'}</h2>
                    <p style={{ fontSize: '0.78rem', color: '#475569', margin: '2px 0 0' }}>{editingStationId ? 'Update dispatch station details' : 'Create a new dispatch station'}</p>
                  </div>
                  <button type="button" onClick={() => setShowModal(false)} style={{ background: '#F1F5F9', border: '1px solid #E2E8F0', borderRadius: '8px', padding: '8px', color: '#475569', cursor: 'pointer', display: 'flex' }}>
                    <X size={18} />
                  </button>
                </div>

                <form onSubmit={handleSubmit} style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: '28px', alignItems: 'start' }}>

                    {/* Left Column: Form Fields */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
                      <div>
                        <label style={labelStyle}>Station Name *</label>
                        <input style={inputStyle} placeholder="e.g. Alpha Dispatch Hub" required value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} />
                      </div>
                      <div>
                        <label style={labelStyle}>Address *</label>
                        <textarea style={{ ...inputStyle, resize: 'none', height: '64px' }} placeholder="Full address of the station" required value={form.address} onChange={e => setForm(f => ({ ...f, address: e.target.value }))} />
                      </div>
                      <div>
                        <label style={labelStyle}>Incharge Name *</label>
                        <input style={inputStyle} placeholder="Station incharge full name" required value={form.incharge_name} onChange={e => setForm(f => ({ ...f, incharge_name: e.target.value }))} />
                      </div>
                      <div>
                        <label style={labelStyle}>Contact Phone *</label>
                        <input style={inputStyle} placeholder="+91-9876543210" required value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
                      </div>
                    </div>

                    {/* Right Column: Interactive Map Picker */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                      <div>
                        <label style={labelStyle}>GPS Location — Click on map to set pin</label>
                        <div style={{ position: 'relative', borderRadius: '12px', overflow: 'hidden', border: '1px solid rgba(15, 23, 42, 0.08)' }}>
                          <div ref={mapContainerRef} style={{ height: '210px', width: '100%', background: '#F1F5F9' }} />
                          {/* Overlay UI */}
                          <button
                            type="button"
                            onClick={flyToCurrentLocation}
                            disabled={gpsLoading}
                            style={{ position: 'absolute', top: '10px', right: '10px', zIndex: 1000, padding: '6px 12px', background: 'rgba(15,23,42,0.9)', border: '1px solid rgba(6,182,212,0.4)', borderRadius: '8px', color: '#06B6D4', cursor: gpsLoading ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.7rem', fontWeight: 600, backdropFilter: 'blur(8px)' }}
                          >
                            {gpsLoading ? <Loader2 size={12} className="spin" /> : <Navigation size={12} />}
                            {gpsLoading ? 'Locating...' : 'My Location'}
                          </button>
                        </div>
                        <div style={{ marginTop: '8px' }}>
                          <div style={{ padding: '8px 12px', borderRadius: '8px', background: gpsCoords ? 'rgba(16,185,129,0.08)' : '#F1F5F9', border: `1px solid ${gpsCoords ? 'rgba(16,185,129,0.2)' : '#E2E8F0'}`, color: gpsCoords ? '#10B981' : '#475569', fontSize: '0.75rem', fontFamily: 'monospace' }}>
                            {gpsCoords ? `Lat: ${gpsCoords.lat.toFixed(6)}  |  Lon: ${gpsCoords.lon.toFixed(6)}` : '📍 Click on the map to place a pin'}
                          </div>
                        </div>
                      </div>

                      {/* Action buttons placed cleanly inside the right column at the bottom */}
                      <div style={{ display: 'flex', gap: '12px', marginTop: '12px' }}>
                        <button type="button" onClick={() => setShowModal(false)}
                          style={{ flex: 1, padding: '11px', background: '#FFFFFF', border: '1px solid #CBD5E1', borderRadius: '12px', color: '#475569', cursor: 'pointer', fontWeight: 600, fontSize: '0.85rem' }}>
                          Cancel
                        </button>
                        <button type="submit" disabled={submitting}
                          style={{ flex: 1.5, padding: '11px', background: submitting ? 'rgba(6,182,212,0.3)' : 'linear-gradient(135deg, #06B6D4, #3B82F6)', border: 'none', borderRadius: '12px', color: '#fff', cursor: submitting ? 'not-allowed' : 'pointer', fontWeight: 700, fontSize: '0.85rem', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', boxShadow: '0 4px 16px rgba(6,182,212,0.3)' }}>
                          {submitting ? (
                            <><Loader2 size={16} className="spin" /> {editingStationId ? 'Updating...' : 'Creating...'}</>
                          ) : (
                            <><Edit size={16} /> {editingStationId ? 'UPDATE' : 'CREATE'}</>
                          )}
                        </button>
                      </div>
                    </div>

                  </div>
                </form>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>,
        document.body
      )}

      {/* Tab Toggle */}
      <div style={{ display: 'flex', gap: '4px', marginBottom: '28px', background: 'rgba(255,255,255,0.03)', padding: '4px', borderRadius: '12px', width: 'fit-content', border: '1px solid rgba(255,255,255,0.06)' }}>
        {(['stations', 'profile'] as const).map(tab => (
          <button key={tab} onClick={() => setActiveTab(tab)} style={{ padding: '10px 24px', borderRadius: '10px', border: 'none', background: activeTab === tab ? 'linear-gradient(135deg, #06B6D4, #3B82F6)' : 'transparent', color: activeTab === tab ? '#fff' : '#64748B', fontWeight: activeTab === tab ? 700 : 500, fontSize: '0.875rem', cursor: 'pointer', transition: 'all 0.3s ease', display: 'flex', alignItems: 'center', gap: '8px', boxShadow: activeTab === tab ? '0 4px 12px rgba(6,182,212,0.3)' : 'none' }}>
            {tab === 'stations' ? <><MapPin size={16} /> Station Management</> : <><Building2 size={16} /> Organisation Profile</>}
          </button>
        ))}
      </div>

      {activeTab === 'profile' ? (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '24px' }}>
            <div style={cardStyle}>
              <h3 style={{ fontSize: '1.1rem', fontWeight: 800, marginBottom: '24px', color: '#fff' }}>Fleet Operator Profile</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
                <div><label style={labelStyle}>Full Name</label><input style={inputStyle} defaultValue={user?.name || ''} placeholder="Full name" /></div>
                <div><label style={labelStyle}>Username</label><input style={{ ...inputStyle, fontFamily: 'monospace', color: '#06B6D4' }} defaultValue={user?.username || ''} readOnly /></div>
                <div><label style={labelStyle}>Email Address</label><input style={inputStyle} type="email" defaultValue={user?.email || ''} placeholder="Email" /></div>
                <div><label style={labelStyle}>Phone Number</label><input style={inputStyle} defaultValue={user?.phone || ''} placeholder="+91-XXXXXXXXXX" /></div>
                <div style={{ gridColumn: '1 / -1' }}><label style={labelStyle}>Organisation ID</label><input style={{ ...inputStyle, fontFamily: 'monospace', fontSize: '0.78rem', color: '#94A3B8' }} defaultValue={user?.organisationId || organisationId || ''} readOnly /></div>
                {user?.department && <div><label style={labelStyle}>Department</label><input style={inputStyle} defaultValue={user.department} /></div>}
                {user?.designation && <div><label style={labelStyle}>Designation</label><input style={inputStyle} defaultValue={user.designation} /></div>}
              </div>
              <div style={{ marginTop: '24px', display: 'flex', justifyContent: 'flex-end' }}>
                <button style={{ padding: '12px 28px', background: 'linear-gradient(135deg, #06B6D4, #3B82F6)', border: 'none', borderRadius: '10px', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: '0.875rem' }}>SAVE CHANGES</button>
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              <div style={{ ...cardStyle, textAlign: 'center' }}>
                <div style={{ width: '72px', height: '72px', borderRadius: '50%', background: 'linear-gradient(135deg, #06B6D4, #3B82F6)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', fontSize: '1.5rem', fontWeight: 900, color: '#fff', boxShadow: '0 0 24px rgba(6,182,212,0.3)' }}>
                  {(user?.name || 'FO').split(' ').map((n: string) => n[0]).join('').toUpperCase().substring(0, 2)}
                </div>
                <h3 style={{ fontSize: '1.1rem', fontWeight: 800 }}>{user?.name || 'Fleet Operator'}</h3>
                <p style={{ fontSize: '0.8rem', color: '#64748B', marginTop: '4px' }}>{user?.email || ''}</p>
                <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  <div style={{ padding: '8px', background: user?.status === 'ACTIVE' ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)', border: `1px solid ${user?.status === 'ACTIVE' ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)'}`, borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', color: user?.status === 'ACTIVE' ? '#10B981' : '#EF4444', fontWeight: 700, fontSize: '0.75rem' }}>
                    <ShieldCheck size={14} /> {user?.status || 'ACTIVE'}
                  </div>
                  <div style={{ padding: '8px', background: 'rgba(6,182,212,0.06)', border: '1px solid rgba(6,182,212,0.12)', borderRadius: '8px', color: '#475569', fontSize: '0.68rem', fontFamily: 'monospace', wordBreak: 'break-all', textAlign: 'left' }}>
                    ORG: {user?.organisationId || organisationId || '—'}
                  </div>
                </div>
              </div>
              <div style={cardStyle}>
                <h4 style={{ fontSize: '0.875rem', fontWeight: 700, marginBottom: '16px', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.5px' }}>Quick Stats</h4>
                {[{ icon: MapPin, label: 'Active Stations', value: stations.length || 0 }, { icon: Truck, label: 'Total Vehicles', value: 25 }, { icon: Users, label: 'Total Staff', value: 71 }].map(({ icon: Icon, label, value }) => (
                  <div key={label} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid rgba(255,255,255,0.04)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px', color: '#94A3B8', fontSize: '0.875rem' }}><Icon size={16} color="#06B6D4" /> {label}</div>
                    <span style={{ fontWeight: 900, fontSize: '1.25rem', color: '#fff' }}>{value}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </motion.div>
      ) : (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              gap: '10px',
              background: '#FFFFFF',
              padding: '10px 16px',
              borderRadius: '12px',
              border: isSearchFocused ? '1px solid #06B6D4' : '1px solid #CBD5E1',
              boxShadow: isSearchFocused ? '0 0 0 3px rgba(6, 182, 212, 0.15)' : '0 2px 4px rgba(15, 23, 42, 0.01)',
              transition: 'all 0.2s ease',
              width: '320px',
              position: 'relative'
            }}>
              <Search size={16} color={isSearchFocused ? "#06B6D4" : "#64748B"} style={{ transition: 'color 0.2s' }} />
              <input 
                type="text" 
                placeholder="Search stations, incharge..." 
                value={searchQuery} 
                onChange={e => setSearchQuery(e.target.value)}
                onFocus={() => setIsSearchFocused(true)}
                onBlur={() => setIsSearchFocused(false)}
                className="stations-search-input"
                style={{ 
                  background: 'transparent', 
                  border: 'none', 
                  color: '#0F172A', 
                  fontSize: '0.875rem', 
                  outline: 'none', 
                  width: '100%',
                  paddingRight: searchQuery ? '24px' : '0'
                }} 
              />
              {searchQuery && (
                <button 
                  onClick={() => setSearchQuery('')}
                  style={{
                    position: 'absolute',
                    right: '12px',
                    background: 'transparent',
                    border: 'none',
                    cursor: 'pointer',
                    color: '#94A3B8',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '2px',
                    borderRadius: '50%',
                  }}
                  onMouseEnter={e => e.currentTarget.style.color = '#475569'}
                  onMouseLeave={e => e.currentTarget.style.color = '#94A3B8'}
                >
                  <X size={14} />
                </button>
              )}
            </div>
            <button onClick={openCreateModal}
              style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '11px 22px', background: 'linear-gradient(135deg, #06B6D4, #3B82F6)', border: 'none', borderRadius: '12px', color: '#fff', fontWeight: 700, cursor: 'pointer', boxShadow: '0 4px 12px rgba(6,182,212,0.3)', fontSize: '0.875rem' }}>
              <Plus size={18} /> ADD NEW STATION
            </button>
          </div>

          {/* Loading state */}
          {loading && (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '200px', gap: '12px', color: '#64748B' }}>
              <Loader2 size={24} style={{ animation: 'spin 1s linear infinite' }} />
              <span>Loading stations...</span>
            </div>
          )}

          {/* Error state */}
          {!loading && fetchError && (
            <div style={{ textAlign: 'center', padding: '40px 24px', background: 'rgba(239,68,68,0.05)', border: '1px solid rgba(239,68,68,0.15)', borderRadius: '16px', marginBottom: '20px' }}>
              <AlertCircle size={36} color="#EF4444" style={{ marginBottom: '12px', opacity: 0.8 }} />
              <h3 style={{ fontSize: '1rem', fontWeight: 700, color: '#EF4444', marginBottom: '8px' }}>Failed to Load Stations</h3>
              <p style={{ fontSize: '0.82rem', color: '#94A3B8', marginBottom: '16px' }}>{fetchError}</p>
              <button onClick={fetchStations} style={{ padding: '10px 24px', background: 'linear-gradient(135deg, #06B6D4, #3B82F6)', border: 'none', borderRadius: '10px', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: '0.875rem' }}>
                ↺ Retry
              </button>
            </div>
          )}

          {/* Empty state */}
          {!loading && !fetchError && filteredStations.length === 0 && (
            <div style={{ textAlign: 'center', padding: '60px 24px', color: '#64748B' }}>
              <MapPin size={48} style={{ opacity: 0.2, marginBottom: '16px' }} />
              <h3 style={{ fontSize: '1.1rem', fontWeight: 700, color: '#94A3B8', marginBottom: '8px' }}>No Stations Found</h3>
              <p style={{ fontSize: '0.875rem' }}>Click "Add New Station" to create your first dispatch station.</p>
            </div>
          )}

          {/* Station Cards */}
          {!loading && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: '20px' }}>
              {filteredStations.map(station => (
                <div key={station.id} style={{ ...cardStyle, position: 'relative', overflow: 'hidden', transition: 'transform 0.2s, box-shadow 0.2s', cursor: 'pointer' }}
                  onMouseEnter={e => { (e.currentTarget as HTMLElement).style.transform = 'translateY(-4px)'; (e.currentTarget as HTMLElement).style.boxShadow = '0 12px 32px rgba(15, 23, 42, 0.06)'; }}
                  onMouseLeave={e => { (e.currentTarget as HTMLElement).style.transform = 'translateY(0)'; (e.currentTarget as HTMLElement).style.boxShadow = 'none'; }}
                >
                  <div style={{ position: 'absolute', top: 0, left: 0, width: '4px', height: '100%', background: station.status === 'INACTIVE' ? '#EF4444' : '#10B981', borderRadius: '4px 0 0 4px' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px' }}>
                    <div>
                      <h3 style={{ fontSize: '1rem', fontWeight: 800, color: '#0F172A' }}>{station.name}</h3>
                      <div style={{ fontSize: '0.7rem', color: '#475569', marginTop: '4px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <Globe size={11} /> {station.id?.substring(0, 8)}...
                      </div>
                    </div>
                    <button style={{ background: 'transparent', border: 'none', color: '#475569', cursor: 'pointer', padding: '4px' }}><MoreVertical size={18} /></button>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '20px' }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: '10px' }}>
                      <MapPin size={15} color="#06B6D4" style={{ marginTop: '2px', flexShrink: 0 }} />
                      <div>
                        <div style={{ fontSize: '0.85rem', color: '#334155' }}>{station.address}</div>
                        {(station.gps_lat || station.gps_lon) && (
                          <div style={{ fontSize: '0.68rem', color: '#475569', fontFamily: 'monospace', marginTop: '2px' }}>
                            GPS: {station.gps_lat}, {station.gps_lon}
                          </div>
                        )}
                      </div>
                    </div>
                    {station.incharge_name && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <Users size={15} color="#06B6D4" />
                        <span style={{ fontSize: '0.85rem', color: '#475569' }}>Incharge: <span style={{ fontWeight: 700, color: '#0F172A' }}>{station.incharge_name}</span></span>
                      </div>
                    )}
                    {station.phone && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <Phone size={15} color="#06B6D4" />
                        <span style={{ fontSize: '0.85rem', color: '#475569' }}>{station.phone}</span>
                      </div>
                    )}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1px', background: '#E2E8F0', borderRadius: '10px', overflow: 'hidden', marginBottom: '16px', border: '1px solid #E2E8F0' }}>
                    <div style={{ textAlign: 'center', padding: '14px', background: '#F8FAFC' }}>
                      <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#0F172A' }}>{station.vehiclesAssigned ?? '—'}</div>
                      <div style={{ fontSize: '0.62rem', color: '#475569', textTransform: 'uppercase', letterSpacing: '0.5px', marginTop: '4px' }}>Vehicles</div>
                    </div>
                    <div style={{ textAlign: 'center', padding: '14px', background: '#F8FAFC' }}>
                      <div style={{ fontSize: '1.5rem', fontWeight: 900, color: '#0F172A' }}>{station.staffAssigned ?? '—'}</div>
                      <div style={{ fontSize: '0.62rem', color: '#475569', textTransform: 'uppercase', letterSpacing: '0.5px', marginTop: '4px' }}>Staff</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    <button
                      onClick={(e) => { e.stopPropagation(); openEditModal(station); }}
                      disabled={loadingDetailsId !== null}
                      style={{
                        flex: '1 1 70px', padding: '9px',
                        background: '#FFFFFF',
                        border: '1px solid #CBD5E1',
                        borderRadius: '8px',
                        color: loadingDetailsId === station.id ? '#06B6D4' : '#475569',
                        fontSize: '0.75rem', fontWeight: 600,
                        cursor: loadingDetailsId !== null ? 'not-allowed' : 'pointer',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px',
                        transition: 'all 0.2s'
                      }}
                    >
                      {loadingDetailsId === station.id ? (
                        <Loader2 size={13} className="spin" />
                      ) : (
                        <Edit size={13} />
                      )}
                      {loadingDetailsId === station.id ? 'FETCHING...' : 'EDIT'}
                    </button>
                    <button 
                      onClick={(e) => { e.stopPropagation(); setSelectedStationForManifest(station); }}
                      style={{ flex: '1.2 1 100px', padding: '9px', background: 'rgba(16, 185, 129, 0.08)', border: '1px solid rgba(16, 185, 129, 0.2)', borderRadius: '8px', color: '#10B981', fontSize: '0.75rem', fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}
                    >
                      <Users size={13} /> MANIFEST
                    </button>
                    {/* <button style={{ flex: '1.5 1 110px', padding: '9px', background: 'rgba(6,182,212,0.08)', border: '1px solid rgba(6,182,212,0.2)', borderRadius: '8px', color: '#06B6D4', fontSize: '0.75rem', fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
                      <Truck size={13} /> ASSIGN ASSETS
                    </button> */}
                  </div>
                </div>
              ))}
            </div>
          )}
        </motion.div>
      )}

      {/* Station Manifest Modal */}
      {createPortal(
        <AnimatePresence>
          {selectedStationForManifest && (
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              style={{ position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.3)', zIndex: 10000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}
              onClick={() => setSelectedStationForManifest(null)}
            >
              <motion.div
                initial={{ scale: 0.92, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.92, opacity: 0 }}
                style={{ background: '#FFFFFF', border: '1px solid rgba(15, 23, 42, 0.08)', borderRadius: '20px', padding: '24px 32px', width: '750px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', boxShadow: '0 20px 50px rgba(15, 23, 42, 0.12)' }}
                onClick={(e) => e.stopPropagation()}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', borderBottom: '1px solid #F1F5F9', paddingBottom: '16px' }}>
                  <div>
                    <h2 style={{ fontSize: '1.25rem', fontWeight: 900, color: '#0F172A', margin: 0 }}>
                      {selectedStationForManifest.name.toUpperCase()} MANIFEST
                    </h2>
                    <p style={{ fontSize: '0.78rem', color: '#64748B', margin: '4px 0 0' }}>
                      📍 {selectedStationForManifest.address}
                    </p>
                  </div>
                  <button type="button" onClick={() => setSelectedStationForManifest(null)} style={{ background: '#F1F5F9', border: '1px solid #E2E8F0', borderRadius: '8px', padding: '8px', color: '#475569', cursor: 'pointer', display: 'flex' }}>
                    <X size={18} />
                  </button>
                </div>

                <StationManifestContent stationId={selectedStationForManifest.id} />

              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>,
        document.body
      )}

      <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .spin { animation: spin 1s linear infinite; }`}</style>
    </div>
  );
};

interface ManifestVehicle {
  id: string;
  registration_number: string;
  brand?: string;
  model?: string;
  vehicle_type?: string;
  status: string;
  activeRoster?: {
    driver?: { user?: { name: string; phone?: string } };
    staff?: { user?: { name: string; phone?: string } };
  };
  activeShift?: {
    driver?: { user?: { name: string; phone?: string } };
    staff?: { user?: { name: string; phone?: string } };
  };
}

const StationManifestContent: React.FC<{ stationId: string }> = ({ stationId }) => {
  const [vehicles, setVehicles] = useState<ManifestVehicle[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let active = true;
    const load = async () => {
      setLoading(true);
      setError(null);
      try {
        const authToken = localStorage.getItem('teleems_token') || '';
        if (!authToken) throw new Error('Session expired — please log in again.');

        const url = `https://teleems-api-gateway.onrender.com/v1/fleet/vehicles?station_id=${stationId}`;
        console.log('[Manifest] Calling:', url);

        const res = await fetch(url, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${authToken}`,
          },
        });

        if (!res.ok) {
          throw new Error(`HTTP error ${res.status}`);
        }

        const json = await res.json();
        if (active) {
          let list = json?.data?.data || json?.data || (Array.isArray(json) ? json : []);
          setVehicles(list);
        }
      } catch (err: any) {
        if (active) {
          setError(err.message || 'Failed to fetch station assets');
        }
      } finally {
        if (active) {
          setLoading(false);
        }
      }
    };
    load();
    return () => { active = false; };
  }, [stationId]);

  const crewList = React.useMemo(() => {
    const map = new Map<string, { name: string; role: string; phone?: string }>();
    vehicles.forEach(v => {
      const roster = v.activeRoster;
      if (roster) {
        if (roster.driver?.user?.name) {
          map.set(roster.driver.user.name, {
            name: roster.driver.user.name,
            role: 'Pilot (Driver)',
            phone: roster.driver.user.phone
          });
        }
        if (roster.staff?.user?.name) {
          map.set(roster.staff.user.name, {
            name: roster.staff.user.name,
            role: 'EMT (Medic)',
            phone: roster.staff.user.phone
          });
        }
      }
      const shift = v.activeShift;
      if (shift) {
        if (shift.driver?.user?.name) {
          map.set(shift.driver.user.name, {
            name: shift.driver.user.name,
            role: 'Pilot (Driver)',
            phone: shift.driver.user.phone
          });
        }
        if (shift.staff?.user?.name) {
          map.set(shift.staff.user.name, {
            name: shift.staff.user.name,
            role: 'EMT (Medic)',
            phone: shift.staff.user.phone
          });
        }
      }
    });
    return Array.from(map.values());
  }, [vehicles]);

  if (loading) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '60px 0', gap: '12px' }}>
        <Loader2 className="spin" size={28} color="#06B6D4" style={{ animation: 'spin 1s linear infinite' }} />
        <span style={{ color: '#64748B', fontSize: '0.85rem', fontWeight: 600 }}>FETCHING STATION ASSETS...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '24px', textAlign: 'center', color: '#EF4444', background: 'rgba(239, 68, 68, 0.05)', borderRadius: '12px', border: '1px solid rgba(239, 68, 68, 0.15)' }}>
        <AlertCircle size={28} style={{ marginBottom: '8px', display: 'inline-block' }} />
        <div style={{ fontSize: '0.875rem', fontWeight: 700 }}>Error Loading Manifest</div>
        <div style={{ fontSize: '0.8rem', opacity: 0.8, marginTop: '4px' }}>{error}</div>
      </div>
    );
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '24px', minHeight: '300px' }}>
      {/* Vehicles Column */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        <h4 style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.9rem', fontWeight: 800, color: '#0F172A', margin: 0, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
          <Truck size={18} color="#06B6D4" /> Deployed Fleet ({vehicles.length})
        </h4>
        
        {vehicles.length === 0 ? (
          <div style={{ padding: '40px 16px', textAlign: 'center', background: '#F8FAFC', borderRadius: '12px', border: '1px dashed #E2E8F0', color: '#64748B', fontSize: '0.82rem', fontStyle: 'italic' }}>
            No vehicles currently docked at this station.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', maxHeight: '50vh', overflowY: 'auto', paddingRight: '4px' }}>
            {vehicles.map(v => {
              const driverName = v.activeRoster?.driver?.user?.name || v.activeShift?.driver?.user?.name;
              const emtName = v.activeRoster?.staff?.user?.name || v.activeShift?.staff?.user?.name;
              return (
                <div key={v.id} style={{ padding: '14px', background: '#F8FAFC', borderRadius: '12px', border: '1px solid #E2E8F0', display: 'flex', flexDirection: 'column', gap: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                      <div style={{ fontSize: '0.9rem', fontWeight: 800, color: '#0F172A' }}>{v.registration_number}</div>
                      <div style={{ fontSize: '0.72rem', color: '#475569', marginTop: '2px' }}>{v.brand} {v.model} • {v.vehicle_type}</div>
                    </div>
                    <span style={{ 
                      fontSize: '0.68rem', 
                      fontWeight: 700, 
                      padding: '4px 10px', 
                      borderRadius: '20px', 
                      background: v.status === 'AVAILABLE' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)', 
                      color: v.status === 'AVAILABLE' ? '#10B981' : '#EF4444' 
                    }}>
                      {v.status}
                    </span>
                  </div>
                  
                  {(driverName || emtName) && (
                    <div style={{ borderTop: '1px solid #E2E8F0', paddingTop: '8px', display: 'flex', flexDirection: 'column', gap: '4px' }}>
                      {driverName && (
                        <div style={{ fontSize: '0.75rem', color: '#475569', display: 'flex', alignItems: 'center', gap: '4px' }}>
                          <span style={{ color: '#94A3B8', fontWeight: 600 }}>Pilot:</span>
                          <strong style={{ color: '#0F172A' }}>{driverName}</strong>
                        </div>
                      )}
                      {emtName && (
                        <div style={{ fontSize: '0.75rem', color: '#475569', display: 'flex', alignItems: 'center', gap: '4px' }}>
                          <span style={{ color: '#94A3B8', fontWeight: 600 }}>EMT:</span>
                          <strong style={{ color: '#0F172A' }}>{emtName}</strong>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Staff Column */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        <h4 style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.9rem', fontWeight: 800, color: '#0F172A', margin: 0, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
          <Users size={18} color="#06B6D4" /> Active Crew ({crewList.length})
        </h4>

        {crewList.length === 0 ? (
          <div style={{ padding: '40px 16px', textAlign: 'center', background: '#F8FAFC', borderRadius: '12px', border: '1px dashed #E2E8F0', color: '#64748B', fontSize: '0.82rem', fontStyle: 'italic' }}>
            No crew members currently on duty.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', maxHeight: '50vh', overflowY: 'auto' }}>
            {crewList.map((c, i) => (
              <div key={i} style={{ padding: '12px 14px', background: '#F8FAFC', borderRadius: '12px', border: '1px solid #E2E8F0', display: 'flex', alignItems: 'center', gap: '12px' }}>
                <div style={{ width: '34px', height: '34px', borderRadius: '50%', background: 'rgba(6, 182, 212, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#06B6D4' }}>
                  <Users size={16} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '0.85rem', fontWeight: 700, color: '#0F172A' }}>{c.name}</div>
                  <div style={{ fontSize: '0.7rem', color: '#475569', marginTop: '2px' }}>{c.role} {c.phone ? `• ${c.phone}` : ''}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
