// Google Places (cities) autocomplete. Returns a ref to attach to a text input;
// when the user picks a place, onPick(formattedAddress) fires.
(function () {
  const { useRef, useEffect } = React;

  window.useCityAutocomplete = function useCityAutocomplete(onPick) {
    const ref = useRef(null);
    const cb = useRef(onPick);
    cb.current = onPick;

    useEffect(() => {
      let ac, listener, cancelled = false, tries = 0;
      (function init() {
        if (cancelled) return;
        if (!(window.google && window.google.maps && window.google.maps.places)) {
          if (tries++ < 150) setTimeout(init, 100); // wait for the Maps JS lib to load
          return;
        }
        if (!ref.current) return;
        try {
          ac = new google.maps.places.Autocomplete(ref.current, {
            types: ["(cities)"],
            fields: ["formatted_address", "name"],
          });
          listener = ac.addListener("place_changed", () => {
            const p = ac.getPlace();
            const val = (p && (p.formatted_address || p.name)) || (ref.current ? ref.current.value : "");
            if (cb.current) cb.current(val);
          });
        } catch (e) {
          console.error("places autocomplete init failed", e);
        }
      })();
      return () => {
        cancelled = true;
        if (listener && listener.remove) listener.remove();
      };
    }, []);

    return ref;
  };
})();
