import { ref as p } from "vue";
class r {
  constructor(t = null, e = {}) {
    if (this.apiKey = t, this.options = e, typeof window > "u")
      throw new Error("google-maps is supported only in browser environment");
  }
  load() {
    return typeof this.api < "u" ? Promise.resolve(this.api) : typeof this.loader < "u" ? this.loader : (window[r.CALLBACK_NAME] = () => {
      if (this.api = window.google, typeof this.resolve > "u")
        throw new Error("Should not happen");
      this.resolve(this.api);
    }, window.gm_authFailure = () => {
      if (typeof this.reject > "u")
        throw new Error("Should not happen");
      this.reject(new Error("google-maps: authentication error"));
    }, this.loader = new Promise((t, e) => {
      this.resolve = t, this.reject = e;
      const o = document.createElement("script");
      o.src = this.createUrl(), o.async = !0, o.onerror = (n) => e(n), document.head.appendChild(o);
    }));
  }
  createUrl() {
    const t = [
      `callback=${r.CALLBACK_NAME}`
    ];
    this.apiKey && t.push(`key=${this.apiKey}`);
    for (let e in this.options)
      if (this.options.hasOwnProperty(e)) {
        let o = this.options[e];
        e === "version" && (e = "v"), e === "libraries" && (o = o.join(",")), t.push(`${e}=${o}`);
      }
    return `https://maps.googleapis.com/maps/api/js?${t.join("&")}`;
  }
}
r.CALLBACK_NAME = "_dk_google_maps_loader_cb";
const s = Object.freeze({
  jb: {
    lat: 1.492659,
    lng: 103.7413591
  }
});
let a = !1;
const l = p({});
function h() {
  return {
    // state
    get _googleMap() {
      return l.value._googleMap;
    },
    set _googleMap(i) {
      l.value._googleMap = i;
    },
    // computed
    get googleMap() {
      if (!this._googleMap) throw new Error("Google Map is not initialized!");
      return this._googleMap;
    },
    get isGoogleMapReady() {
      return !!this._googleMap;
    },
    // actions
    async initGoogleMap(i) {
      if (!(this._googleMap || a)) {
        a = !0;
        try {
          const e = await new r(i, {
            libraries: ["places"]
          }).load();
          this._googleMap = e;
        } catch {
        } finally {
          a = !1;
        }
      }
    },
    getGeocoder() {
      return new this.googleMap.maps.Geocoder();
    },
    getFirstMatchingAddress(i, t) {
      return new Promise((e) => {
        this.getGeocoder().geocode({ location: { lat: i, lng: t } }, (o) => {
          if (o != null && o.length) {
            const [n] = o;
            e(n.formatted_address);
          } else
            e("");
        });
      });
    },
    getFirstMatchingCoordinate(i) {
      return new Promise((t) => {
        this.getGeocoder().geocode({ address: i }, (e) => {
          if (e != null && e.length) {
            const [{ geometry: o }] = e;
            t([o.location.lng(), o.location.lat()]);
          } else
            t([s.jb.lng, s.jb.lat]);
        });
      });
    }
  };
}
export {
  s as c,
  h as u
};
