import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  X,
  User,
  Users,
  Settings,
  Languages,
  Info,
  LogOut,
  ArrowLeft,
  Camera,
  Edit3,
  Check,
  Loader2,
  Trash2,
  Calendar,
  AtSign,
  MessageSquare,
  ChevronRight,
  ChevronLeft,
  Palette,
  Sparkles,
  UserPlus,
  UserMinus,
  UserCheck,
  Clock,
  Search,
  Shield,
  Eye,
} from 'lucide-react';
import { useAuthStore } from '../../../modules/auth/application/authStore';
import { useFriendStore } from '../../../modules/friends/application/friendStore';
import { useChatStore } from '../../../modules/chats/application/chatStore';
import { UserApi } from '../../../modules/users/infrastructure/userApi';
import { getSocket } from '../../infrastructure/socket';
import { useLang } from '../../infrastructure/i18n';
import { useThemeStore, ChatTheme } from '../../application/stores/themeStore';
import DatePicker from '../components/ui/DatePicker';
import type { User as UserType, UserPresence, FriendRequest, FriendWithId } from '../../domain/types';

import { getInitials } from '../../utils/utils';

type SideView = 'main' | 'profile' | 'settings' | 'about' | 'themes' | 'friends';

interface SideMenuProps {
  isOpen: boolean;
  onClose: () => void;
  onOpenProfile: () => void;
  onOpenTelegramImport: () => void;
}

