import React, { useEffect, useState, useRef } from 'react';
import { io, Socket } from 'socket.io-client';
import { Capacitor } from '@capacitor/core';
import { BACKEND_URL } from '@/utils/backendEndpoint';
import { queueOfflineUpload } from '@/utils/offlineQueue';
import {
  Compass,
  Users,
  Image as ImageIcon,
  MessageSquare,
  LogOut,
  Search,
  Check,
  X,
  Trash2,
  Send,
  UserPlus,
  Clock,
  ChevronRight,
  ChevronLeft,
  Shield,
  Calendar,
  MapPin,
  Download,
  Loader2,
  Bell,
  BellOff,
  ShieldAlert,
  Camera
} from 'lucide-react';
import { useTourStore } from '@/store/useTourStore';
import { useNotification } from '@/hooks/useNotification';
import { useConfirm } from '@/hooks/useConfirm';
import { MyPhotosPage } from './MyPhotosPage';
import { useTranslation } from '../hooks/useTranslation';
import { useTheme } from '../hooks/useTheme';

interface MemberDashboardProps {
  user: any;
  onLogout: () => void;
  onExploreTours: () => void;
  onViewTour: (tourId: string, fromPage?: 'explore' | 'dashboard') => void;
  onOpenMyPhotos: () => void;
  initialTab?: 'tours' | 'connections' | 'photos' | 'chats';
}

