'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { useAppStore, type AppSection } from '@/lib/store';
import { t } from '@/lib/i18n';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';

import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Camera,
  ChevronRight,
  Edit3,
  ListChecks,
  Package,
  Heart,
  Bell,
  Settings,
  HelpCircle,
  Info,
  LogOut,
  UserPlus,
  LogIn,
  Lock,
  Upload,
  X,
  MapPin,
  Phone,
  Mail,
  CheckCircle,
  Loader2,
  Calendar,
  Shield,
  ShoppingBag,
  Star,
  FileText,
  MessageSquare,
  ExternalLink,
  Facebook,
  MessageCircle,
  Share2,
  Clock,
  Sparkles,
  UserCheck,
  Home,
  Store,
  BookOpen,
  ShieldCheck,
  FileQuestion,
  ChevronDown,
  ImagePlus,
  Eye,
  EyeOff,
  CreditCard,
  XCircle,
  Fingerprint,
} from 'lucide-react';

const roleColors: Record<string, string> = {
  general: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  student: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
  houseOwner: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  shopOwner: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
};

const roleLabels: Record<string, string> = {
  general: 'General',
  student: 'Student',
  houseOwner: 'House Owner',
  shopOwner: 'Shop Owner',
};

// ============ PROFILE COMPLETION CIRCLE ============
function ProfileCompletionCircle({ percentage }: { percentage: number }) {
  const radius = 32;
  const circumference = 2 * Math.PI * radius;
  const strokeDashoffset = circumference - (percentage / 100) * circumference;

  const getColor = (p: number) => {
    if (p >= 80) return 'text-emerald-500';
    if (p >= 50) return 'text-amber-500';
    return 'text-red-500';
  };

  return (
    <div className="relative flex items-center justify-center">
      <svg className="-rotate-90" width="76" height="76">
        <circle cx="38" cy="38" r={radius} stroke="currentColor" strokeWidth="5" fill="none" className="text-muted/20" />
        <circle
          cx="38" cy="38" r={radius}
          stroke="currentColor" strokeWidth="5" fill="none"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          strokeLinecap="round"
          className={`${getColor(percentage)} transition-all duration-700 ease-out`}
        />
      </svg>
      <span className={`absolute text-sm font-bold ${getColor(percentage)}`}>
        {percentage}%
      </span>
    </div>
  );
}

// ============ MENU ITEM ============
interface MenuItemProps {
  icon: React.ElementType;
  label: string;
  description?: string;
  onClick: () => void;
  danger?: boolean;
  badge?: string | number;
}

function MenuItem({ icon: Icon, label, description, onClick, danger, badge }: MenuItemProps) {
  return (
    <button
      onClick={onClick}
      className={`flex w-full items-center gap-3 rounded-xl px-4 py-3.5 transition-colors duration-150 hover:bg-accent active:bg-accent/80 ${
        danger ? 'text-destructive hover:bg-destructive/5' : ''
      }`}
    >
      <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${
        danger ? 'bg-destructive/10' : 'bg-primary/10'
      }`}>
        <Icon className={`h-4.5 w-4.5 ${danger ? 'text-destructive' : 'text-primary'}`} strokeWidth={1.75} />
      </div>
      <div className="flex-1 text-left">
        <span className={`block text-sm font-medium ${danger ? 'text-destructive' : 'text-foreground'}`}>
          {label}
        </span>
        {description && (
          <span className="block text-[11px] text-muted-foreground">{description}</span>
        )}
      </div>
      {badge !== undefined && badge !== 0 && (
        <Badge variant="secondary" className="mr-1 bg-primary/10 text-primary text-[10px] px-1.5">
          {badge}
        </Badge>
      )}
      <ChevronRight className={`h-4 w-4 ${danger ? 'text-destructive/50' : 'text-muted-foreground/50'}`} />
    </button>
  );
}

// ============ STAT CARD ============
interface StatCardProps {
  value: number | string;
  label: string;
  icon: React.ElementType;
  onClick: () => void;
}

function StatCard({ value, label, icon: Icon, onClick }: StatCardProps) {
  return (
    <button
      onClick={onClick}
      className="group flex flex-col items-center gap-1.5 rounded-xl bg-background p-3 transition-all duration-150 hover:bg-accent hover:shadow-sm active:bg-accent/80"
    >
      <Icon className="h-4 w-4 text-primary/60 group-hover:text-primary transition-colors" />
      <span className="text-lg font-bold text-primary">{value}</span>
      <span className="text-[11px] text-muted-foreground">{label}</span>
    </button>
  );
}

// ============ ACTIVITY ITEM ============
interface ActivityItemProps {
  icon: React.ElementType;
  iconColor: string;
  title: string;
  description: string;
  time: string;
}

function ActivityItem({ icon: Icon, iconColor, title, description, time }: ActivityItemProps) {
  return (
    <div className="flex items-start gap-3 py-3">
      <div className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${iconColor}`}>
        <Icon className="h-4 w-4" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-foreground truncate">{title}</p>
        <p className="text-xs text-muted-foreground truncate">{description}</p>
      </div>
      <span className="shrink-0 text-[10px] text-muted-foreground/60 flex items-center gap-1">
        <Clock className="h-3 w-3" />
        {time}
      </span>
    </div>
  );
}

