import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sixam_mart/common/widgets/custom_asset_image_widget.dart';
import 'package:sixam_mart/common/widgets/custom_snackbar.dart';
import 'package:sixam_mart/common/widgets/custom_text_field.dart';
import 'package:sixam_mart/features/auth/widgets/pickup_zone_widget.dart';
import 'package:sixam_mart/features/auth/widgets/zone_selection_widget.dart';
import 'package:sixam_mart/features/location/controllers/location_controller.dart';
import 'package:sixam_mart/features/location/domain/models/zone_data_model.dart';
import 'package:sixam_mart/features/location/widgets/permission_dialog_widget.dart';
import 'package:sixam_mart/features/splash/controllers/splash_controller.dart';
import 'package:sixam_mart/features/auth/controllers/store_registration_controller.dart';
import 'package:sixam_mart/features/location/widgets/location_search_dialog_widget.dart';
import 'package:sixam_mart/helper/responsive_helper.dart';
import 'package:sixam_mart/helper/validate_check.dart';
import 'package:sixam_mart/util/app_constants.dart';
import 'package:sixam_mart/util/dimensions.dart';
import 'package:sixam_mart/util/images.dart';
import 'package:sixam_mart/util/styles.dart';
import 'package:sixam_mart/common/widgets/custom_app_bar.dart';
import 'package:sixam_mart/common/widgets/custom_button.dart';
import 'package:sixam_mart/common/widgets/custom_dropdown.dart';

class SelectLocationViewWidget extends StatefulWidget {
  final bool fromView;
  final bool mapView;
  final bool zoneModuleView;
  final GoogleMapController? mapController;
  final TextEditingController? addressController;
  final FocusNode? addressFocus;
  final bool inDialog;
  final bool resetZoneIndex;
  const SelectLocationViewWidget({super.key, required this.fromView, this.mapController, this.mapView = false, this.zoneModuleView = false, this.addressController, this.addressFocus, this.inDialog = false, this.resetZoneIndex = true});

  @override
  State<SelectLocationViewWidget> createState() => _SelectLocationViewWidgetState();
}

class _SelectLocationViewWidgetState extends State<SelectLocationViewWidget> {

  late CameraPosition _cameraPosition;
  Set<Polygon> _polygons = {};
  GoogleMapController? _mapController;
  bool isSelected = false;
  bool _isSettingPolygon = false;
  bool _hasUserInteractedWithMap = false; // Track if user has moved the map
  bool _isInitialLoad = true; // Track if this is the initial load
  bool _isMarkerVisible = false;

