All files / app/(tabs)/forum/components LocationSelectorModal.tsx

22.53% Statements 32/142
10% Branches 13/130
18.51% Functions 5/27
22.62% Lines 31/137

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799                                                                                                                                                                                            11x 11x 11x 11x     11x 11x 11x 11x 11x 11x   11x     11x 5x                                                                                                                                                                                                                                                                                                                                                                                                                                                   11x                                                                                                     11x                                                                                                                           11x                                                                                                                 11x                                                                                                                             11x 5x       5x         5x     5x 5x             11x 5x         11x         11x             11x   11x                                                                                     11x                                                                   11x                                                                                                                                                                                                                                            
/**
 * LocationSelectorModal - 位置选择模态框
 *
 * 功能:
 * - 获取当前GPS位置
 * - 搜索真实地理地址
 * - 显示附近位置
 * - 反向地理编码
 */
 
import React, { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import {
  Modal,
  View,
  Text,
  TextInput,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  Alert,
  Keyboard,
} from 'react-native';
import { X, Search, MapPin, Navigation } from '@tamagui/lucide-icons';
import { BlurView } from 'expo-blur';
import * as ExpoLocation from 'expo-location';
import { useThemeColors, useIsDarkMode } from '@/src/hooks/useThemeColors';
 
interface Location {
  id: string;
  name: string;
  address?: string;
  distance?: string;
  lat?: number;
  lon?: number;
}
 
interface NominatimResult {
  place_id: number;
  display_name: string;
  name?: string;
  lat: string;
  lon: string;
  address?: {
    road?: string;
    suburb?: string;
    city?: string;
    county?: string;
    state?: string;
    country?: string;
    postcode?: string;
    neighbourhood?: string;
    village?: string;
    suffix?: string;
    district?: string;
  };
}
 
interface LocationSelectorModalProps {
  visible: boolean;
  onClose: () => void;
  onConfirm: (location: Location) => void;
  initialLocation?: Location;
}
 
// 计算两点之间的距离(米)
function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  const R = 6371000; // 地球半径(米)
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLon = ((lon2 - lon1) * Math.PI) / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}
 
// 格式化距离显示
function formatDistance(meters: number): string {
  if (meters < 1000) {
    return `${Math.round(meters)}m`;
  }
  return `${(meters / 1000).toFixed(1)}km`;
}
 