// ============ EDIT PROFILE DIALOG ============
function EditProfileDialog({ open, onOpenChange, onProfileUpdated }: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onProfileUpdated: () => void;
}) {
  const { language, user, setUser } = useAppStore();
  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const avatarDropRef = useRef<HTMLDivElement>(null);

  const [activeTab, setActiveTab] = useState('personal');
  const [name, setName] = useState(user?.name || '');
  const [phone, setPhone] = useState(user?.phone || '');
  const [bio, setBio] = useState('');
  const [address, setAddress] = useState('');
  const [division, setDivision] = useState('');
  const [district, setDistrict] = useState('');
  const [upazila, setUpazila] = useState('');
  const [avatarPreview, setAvatarPreview] = useState(user?.avatar || '');
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

  // Social links
  const [facebook, setFacebook] = useState('');
  const [whatsapp, setWhatsapp] = useState('');
  const [telegram, setTelegram] = useState('');
  const [instagram, setInstagram] = useState('');

  // Fetch full profile when dialog opens
  useEffect(() => {
    if (open && user?.id) {
      fetch('/api/auth/profile?userId=' + user.id)
        .then(res => res.json())
        .then(data => {
          if (data.user) {
            setName(data.user.name || '');
            setPhone(data.user.phone || '');
            setBio(data.user.bio || '');
            setAddress(data.user.address || '');
            setDivision(data.user.division || '');
            setDistrict(data.user.district || '');
            setUpazila(data.user.upazila || '');
            setAvatarPreview(data.user.avatar || '');
            // Parse social links
            if (data.user.socialLinks) {
              try {
                const links = JSON.parse(data.user.socialLinks);
                setFacebook(links.facebook || '');
                setWhatsapp(links.whatsapp || '');
                setTelegram(links.telegram || '');
                setInstagram(links.instagram || '');
              } catch { /* ignore */ }
            }
          }
        })
        .catch(() => {});
      setActiveTab('personal');
    }
  }, [open, user?.id]);

  const processFile = useCallback((file: File) => {
    if (file.size > 5 * 1024 * 1024) {
      toast({
        title: language === 'en' ? 'File too large' : 'ফাইল অনেক বড়',
        description: language === 'en' ? 'Max 5MB' : 'সর্বোচ্চ ৫এমবি',
        variant: 'destructive',
      });
      return;
    }
    setAvatarFile(file);
    const reader = new FileReader();
    reader.onloadend = () => setAvatarPreview(reader.result as string);
    reader.readAsDataURL(file);
  }, [language, toast]);

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) processFile(file);
  };

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    const file = e.dataTransfer.files?.[0];
    if (file && file.type.startsWith('image/')) {
      processFile(file);
    }
  }, [processFile]);

  const handleRemoveAvatar = () => {
    setAvatarFile(null);
    setAvatarPreview('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user?.id) return;
    setIsLoading(true);

    try {
      let avatarUrl = avatarPreview;

      // Upload avatar if new file selected
      if (avatarFile) {
        const formData = new FormData();
        formData.append('file', avatarFile);
        formData.append('type', 'avatar');

        const uploadRes = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });
        const uploadData = await uploadRes.json();
        if (uploadData.url) {
          avatarUrl = uploadData.url;
        }
      }

      // Build social links JSON
      const socialLinksObj: Record<string, string> = {};
      if (facebook) socialLinksObj.facebook = facebook;
      if (whatsapp) socialLinksObj.whatsapp = whatsapp;
      if (telegram) socialLinksObj.telegram = telegram;
      if (instagram) socialLinksObj.instagram = instagram;

      const res = await fetch('/api/auth/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          name,
          phone,
          bio,
          address,
          division,
          district,
          upazila,
          avatar: avatarUrl || null,
          socialLinks: Object.keys(socialLinksObj).length > 0 ? JSON.stringify(socialLinksObj) : null,
        }),
      });

      const data = await res.json();
      if (res.ok) {
        // Update store
        setUser({
          id: data.user.id,
          name: data.user.name,
          email: data.user.email,
          phone: data.user.phone || undefined,
          avatar: data.user.avatar || undefined,
          roles: data.user.roles,
        });
        toast({
          title: t('profile.updateSuccess', language),
          duration: 3000,
        });
        onProfileUpdated();
        onOpenChange(false);
      } else {
        toast({
          title: language === 'en' ? 'Update Failed' : 'আপডেট ব্যর্থ',
          description: data.error || '',
          variant: 'destructive',
        });
      }
    } catch {
      toast({
        title: language === 'en' ? 'Network Error' : 'নেটওয়ার্ক ত্রুটি',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg p-0">
        <DialogHeader className="px-6 pt-6 pb-2 flex-row items-center gap-2 space-y-0">
          <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
            <ArrowLeft className="h-4 w-4" />
            <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
          </Button>
          <DialogTitle>{t('profile.editProfile', language)}</DialogTitle>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <div className="px-6">
            <TabsList className="w-full">
              <TabsTrigger value="personal" className="flex-1 text-xs">
                <UserCheck className="h-3.5 w-3.5 mr-1" />
                {language === 'en' ? 'Personal' : 'ব্যক্তিগত'}
              </TabsTrigger>
              <TabsTrigger value="location" className="flex-1 text-xs">
                <MapPin className="h-3.5 w-3.5 mr-1" />
                {language === 'en' ? 'Location' : 'অবস্থান'}
              </TabsTrigger>
              <TabsTrigger value="social" className="flex-1 text-xs">
                <Share2 className="h-3.5 w-3.5 mr-1" />
                {language === 'en' ? 'Social' : 'সোশ্যাল'}
              </TabsTrigger>
            </TabsList>
          </div>

          <form onSubmit={handleSubmit} className="pb-6">
            {/* Personal Tab */}
            <TabsContent value="personal" className="px-6 space-y-4 mt-2">
              {/* Avatar Upload with Drag & Drop */}
              <div className="flex flex-col items-center gap-3">
                <div
                  ref={avatarDropRef}
                  onDragOver={handleDragOver}
                  onDragLeave={handleDragLeave}
                  onDrop={handleDrop}
                  className={`relative transition-all duration-200 ${
                    isDragging ? 'scale-105 ring-4 ring-primary/40' : ''
                  }`}
                >
                  <Avatar className={`h-28 w-28 border-4 transition-all duration-200 ${
                    isDragging ? 'border-primary' : 'border-primary/20'
                  }`}>
                    <AvatarImage src={avatarPreview} alt="Avatar" />
                    <AvatarFallback className="bg-primary/10 text-3xl font-bold text-primary">
                      {name ? name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) : '?'}
                    </AvatarFallback>
                  </Avatar>
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="absolute bottom-0 right-0 flex h-9 w-9 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform hover:scale-110 active:scale-95"
                  >
                    <Camera className="h-4 w-4" />
                  </button>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    onChange={handleAvatarChange}
                    className="hidden"
                  />
                </div>
                {isDragging && (
                  <p className="text-xs text-primary font-medium animate-pulse">
                    {language === 'en' ? 'Drop image here' : 'ছবি এখানে ফেলুন'}
                  </p>
                )}
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="text-xs"
                    onClick={() => fileInputRef.current?.click()}
                  >
                    <ImagePlus className="mr-1 h-3 w-3" />
                    {t('profile.uploadPhoto', language)}
                  </Button>
                  {avatarPreview && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="text-xs text-destructive hover:bg-destructive/5"
                      onClick={handleRemoveAvatar}
                    >
                      <X className="mr-1 h-3 w-3" />
                      {t('profile.removePhoto', language)}
                    </Button>
                  )}
                </div>
              </div>

              <Separator />

              {/* Name */}
              <div className="space-y-2">
                <Label htmlFor="edit-name">{t('auth.name', language)}</Label>
                <Input id="edit-name" value={name} onChange={(e) => setName(e.target.value)} required />
              </div>

              {/* Phone */}
              <div className="space-y-2">
                <Label htmlFor="edit-phone">{t('auth.phone', language)}</Label>
                <Input id="edit-phone" type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+880 1XXX-XXXXXX" />
              </div>

              {/* Bio */}
              <div className="space-y-2">
                <Label htmlFor="edit-bio">{t('profile.bio', language)}</Label>
                <Textarea
                  id="edit-bio"
                  value={bio}
                  onChange={(e) => setBio(e.target.value)}
                  placeholder={language === 'en' ? 'Tell us about yourself...' : 'আপনার সম্পর্কে বলুন...'}
                  rows={3}
                />
              </div>
            </TabsContent>

            {/* Location Tab */}
            <TabsContent value="location" className="px-6 space-y-4 mt-2">
              {/* Address */}
              <div className="space-y-2">
                <Label htmlFor="edit-address">{t('profile.address', language)}</Label>
                <Input id="edit-address" value={address} onChange={(e) => setAddress(e.target.value)} placeholder={language === 'en' ? 'Full address' : 'সম্পূর্ণ ঠিকানা'} />
              </div>

              {/* Location */}
              <div className="grid grid-cols-3 gap-2">
                <div className="space-y-2">
                  <Label htmlFor="edit-division" className="text-xs">{t('profile.division', language)}</Label>
                  <Input id="edit-division" value={division} onChange={(e) => setDivision(e.target.value)} placeholder={language === 'en' ? 'Division' : 'বিভাগ'} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-district" className="text-xs">{t('profile.district', language)}</Label>
                  <Input id="edit-district" value={district} onChange={(e) => setDistrict(e.target.value)} placeholder={language === 'en' ? 'District' : 'জেলা'} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="edit-upazila" className="text-xs">{t('profile.upazila', language)}</Label>
                  <Input id="edit-upazila" value={upazila} onChange={(e) => setUpazila(e.target.value)} placeholder={language === 'en' ? 'Upazila' : 'উপজেলা'} />
                </div>
              </div>

              {/* Location preview */}
              {(division || district || upazila) && (
                <div className="rounded-lg bg-primary/5 p-3 flex items-start gap-2">
                  <MapPin className="h-4 w-4 text-primary mt-0.5 shrink-0" />
                  <p className="text-xs text-muted-foreground">
                    {[upazila, district, division].filter(Boolean).join(', ')}
                  </p>
                </div>
              )}
            </TabsContent>

            {/* Social Tab */}
            <TabsContent value="social" className="px-6 space-y-4 mt-2">
              <p className="text-xs text-muted-foreground">
                {language === 'en'
                  ? 'Add your social media links so others can connect with you'
                  : 'আপনার সোশ্যাল মিডিয়া লিঙ্ক যোগ করুন যাতে অন্যরা আপনার সাথে যুক্ত হতে পারে'}
              </p>

              {/* Facebook */}
              <div className="space-y-2">
                <Label htmlFor="edit-facebook" className="flex items-center gap-2">
                  <Facebook className="h-4 w-4 text-orange-500" />
                  Facebook
                </Label>
                <Input
                  id="edit-facebook"
                  value={facebook}
                  onChange={(e) => setFacebook(e.target.value)}
                  placeholder="https://facebook.com/username"
                />
              </div>

              {/* WhatsApp */}
              <div className="space-y-2">
                <Label htmlFor="edit-whatsapp" className="flex items-center gap-2">
                  <MessageCircle className="h-4 w-4 text-green-600" />
                  WhatsApp
                </Label>
                <Input
                  id="edit-whatsapp"
                  value={whatsapp}
                  onChange={(e) => setWhatsapp(e.target.value)}
                  placeholder="+880 1XXX-XXXXXX"
                />
              </div>

              {/* Telegram */}
              <div className="space-y-2">
                <Label htmlFor="edit-telegram" className="flex items-center gap-2">
                  <Share2 className="h-4 w-4 text-orange-500" />
                  Telegram
                </Label>
                <Input
                  id="edit-telegram"
                  value={telegram}
                  onChange={(e) => setTelegram(e.target.value)}
                  placeholder="@username or https://t.me/username"
                />
              </div>

              {/* Instagram */}
              <div className="space-y-2">
                <Label htmlFor="edit-instagram" className="flex items-center gap-2">
                  <Camera className="h-4 w-4 text-pink-500" />
                  Instagram
                </Label>
                <Input
                  id="edit-instagram"
                  value={instagram}
                  onChange={(e) => setInstagram(e.target.value)}
                  placeholder="@username or https://instagram.com/username"
                />
              </div>
            </TabsContent>

            {/* Submit Button */}
            <div className="px-6 pt-4">
              <Button type="submit" className="w-full" disabled={isLoading}>
                {isLoading ? (
                  <span className="flex items-center gap-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    {t('common.loading', language)}
                  </span>
                ) : (
                  t('common.save', language)
                )}
              </Button>
            </div>
          </form>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}

