## Overview

Mirror the Flutter SDK sharding work in the RN SDK. Replace hardcoded base URLs with per-currency endpoints fetched at init from `POST /api/v1/sdk/config`. Async setup, in-memory cache, hard-fail. No tests (manual QA).

**Spec**: `ai_specs/sdk-config-sharded-base-urls.md` (Flutter spec — read for full requirements; RN parity adjustments below).
**Reference plan**: `ai_specs/sdk-config-sharded-base-urls-plan.md` (Flutter execution log; mirror phase split).

## Context

- **Structure**: `src/lib/TabbyRN.ts` (singleton), `src/components/*` (widgets), `src/constants/*` (types/URLs), `src/lib/utils/headers.ts` (`X-SDK-Version`).
- **State management**: none — module-level singleton (`new TabbyRN()`), `fetch` for I/O.
- **Reference implementations**:
  - `src/lib/TabbyRN.ts:24-35` — `apiHost` / `widgetsUrl` getters template `${env}` ('ai' | 'dev'); `setApiKey` is sync.
  - `src/lib/TabbyRN.ts:47-56` — `createSession` HTTP shape (used as the post-setup request template).
  - `src/components/TabbyProductPageWidget.tsx:50-60` — currency-agnostic `Tabby.widgetsUrl` consumer; URL composed in `useMemo`.
  - `src/constants/payment.ts:79` — `Currency` is a TS string union; the value IS the API key (no displayName indirection).
- **RN-specific divergence from Flutter spec**:
  - Public method renamed `setApiKey(apiKey, env)` → `setup(apiKey, env): Promise<void>` for parity with Flutter; signature change is breaking (must `await`).
  - Bootstrap call sends **no `Authorization`** header (merchant-agnostic — matches the Flutter implementation, not the literal spec wording).
  - Bootstrap body: `{}` with `Content-Type: application/json` (mirrors Flutter; flag if backend rejects).
  - No DI seam for `fetch` — manual QA only, no test scaffold introduced.
- **Assumptions/Gaps**:
  - `TabbyEnv` 'dev'/'ai' values stay; bootstrap host derived as `https://api.tabby.${env}/api/v1/sdk/config`.
  - Currency lookup is direct on the union value (uppercase). No transformation.
  - `productPageSnippetWebViewUrls` in `src/constants/urls.ts` are unrelated marketing pages — leave untouched.

## Plan

### Phase 1: Bootstrap + per-currency checkout routing (vertical slice) — COMPLETE

- **Goal**: `await Tabby.setup(...)` fetches sharded config; `createSession` routes by `payload.payment.currency`.
- [x] `src/constants/sdkConfig.ts` — new file. Exports:
  - `interface SdkEndpoints { checkoutApiBaseUrl: string; widgetsBaseUrl: string }`
  - `class SdkConfig { endpointsByKey: Readonly<Record<string, SdkEndpoints>>; endpointsFor(currency: Currency): SdkEndpoints }` (chose class over interface so behaviour ships with the data — interface methods would force consumers to spread/wrap)
  - `parseSdkConfig(json: unknown): SdkConfig` — pure; throws on missing/empty `default` or any malformed per-key `endpoints`; preserves unknown keys (e.g. `EGP`); ignores extra fields (`webCheckoutBaseUrl`, `analyticsBaseUrl`, future). `endpointsFor` looks up by `currency` directly; falls back to `'default'`.
- [x] `src/index.ts` — export `SdkConfig`, `SdkEndpoints`, `parseSdkConfig`.
- [x] `src/lib/TabbyRN.ts`:
  - Remove `apiHost` / `widgetsUrl` getters.
  - Add `private config: SdkConfig | null = null`.
  - Rename `setApiKey` → `async setup(apiKey: string, env: TabbyEnv = TabbyEnv.PRODUCTION): Promise<void>`. Empty-`apiKey` short-circuit throws before any fetch. Calls `POST https://api.tabby.${env}/api/v1/sdk/config` with headers `Accept: application/json`, `Content-Type: application/json`, `X-SDK-Version: getVersionHeader()` (no `Authorization`), body `'{}'`. Stores parsed config + apiKey + env.
  - Non-200 → `throw new Error('TabbySDK setup failed: HTTP <status>')` (log body via `console.error`). Network/transport error propagates unchanged. Malformed JSON or missing `default` → `throw new Error('TabbySDK setup failed: malformed config')`.
  - `createSession`: replace `this.apiHost` with `this.config!.endpointsFor(payload.payment.currency).checkoutApiBaseUrl + '/api/v2/checkout'`. Pre-flight `checkSetup()` helper throws `"TabbySDK did not setup. Call await Tabby.setup(...) before any other calls."` if `config` or `apiKey` missing.
  - Add `widgetsBaseUrlFor(currency: Currency): string` returning `this.config!.endpointsFor(currency).widgetsBaseUrl` (with `checkSetup()`).