export function LocationSelectorModal({
  visible,
  onClose,
  onConfirm,
  initialLocation,
}: LocationSelectorModalProps) {
  const colors = useThemeColors();
  const isDark = useIsDarkMode();
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(
    initialLocation || null
  );
  const [isLocating, setIsLocating] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [currentCoords, setCurrentCoords] = useState<{ lat: number; lon: number } | null>(null);
  const [currentLocation, setCurrentLocation] = useState<Location | null>(null);
  const [nearbyLocations, setNearbyLocations] = useState<Location[]>([]);
  const [searchResults, setSearchResults] = useState<Location[]>([]);
 
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  // 样式定义
  const dynamicStyles = useMemo(() => {
    return StyleSheet.create({
      backdrop: {
        flex: 1,
        backgroundColor: colors.overlay as any,
        justifyContent: 'flex-end',
      },
      container: {
        backgroundColor: colors.cardBackground as any,
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
        height: '80%',
        paddingTop: 20,
      },
      header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 20,
        paddingBottom: 16,
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: colors.border as any,
      },
      headerTitle: {
        fontSize: 18,
        fontWeight: '700',
        color: colors.text as any,
      },
      closeButton: {
        position: 'absolute',
        right: 20,
        width: 40,
        height: 40,
        alignItems: 'center',
        justifyContent: 'center',
      },
      searchContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: colors.backgroundMuted as any,
        marginHorizontal: 20,
        marginTop: 16,
        marginBottom: 12,
        paddingHorizontal: 14,
        paddingVertical: 12,
        borderRadius: 12,
      },
      searchInput: {
        flex: 1,
        fontSize: 15,
        color: colors.text as any,
        marginLeft: 10,
        marginRight: 10,
      },
      locateButton: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginHorizontal: 20,
        marginBottom: 12,
        paddingVertical: 10,
        paddingHorizontal: 16,
        backgroundColor: (isDark ? '#3D2A1F' : colors.primaryLight) as any,
        borderRadius: 10,
      },
      locateButtonText: {
        fontSize: 14,
        fontWeight: '600',
        color: colors.primary as any,
        marginLeft: 8,
      },
      content: {
        flex: 1,
      },
      section: {
        paddingHorizontal: 20,
        paddingTop: 8,
        paddingBottom: 8,
      },
      sectionTitle: {
        fontSize: 13,
        fontWeight: '600',
        color: colors.textSecondary as any,
        textTransform: 'uppercase',
        letterSpacing: 0.5,
      },
      currentLocationItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 12,
        paddingHorizontal: 14,
        marginTop: 8,
        backgroundColor: (isDark ? '#0D2818' : colors.successMuted) as any,
        borderRadius: 12,
        borderWidth: 2,
        borderColor: 'transparent',
      },
      currentIcon: {
        backgroundColor: colors.success as any,
        borderRadius: 8,
        padding: 6,
        marginRight: 12,
      },
      currentTag: {
        fontSize: 12,
        fontWeight: '600',
        color: colors.success as any,
        backgroundColor: (isDark ? '#0D2818' : colors.successMuted) as any,
        paddingHorizontal: 8,
        paddingVertical: 4,
        borderRadius: 6,
      },
      list: {
        flex: 1,
      },
      listContent: {
        paddingHorizontal: 20,
        paddingBottom: 16,
      },
      locationItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingVertical: 12,
        paddingHorizontal: 14,
        marginBottom: 8,
        backgroundColor: colors.backgroundSubtle as any,
        borderRadius: 12,
        borderWidth: 2,
        borderColor: 'transparent',
      },
      locationItemSelected: {
        backgroundColor: (isDark ? '#3D2A1F' : colors.primaryLight) as any,
        borderColor: colors.primary as any,
      },
      locationLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
      },
      iconContainer: {
        marginRight: 12,
      },
      locationInfo: {
        flex: 1,
      },
      locationName: {
        fontSize: 15,
        fontWeight: '500',
        color: colors.text as any,
        marginBottom: 2,
      },
      locationNameSelected: {
        color: colors.primary as any,
        fontWeight: '600',
      },
      locationAddress: {
        fontSize: 12,
        color: colors.textTertiary as any,
        lineHeight: 16,
      },
      distance: {
        fontSize: 12,
        color: colors.textSecondary as any,
        fontWeight: '500',
        marginLeft: 8,
        backgroundColor: colors.borderMuted as any,
        paddingHorizontal: 8,
        paddingVertical: 4,
        borderRadius: 6,
      },
      emptyState: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 40,
      },
      emptyText: {
        fontSize: 16,
        fontWeight: '500',
        color: colors.textSecondary as any,
        marginTop: 16,
        textAlign: 'center',
      },
      emptyHint: {
        fontSize: 14,
        color: colors.textTertiary as any,
        marginTop: 8,
        textAlign: 'center',
      },
      footer: {
        paddingHorizontal: 20,
        paddingTop: 16,
        paddingBottom: 24,
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: colors.border as any,
      },
      confirmButton: {
        backgroundColor: colors.primary as any,
        paddingVertical: 14,
        borderRadius: 12,
        alignItems: 'center',
      },
      confirmButtonDisabled: {
        backgroundColor: colors.border as any,
      },
      confirmButtonText: {
        fontSize: 16,
        fontWeight: '600',
        color: '#FFFFFF',
      },
      confirmButtonTextDisabled: {
        color: colors.textTertiary as any,
      },
    });
  }, [colors, isDark]);
 
  // 通过 Nominatim API 获取地址
  const fetchAddressFromNominatim = async (
    latitude: number,
    longitude: number
  ): Promise<Location> => {
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 8000);
 
      const response = await fetch(
        `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json&addressdetails=1&accept-language=zh-CN`,
        {
          headers: {
            'User-Agent': 'PetLoveApp/1.0',
          },
          signal: controller.signal,
        }
      );
      clearTimeout(timeoutId);
      const data: NominatimResult = await response.json();
 
      if (data && data.address) {
        const addr = data.address;
        const locationName =
          addr?.road || addr?.suburb || addr?.district || data.name || '当前位置';
        const fullAddress = [addr?.city || addr?.county, addr?.district || addr?.suburb, addr?.road]
          .filter(Boolean)
          .join(' ');
 
        return {
          id: 'current',
          name: locationName,
          address: fullAddress || data.display_name,
          lat: latitude,
          lon: longitude,
        };
      }
    } catch (error) {
      console.log('Nominatim geocoding failed:', error);
    }
 
    // 最终回退:使用坐标
    return {
      id: 'current',
      name: '当前位置',
      address: `纬度 ${latitude.toFixed(4)}, 经度 ${longitude.toFixed(4)}`,
      lat: latitude,
      lon: longitude,
    };
  };
 
  // 获取当前位置
  const getCurrentLocation = useCallback(async () => {
    setIsLocating(true);
    try {
      const { status } = await ExpoLocation.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('权限被拒绝', '需要位置权限来获取当前位置,请在设置中开启');
        setIsLocating(false);
        return;
      }
 
      const location = await ExpoLocation.getCurrentPositionAsync({
        accuracy: ExpoLocation.Accuracy.High,
      });
 
      const { latitude, longitude } = location.coords;
      setCurrentCoords({ lat: latitude, lon: longitude });
 
      // 首先尝试使用 expo-location 的原生反向地理编码(更快更可靠)
      let current: Location;
      try {
        const nativeAddresses = await ExpoLocation.reverseGeocodeAsync({
          latitude,
          longitude,
        });
 
        if (nativeAddresses && nativeAddresses.length > 0) {
          const addr = nativeAddresses[0];
          const locationName = addr.street || addr.district || addr.city || '当前位置';
          const fullAddress = [addr.city, addr.district, addr.street, addr.name]
            .filter(Boolean)
            .join(' ');
 
          current = {
            id: 'current',
            name: locationName,
            address: fullAddress || `${addr.city || ''}`.trim(),
            lat: latitude,
            lon: longitude,
          };
        } else {
          // 如果原生反向地理编码没有返回结果,尝试 Nominatim API
          current = await fetchAddressFromNominatim(latitude, longitude);
        }
      } catch (nativeError) {
        console.log('Native geocoding failed, trying Nominatim:', nativeError);
        // 如果原生反向地理编码失败,尝试 Nominatim API
        current = await fetchAddressFromNominatim(latitude, longitude);
      }
      setCurrentLocation(current);
      setSelectedLocation(current);
 
      // 获取附近位置(不阻塞主流程)
      fetchNearbyLocations(latitude, longitude).catch(() => {});
    } catch (error) {
      console.error('Failed to get location:', error);
      Alert.alert('定位失败', '无法获取当前位置,请检查网络连接或手动搜索位置');
    } finally {
      setIsLocating(false);
    }
  }, []);
 
  // 获取附近位置
  const fetchNearbyLocations = async (lat: number, lon: number) => {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000); // 减少到5秒
 
    try {
      // 搜索附近的 POI(兴趣点)
      const response = await fetch(
        `https://nominatim.openstreetmap.org/search?q=*&format=json&addressdetails=1&limit=15&bounded=1&viewbox=${lon - 0.02},${lat + 0.02},${lon + 0.02},${lat - 0.02}&accept-language=zh-CN`,
        {
          headers: {
            'User-Agent': 'PetLoveApp/1.0',
          },
          signal: controller.signal,
        }
      );
      clearTimeout(timeoutId);
      const data: NominatimResult[] = await response.json();
 
      if (data && data.length > 0) {
        const locations: Location[] = data
          .filter((item) => item.name || item.address?.road)
          .map((item) => {
            const addr = item.address;
            const distance = calculateDistance(
              lat,
              lon,
              parseFloat(item.lat),
              parseFloat(item.lon)
            );
            return {
              id: item.place_id.toString(),
              name: item.name || addr?.road || addr?.suburb || '未知地点',
              address: [addr?.city, addr?.district, addr?.road].filter(Boolean).join(' '),
              distance: formatDistance(distance),
              lat: parseFloat(item.lat),
              lon: parseFloat(item.lon),
            };
          })
          .sort((a, b) => {
            const distA = parseFloat(a.distance?.replace(/[^0-9.]/g, '') || '0');
            const distB = parseFloat(b.distance?.replace(/[^0-9.]/g, '') || '0');
            return distA - distB;
          });
 
        setNearbyLocations(locations);
      }
    } catch (error) {
      // 静默处理错误,不影响主流程
      if (error instanceof Error && error.name !== 'AbortError') {
        console.log('Failed to fetch nearby locations:', error.message);
      }
    } finally {
      clearTimeout(timeoutId);
    }
  };
 
  // 搜索地址
  const searchLocations = useCallback(
    async (query: string) => {
      if (!query.trim()) {
        setSearchResults([]);
        return;
      }
 
      setIsSearching(true);
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 8000);
 
      try {
        const response = await fetch(
          `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&addressdetails=1&limit=20&accept-language=zh-CN`,
          {
            headers: {
              'User-Agent': 'PetLoveApp/1.0',
            },
            signal: controller.signal,
          }
        );
        clearTimeout(timeoutId);
        const data: NominatimResult[] = await response.json();
 
        if (data && data.length > 0) {
          const locations: Location[] = data.map((item) => {
            const addr = item.address;
            const distance = currentCoords
              ? formatDistance(
                  calculateDistance(
                    currentCoords.lat,
                    currentCoords.lon,
                    parseFloat(item.lat),
                    parseFloat(item.lon)
                  )
                )
              : undefined;
 
            return {
              id: item.place_id.toString(),
              name: item.name || addr?.road || addr?.suburb || item.display_name.split(',')[0],
              address: item.display_name,
              distance,
              lat: parseFloat(item.lat),
              lon: parseFloat(item.lon),
            };
          });
 
          setSearchResults(locations);
        } else {
          setSearchResults([]);
        }
      } catch (error) {
        console.error('Failed to search locations:', error);
        setSearchResults([]);
      } finally {
        setIsSearching(false);
      }
    },
    [currentCoords]
  );
 
  // 搜索防抖
  useEffect(() => {
    Iif (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
 
    Iif (searchQuery.trim()) {
      searchTimeoutRef.current = setTimeout(() => {
        searchLocations(searchQuery);
      }, 500);
    } else {
      setSearchResults([]);
    }
 
    return () => {
      Iif (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, [searchQuery, searchLocations]);
 
  // 打开时自动获取位置
  useEffect(() => {
    Iif (visible && !currentLocation) {
      getCurrentLocation();
    }
  }, [visible, currentLocation, getCurrentLocation]);
 
  const handleLocationSelect = useCallback((location: Location) => {
    setSelectedLocation(location);
    Keyboard.dismiss();
  }, []);
 
  const handleConfirm = useCallback(() => {
    if (selectedLocation) {
      onConfirm(selectedLocation);
      onClose();
    }
  }, [selectedLocation, onConfirm, onClose]);
 
  const displayLocations = searchQuery.trim() ? searchResults : nearbyLocations;
 
  const renderLocationItem = useCallback(
    ({ item }: { item: Location }) => {
      const isSelected = selectedLocation?.id === item.id;
 
      return (
        <TouchableOpacity
          style={[dynamicStyles.locationItem, isSelected && dynamicStyles.locationItemSelected]}
          onPress={() => handleLocationSelect(item)}
          activeOpacity={0.7}
        >
          <View style={dynamicStyles.locationLeft}>
            <View style={dynamicStyles.iconContainer}>
              <MapPin
                size={20}
                color={(isSelected ? colors.primary : colors.textTertiary) as any}
                strokeWidth={2}
              />
            </View>
            <View style={dynamicStyles.locationInfo}>
              <Text
                style={[
                  dynamicStyles.locationName,
                  isSelected && dynamicStyles.locationNameSelected,
                ]}
                numberOfLines={1}
              >
                {item.name}
              </Text>
              {item.address && (
                <Text style={dynamicStyles.locationAddress} numberOfLines={2}>
                  {item.address}
                </Text>
              )}
            </View>
          </View>
 
          {item.distance && <Text style={dynamicStyles.distance}>{item.distance}</Text>}
        </TouchableOpacity>
      );
    },
    [selectedLocation, handleLocationSelect, dynamicStyles, colors]
  );
 
  const renderCurrentLocation = () => {
    if (!currentLocation) return null;
 
    const isSelected = selectedLocation?.id === currentLocation.id;
 
    return (
      <TouchableOpacity
        style={[
          dynamicStyles.currentLocationItem,
          isSelected && dynamicStyles.locationItemSelected,
        ]}
        onPress={() => handleLocationSelect(currentLocation)}
        activeOpacity={0.7}
      >
        <View style={dynamicStyles.locationLeft}>
          <View style={[dynamicStyles.iconContainer, dynamicStyles.currentIcon]}>
            <Navigation size={18} color="#FFFFFF" strokeWidth={2} />
          </View>
          <View style={dynamicStyles.locationInfo}>
            <Text
              style={[dynamicStyles.locationName, isSelected && dynamicStyles.locationNameSelected]}
            >
              {currentLocation.name}
            </Text>
            <Text style={dynamicStyles.locationAddress} numberOfLines={1}>
              {currentLocation.address}
            </Text>
          </View>
        </View>
        <Text style={dynamicStyles.currentTag}>当前</Text>
      </TouchableOpacity>
    );
  };
 
  Eif (!visible) return null;
 
  return (
    <Modal visible={visible} animationType="slide" transparent onRequestClose={onClose}>
      <BlurView intensity={20} style={dynamicStyles.backdrop}>
        <View style={dynamicStyles.container}>
          <View style={dynamicStyles.header}>
            <Text style={dynamicStyles.headerTitle}>选择位置</Text>
            <TouchableOpacity
              style={dynamicStyles.closeButton}
              onPress={onClose}
              activeOpacity={0.7}
            >
              <X size={24} color={colors.text as any} strokeWidth={2} />
            </TouchableOpacity>
          </View>
 
          <View style={dynamicStyles.searchContainer}>
            <Search size={20} color={colors.textTertiary as any} strokeWidth={2} />
            <TextInput
              style={dynamicStyles.searchInput}
              value={searchQuery}
              onChangeText={setSearchQuery}
              placeholder="搜索地址、街道、城市..."
              placeholderTextColor={colors.textTertiary as any}
              returnKeyType="search"
            />
            {isSearching && <ActivityIndicator size="small" color={colors.primary} />}
          </View>
 
          {/* 定位按钮 */}
          <TouchableOpacity
            style={dynamicStyles.locateButton}
            onPress={getCurrentLocation}
            disabled={isLocating}
            activeOpacity={0.7}
          >
            {isLocating ? (
              <ActivityIndicator size="small" color={colors.primary} />
            ) : (
              <Navigation size={20} color={colors.primary as any} strokeWidth={2} />
            )}
            <Text style={dynamicStyles.locateButtonText}>
              {isLocating ? '定位中...' : '重新定位'}
            </Text>
          </TouchableOpacity>
 
          <View style={dynamicStyles.content}>
            {/* 当前位置 */}
            {currentLocation && !searchQuery && (
              <View style={dynamicStyles.section}>
                <Text style={dynamicStyles.sectionTitle}>当前位置</Text>
                {renderCurrentLocation()}
              </View>
            )}
 
            {/* 搜索结果或附近位置 */}
            <View style={dynamicStyles.section}>
              <Text style={dynamicStyles.sectionTitle}>
                {searchQuery ? '搜索结果' : '附近位置'}
                {isSearching && ' (搜索中...)'}
              </Text>
            </View>
 
            {displayLocations.length > 0 ? (
              <FlatList
                data={displayLocations}
                renderItem={renderLocationItem}
                keyExtractor={(item) => item.id}
                style={dynamicStyles.list}
                contentContainerStyle={dynamicStyles.listContent}
                showsVerticalScrollIndicator={false}
                keyboardShouldPersistTaps="handled"
              />
            ) : (
              <View style={dynamicStyles.emptyState}>
                {isLocating || isSearching ? (
                  <ActivityIndicator size="large" color={colors.primary} />
                ) : (
                  <>
                    <MapPin size={48} color={colors.textTertiary as any} strokeWidth={1.5} />
                    <Text style={dynamicStyles.emptyText}>
                      {searchQuery ? '未找到相关位置' : '正在获取附近位置...'}
                    </Text>
                    <Text style={dynamicStyles.emptyHint}>
                      {searchQuery ? '请尝试其他关键词' : '请确保已开启定位权限'}
                    </Text>
                  </>
                )}
              </View>
            )}
          </View>
 
          <View style={dynamicStyles.footer}>
            <TouchableOpacity
              style={[
                dynamicStyles.confirmButton,
                !selectedLocation && dynamicStyles.confirmButtonDisabled,
              ]}
              onPress={handleConfirm}
              disabled={!selectedLocation}
              activeOpacity={0.8}
            >
              <Text
                style={[
                  dynamicStyles.confirmButtonText,
                  !selectedLocation && dynamicStyles.confirmButtonTextDisabled,
                ]}
              >
                确定
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </BlurView>
    </Modal>
  );
}