// ============ VERIFICATION DIALOG ============
function VerificationDialog({ open, onOpenChange, onVerified }: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onVerified: () => void;
}) {
  const { language, user } = useAppStore();
  const { toast } = useToast();
  const [step, setStep] = useState<1 | 2 | 3 | 4>(1);
  const [selfiePreview, setSelfiePreview] = useState('');
  const [selfieBase64, setSelfieBase64] = useState('');
  const [idCardPreview, setIdCardPreview] = useState('');
  const [idCardBase64, setIdCardBase64] = useState('');
  const [verificationResult, setVerificationResult] = useState<{
    verified: boolean;
    confidence: number;
    reason: string;
  } | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const selfieInputRef = useRef<HTMLInputElement>(null);
  const idCardInputRef = useRef<HTMLInputElement>(null);

  // Reset state when dialog opens/closes
  useEffect(() => {
    if (!open) {
      setStep(1);
      setSelfiePreview('');
      setSelfieBase64('');
      setIdCardPreview('');
      setIdCardBase64('');
      setVerificationResult(null);
      setIsLoading(false);
      setError('');
    }
  }, [open]);

  // Compress image using canvas to reduce payload size
  const compressImage = (dataUrl: string, maxWidth: number, quality: number): Promise<string> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => {
        const canvas = document.createElement('canvas');
        let width = img.width;
        let height = img.height;

        // Scale down if larger than maxWidth
        if (width > maxWidth) {
          height = (height * maxWidth) / width;
          width = maxWidth;
        }

        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        if (!ctx) {
          reject(new Error('Canvas not supported'));
          return;
        }
        ctx.drawImage(img, 0, 0, width, height);
        const compressed = canvas.toDataURL('image/jpeg', quality);
        resolve(compressed);
      };
      img.onerror = () => reject(new Error('Failed to load image'));
      img.src = dataUrl;
    });
  };

  const processImageFile = async (file: File, type: 'selfie' | 'idCard') => {
    if (file.size > 10 * 1024 * 1024) {
      toast({
        title: language === 'en' ? 'File too large' : 'ফাইল অনেক বড়',
        description: language === 'en' ? 'Maximum 10MB allowed' : 'সর্বোচ্চ ১০এমবি অনুমোদিত',
        variant: 'destructive',
      });
      return;
    }

    const reader = new FileReader();
    reader.onloadend = async () => {
      const result = reader.result as string;
      try {
        // Compress: selfie max 800px width, ID card max 1200px, quality 0.7
        const maxWidth = type === 'selfie' ? 800 : 1200;
        const compressed = await compressImage(result, maxWidth, 0.7);
        if (type === 'selfie') {
          setSelfiePreview(result); // Show original for preview
          setSelfieBase64(compressed); // Send compressed to API
        } else {
          setIdCardPreview(result); // Show original for preview
          setIdCardBase64(compressed); // Send compressed to API
        }
      } catch {
        // Fallback: use original if compression fails
        if (type === 'selfie') {
          setSelfiePreview(result);
          setSelfieBase64(result);
        } else {
          setIdCardPreview(result);
          setIdCardBase64(result);
        }
      }
    };
    reader.readAsDataURL(file);
  };

  const handleSelfieChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) processImageFile(file, 'selfie');
  };

  const handleIdCardChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) processImageFile(file, 'idCard');
  };

  const handleVerify = async () => {
    if (!user?.id) {
      setError(language === 'en' ? 'You must be logged in to verify your identity.' : 'আপনার পরিচয় যাচাই করতে লগইন করতে হবে।');
      toast({
        title: language === 'en' ? 'Login Required' : 'লগইন প্রয়োজন',
        description: language === 'en' ? 'Please log in first to verify your identity.' : 'আপনার পরিচয় যাচাই করতে প্রথমে লগইন করুন।',
        variant: 'destructive',
      });
      return;
    }
    if (!selfieBase64 || !idCardBase64) return;

    setStep(3);
    setIsLoading(true);
    setError('');

    try {
      // Strip data URL prefix for smaller payload
      const selfieData = selfieBase64.includes(',') ? selfieBase64.split(',')[1] : selfieBase64;
      const idCardData = idCardBase64.includes(',') ? idCardBase64.split(',')[1] : idCardBase64;

      const res = await fetch('/api/auth/verify-identity', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          selfieBase64: `data:image/jpeg;base64,${selfieData}`,
          idCardBase64: `data:image/jpeg;base64,${idCardData}`,
        }),
      });

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

      const data = await res.json();
      setVerificationResult({
        verified: data.verified ?? false,
        confidence: data.confidence ?? 0,
        reason: data.reason || data.error || '',
      });
      setStep(4);

      if (data.verified) {
        onVerified();
        toast({
          title: language === 'en' ? 'Identity Verified!' : 'পরিচয় যাচাইকৃত!',
          description: language === 'en' ? 'Your account has been verified successfully.' : 'আপনার অ্যাকাউন্ট সফলভাবে যাচাই করা হয়েছে।',
        });
      }
    } catch (err) {
      const message = err instanceof Error && err.message
        ? err.message
        : (language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। আবার চেষ্টা করুন।');
      setVerificationResult({
        verified: false,
        confidence: 0,
        reason: message,
      });
      setStep(4);
    } finally {
      setIsLoading(false);
    }
  };

  const goBack = () => {
    if (step === 1) {
      onOpenChange(false);
    } else if (step === 2) {
      setStep(1);
    } else if (step === 4 && !verificationResult?.verified) {
      setStep(1);
      setSelfiePreview('');
      setSelfieBase64('');
      setIdCardPreview('');
      setIdCardBase64('');
      setVerificationResult(null);
    } else {
      onOpenChange(false);
    }
  };

  const stepLabels = [
    language === 'en' ? 'Selfie' : 'সেলফি',
    language === 'en' ? 'ID Card' : 'আইডি কার্ড',
    language === 'en' ? 'Verify' : 'যাচাই',
    language === 'en' ? 'Result' : 'ফলাফল',
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md p-0 overflow-hidden">
        <DialogHeader className="px-6 pt-6 pb-2 flex-row items-center gap-2 space-y-0">
          <Button variant="ghost" size="sm" onClick={goBack} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
            <ArrowLeft className="h-4 w-4" />
            <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
          </Button>
          <DialogTitle className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5 text-orange-500" />
            {language === 'en' ? 'Verify Your Identity' : 'আপনার পরিচয় যাচাই করুন'}
          </DialogTitle>
        </DialogHeader>

        {/* Step Indicator */}
        <div className="px-6 pb-2">
          <div className="flex items-center justify-between gap-2">
            {[1, 2, 3, 4].map((s) => (
              <div key={s} className="flex flex-1 items-center gap-2">
                <div className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold transition-all duration-300 ${
                  step >= s
                    ? 'bg-orange-500 text-white shadow-md shadow-orange-500/30'
                    : 'bg-muted text-muted-foreground'
                } ${step === s ? 'scale-110 ring-2 ring-orange-500/30' : ''}`}>
                  {step > s ? <CheckCircle className="h-4 w-4" /> : s}
                </div>
                <span className={`hidden sm:block text-[10px] font-medium ${
                  step >= s ? 'text-orange-600 dark:text-orange-400' : 'text-muted-foreground'
                }`}>
                  {stepLabels[s - 1]}
                </span>
                {s < 4 && (
                  <div className={`h-0.5 flex-1 rounded-full transition-all duration-300 ${
                    step > s ? 'bg-orange-500' : 'bg-muted'
                  }`} />
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="px-6 pb-6">
          {/* Not logged in message */}
          {!user && (
            <div className="flex flex-col items-center gap-4 py-6">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-950/40">
                <Lock className="h-8 w-8 text-amber-500" />
              </div>
              <div className="text-center">
                <h3 className="text-base font-semibold text-foreground">
                  {language === 'en' ? 'Login Required' : 'লগইন প্রয়োজন'}
                </h3>
                <p className="mt-1 text-xs text-muted-foreground max-w-xs">
                  {language === 'en'
                    ? 'You need to log in first to verify your identity.'
                    : 'আপনার পরিচয় যাচাই করতে প্রথমে লগইন করুন।'}
                </p>
              </div>
              <Button
                onClick={() => onOpenChange(false)}
                className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
              >
                <LogIn className="mr-2 h-4 w-4" />
                {language === 'en' ? 'Go to Login' : 'লগইন করুন'}
              </Button>
            </div>
          )}

          {/* Step 1: Selfie Upload */}
          {step === 1 && user && (
            <div className="space-y-4">
              <div className="text-center">
                <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-orange-50 dark:bg-orange-950/30">
                  <Camera className="h-7 w-7 text-orange-500" />
                </div>
                <h3 className="text-base font-semibold text-foreground">
                  {language === 'en' ? 'Take a Selfie' : 'একটি সেলফি তুলুন'}
                </h3>
                <p className="mt-1 text-xs text-muted-foreground">
                  {language === 'en'
                    ? 'Upload a clear photo of your face for verification'
                    : 'যাচাইয়ের জন্য আপনার মুখের একটি স্পষ্ট ছবি আপলোড করুন'}
                </p>
              </div>

              <input
                ref={selfieInputRef}
                type="file"
                accept="image/*"
                capture="user"
                onChange={handleSelfieChange}
                className="hidden"
              />

              {selfiePreview ? (
                <div className="relative mx-auto w-48 h-48 rounded-2xl overflow-hidden border-2 border-orange-200 dark:border-orange-800 shadow-lg">
                  <img src={selfiePreview} alt="Selfie preview" className="h-full w-full object-cover" />
                  <button
                    type="button"
                    onClick={() => { setSelfiePreview(''); setSelfieBase64(''); }}
                    className="absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70 transition-colors"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => selfieInputRef.current?.click()}
                  className="mx-auto flex w-48 h-48 flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed border-orange-300 dark:border-orange-700 bg-orange-50/50 dark:bg-orange-950/20 hover:bg-orange-100/70 dark:hover:bg-orange-950/40 transition-all duration-200 hover:border-orange-400 hover:scale-[1.02]"
                >
                  <Upload className="h-8 w-8 text-orange-400" />
                  <span className="text-xs font-medium text-orange-600 dark:text-orange-400">
                    {language === 'en' ? 'Tap to upload' : 'আপলোড করতে ট্যাপ করুন'}
                  </span>
                </button>
              )}

              <Button
                onClick={() => setStep(2)}
                disabled={!selfieBase64}
                className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
              >
                {language === 'en' ? 'Next' : 'পরবর্তী'}
                <ChevronRight className="ml-1 h-4 w-4" />
              </Button>
            </div>
          )}

          {/* Step 2: ID Card Upload */}
          {step === 2 && user && (
            <div className="space-y-4">
              <div className="text-center">
                <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-orange-50 dark:bg-orange-950/30">
                  <CreditCard className="h-7 w-7 text-orange-500" />
                </div>
                <h3 className="text-base font-semibold text-foreground">
                  {language === 'en' ? 'Upload Your ID Card' : 'আপনার আইডি কার্ড আপলোড করুন'}
                </h3>
                <p className="mt-1 text-xs text-muted-foreground">
                  {language === 'en'
                    ? 'Upload a clear photo of your NID or ID card'
                    : 'আপনার এনআইডি বা আইডি কার্ডের একটি স্পষ্ট ছবি আপলোড করুন'}
                </p>
              </div>

              <input
                ref={idCardInputRef}
                type="file"
                accept="image/*"
                onChange={handleIdCardChange}
                className="hidden"
              />

              {idCardPreview ? (
                <div className="relative mx-auto max-w-xs rounded-2xl overflow-hidden border-2 border-orange-200 dark:border-orange-800 shadow-lg">
                  <img src={idCardPreview} alt="ID card preview" className="h-auto w-full object-cover" />
                  <button
                    type="button"
                    onClick={() => { setIdCardPreview(''); setIdCardBase64(''); }}
                    className="absolute top-2 right-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/50 text-white hover:bg-black/70 transition-colors"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => idCardInputRef.current?.click()}
                  className="mx-auto flex w-full max-w-xs h-36 flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed border-orange-300 dark:border-orange-700 bg-orange-50/50 dark:bg-orange-950/20 hover:bg-orange-100/70 dark:hover:bg-orange-950/40 transition-all duration-200 hover:border-orange-400 hover:scale-[1.01]"
                >
                  <Upload className="h-8 w-8 text-orange-400" />
                  <span className="text-xs font-medium text-orange-600 dark:text-orange-400">
                    {language === 'en' ? 'Tap to upload ID card' : 'আইডি কার্ড আপলোড করুন'}
                  </span>
                </button>
              )}

              <div className="flex gap-3">
                <Button
                  variant="outline"
                  onClick={() => setStep(1)}
                  className="flex-1"
                >
                  <ArrowLeft className="mr-1 h-4 w-4" />
                  {language === 'en' ? 'Back' : 'ফিরুন'}
                </Button>
                <Button
                  onClick={handleVerify}
                  disabled={!idCardBase64 || isLoading}
                  className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold"
                >
                  {isLoading ? (
                    <span className="flex items-center gap-1.5">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      {language === 'en' ? 'Verifying...' : 'যাচাই হচ্ছে...'}
                    </span>
                  ) : (
                    <>
                      <Fingerprint className="mr-1 h-4 w-4" />
                      {language === 'en' ? 'Verify' : 'যাচাই করুন'}
                    </>
                  )}
                </Button>
              </div>
            </div>
          )}

          {/* Step 3: AI Verifying */}
          {step === 3 && (
            <div className="flex flex-col items-center justify-center gap-4 py-8">
              <div className="relative">
                <div className="h-20 w-20 rounded-full bg-orange-100 dark:bg-orange-950/40 flex items-center justify-center animate-pulse">
                  <Fingerprint className="h-10 w-10 text-orange-500" />
                </div>
                <div className="absolute inset-0 h-20 w-20 rounded-full border-4 border-orange-200 dark:border-orange-800 border-t-orange-500 animate-spin" />
              </div>
              <div className="text-center">
                <h3 className="text-base font-semibold text-foreground">
                  {language === 'en' ? 'AI is verifying your identity...' : 'এআই আপনার পরিচয় যাচাই করছে...'}
                </h3>
                <p className="mt-1 text-xs text-muted-foreground">
                  {language === 'en'
                    ? 'Comparing your selfie with your ID card photo'
                    : 'আপনার সেলফি আইডি কার্ডের ছবির সাথে মিলানো হচ্ছে'}
                </p>
              </div>
              <div className="flex gap-1.5">
                <div className="h-2 w-2 rounded-full bg-orange-500 animate-bounce [animation-delay:0ms]" />
                <div className="h-2 w-2 rounded-full bg-orange-500 animate-bounce [animation-delay:150ms]" />
                <div className="h-2 w-2 rounded-full bg-orange-500 animate-bounce [animation-delay:300ms]" />
              </div>
            </div>
          )}

          {/* Step 4: Result */}
          {step === 4 && verificationResult && (
            <div className="flex flex-col items-center gap-4 py-4">
              {verificationResult.verified ? (
                <>
                  <div className="flex h-20 w-20 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/40 animate-in zoom-in duration-300">
                    <CheckCircle className="h-12 w-12 text-emerald-500" />
                  </div>
                  <div className="text-center">
                    <h3 className="text-lg font-bold text-emerald-600 dark:text-emerald-400">
                      {language === 'en' ? 'Identity Verified!' : 'পরিচয় যাচাইকৃত!'}
                    </h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {language === 'en'
                        ? `Confidence: ${verificationResult.confidence}%`
                        : `আস্থা: ${verificationResult.confidence}%`}
                    </p>
                    {verificationResult.reason && (
                      <p className="mt-2 text-xs text-muted-foreground/80 max-w-xs">
                        {verificationResult.reason}
                      </p>
                    )}
                  </div>
                  <div className="flex items-center gap-2 rounded-lg bg-emerald-50 dark:bg-emerald-950/30 px-4 py-2">
                    <ShieldCheck className="h-5 w-5 text-emerald-500" />
                    <span className="text-sm font-medium text-emerald-700 dark:text-emerald-400">
                      {language === 'en' ? 'Your account is now verified' : 'আপনার অ্যাকাউন্ট এখন যাচাইকৃত'}
                    </span>
                  </div>
                  <Button
                    onClick={() => onOpenChange(false)}
                    className="w-full bg-gradient-to-r from-emerald-500 to-emerald-600 font-semibold text-white hover:from-emerald-600 hover:to-emerald-700"
                  >
                    {language === 'en' ? 'Done' : 'সম্পন্ন'}
                  </Button>
                </>
              ) : (
                <>
                  <div className="flex h-20 w-20 items-center justify-center rounded-full bg-red-100 dark:bg-red-950/40 animate-in zoom-in duration-300">
                    <XCircle className="h-12 w-12 text-red-500" />
                  </div>
                  <div className="text-center">
                    <h3 className="text-lg font-bold text-red-600 dark:text-red-400">
                      {language === 'en' ? 'Verification Failed' : 'যাচাই ব্যর্থ'}
                    </h3>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {language === 'en'
                        ? `Confidence: ${verificationResult.confidence}%`
                        : `আস্থা: ${verificationResult.confidence}%`}
                    </p>
                    {verificationResult.reason && (
                      <p className="mt-2 text-xs text-muted-foreground/80 max-w-xs">
                        {verificationResult.reason}
                      </p>
                    )}
                  </div>
                  <div className="w-full rounded-lg bg-orange-50 dark:bg-orange-950/30 p-3">
                    <p className="text-xs text-orange-700 dark:text-orange-400 text-center">
                      {language === 'en'
                        ? 'Make sure your selfie and ID card photos are clear and the face is visible in both.'
                        : 'নিশ্চিত করুন যে আপনার সেলফি এবং আইডি কার্ডের ছবি স্পষ্ট এবং উভয়েই মুখ দৃশ্যমান।'}
                    </p>
                  </div>
                  <Button
                    onClick={() => {
                      setStep(1);
                      setSelfiePreview('');
                      setSelfieBase64('');
                      setIdCardPreview('');
                      setIdCardBase64('');
                      setVerificationResult(null);
                    }}
                    className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold"
                  >
                    {language === 'en' ? 'Try Again' : 'আবার চেষ্টা করুন'}
                  </Button>
                </>
              )}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ============ CHANGE PASSWORD DIALOG ============
function ChangePasswordDialog({ open, onOpenChange }: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { language, user } = useAppStore();
  const { toast } = useToast();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!user?.id) {
      setError(language === 'en' ? 'You must be logged in to change your password.' : 'পাসওয়ার্ড পরিবর্তন করতে আপনাকে লগইন করতে হবে।');
      toast({
        title: language === 'en' ? 'Not Logged In' : 'লগইন নেই',
        description: language === 'en' ? 'Please log in to change your password.' : 'পাসওয়ার্ড পরিবর্তন করতে দয়া করে লগইন করুন।',
        variant: 'destructive',
        duration: 4000,
      });
      return;
    }
    setError('');

    if (!currentPassword.trim()) {
      setError(language === 'en' ? 'Please enter your current password' : 'দয়া করে আপনার বর্তমান পাসওয়ার্ড লিখুন');
      return;
    }

    if (newPassword.length < 6) {
      setError(t('profile.minPasswordLength', language));
      return;
    }

    if (newPassword !== confirmPassword) {
      setError(t('auth.passwordMismatch', language));
      return;
    }

    if (currentPassword === newPassword) {
      setError(language === 'en' ? 'New password must be different from current password' : 'নতুন পাসওয়ার্ড বর্তমান পাসওয়ার্ড থেকে আলাদা হতে হবে');
      return;
    }

    setIsLoading(true);

    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          currentPassword,
          newPassword,
        }),
      });
      const data = await res.json();

      if (res.ok) {
        toast({
          title: t('profile.passwordChanged', language),
          description: language === 'en'
            ? 'Your password has been updated successfully. Please use the new password next time you log in.'
            : 'আপনার পাসওয়ার্ড সফলভাবে আপডেট হয়েছে। পরবর্তী লগইনে নতুন পাসওয়ার্ড ব্যবহার করুন।',
          duration: 5000,
        });
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        setShowCurrentPassword(false);
        setShowNewPassword(false);
        setShowConfirmPassword(false);
        onOpenChange(false);
      } else {
        const errorMessage = data.error || t('profile.wrongPassword', language);
        setError(errorMessage);
        toast({
          title: language === 'en' ? 'Change Password Failed' : 'পাসওয়ার্ড পরিবর্তন ব্যর্থ',
          description: errorMessage,
          variant: 'destructive',
          duration: 4000,
        });
      }
    } catch {
      const networkError = language === 'en' ? 'Network error. Please try again.' : 'নেটওয়ার্ক ত্রুটি। দয়া করে আবার চেষ্টা করুন।';
      setError(networkError);
      toast({
        title: language === 'en' ? 'Network Error' : 'নেটওয়ার্ক ত্রুটি',
        description: networkError,
        variant: 'destructive',
        duration: 4000,
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader className="flex-row items-center gap-2 space-y-0">
          <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30 -ml-2">
            <ArrowLeft className="h-4 w-4" />
            <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
          </Button>
          <DialogTitle>{t('profile.changePassword', language)}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && (
            <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-3 text-center text-sm text-destructive">
              {error}
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="current-password">{t('profile.currentPassword', language)}</Label>
            <div className="relative">
              <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="current-password"
                type={showCurrentPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={currentPassword}
                onChange={(e) => { setCurrentPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
              />
              <button
                type="button"
                onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showCurrentPassword ? 'Hide password' : 'Show password'}
              >
                {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="new-pass">{t('auth.newPassword', language)}</Label>
            <div className="relative">
              <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="new-pass"
                type={showNewPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={newPassword}
                onChange={(e) => { setNewPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
                minLength={6}
              />
              <button
                type="button"
                onClick={() => setShowNewPassword(!showNewPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showNewPassword ? 'Hide password' : 'Show password'}
              >
                {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirm-pass">{t('auth.confirmPassword', language)}</Label>
            <div className="relative">
              <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                id="confirm-pass"
                type={showConfirmPassword ? 'text' : 'password'}
                placeholder="••••••••"
                value={confirmPassword}
                onChange={(e) => { setConfirmPassword(e.target.value); setError(''); }}
                className="pl-9 pr-10"
                required
                minLength={6}
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showConfirmPassword ? 'Hide password' : 'Show password'}
              >
                {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
          </div>

          <Button type="submit" className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold" disabled={isLoading}>
            {isLoading ? (
              <span className="flex items-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                {t('common.loading', language)}
              </span>
            ) : (
              t('profile.changePassword', language)
            )}
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}

// ============ MAIN PROFILE MODULE ============
export default function ProfileModule() {
  const { language, isLoggedIn, user, logout, setCurrentSection } = useAppStore();
  const { toast } = useToast();

  const [editOpen, setEditOpen] = useState(false);
  const [changePassOpen, setChangePassOpen] = useState(false);
  const [verificationOpen, setVerificationOpen] = useState(false);
  const [profileData, setProfileData] = useState<any>(null);
  const [stats, setStats] = useState({ listings: 0, orders: 0, favourites: 0, reviews: 0 });
  const [recentOrders, setRecentOrders] = useState<any[]>([]);
  const [socialLinks, setSocialLinks] = useState<Record<string, string>>({});

  const navigateTo = (section: AppSection) => {
    setCurrentSection(section);
  };

  // Fetch profile data when user logs in
  useEffect(() => {
    if (!isLoggedIn || !user?.id) return;

    let cancelled = false;

    const loadProfile = async () => {
      try {
        const res = await fetch('/api/auth/profile?userId=' + user.id);
        const data = await res.json();
        if (!cancelled && data.user) {
          setProfileData(data.user);
          // Parse social links
          if (data.user.socialLinks) {
            try {
              setSocialLinks(JSON.parse(data.user.socialLinks));
            } catch { /* ignore */ }
          }
        }
      } catch {
        // Ignore
      }
    };

    const loadStats = async () => {
      try {
        const [housesRes, shopsRes, productsRes, ordersRes, favRes, reviewsRes] = await Promise.all([
          fetch('/api/houses/my?userId=' + user.id).catch(() => ({ json: () => ({ houses: [] }) })),
          fetch('/api/shops/my?userId=' + user.id).catch(() => ({ json: () => ({ shops: [] }) })),
          fetch('/api/products/my?userId=' + user.id).catch(() => ({ json: () => ({ products: [] }) })),
          fetch('/api/orders?userId=' + user.id + '&limit=5').catch(() => ({ json: () => ({ orders: [], pagination: { total: 0 } }) })),
          fetch('/api/favourites?userId=' + user.id).catch(() => ({ json: () => ({ favourites: [], pagination: { total: 0 } }) })),
          fetch('/api/reviews/my?userId=' + user.id).catch(() => ({ json: () => ({ reviews: [], total: 0 }) })),
        ]);
        const housesData = await housesRes.json();
        const shopsData = await shopsRes.json();
        const productsData = await productsRes.json();
        const ordersData = await ordersRes.json();
        const favData = await favRes.json();
        const reviewsData = await reviewsRes.json();

        if (!cancelled) {
          const listingCount = (housesData.houses?.length || 0) + (shopsData.shops?.length || 0) + (productsData.products?.length || 0);
          const orderCount = ordersData.pagination?.total || ordersData.orders?.length || 0;
          const favCount = favData.pagination?.total || favData.favourites?.length || 0;
          const reviewCount = reviewsData.total || reviewsData.reviews?.length || 0;

          setStats({
            listings: listingCount,
            orders: orderCount,
            favourites: favCount,
            reviews: reviewCount,
          });

          // Set recent orders for activity feed
          if (ordersData.orders && ordersData.orders.length > 0) {
            setRecentOrders(ordersData.orders.slice(0, 3));
          }
        }
      } catch {
        // Ignore
      }
    };

    loadProfile();
    loadStats();

    return () => { cancelled = true; };
  }, [isLoggedIn, user?.id]);

  // Refresh profile data (called after edit)
  const refreshProfile = async () => {
    if (!user?.id) return;
    try {
      const res = await fetch('/api/auth/profile?userId=' + user.id);
      const data = await res.json();
      if (data.user) {
        setProfileData(data.user);
        if (data.user.socialLinks) {
          try {
            setSocialLinks(JSON.parse(data.user.socialLinks));
          } catch { /* ignore */ }
        }
      }
    } catch {
      // Ignore
    }
  };

  const handleLogout = () => {
    logout();
    toast({
      title: language === 'en' ? 'Logged Out' : 'লগআউট হয়েছে',
      description: language === 'en' ? 'See you soon!' : 'শীঘ্রই দেখা হবে!',
      duration: 3000,
    });
  };

  // Calculate profile completion
  const getProfileCompletion = () => {
    if (!profileData) return 0;
    const fields = [
      !!profileData.name,
      !!profileData.email,
      !!profileData.phone,
      !!profileData.bio,
      !!profileData.address,
      !!profileData.avatar,
      !!profileData.division,
      !!profileData.district,
    ];
    const filled = fields.filter(Boolean).length;
    return Math.round((filled / fields.length) * 100);
  };

  const formatDate = (dateStr: string) => {
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString(language === 'en' ? 'en-US' : 'bn-BD', {
        year: 'numeric',
        month: 'long',
      });
    } catch {
      return dateStr;
    }
  };

  const getTimeAgo = (dateStr: string) => {
    try {
      const now = new Date();
      const date = new Date(dateStr);
      const diffMs = now.getTime() - date.getTime();
      const diffMins = Math.floor(diffMs / 60000);
      const diffHours = Math.floor(diffMs / 3600000);
      const diffDays = Math.floor(diffMs / 86400000);

      if (diffMins < 1) return language === 'en' ? 'Just now' : 'এইমাত্র';
      if (diffMins < 60) return language === 'en' ? `${diffMins}m ago` : `${diffMins} মি আগে`;
      if (diffHours < 24) return language === 'en' ? `${diffHours}h ago` : `${diffHours} ঘ আগে`;
      if (diffDays < 7) return language === 'en' ? `${diffDays}d ago` : `${diffDays} দি আগে`;
      return formatDate(dateStr);
    } catch {
      return '';
    }
  };

  // Logged Out State
  if (!isLoggedIn || !user) {
    return (
      <div className="flex min-h-[calc(100vh-8rem)] flex-col items-center justify-center px-6 py-12">
        {/* App Branding */}
        <div className="mb-8 flex flex-col items-center gap-4">
          <img
            src="/logo-needyfy.png"
            alt="Needyfy Logo"
            className="h-24 w-24 rounded-3xl object-cover shadow-lg shadow-primary/25"
          />
          <div className="text-center">
            <h1 className="gradient-text text-3xl font-bold tracking-tight">
              {t('app.name', language)}
            </h1>
            <p className="mt-1 text-sm text-muted-foreground">
              {t('app.tagline', language)}
            </p>
          </div>
        </div>

        {/* Login Message */}
        <div className="mb-8 rounded-2xl bg-accent/50 p-6 text-center">
          <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
            <UserPlus className="h-6 w-6 text-primary" />
          </div>
          <p className="text-sm font-medium text-foreground">
            {language === 'en' ? 'Login to access all features' : 'সব ফিচার ব্যবহার করতে লগইন করুন'}
          </p>
          <p className="mt-1 text-xs text-muted-foreground">
            {language === 'en'
              ? 'Manage your listings, orders, and more'
              : 'আপনার তালিকা, অর্ডার এবং আরও অনেক কিছু পরিচালনা করুন'}
          </p>
        </div>

        {/* Auth Buttons */}
        <div className="flex w-full max-w-xs flex-col gap-3">
          <Button
            onClick={() => navigateTo('auth')}
            className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold shadow-md shadow-primary/20"
            size="lg"
          >
            <LogIn className="mr-2 h-4 w-4" />
            {t('profile.login', language)}
          </Button>
          <Button
            variant="outline"
            onClick={() => navigateTo('auth')}
            className="w-full border-primary/20 font-semibold text-primary hover:bg-primary/5"
            size="lg"
          >
            <UserPlus className="mr-2 h-4 w-4" />
            {t('profile.signup', language)}
          </Button>
        </div>
      </div>
    );
  }

  // Logged In State
  const displayUser = profileData || user;
  const initials = displayUser.name
    .split(' ')
    .map((n: string) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
  const completion = getProfileCompletion();

  return (
    <div className="custom-scrollbar flex min-h-[calc(100vh-8rem)] flex-col overflow-y-auto pb-6">
      {/* ====== PROFILE HEADER ====== */}
      <div className="relative">
        {/* Back Button */}
        <div className="absolute top-3 left-3 z-20">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setCurrentSection('home')}
            className="h-9 w-9 rounded-full bg-black/20 text-white hover:bg-black/40 hover:text-white backdrop-blur-sm"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
        </div>

        {/* Banner / Cover Photo */}
        <div className="h-32 bg-gradient-to-br from-primary via-primary/85 to-amber-500 relative overflow-hidden">
          {/* Decorative pattern */}
          <div className="absolute inset-0 opacity-10">
            <div className="absolute top-0 right-0 w-40 h-40 rounded-full bg-white/30 -translate-y-1/2 translate-x-1/4" />
            <div className="absolute bottom-0 left-0 w-32 h-32 rounded-full bg-white/20 translate-y-1/2 -translate-x-1/4" />
            <div className="absolute top-1/2 left-1/2 w-24 h-24 rounded-full bg-white/15 -translate-x-1/2 -translate-y-1/2" />
          </div>
        </div>

        {/* Avatar overlapping the banner */}
        <div className="flex flex-col items-center -mt-14 relative z-10">
          <div className="relative group">
            <Avatar className="h-28 w-28 border-4 border-background shadow-xl ring-4 ring-primary/10">
              <AvatarImage src={displayUser.avatar} alt={displayUser.name} />
              <AvatarFallback className="bg-primary/10 text-3xl font-bold text-primary">
                {initials}
              </AvatarFallback>
            </Avatar>
            {/* Camera overlay */}
            <button
              className="absolute bottom-1 right-1 flex h-9 w-9 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-all duration-200 hover:scale-110 active:scale-95 hover:shadow-xl"
              onClick={() => setEditOpen(true)}
              aria-label="Change avatar"
            >
              <Camera className="h-4 w-4" />
            </button>
            {/* Verified badge */}
            {displayUser.isVerified && (
              <div className="absolute -top-1 -right-1 flex h-7 w-7 items-center justify-center rounded-full bg-emerald-500 shadow-md">
                <CheckCircle className="h-4 w-4 text-white" />
              </div>
            )}
          </div>

          {/* Name & Info */}
          <div className="mt-3 text-center px-6">
            <div className="flex items-center justify-center gap-2">
              <h2 className="text-xl font-bold text-foreground">{displayUser.name}</h2>
              {displayUser.isVerified && (
                <Badge className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-0 text-[10px] px-1.5">
                  <ShieldCheck className="mr-0.5 h-3 w-3" />
                  {t('profile.verified', language)}
                </Badge>
              )}
            </div>
            <div className="mt-1 flex flex-col items-center gap-0.5">
              <p className="flex items-center gap-1 text-sm text-muted-foreground">
                <Mail className="h-3 w-3" />
                {displayUser.email}
              </p>
              {displayUser.phone && (
                <p className="flex items-center gap-1 text-xs text-muted-foreground">
                  <Phone className="h-3 w-3" />
                  {displayUser.phone}
                </p>
              )}
              {displayUser.address && (
                <p className="flex items-center gap-1 text-xs text-muted-foreground">
                  <MapPin className="h-3 w-3" />
                  {displayUser.address}
                </p>
              )}
              {displayUser.createdAt && (
                <p className="flex items-center gap-1 text-xs text-muted-foreground/60 mt-0.5">
                  <Calendar className="h-3 w-3" />
                  {language === 'en' ? 'Member since' : 'সদস্য হয়েছেন'} {formatDate(displayUser.createdAt)}
                </p>
              )}
            </div>
          </div>

          {/* Role Badges */}
          {user.roles && user.roles.length > 0 && (
            <div className="mt-2 flex flex-wrap items-center justify-center gap-2">
              {user.roles.map((role) => (
                <Badge
                  key={role}
                  variant="secondary"
                  className={`border-0 text-[11px] font-medium ${
                    roleColors[role] || 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300'
                  }`}
                >
                  {roleLabels[role] || role}
                </Badge>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* ====== PROFILE COMPLETION ====== */}
      <div className="px-4 mt-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center gap-4">
              <ProfileCompletionCircle percentage={completion} />
              <div className="flex-1">
                <div className="flex items-center justify-between mb-1">
                  <p className="text-sm font-medium text-foreground">
                    {language === 'en' ? 'Profile Completion' : 'প্রোফাইল সম্পূর্ণতা'}
                  </p>
                  <span className="text-xs text-muted-foreground">{completion}%</span>
                </div>
                <Progress value={completion} className="h-2" />
                {completion < 80 && (
                  <button
                    onClick={() => setEditOpen(true)}
                    className="mt-2 text-xs font-medium text-primary hover:underline flex items-center gap-1"
                  >
                    <Sparkles className="h-3 w-3" />
                    {language === 'en' ? 'Complete your profile' : 'আপনার প্রোফাইল সম্পূর্ণ করুন'}
                  </button>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ====== STATS ROW ====== */}
      <div className="px-4 mt-3">
        <Card className="shadow-md">
          <CardContent className="grid grid-cols-4 gap-2 p-2">
            <StatCard
              value={stats.listings}
              label={language === 'en' ? 'Listings' : 'তালিকা'}
              icon={ListChecks}
              onClick={() => navigateTo('house-rental')}
            />
            <StatCard
              value={stats.orders}
              label={language === 'en' ? 'Orders' : 'অর্ডার'}
              icon={ShoppingBag}
              onClick={() => navigateTo('orders')}
            />
            <StatCard
              value={stats.favourites}
              label={language === 'en' ? 'Favourites' : 'পছন্দ'}
              icon={Heart}
              onClick={() => navigateTo('favourites')}
            />
            <StatCard
              value={stats.reviews}
              label={language === 'en' ? 'Reviews' : 'রিভিউ'}
              icon={Star}
              onClick={() => navigateTo('profile')}
            />
          </CardContent>
        </Card>
      </div>

      {/* ====== BIO SECTION ====== */}
      {displayUser.bio && (
        <div className="px-4 mt-3">
          <Card>
            <CardContent className="p-4">
              <p className="text-sm text-muted-foreground leading-relaxed">{displayUser.bio}</p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ====== SOCIAL LINKS ====== */}
      {Object.keys(socialLinks).length > 0 && (
        <div className="px-4 mt-3">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center gap-2 mb-2">
                <Share2 className="h-4 w-4 text-primary" />
                <span className="text-sm font-medium">
                  {language === 'en' ? 'Social Links' : 'সোশ্যাল লিঙ্ক'}
                </span>
              </div>
              <div className="flex flex-wrap gap-2">
                {socialLinks.facebook && (
                  <a
                    href={socialLinks.facebook.startsWith('http') ? socialLinks.facebook : `https://facebook.com/${socialLinks.facebook}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 rounded-lg bg-orange-500/10 px-3 py-1.5 text-xs font-medium text-orange-600 dark:text-orange-400 hover:bg-orange-500/20 transition-colors"
                  >
                    <Facebook className="h-3.5 w-3.5" />
                    Facebook
                  </a>
                )}
                {socialLinks.whatsapp && (
                  <a
                    href={`https://wa.me/${socialLinks.whatsapp.replace(/[^0-9]/g, '')}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 rounded-lg bg-green-500/10 px-3 py-1.5 text-xs font-medium text-green-600 dark:text-green-400 hover:bg-green-500/20 transition-colors"
                  >
                    <MessageCircle className="h-3.5 w-3.5" />
                    WhatsApp
                  </a>
                )}
                {socialLinks.telegram && (
                  <a
                    href={socialLinks.telegram.startsWith('http') ? socialLinks.telegram : `https://t.me/${socialLinks.telegram.replace('@', '')}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 rounded-lg bg-orange-500/10 px-3 py-1.5 text-xs font-medium text-orange-600 dark:text-orange-400 hover:bg-orange-500/20 transition-colors"
                  >
                    <Share2 className="h-3.5 w-3.5" />
                    Telegram
                  </a>
                )}
                {socialLinks.instagram && (
                  <a
                    href={socialLinks.instagram.startsWith('http') ? socialLinks.instagram : `https://instagram.com/${socialLinks.instagram.replace('@', '')}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-1.5 rounded-lg bg-pink-500/10 px-3 py-1.5 text-xs font-medium text-pink-600 dark:text-pink-400 hover:bg-pink-500/20 transition-colors"
                  >
                    <Camera className="h-3.5 w-3.5" />
                    Instagram
                  </a>
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* ====== RECENT ACTIVITY ====== */}
      <div className="px-4 mt-3">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <Clock className="h-4 w-4 text-primary" />
                <span className="text-sm font-medium">
                  {language === 'en' ? 'Recent Activity' : 'সাম্প্রতিক কার্যক্রম'}
                </span>
              </div>
              {recentOrders.length > 0 && (
                <button
                  onClick={() => navigateTo('orders')}
                  className="text-xs text-primary hover:underline"
                >
                  {language === 'en' ? 'View all' : 'সব দেখুন'}
                </button>
              )}
            </div>
            {recentOrders.length > 0 ? (
              <div className="divide-y divide-border/50">
                {recentOrders.map((order: any) => (
                  <ActivityItem
                    key={order.id}
                    icon={ShoppingBag}
                    iconColor="bg-primary/10 text-primary"
                    title={language === 'en' ? `Order #${order.id.slice(-6).toUpperCase()}` : `অর্ডার #${order.id.slice(-6).toUpperCase()}`}
                    description={`${language === 'en' ? 'Status' : 'অবস্থা'}: ${order.status} · ৳${order.totalAmount?.toFixed(0) || '0'}`}
                    time={getTimeAgo(order.createdAt)}
                  />
                ))}
              </div>
            ) : stats.listings > 0 ? (
              <div className="divide-y divide-border/50">
                <ActivityItem
                  icon={Home}
                  iconColor="bg-amber-500/10 text-amber-500"
                  title={language === 'en' ? `${stats.listings} Active Listing${stats.listings > 1 ? 's' : ''}` : `${stats.listings}টি সক্রিয় তালিকা`}
                  description={language === 'en' ? 'Your listings are live' : 'আপনার তালিকা সরাসরি আছে'}
                  time={language === 'en' ? 'Active' : 'সক্রিয়'}
                />
              </div>
            ) : (
              <div className="py-4 text-center">
                <div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-muted/50">
                  <Clock className="h-5 w-5 text-muted-foreground" />
                </div>
                <p className="text-xs text-muted-foreground">
                  {language === 'en' ? 'No recent activity yet' : 'এখনো কোনো কার্যক্রম নেই'}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* ====== MENU ITEMS ====== */}
      <div className="mt-3 px-4 space-y-3">
        {/* Account Category */}
        <div>
          <p className="mb-1.5 px-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {language === 'en' ? 'Account' : 'অ্যাকাউন্ট'}
          </p>
          <Card>
            <CardContent className="p-2">
              <MenuItem
                icon={Edit3}
                label={t('profile.editProfile', language)}
                description={language === 'en' ? 'Update your personal info' : 'আপনার ব্যক্তিগত তথ্য আপডেট করুন'}
                onClick={() => setEditOpen(true)}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Lock}
                label={t('profile.changePassword', language)}
                description={language === 'en' ? 'Keep your account secure' : 'আপনার অ্যাকাউন্ট নিরাপদ রাখুন'}
                onClick={() => {
                  if (isLoggedIn) {
                    setChangePassOpen(true);
                  } else {
                    toast({
                      title: language === 'en' ? 'Not Logged In' : 'লগইন নেই',
                      description: language === 'en' ? 'Please log in to change your password.' : 'পাসওয়ার্ড পরিবর্তন করতে দয়া করে লগইন করুন।',
                      variant: 'destructive',
                      duration: 3000,
                    });
                    setCurrentSection('auth');
                  }
                }}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Shield}
                label={language === 'en' ? 'Verification' : 'যাচাইকরণ'}
                description={displayUser.isVerified
                  ? (language === 'en' ? 'Your account is verified' : 'আপনার অ্যাকাউন্ট যাচাইকৃত')
                  : (language === 'en' ? 'Verify your identity' : 'আপনার পরিচয় যাচাই করুন')
                }
                onClick={() => setVerificationOpen(true)}
                badge={displayUser.isVerified ? '✓' : undefined}
              />
            </CardContent>
          </Card>
        </div>

        {/* Content Category */}
        <div>
          <p className="mb-1.5 px-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {language === 'en' ? 'Content' : 'বিষয়বস্তু'}
          </p>
          <Card>
            <CardContent className="p-2">
              <MenuItem
                icon={Home}
                label={language === 'en' ? 'My Houses' : 'আমার বাড়ি'}
                description={language === 'en' ? 'Manage house listings' : 'বাড়ির তালিকা পরিচালনা'}
                onClick={() => navigateTo('house-rental')}
                badge={stats.listings || undefined}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Store}
                label={language === 'en' ? 'My Shops' : 'আমার দোকান'}
                description={language === 'en' ? 'Manage shop listings' : 'দোকানের তালিকা পরিচালনা'}
                onClick={() => navigateTo('shop-rental')}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={ShoppingBag}
                label={t('profile.myOrders', language)}
                description={language === 'en' ? 'Track your purchases' : 'আপনার কেনাকাটা ট্র্যাক করুন'}
                onClick={() => navigateTo('orders')}
                badge={stats.orders || undefined}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Heart}
                label={t('fav.title', language)}
                description={language === 'en' ? 'Your saved items' : 'আপনার সংরক্ষিত আইটেম'}
                onClick={() => navigateTo('favourites')}
                badge={stats.favourites || undefined}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Star}
                label={t('profile.myReviews', language)}
                description={language === 'en' ? 'Reviews you have written' : 'আপনার লেখা রিভিউ'}
                onClick={() => navigateTo('profile')}
                badge={stats.reviews || undefined}
              />
            </CardContent>
          </Card>
        </div>

        {/* Support Category */}
        <div>
          <p className="mb-1.5 px-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {language === 'en' ? 'Support' : 'সাহায্য'}
          </p>
          <Card>
            <CardContent className="p-2">
              <MenuItem
                icon={Bell}
                label={t('settings.notifications', language)}
                description={language === 'en' ? 'Manage alerts' : 'বিজ্ঞপ্তি পরিচালনা'}
                onClick={() => navigateTo('settings')}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Settings}
                label={t('settings.title', language)}
                description={language === 'en' ? 'App preferences' : 'অ্যাপ পছন্দসমূহ'}
                onClick={() => navigateTo('settings')}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={HelpCircle}
                label={t('settings.help', language)}
                description={language === 'en' ? 'FAQs and support' : 'সাহায্য ও সমর্থন'}
                onClick={() => navigateTo('settings')}
              />
              <Separator className="mx-4" />
              <MenuItem
                icon={Info}
                label={language === 'en' ? 'About Needyfy' : 'Needyfy সম্পর্কে'}
                description="v0.0.8"
                onClick={() => navigateTo('settings')}
              />
            </CardContent>
          </Card>
        </div>

        {/* Logout */}
        <Card>
          <CardContent className="p-2">
            <MenuItem
              icon={LogOut}
              label={t('profile.logout', language)}
              onClick={handleLogout}
              danger
            />
          </CardContent>
        </Card>
      </div>

      {/* ====== DIALOGS ====== */}
      <EditProfileDialog
        open={editOpen}
        onOpenChange={setEditOpen}
        onProfileUpdated={refreshProfile}
      />
      <ChangePasswordDialog
        open={changePassOpen}
        onOpenChange={setChangePassOpen}
      />
      <VerificationDialog
        open={verificationOpen}
        onOpenChange={setVerificationOpen}
        onVerified={refreshProfile}
      />
    </div>
  );
}