export default function SideMenu({ isOpen, onClose, onOpenProfile, onOpenTelegramImport }: SideMenuProps) {
  const { user, updateUser, logout } = useAuthStore();
  const { clearStore } = useChatStore();
  const { chatTheme, setChatTheme } = useThemeStore();
  const { t, lang, setLang } = useLang();

  const [view, setView] = useState<SideView>('main');
  const [prevView, setPrevView] = useState<SideView>('main');
  const [themeIndex, setThemeIndex] = useState(0);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Friends state
  const {
    friends,
    friendRequests,
    isLoading: friendsLoading,
    searchQuery: friendSearch,
    searchResults: friendSearchResults,
    isSearching: friendSearchLoading,
    setSearchQuery: setFriendSearch,
    loadFriends,
    acceptRequest: handleAcceptRequest,
    declineRequest: handleDeclineRequest,
    removeFriend: handleRemoveFriend,
    sendRequest: handleSendFriendRequest,
    searchFriends,
    clearSearch,
    initializeSocketEvents
  } = useFriendStore();

  const themeCards: { id: ChatTheme; color: string; accent: string; name: string; nameEn: string; desc: string; descEn: string; animated?: boolean; gradient?: string }[] = [
    { id: 'midnight', color: '#0f0f13', accent: '#6366f1', name: 'Полночь', nameEn: 'Midnight', desc: 'Тёмная тема с мягкими акцентами', descEn: 'Dark theme with soft accents' },
    { id: 'ocean', color: '#0b172a', accent: '#3b82f6', name: 'Океан', nameEn: 'Ocean', desc: 'Глубокий синий с прохладными тонами', descEn: 'Deep blue with cool tones' },
    { id: 'forest', color: '#0f1c15', accent: '#10b981', name: 'Лес', nameEn: 'Forest', desc: 'Природный зелёный и спокойствие', descEn: 'Natural green and serenity' },
    { id: 'sunset', color: '#1f111a', accent: '#ec4899', gradient: 'linear-gradient(135deg, #1f111a, #150a0f)', name: 'Закат', nameEn: 'Sunset', desc: 'Тёплый розовый градиент заката', descEn: 'Warm pink sunset gradient' },
    { id: 'classic', color: '#121215', accent: '#a1a1aa', name: 'Классика', nameEn: 'Classic', desc: 'Минималистичная монохромная тема', descEn: 'Minimalist monochrome theme' },
    { id: 'neon', color: '#0b0f19', accent: '#8b5cf6', name: 'Неон', nameEn: 'Neon', desc: 'Фиолетовое свечение за курсором', descEn: 'Purple glow follows your cursor', animated: true },
    { id: 'aurora', color: '#022c22', accent: '#10b981', gradient: 'linear-gradient(135deg, #022c22, #064e3b)', name: 'Аврора', nameEn: 'Aurora', desc: 'Северное сияние реагирует на мышь', descEn: 'Northern lights react to mouse', animated: true },
    { id: 'cyber', color: '#000000', accent: '#f59e0b', name: 'Кибер', nameEn: 'Cyber', desc: 'Сетка и янтарное свечение мыши', descEn: 'Grid pattern with amber glow', animated: true },
    { id: 'glass', color: '#0d1117', accent: '#3b82f6', name: 'Стекло', nameEn: 'Glass', desc: 'Плавное свечение следует за мышью', descEn: 'Smooth glow follows the cursor', animated: true },
    { id: 'void', color: '#000000', accent: '#ffffff', name: 'Бездна', nameEn: 'Void', desc: 'Абсолютный мрак с точечным светом', descEn: 'Absolute darkness with spot light', animated: true },
  ];

  const changeView = (next: SideView) => {
    setPrevView(view);
    setView(next);
    if (next === 'themes') {
      const idx = themeCards.findIndex(tc => tc.id === chatTheme);
      if (idx >= 0) setThemeIndex(idx);
    }
    if (next === 'friends') {
      loadFriends();
    }
  };

  // Friend search effect
  useEffect(() => {
    const timer = setTimeout(() => {
      searchFriends(friendSearch, user?.id);
    }, 400);
    return () => clearTimeout(timer);
  }, [friendSearch, user?.id, searchFriends]);

  useEffect(() => {
    if (!isOpen) {
      const timer = setTimeout(() => { setView('main'); setPrevView('main'); }, 300);
      clearSearch();
      return () => clearTimeout(timer);
    }
    // Load friend request count when menu opens
    useFriendStore.getState().loadFriends();
  }, [isOpen, clearSearch]);

  // Real-time friend updates via socket
  useEffect(() => {
    const cleanup = initializeSocketEvents();
    return cleanup;
  }, [initializeSocketEvents]);

  const handleLogout = () => {
    clearStore();
    logout();
    onClose();
  };

  const initials = getInitials(user?.displayName || user?.userName || user?.username || '??');

  const menuItems = [
    { icon: User, label: t('myProfile'), onClick: () => { onClose(); onOpenProfile(); } },
    { icon: Users, label: t('friends'), onClick: () => changeView('friends'), badge: friendRequests.length > 0 ? friendRequests.length : undefined },


    { divider: true },
    { icon: Info, label: t('aboutApp'), subtitle: 'Knot Messenger v1.0', onClick: () => changeView('about') },
  ];

  // Slide direction for animations
  const slideDir = prevView === 'main' ? 1 : -1;
  const viewVariants = {
    enter: (dir: number) => ({ x: dir * 100, opacity: 0 }),
    center: { x: 0, opacity: 1 },
    exit: (dir: number) => ({ x: -dir * 100, opacity: 0 }),
  };

  // ======= MAIN VIEW =======
  const renderMain = () => (
    <motion.div key="main" className="flex flex-col h-full" initial={false} animate="center" exit="exit" variants={viewVariants} custom={-1} transition={{ duration: 0.2 }}>
      {/* ── Premium header with avatar ── */}
      <div className="relative overflow-hidden flex-shrink-0">
        {/* Animated gradient backdrop */}
        <div className="absolute inset-0 bg-gradient-to-br from-primary/30 via-primary-container/20 to-transparent pointer-events-none" />
        <div className="absolute -top-20 -right-20 w-56 h-56 bg-primary/10 rounded-full blur-[80px] pointer-events-none" />
        <div className="absolute -bottom-10 -left-10 w-40 h-40 bg-primary-container/10 rounded-full blur-[60px] pointer-events-none" />

        <div className="relative p-6 pb-5">
          <div className="flex items-start justify-between mb-5">
            {/* Avatar with glow ring */}
            <div className="relative group cursor-pointer" onClick={() => { onClose(); onOpenProfile(); }}>
              <div className="absolute -inset-1 bg-gradient-to-r from-accent via-purple-500 to-accent rounded-2xl opacity-60 blur group-hover:opacity-90 transition duration-500 animate-[spin_4s_linear_infinite]" />
              <div className="relative">
                {user?.avatar ? (
                  <img src={user.avatar} alt="" className="w-[72px] h-[72px] rounded-2xl object-cover ring-[3px] ring-surface" />
                ) : (
                  <div className="w-[72px] h-[72px] rounded-2xl bg-linear-to-br from-primary/80 to-primary flex items-center justify-center ring-[3px] ring-surface relative overflow-hidden">
                    <span className="relative z-10 text-2xl font-black text-on-primary drop-shadow-md">{initials}</span>
                  </div>
                )}
              </div>
              {/* Online indicator */}
              <div className="absolute bottom-0 right-0 w-4 h-4 bg-emerald-500 rounded-full ring-[3px] ring-surface shadow-[0_0_8px_rgba(16,185,129,0.6)]" />
            </div>
            <button onClick={onClose} className="p-2 rounded-xl text-zinc-400 hover:text-white hover:bg-white/10 transition-all backdrop-blur-sm">
              <X size={20} />
            </button>
          </div>
          {/* Name & username */}
          <h3 className="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-b from-white to-white/70 tracking-tight leading-tight">
            {user?.displayName || user?.userName || user?.username || ''}
          </h3>
          <div className="flex items-center gap-1.5 mt-1.5">
            <AtSign size={12} className="text-knot-400" />
            <span className="text-sm font-medium text-knot-100/70">{user?.userName || user?.username || ''}</span>
          </div>
        </div>
        {/* Bottom fade line */}
        <div className="h-px bg-gradient-to-r from-transparent via-white/10 to-transparent" />
      </div>

      {/* ── Menu items ── */}
      <div className="flex-1 overflow-y-auto px-3 py-4 space-y-1">
        {menuItems.map((item, i) => {
          if ('divider' in item) return <div key={i} className="my-2 mx-2 h-px bg-gradient-to-r from-transparent via-white/8 to-transparent" />;
          const Icon = item.icon!;
          return (
            <button
              key={i}
              onClick={item.onClick}
              className="group w-full flex items-center gap-3.5 px-4 py-3 rounded-2xl text-left transition-all duration-200 hover:bg-white/[0.06] active:scale-[0.98]"
            >
              <div className="w-9 h-9 rounded-xl bg-white/[0.06] group-hover:bg-knot-500/15 flex items-center justify-center transition-all duration-200 border border-white/[0.04] group-hover:border-knot-500/20">
                <Icon size={17} className="text-zinc-400 group-hover:text-knot-400 transition-colors duration-200" />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-[13.5px] font-medium text-zinc-200 group-hover:text-white transition-colors">{item.label}</p>
                {item.subtitle && <p className="text-[11px] text-zinc-500 mt-0.5">{item.subtitle}</p>}
              </div>
              {'badge' in item && item.badge ? (
                <span className="bg-linear-to-r from-primary to-primary-container text-on-primary text-[11px] font-black min-w-[22px] h-[22px] px-1.5 rounded-full flex items-center justify-center flex-shrink-0 shadow-[0_0_12px_rgba(var(--color-primary),0.4)]">
                  {item.badge}
                </span>
              ) : (
                <ChevronRight size={15} className="text-zinc-600 group-hover:text-zinc-400 transition-colors flex-shrink-0" />
              )}
            </button>
          );
        })}
      </div>

      {/* ── Logout button ── */}
      <div className="px-3 pb-4 pt-1">
        <div className="h-px bg-gradient-to-r from-transparent via-white/8 to-transparent mb-3" />
        <button
          onClick={handleLogout}
          className="group w-full flex items-center gap-3.5 px-4 py-3 rounded-2xl transition-all duration-200 hover:bg-red-500/[0.08] active:scale-[0.98]"
        >
          <div className="w-9 h-9 rounded-xl bg-red-500/[0.08] group-hover:bg-red-500/15 flex items-center justify-center transition-all duration-200 border border-red-500/[0.06] group-hover:border-red-500/20">
            <LogOut size={17} className="text-red-400/70 group-hover:text-red-400 transition-colors duration-200" />
          </div>
          <span className="text-[13.5px] font-medium text-red-400/70 group-hover:text-red-400 transition-colors">{t('logout')}</span>
        </button>
      </div>
    </motion.div>
  );

  // ======= SETTINGS VIEW =======
  const renderSettings = () => (
    <motion.div key="settings" className="flex flex-col h-full" initial={{ x: 100, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 100, opacity: 0 }} transition={{ duration: 0.2 }}>
      <div className="h-14 flex items-center gap-3 px-4 border-b border-border flex-shrink-0">
        <button onClick={() => changeView('main')} className="p-1.5 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 transition-colors">
          <ArrowLeft size={20} />
        </button>
        <h3 className="text-sm font-semibold text-white flex-1">{t('settings')}</h3>
      </div>
      <div className="flex-1 overflow-y-auto py-2">
        {/* Theme picker row */}
        <div className="px-4 py-1">
          <button
            onClick={() => changeView('themes')}
            className="w-full flex items-center gap-4 px-4 py-3.5 rounded-xl bg-surface-tertiary/50 hover:bg-surface-hover transition-colors group"
          >
            <div className="w-9 h-9 rounded-full flex items-center justify-center" style={{ backgroundColor: themeCards.find(t => t.id === chatTheme)?.accent || '#6366f1' }}>
              <Palette size={18} className="text-white" />
            </div>
            <div className="flex-1 min-w-0 text-left">
              <p className="text-sm font-medium text-zinc-200">{t('theme')}</p>
              <p className="text-xs text-zinc-500">{lang === 'ru' ? themeCards.find(tc => tc.id === chatTheme)?.name : themeCards.find(tc => tc.id === chatTheme)?.nameEn}</p>
            </div>
            <ChevronRight size={18} className="text-zinc-500 group-hover:text-zinc-300 transition-colors" />
          </button>
        </div>
        <div className="px-5 py-3">
          <h4 className="text-xs text-zinc-500 uppercase tracking-wide mb-3">{t('language')}</h4>
          <div className="space-y-1">
            <button
              onClick={() => setLang('ru')}
              className={`w-full flex items-center gap-4 px-3 py-3 rounded-xl transition-colors ${lang === 'ru' ? 'bg-knot-500/15 ring-1 ring-knot-500/30' : 'bg-surface-tertiary/50 hover:bg-surface-hover'}`}
            >
              <span className="text-lg">🇷🇺</span>
              <div className="flex-1 min-w-0 text-left">
                <p className="text-sm text-zinc-200">Русский</p>
              </div>
              {lang === 'ru' && <Check size={16} className="text-knot-400" />}
            </button>
            <button
              onClick={() => setLang('en')}
              className={`w-full flex items-center gap-4 px-3 py-3 rounded-xl transition-colors ${lang === 'en' ? 'bg-knot-500/15 ring-1 ring-knot-500/30' : 'bg-surface-tertiary/50 hover:bg-surface-hover'}`}
            >
              <span className="text-lg">🇬🇧</span>
              <div className="flex-1 min-w-0 text-left">
                <p className="text-sm text-zinc-200">English</p>
              </div>
              {lang === 'en' && <Check size={16} className="text-knot-400" />}
            </button>
          </div>
        </div>
        {/* Privacy */}
        <div className="px-5 py-3">
          <h4 className="text-xs text-zinc-500 uppercase tracking-wide mb-3">{t('privacy')}</h4>
          <div className="space-y-1">
            <button
              onClick={async () => {
                const newVal = !user?.hideStoryViews;
                try {
                  await UserApi.updateSettings({ hideStoryViews: newVal });
                  useAuthStore.getState().updateUser({ hideStoryViews: newVal });
                } catch {}
              }}
              className="w-full flex items-center gap-4 px-3 py-3 rounded-xl bg-surface-tertiary/50 hover:bg-surface-hover transition-colors"
            >
              <Eye size={18} className="text-zinc-400 flex-shrink-0" />
              <div className="flex-1 min-w-0 text-left">
                <p className="text-sm text-zinc-200">{t('hideStoryViews')}</p>
                <p className="text-[11px] text-zinc-500 mt-0.5">{t('hideStoryViewsDesc')}</p>
              </div>
              <div className={`w-10 h-6 rounded-full transition-colors flex items-center px-0.5 ${user?.hideStoryViews ? 'bg-knot-500' : 'bg-zinc-600'}`}>
                <div className={`w-5 h-5 rounded-full bg-white shadow transition-transform ${user?.hideStoryViews ? 'translate-x-4' : 'translate-x-0'}`} />
              </div>
            </button>
          </div>
        </div>
        <div className="px-5 py-3 border-t border-border mt-2">
          <h4 className="text-xs text-zinc-500 uppercase tracking-wide mb-3">Хранилище и данные</h4>
          <button
            onClick={() => { onOpenTelegramImport(); }}
            className="w-full flex items-center gap-4 px-3 py-3 rounded-xl bg-surface-tertiary/50 hover:bg-surface-hover transition-colors"
          >
            <div className="w-8 h-8 rounded-lg bg-blue-500/20 flex items-center justify-center">
              <MessageSquare size={16} className="text-blue-400" />
            </div>
            <div className="flex-1 min-w-0 text-left">
              <p className="text-sm text-zinc-200">Импорт истории Telegram</p>
              <p className="text-[11px] text-zinc-500 mt-0.5">Перенести сообщения и медиа</p>
            </div>
            <ChevronRight size={18} className="text-zinc-500 transition-colors" />
          </button>
        </div>

        <div className="px-5 py-3">
          <h4 className="text-xs text-zinc-500 uppercase tracking-wide mb-3">{t('about')}</h4>
    <div className="flex items-center gap-4 px-3 py-3 rounded-xl bg-surface-tertiary/50">
      <Info size={18} className="text-zinc-400" />
      <div className="flex-1 min-w-0">
        <p className="text-sm text-zinc-200">Knot Messenger</p>
        <p className="text-xs text-zinc-500">{t('version')} 1.0.0</p>
      </div>
    </div>
        </div>
      </div>
    </motion.div>
  );

  // ======= THEMES VIEW =======
  const renderThemes = () => {
    const currentCard = themeCards[themeIndex];
    const isActive = chatTheme === currentCard.id;
    return (
      <motion.div key="themes" className="flex flex-col h-full" initial={{ x: 100, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 100, opacity: 0 }} transition={{ duration: 0.2 }}>
        <div className="h-14 flex items-center gap-3 px-4 border-b border-border flex-shrink-0">
          <button onClick={() => changeView('settings')} className="p-1.5 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 transition-colors">
            <ArrowLeft size={20} />
          </button>
          <h3 className="text-sm font-semibold text-white flex-1">{t('theme')}</h3>
          <span className="text-xs text-zinc-500 tabular-nums">{themeIndex + 1} / {themeCards.length}</span>
        </div>

        <div className="flex-1 flex flex-col items-center justify-center px-5 py-4 gap-4 overflow-hidden">
          {/* Preview card */}
          <AnimatePresence mode="wait">
            <motion.div
              key={currentCard.id}
              initial={{ opacity: 0, scale: 0.92, x: 40 }}
              animate={{ opacity: 1, scale: 1, x: 0 }}
              exit={{ opacity: 0, scale: 0.92, x: -40 }}
              transition={{ duration: 0.25, ease: 'easeOut' }}
              className="w-full rounded-2xl overflow-hidden border border-border/40 shadow-xl flex flex-col"
              style={{ minHeight: 200 }}
            >
              {/* Theme background preview */}
              <div
                className={`relative w-full h-32 chat-theme-${currentCard.id}`}
                style={currentCard.gradient ? { background: currentCard.gradient } : { backgroundColor: currentCard.color }}
              >
                {/* Fake chat bubbles */}
                <div className="absolute inset-0 p-4 flex flex-col justify-end gap-2">
                  <div className="self-start max-w-[65%] px-3 py-2 rounded-2xl rounded-bl-md bg-white/10 backdrop-blur-sm">
                    <p className="text-[11px] text-white/70">Hey! How's it going? 👋</p>
                  </div>
                  <div className="self-end max-w-[65%] px-3 py-2 rounded-2xl rounded-br-md" style={{ backgroundColor: currentCard.accent + '40' }}>
                    <p className="text-[11px] text-white/80">Pretty great, thanks! ✨</p>
                  </div>
                </div>
                {currentCard.animated && (
                  <div className="absolute top-3 right-3 flex items-center gap-1 px-2 py-0.5 rounded-full bg-white/10 backdrop-blur-sm">
                    <Sparkles size={10} className="text-yellow-400" />
                    <span className="text-[9px] text-white/60 font-medium">{lang === 'ru' ? 'Интерактив' : 'Interactive'}</span>
                  </div>
                )}
              </div>
              {/* Info */}
              <div className="p-4 bg-surface-secondary">
                <div className="flex items-center gap-3 mb-1">
                  <div className="w-3 h-3 rounded-full" style={{ backgroundColor: currentCard.accent }} />
                  <h3 className="text-base font-bold text-white">{lang === 'ru' ? currentCard.name : currentCard.nameEn}</h3>
                </div>
                <p className="text-xs text-zinc-400 ml-6">{lang === 'ru' ? currentCard.desc : currentCard.descEn}</p>
              </div>
            </motion.div>
          </AnimatePresence>

          {/* Navigation arrows + select */}
          <div className="flex items-center gap-3 w-full">
            <button
              onClick={() => setThemeIndex(i => (i - 1 + themeCards.length) % themeCards.length)}
              className="p-2.5 rounded-xl bg-surface-tertiary/60 text-zinc-400 hover:text-white hover:bg-surface-hover transition-colors"
            >
              <ChevronLeft size={20} />
            </button>
            <button
              onClick={() => { setChatTheme(currentCard.id); }}
              className={`flex-1 py-3 rounded-xl text-sm font-semibold transition-all duration-200 ${isActive
                ? 'bg-accent/20 text-accent ring-1 ring-accent/40 cursor-default'
                : 'bg-accent text-white hover:bg-accent/90 shadow-lg shadow-accent/20'
                }`}
              disabled={isActive}
            >
              {isActive ? (lang === 'ru' ? '✓ Выбрано' : '✓ Selected') : (lang === 'ru' ? 'Применить' : 'Apply')}
            </button>
            <button
              onClick={() => setThemeIndex(i => (i + 1) % themeCards.length)}
              className="p-2.5 rounded-xl bg-surface-tertiary/60 text-zinc-400 hover:text-white hover:bg-surface-hover transition-colors"
            >
              <ChevronRight size={20} />
            </button>
          </div>

          {/* Dot indicators */}
          <div className="flex items-center gap-1.5">
            {themeCards.map((tc, i) => (
              <button
                key={tc.id}
                onClick={() => setThemeIndex(i)}
                className={`rounded-full transition-all duration-200 ${i === themeIndex
                  ? 'w-6 h-2 bg-accent'
                  : chatTheme === tc.id
                    ? 'w-2 h-2 bg-accent/50'
                    : 'w-2 h-2 bg-zinc-600 hover:bg-zinc-500'
                  }`}
              />
            ))}
          </div>
        </div>
      </motion.div>
    );
  };

  // ======= FRIENDS VIEW =======
  const renderFriends = () => (
    <motion.div key="friends" className="flex flex-col h-full" initial={{ x: 100, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 100, opacity: 0 }} transition={{ duration: 0.2 }}>
      <div className="h-14 flex items-center gap-3 px-4 border-b border-border flex-shrink-0">
        <button onClick={() => { changeView('main'); clearSearch(); }} className="p-1.5 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 transition-colors">
          <ArrowLeft size={20} />
        </button>
        <h3 className="text-sm font-semibold text-white flex-1">{t('friends')}</h3>
      </div>

      {/* Search bar */}
      <div className="px-4 pt-3 pb-2">
        <div className="relative">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
          <input
            type="text"
            placeholder={t('searchFriends')}
            value={friendSearch}
            onChange={(e) => setFriendSearch(e.target.value)}
            className="w-full pl-9 pr-4 py-2.5 rounded-xl bg-surface-tertiary text-sm text-white placeholder-zinc-500 border border-border focus:border-accent transition-colors"
          />
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        {friendsLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 size={24} className="animate-spin text-zinc-400" />
          </div>
        ) : (
          <>
            {/* Search results */}
            {friendSearch.trim().length > 0 && (
              <div className="px-4 pt-2 pb-2">
                <h4 className="text-xs font-semibold text-zinc-400 uppercase tracking-wider mb-3">
                  <Search size={12} className="inline mr-1" />{t('searchFriends').split('(')[0].trim()}
                </h4>
                {(() => {
                  const raw = friendSearch.trim();
                  const q = raw.startsWith('@') ? raw.slice(1) : raw;
                  if (q.length < 3) {
                    return <p className="text-xs text-zinc-500 text-center py-3">{t('minCharsHint')}</p>;
                  }
                  if (friendSearchLoading) {
                    return (
                      <div className="flex items-center justify-center py-4">
                        <Loader2 size={18} className="animate-spin text-zinc-400" />
                      </div>
                    );
                  }
                  if (friendSearchResults.length === 0) {
                    return <p className="text-xs text-zinc-500 text-center py-3">{t('noSearchResults')}</p>;
                  }
                  return (
                    <div className="space-y-1">
                      {friendSearchResults.map((u) => (
                        <div key={u.id} className="flex items-center gap-3 p-3 rounded-xl bg-white/5 border border-border/50">
                          {u.avatar ? (
                            <img src={u.avatar} alt="" className="w-10 h-10 rounded-xl object-cover" />
                          ) : (
                            <div className="w-10 h-10 rounded-xl bg-linear-to-br from-primary/80 to-primary flex items-center justify-center text-on-primary font-black text-sm">
                              {getInitials(u.displayName || u.username || '?')}
                            </div>
                          )}
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-white truncate">{u.displayName || u.userName || u.username || ''}</p>
                            <p className="text-xs text-zinc-500">@{u.userName || u.username || ''}</p>
                          </div>
                          <button
                            onClick={() => handleSendFriendRequest(u.id)}
                            className="p-2 rounded-lg bg-knot-500/20 text-knot-400 hover:bg-knot-500/30 transition-colors"
                            title={t('addFriend')}
                          >
                            <UserPlus size={16} />
                          </button>
                        </div>
                      ))}
                    </div>
                  );
                })()}
              </div>
            )}

            {/* Incoming requests */}
            {friendRequests.length > 0 && (
              <div className="px-4 pt-4 pb-2">
                <h4 className="text-xs font-semibold text-zinc-400 uppercase tracking-wider mb-3">
                  {t('friendRequests')} ({friendRequests.length})
                </h4>
                <div className="space-y-2">
                  {friendRequests.map((req) => (
                    <div key={req.id} className="flex items-center gap-3 p-3 rounded-xl bg-white/5 border border-border/50">
                      {req.user.avatar ? (
                        <img src={req.user.avatar} alt="" className="w-10 h-10 rounded-xl object-cover" />
                      ) : (
                        <div className="w-10 h-10 rounded-xl bg-linear-to-br from-primary/80 to-primary flex items-center justify-center text-on-primary font-black text-sm">
                          {getInitials(req.user.displayName || req.user.username || '?')}
                        </div>
                      )}
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-white truncate">{req.user.displayName || req.user.userName || req.user.username || ''}</p>
                        <p className="text-xs text-zinc-500">@{req.user.userName || req.user.username || ''}</p>
                      </div>
                      <div className="flex gap-1.5">
                        <button
                          onClick={() => handleAcceptRequest(req.id)}
                          className="p-2 rounded-lg bg-green-500/20 text-green-400 hover:bg-green-500/30 transition-colors"
                          title={t('accept')}
                        >
                          <UserCheck size={16} />
                        </button>
                        <button
                          onClick={() => handleDeclineRequest(req.id)}
                          className="p-2 rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors"
                          title={t('decline')}
                        >
                          <X size={16} />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Friends list */}
            <div className="px-4 pt-4 pb-2">
              <h4 className="text-xs font-semibold text-zinc-400 uppercase tracking-wider mb-3">
                {t('friendsList')} ({friends.length})
              </h4>
              {friends.length === 0 ? (
                <p className="text-sm text-zinc-500 text-center py-8">{t('noFriends')}</p>
              ) : (
                <div className="space-y-1">
                  {friends.map((friend) => (
                    <div key={friend.id} className="flex items-center gap-3 p-3 rounded-xl hover:bg-white/5 transition-colors group/friend">
                      <div className="relative">
                        {friend.avatar ? (
                          <img src={friend.avatar} alt="" className="w-10 h-10 rounded-xl object-cover" />
                        ) : (
                          <div className="w-10 h-10 rounded-xl bg-linear-to-br from-primary/80 to-primary flex items-center justify-center text-on-primary font-black text-sm">
                            {getInitials(friend.displayName || friend.username || '?')}
                          </div>
                        )}
                        {friend.isOnline && (
                          <div className="absolute bottom-0 right-0 w-3 h-3 rounded-full bg-green-500 border-2 border-surface-secondary" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-white truncate">{friend.displayName || friend.userName || friend.username || ''}</p>
                        <p className="text-xs text-zinc-500">
                          {friend.isOnline ? t('online') : `@${friend.userName || friend.username || ''}`}
                        </p>
                      </div>
                      <button
                        onClick={() => handleRemoveFriend(friend.friendshipId)}
                        className="p-2 rounded-lg text-zinc-600 opacity-0 group-hover/friend:opacity-100 hover:bg-red-500/20 hover:text-red-400 transition-all"
                        title={t('removeFriend')}
                      >
                        <UserMinus size={16} />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </motion.div>
  );

  // ======= ABOUT VIEW =======
  const renderAbout = () => (
    <motion.div key="about" className="flex flex-col h-full" initial={{ x: 100, opacity: 0 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 100, opacity: 0 }} transition={{ duration: 0.2 }}>
      <div className="h-14 flex items-center gap-3 px-4 border-b border-border flex-shrink-0">
        <button onClick={() => changeView('main')} className="p-1.5 rounded-lg text-zinc-400 hover:text-white hover:bg-white/10 transition-colors">
          <ArrowLeft size={20} />
        </button>
        <h3 className="text-sm font-semibold text-white flex-1">{t('aboutApp')}</h3>
      </div>
      <div className="flex-1 flex flex-col items-center justify-center p-8 text-center">
        <div className="w-20 h-20 mx-auto mb-4 rounded-2xl bg-gradient-to-br from-accent/20 to-purple-600/20 flex items-center justify-center shadow-[0_0_30px_-5px_var(--color-accent)] ring-1 ring-white/10 relative overflow-hidden">
          <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-white/[0.05] to-transparent pointer-events-none" />
          <MessageSquare size={36} className="text-accent drop-shadow-md relative z-10" />
        </div>
        <h2 className="text-xl font-bold gradient-text mb-1">Knot Messenger</h2>
        <p className="text-sm text-zinc-400 mb-6">{t('version')} 1.0.0</p>
        <div className="text-xs text-zinc-500 space-y-1">
          <p>{t('modernMessenger')}</p>
          <p>{t('onPrivacy')}</p>
          <p className="mt-4 text-zinc-600">© 2026 Knot Team</p>
        </div>
      </div>
    </motion.div>
  );

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 bg-black/60 z-50" onClick={onClose} />
          <motion.div
            initial={{ x: -320, opacity: 0 }}
            animate={{ x: 0, opacity: 1 }}
            exit={{ x: -320, opacity: 0 }}
            transition={{ type: 'spring', damping: 25, stiffness: 300 }}
            className="fixed inset-0 lg:left-3 lg:top-3 lg:bottom-3 w-full lg:w-[340px] lg:max-w-[calc(100vw-24px)] bg-surface-secondary/95 backdrop-blur-3xl shadow-[0_0_100px_rgba(0,0,0,0.5)] border-none lg:border lg:border-border/50 lg:rounded-3xl z-50 flex flex-col overflow-hidden"
          >
            <AnimatePresence mode="wait" custom={slideDir}>
              {view === 'main' && renderMain()}
              {view === 'settings' && renderSettings()}
              {view === 'themes' && renderThemes()}
              {view === 'friends' && renderFriends()}
              {view === 'about' && renderAbout()}
            </AnimatePresence>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
