import { Meta, Title, Subtitle } from '@storybook/addon-docs/blocks';

<Meta title="System/GoogleMapsLoader" />

<Title>GoogleMapsLoader</Title>
<Subtitle>Async Google Maps API loader with deduplication and React context.</Subtitle>

---

## Overview

`GoogleMapsLoaderProvider` lazily loads the Google Maps JavaScript SDK once and shares the loading state across the component tree through React context. When you use `XerticaProvider` with a `googleMapsApiKey`, this provider is included automatically — you do not need to add it separately.

```tsx
// Automatically wired when using XerticaProvider:
import { XerticaProvider } from 'xertica-ui/brand';

<XerticaProvider googleMapsApiKey={import.meta.env.VITE_GOOGLE_MAPS_KEY}>
  <App />
</XerticaProvider>
```

For standalone usage without `XerticaProvider`:

```tsx
import { GoogleMapsLoaderProvider } from 'xertica-ui';

<GoogleMapsLoaderProvider apiKey={import.meta.env.VITE_GOOGLE_MAPS_KEY}>
  <YourMapComponent />
</GoogleMapsLoaderProvider>
```

---

## Exports

| Export | Type | Description |
|---|---|---|
| `GoogleMapsLoaderProvider` | Component | Context provider that loads the Maps SDK. |
| `useGoogleMapsLoader` | Hook | Returns `{ isLoaded, loadError }` for the current load state. |
| `reloadGoogleMaps` | Function | Imperatively retriggers the Maps SDK load (e.g., after an API key change). |

---

## `useGoogleMapsLoader`

```tsx
import { useGoogleMapsLoader } from 'xertica-ui';

function MyMap() {
  const { isLoaded, loadError } = useGoogleMapsLoader();

  if (loadError) return <p>Failed to load Google Maps.</p>;
  if (!isLoaded) return <p>Loading map…</p>;

  return <div id="map" className="h-64 w-full" />;
}
```

---

## AI Best Practices

> [!IMPORTANT]
> - **API Key** — Always pass the key via an environment variable (`import.meta.env.VITE_GOOGLE_MAPS_KEY`). Never hardcode it in source.
> - **Single provider** — Mount `GoogleMapsLoaderProvider` once at the root (or rely on `XerticaProvider`). Multiple providers on the same page will cause duplicate script injection.
> - **Guard rendering** — Always check `isLoaded` before instantiating `new google.maps.Map(...)` to avoid "google is not defined" errors.
> - **`SimpleMap` shortcut** — For basic map display, prefer `<SimpleMap />` over wiring the loader manually.
