'use client';

import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockHouses, bangladeshDivisions } from '@/lib/mock-data';
import { getDistricts, getUpazilas, getUnions } from '@/lib/bangladesh-locations';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
/* Sheet removed - filter now uses Dialog */
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Search,
  SlidersHorizontal,
  MapPin,
  Heart,
  Bed,
  Bath,
  Maximize,
  Building2,
  Phone,
  MessageCircle,
  X,
  RotateCcw,
  Plus,
  Edit3,
  Trash2,
  Eye,
  EyeOff,
  Home,
  Navigation,
} from 'lucide-react';

type RentType = 'all' | 'family' | 'bachelor' | 'both';

interface HouseFilters {
  rentType: RentType;
  rooms: number | null;
  priceMin: string;
  priceMax: string;
  division: string;
  district: string;
  upazila: string;
  union: string;
}

interface DbHouse {
  id: string;
  title: string;
  description: string;
  price: number;
  rooms: number;
  bathrooms: number | null;
  area: number | null;
  floor: string | null;
  houseType: string;
  rentType: string;
  isAvailable: boolean;
  images: string;
  address: string;
  division: string;
  district: string;
  upazila: string | null;
  createdAt: string;
  owner: { id: string; name: string; phone: string | null; avatar: string | null };
}

// ─── House Upload Form ──────────────────────────────────────────
function HouseUploadForm({
  language,
  ownerId,
  onHousePosted,
  editHouse,
  onCancelEdit,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onHousePosted: () => void;
  editHouse: DbHouse | null;
  onCancelEdit: () => void;
}) {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);

  const [form, setForm] = useState({
    title: editHouse?.title || '',
    description: editHouse?.description || '',
    price: editHouse?.price?.toString() || '',
    rooms: editHouse?.rooms?.toString() || '',
    bathrooms: editHouse?.bathrooms?.toString() || '',
    area: editHouse?.area?.toString() || '',
    floor: editHouse?.floor || '',
    houseType: editHouse?.houseType || 'flat',
    rentType: editHouse?.rentType || 'both',
    address: editHouse?.address || '',
    division: editHouse?.division || '',
    district: editHouse?.district || '',
    upazila: editHouse?.upazila || '',
  });

  // Update form when editHouse changes
  useEffect(() => {
    if (editHouse) {
      setForm({
        title: editHouse.title,
        description: editHouse.description,
        price: editHouse.price.toString(),
        rooms: editHouse.rooms.toString(),
        bathrooms: editHouse.bathrooms?.toString() || '',
        area: editHouse.area?.toString() || '',
        floor: editHouse.floor || '',
        houseType: editHouse.houseType,
        rentType: editHouse.rentType,
        address: editHouse.address,
        division: editHouse.division,
        district: editHouse.district,
        upazila: editHouse.upazila || '',
      });
    }
  }, [editHouse]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title || !form.description || !form.price || !form.rooms || !form.address || !form.division || !form.district) {
      toast({ title: 'Please fill all required fields', variant: 'destructive' });
      return;
    }

    setIsLoading(true);
    try {
      if (editHouse) {
        // Update existing house
        const res = await fetch('/api/houses', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: editHouse.id,
            ...form,
            price: parseFloat(form.price),
            rooms: parseInt(form.rooms),
            bathrooms: form.bathrooms ? parseInt(form.bathrooms) : null,
            area: form.area ? parseFloat(form.area) : null,
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: t('house.updateSuccess', language) });
          onHousePosted();
          onCancelEdit();
        } else {
          toast({ title: data.error || 'Failed to update', variant: 'destructive' });
        }
      } else {
        // Create new house
        const res = await fetch('/api/houses', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...form,
            price: parseFloat(form.price),
            rooms: parseInt(form.rooms),
            bathrooms: form.bathrooms ? parseInt(form.bathrooms) : null,
            area: form.area ? parseFloat(form.area) : null,
            ownerId,
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: t('house.postSuccess', language) });
          onHousePosted();
          // Reset form
          setForm({
            title: '', description: '', price: '', rooms: '', bathrooms: '',
            area: '', floor: '', houseType: 'flat', rentType: 'both',
            address: '', division: '', district: '', upazila: '',
          });
        } else {
          toast({ title: data.error || 'Failed to post', variant: 'destructive' });
        }
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally {
      setIsLoading(false);
    }
  };

  const inputClass = "text-sm";

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {editHouse && (
        <div className="rounded-lg border border-primary/20 bg-primary/5 p-3 text-center text-xs font-medium text-primary">
          {language === 'en' ? 'Editing' : 'সম্পাদনা করছেন'}: {editHouse.title}
        </div>
      )}

      {/* Title */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{t('house.houseTitle', language)} *</Label>
        <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder={language === 'en' ? 'e.g. 3BHK Flat in Dhanmondi' : 'যেমন: ধানমন্ডিতে ৩ বেডরুম ফ্ল্যাট'} className={inputClass} required />
      </div>

      {/* Description */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{t('house.description', language)} *</Label>
        <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={language === 'en' ? 'Describe your house...' : 'আপনার বাড়ির বিবরণ...'} className="min-h-[80px] text-sm" required />
      </div>

      {/* House Type & Rent Type */}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.houseType', language)} *</Label>
          <select value={form.houseType} onChange={(e) => setForm({ ...form, houseType: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="flat">{t('house.flat', language)}</option>
            <option value="house">{t('house.house', language)}</option>
            <option value="room">{t('house.room', language)}</option>
            <option value="mess">{t('house.mess', language)}</option>
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.rentType', language)} *</Label>
          <select value={form.rentType} onChange={(e) => setForm({ ...form, rentType: e.target.value })} className="w-full rounded-md border bg-background px-3 py-2 text-sm">
            <option value="family">{t('house.family', language)}</option>
            <option value="bachelor">{t('house.bachelor', language)}</option>
            <option value="both">{t('house.both', language)}</option>
          </select>
        </div>
      </div>

      {/* Price & Floor */}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.monthlyRent', language)} *</Label>
          <Input type="number" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="25000" className={inputClass} required />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.floorNo', language)}</Label>
          <Input value={form.floor} onChange={(e) => setForm({ ...form, floor: e.target.value })} placeholder={language === 'en' ? 'e.g. 4th' : 'যেমন: ৪র্থ'} className={inputClass} />
        </div>
      </div>

      {/* Rooms, Bathrooms, Area */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.noBedrooms', language)} *</Label>
          <Input type="number" value={form.rooms} onChange={(e) => setForm({ ...form, rooms: e.target.value })} placeholder="3" className={inputClass} required min="1" />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.noBathrooms', language)}</Label>
          <Input type="number" value={form.bathrooms} onChange={(e) => setForm({ ...form, bathrooms: e.target.value })} placeholder="2" className={inputClass} min="0" />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.areaSqft', language)}</Label>
          <Input type="number" value={form.area} onChange={(e) => setForm({ ...form, area: e.target.value })} placeholder="1200" className={inputClass} min="0" />
        </div>
      </div>

      <Separator />

      {/* Address */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{t('house.addressLine', language)} *</Label>
        <Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} placeholder={language === 'en' ? 'House 12, Road 27, Dhanmondi' : 'বাড়ি ১২, রোড ২৭, ধানমন্ডি'} className={inputClass} required />
      </div>

      {/* Division, District, Upazila */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.division', language)} *</Label>
          <select value={form.division} onChange={(e) => setForm({ ...form, division: e.target.value })} className="w-full rounded-md border bg-background px-2 py-2 text-sm" required>
            <option value="">{language === 'en' ? 'Select' : 'নির্বাচন'}</option>
            {bangladeshDivisions.map((d) => <option key={d} value={d}>{d}</option>)}
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.district', language)} *</Label>
          <Input value={form.district} onChange={(e) => setForm({ ...form, district: e.target.value })} placeholder={language === 'en' ? 'Dhaka' : 'ঢাকা'} className={inputClass} required />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.upazila', language)}</Label>
          <Input value={form.upazila} onChange={(e) => setForm({ ...form, upazila: e.target.value })} placeholder={language === 'en' ? 'Dhanmondi' : 'ধানমন্ডি'} className={inputClass} />
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex gap-3 pt-2">
        {editHouse && (
          <Button type="button" variant="outline" className="flex-1" onClick={onCancelEdit}>
            {t('common.cancel', language)}
          </Button>
        )}
        <Button type="submit" className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold" disabled={isLoading}>
          {isLoading ? t('common.loading', language) : editHouse ? t('common.save', language) : t('house.postHouse', language)}
        </Button>
      </div>
    </form>
  );
}

// ─── Owner's Houses Section ─────────────────────────────────────
function OwnerHouses({
  language,
  ownerId,
  onRefresh,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onRefresh: () => void;
}) {
  const { toast } = useToast();
  const [houses, setHouses] = useState<DbHouse[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingHouse, setEditingHouse] = useState<DbHouse | null>(null);
  const [uploadOpen, setUploadOpen] = useState(false);

  const fetchMyHouses = useCallback(async () => {
    try {
      const res = await fetch(`/api/houses/my?ownerId=${ownerId}`);
      const data = await res.json();
      if (data.houses) setHouses(data.houses);
    } catch (err) {
      console.error('Failed to fetch my houses:', err);
    } finally {
      setLoading(false);
    }
  }, [ownerId]);

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

  const handleToggleAvailable = async (houseId: string, current: boolean) => {
    try {
      const res = await fetch('/api/houses', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: houseId, isAvailable: !current }),
      });
      if (res.ok) {
        toast({ title: current ? t('house.markRented', language) : t('house.availableNow', language) });
        fetchMyHouses();
      }
    } catch (err) {
      console.error('Failed to toggle:', err);
    }
  };

  const handleDelete = async (houseId: string) => {
    try {
      const res = await fetch('/api/houses', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: houseId }),
      });
      if (res.ok) {
        toast({ title: t('house.deleteSuccess', language) });
        fetchMyHouses();
      }
    } catch (err) {
      console.error('Failed to delete:', err);
    }
  };

  const handleEdit = (house: DbHouse) => {
    setEditingHouse(house);
    setUploadOpen(true);
  };

  const handleNewHouse = () => {
    setEditingHouse(null);
    setUploadOpen(true);
  };

  const handleHousePosted = () => {
    fetchMyHouses();
    onRefresh();
    setUploadOpen(false);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header with Post button */}
      <div className="flex items-center justify-between">
        <h2 className="text-base font-bold">{t('house.myListings', language)}</h2>
        <Button size="sm" className="gap-1" onClick={handleNewHouse}>
          <Plus className="h-4 w-4" />
          {t('house.postHouse', language)}
        </Button>
      </div>

      {/* Upload Dialog */}
      <Dialog open={uploadOpen} onOpenChange={setUploadOpen}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          <DialogHeader>
            <DialogTitle>{editingHouse ? t('house.editHouse', language) : t('house.uploadHouse', language)}</DialogTitle>
            <DialogDescription>
              {language === 'en'
                ? 'Fill in the details to list your house'
                : 'আপনার বাড়ি তালিকাভুক্ত করতে বিস্তারিত পূরণ করুন'}
            </DialogDescription>
          </DialogHeader>
          <HouseUploadForm
            language={language}
            ownerId={ownerId}
            onHousePosted={handleHousePosted}
            editHouse={editingHouse}
            onCancelEdit={() => { setEditingHouse(null); setUploadOpen(false); }}
          />
        </DialogContent>
      </Dialog>

      {/* Houses List */}
      {houses.length === 0 ? (
        <Card className="py-8">
          <CardContent className="flex flex-col items-center gap-3 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10">
              <Building2 className="h-8 w-8 text-primary/40" />
            </div>
            <p className="text-sm text-muted-foreground">
              {language === 'en' ? 'No houses listed yet' : 'এখনো কোনো বাড়ি তালিকাভুক্ত নেই'}
            </p>
            <Button size="sm" variant="outline" onClick={handleNewHouse} className="gap-1">
              <Plus className="h-4 w-4" />
              {t('house.postHouse', language)}
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {houses.map((house) => (
            <Card key={house.id} className="overflow-hidden transition-shadow hover:shadow-md">
              <div className={`relative h-28 overflow-hidden bg-gradient-to-br ${
                house.houseType === 'flat' ? 'from-orange-400 to-amber-500' :
                house.houseType === 'house' ? 'from-orange-500 to-red-500' :
                house.houseType === 'room' ? 'from-amber-400 to-orange-500' :
                'from-yellow-400 to-orange-400'
              }`}>
                {house.images ? (
                  <img src={house.images} alt={house.title} className="h-full w-full object-cover" loading="lazy" />
                ) : (
                  <div className="flex h-full items-center justify-center">
                    <Building2 className="h-12 w-12 text-white/30" />
                  </div>
                )}
                <Badge className={`absolute left-3 top-3 text-[10px] ${
                  house.isAvailable
                    ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                    : 'bg-red-500 text-white hover:bg-red-600'
                }`}>
                  {house.isAvailable ? t('house.availableNow', language) : t('house.rented', language)}
                </Badge>
              </div>
              <CardContent className="p-3">
                <h3 className="truncate text-sm font-semibold">{house.title}</h3>
                <div className="mt-1 flex items-center gap-2">
                  <span className="text-base font-bold text-primary">৳{house.price.toLocaleString()}</span>
                  <span className="text-[10px] text-muted-foreground">{t('house.perMonth', language)}</span>
                </div>
                <div className="mt-1 flex items-center gap-2 text-[10px] text-muted-foreground">
                  <span className="flex items-center gap-0.5"><Bed className="h-3 w-3" />{house.rooms}</span>
                  <span className="flex items-center gap-0.5"><Bath className="h-3 w-3" />{house.bathrooms || '-'}</span>
                  {house.area && <span>{house.area} sqft</span>}
                </div>
                <div className="mt-3 flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    className="flex-1 text-[11px]"
                    onClick={() => handleToggleAvailable(house.id, house.isAvailable)}
                  >
                    {house.isAvailable ? (
                      <><EyeOff className="mr-1 h-3 w-3" />{t('house.markRented', language)}</>
                    ) : (
                      <><Eye className="mr-1 h-3 w-3" />{t('house.availableNow', language)}</>
                    )}
                  </Button>
                  <Button variant="outline" size="sm" className="text-[11px]" onClick={() => handleEdit(house)}>
                    <Edit3 className="h-3 w-3" />
                  </Button>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button variant="outline" size="sm" className="text-[11px] text-destructive hover:bg-destructive/5">
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                        <AlertDialogDescription>
                          {language === 'en'
                            ? `This will permanently delete "${house.title}".`
                            : `এটি "${house.title}" স্থায়ীভাবে মুছে ফেলবে।`}
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                        <AlertDialogAction className="bg-destructive text-destructive-foreground" onClick={() => handleDelete(house.id)}>
                          {t('common.delete', language)}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Main House Rental Module ───────────────────────────────────
export default function HouseRentalModule() {
  const { language, isLoggedIn, user, setCurrentSection, setOpenChatWith } = useAppStore();
  const { toast } = useToast();

  const [searchQuery, setSearchQuery] = useState('');
  const [filterOpen, setFilterOpen] = useState(false);
  const [selectedHouseId, setSelectedHouseId] = useState<string | null>(null);
  const [favourites, setFavourites] = useState<Set<string>>(new Set());
  const [ownerMode, setOwnerMode] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [selectedPriceRange, setSelectedPriceRange] = useState<string | null>(null);

  // Refs for auto-scrolling in filter dialog
  const filterScrollRef = useRef<HTMLDivElement>(null);
  const districtRef = useRef<HTMLDivElement>(null);
  const upazilaRef = useRef<HTMLDivElement>(null);
  const unionRef = useRef<HTMLDivElement>(null);

  const isHouseOwner = isLoggedIn && user?.roles?.includes('houseOwner');

  const [filters, setFilters] = useState<HouseFilters>({
    rentType: 'all',
    rooms: null,
    priceMin: '',
    priceMax: '',
    division: '',
    district: '',
    upazila: '',
    union: '',
  });

  const [appliedFilters, setAppliedFilters] = useState<HouseFilters>({
    rentType: 'all',
    rooms: null,
    priceMin: '',
    priceMax: '',
    division: '',
    district: '',
    upazila: '',
    union: '',
  });

  // Auto-scroll to newly appeared filter dropdown
  useEffect(() => {
    if (!filterOpen) return;
    // Small delay to let the DOM render the new select
    const timer = setTimeout(() => {
      if (filters.union && unionRef.current) {
        unionRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      } else if (filters.upazila && upazilaRef.current) {
        upazilaRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      } else if (filters.district && districtRef.current) {
        districtRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      }
    }, 100);
    return () => clearTimeout(timer);
  }, [filters.division, filters.district, filters.upazila, filters.union, filterOpen]);

  const filteredHouses = useMemo(() => {
    return mockHouses.filter((house) => {
      if (searchQuery) {
        const q = searchQuery.toLowerCase();
        const matchesSearch =
          house.title.toLowerCase().includes(q) ||
          house.address.toLowerCase().includes(q) ||
          house.division.toLowerCase().includes(q) ||
          house.description.toLowerCase().includes(q);
        if (!matchesSearch) return false;
      }
      if (appliedFilters.rentType !== 'all') {
        if (appliedFilters.rentType === 'both') {
          if (house.rentType !== 'both') return false;
        } else if (house.rentType !== appliedFilters.rentType && house.rentType !== 'both') {
          return false;
        }
      }
      if (appliedFilters.rooms !== null) {
        if (appliedFilters.rooms === 5) {
          if (house.rooms < 5) return false;
        } else {
          if (house.rooms !== appliedFilters.rooms) return false;
        }
      }
      if (appliedFilters.priceMin) {
        const min = parseInt(appliedFilters.priceMin);
        if (!isNaN(min) && house.price < min) return false;
      }
      if (appliedFilters.priceMax) {
        const max = parseInt(appliedFilters.priceMax);
        if (!isNaN(max) && house.price > max) return false;
      }
      if (appliedFilters.division) {
        if (house.division !== appliedFilters.division) return false;
      }
      if (appliedFilters.district) {
        if (house.district !== appliedFilters.district) return false;
      }
      if (appliedFilters.upazila) {
        if (house.upazila !== appliedFilters.upazila) return false;
      }
      return true;
    });
  }, [searchQuery, appliedFilters]);

  const selectedHouse = useMemo(
    () => mockHouses.find((h) => h.id === selectedHouseId) || null,
    [selectedHouseId]
  );

  const toggleFavourite = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    setFavourites((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const applyFilters = () => {
    setAppliedFilters({ ...filters });
    setFilterOpen(false);
  };

  const resetFilters = () => {
    const reset: HouseFilters = { rentType: 'all', rooms: null, priceMin: '', priceMax: '', division: '', district: '', upazila: '', union: '' };
    setFilters(reset);
    setAppliedFilters(reset);
    setSelectedPriceRange(null);
    setFilterOpen(false);
  };

  const hasActiveFilters =
    appliedFilters.rentType !== 'all' || appliedFilters.rooms !== null ||
    appliedFilters.priceMin !== '' || appliedFilters.priceMax !== '' || appliedFilters.division !== '' ||
    appliedFilters.district !== '' || appliedFilters.upazila !== '' || appliedFilters.union !== '';

  const getRentTypeBadge = (rentType: string) => {
    if (rentType === 'family') return t('house.family', language);
    if (rentType === 'bachelor') return t('house.bachelor', language);
    return `${t('house.family', language)}/${t('house.bachelor', language)}`;
  };

  const getHouseTypeGradient = (houseType: string) => {
    switch (houseType) {
      case 'flat': return 'from-orange-400 to-amber-500';
      case 'house': return 'from-orange-500 to-red-500';
      case 'room': return 'from-amber-400 to-orange-500';
      case 'mess': return 'from-yellow-400 to-orange-400';
      default: return 'from-orange-400 to-amber-500';
    }
  };

  return (
    <div className="flex min-h-[calc(100vh-8rem)] flex-col">
      {/* Header */}
      <div className="sticky top-0 z-30 border-b bg-background/95 backdrop-blur-sm">
        <div className="flex items-center gap-3 px-4 py-3">
          <Button variant="ghost" size="icon" onClick={() => setCurrentSection('home')} className="shrink-0">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <h1 className="text-lg font-bold text-foreground">
            {t('house.title', language)}
          </h1>
          {isHouseOwner && (
            <Button
              size="sm"
              variant={ownerMode ? 'default' : 'outline'}
              className="ml-auto gap-1 text-xs"
              onClick={() => setOwnerMode(!ownerMode)}
            >
              <Home className="h-3.5 w-3.5" />
              {ownerMode ? (language === 'en' ? 'Browse' : 'ব্রাউজ') : t('house.ownerDashboard', language)}
            </Button>
          )}
          {!ownerMode && (
            <Badge variant="secondary" className="ml-auto text-xs">
              {filteredHouses.length} {language === 'bn' ? 'টি' : 'listed'}
            </Badge>
          )}
        </div>

        {/* Search & Filter Bar - only in browse mode */}
        {!ownerMode && (
          <div className="flex items-center gap-2 px-4 pb-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input placeholder={t('house.search', language)} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9 pr-9" />
              {searchQuery && (
                <button onClick={() => setSearchQuery('')} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground">
                  <X className="h-4 w-4" />
                </button>
              )}
            </div>
            <Button variant={hasActiveFilters ? 'default' : 'outline'} size="icon" onClick={() => setFilterOpen(true)} className="relative shrink-0">
              <SlidersHorizontal className="h-4 w-4" />
              {hasActiveFilters && (
                <span className="absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] text-white">!</span>
              )}
            </Button>
          </div>
        )}

        {/* Inline Filter Pills - only in browse mode */}
        {!ownerMode && (
          <div className="space-y-2 border-t px-4 py-2">
            {/* Rent Type Pills */}
            <div className="flex items-center gap-1.5 overflow-x-auto hide-scrollbar">
              {[
                { value: 'all' as RentType, label: language === 'bn' ? 'সব' : 'All' },
                { value: 'family' as RentType, label: t('house.family', language) },
                { value: 'bachelor' as RentType, label: t('house.bachelor', language) },
                { value: 'both' as RentType, label: `${t('house.family', language)}/${t('house.bachelor', language)}` },
              ].map((option) => (
                <button
                  key={option.value}
                  onClick={() => {
                    setFilters((f) => ({ ...f, rentType: option.value }));
                    setAppliedFilters((f) => ({ ...f, rentType: option.value }));
                  }}
                  className={`shrink-0 rounded-full border px-3 py-1 text-[11px] font-medium transition-colors ${
                    appliedFilters.rentType === option.value
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
            {/* Room Pills */}
            <div className="flex items-center gap-1.5 overflow-x-auto hide-scrollbar">
              <span className="shrink-0 text-[10px] text-muted-foreground">{t('house.rooms', language)}:</span>
              {[1, 2, 3, 4, 5].map((room) => (
                <button
                  key={room}
                  onClick={() => {
                    const newRooms = appliedFilters.rooms === room ? null : room;
                    setFilters((f) => ({ ...f, rooms: newRooms }));
                    setAppliedFilters((f) => ({ ...f, rooms: newRooms }));
                  }}
                  className={`flex shrink-0 items-center justify-center rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                    appliedFilters.rooms === room
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                  }`}
                >
                  {room === 5 ? '5+' : room}
                </button>
              ))}
            </div>
            {/* Price Range Pills */}
            <div className="flex items-center gap-1.5 overflow-x-auto hide-scrollbar">
              <span className="shrink-0 text-[10px] text-muted-foreground">{language === 'bn' ? 'মূল্য' : 'Price'}:</span>
              {[
                { key: '0-5000', label: language === 'bn' ? '৳৫,০০০ এর কম' : 'Under ৳5,000', min: '', max: '5000' },
                { key: '5000-10000', label: '৳5K-10K', min: '5000', max: '10000' },
                { key: '10000-20000', label: '৳10K-20K', min: '10000', max: '20000' },
                { key: '20000-35000', label: '৳20K-35K', min: '20000', max: '35000' },
                { key: '35000+', label: '৳35K+', min: '35000', max: '' },
              ].map((range) => (
                <button
                  key={range.key}
                  onClick={() => {
                    if (selectedPriceRange === range.key) {
                      setSelectedPriceRange(null);
                      setFilters((f) => ({ ...f, priceMin: '', priceMax: '' }));
                      setAppliedFilters((f) => ({ ...f, priceMin: '', priceMax: '' }));
                    } else {
                      setSelectedPriceRange(range.key);
                      setFilters((f) => ({ ...f, priceMin: range.min, priceMax: range.max }));
                      setAppliedFilters((f) => ({ ...f, priceMin: range.min, priceMax: range.max }));
                    }
                  }}
                  className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                    selectedPriceRange === range.key
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                  }`}
                >
                  {range.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Content Area */}
      <div className="flex-1 px-4 py-3">
        {ownerMode && isHouseOwner && user ? (
          <OwnerHouses language={language} ownerId={user.id} onRefresh={() => setRefreshKey((k) => k + 1)} />
        ) : filteredHouses.length > 0 ? (
          <div className="grid grid-cols-2 gap-3">
            {filteredHouses.map((house) => (
              <Card
                key={house.id}
                className="group cursor-pointer overflow-hidden border-border/50 bg-card py-0 transition-all duration-200 hover:border-primary/20 hover:shadow-md"
                onClick={() => setSelectedHouseId(house.id)}
              >
                <div className={`relative h-28 overflow-hidden bg-gradient-to-br ${getHouseTypeGradient(house.houseType)}`}>
                  {house.images && house.images.length > 0 ? (
                    <img src={house.images[0]} alt={house.title} className="h-full w-full object-cover" loading="lazy" />
                  ) : (
                    <div className="flex h-full items-center justify-center">
                      <Building2 className="h-8 w-8 text-white/40" />
                    </div>
                  )}
                  <Badge className="absolute left-2 top-2 bg-white/90 text-[10px] text-gray-800 backdrop-blur-sm dark:bg-black/60 dark:text-gray-100">
                    {house.houseType.charAt(0).toUpperCase() + house.houseType.slice(1)}
                  </Badge>
                  <Badge className={`absolute right-2 top-2 text-[9px] ${house.isAvailable ? 'bg-emerald-500 text-white hover:bg-emerald-600' : 'bg-red-500 text-white hover:bg-red-600'}`}>
                    {house.isAvailable ? t('house.available', language) : t('house.rented', language)}
                  </Badge>
                  <button onClick={(e) => toggleFavourite(house.id, e)} className="absolute bottom-2 right-2 flex h-6 w-6 items-center justify-center rounded-full bg-white/80 backdrop-blur-sm transition-colors hover:bg-white dark:bg-black/50 dark:hover:bg-black/70">
                    <Heart className={`h-3 w-3 transition-colors ${favourites.has(house.id) ? 'fill-red-500 text-red-500' : 'text-gray-600 dark:text-gray-300'}`} />
                  </button>
                </div>
                <CardContent className="p-2.5">
                  <h3 className="line-clamp-1 text-xs font-semibold">{house.title}</h3>
                  <p className="text-sm font-bold text-primary">৳{house.price.toLocaleString()}<span className="text-[10px] font-normal text-muted-foreground">/{language === 'bn' ? 'মাস' : 'mo'}</span></p>
                  <p className="line-clamp-1 text-[10px] text-muted-foreground">📍 {house.address}</p>
                  <div className="flex items-center gap-2 text-[10px] text-muted-foreground">
                    <span>🛏 {house.rooms}</span>
                    <span>🚿 {house.bathrooms}</span>
                  </div>
                  <div className="mt-1 flex gap-1.5">
                    <Button size="sm" variant="outline" className="flex-1 h-7 text-[11px] gap-1" onClick={(e) => {
                      e.stopPropagation();
                      if (house.ownerPhone) {
                        window.open(`tel:${house.ownerPhone}`, '_self');
                      } else {
                        toast({ title: language === 'en' ? 'No phone number available' : 'ফোন নম্বর নেই', variant: 'destructive' });
                      }
                    }}>
                      <Phone className="h-3 w-3" />
                      {language === 'bn' ? 'কল' : 'Call'}
                    </Button>
                    <Button size="sm" className="flex-1 h-7 bg-gradient-to-r from-primary to-primary/90 text-[11px] gap-1" onClick={(e) => {
                      e.stopPropagation();
                      setOpenChatWith({
                        id: `owner-${house.ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                        name: house.ownerName,
                        phone: house.ownerPhone,
                        listingTitle: house.title,
                      });
                      setCurrentSection('messages');
                    }}>
                      <MessageCircle className="h-3 w-3" />
                      {language === 'bn' ? 'মেসেজ' : 'Message'}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-3 py-16">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10">
              <Building2 className="h-8 w-8 text-primary/50" />
            </div>
            <p className="text-sm text-muted-foreground">{t('common.noResults', language)}</p>
            {hasActiveFilters && (
              <Button variant="outline" size="sm" onClick={resetFilters}>
                <RotateCcw className="mr-1.5 h-3.5 w-3.5" />{language === 'bn' ? 'ফিল্টার রিসেট' : 'Reset Filters'}
              </Button>
            )}
          </div>
        )}
      </div>

      {/* Filter Dialog */}
      <Dialog open={filterOpen} onOpenChange={setFilterOpen}>
        <DialogContent className="max-w-md flex flex-col p-0 gap-0">
          <DialogHeader className="px-5 pt-5 pb-3">
            <DialogTitle>{language === 'bn' ? 'অ্যাডভান্সড ফিল্টার' : 'Advanced Filters'}</DialogTitle>
            <DialogDescription>{language === 'bn' ? 'মূল্য ও অবস্থান দিয়ে বাড়ি খুঁজুন' : 'Filter by price range and location'}</DialogDescription>
          </DialogHeader>
          <div ref={filterScrollRef} className="max-h-[60vh] overflow-y-auto px-5 custom-scrollbar space-y-4">
            <div className="space-y-3">
              <Label className="text-sm font-semibold">{t('house.priceRange', language)} (৳)</Label>
              <div className="flex items-center gap-2">
                <Input type="number" placeholder={language === 'bn' ? 'সর্বনিম্ন' : 'Min'} value={filters.priceMin} onChange={(e) => setFilters((f) => ({ ...f, priceMin: e.target.value }))} className="text-xs" />
                <span className="text-muted-foreground">—</span>
                <Input type="number" placeholder={language === 'bn' ? 'সর্বোচ্চ' : 'Max'} value={filters.priceMax} onChange={(e) => setFilters((f) => ({ ...f, priceMax: e.target.value }))} className="text-xs" />
              </div>
            </div>
            <Separator />
            {/* Division */}
            <div className="space-y-3">
              <Label className="text-sm font-semibold">{language === 'bn' ? 'বিভাগ' : 'Division'}</Label>
              <Select value={filters.division} onValueChange={(val) => {
                setFilters((f) => ({ ...f, division: val === 'all' ? '' : val, district: '', upazila: '', union: '' }));
              }}>
                <SelectTrigger className="w-full"><SelectValue placeholder={language === 'bn' ? 'বিভাগ নির্বাচন' : 'Select Division'} /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{language === 'bn' ? 'সব বিভাগ' : 'All Divisions'}</SelectItem>
                  {bangladeshDivisions.map((div) => <SelectItem key={div} value={div}>{div}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            {/* District - only shows when division is selected */}
            {filters.division && (
              <div ref={districtRef} className="space-y-3">
                <Label className="text-sm font-semibold">{language === 'bn' ? 'জেলা' : 'District'}</Label>
                <Select value={filters.district || 'all'} onValueChange={(val) => {
                  setFilters((f) => ({ ...f, district: val === 'all' ? '' : val, upazila: '', union: '' }));
                }}>
                  <SelectTrigger className="w-full"><SelectValue placeholder={language === 'bn' ? 'জেলা নির্বাচন' : 'Select District'} /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">{language === 'bn' ? 'সব জেলা' : 'All Districts'}</SelectItem>
                    {getDistricts(filters.division).map((d) => <SelectItem key={d} value={d}>{d}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* Upazila - only shows when district is selected */}
            {filters.district && (
              <div ref={upazilaRef} className="space-y-3">
                <Label className="text-sm font-semibold">{language === 'bn' ? 'উপজেলা' : 'Upazila'}</Label>
                <Select value={filters.upazila || 'all'} onValueChange={(val) => {
                  setFilters((f) => ({ ...f, upazila: val === 'all' ? '' : val, union: '' }));
                }}>
                  <SelectTrigger className="w-full"><SelectValue placeholder={language === 'bn' ? 'উপজেলা নির্বাচন' : 'Select Upazila'} /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">{language === 'bn' ? 'সব উপজেলা' : 'All Upazilas'}</SelectItem>
                    {getUpazilas(filters.division, filters.district).map((u) => <SelectItem key={u} value={u}>{u}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* Union - only shows when upazila is selected */}
            {filters.upazila && (
              <div ref={unionRef} className="space-y-3">
                <Label className="text-sm font-semibold">{language === 'bn' ? 'ইউনিয়ন' : 'Union'}</Label>
                <Select value={filters.union || 'all'} onValueChange={(val) => {
                  setFilters((f) => ({ ...f, union: val === 'all' ? '' : val }));
                }}>
                  <SelectTrigger className="w-full"><SelectValue placeholder={language === 'bn' ? 'ইউনিয়ন নির্বাচন' : 'Select Union'} /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">{language === 'bn' ? 'সব ইউনিয়ন' : 'All Unions'}</SelectItem>
                    {getUnions(filters.division, filters.district, filters.upazila).map((u) => <SelectItem key={u} value={u}>{u}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>
          <div className="border-t bg-background px-5 py-3 flex items-center gap-3">
            <Button variant="outline" className="flex-1 h-9" onClick={resetFilters}><RotateCcw className="mr-1.5 h-3.5 w-3.5" />{language === 'bn' ? 'রিসেট' : 'Reset'}</Button>
            <Button className="flex-1 h-9 bg-gradient-to-r from-primary to-primary/90 font-semibold" onClick={applyFilters}>{language === 'bn' ? 'প্রয়োগ করুন' : 'Apply'}</Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* House Detail Dialog */}
      <Dialog open={!!selectedHouseId} onOpenChange={(open) => { if (!open) setSelectedHouseId(null); }}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          <DialogTitle className="sr-only">{selectedHouse?.title || 'House Details'}</DialogTitle>
          <DialogDescription className="sr-only">{selectedHouse?.address || 'House rental details'}</DialogDescription>
          {selectedHouse && (
            <div className="space-y-4">
              <div className={`relative h-52 overflow-hidden rounded-lg bg-gradient-to-br ${getHouseTypeGradient(selectedHouse.houseType)}`}>
                {selectedHouse.images && selectedHouse.images.length > 0 ? (
                  <img src={selectedHouse.images[0]} alt={selectedHouse.title} className="h-full w-full object-cover" loading="lazy" />
                ) : (
                  <div className="flex h-full items-center justify-center">
                    <Building2 className="h-20 w-20 text-white/30" />
                  </div>
                )}
                <div className="absolute left-3 top-3 flex flex-wrap gap-1.5">
                  <button
                    onClick={() => setSelectedHouseId(null)}
                    className="flex h-8 w-8 items-center justify-center rounded-full bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/50"
                    aria-label="Back to houses"
                  >
                    <ArrowLeft className="h-4 w-4" />
                  </button>
                  <Badge className="bg-emerald-500 text-white hover:bg-emerald-600 text-xs">{selectedHouse.isAvailable ? t('house.available', language) : t('house.rented', language)}</Badge>
                  <Badge variant="outline" className="border-white/40 bg-black/30 text-xs text-white backdrop-blur-sm">{getRentTypeBadge(selectedHouse.rentType)}</Badge>
                </div>
              </div>
              <DialogHeader>
                <DialogTitle className="text-lg leading-tight">{selectedHouse.title}</DialogTitle>
                <DialogDescription className="sr-only">{selectedHouse.description}</DialogDescription>
              </DialogHeader>
              <div className="space-y-3">
                <p className="text-2xl font-bold text-primary">৳{selectedHouse.price.toLocaleString()}<span className="text-sm font-normal text-muted-foreground">{t('house.perMonth', language)}</span></p>
                <div className="grid grid-cols-3 gap-3">
                  <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3"><Bed className="h-5 w-5 text-primary" /><span className="text-xs font-semibold">{selectedHouse.rooms}</span><span className="text-[10px] text-muted-foreground">{t('house.bedrooms', language)}</span></div>
                  <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3"><Bath className="h-5 w-5 text-primary" /><span className="text-xs font-semibold">{selectedHouse.bathrooms}</span><span className="text-[10px] text-muted-foreground">{t('house.bathrooms', language)}</span></div>
                  <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3"><Maximize className="h-5 w-5 text-primary" /><span className="text-xs font-semibold">{selectedHouse.area} sqft</span><span className="text-[10px] text-muted-foreground">{t('house.area', language)}</span></div>
                </div>
                <div className="flex items-center gap-2 rounded-lg bg-muted/50 px-3 py-2">
                  <Building2 className="h-4 w-4 text-primary/70" />
                  <span className="text-xs text-muted-foreground">{language === 'bn' ? 'তলা' : 'Floor'}:</span>
                  <span className="text-xs font-medium">{selectedHouse.floor}</span>
                </div>
                <Separator />
                <div>
                  <h4 className="mb-1.5 text-sm font-semibold text-foreground">{language === 'bn' ? 'বিবরণ' : 'Description'}</h4>
                  <p className="text-xs leading-relaxed text-muted-foreground">{selectedHouse.description}</p>
                </div>
                <Separator />
                <div>
                  <h4 className="mb-1.5 text-sm font-semibold text-foreground">{language === 'bn' ? 'অবস্থান' : 'Location'}</h4>
                  <div className="flex items-start gap-2 text-xs text-muted-foreground">
                    <MapPin className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
                    <div><p>{selectedHouse.address}</p><p>{selectedHouse.upazila}, {selectedHouse.district}, {selectedHouse.division}</p></div>
                  </div>
                  {/* Google Map */}
                  <div className="mt-3 overflow-hidden rounded-lg border shadow-sm">
                    <iframe
                      src={`https://maps.google.com/maps?q=${encodeURIComponent(`${selectedHouse.address}, ${selectedHouse.upazila}, ${selectedHouse.district}, ${selectedHouse.division}, Bangladesh`)}&output=embed`}
                      width="100%"
                      height="200"
                      style={{ border: 0 }}
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      className="w-full"
                      title="Location Map"
                    />
                  </div>
                  {/* Open in Google Maps button */}
                  <Button
                    variant="outline"
                    className="w-full gap-1.5 text-xs mt-2"
                    onClick={() => {
                      const query = encodeURIComponent(`${selectedHouse.address}, ${selectedHouse.upazila}, ${selectedHouse.district}, ${selectedHouse.division}, Bangladesh`);
                      window.open(`https://www.google.com/maps/search/?api=1&query=${query}`, '_blank');
                    }}
                  >
                    <MapPin className="h-3.5 w-3.5" />
                    {language === 'en' ? 'Open in Google Maps' : 'গুগল ম্যাপে খুলুন'}
                  </Button>
                  {/* Get Directions button */}
                  <Button
                    variant="outline"
                    className="w-full gap-1.5 text-xs mt-1.5"
                    onClick={() => {
                      const query = encodeURIComponent(`${selectedHouse.address}, ${selectedHouse.upazila}, ${selectedHouse.district}, ${selectedHouse.division}, Bangladesh`);
                      window.open(`https://www.google.com/maps/dir/?api=1&destination=${query}`, '_blank');
                    }}
                  >
                    <Navigation className="h-3.5 w-3.5" />
                    {language === 'en' ? 'Get Directions' : 'দিকনির্দেশনা পান'}
                  </Button>
                </div>
                <Separator />
                <div>
                  <h4 className="mb-2 text-sm font-semibold text-foreground">{language === 'bn' ? 'মালিকের তথ্য' : 'Owner Info'}</h4>
                  <div className="flex items-center gap-3 rounded-lg bg-muted/50 p-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10"><span className="text-sm font-bold text-primary">{selectedHouse.ownerName.charAt(0)}</span></div>
                    <div className="flex-1"><p className="text-sm font-medium">{selectedHouse.ownerName}</p><p className="text-xs text-muted-foreground">{selectedHouse.ownerPhone}</p></div>
                  </div>
                </div>
              </div>
              <div className="flex flex-col gap-2 pt-2 sm:flex-row">
                <Button variant="outline" className="flex-1 gap-1.5" onClick={() => {
                  if (selectedHouse.ownerPhone) {
                    window.open(`tel:${selectedHouse.ownerPhone}`, '_self');
                  } else {
                    toast({ title: language === 'en' ? 'No phone number available' : 'ফোন নম্বর নেই', variant: 'destructive' });
                  }
                }}>
                  <Phone className="h-4 w-4" />
                  {language === 'bn' ? 'কল' : 'Call'}
                </Button>
                <Button className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold gap-1.5" onClick={() => {
                  setSelectedHouseId(null);
                  setOpenChatWith({
                    id: `owner-${selectedHouse.ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                    name: selectedHouse.ownerName,
                    phone: selectedHouse.ownerPhone,
                    listingTitle: selectedHouse.title,
                  });
                  setCurrentSection('messages');
                }}>
                  <MessageCircle className="h-4 w-4" />
                  {language === 'bn' ? 'মেসেজ' : 'Message'}
                </Button>
                <Button variant="outline" className="flex-1" onClick={() => toggleFavourite(selectedHouse.id)}>
                  <Heart className={`mr-1.5 h-4 w-4 ${favourites.has(selectedHouse.id) ? 'fill-red-500 text-red-500' : ''}`} />{t('house.favourite', language)}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
