import { keyBy as k } from "es-toolkit";
import { onMounted as O } from "vue";
function A(s, e, i, t) {
  function o(r) {
    return r instanceof i ? r : new i(function(n) {
      n(r);
    });
  }
  return new (i || (i = Promise))(function(r, n) {
    function l(h) {
      try {
        c(t.next(h));
      } catch (d) {
        n(d);
      }
    }
    function a(h) {
      try {
        c(t.throw(h));
      } catch (d) {
        n(d);
      }
    }
    function c(h) {
      h.done ? r(h.value) : o(h.value).then(l, a);
    }
    c((t = t.apply(s, [])).next());
  });
}
function C(s) {
  return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s;
}
var $ = function s(e, i) {
  if (e === i) return !0;
  if (e && i && typeof e == "object" && typeof i == "object") {
    if (e.constructor !== i.constructor) return !1;
    var t, o, r;
    if (Array.isArray(e)) {
      if (t = e.length, t != i.length) return !1;
      for (o = t; o-- !== 0; )
        if (!s(e[o], i[o])) return !1;
      return !0;
    }
    if (e.constructor === RegExp) return e.source === i.source && e.flags === i.flags;
    if (e.valueOf !== Object.prototype.valueOf) return e.valueOf() === i.valueOf();
    if (e.toString !== Object.prototype.toString) return e.toString() === i.toString();
    if (r = Object.keys(e), t = r.length, t !== Object.keys(i).length) return !1;
    for (o = t; o-- !== 0; )
      if (!Object.prototype.hasOwnProperty.call(i, r[o])) return !1;
    for (o = t; o-- !== 0; ) {
      var n = r[o];
      if (!s(e[n], i[n])) return !1;
    }
    return !0;
  }
  return e !== e && i !== i;
}, M = /* @__PURE__ */ C($);
const I = "__googleMapsScriptId";
var y;
(function(s) {
  s[s.INITIALIZED = 0] = "INITIALIZED", s[s.LOADING = 1] = "LOADING", s[s.SUCCESS = 2] = "SUCCESS", s[s.FAILURE = 3] = "FAILURE";
})(y || (y = {}));
class m {
  /**
   * Creates an instance of Loader using [[LoaderOptions]]. No defaults are set
   * using this library, instead the defaults are set by the Google Maps
   * JavaScript API server.
   *
   * ```
   * const loader = Loader({apiKey, version: 'weekly', libraries: ['places']});
   * ```
   */
  constructor({ apiKey: e, authReferrerPolicy: i, channel: t, client: o, id: r = I, language: n, libraries: l = [], mapIds: a, nonce: c, region: h, retries: d = 3, url: u = "https://maps.googleapis.com/maps/api/js", version: p }) {
    if (this.callbacks = [], this.done = !1, this.loading = !1, this.errors = [], this.apiKey = e, this.authReferrerPolicy = i, this.channel = t, this.client = o, this.id = r || I, this.language = n, this.libraries = l, this.mapIds = a, this.nonce = c, this.region = h, this.retries = d, this.url = u, this.version = p, m.instance) {
      if (!M(this.options, m.instance.options))
        throw new Error(`Loader must not be called again with different options. ${JSON.stringify(this.options)} !== ${JSON.stringify(m.instance.options)}`);
      return m.instance;
    }
    m.instance = this;
  }
  get options() {
    return {
      version: this.version,
      apiKey: this.apiKey,
      channel: this.channel,
      client: this.client,
      id: this.id,
      libraries: this.libraries,
      language: this.language,
      region: this.region,
      mapIds: this.mapIds,
      nonce: this.nonce,
      url: this.url,
      authReferrerPolicy: this.authReferrerPolicy
    };
  }
  get status() {
    return this.errors.length ? y.FAILURE : this.done ? y.SUCCESS : this.loading ? y.LOADING : y.INITIALIZED;
  }
  get failed() {
    return this.done && !this.loading && this.errors.length >= this.retries + 1;
  }
  /**
   * CreateUrl returns the Google Maps JavaScript API script url given the [[LoaderOptions]].
   *
   * @ignore
   * @deprecated
   */
  createUrl() {
    let e = this.url;
    return e += "?callback=__googleMapsCallback&loading=async", this.apiKey && (e += `&key=${this.apiKey}`), this.channel && (e += `&channel=${this.channel}`), this.client && (e += `&client=${this.client}`), this.libraries.length > 0 && (e += `&libraries=${this.libraries.join(",")}`), this.language && (e += `&language=${this.language}`), this.region && (e += `&region=${this.region}`), this.version && (e += `&v=${this.version}`), this.mapIds && (e += `&map_ids=${this.mapIds.join(",")}`), this.authReferrerPolicy && (e += `&auth_referrer_policy=${this.authReferrerPolicy}`), e;
  }
  deleteScript() {
    const e = document.getElementById(this.id);
    e && e.remove();
  }
  /**
   * Load the Google Maps JavaScript API script and return a Promise.
   * @deprecated, use importLibrary() instead.
   */
  load() {
    return this.loadPromise();
  }
  /**
   * Load the Google Maps JavaScript API script and return a Promise.
   *
   * @ignore
   * @deprecated, use importLibrary() instead.
   */
  loadPromise() {
    return new Promise((e, i) => {
      this.loadCallback((t) => {
        t ? i(t.error) : e(window.google);
      });
    });
  }
  importLibrary(e) {
    return this.execute(), google.maps.importLibrary(e);
  }
  /**
   * Load the Google Maps JavaScript API script with a callback.
   * @deprecated, use importLibrary() instead.
   */
  loadCallback(e) {
    this.callbacks.push(e), this.execute();
  }
  /**
   * Set the script on document.
   */
  setScript() {
    var e, i;
    if (document.getElementById(this.id)) {
      this.callback();
      return;
    }
    const t = {
      key: this.apiKey,
      channel: this.channel,
      client: this.client,
      libraries: this.libraries.length && this.libraries,
      v: this.version,
      mapIds: this.mapIds,
      language: this.language,
      region: this.region,
      authReferrerPolicy: this.authReferrerPolicy
    };
    Object.keys(t).forEach(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (r) => !t[r] && delete t[r]
    ), !((i = (e = window == null ? void 0 : window.google) === null || e === void 0 ? void 0 : e.maps) === null || i === void 0) && i.importLibrary || ((r) => {
      let n, l, a, c = "The Google Maps JavaScript API", h = "google", d = "importLibrary", u = "__ib__", p = document, g = window;
      g = g[h] || (g[h] = {});
      const f = g.maps || (g.maps = {}), E = /* @__PURE__ */ new Set(), v = new URLSearchParams(), S = () => (
        // @ts-ignore
        n || (n = new Promise((w, _) => A(this, void 0, void 0, function* () {
          var b;
          yield l = p.createElement("script"), l.id = this.id, v.set("libraries", [...E] + "");
          for (a in r)
            v.set(a.replace(/[A-Z]/g, (P) => "_" + P[0].toLowerCase()), r[a]);
          v.set("callback", h + ".maps." + u), l.src = this.url + "?" + v, f[u] = w, l.onerror = () => n = _(Error(c + " could not load.")), l.nonce = this.nonce || ((b = p.querySelector("script[nonce]")) === null || b === void 0 ? void 0 : b.nonce) || "", p.head.append(l);
        })))
      );
      f[d] ? console.warn(c + " only loads once. Ignoring:", r) : f[d] = (w, ..._) => E.add(w) && S().then(() => f[d](w, ..._));
    })(t);
    const o = this.libraries.map((r) => this.importLibrary(r));
    o.length || o.push(this.importLibrary("core")), Promise.all(o).then(() => this.callback(), (r) => {
      const n = new ErrorEvent("error", { error: r });
      this.loadErrorCallback(n);
    });
  }
  /**
   * Reset the loader state.
   */
  reset() {
    this.deleteScript(), this.done = !1, this.loading = !1, this.errors = [], this.onerrorEvent = null;
  }
  resetIfRetryingFailed() {
    this.failed && this.reset();
  }
  loadErrorCallback(e) {
    if (this.errors.push(e), this.errors.length <= this.retries) {
      const i = this.errors.length * Math.pow(2, this.errors.length);
      console.error(`Failed to load Google Maps script, retrying in ${i} ms.`), setTimeout(() => {
        this.deleteScript(), this.setScript();
      }, i);
    } else
      this.onerrorEvent = e, this.callback();
  }
  callback() {
    this.done = !0, this.loading = !1, this.callbacks.forEach((e) => {
      e(this.onerrorEvent);
    }), this.callbacks = [];
  }
  execute() {
    if (this.resetIfRetryingFailed(), !this.loading)
      if (this.done)
        this.callback();
      else {
        if (window.google && window.google.maps && window.google.maps.version) {
          console.warn("Google Maps already loaded outside @googlemaps/js-api-loader. This may result in undesirable behavior as options and script parameters may not match."), this.callback();
          return;
        }
        this.loading = !0, this.setScript();
      }
  }
}
function j(s) {
  var i, t, o, r, n, l, a, c, h, d, u;
  const e = k(s, (p) => p.types[0]);
  return {
    street_address: [(i = e.street_number) == null ? void 0 : i.long_name, (t = e.route) == null ? void 0 : t.short_name].filter(Boolean).join(" ") || void 0,
    extended_address: ((o = e.premise) == null ? void 0 : o.long_name) || ((r = e.subpremise) == null ? void 0 : r.long_name),
    state: (n = e.administrative_area_level_1) == null ? void 0 : n.short_name,
    postal_code: (l = e.postal_code) == null ? void 0 : l.long_name,
    city: ((a = e.locality) == null ? void 0 : a.long_name) || ((c = e == null ? void 0 : e.administrative_area_level_2) == null ? void 0 : c.long_name) || ((h = e == null ? void 0 : e.sublocality_level_1) == null ? void 0 : h.long_name) || ((d = e == null ? void 0 : e.sublocality) == null ? void 0 : d.long_name),
    country: (u = e.country) == null ? void 0 : u.short_name
  };
}
function F(s) {
  let e = null, i = null;
  function t(r) {
    return new Promise((n, l) => {
      if (!e) {
        l({ isGoogleMapsError: !1, message: "Autocomplete service not initialized" });
        return;
      }
      e.getPlacePredictions({ input: r }, (a, c) => {
        if (c !== google.maps.places.PlacesServiceStatus.OK) {
          l({
            isGoogleMapsError: !0,
            message: `Failed to get query predictions with status ${c}`,
            status: c
          }), l(c);
          return;
        }
        const h = (a || []).map(({ place_id: d, description: u }) => ({
          id: d,
          name: u
        }));
        n(h);
      });
    });
  }
  function o(r) {
    return new Promise((n, l) => {
      if (!i) {
        l({ isGoogleMapsError: !1, message: "Places service not initialized" });
        return;
      }
      i.getDetails({ placeId: r, fields: ["address_components", "geometry"] }, (a, c) => {
        var u, p, g, f;
        if (c !== google.maps.places.PlacesServiceStatus.OK) {
          l({
            isGoogleMapsError: !0,
            message: `Failed to get place details with status ${c}`,
            status: c
          });
          return;
        }
        const d = {
          ...j((a == null ? void 0 : a.address_components) || []),
          lat: (p = (u = a == null ? void 0 : a.geometry) == null ? void 0 : u.location) == null ? void 0 : p.lat(),
          long: (f = (g = a == null ? void 0 : a.geometry) == null ? void 0 : g.location) == null ? void 0 : f.lng(),
          place_id: r
        };
        n(d);
      });
    });
  }
  return O(() => {
    new m({
      apiKey: s,
      version: "weekly",
      libraries: ["places"]
    }).importLibrary("places").then((r) => {
      e = new r.AutocompleteService(), i = new r.PlacesService(document.createElement("div"));
    });
  }), { getPlaceDetails: o, getPlacePredictions: t };
}
export {
  F as default
};
//# sourceMappingURL=useGoogleMaps.js.map