export const MemberDashboard: React.FC<MemberDashboardProps> = ({
  user,
  onLogout,
  onExploreTours,
  onViewTour,
  initialTab,
}) => {
  // GUARD: Prevent guest users from accessing dashboard
  const guestToken = localStorage.getItem('guest_token');
  const token = localStorage.getItem('token');
  if (guestToken && !token) {
    // This is a guest user - redirect them by triggering onLogout
    // which will clear everything and redirect to landing
    console.warn('Guest user attempted to access MemberDashboard - redirecting to home');
    // Clear guest tokens
    localStorage.removeItem('guest_token');
    localStorage.removeItem('guest_user');
    // Redirect to home
    window.location.href = '/';
    return null;
  }

  const notify = useNotification();
  const confirm = useConfirm();
  const { t, lang, changeLanguage } = useTranslation();
  const { theme, changeTheme } = useTheme();

  const publicTours = useTourStore(state => state.publicTours);
  const fetchPublicTours = useTourStore(state => state.fetchPublicTours);

  const [activeTab, setActiveTab] = useState<'tours' | 'connections' | 'photos' | 'chats'>(initialTab || 'tours');

  useEffect(() => {
    if (initialTab) {
      setActiveTab(initialTab);
    }
  }, [initialTab]);
  const [connectionSubTab, setConnectionSubTab] = useState<'list' | 'search' | 'pending'>('list');

  // Connection states
  const [connections, setConnections] = useState<any[]>([]);
  const [receivedRequests, setReceivedRequests] = useState<any[]>([]);
  const [sentRequests, setSentRequests] = useState<any[]>([]);

  // User search states
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [searchingUsers, setSearchingUsers] = useState(false);

  // Photos states
  const [photos, setPhotos] = useState<any[]>([]);

  // Chat states
  const [activeChatUser, setActiveChatUser] = useState<any | null>(null);
  const [chatMessages, setChatMessages] = useState<any[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const socketRef = useRef<Socket | null>(null);


  useEffect(() => {
    (window as any).activeChatUserId = activeChatUser?.id;
    return () => {
      (window as any).activeChatUserId = undefined;
    };
  }, [activeChatUser]);

  const [unreadChatSenders, setUnreadChatSenders] = useState<string[]>([]);
  const [unreadTourSenders, setUnreadTourSenders] = useState<string[]>([]);
  const [unreadTourChats, setUnreadTourChats] = useState<string[]>([]);

  const hasNotifications = unreadChatSenders.length > 0 || unreadTourChats.length > 0 || unreadTourSenders.length > 0 || receivedRequests.length > 0;

  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [attachedLocation, setAttachedLocation] = useState<{ latitude: number; longitude: number } | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [isLocating, setIsLocating] = useState(false);

  // Emergency share states
  const [sharingTour, setSharingTour] = useState<any | null>(null);
  const [shareStatus, setShareStatus] = useState<any | null>(null);
  const [loadingShare, setLoadingShare] = useState(false);

  const handleNavigateToItinerary = (tour: any) => {
    let targetLegId = null;

    if (tour?.legs && tour.legs.length > 0) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      for (const leg of tour.legs) {
        const rawStart = leg.startDate || leg.plannedStart || leg.date;
        const rawEnd = leg.endDate || leg.plannedEnd || leg.date;

        if (rawStart) {
          const startBound = new Date(rawStart);
          startBound.setHours(0, 0, 0, 0);

          const endBound = rawEnd ? new Date(rawEnd) : new Date(rawStart);
          endBound.setHours(23, 59, 59, 999);

          if (today >= startBound && today <= endBound) {
            targetLegId = leg.id;
            break;
          }
        }
      }

      if (!targetLegId) {
        targetLegId = tour.legs[0].id;
      }
    }

    if (targetLegId) {
      sessionStorage.setItem('defaultExpandedLegId', targetLegId);
    }
    onViewTour(tour.id, 'dashboard');
  };

  const handleOpenShareModal = async (tour: any) => {
    setSharingTour(tour);
    setShareStatus(null);
    setLoadingShare(true);
    try {
      const token = localStorage.getItem('token');
      const res = await fetch(`/api/v1/tours/${tour.id}/share`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (res.ok) {
        const data = await res.json();
        setShareStatus(data);
      }
    } catch (e) {
      console.error('Error fetching share status:', e);
    } finally {
      setLoadingShare(false);
    }
  };

  const handleEmergencyShare = async (tour: any) => {
    try {
      setLoadingShare(true);
      // Get current location
      const position = await new Promise<GeolocationCoordinates>((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(
          (pos) => resolve(pos.coords),
          (err) => reject(err),
          { enableHighAccuracy: true, timeout: 5000 }
        );
      });

      // Send location message to tour chat
      const token = localStorage.getItem('token');
      const message = `📍 Vị trí hiện tại: ${position.latitude.toFixed(6)}, ${position.longitude.toFixed(6)}\n🔗 Google Maps: https://maps.google.com/?q=${position.latitude},${position.longitude}`;

      const res = await fetch(`/api/v1/tours/${tour.id}/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ content: message })
      });

      if (res.ok) {
        notify({
          title: 'Thành công',
          message: 'Đã gửi vị trí hiện tại cho nhóm',
          type: 'success'
        });
      } else {
        notify({
          title: 'Lỗi',
          message: 'Không thể gửi vị trí',
          type: 'error'
        });
      }
    } catch (e) {
      console.error('Error sharing location:', e);
      notify({
        title: 'Lỗi',
        message: 'Không thể lấy vị trí hiện tại',
        type: 'error'
      });
    } finally {
      setLoadingShare(false);
    }
  };

  const handleToggleShare = async (isEnabled: boolean) => {
    if (!sharingTour) return;
    try {
      const token = localStorage.getItem('token');
      const res = await fetch(`/api/v1/tours/${sharingTour.id}/share`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ isEnabled })
      });
      if (res.ok) {
        const data = await res.json();
        setShareStatus(data);
        notify({
          title: 'Thành công',
          message: isEnabled ? t('emergencySharingEnabled') : t('emergencySharingDisabled'),
          type: 'success'
        });
      }
    } catch (e) {
      console.error(e);
    }
  };

  const handleTakeCameraPhoto = async (tour: any) => {
    if (cameraInputRef.current) {
      cameraInputRef.current.click();
      // Store tour ID for later processing
      (cameraInputRef.current as any).dataset.tourId = tour.id;
    }
  };

  const handleCameraFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const tourId = (event.target as any).dataset.tourId;
      // Get current location if available
      try {
        setIsLocating(true);
        const position = await new Promise<GeolocationCoordinates>((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(
            (pos) => resolve(pos.coords),
            (err) => reject(err),
            { enableHighAccuracy: true, timeout: 5000 }
          );
        });
        setAttachedLocation({ latitude: position.latitude, longitude: position.longitude });
      } catch (e) {
        console.log('Could not get location:', e);
      }
      setIsLocating(false);

      // ── OFFLINE GUARD ──────────────────────────────────────────────────────────
      if (!navigator.onLine) {
        try {
          const token = localStorage.getItem('token') || '';
          const formFields: Record<string, string> = {};
          if (attachedLocation) {
            formFields['latitude']  = attachedLocation.latitude.toString();
            formFields['longitude'] = attachedLocation.longitude.toString();
          }

          await queueOfflineUpload({
            endpoint:  `${BACKEND_URL}/api/v1/tours/${tourId}/photos`,
            authToken: token,
            fileBlob:  file,
            fileName:  file.name,
            formFields,
          });

          notify({
            title:   'Ảnh đã được lưu tạm ngoại tuyến 📦',
            message: 'Kết nối lại mạng, ảnh sẽ tự động được tải lên tour.',
            type: 'info',
          });
        } catch (err) {
          notify({ title: 'Lỗi', message: 'Không thể lưu ảnh ngoại tuyến.', type: 'error' });
        } finally {
          if (cameraInputRef.current) cameraInputRef.current.value = '';
        }
        return;
      }
      // ── ONLINE PATH ───────────────────────────────────────────────────────────────
      // Upload photo to tour
      setIsUploading(true);
      try {
        const token = localStorage.getItem('token');
        const formData = new FormData();
        formData.append('images', file);
        if (attachedLocation) {
          formData.append('latitude', attachedLocation.latitude.toString());
          formData.append('longitude', attachedLocation.longitude.toString());
        }

        const res = await fetch(`/api/v1/tours/${tourId}/photos`, {
          method: 'POST',
          headers: { 'Authorization': `Bearer ${token}` },
          body: formData
        });

        if (res.ok) {
          notify({
            title: 'Thành công',
            message: 'Đã upload ảnh vào thư viện tour',
            type: 'success'
          });
          // Clear input
          if (cameraInputRef.current) cameraInputRef.current.value = '';
        } else {
          notify({
            title: 'Lỗi',
            message: 'Không thể upload ảnh',
            type: 'error'
          });
        }
      } catch (e) {
        console.error('Upload error:', e);
        notify({
          title: 'Lỗi',
          message: 'Lỗi upload ảnh',
          type: 'error'
        });
      } finally {
        setIsUploading(false);
      }
    }
  };

  const fileInputRef = useRef<HTMLInputElement>(null);
  const cameraInputRef = useRef<HTMLInputElement>(null);

  const [isMobile, setIsMobile] = useState(window.innerWidth < 768);

  const [muteNotifications, setMuteNotifications] = useState<boolean>(() => {
    return localStorage.getItem('muteNotifications') === 'true';
  });
  const muteNotificationsRef = useRef(muteNotifications);
  const [mobileShowDetail, setMobileShowDetail] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);



  const isMemberOfMyTours = (senderId: string) => {
    if (!publicTours) return false;
    const userTours = publicTours.filter(tour =>
      tour.participants?.some((p: any) => p.userId === user?.id)
    );
    return userTours.some(tour =>
      tour.participants?.some((p: any) => p.userId === senderId && p.userId !== user?.id)
    );
  };

  // Compress image to 2K (max 2048px longest side)
  const compressImageTo2K = (file: File): Promise<Blob> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (event) => {
        const img = new Image();
        img.src = event.target?.result as string;
        img.onload = () => {
          const MAX_DIM = 2048;
          let width = img.width;
          let height = img.height;

          if (width > MAX_DIM || height > MAX_DIM) {
            if (width > height) {
              height = Math.round((height * MAX_DIM) / width);
              width = MAX_DIM;
            } else {
              width = Math.round((width * MAX_DIM) / height);
              height = MAX_DIM;
            }
          }

          const canvas = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext('2d');
          if (!ctx) {
            resolve(file);
            return;
          }
          ctx.drawImage(img, 0, 0, width, height);
          canvas.toBlob(
            (blob) => {
              if (blob) {
                resolve(blob);
              } else {
                resolve(file);
              }
            },
            'image/jpeg',
            0.85
          );
        };
        img.onerror = (err) => reject(err);
      };
      reader.onerror = (err) => reject(err);
    });
  };

  // Upload image to backend
  const uploadImage = async (file: File): Promise<string | null> => {
    try {
      setIsUploading(true);
      const compressedBlob = await compressImageTo2K(file);
      const formData = new FormData();
      formData.append('image', compressedBlob, 'compressed.jpg');

      const res = await fetch('/api/v1/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: formData
      });

      if (res.ok) {
        const data = await res.json();
        return data.url;
      }
      return null;
    } catch (err) {
      console.error('Lỗi upload ảnh:', err);
      return null;
    } finally {
      setIsUploading(false);
    }
  };

  // Handle Location Sharing
  const handleGetLocation = () => {
    if (!navigator.geolocation) {
      notify({
        title: 'Không hỗ trợ',
        message: 'Trình duyệt của bạn không hỗ trợ định vị GPS.',
        type: 'error'
      });
      return;
    }

    setIsLocating(true);
    navigator.geolocation.getCurrentPosition(
      (position) => {
        setAttachedLocation({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        });
        notify({
          title: 'Gắn vị trí thành công',
          message: 'Vị trí hiện tại đã được đính kèm vào tin nhắn.',
          type: 'success'
        });
        setIsLocating(false);
      },
      (error) => {
        console.error('Lỗi định vị:', error);
        notify({
          title: 'Lỗi GPS',
          message: 'Không thể lấy vị trí hiện tại của bạn. Hãy kiểm tra quyền truy cập.',
          type: 'error'
        });
        setIsLocating(false);
      },
      { enableHighAccuracy: true, timeout: 10000 }
    );
  };

  // Download image file helper
  const handleDownloadImage = async (url: string, id: string) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const blobUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = `chat-photo-${id}.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
    } catch (error) {
      console.error('Lỗi tải ảnh:', error);
      window.open(url, '_blank');
    }
  };

  const handleSelectTab = (tab: 'tours' | 'connections' | 'photos' | 'chats') => {
    setActiveTab(tab);
    if (tab === 'tours') {
      setUnreadTourSenders([]);
      setUnreadTourChats([]);
    }
    if (window.innerWidth < 768) {
      setMobileShowDetail(true);
    }
  };

  // Fetch connections, tours, and photos on mount
  useEffect(() => {
    Promise.all([
      fetchPublicTours().catch(err => {
        console.error('[MemberDashboard] fetchPublicTours failed:', err.message);
        // If fetch fails due to anonymous user rejection, don't crash
        // The page is already loaded
      }),
      fetchConnections(),
      fetchPhotos()
    ]);
  }, []);

  const fetchConnectionsRef = useRef<() => Promise<void>>(null as any);
  const fetchPublicToursRef = useRef<() => Promise<void>>(null as any);
  const isMemberOfMyToursRef = useRef<(senderId: string) => boolean>(null as any);

  useEffect(() => {
    fetchConnectionsRef.current = fetchConnections;
    fetchPublicToursRef.current = fetchPublicTours;
    isMemberOfMyToursRef.current = isMemberOfMyTours;
    muteNotificationsRef.current = muteNotifications;
  });

  // Socket connection for realtime messaging
  useEffect(() => {
    if (!user?.id) return;

    // Connect to WebSocket: absolute URL on native, relative (Vite proxy) on web
    const socket = Capacitor.isNativePlatform()
      ? io(BACKEND_URL)
      : io();
    socketRef.current = socket;

    socket.on('connect', () => {
      console.log('[WS] MemberDashboard connected:', socket.id);
      socket.emit('joinUser', user.id);
    });

    const handleMessageReceived = (message: any) => {
      // Check against window-global activeChatUserId so stale closure doesn't block updates
      const activeChatUserId = (window as any).activeChatUserId;
      if (activeChatUserId && (message.senderId === activeChatUserId || message.receiverId === activeChatUserId)) {
        setChatMessages(prev => [...prev, message]);
      } else {
        // Add to unread states
        setUnreadChatSenders(prev => prev.includes(message.senderId) ? prev : [...prev, message.senderId]);
        if (isMemberOfMyToursRef.current(message.senderId)) {
          setUnreadTourSenders(prev => prev.includes(message.senderId) ? prev : [...prev, message.senderId]);
        }
      }
    };

    socket.on('messageReceived', handleMessageReceived);

    socket.on('connectionAccepted', () => {
      fetchConnectionsRef.current();
    });

    socket.on('tourMessageNotification', (data: any) => {
      setUnreadTourChats(prev => prev.includes(data.tourId) ? prev : [...prev, data.tourId]);
    });

    socket.on('joinRequestAccepted', () => {
      fetchPublicToursRef.current();
    });

    return () => {
      socket.disconnect();
    };
  }, [user?.id]);

  // Autoscroll chat to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatMessages]);

  const getHeaders = () => ({
    'Authorization': `Bearer ${localStorage.getItem('token')}`,
    'Content-Type': 'application/json'
  });

  const fetchConnections = async () => {
    try {
      const res = await fetch('/api/v1/connections', { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        // Defensive Array.isArray guards — API may return objects or null on error
        setConnections(Array.isArray(data.connections) ? data.connections : []);
        setReceivedRequests(Array.isArray(data.receivedRequests) ? data.receivedRequests : []);
        setSentRequests(Array.isArray(data.sentRequests) ? data.sentRequests : []);
      }
    } catch (err) {
      console.error('Lỗi khi tải danh sách kết nối:', err);
      // Ensure state is always a clean array even on network failures
      setConnections([]);
      setReceivedRequests([]);
      setSentRequests([]);
    }
  };

  const fetchPhotos = async () => {
    try {
      const res = await fetch('/api/v1/users/me/photos', { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        // Defensive guard — API may return { photos: [] } or null
        setPhotos(Array.isArray(data) ? data : (Array.isArray(data?.photos) ? data.photos : []));
      }
    } catch (err) {
      console.error('Lỗi tải ảnh cá nhân:', err);
      setPhotos([]);
    }
  };

  // Search system users
  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      if (searchQuery.trim().length >= 2) {
        performUserSearch();
      } else {
        setSearchResults([]);
      }
    }, 400);

    return () => clearTimeout(delayDebounce);
  }, [searchQuery]);

  const performUserSearch = async () => {
    setSearchingUsers(true);
    try {
      const res = await fetch(`/api/v1/users?q=${encodeURIComponent(searchQuery)}`, { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        // Defensive guard — search endpoint may return { users: [] } or plain array
        setSearchResults(Array.isArray(data) ? data : (Array.isArray(data?.users) ? data.users : []));
      }
    } catch (err) {
      console.error('Lỗi tìm kiếm thành viên:', err);
    } finally {
      setSearchingUsers(false);
    }
  };

  // Send a connection request
  const handleSendConnectionRequest = async (receiverId: string) => {
    try {
      const res = await fetch('/api/v1/connections', {
        method: 'POST',
        headers: getHeaders(),
        body: JSON.stringify({ receiverId })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Gửi lời mời thất bại.');

      notify({
        title: 'Thành công',
        message: 'Đã gửi lời mời kết nối thành công.',
        type: 'success'
      });
      fetchConnections();
      // Refresh search results to show pending status
      performUserSearch();
    } catch (err: any) {
      notify({
        title: 'Lỗi',
        message: err.message,
        type: 'error'
      });
    }
  };

  // Accept or Reject connection request
  const handleUpdateConnectionStatus = async (connId: string, status: 'ACCEPTED' | 'REJECTED') => {
    try {
      const res = await fetch(`/api/v1/connections/${connId}`, {
        method: 'PATCH',
        headers: getHeaders(),
        body: JSON.stringify({ status })
      });
      if (res.ok) {
        notify({
          title: 'Thành công',
          message: status === 'ACCEPTED' ? 'Đã chấp nhận kết nối.' : 'Đã từ chối kết nối.',
          type: 'success'
        });
        fetchConnections();
      }
    } catch (err) {
      console.error('Lỗi cập nhật kết nối:', err);
    }
  };

  // Change classification: FRIEND <-> FAMILY
  const handleChangeConnectionType = async (connId: string, type: 'FRIEND' | 'FAMILY') => {
    try {
      const res = await fetch(`/api/v1/connections/${connId}`, {
        method: 'PATCH',
        headers: getHeaders(),
        body: JSON.stringify({ type })
      });
      if (res.ok) {
        notify({
          title: 'Đã cập nhật',
          message: `${t('changeConnectionType')}${type === 'FAMILY' ? t('familyGroup') : t('friends')}.`,
          type: 'success'
        });
        fetchConnections();
      }
    } catch (err) {
      console.error('Lỗi chuyển nhóm kết nối:', err);
    }
  };

  // Remove connection
  const handleRemoveConnection = async (connId: string, targetName: string) => {
    const isConfirmed = await confirm({
      title: t('disconnectTitle'),
      message: `${t('disconnectConfirm')} ${targetName}?`
    });

    if (isConfirmed) {
      try {
        const res = await fetch(`/api/v1/connections/${connId}`, {
          method: 'DELETE',
          headers: getHeaders()
        });
        if (res.ok) {
          notify({
            title: 'Thành công',
            message: t('disconnectSuccess'),
            type: 'success'
          });
          fetchConnections();
          if (activeChatUser && connections.find(c => c.id === connId)?.targetUser?.id === activeChatUser.id) {
            setActiveChatUser(null);
          }
        }
      } catch (err) {
        console.error(t('disconnectError'), err);
      }
    }
  };

  // Fetch chat messages
  const handleSelectChatUser = async (targetUser: any) => {
    setActiveChatUser(targetUser);
    setUnreadChatSenders(prev => prev.filter(id => id !== targetUser.id));
    setUnreadTourSenders(prev => prev.filter(id => id !== targetUser.id));
    setChatMessages([]);
    try {
      const res = await fetch(`/api/v1/messages/${targetUser.id}`, { headers: getHeaders() });
      if (res.ok) {
        const data = await res.json();
        setChatMessages(data || []);
      }
    } catch (err) {
      console.error('Lỗi tải tin nhắn:', err);
    }
  };

  // Send chat message
  const handleSendMessage = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!newMessage.trim() && !selectedImage && !attachedLocation) return;
    if (!activeChatUser) return;

    let attachmentUrl = undefined;
    if (selectedImage) {
      attachmentUrl = await uploadImage(selectedImage);
      if (!attachmentUrl) {
        notify({
          title: 'Lỗi',
          message: 'Không thể tải ảnh đính kèm lên server.',
          type: 'error'
        });
        return;
      }
    }

    const payload = {
      receiverId: activeChatUser.id,
      content: newMessage,
      attachmentUrl,
      latitude: attachedLocation?.latitude,
      longitude: attachedLocation?.longitude
    };

    setNewMessage('');
    setSelectedImage(null);
    setImagePreview(null);
    setAttachedLocation(null);

    try {
      const res = await fetch('/api/v1/messages', {
        method: 'POST',
        headers: getHeaders(),
        body: JSON.stringify(payload)
      });
      if (res.ok) {
        const data = await res.json();
        setChatMessages(prev => [...prev, data]);
      } else {
        notify({
          title: 'Lỗi',
          message: 'Không thể gửi tin nhắn.',
          type: 'error'
        });
      }
    } catch (err) {
      console.error('Lỗi gửi tin nhắn:', err);
    }
  };



  // Filter tours where the current logged-in user is a participant
  const myTours = React.useMemo(() => {
    if (!publicTours) return [];
    return publicTours.filter(tour =>
      tour.participants?.some((p: any) => p.userId === user?.id)
    );
  }, [publicTours, user?.id]);

  // Check relationship status for query results
  const getConnectionStatusText = (targetId: string) => {
    const isConnected = connections.find(c => c.targetUser?.id === targetId);
    if (isConnected) {
      return isConnected.type === 'FAMILY' ? t('familyGroup') : t('friends');
    }
    const isPendingReceived = receivedRequests.find(r => r.requester?.id === targetId);
    if (isPendingReceived) return 'Chờ bạn duyệt';

    const isPendingSent = sentRequests.find(s => s.receiver?.id === targetId);
    if (isPendingSent) return 'Đã gửi yêu cầu';

    return null;
  };

  // Helper function to render a user's initials avatar
  const renderInitialsAvatar = (name: string, sizeClass = 'w-10 h-10 text-sm') => {
    const initials = name
      ? name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase()
      : 'U';
    return (
      <div className={`${sizeClass} rounded-full bg-gradient-to-tr from-indigo-500 via-purple-500 to-pink-500 flex items-center justify-center font-black text-white shadow-md border-2 border-white`}>
        {initials}
      </div>
    );
  };

  // Define mobile back button handler
  const handleMobileBack = () => {
    if (activeTab === 'chats' && activeChatUser) {
      setActiveChatUser(null);
    } else {
      setMobileShowDetail(false);
    }
  };

  const showMobileHeader = isMobile && mobileShowDetail && activeTab !== 'photos' && !(activeTab === 'chats' && activeChatUser);

  if (isMobile && !mobileShowDetail) {
    return (
      <div className="h-screen w-full bg-slate-950 text-white flex flex-col font-sans overflow-y-auto">
        {/* User Card */}
        <div className="p-6 border-b border-slate-900 flex flex-col items-center text-center bg-slate-900/30">
          <div className="relative mb-3">
            {user?.avatar ? (
              <img
                src={user.avatar}
                alt={user.name}
                className="w-20 h-20 rounded-full object-cover border-4 border-slate-800 shadow-xl"
              />
            ) : (
              renderInitialsAvatar(user?.name || 'User', 'w-20 h-20 text-2xl')
            )}
            <button
              type="button"
              onClick={() => {
                const newVal = !muteNotifications;
                setMuteNotifications(newVal);
                localStorage.setItem('muteNotifications', String(newVal));
                notify({
                  title: newVal ? 'Đã tắt thông báo' : 'Đã bật thông báo',
                  message: newVal ? 'Bạn sẽ không nhận được âm thanh và thông báo đẩy.' : 'Bạn sẽ nhận được thông báo khi có tin nhắn mới.',
                  type: 'info'
                });
              }}
              className={`absolute -bottom-1 -right-1 p-1.5 rounded-full border shadow-md transition-all active:scale-95 z-20 ${muteNotifications
                ? 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
                : 'bg-indigo-650 border-indigo-500 text-white hover:bg-indigo-600'
                }`}
              title={muteNotifications ? "Bật thông báo đẩy" : "Tắt thông báo đẩy"}
            >
              {muteNotifications ? (
                <BellOff className="w-3.5 h-3.5" />
              ) : (
                <Bell className={`w-3.5 h-3.5 text-white ${hasNotifications ? 'animate-ring' : ''}`} />
              )}
            </button>
          </div>
          <h2 className="text-lg font-black tracking-tight text-white/95">
            {user?.name || 'Thành viên'}
          </h2>
          <p className="text-xs text-slate-400 mt-0.5 max-w-[200px] truncate">{user?.email}</p>
          {user?.isAdmin && (
            <span className="mt-2 px-2.5 py-0.5 bg-indigo-900/40 text-indigo-300 border border-indigo-700/50 rounded-full text-[10px] font-black uppercase tracking-wider flex items-center gap-1">
              <Shield className="w-3 h-3" /> Quản trị viên
            </span>
          )}
        </div>

        {/* Mobile Language & Theme Selectors */}
        <div className="px-6 py-4 flex flex-col gap-3 border-b border-slate-900 bg-slate-900/10 shrink-0">
          <div className="flex items-center justify-between gap-2">
            <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">{t('languageSelect') || 'Ngôn ngữ'}</span>
            <select
              value={lang}
              onChange={(e) => changeLanguage(e.target.value as any)}
              className="bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs font-bold focus:outline-none cursor-pointer"
            >
              <option value="vi">Tiếng Việt</option>
              <option value="en">English</option>
              <option value="zh">中文</option>
            </select>
          </div>
          <div className="flex items-center justify-between gap-2">
            <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">{t('themeSelect') || 'Giao diện'}</span>
            <select
              value={theme}
              onChange={(e) => changeTheme(e.target.value as any)}
              className="bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs font-bold focus:outline-none cursor-pointer"
            >
              <option value="light">{t('themeLight') || 'Sáng'}</option>
              <option value="dark">{t('themeDark') || 'Tối'}</option>
              <option value="system">{t('themeSystem') || 'Hệ thống'}</option>
            </select>
          </div>
        </div>

        {/* Explore Map Quick Button */}
        <div className="p-4 border-b border-slate-900 flex flex-col gap-2">
          <button
            onClick={onExploreTours}
            className="w-full py-4 px-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl font-bold flex items-center justify-center gap-2 shadow-lg active:scale-98 transition-all"
          >
            <Compass className="w-5 h-5 animate-spin-slow" />
            {t('exploreTourMap')}
          </button>

          <a
            href={`${BACKEND_URL}/downloads/yotrip-latest.apk`}
            download="yotrip.apk"
            className="w-full py-3 px-4 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-2xl font-bold flex items-center justify-center gap-2 shadow-md active:scale-95 transition-all text-xs text-center"
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 text-green-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v1m-4-4l-4 4m0 0l-4-4m4 4V4" />
            </svg>
            <span>Tải ứng dụng Android (APK)</span>
          </a>
        </div>

        {/* Menu Items List */}
        <div className="flex-1 p-4 flex flex-col gap-3">
          <button
            onClick={() => handleSelectTab('tours')}
            className={`w-full p-4 hover:bg-slate-900 text-white rounded-2xl flex items-center justify-between font-bold active:scale-98 transition-all border ${activeTab === 'tours'
              ? 'bg-indigo-900/40 border-indigo-500/40'
              : 'bg-slate-850/80 border-slate-700/80'
              }`}
          >
            <div className="flex items-center gap-3">
              <Compass className="w-5 h-5 text-indigo-400" />
              <div className="flex flex-col text-left">
                <span className="text-sm flex items-center gap-1.5">
                  {t('myItineraries')}
                  {(unreadTourSenders.length > 0 || unreadTourChats.length > 0) && (
                    <span className="w-2 h-2 rounded-full bg-indigo-500 animate-pulse" title="Có tin nhắn mới"></span>
                  )}
                </span>
                <span className="text-[10px] font-medium text-slate-400">{t('toursManagementDesc')}</span>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              <span className="bg-slate-800 px-2.5 py-0.5 text-xs rounded-full text-white/90 font-bold border border-slate-700">
                {myTours.length}
              </span>
              <ChevronRight className="w-4 h-4 text-slate-500" />
            </div>
          </button>

          <button
            onClick={() => handleSelectTab('photos')}
            className={`w-full p-4 hover:bg-slate-900 text-white rounded-2xl flex items-center justify-between font-bold active:scale-98 transition-all border ${activeTab === 'photos'
              ? 'bg-indigo-900/40 border-indigo-500/40'
              : 'bg-slate-850/80 border-slate-700/80'
              }`}
          >
            <div className="flex items-center gap-3">
              <ImageIcon className="w-5 h-5 text-indigo-400" />
              <div className="flex flex-col text-left">
                <span className="text-sm">{t('photoGallery')}</span>
                <span className="text-[10px] font-medium text-slate-400">{t('photoGalleryDesc')}</span>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              <span className="bg-slate-800 px-2.5 py-0.5 text-xs rounded-full text-slate-350 font-bold border border-slate-700">
                {photos.length}
              </span>
              <ChevronRight className="w-4 h-4 text-slate-500" />
            </div>
          </button>
        </div>

        {/* Bottom Menu Items */}
        <div className="p-4 flex flex-col gap-3">
          <button
            onClick={() => handleSelectTab('connections')}
            className={`w-full p-4 hover:bg-slate-900 text-white rounded-2xl flex items-center justify-between font-bold active:scale-98 transition-all border ${activeTab === 'connections'
              ? 'bg-indigo-900/40 border-indigo-500/40'
              : 'bg-slate-900/60 border-slate-800/60'
              }`}
          >
            <div className="flex items-center gap-3">
              <Users className="w-5 h-5 text-indigo-400" />
              <div className="flex flex-col text-left">
                <span className="text-sm">{t('friendsList')}</span>
                <span className="text-[10px] font-medium text-slate-400">{t('manageFriendsDesc')}</span>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              {receivedRequests.length > 0 && (
                <span className="bg-rose-600 px-2 py-0.5 text-[10px] rounded-full text-white font-bold animate-pulse">
                  {receivedRequests.length}
                </span>
              )}
              <span className="bg-slate-800 px-2.5 py-0.5 text-xs rounded-full text-slate-350 font-bold border border-slate-700">
                {connections.length}
              </span>
              <ChevronRight className="w-4 h-4 text-slate-500" />
            </div>
          </button>

          <button
            onClick={() => handleSelectTab('chats')}
            className={`w-full p-4 hover:bg-slate-900 text-white rounded-2xl flex items-center justify-between font-bold active:scale-98 transition-all border ${activeTab === 'chats'
              ? 'bg-indigo-900/40 border-indigo-500/40'
              : 'bg-slate-900/60 border-slate-800/60'
              }`}
          >
            <div className="flex items-center gap-3">
              <MessageSquare className="w-5 h-5 text-indigo-400" />
              <div className="flex flex-col text-left">
                <span className="text-sm flex items-center gap-1.5">
                  Trò chuyện trực tiếp
                  {unreadChatSenders.length > 0 && (
                    <span className="bg-rose-600 px-2 py-0.5 text-[9px] rounded-full text-white font-black animate-bounce shadow-md">
                      {unreadChatSenders.length}
                    </span>
                  )}
                </span>
                <span className="text-[10px] font-medium text-slate-400">Nhắn tin trực tiếp với kết nối</span>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              <ChevronRight className="w-4 h-4 text-slate-500" />
            </div>
          </button>
        </div>

        {/* Horizontal Divider ---- */}
        <hr className="border-slate-800/80 mx-4 my-1" />

        {/* Logout Section */}
        <div className="p-4">
          <button
            onClick={onLogout}
            className="w-full py-3.5 px-4 bg-slate-900/40 hover:bg-rose-950/40 hover:text-rose-450 text-rose-400 rounded-2xl text-sm font-bold flex items-center justify-center gap-2 border border-slate-800 transition-all"
          >
            <LogOut className="w-4 h-4" />
            Đăng xuất
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="h-auto min-h-dvh w-full bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 text-white flex flex-col md:flex-row p-3 sm:p-6 gap-4 sm:gap-6 overflow-x-hidden">

      {/* Background Glow */}
      <div className="hidden md:block absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-500/5 rounded-full blur-[120px] pointer-events-none z-0"></div>
      <div className="hidden md:block absolute bottom-0 left-0 w-[500px] h-[500px] bg-purple-500/5 rounded-full blur-[120px] pointer-events-none z-0"></div>

      <div className={`w-full relative z-10 flex overflow-hidden transition-all duration-350 ${isMobile
        ? 'flex-col h-full bg-slate-950'
        : 'max-w-7xl h-[90vh] bg-slate-900/30 border border-slate-800/80 shadow-2xl rounded-3xl backdrop-blur-md'
        }`}>

        {/* Mobile Detail Header: Only on Mobile detail mode */}
        {showMobileHeader && (
          <div className="px-4 py-3.5 bg-slate-900 border-b border-slate-800/80 flex items-center gap-3 shrink-0">
            <button
              onClick={handleMobileBack}
              className="p-1.5 hover:bg-slate-800 rounded-lg text-slate-400 hover:text-white transition-colors"
            >
              <ChevronLeft className="w-6 h-6" />
            </button>
            <div>
              <h2 className="text-sm font-black uppercase text-white tracking-wider">
                {activeTab === 'tours' && t('myItineraries')}
                {activeTab === 'connections' && t('friendsList')}
                {activeTab === 'chats' && 'Trò chuyện trực tiếp'}
              </h2>
            </div>
          </div>
        )}

        {/* Left Sidebar Menu (Desktop only) */}
        {!isMobile && (
          <aside className="w-80 bg-slate-900/60 backdrop-blur-md border-r border-slate-800/80 flex flex-col shrink-0">
            {/* User Card */}
            <div className="p-6 border-b border-slate-800/60 flex flex-col items-center text-center">
              <div className="relative mb-3 group">
                {user?.avatar ? (
                  <img
                    src={user.avatar}
                    alt={user.name}
                    className="w-20 h-20 rounded-full object-cover border-4 border-slate-700/50 shadow-xl group-hover:border-indigo-500 transition-all duration-300"
                  />
                ) : (
                  renderInitialsAvatar(user?.name || 'User', 'w-20 h-20 text-2xl')
                )}
                {user?.isAdmin && (
                  <span className="absolute -top-1 -right-1 bg-indigo-600 text-[9px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full text-white shadow-md border border-indigo-500">
                    Admin
                  </span>
                )}
                <button
                  type="button"
                  onClick={() => {
                    const newVal = !muteNotifications;
                    setMuteNotifications(newVal);
                    localStorage.setItem('muteNotifications', String(newVal));
                    notify({
                      title: newVal ? 'Đã tắt thông báo' : 'Đã bật thông báo',
                      message: newVal ? 'Bạn sẽ không nhận được âm thanh và thông báo đẩy.' : 'Bạn sẽ nhận được thông báo khi có tin nhắn mới.',
                      type: 'info'
                    });
                  }}
                  className={`absolute -bottom-1 -right-1 p-1.5 rounded-full border shadow-md transition-all active:scale-90 z-20 ${muteNotifications
                    ? 'bg-slate-900 border-slate-800 text-slate-400 hover:text-slate-200'
                    : 'bg-indigo-650 border-indigo-500 text-white hover:bg-indigo-600'
                    }`}
                  title={muteNotifications ? "Bật thông báo đẩy" : "Tắt thông báo đẩy"}
                >
                  {muteNotifications ? (
                    <BellOff className="w-3.5 h-3.5" />
                  ) : (
                    <Bell className={`w-3.5 h-3.5 text-white ${hasNotifications ? 'animate-ring' : ''}`} />
                  )}
                </button>
              </div>
              <h2 className="text-base font-black text-white">{user?.name || 'Thành viên'}</h2>
              <p className="text-xs text-slate-400 mt-0.5 max-w-[200px] truncate">{user?.email}</p>
              {user?.isAdmin && (
                <span className="mt-2 px-2.5 py-0.5 bg-indigo-900/40 text-indigo-300 border border-indigo-700/50 rounded-full text-[10px] font-black uppercase tracking-wider flex items-center gap-1">
                  <Shield className="w-3 h-3" /> Quản trị viên
                </span>
              )}
            </div>

            {/* Desktop Language & Theme Selectors */}
            <div className="px-6 py-4 flex flex-col gap-3 border-b border-slate-800/60 shrink-0">
              <div className="flex items-center justify-between gap-2">
                <span className="text-[10px] font-black uppercase tracking-widest text-slate-500">{t('languageSelect') || 'Ngôn ngữ'}</span>
                <select
                  value={lang}
                  onChange={(e) => changeLanguage(e.target.value as any)}
                  className="bg-slate-950 border border-slate-800 text-white rounded-xl px-2.5 py-1.5 text-xs font-bold focus:outline-none cursor-pointer"
                >
                  <option value="vi">Tiếng Việt</option>
                  <option value="en">English</option>
                  <option value="zh">中文</option>
                </select>
              </div>
              <div className="flex items-center justify-between gap-2">
                <span className="text-[10px] font-black uppercase tracking-widest text-slate-500">{t('themeSelect') || 'Giao diện'}</span>
                <select
                  value={theme}
                  onChange={(e) => changeTheme(e.target.value as any)}
                  className="bg-slate-950 border border-slate-800 text-white rounded-xl px-2.5 py-1.5 text-xs font-bold focus:outline-none cursor-pointer"
                >
                  <option value="light">{t('themeLight') || 'Sáng'}</option>
                  <option value="dark">{t('themeDark') || 'Tối'}</option>
                  <option value="system">{t('themeSystem') || 'Hệ thống'}</option>
                </select>
              </div>
            </div>

            {/* Quick Nav Links */}
            <div className="px-4 py-6 flex flex-col gap-2 border-b border-slate-800/60">
              <button
                onClick={onExploreTours}
                className="w-full py-3 px-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold flex items-center justify-center gap-2 shadow-lg hover:shadow-indigo-500/20 active:scale-95 transition-all duration-150"
              >
                <Compass className="w-4 h-4 animate-spin-slow" />
                Khám phá Bản đồ Tour
              </button>

              <a
                href={`${BACKEND_URL}/downloads/yotrip-latest.apk`}
                download="yotrip.apk"
                className="w-full py-2.5 px-4 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-xl font-bold flex items-center justify-center gap-2 shadow-md active:scale-95 transition-all duration-150 text-xs"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4 text-green-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                <span>Tải ứng dụng Android (APK)</span>
              </a>
            </div>

            {/* Vertical Tabs */}
            <nav className="flex-1 px-3 py-6 flex flex-col gap-1.5 overflow-y-auto">
              <button
                onClick={() => handleSelectTab('tours')}
                className={`w-full py-3 px-4 rounded-xl flex items-center justify-between text-sm font-bold transition-all duration-150 ${activeTab === 'tours'
                  ? 'bg-slate-800/80 text-white border-l-4 border-indigo-500 shadow-md'
                  : 'text-slate-400 hover:bg-slate-800/30 hover:text-slate-200'
                  }`}
              >
                <div className="flex items-center gap-3">
                  <Compass className="w-4 h-4" />
                  <span>Hành trình của tôi</span>
                  {(unreadTourSenders.length > 0 || unreadTourChats.length > 0) && (
                    <span className="w-2 h-2 rounded-full bg-indigo-500 animate-pulse" title="Có tin nhắn mới"></span>
                  )}
                </div>
                <span className="bg-slate-800/80 px-2 py-0.5 text-xs rounded-full text-slate-400 font-semibold border border-slate-700">
                  {myTours.length}
                </span>
              </button>

              <button
                onClick={() => handleSelectTab('photos')}
                className={`w-full py-3 px-4 rounded-xl flex items-center justify-between text-sm font-bold transition-all duration-150 ${activeTab === 'photos'
                  ? 'bg-slate-800/80 text-white border-l-4 border-indigo-500 shadow-md'
                  : 'text-slate-400 hover:bg-slate-800/30 hover:text-slate-200'
                  }`}
              >
                <div className="flex items-center gap-3">
                  <ImageIcon className="w-4 h-4" />
                  <span>{t('photoGallery')}</span>
                </div>
                <span className="bg-slate-800/80 px-2 py-0.5 text-xs rounded-full text-slate-400 font-semibold border border-slate-700">
                  {photos.length}
                </span>
              </button>

              {/* Spacer to push bottom items down */}
              <div className="flex-1" />

              <button
                onClick={() => handleSelectTab('chats')}
                className={`w-full py-3 px-4 rounded-xl flex items-center justify-between text-sm font-bold transition-all duration-150 ${activeTab === 'chats'
                  ? 'bg-slate-800/80 text-white border-l-4 border-indigo-500 shadow-md'
                  : 'text-slate-400 hover:bg-slate-800/30 hover:text-slate-200'
                  }`}
              >
                <div className="flex items-center gap-3">
                  <MessageSquare className="w-4 h-4" />
                  <span>Trò chuyện trực tiếp</span>
                </div>
                {unreadChatSenders.length > 0 && (
                  <span className="bg-rose-600 px-2 py-0.5 text-[10px] rounded-full text-white font-black animate-bounce shadow-md">
                    {unreadChatSenders.length}
                  </span>
                )}
              </button>

              <button
                onClick={() => handleSelectTab('connections')}
                className={`w-full py-3 px-4 rounded-xl flex items-center justify-between text-sm font-bold transition-all duration-150 ${activeTab === 'connections'
                  ? 'bg-slate-800/80 text-white border-l-4 border-indigo-500 shadow-md'
                  : 'text-slate-400 hover:bg-slate-800/30 hover:text-slate-200'
                  }`}
              >
                <div className="flex items-center gap-3">
                  <Users className="w-4 h-4" />
                  <span>{t('friendsList')}</span>
                </div>
                <div className="flex items-center gap-1.5">
                  {receivedRequests.length > 0 && (
                    <span className="bg-rose-600 px-1.5 py-0.5 text-[10px] rounded-full text-white font-bold animate-pulse">
                      {receivedRequests.length}
                    </span>
                  )}
                  <span className="bg-slate-800/80 px-2 py-0.5 text-xs rounded-full text-slate-400 font-semibold border border-slate-700">
                    {connections.length}
                  </span>
                </div>
              </button>
            </nav>

            {/* Logout Footer */}
            <div className="p-4 border-t border-slate-800/60 flex flex-col gap-3">
              <hr className="border-slate-800 border-dashed" />
              <button
                onClick={onLogout}
                className="w-full py-2.5 px-4 bg-slate-800/40 hover:bg-rose-950/40 hover:text-rose-450 text-slate-450 rounded-xl text-sm font-bold flex items-center justify-center gap-2 border border-slate-800 hover:border-rose-900/50 transition-all"
              >
                <LogOut className="w-4 h-4" />
                Đăng xuất
              </button>
            </div>
          </aside>
        )}

        {/* Main Content Area */}
        <main className="flex-1 bg-slate-950/10 flex flex-col overflow-hidden relative">
          {/* Background Glow */}
          {!isMobile && (
            <>
              <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-500/5 rounded-full blur-[120px] pointer-events-none z-0"></div>
              <div className="absolute bottom-0 left-0 w-[500px] h-[500px] bg-purple-500/5 rounded-full blur-[120px] pointer-events-none z-0"></div>
            </>
          )}

          {/* Tab content renders here */}
          <div className={`flex-1 relative z-10 flex flex-col ${activeTab === 'chats' || activeTab === 'photos'
            ? 'overflow-hidden p-0'
            : 'p-4 md:p-8 overflow-y-auto'
            }`}>

            {/* TAB 1: MY TOURS */}
            {activeTab === 'tours' && (
              <div className="animate-in fade-in slide-in-from-bottom-2 duration-300">
                <div className="flex justify-between items-center mb-6">
                  <div>
                    <h1 className="text-2xl font-black uppercase tracking-tight flex items-center gap-2 text-white">
                      <Compass className="w-6 h-6 text-indigo-500" />
                      {t('myItineraries')}
                    </h1>
                    <p className="text-xs text-slate-400 mt-1">Danh sách các chuyến đi bạn tham gia (với vai trò chủ sở hữu, quản lý hoặc thành viên).</p>
                  </div>
                </div>

                {myTours.length === 0 ? (
                  <div className="bg-slate-900/40 border border-slate-800/60 rounded-3xl p-12 text-center max-w-2xl mx-auto mt-12 flex flex-col items-center">
                    <div className="w-16 h-16 rounded-full bg-slate-800 flex items-center justify-center mb-4 text-indigo-500 border border-slate-700">
                      <Compass className="w-8 h-8" />
                    </div>
                    <h3 className="text-lg font-bold mb-1">Chưa có hành trình nào</h3>
                    <p className="text-sm text-slate-400 mb-6">Bạn chưa tham gia bất kỳ hành trình nào. Hãy bắt đầu bằng cách tìm các hành trình công khai hoặc tạo chuyến đi mới.</p>
                    <button
                      onClick={onExploreTours}
                      className="py-2.5 px-6 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-sm shadow-lg shadow-indigo-600/20 transition-all flex items-center gap-2"
                    >
                      <Compass className="w-4 h-4" /> Khám phá bản đồ tour
                    </button>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                    {myTours.map((tour) => {
                      const status = (() => {
                        const now = new Date();
                        const start = tour.startDate ? new Date(tour.startDate) : null;
                        const end = tour.endDate ? new Date(tour.endDate) : null;
                        if (end && end < now) return { color: 'gray', label: 'Đã hoàn thành', bg: 'bg-slate-800/80 border-slate-700 text-slate-400' };
                        if (start && end && start <= now && end >= now) return { color: 'red', label: 'Đang diễn ra', bg: 'bg-rose-900/30 border-rose-800/50 text-rose-300' };
                        return { color: 'green', label: 'Mới tạo / Sắp tới', bg: 'bg-emerald-900/30 border-emerald-800/50 text-emerald-300' };
                      })();

                      const participant = tour.participants?.find((p: any) => p.userId === user?.id);
                      const roleLabel = participant?.role === 'OWNER' ? 'Chủ tour' :
                        participant?.role === 'MANAGER' ? 'Quản lý' : 'Thành viên';

                      return (
                        <div
                          key={tour.id}
                          className="bg-slate-800/90 hover:bg-slate-800 border border-slate-700/60 rounded-2xl overflow-hidden transition-all duration-300 hover:shadow-xl hover:shadow-indigo-950/10 group flex flex-col h-full"
                        >
                          <div className="p-5 flex-1 flex flex-col justify-between">
                            <div>
                              <div className="flex justify-between items-start gap-2 mb-3">
                                <span className={`px-2.5 py-0.5 rounded-full text-[10px] font-black border uppercase tracking-wider ${status.bg}`}>
                                  {status.label}
                                </span>
                                <div className="flex gap-1.5 items-center">
                                  {unreadTourChats.includes(tour.id) && (
                                    <span className="px-2 py-0.5 bg-indigo-650 border border-indigo-500 rounded text-[9px] text-white font-black uppercase tracking-wider animate-pulse">
                                      Tin nhắn mới
                                    </span>
                                  )}
                                  <span className="px-2.5 py-0.5 bg-slate-900 rounded-full text-[10px] text-slate-300 border border-slate-800 font-bold">
                                    {roleLabel}
                                  </span>
                                </div>
                              </div>

                              <h3 className="text-base font-bold text-white group-hover:text-indigo-400 transition-colors line-clamp-1">
                                {tour.title}
                              </h3>

                              {tour.description && (
                                <p className="text-xs text-slate-400 line-clamp-2 mt-2 leading-relaxed italic">
                                  {tour.description}
                                </p>
                              )}

                              {/* Tags */}
                              {tour.tags && tour.tags.length > 0 && (
                                <div className="flex flex-wrap gap-1.5 mt-3">
                                  {tour.tags.map((tag: string) => (
                                    <span key={tag} className="px-2 py-0.5 bg-slate-900/60 text-slate-400 rounded-md text-[9px] font-bold border border-slate-900">
                                      {tag}
                                    </span>
                                  ))}
                                </div>
                              )}
                            </div>

                            <div className="mt-5 pt-4 border-t border-slate-700/60 flex flex-col gap-2">
                              <div className="flex items-center text-[11px] text-slate-400 gap-1.5">
                                <Calendar className="w-3.5 h-3.5 text-indigo-500" />
                                <span>
                                  {tour.startDate ? new Date(tour.startDate).toLocaleDateString('vi-VN') : 'N/A'}
                                  {' - '}
                                  {tour.endDate ? new Date(tour.endDate).toLocaleDateString('vi-VN') : 'N/A'}
                                </span>
                              </div>
                              <div className="flex flex-col gap-2 mt-2">
                                {/* Chat button - moved to top */}
                                <button
                                  onClick={() => {
                                    localStorage.setItem('tour_detail_default_tab', 'chat');
                                    setUnreadTourChats(prev => prev.filter(id => id !== tour.id));
                                    onViewTour(tour.id, 'dashboard');
                                  }}
                                  className="w-full py-2 px-2 bg-indigo-600/20 hover:bg-indigo-600 text-black-300 hover:text-white rounded-xl text-xs font-bold transition-all border border-indigo-500/30 hover:border-indigo-500 flex items-center justify-center gap-1 relative whitespace-nowrap"
                                >
                                  <MessageSquare className="w-3.5 h-3.5" />
                                  <span>Trò chuyện</span>
                                  {unreadTourChats.includes(tour.id) && (
                                    <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-rose-600 rounded-full animate-ping border border-slate-800" />
                                  )}
                                  {unreadTourChats.includes(tour.id) && (
                                    <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-rose-600 rounded-full border border-slate-800" />
                                  )}
                                </button>

                                {/* Camera + Detail buttons row */}
                                <div className="flex gap-2">
                                  <button
                                    onClick={() => handleTakeCameraPhoto(tour)}
                                    disabled={isUploading}
                                    className="flex-1 py-2 px-2 bg-green-600/20 hover:bg-green-600 text-black-300 hover:text-white rounded-xl text-xs font-bold transition-all border border-green-500/30 hover:border-green-500 flex items-center justify-center gap-1 disabled:opacity-50 disabled:cursor-not-allowed"
                                  >
                                    {isUploading ? (
                                      <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                    ) : (
                                      <Camera className="w-3.5 h-3.5" />
                                    )}
                                    <span>Chụp ảnh</span>
                                  </button>

                                  <button
                                    onClick={() => handleNavigateToItinerary(tour)}
                                    className="flex-1 py-2 px-2 bg-slate-900 hover:bg-slate-800 text-slate-850 hover:text-white rounded-xl text-xs font-bold transition-all border border-slate-800 hover:border-slate-700 flex items-center justify-center gap-1"
                                  >
                                    <span>Chi tiết hành trình</span>
                                    <ChevronRight className="w-3.5 h-3.5" />
                                  </button>
                                </div>

                                {/* Emergency Share Button - moved to bottom */}
                                <button
                                  onClick={() => handleEmergencyShare(tour)}
                                  disabled={loadingShare}
                                  className="w-full py-2 px-3 bg-rose-600/10 hover:bg-rose-600 text-rose-400 hover:text-white-500 rounded-xl text-xs font-bold transition-all border border-rose-500/20 hover:border-rose-500 flex items-center justify-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                  {loadingShare ? (
                                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                  ) : (
                                    <ShieldAlert className="w-3.5 h-3.5 text-rose-500" />
                                  )}
                                  <span>Chia sẻ vị trí khẩn cấp</span>
                                </button>
                              </div>

                              {/* Hidden camera input */}
                              <input
                                ref={cameraInputRef}
                                type="file"
                                accept="image/*"
                                capture="environment"
                                onChange={handleCameraFileSelect}
                                className="hidden"
                              />
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}

            {/* TAB 2: CONNECTIONS */}
            {activeTab === 'connections' && (
              <div className="animate-in fade-in slide-in-from-bottom-2 duration-300 flex flex-col h-full min-h-0">
                <div className="mb-6">
                  <h1 className="text-2xl font-black uppercase tracking-tight flex items-center gap-2 text-white">
                    <Users className="w-6 h-6 text-indigo-500" />
                    {t('friendsList')}
                  </h1>
                  <p className="text-xs text-slate-400 mt-1">{t('manageRelations')}</p>
                </div>

                {/* Sub-tabs for connections */}
                <div className="flex gap-2 border-b border-slate-800/60 pb-3 mb-6">
                  <button
                    onClick={() => setConnectionSubTab('list')}
                    className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all ${connectionSubTab === 'list'
                      ? 'bg-indigo-600 text-white shadow-md'
                      : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200'
                      }`}
                  >
                    Danh sách kết nối
                  </button>
                  <button
                    onClick={() => setConnectionSubTab('search')}
                    className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 ${connectionSubTab === 'search'
                      ? 'bg-indigo-600 text-white shadow-md'
                      : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200'
                      }`}
                  >
                    <Search className="w-3.5 h-3.5" /> Tìm thành viên mới
                  </button>
                  <button
                    onClick={() => setConnectionSubTab('pending')}
                    className={`px-4 py-1.5 rounded-lg text-xs font-bold transition-all relative ${connectionSubTab === 'pending'
                      ? 'bg-indigo-600 text-white shadow-md'
                      : 'text-slate-400 hover:bg-slate-800 hover:text-slate-200'
                      }`}
                  >
                    Yêu cầu chờ duyệt
                    {receivedRequests.length > 0 && (
                      <span className="absolute -top-1.5 -right-1.5 bg-rose-600 text-white text-[9px] font-black rounded-full px-1.5 py-0.5 animate-bounce shadow-md">
                        {receivedRequests.length}
                      </span>
                    )}
                  </button>
                </div>

                {/* SUB TAB CONTENT 2.1: LIST CONNECTIONS */}
                {connectionSubTab === 'list' && (
                  <div className="bg-slate-900/20 border border-slate-800/60 rounded-3xl p-6 shadow-xl overflow-y-auto">
                    {connections.length === 0 ? (
                      <div className="bg-slate-900/40 border border-slate-800/60 rounded-3xl p-12 text-center max-w-md mx-auto my-6">
                        <Users className="w-12 h-12 text-indigo-500 mx-auto mb-4" />
                        <h3 className="text-base font-bold mb-1">Chưa có kết nối nào</h3>
                        <p className="text-xs text-slate-400 mb-6">{t('noConnections')}</p>
                        <button
                          onClick={() => setConnectionSubTab('search')}
                          className="py-2 px-4 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold transition-all"
                        >
                          Tìm thành viên ngay
                        </button>
                      </div>
                    ) : (
                      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                        {connections.map((conn) => {
                          const connUser = conn.targetUser;
                          return (
                            <div
                              key={conn.id}
                              className="bg-slate-900/50 hover:bg-slate-900/70 border border-slate-800/60 rounded-2xl p-5 flex items-center justify-between transition-all"
                            >
                              <div className="flex items-center gap-3.5 min-w-0">
                                {connUser.avatar ? (
                                  <img
                                    src={connUser.avatar}
                                    alt={connUser.name}
                                    className="w-12 h-12 rounded-full object-cover border border-slate-700"
                                  />
                                ) : (
                                  renderInitialsAvatar(connUser.name, 'w-12 h-12 text-base')
                                )}
                                <div className="min-w-0">
                                  <h4 className="text-sm font-bold text-white truncate">{connUser.name}</h4>
                                  <p className="text-[10px] text-slate-400 truncate">{connUser.email}</p>
                                  <div className="mt-1.5 flex items-center gap-1.5">
                                    <span className={`px-2 py-0.5 rounded text-[8px] font-black uppercase tracking-wider border ${conn.type === 'FAMILY'
                                      ? 'bg-rose-950/40 text-rose-300 border-rose-900/50'
                                      : 'bg-indigo-950/40 text-indigo-300 border-indigo-900/50'
                                      }`}>
                                      {conn.type === 'FAMILY' ? t('familyGroup') : t('friends')}
                                    </span>
                                  </div>
                                </div>
                              </div>

                              <div className="flex flex-col items-end gap-2 shrink-0">
                                {/* Classification selector */}
                                <select
                                  value={conn.type}
                                  onChange={(e) => handleChangeConnectionType(conn.id, e.target.value as any)}
                                  className="bg-slate-800 text-slate-200 border border-slate-700/80 rounded-md text-[10px] px-2 py-1 outline-none font-bold cursor-pointer hover:bg-slate-750 transition-colors"
                                >
                                  <option value="FRIEND">{t('friends')}</option>
                                  <option value="FAMILY">Gia đình</option>
                                </select>

                                <div className="flex gap-1.5">
                                  <button
                                    onClick={() => {
                                      handleSelectChatUser(connUser);
                                      setActiveTab('chats');
                                      if (isMobile) {
                                        setMobileShowDetail(true);
                                      }
                                    }}
                                    className="p-1.5 bg-indigo-950/550 hover:bg-indigo-600 text-blue-500 hover:text-white border border-indigo-800/40 hover:border-indigo-500 rounded-lg text-xs font-bold transition-all"
                                    title="Trò chuyện"
                                  >
                                    <MessageSquare className="w-3.5 h-3.5" />
                                  </button>
                                  <button
                                    onClick={() => handleRemoveConnection(conn.id, connUser.name)}
                                    className="p-1.5 bg-rose-950/50 hover:bg-rose-600 text-rose-300 hover:text-white border border-rose-800/40 hover:border-rose-500 rounded-lg text-xs font-bold transition-all"
                                    title={t('disconnectTitle')}
                                  >
                                    <Trash2 className="w-3.5 h-3.5" />
                                  </button>
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}

                {/* SUB TAB CONTENT 2.2: SEARCH USERS */}
                {connectionSubTab === 'search' && (
                  <div className="bg-slate-900/20 border border-slate-800/60 rounded-3xl p-6 shadow-xl overflow-y-auto">
                    <div className="max-w-2xl mx-auto">
                      <div className="relative mb-6">
                        <Search className="absolute left-4 top-3.5 w-4 h-4 text-slate-400" />
                        <input
                          type="text"
                          placeholder={t('searchMembers')}
                          value={searchQuery}
                          onChange={(e) => setSearchQuery(e.target.value)}
                          className="w-full bg-slate-950 border border-slate-800/80 rounded-2xl py-3 pl-11 pr-4 text-sm text-white placeholder-slate-500 outline-none focus:border-indigo-500/80 transition-all duration-150"
                        />
                      </div>

                      {searchingUsers ? (
                        <div className="text-center py-8 text-slate-400 text-xs font-bold flex items-center justify-center gap-1.5">
                          <Clock className="w-4 h-4 animate-spin text-indigo-500" /> {t('searching')}...
                        </div>
                      ) : searchQuery.trim().length < 2 ? (
                        <div className="text-center py-12 text-slate-500 text-xs italic">
                          {t('minCharsRequired')}
                        </div>
                      ) : searchResults.length === 0 ? (
                        <div className="text-center py-12 text-slate-400 text-xs">
                          Không tìm thấy thành viên phù hợp.
                        </div>
                      ) : (
                        <div className="flex flex-col gap-3">
                          {searchResults.map((usr) => {
                            const statusText = getConnectionStatusText(usr.id);

                            return (
                              <div
                                key={usr.id}
                                className="bg-slate-900/40 border border-slate-800/60 rounded-2xl p-4 flex items-center justify-between hover:bg-slate-900/60 transition-all"
                              >
                                <div className="flex items-center gap-3">
                                  {usr.avatar ? (
                                    <img
                                      src={usr.avatar}
                                      alt={usr.name}
                                      className="w-10 h-10 rounded-full object-cover"
                                    />
                                  ) : (
                                    renderInitialsAvatar(usr.name, 'w-10 h-10 text-xs')
                                  )}
                                  <div>
                                    <h4 className="text-sm font-bold text-white">{usr.name}</h4>
                                    <p className="text-[10px] text-slate-400">{usr.email}</p>
                                  </div>
                                </div>

                                <div>
                                  {statusText ? (
                                    <span className={`px-3 py-1 rounded-lg text-xs font-bold border ${statusText === t('friends') || statusText === t('familyGroup')
                                      ? 'bg-emerald-950/30 border-emerald-900/50 text-emerald-300'
                                      : 'bg-slate-800/80 border-slate-700 text-slate-400'
                                      }`}>
                                      {statusText}
                                    </span>
                                  ) : (
                                    <button
                                      onClick={() => handleSendConnectionRequest(usr.id)}
                                      className="py-1.5 px-3.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold flex items-center gap-1.5 transition-all"
                                    >
                                      <UserPlus className="w-3.5 h-3.5" /> Kết nối
                                    </button>
                                  )}
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* SUB TAB CONTENT 2.3: PENDING REQUESTS */}
                {connectionSubTab === 'pending' && (
                  <div className="bg-slate-900/20 border border-slate-800/60 rounded-3xl p-6 shadow-xl overflow-y-auto">
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                      {/* Received Requests */}
                      <div>
                        <h3 className="text-sm font-black uppercase text-slate-400 tracking-wider mb-4 flex items-center gap-2">
                          Lời mời nhận được ({receivedRequests.length})
                        </h3>
                        {receivedRequests.length === 0 ? (
                          <div className="bg-slate-900/20 border border-slate-800/60 rounded-2xl p-6 text-center text-xs text-slate-500 italic">
                            Không có lời mời kết nối nào.
                          </div>
                        ) : (
                          <div className="flex flex-col gap-3">
                            {receivedRequests.map((req) => (
                              <div
                                key={req.id}
                                className="bg-slate-900/50 border border-slate-800/60 rounded-2xl p-4 flex items-center justify-between"
                              >
                                <div className="flex items-center gap-3">
                                  {req.requester?.avatar ? (
                                    <img
                                      src={req.requester.avatar}
                                      alt={req.requester.name}
                                      className="w-10 h-10 rounded-full object-cover"
                                    />
                                  ) : (
                                    renderInitialsAvatar(req.requester?.name || 'User', 'w-10 h-10 text-xs')
                                  )}
                                  <div>
                                    <h4 className="text-sm font-bold text-white">{req.requester?.name}</h4>
                                    <p className="text-[10px] text-slate-400">{req.requester?.email}</p>
                                  </div>
                                </div>

                                <div className="flex gap-2">
                                  <button
                                    onClick={() => handleUpdateConnectionStatus(req.id, 'ACCEPTED')}
                                    className="p-1.5 bg-emerald-950/60 hover:bg-emerald-600 border border-emerald-800/60 text-emerald-300 hover:text-white rounded-lg text-xs font-bold transition-all"
                                    title="Đồng ý"
                                  >
                                    <Check className="w-4 h-4" />
                                  </button>
                                  <button
                                    onClick={() => handleUpdateConnectionStatus(req.id, 'REJECTED')}
                                    className="p-1.5 bg-rose-950/60 hover:bg-rose-600 border border-rose-800/60 text-rose-300 hover:text-white rounded-lg text-xs font-bold transition-all"
                                    title="Từ chối"
                                  >
                                    <X className="w-4 h-4" />
                                  </button>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>

                      {/* Sent Requests */}
                      <div>
                        <h3 className="text-sm font-black uppercase text-slate-400 tracking-wider mb-4 flex items-center gap-2">
                          Yêu cầu đã gửi ({sentRequests.length})
                        </h3>
                        {sentRequests.length === 0 ? (
                          <div className="bg-slate-900/20 border border-slate-800/60 rounded-2xl p-6 text-center text-xs text-slate-500 italic">
                            Không có yêu cầu đang chờ duyệt.
                          </div>
                        ) : (
                          <div className="flex flex-col gap-3">
                            {sentRequests.map((req) => (
                              <div
                                key={req.id}
                                className="bg-slate-900/50 border border-slate-800/60 rounded-2xl p-4 flex items-center justify-between"
                              >
                                <div className="flex items-center gap-3">
                                  {req.receiver?.avatar ? (
                                    <img
                                      src={req.receiver.avatar}
                                      alt={req.receiver.name}
                                      className="w-10 h-10 rounded-full object-cover"
                                    />
                                  ) : (
                                    renderInitialsAvatar(req.receiver?.name || 'User', 'w-10 h-10 text-xs')
                                  )}
                                  <div>
                                    <h4 className="text-sm font-bold text-white">{req.receiver?.name}</h4>
                                    <p className="text-[10px] text-slate-400">{req.receiver?.email}</p>
                                  </div>
                                </div>

                                <button
                                  onClick={() => handleRemoveConnection(req.id, req.receiver?.name || '')}
                                  className="py-1 px-2.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white border border-slate-700/65 rounded-lg text-[10px] font-bold transition-all flex items-center gap-1"
                                >
                                  <X className="w-3 h-3" /> Hủy
                                </button>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* TAB 3: PERSONAL PHOTOS */}
            {activeTab === 'photos' && (
              <div className="animate-in fade-in slide-in-from-bottom-2 duration-300 flex-1 flex flex-col min-h-0 overflow-y-auto">
                <MyPhotosPage onBack={isMobile ? () => setMobileShowDetail(false) : () => setActiveTab('tours')} />
              </div>
            )}

            {/* TAB 4: REALTIME CHAT */}
            {activeTab === 'chats' && (
              <div className="flex flex-col h-[100dvh] md:h-auto w-full bg-slate-900/40 border-0 md:border border-slate-800/80 md:rounded-3xl overflow-hidden flex animate-in fade-in slide-in-from-bottom-2 duration-300">

                {/* Chats List sidebar: show if not mobile OR if mobile and no active chat user */}
                {(!isMobile || !activeChatUser) && (
                  <div className={`${isMobile ? 'w-full' : 'w-72 border-r border-slate-800/60'} bg-slate-950/25 flex flex-col shrink-0`}>
                    <div className="p-4 border-b border-slate-800/60">
                      <h3 className="text-xs font-black uppercase text-slate-400 tracking-wider">Chọn người hội thoại</h3>
                    </div>

                    <div className="flex-1 overflow-y-auto p-2 flex flex-col gap-1">
                      {connections.length === 0 ? (
                        <div className="text-center py-8 text-xs text-slate-500 italic px-4">
                          Bạn cần kết bạn trước khi có thể nhắn tin.
                        </div>
                      ) : (
                        connections.map((conn) => {
                          const connUser = conn.targetUser;
                          const isActive = activeChatUser && activeChatUser.id === connUser.id;

                          return (
                            <button
                              key={conn.id}
                              onClick={() => handleSelectChatUser(connUser)}
                              className={`w-full p-3 rounded-xl flex items-center gap-3 transition-all text-left ${isActive
                                ? 'bg-indigo-650 text-white shadow-md'
                                : 'text-slate-350 hover:bg-slate-850/40 hover:text-slate-100'
                                }`}
                            >
                              {connUser.avatar ? (
                                <img
                                  src={connUser.avatar}
                                  alt={connUser.name}
                                  className={`w-10 h-10 rounded-full object-cover ${isActive ? 'border-2 border-white' : 'border border-slate-700'}`}
                                />
                              ) : (
                                renderInitialsAvatar(connUser.name, 'w-10 h-10 text-xs')
                              )}
                              <div className="min-w-0 flex-1 flex items-center justify-between">
                                <div className="min-w-0">
                                  <span className="text-sm font-bold block truncate">{connUser.name}</span>
                                  <span className={`text-[9px] font-black uppercase tracking-wide block ${isActive ? 'text-indigo-200' : 'text-slate-500'}`}>
                                    {conn.type === 'FAMILY' ? 'Gia đình' : 'Bạn bè'}
                                  </span>
                                </div>
                                {unreadChatSenders.includes(connUser.id) && (
                                  <span className="relative flex h-2 w-2 shrink-0 ml-2">
                                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-rose-400 opacity-75"></span>
                                    <span className="relative inline-flex rounded-full h-2 w-2 bg-rose-600"></span>
                                  </span>
                                )}
                              </div>
                            </button>
                          );
                        })
                      )}
                    </div>
                  </div>
                )}

                {/* Chat Window Panel: show if not mobile OR if mobile and active chat user */}
                {(!isMobile || activeChatUser) && (
                  <div className="flex-1 flex flex-col bg-slate-950/15 min-w-0">
                    {activeChatUser ? (
                      <>
                        {/* Chat Header */}
                        <div className="p-4 bg-slate-900/60 border-b border-slate-800/80 flex items-center justify-between">
                          <div className="flex items-center gap-3">
                            {isMobile && (
                              <button
                                type="button"
                                onClick={() => setActiveChatUser(null)}
                                className="p-1 hover:bg-slate-800 rounded-lg text-slate-400 hover:text-white transition-colors mr-1"
                              >
                                <ChevronLeft className="w-6 h-6" />
                              </button>
                            )}
                            {activeChatUser.avatar ? (
                              <img
                                src={activeChatUser.avatar}
                                alt={activeChatUser.name}
                                className="w-10 h-10 rounded-full object-cover border border-indigo-500"
                              />
                            ) : (
                              renderInitialsAvatar(activeChatUser.name, 'w-10 h-10 text-xs')
                            )}
                            <div>
                              <h3 className="text-sm font-bold text-white">{activeChatUser.name}</h3>
                              <span className="text-[10px] text-emerald-400 font-bold flex items-center gap-1">
                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
                                Trực tuyến (Realtime)
                              </span>
                            </div>
                          </div>
                        </div>

                        {/* Chat Messages Panel */}
                        <div className="flex-1 p-5 overflow-y-auto flex flex-col gap-4">
                          {chatMessages.length === 0 ? (
                            <div className="flex-1 flex flex-col items-center justify-center text-slate-500 text-xs italic gap-2">
                              <MessageSquare className="w-8 h-8 text-slate-700" />
                              <span>Chưa có tin nhắn nào. Gửi tin nhắn để bắt đầu cuộc hội thoại!</span>
                            </div>
                          ) : (
                            chatMessages.map((msg) => {
                              const isMe = msg.senderId === user.id;
                              return (
                                <div
                                  key={msg.id}
                                  className={`flex flex-col max-w-[70%] ${isMe ? 'self-end items-end' : 'self-start items-start'}`}
                                >
                                  <div className={`p-3.5 rounded-2xl text-xs font-medium leading-relaxed flex flex-col gap-1.5 relative group ${isMe
                                    ? 'bg-indigo-650 text-white rounded-br-none shadow-md shadow-indigo-950/20'
                                    : 'bg-slate-800 text-slate-200 rounded-bl-none border border-slate-700/60'
                                    }`}>
                                    {msg.attachmentUrl && (
                                      <div className="relative rounded-lg overflow-hidden border border-black/10 max-w-xs group/img">
                                        <img
                                          src={msg.attachmentUrl}
                                          alt="Đính kèm"
                                          className="w-full max-h-48 object-cover hover:brightness-95 transition-all"
                                        />
                                        <button
                                          type="button"
                                          onClick={() => handleDownloadImage(msg.attachmentUrl, msg.id)}
                                          className="absolute bottom-2 right-2 p-1.5 bg-black/65 hover:bg-black/85 text-white rounded-md transition-all shadow-md flex items-center justify-center animate-fade-in"
                                          title="Tải ảnh này về máy"
                                        >
                                          <Download className="w-3.5 h-3.5" />
                                        </button>
                                      </div>
                                    )}

                                    {msg.latitude !== undefined && msg.latitude !== null && (
                                      <a
                                        href={`https://www.google.com/maps/search/?api=1&query=${msg.latitude},${msg.longitude}`}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-[11px] font-bold transition-all border ${isMe
                                          ? 'bg-indigo-750 border-indigo-750/30 text-indigo-100 hover:bg-indigo-800'
                                          : 'bg-slate-900/60 border-slate-800/80 text-slate-200 hover:bg-slate-900'
                                          }`}
                                      >
                                        <MapPin className="w-3.5 h-3.5 text-rose-500 shrink-0 animate-bounce" />
                                        <div className="flex flex-col text-left">
                                          <span>Vị trí hiện tại</span>
                                          <span className="text-[9px] opacity-75">{msg.latitude.toFixed(6)}, {msg.longitude.toFixed(6)}</span>
                                        </div>
                                      </a>
                                    )}

                                    {msg.content && <p className="whitespace-pre-wrap break-words">{msg.content}</p>}
                                  </div>
                                  <span className="text-[8px] text-slate-500 font-bold mt-1 px-1">
                                    {new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                  </span>
                                </div>
                              );
                            })
                          )}
                          <div ref={messagesEndRef} />
                        </div>

                        {/* Previews (Image & GPS Location) */}
                        {(imagePreview || attachedLocation) && (
                          <div className="px-4 py-2 border-t border-slate-800/40 bg-slate-900/30 flex flex-wrap gap-2 animate-in fade-in duration-200">
                            {imagePreview && (
                              <div className="relative w-14 h-14 rounded-lg overflow-hidden border border-slate-700 shadow-sm">
                                <img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
                                <button
                                  type="button"
                                  onClick={() => {
                                    setSelectedImage(null);
                                    setImagePreview(null);
                                  }}
                                  className="absolute top-0.5 right-0.5 p-0.5 bg-black/60 hover:bg-black text-white rounded-full transition-all"
                                >
                                  <X className="w-2.5 h-2.5" />
                                </button>
                              </div>
                            )}
                            {attachedLocation && (
                              <div className="flex items-center gap-1.5 bg-rose-950/40 border border-rose-900/50 rounded-lg px-2.5 py-1 text-xs text-rose-300 font-bold">
                                <MapPin className="w-3.5 h-3.5 text-rose-500 animate-pulse" />
                                <span>Đã đính kèm GPS</span>
                                <button
                                  type="button"
                                  onClick={() => setAttachedLocation(null)}
                                  className="hover:text-rose-450 transition-colors ml-1"
                                >
                                  <X className="w-3.5 h-3.5" />
                                </button>
                              </div>
                            )}
                          </div>
                        )}

                        {/* Chat Input form */}
                        <form
                          onSubmit={handleSendMessage}
                          className="p-4 border-t border-slate-800/80 bg-slate-900/60 flex gap-2 items-center"
                        >
                          <input
                            type="file"
                            accept="image/*"
                            ref={fileInputRef}
                            onChange={(e) => {
                              const file = e.target.files?.[0];
                              if (file) {
                                setSelectedImage(file);
                                setImagePreview(URL.createObjectURL(file));
                              }
                            }}
                            className="hidden"
                          />

                          <button
                            type="button"
                            onClick={() => fileInputRef.current?.click()}
                            className="p-3 bg-slate-900 border border-slate-800 hover:bg-slate-855 text-slate-400 hover:text-white rounded-2xl transition-all shadow-sm active:scale-95 flex items-center justify-center shrink-0"
                            title="Đính kèm hình ảnh"
                          >
                            <ImageIcon className="w-4 h-4 text-indigo-400" />
                          </button>

                          <button
                            type="button"
                            onClick={handleGetLocation}
                            disabled={isLocating}
                            className={`p-3 bg-slate-900 border border-slate-800 hover:bg-slate-855 text-slate-400 hover:text-white rounded-2xl transition-all shadow-sm active:scale-95 flex items-center justify-center shrink-0 ${isLocating ? 'animate-pulse' : ''
                              }`}
                            title="Chia sẻ vị trí GPS hiện tại"
                          >
                            {isLocating ? (
                              <Loader2 className="w-4 h-4 animate-spin text-rose-500" />
                            ) : (
                              <MapPin className="w-4 h-4 text-rose-500" />
                            )}
                          </button>

                          <input
                            type="text"
                            value={newMessage}
                            onChange={(e) => setNewMessage(e.target.value)}
                            placeholder={isUploading ? "Đang tải ảnh lên..." : `Nhắn cho ${activeChatUser.name.split(' ').pop()}...`}
                            disabled={isUploading}
                            className="flex-1 bg-slate-950 border border-slate-800 rounded-2xl py-3 px-4 text-xs text-white placeholder-slate-500 outline-none focus:border-indigo-500/80 transition-all disabled:bg-slate-900 disabled:cursor-not-allowed"
                          />
                          <button
                            type="submit"
                            disabled={isUploading || (!newMessage.trim() && !selectedImage && !attachedLocation)}
                            className="p-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-2xl transition-all shadow-md shadow-indigo-600/10 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
                          >
                            {isUploading ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <Send className="w-4 h-4" />
                            )}
                          </button>
                        </form>
                      </>
                    ) : (
                      <div className="flex-1 flex flex-col items-center justify-center text-slate-500 gap-3">
                        <MessageSquare className="w-16 h-16 text-slate-800 animate-bounce" />
                        <span className="text-sm font-medium">Chọn một kết nối bên trái để bắt đầu cuộc trò chuyện trực tiếp!</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* Emergency Share Configuration Modal */}
            {sharingTour && (
              <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md animate-in fade-in duration-300">
                <div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-[32px] overflow-hidden shadow-2xl animate-in zoom-in-95 duration-300">
                  {/* Modal Header */}
                  <div className="p-6 border-b border-slate-800/80 flex items-center justify-between">
                    <div className="flex items-center gap-3 text-rose-500">
                      <ShieldAlert className="w-6 h-6 animate-pulse" />
                      <h3 className="text-lg font-black uppercase tracking-tight text-white">{t('emergencyShare')}</h3>
                    </div>
                    <button
                      onClick={() => setSharingTour(null)}
                      className="p-2 hover:bg-slate-800 rounded-xl text-slate-400 hover:text-white transition-all active:scale-95"
                    >
                      <X className="w-5 h-5" />
                    </button>
                  </div>

                  {/* Modal Body */}
                  <div className="p-6 space-y-6">
                    <div>
                      <h4 className="text-sm font-bold text-white mb-1">{sharingTour.title}</h4>
                      <p className="text-xs text-slate-450 leading-relaxed">{t('emergencyShareTooltip')}</p>
                    </div>

                    {loadingShare ? (
                      <div className="py-8 flex flex-col items-center justify-center gap-2">
                        <Loader2 className="w-8 h-8 text-rose-500 animate-spin" />
                        <span className="text-xs text-slate-500 font-bold">{t('loading')}</span>
                      </div>
                    ) : (
                      <>
                        {/* Share Activation Toggle */}
                        <div className="bg-slate-950/40 border border-slate-800/60 p-4 rounded-2xl flex items-center justify-between">
                          <div>
                            <span className="text-xs font-bold text-slate-300">Kích hoạt đường dẫn cứu hộ</span>
                          </div>
                          {shareStatus && (
                            <label className="relative inline-flex items-center cursor-pointer">
                              <input
                                type="checkbox"
                                checked={shareStatus.isEnabled}
                                onChange={(e) => handleToggleShare(e.target.checked)}
                                className="sr-only peer"
                              />
                              <div className="w-11 h-6 bg-slate-800 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-rose-600"></div>
                            </label>
                          )}
                        </div>

                        {shareStatus?.isEnabled && (
                          <>
                            {/* Configuration: Language and Theme selectors */}
                            <div className="grid grid-cols-2 gap-4">
                              <div className="space-y-2">
                                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500">{t('languageSelect')}</label>
                                <select
                                  value={lang}
                                  onChange={(e) => changeLanguage(e.target.value as any)}
                                  className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2.5 text-xs font-bold focus:outline-none cursor-pointer"
                                >
                                  <option value="vi">Tiếng Việt</option>
                                  <option value="en">English</option>
                                  <option value="zh">中文</option>
                                </select>
                              </div>

                              <div className="space-y-2">
                                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500">{t('themeSelect')}</label>
                                <select
                                  value={theme}
                                  onChange={(e) => changeTheme(e.target.value as any)}
                                  className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2.5 text-xs font-bold focus:outline-none cursor-pointer"
                                >
                                  <option value="light">{t('themeLight')}</option>
                                  <option value="dark">{t('themeDark')}</option>
                                  <option value="system">{t('themeSystem')}</option>
                                </select>
                              </div>
                            </div>

                            {/* Shareable Link Input with Copy button */}
                            <div className="bg-rose-950/10 border border-rose-950/20 p-4 rounded-2xl space-y-2">
                              <div className="text-[10px] font-black text-rose-400 uppercase tracking-widest">Đường dẫn khẩn cấp:</div>
                              <div className="flex items-center gap-2">
                                <input
                                  type="text"
                                  readOnly
                                  value={`${window.location.origin}/journey/${shareStatus.token}?lang=${lang}&theme=${theme}`}
                                  className="flex-1 bg-slate-950 border border-slate-800 rounded-xl px-3 py-2.5 text-xs text-slate-200 select-all outline-none"
                                />
                                <button
                                  type="button"
                                  onClick={() => {
                                    navigator.clipboard.writeText(`${window.location.origin}/journey/${shareStatus.token}?lang=${lang}&theme=${theme}`);
                                    notify({ title: 'Thành công', message: 'Đã sao chép liên kết!', type: 'success' });
                                  }}
                                  className="bg-rose-600 hover:bg-rose-700 text-white font-bold px-4 py-2.5 rounded-xl text-xs transition-all active:scale-95 shrink-0"
                                >
                                  {t('copyShareLink')}
                                </button>
                              </div>
                            </div>
                          </>
                        )}
                      </>
                    )}
                  </div>

                  {/* Modal Footer */}
                  <div className="p-6 bg-slate-950/20 border-t border-slate-800/80 flex justify-end">
                    <button
                      type="button"
                      onClick={() => setSharingTour(null)}
                      className="py-2.5 px-6 bg-slate-800 hover:bg-slate-700 text-white font-bold rounded-xl text-xs transition-all active:scale-95"
                    >
                      Đóng
                    </button>
                  </div>
                </div>
              </div>
            )}

          </div>
        </main>
      </div>
    </div>
  );
};