  @override
  void initState() {
    super.initState();
    // Initialize camera position but don't set any zone or location
    _cameraPosition = CameraPosition(
      target: LatLng(
        double.parse(Get.find<SplashController>().configModel!.defaultLocation!.lat ?? '0'),
        double.parse(Get.find<SplashController>().configModel!.defaultLocation!.lng ?? '0'),
      ),
      zoom: 16,
    );

    // Ensure zone index is -1 initially
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final storeRegController = Get.find<StoreRegistrationController>();
      if (storeRegController.selectedZoneIndex != -1 && widget.resetZoneIndex) {
        storeRegController.setZoneIndex(-1, canUpdate: false);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<StoreRegistrationController>(builder: (storeRegController) {
      bool isDesktop = ResponsiveHelper.isDesktop(context);

      bool isRentalModule = widget.fromView && storeRegController.moduleList != null && storeRegController.selectedModuleIndex != -1 &&
          storeRegController.moduleList![storeRegController.selectedModuleIndex!].moduleType == AppConstants.taxi;

      List<int> zoneIndexList = [];
      List<DropdownItem<int>> zoneList = [];

      // Build zone list if zones exist
      if (storeRegController.zoneList != null) {
        for (int index = 0; index < storeRegController.zoneList!.length; index++) {
          zoneIndexList.add(index);
          zoneList.add(DropdownItem<int>(
            value: index,
            child: SizedBox(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text('${storeRegController.zoneList![index].name}'),
              ),
            ),
          ));
        }
      }

      return Container(
        alignment: Alignment.center,
        height: widget.fromView ? null : context.height,
        child: SizedBox(
          width: Dimensions.webMaxWidth,
          child: Padding(
            padding: EdgeInsets.all(widget.fromView ? 0 : 0),
            child: SingleChildScrollView(
              child: isDesktop && widget.fromView ? webView(storeRegController, zoneList) : Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                const SizedBox(height: Dimensions.paddingSizeSmall),

                widget.fromView ? ZoneSelectionWidget(
                  storeRegController: storeRegController,
                  zoneList: zoneList,
                  callBack: () {
                    // When user manually selects a zone from dropdown
                    if (storeRegController.selectedZoneIndex != null &&
                        storeRegController.selectedZoneIndex! >= 0 &&
                        storeRegController.selectedZoneIndex! < storeRegController.zoneList!.length) {
                      _setPolygon(storeRegController.zoneList![storeRegController.selectedZoneIndex!]);

                      // If user hasn't interacted with map yet, don't validate location
                      if (_hasUserInteractedWithMap) {
                        // Re-validate current location against newly selected zone
                        storeRegController.setLocation(
                          _cameraPosition.target,
                          forStoreRegistration: true,
                          zoneId: storeRegController.zoneList![storeRegController.selectedZoneIndex!].id,
                        );

                        _isMarkerVisible = false;
                      }
                    } else if (storeRegController.selectedZoneIndex == -1) {
                      // User deselected zone - clear polygon
                      setState(() {
                        _polygons = {};
                      });
                    }
                  },
                ) : const SizedBox(),
                SizedBox(height: widget.fromView ? Dimensions.paddingSizeExtraLarge : 0),

                widget.fromView && !isDesktop ? CustomTextField(
                  titleText: 'write_store_address'.tr,
                  labelText: 'address'.tr,
                  controller: widget.addressController,
                  focusNode: widget.addressFocus,
                  inputAction: TextInputAction.done,
                  inputType: TextInputType.text,
                  capitalization: TextCapitalization.sentences,
                  maxLines: 2,
                  showTitle: isDesktop,
                  required: true,
                  validator: (value) => ValidateCheck.validateEmptyText(value, "store_address_field_is_required".tr),
                ) : const SizedBox(),
                SizedBox(height: widget.fromView ? Dimensions.paddingSizeExtraLarge : 0),

                isRentalModule ? const PickupZoneWidget() : const SizedBox(),
                SizedBox(height: isRentalModule ? Dimensions.paddingSizeExtremeLarge : 0),

                mapView(storeRegController),
                SizedBox(height: !widget.fromView ? Dimensions.paddingSizeSmall : 0),

                !widget.fromView && !widget.inDialog ? CustomButton(
                  buttonText: 'set_location'.tr,
                  onPressed: () {
                    try {
                      widget.mapController!.moveCamera(
                        CameraUpdate.newCameraPosition(_cameraPosition),
                      );
                      Get.back();
                    } catch (_) {
                      Get.back();
                    }
                  },
                ) : const SizedBox(),
              ]),
            ),
          ),
        ),
      );
    });
  }

  Widget webView(StoreRegistrationController storeRegController, List<DropdownItem<int>> zoneList) {
    return Row(children: [
      SizedBox(width: (widget.fromView && widget.zoneModuleView) ? 0 : Dimensions.paddingSizeLarge),

      (widget.fromView && widget.mapView) ? Expanded(
        child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
          ZoneSelectionWidget(
            storeRegController: storeRegController,
            zoneList: zoneList,
            callBack: () {
              // When user manually selects a zone from dropdown
              if (storeRegController.selectedZoneIndex != null &&
                  storeRegController.selectedZoneIndex! >= 0 &&
                  storeRegController.selectedZoneIndex! < storeRegController.zoneList!.length) {
                _setPolygon(storeRegController.zoneList![storeRegController.selectedZoneIndex!]);

                // If user has interacted with map, re-validate location
                if (_hasUserInteractedWithMap) {
                  storeRegController.setLocation(
                    _cameraPosition.target,
                    forStoreRegistration: true,
                    zoneId: storeRegController.zoneList![storeRegController.selectedZoneIndex!].id,
                  );
                  _isMarkerVisible = false;
                }
              } else if (storeRegController.selectedZoneIndex == -1) {
                // User deselected zone - clear polygon
                setState(() {
                  _polygons = {};
                });
              }
            },
          ),
          const SizedBox(height: Dimensions.paddingSizeLarge),

          mapView(storeRegController),
        ]),
      ) : const SizedBox(),
    ]);
  }

  Widget mapView(StoreRegistrationController storeRegController) {
    return storeRegController.zoneList!.isNotEmpty ? Center(
      child: Container(
        height: ResponsiveHelper.isDesktop(context) ? widget.fromView ? 190 : MediaQuery.of(context).size.height * 0.8 : widget.fromView ? 350 : (context.height * 0.87),
        width: widget.inDialog ? MediaQuery.of(context).size.width * 0.7 : MediaQuery.of(context).size.width,
        decoration: widget.fromView ? BoxDecoration(
          borderRadius: BorderRadius.circular(Dimensions.radiusSmall),
          border: Border.all(width: 1, color: Theme.of(context).disabledColor.withValues(alpha: 0.6)),
        ) : null,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(Dimensions.radiusSmall),
          child: Stack(clipBehavior: Clip.none, children: [
            GoogleMap(
              initialCameraPosition: _cameraPosition,
              minMaxZoomPreference: const MinMaxZoomPreference(0, 16),
              zoomControlsEnabled: false, compassEnabled: false,
              indoorViewEnabled: false, mapToolbarEnabled: false,
              myLocationEnabled: false, zoomGesturesEnabled: true,
              polygons: _polygons,
              onTap: (LatLng position) {
                // When user taps on map, mark interaction and move camera to that position
                setState(() {
                  _hasUserInteractedWithMap = true;
                  _isMarkerVisible = true;
                  _isInitialLoad = false;
                  _cameraPosition = CameraPosition(target: position, zoom: _cameraPosition.zoom);
                });
                _mapController?.animateCamera(CameraUpdate.newLatLng(position));
              },
              onCameraIdle: () {
                // Skip on initial load
                if (_isInitialLoad) {
                  _isInitialLoad = false;
                  return;
                }

                // Skip auto-detection if we're in the middle of setting a polygon
                if (_isSettingPolygon) {
                  return;
                }

                // Mark that user has interacted with the map
                if (!_hasUserInteractedWithMap) {
                  _hasUserInteractedWithMap = true;
                }

                // Automatically find the zone for the current location
                int? foundZoneIndex = _findZoneForLocation(_cameraPosition.target, storeRegController.zoneList!);

                if (foundZoneIndex != null) {
                  // Update the zone index and polygon if a different zone was found
                  if (storeRegController.selectedZoneIndex != foundZoneIndex) {
                    // Use canUpdate:false to skip async module loading, preventing state conflicts
                    storeRegController.setZoneIndex(foundZoneIndex, canUpdate: true);
                    _setPolygon(storeRegController.zoneList![foundZoneIndex]);
                  }

                  // Set location with the found zone's ID for API validation
                  storeRegController.setLocation(
                    _cameraPosition.target,
                    forStoreRegistration: true,
                    zoneId: storeRegController.zoneList![foundZoneIndex].id,
                  );
                } else {
                  // No zone found - reset the dropdown selection
                  if (storeRegController.selectedZoneIndex != -1) {
                    storeRegController.setZoneIndex(-1, canUpdate: false);
                  }

                  // Clear polygon when no zone is selected
                  setState(() {
                    _polygons = {};
                  });

                  // Call setLocation with null zoneId - this will set inZone to false
                  storeRegController.setLocation(
                    _cameraPosition.target,
                    forStoreRegistration: true,
                    zoneId: null, resetAddress: true,
                  );
                }

                if (!widget.fromView) {
                  widget.mapController!.moveCamera(
                    CameraUpdate.newCameraPosition(_cameraPosition),
                  );
                }
              },
              onCameraMove: ((position) => _cameraPosition = position),
              onMapCreated: (GoogleMapController controller) {
                _mapController = controller;
                // Don't set any polygon initially - wait for user interaction
              },
              myLocationButtonEnabled: false,
              gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
                Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
                Factory<PanGestureRecognizer>(() => PanGestureRecognizer()),
                Factory<ScaleGestureRecognizer>(() => ScaleGestureRecognizer()),
                Factory<TapGestureRecognizer>(() => TapGestureRecognizer()),
                Factory<VerticalDragGestureRecognizer>(() => VerticalDragGestureRecognizer()),
              },
            ),

            // Show center marker only after user has interacted with map
            _isMarkerVisible && _hasUserInteractedWithMap
                ? const Center(child: CustomAssetImageWidget(Images.markerStore, height: 40, width: 40))
                : const SizedBox(),

            Positioned(
              top: widget.fromView ? 10 : 20,
              left: widget.fromView ? 10 : 20,
              right: widget.fromView ? 10 : 20,
              child: InkWell(
                onTap: () async {
                  var p = await Get.dialog(
                    LocationSearchDialogWidget(
                      showEmptyState: true,
                      mapController: _mapController,
                    ),
                  );
                  Position? position = p;
                  if (position != null) {
                    // Mark that user has interacted with map
                    _hasUserInteractedWithMap = true;
                    _isMarkerVisible = true;
                    _isInitialLoad = false;

                    _cameraPosition = CameraPosition(
                      target: LatLng(position.latitude, position.longitude),
                      zoom: 16,
                    );

                    _mapController?.animateCamera(CameraUpdate.newCameraPosition(_cameraPosition));

                    // Automatically find the zone for the searched location
                    int? foundZoneIndex = _findZoneForLocation(_cameraPosition.target, storeRegController.zoneList!);

                    if (foundZoneIndex != null) {
                      // Update the zone index and polygon if a different zone was found
                      if (storeRegController.selectedZoneIndex != foundZoneIndex) {
                        storeRegController.setZoneIndex(foundZoneIndex, canUpdate: true);
                        _setPolygon(storeRegController.zoneList![foundZoneIndex]);
                      }

                      // Set location with detected zone ID
                      storeRegController.setLocation(
                        _cameraPosition.target,
                        forStoreRegistration: true,
                        zoneId: storeRegController.zoneList![foundZoneIndex].id,
                      );
                    } else {
                      // No zone found - reset dropdown
                      if (storeRegController.selectedZoneIndex != -1) {
                        storeRegController.setZoneIndex(-1, canUpdate: false);
                      }

                      // Clear polygon
                      setState(() {
                        _polygons = {};
                      });

                      // Set location with null zoneId (will set inZone to false)
                      storeRegController.setLocation(
                        _cameraPosition.target,
                        forStoreRegistration: true,
                        zoneId: null, resetAddress: true,
                      );
                    }

                    if (!widget.fromView) {
                      widget.mapController!.moveCamera(CameraUpdate.newCameraPosition(_cameraPosition));
                    }
                  }
                },
                child: Container(
                  height: widget.fromView ? 30 : 40, width: 200,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimensions.radiusSmall),
                    color: Theme.of(context).cardColor,
                    boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 5, spreadRadius: 1)],
                  ),
                  padding: const EdgeInsets.only(left: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    'location_search_here'.tr,
                    style: robotoRegular.copyWith(color: Theme.of(context).hintColor),
                  ),
                ),
              ),
            ),

            widget.inDialog ? Positioned(
              top: 0, right: 0,
              child: IconButton(
                onPressed: () => Get.back(),
                icon: const Icon(Icons.clear),
              ),
            ) : const SizedBox(),

            widget.fromView ? Positioned(
              top: 50, right: 0,
              child: InkWell(
                onTap: () {
                  if (storeRegController.selectedZoneIndex == null || storeRegController.selectedZoneIndex == -1) {
                    showCustomSnackBar('please_select_zone'.tr);
                  } else {
                    if (ResponsiveHelper.isDesktop(context)) {
                      showGeneralDialog(context: context, pageBuilder: (_, _, _) {
                        return Center(
                          child: SelectLocationViewWidget(
                            fromView: false, mapController: _mapController, inDialog: true,
                          ),
                        );
                      });
                    } else {
                      Get.to(
                        Scaffold(
                          appBar: CustomAppBar(title: 'set_your_store_location'.tr),
                          body: SelectLocationViewWidget(fromView: false, mapController: _mapController),
                        ),
                      );
                    }
                  }
                },
                child: Container(
                  width: 30, height: 30,
                  margin: const EdgeInsets.only(right: Dimensions.paddingSizeDefault),
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle, color: Colors.white,
                  ),
                  child: Icon(Icons.fullscreen, color: Theme.of(context).hintColor, size: 20),
                ),
              ),
            ) : const SizedBox(),

            Positioned(
              bottom: widget.fromView ? null : 210, right: 0, top: widget.fromView ? 90 : null,
              child: InkWell(
                onTap: () => _checkPermission(() async {
                  // Mark that user has interacted with map
                  _hasUserInteractedWithMap = true;
                  _isMarkerVisible = true;
                  _isInitialLoad = false;
                  await Get.find<LocationController>().getCurrentLocation(false, mapController: _mapController);
                }),
                child: Container(
                  padding: EdgeInsets.all(widget.fromView ? Dimensions.paddingSizeExtraSmall : Dimensions.paddingSizeSmall),
                  margin: const EdgeInsets.only(right: Dimensions.paddingSizeDefault),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(50), color: Colors.white,
                  ),
                  child: Icon(Icons.my_location_outlined, color: Theme.of(context).hintColor, size: widget.fromView ? 20 : 25),
                ),
              ),
            ),

            !widget.fromView ? Positioned(
              bottom: 100, right: 0,
              child: Container(
                margin: const EdgeInsets.only(right: Dimensions.paddingSizeDefault),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  color: Theme.of(context).cardColor,
                ),
                padding: const EdgeInsets.all(Dimensions.paddingSizeSmall),
                child: Column(mainAxisSize: MainAxisSize.min, children: [
                  InkWell(
                    onTap: () async {
                      var currentZoomLevel = await _mapController?.getZoomLevel();
                      currentZoomLevel = (currentZoomLevel! + 1);
                      _mapController?.animateCamera(
                        CameraUpdate.newCameraPosition(
                          CameraPosition(
                            target: _cameraPosition.target,
                            zoom: currentZoomLevel,
                          ),
                        ),
                      );
                    },
                    child: const Icon(Icons.add, size: 25),
                  ),
                  const Divider(),

                  InkWell(
                    onTap: () async {
                      var currentZoomLevel = await _mapController?.getZoomLevel();
                      currentZoomLevel = (currentZoomLevel! - 1);
                      _mapController?.animateCamera(
                        CameraUpdate.newCameraPosition(
                          CameraPosition(
                            target: _cameraPosition.target,
                            zoom: currentZoomLevel,
                          ),
                        ),
                      );
                    },
                    child: const Icon(Icons.remove, size: 25),
                  ),
                ]),
              ),
            ) : const SizedBox(),

            !widget.fromView ? Positioned(
              left: 20, right: 20,
              bottom: ResponsiveHelper.isDesktop(context) ? 40 : 20,
              child: CustomButton(
                buttonText: storeRegController.inZone ? 'set_location'.tr : 'not_in_zone'.tr,
                onPressed: storeRegController.inZone ? () {
                  try {
                    widget.mapController!.moveCamera(
                      CameraUpdate.newCameraPosition(_cameraPosition),
                    );
                    Get.back();
                  } catch (e) {
                    showCustomSnackBar('please_setup_the_marker_in_your_required_location'.tr);
                  }
                } : null,
              ),
            ) : const SizedBox(),

            // Only show warning if user has interacted with map
            (_hasUserInteractedWithMap && !storeRegController.inZone) ? Positioned(
              bottom: 10, right: 10, left: 10,
              child: Container(
                padding: EdgeInsets.all(Dimensions.paddingSizeSmall),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(Dimensions.radiusDefault),
                  color: Colors.black,
                ),
                child: Row(children: [
                  CustomAssetImageWidget(Images.infoError, height: 20, width: 20),
                  const SizedBox(width: Dimensions.paddingSizeExtraSmall),

                  Expanded(
                    child: Text(
                      'please_place_the_marker_inside_the_zone'.tr,
                      style: robotoRegular.copyWith(color: Colors.white, fontSize: Dimensions.fontSizeSmall),
                    ),
                  ),
                ]),
              ),
            ) : const SizedBox(),

          ]),
        ),
      ),
    ) : const SizedBox();
  }

  void _setPolygon(ZoneDataModel zoneModel) {
    final coords = zoneModel.formatedCoordinates;
    if (coords == null || coords.isEmpty) return;

    // 🔒 Lock auto detection
    _isSettingPolygon = true;

    // Build LatLng list
    final List<LatLng> zoneLatLng = coords.map((c) => LatLng(c.lat!, c.lng!)).toList();

    // Draw polygon
    _polygons = {
      Polygon(
        polygonId: PolygonId(zoneModel.id.toString()),
        points: zoneLatLng,
        strokeWidth: 2,
        strokeColor: Get.theme.colorScheme.primary,
        fillColor: Get.theme.colorScheme.primary.withValues(alpha: .2),
      ),
    };

    setState(() {});

    // 🌍 Global zone → NO camera movement
    if (_isGlobalZone(zoneModel)) {
      Future.delayed(const Duration(milliseconds: 800), () {
        _isSettingPolygon = false;
      });
      return;
    }

    // 🎯 Specific zone → fit camera
    Future.delayed(const Duration(milliseconds: 300), () {
      _mapController?.animateCamera(
        CameraUpdate.newLatLngBounds(
          boundsFromLatLngList(zoneLatLng),
          ResponsiveHelper.isDesktop(Get.context) ? 30 : 100,
        ),
      );
    });

    // 🔓 Unlock auto detection after camera settles
    Future.delayed(const Duration(milliseconds: 1500), () {
      _isSettingPolygon = false;
    });
  }

  static LatLngBounds boundsFromLatLngList(List<LatLng> list) {
    double? x0, x1, y0, y1;
    for (LatLng latLng in list) {
      if (x0 == null) {
        x0 = x1 = latLng.latitude;
        y0 = y1 = latLng.longitude;
      } else {
        if (latLng.latitude > x1!) x1 = latLng.latitude;
        if (latLng.latitude < x0) x0 = latLng.latitude;
        if (latLng.longitude > y1!) y1 = latLng.longitude;
        if (latLng.longitude < y0!) y0 = latLng.longitude;
      }
    }
    return LatLngBounds(
      northeast: LatLng(x1 ?? 0, y1 ?? 0),
      southwest: LatLng(x0 ?? 0, y0 ?? 0),
    );
  }

  void _checkPermission(Function onTap) async {
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }
    if (permission == LocationPermission.denied) {
      showCustomSnackBar('you_have_to_allow'.tr);
    } else if (permission == LocationPermission.deniedForever) {
      Get.dialog(const PermissionDialogWidget());
    } else {
      onTap();
    }
  }

  // Helper method to check if a point is inside a polygon using ray-casting algorithm
  bool _isPointInPolygon(LatLng point, List<FormatedCoordinates> polygon) {
    int intersectCount = 0;
    for (int i = 0; i < polygon.length; i++) {
      FormatedCoordinates vertex1 = polygon[i];
      FormatedCoordinates vertex2 = polygon[(i + 1) % polygon.length];

      if (_rayCastIntersect(point, vertex1, vertex2)) {
        intersectCount++;
      }
    }
    // If odd number of intersections, point is inside
    return (intersectCount % 2) == 1;
  }

  bool _rayCastIntersect(LatLng point, FormatedCoordinates vertex1, FormatedCoordinates vertex2) {
    double px = point.latitude;
    double py = point.longitude;
    double v1x = vertex1.lat!;
    double v1y = vertex1.lng!;
    double v2x = vertex2.lat!;
    double v2y = vertex2.lng!;

    if ((v1y > py) != (v2y > py) && px < (v2x - v1x) * (py - v1y) / (v2y - v1y) + v1x) {
      return true;
    }
    return false;
  }

  // Helper method to find which zone contains the given location
  int? _findZoneForLocation(LatLng location, List<ZoneDataModel> zoneList) {
    int? fallbackZoneIndex;

    for (int i = 0; i < zoneList.length; i++) {
      final zone = zoneList[i];

      if (zone.formatedCoordinates == null ||
          zone.formatedCoordinates!.isEmpty) {
        continue;
      }

      // Detect fallback/global zone
      if (_isGlobalZone(zone)) {
        fallbackZoneIndex = i;
        continue;
      }

      // Specific zones
      if (_isPointInPolygon(location, zone.formatedCoordinates!)) {
        return i;
      }
    }

    // Only return fallback if it exists
    return fallbackZoneIndex;
  }

  bool _isGlobalZone(ZoneDataModel zone) {
    final coords = zone.formatedCoordinates;
    if (coords == null || coords.isEmpty) return false;

    double minLat = coords.first.lat!;
    double maxLat = coords.first.lat!;
    double minLng = coords.first.lng!;
    double maxLng = coords.first.lng!;

    for (final c in coords) {
      minLat = min(minLat, c.lat!);
      maxLat = max(maxLat, c.lat!);
      minLng = min(minLng, c.lng!);
      maxLng = max(maxLng, c.lng!);
    }

    final latSpan = (maxLat - minLat).abs();
    final lngSpan = (maxLng - minLng).abs();

    // 🌍 Almost whole earth
    return latSpan > 120 && lngSpan > 200;
  }

}