### Phase 2: Snippet currency-aware widget URL — COMPLETE

- **Goal**: `TabbyProductPageWidget` builds URL from `Tabby.widgetsBaseUrlFor(currency)` + `/tabby-promo.html` with single-slash join.
- [x] `src/components/TabbyProductPageWidget.tsx`:
  - Replace `Tabby.widgetsUrl` reference with `Tabby.widgetsBaseUrlFor(currency)`.
  - Add small helper `joinPath(base, segment)` (strip trailing `/` on base, prepend `/segment`) — colocate at top of file, not exported.
  - Recompose `uri` in `useMemo`: `${joinPath(base, 'tabby-promo.html')}?price=...` etc. Keep all existing query params unchanged. Add `currency` to the dependency array (already present) — no other deps change.

### Phase 3: Release packaging, docs, version bump — COMPLETE

- **Goal**: Ship as v2.0.0 with breaking-change migration note.
- [x] `src/lib/utils/headers.ts` — bump `'RN/1.4.0'` → `'RN/2.0.0'`.
- [x] `package.json` — bump `1.4.1` → `2.0.0`.
- [x] `README.md`:
  - "1. Init Tabby" snippet uses `await Tabby.setup(apiKey, env)` (top-level `await` or wrapped in async init).
  - Add **Migrating from 1.x → 2.0** section: rename `setApiKey` → `setup`, signature is now `Promise<void>`, must `await`, surface failures (network / non-200 / malformed config).
  - Note bootstrap call happens once at setup time; no fallback to embedded URLs.
- [x] `CHANGELOG.md` — new file. `## 2.0.0` entry: async `setup()`, sharded URL routing per `Currency`, new public types (`SdkConfig`, `SdkEndpoints`, `parseSdkConfig`), removed `Tabby.apiHost` / `Tabby.widgetsUrl` getters, renamed `setApiKey` → `setup`, hard-fail policy.
- [x] Verify: `npm run validate` (tsc clean) && `npm run build` (clean) — both pass on the v2.0.0 branch.
- [ ] Manual QA (run before publish): consumer app awaits `Tabby.setup`, observes bootstrap on cold start with `X-SDK-Version: RN/2.0.0`; SAR `createSession` hits `api.tabby.sa`; AED hits `api.tabby.ai`; product widget loads `widgets.tabby.sa` for SAR, `widgets.tabby.ai` for AED. **BLOCKED on user-side device run.**

## Risks / Out of scope

- **Risks**:
  - Breaking `setup` rename + async signature affects every RN integrator; CHANGELOG + README migration must be unmissable.
  - Bootstrap body `{}` is an assumption inherited from Flutter; verify with one live call before publishing — drop body + `Content-Type` if backend rejects.
  - No request timeout (RN `fetch` defaults). Bootstrap can hang on bad networks; acceptable per spec, flag for follow-up.
  - No test scaffold — regressions land on manual QA. Compensating control: keep `parseSdkConfig` pure so it can be added later trivially.
- **Out of scope**:
  - Disk persistence / TTL / refresh of config (in-memory only).
  - Retry / fallback to embedded URLs (hard-fail).
  - Consuming `webCheckoutBaseUrl` / `analyticsBaseUrl`.
  - Extending `Currency` union (handled when backend ships a new shard requiring it).
  - Introducing automated tests (manual QA per user direction).
  - Touching `productPageSnippetWebViewUrls` in `src/constants/urls.ts` (unrelated marketing pages).
