> For the complete documentation index, see [llms.txt](https://docs.wynta.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.wynta.com/playerapi/react-native-sdk-integration-guide.md).

# React Native SDK — Integration Guide

This guide covers everything a client application needs to integrate the wynta SDK: native Firebase setup, initialisation, user identity, push notification token management, event tracking, and background push handling. It is self-contained — you should not need anything beyond this document to complete a correct integration.

***

### Table of Contents

1. Installation
2. Native Setup — Firebase, Android & iOS
   * Firebase Project Setup
   * Android Native Configuration
   * iOS Native Configuration
3. Initialisation
4. User Identity
   * Anonymous (pre-login)
   * After login
   * Updating traits
   * Logout
5. FCM Token — Push Notifications
   * Spot 1 — At app start
   * Spot 2 — At login
   * Spot 3 — Retry on app foreground
6. Background Push Handling
   * Push Notification Templates
   * Deep Linking
7. Event Tracking
8. Full Lifecycle Example
9. API Reference
10. TypeScript Types
11. Troubleshooting & Checklist

***

### 1. Installation

```bash
npm install signal-react-native-sdk
```

**Required peer dependencies** (install alongside the SDK if not already present):

| Package                            | Version          | Required for                      |
| ---------------------------------- | ---------------- | --------------------------------- |
| `@react-native-firebase/app`       | `^22.x` or later | Firebase core                     |
| `@react-native-firebase/messaging` | `^22.x` or later | FCM token + push message handling |

```bash
npm install @react-native-firebase/app @react-native-firebase/messaging
```

**For iOS (Native Bridge Linking):**

Because the Signal SDK contains native wrappers for automatic push notification tracking, you must link the iOS pod dependencies:

```bash
cd ios && pod install && cd ..
```

Installing the package is only step one — push notifications will not work until the native Firebase setup in **§2** is also complete.

***

### 2. Native Setup — Firebase, Android & iOS

Push notifications are delivered through Firebase Cloud Messaging (FCM). Before any JS code in this guide can register a real token, your app needs a Firebase project and the native platform configuration below. Skip this section only if push notifications are already fully working in your app for a different SDK/purpose.

#### 2.1 Firebase Project Setup

**Android:**

1. Go to the [Firebase Console](https://console.firebase.google.com) → your project → **Project Settings**.
2. Under **Your apps**, add an Android app with your app's package name (e.g. `com.yourapp`).
3. Download `google-services.json`.
4. Place it at `android/app/google-services.json`.

**iOS:**

1. In the same Firebase project, add an iOS app with your app's bundle ID (e.g. `com.yourapp`).
2. Download `GoogleService-Info.plist`.
3. Place it at `ios/<YourApp>/GoogleService-Info.plist`.
4. Open Xcode → right-click your app target → **Add Files** → select the plist (do not copy to a different location; select "Create folder references" off / add directly to the target).

#### 2.2 Android Native Configuration

**a. `android/build.gradle` — add the Google Services plugin:**

```groovy
buildscript {
    dependencies {
        // ...existing dependencies
        classpath("com.google.gms:google-services:4.4.2")
    }
}
```

**b. `android/app/build.gradle` — apply the plugin** (add at the bottom of the file):

```groovy
apply plugin: "com.google.gms.google-services"
```

**c. `android/app/src/main/AndroidManifest.xml` — permissions and default channel:**

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- Required for push notifications on Android 13+ -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

    <application ...>

        <!-- Tell Firebase which notification channel to use -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="default_push_channel"
            tools:replace="android:value" />

        ...
    </application>
</manifest>
```

**d. Create a high-importance notification channel.** Firebase's auto-created fallback channel uses low importance (silent notifications) — create your own with high importance so notifications appear as banners. In `android/app/src/main/java/<your_package>/MainApplication.kt`:

```kotlin
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build

class MainApplication : Application(), ReactApplication {

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()   // <-- add this line
        // ... rest of your onCreate
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "default_push_channel",           // must match the value in AndroidManifest
                "App Notifications",
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "Push notifications"
                enableLights(true)
                enableVibration(true)
            }
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }
}
```

> **Note:** The channel ID `"default_push_channel"` must match the value set in `AndroidManifest.xml` exactly.

**e. Request the runtime permission (Android 13+).** `POST_NOTIFICATIONS` must also be requested at runtime — see §5.1 for where this fits into the JS flow.

**f. Add the notification icon (`ic_notification_icon`).** The SDK shows push notifications with a drawable named **exactly `ic_notification_icon`** from your app's Android resources. There is no `initSDK` option for the icon or color in React Native (unlike the native Android SDK) — it's picked up by name. Add it to the React Native app's own Android project:

```
android/app/src/main/res/drawable/ic_notification_icon.xml        ← vector drawable (recommended), or PNGs:
android/app/src/main/res/drawable-mdpi/ic_notification_icon.png    (24×24)
android/app/src/main/res/drawable-hdpi/ic_notification_icon.png    (36×36)
android/app/src/main/res/drawable-xhdpi/ic_notification_icon.png   (48×48)
android/app/src/main/res/drawable-xxhdpi/ic_notification_icon.png  (72×72)
android/app/src/main/res/drawable-xxxhdpi/ic_notification_icon.png (96×96)
```

* It must be in a `drawable*` folder (not `mipmap`) and be a **white shape on a transparent background** — Android renders the status-bar icon from the alpha channel only, so a full-color launcher icon becomes a blob.
* Without it, notifications still work but show a generic system icon.
* It's a native resource: **rebuild the app** after adding it (a JS reload isn't enough).
* **Expo (managed):** there's no `android/` folder to edit — run `npx expo prebuild` and add the files there, or use a config plugin that copies `ic_notification_icon.png` into `android/app/src/main/res/drawable*` on every build. Expo's own `expo-notifications` icon setting creates a file named `notification_icon`, which the SDK does **not** use.
* The notification's accent color comes from each push's `bg_color`. iOS needs nothing — it always uses the app icon.

#### 2.3 iOS Native Configuration

**a. Enable the Push Notifications capability in Xcode:**

1. Open `ios/<YourApp>.xcworkspace` in Xcode.
2. Select your app target → **Signing & Capabilities**.
3. Click **+ Capability** → add **Push Notifications**.
4. Also add **Background Modes** → check **Remote notifications**.
5. Confirm `ios/<YourApp>/<YourApp>.entitlements` now contains an `aps-environment` key. A missing entitlement here silently breaks APNs/FCM registration on every iOS device — this is worth double-checking explicitly, not just assuming Xcode added it correctly.

**b. `ios/Podfile` — add modular headers for Firebase.** Some Firebase pods require modular headers; add these inside your target block:

```ruby
target 'YourApp' do
  # ...
  pod 'GoogleUtilities', :modular_headers => true
  pod 'FirebaseCoreInternal', :modular_headers => true
  # ...
end
```

Then run `pod install` again.

***

### 3. Initialization

Call `initSDK` once at app startup, before anything else. It is `async` — always `await` it.

```typescript
import SignalSDK from 'signal-react-native-sdk';

await SignalSDK.initSDK({
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
});
```

**Config fields:**

| Field          | Type     | Required | Description                                                 |
| -------------- | -------- | -------- | ----------------------------------------------------------- |
| `clientId`     | string   | Yes      | Your Signal client ID                                       |
| `clientSecret` | string   | Yes      | Your Signal client secret (used as Bearer token)            |
| `onApiLog`     | function | No       | Callback fired after every HTTP call — useful for debugging |

After `initSDK`, always call `setIdentity` to set a user ID before tracking events.

**Recommended location — `App.tsx`:**

```typescript
import React, { useEffect, useRef } from 'react';
import SignalSDK from 'signal-react-native-sdk';

export default function App() {
  // Other parts of your app (e.g. an FCM-token effect — see §5) need to know
  // when initSDK() has actually settled, so they don't call setIdentity()
  // before it's ready. A stored promise is the simplest way to share that.
  const sdkReady = useRef<Promise<void>>();

  useEffect(() => {
    sdkReady.current = (async () => {
      try {
        await SignalSDK.initSDK({
          clientId: 'YOUR_CLIENT_ID',
          clientSecret: 'YOUR_CLIENT_SECRET',
        });
        // Set anonymous identity immediately after init
        await SignalSDK.setIdentity({ user_id: 'anon-' + generateUUID() });
      } catch (err) {
        console.warn('[SignalSDK] initSDK failed:', err);
        // Report to your crash/error tool here — see §11, Pitfall #5
      }
    })();
  }, []);

  return <YourAppNavigator />;
}
```

***

### 4. User Identity

Identity tells the SDK **who is using the app**. The SDK maintains one active identity at a time. It can be anonymous (a UUID you generate) or a real player ID after login.

#### 4.1 Anonymous (pre-login)

Call `setIdentity` right after `initSDK` with an anonymous UUID. Events sent before login are attributed to this anonymous ID.

```typescript
await SignalSDK.setIdentity({
  user_id: 'anon-' + generateUUID(),
});

// Events can now be tracked immediately
await SignalSDK.sendEvent('app_open', { screen: 'Splash' });
await SignalSDK.sendEvent('onboarding_started', {});
```

#### 4.2 After login

Call `setIdentity` immediately after a successful login. Pass the real `user_id` and as many player traits as you have available. The SDK will send these to the Signal backend and all subsequent events will be attributed to the real player.

```typescript
const result = await SignalSDK.setIdentity({
  user_id: 'ply_776192',
  traits: {
    email: 'player@example.com',
    first_name: 'Alex',
    last_name: 'Smith',
    date_of_birth: '1990-04-15',
    country: 'MT',
    currency: 'EUR',
    language: 'en',
    kyc_status: 'pending',
    vip_level: 'bronze',
    account_status: 'active',
    registration_date: '2026-05-18T14:38:00.000Z',
    brand_id: 'brand_01',
  },
});

if (!result.success) {
  console.warn('[SignalSDK] setIdentity failed at login:', result.error);
  // Report to your crash/error tool — do not let this fail silently
}
```

After this call, `sendEvent` automatically uses `'ply_776192'` as the `user_id`.

#### 4.3 Updating traits

You can call `setIdentity` at any point to update specific traits without re-sending everything — only include the fields that changed:

```typescript
// KYC approved
await SignalSDK.setIdentity({
  traits: { kyc_status: 'approved' },
});

// VIP tier upgrade
await SignalSDK.setIdentity({
  traits: { vip_level: 'gold' },
});

// Removing a field
await SignalSDK.setIdentity({
  unset_traits: ['referral_code'],
});
```

#### 4.4 Logout

Call `clearIdentity` when the user logs out. This clears the `user_id` from the SDK. The FCM token is intentionally preserved because it is device-level, not user-level.

```typescript
SignalSDK.clearIdentity();

// After logout, re-set an anonymous ID so events can still be tracked
await SignalSDK.setIdentity({
  user_id: 'anon-' + generateUUID(),
});
```

***

### 5. FCM Token — Push Notifications

**The SDK never fetches the FCM token itself.** To receive push notifications, your app must obtain the token via Firebase and pass it to the SDK with `setIdentity({ fcm_token })`. There are exactly **three spots** in your app where this needs to happen — cover all three and push notifications will work reliably; miss one and some devices/users will silently not receive pushes.

#### 5.1 Spot 1 — At app start

Request permission, get the token, and register it right after app launch (native setup from **§2** must be complete first).

```typescript
import { Platform, PermissionsAndroid } from 'react-native';
import messaging from '@react-native-firebase/messaging';

// Android 13+ also needs the runtime notification permission requested
// separately (the native manifest entry from §2.2c is not enough on its own).
if (Platform.OS === 'android' && Platform.Version >= 33) {
  await PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
  ]).catch(err => console.warn('[SignalSDK] Android permission request failed:', err));
}

const authStatus = await messaging().requestPermission();
const granted =
  authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
  authStatus === messaging.AuthorizationStatus.PROVISIONAL;

if (granted) {
  const fcmToken = await messaging().getToken();
  const result = await SignalSDK.setIdentity({ fcm_token: fcmToken });
  if (!result.success) {
    console.warn('[SignalSDK] Failed to register fcm_token:', result.error);
  }
} else {
  console.warn('[SignalSDK] Push permission not granted — no token to register');
  // Log this — see §11, Pitfall #5. A denied/undecided permission is not an
  // error in itself, but it should be visible, not silent.
}
```

#### 5.2 Spot 2 — At login

Fetch a **fresh** token at the moment of login — don't rely only on whatever was registered at app start, it may be stale or not have arrived yet.

```typescript
const fcmToken = await messaging().getToken().catch(() => null);

const result = await SignalSDK.setIdentity({
  user_id: 'ply_776192',
  ...(fcmToken && { fcm_token: fcmToken }),
  traits: {
    email: 'player@example.com',
    account_status: 'active',
  },
});

if (!result.success) {
  console.warn('[SignalSDK] setIdentity failed at login:', result.error);
}
```

#### 5.3 Spot 3 — Retry on app foreground

A single attempt at cold start is fragile: no internet yet, a permission dialog the user dismissed without deciding, a momentary Play Services hiccup — any of these silently costs that device push notifications for the rest of the session unless you retry.

```typescript
import { AppState } from 'react-native';

useEffect(() => {
  const registerToken = async () => {
    if (cachedToken.current) return; // already have one, nothing to do
    try {
      const token = await messaging().getToken();
      cachedToken.current = token;
      await sdkReady.current;
      const result = await SignalSDK.setIdentity({ fcm_token: token });
      if (!result.success) console.warn('[SignalSDK] setIdentity failed:', result.error);
    } catch (err) {
      console.warn('[SignalSDK] FCM registration retry failed:', err);
    }
  };

  registerToken(); // initial attempt (Spot 1, above)

  const sub = AppState.addEventListener('change', state => {
    if (state === 'active') registerToken(); // retry on foreground
  });
  return () => sub.remove();
}, []);
```

***

### 6. Background Push Handling

For push notifications received when the app is **killed or in the background** (data-only FCM messages), wire up `handleBackgroundMessage` in your `index.js`:

```javascript
// index.js
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import messaging from '@react-native-firebase/messaging';
import SignalSDK from 'signal-react-native-sdk';

// Runs in headless mode — no React lifecycle needed
messaging().setBackgroundMessageHandler(SignalSDK.handleBackgroundMessage);

AppRegistry.registerComponent(appName, () => App);
```

`handleBackgroundMessage` (and the SDK's foreground `onMessage` handler, wired up internally during `initSDK`) both parse `remoteMessage.data`, build the notification, and post it natively — no extra JS code needed to render a campaign push once this is wired up.

#### 6.1 Push Notification Templates

On **Android**, the SDK's native module renders campaign pushes with custom UI (mirroring `androidsdk`'s renderer): Standard is a plain title/body notification, Branded fills a rounded card with an accent color, Hero Banner shows a full-bleed image with the title/body overlaid directly at the bottom. On **iOS**, template rendering is not something a JS-only integration can provide — it requires the host iOS project to add its own Notification Service Extension + Notification Content Extension targets that call into `SignalSDK`'s native Swift code directly, exactly as described in the iOS SDK's own integration guide, §8. There is no React Native-specific extra step for this beyond that native target setup.

Payload contract (same fields for both platforms, sent from the backend as the FCM/APNs data payload):

| Field                                                     | Scope                 | Description                                                                                                                                                                                                                                                                                                  |
| --------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `template`                                                | all                   | `"standard"` \| `"branded"` \| `"hero_banner"` (case-insensitive)                                                                                                                                                                                                                                            |
| `title` / `content`                                       | all                   | Required — `content` is the current field name for the body text; `body` is still accepted as a fallback for older campaigns                                                                                                                                                                                 |
| `bg_color`                                                | `branded` only        | e.g. `"#3A4CE0"` — fills the card background (Android only; ignored on iOS's default banner). `accentColorHex` is still accepted as a fallback                                                                                                                                                               |
| `image_url`                                               | `standard`, `branded` | "Add a rich image": shown full width above the title/body in the expanded notification (Android: the collapsed view stays text-only; iOS: needs the native extensions, see the iOS guide). If absent or the download fails, the push shows without an image. Branded no longer shows an icon beside the text |
| `banner_url`                                              | `hero_banner` only    | Full-bleed image; falls back to `standard` if the download fails. `imageUrl` is still accepted as a fallback                                                                                                                                                                                                 |
| `text_color`                                              | all                   | e.g. `"#FFFFFF"` — overrides the title/body text color on all three templates (Android; on iOS applies only to the expanded Content Extension UI, not the collapsed banner). Not scoped to one template like `bg_color`/`banner_url`/the rich image. Ignored if invalid/absent                               |
| `notification_tap_type`                                   | all                   | `"dismiss"` \| `"deeplink"` \| `"share"` \| `"call"` \| `"track_event"`                                                                                                                                                                                                                                      |
| `notification_tap_action_1` / `notification_tap_action_2` | all                   | Opaque strings the app interprets — see 6.2                                                                                                                                                                                                                                                                  |

#### 6.2 Deep Linking

The SDK only special-cases `notification_tap_type == "dismiss"` — the notification is posted with no tap action, so tapping it just clears it. **Every other value is opaque to the SDK** — it attaches `notification_tap_type`, `notification_tap_action_1`, and `notification_tap_action_2` to the native launch intent (Android) alongside the existing tap-tracking extras, and the app is responsible for reading them and deciding what to do; the SDK does not navigate anywhere itself.

Read these off the native launch intent in your Android host code — the JS layer does not currently expose them, since routing on tap generally needs to happen before/independent of the RN bridge being up. A typical app has a single place where the deep-link screen gets decided, e.g. in `MainActivity`:

```kotlin
override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    if (intent.getStringExtra("notification_tap_type")?.equals("deeplink", ignoreCase = true) == true) {
        val screen = intent.getStringExtra("notification_tap_action_1")
        // ...route to `screen`, however your app's navigation is structured
    }
}
```

***

### 7. Event Tracking

Use `sendEvent` to track any player action or screen view.

```typescript
await SignalSDK.sendEvent(eventName, properties);
```

#### Events do NOT depend on login state

Events can be sent as soon as `initSDK` + `setIdentity` completes — whether the user is anonymous or logged in.

```
App start  →  initSDK  →  setIdentity (anon)  →  sendEvent ✓
                          setIdentity (login)  →  sendEvent ✓  (attributed to real player)
                          clearIdentity (logout) →  setIdentity (new anon)  →  sendEvent ✓
```

#### Reserved property keys

The following keys are **automatically stripped** from `properties` even if passed — they are already top-level fields managed by the SDK:

`user_id`, `session_id`, `event_id`, `event_name`, `timestamp`, `device_type`, `platform`, `brand_id`

#### Common events

```typescript
// Screen view
await SignalSDK.sendEvent('screen_view', { screen_name: 'Home' });

// Button / CTA tap
await SignalSDK.sendEvent('button_tap', { button_id: 'deposit_cta', screen: 'Wallet' });

// Game started
await SignalSDK.sendEvent('game_started', {
  game_id: 'slots_001',
  game_name: 'Lucky Spin',
  category: 'slots',
});

// Deposit
await SignalSDK.sendEvent('deposit_initiated', {
  amount: 100,
  currency: 'EUR',
  transaction_id: 'txn_abc123',
});

// Bonus page viewed
await SignalSDK.sendEvent('bonus_page_viewed', {
  bonus_id: 'welcome_bonus',
  bonus_type: 'deposit_match',
});
```

***

### 8. Full Lifecycle Example

This example incorporates every pitfall fix from **§11** — copy this pattern rather than the simplified snippets in earlier sections when building the real thing.

```typescript
import React, { useEffect, useRef } from 'react';
import { AppState, Platform, PermissionsAndroid } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import SignalSDK from 'signal-react-native-sdk';

export default function App() {
  // Shared "SDK ready" gate — anything that calls setIdentity() outside the
  // main bootstrap sequence below must await this first (§3, §5.1, Pitfall #3).
  const sdkReady = useRef<Promise<void>>();
  const cachedFcmToken = useRef<string | null>(null);

  useEffect(() => {
    sdkReady.current = (async () => {
      try {
        // 1. Initialize SDK — unconditional, never gated on connectivity (Pitfall #1)
        await SignalSDK.initSDK({
          clientId: 'YOUR_CLIENT_ID',
          clientSecret: 'YOUR_CLIENT_SECRET',
        });

        // 2. Set anonymous identity
        const result = await SignalSDK.setIdentity({ user_id: 'anon-' + generateUUID() });
        if (!result.success) console.warn('[SignalSDK] anon setIdentity failed:', result.error); // Pitfall #2

        // 3. Track app open
        await SignalSDK.sendEvent('app_open', { version: '1.0.0' });
      } catch (err) {
        console.warn('[SignalSDK] initSDK failed:', err);
        // report(err) — Pitfall #5
      }
    })();
  }, []);

  useEffect(() => {
    const registerFcmToken = async (trigger: string) => {
      try {
        if (Platform.OS === 'android' && Platform.Version >= 33) {
          await PermissionsAndroid.requestMultiple([
            PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
          ]).catch(err => console.warn(`[SignalSDK] Android permission request failed (${trigger}):`, err));
        }

        const authStatus = await messaging().requestPermission();
        const granted =
          authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
          authStatus === messaging.AuthorizationStatus.PROVISIONAL;

        if (!granted) {
          console.warn(`[SignalSDK] push permission not granted (${trigger})`); // Pitfall #5
          return;
        }

        const token = await messaging().getToken();
        cachedFcmToken.current = token;

        await sdkReady.current; // Pitfall #3 — never call setIdentity before initSDK settles
        const result = await SignalSDK.setIdentity({ fcm_token: token });
        if (!result.success) {
          console.warn(`[SignalSDK] setIdentity failed (${trigger}):`, result.error); // Pitfall #2
        }
      } catch (err) {
        console.warn(`[SignalSDK] FCM registration failed (${trigger}):`, err);
      }
    };

    registerFcmToken('mount');

    // Pitfall #4 — retry on foreground, don't rely on a single attempt
    const sub = AppState.addEventListener('change', state => {
      if (state === 'active' && !cachedFcmToken.current) registerFcmToken('foreground');
    });
    return () => sub.remove();
  }, []);

  return <YourAppNavigator />;
}


// --- In your login flow ---

const onLoginSuccess = async (player: Player) => {
  // Pitfall #6 — fetch a fresh token at login, don't rely only on the cache
  let fcmToken: string | undefined;
  try {
    fcmToken = await messaging().getToken();
  } catch (err) {
    console.warn('[SignalSDK] getToken failed at login:', err);
  }

  const result = await SignalSDK.setIdentity({
    user_id: player.id,
    ...(fcmToken && { fcm_token: fcmToken }),
    traits: {
      email: player.email,
      first_name: player.firstName,
      last_name: player.lastName,
      country: player.country,
      currency: player.currency,
      kyc_status: player.kycStatus,
      vip_level: player.vipLevel,
      account_status: 'active',
      registration_date: player.registeredAt,
    },
  });
  if (!result.success) console.warn('[SignalSDK] setIdentity failed at login:', result.error);

  await SignalSDK.sendEvent('login_success', { method: 'email' });
};


// --- When KYC is approved ---

const onKycApproved = async () => {
  await SignalSDK.setIdentity({ traits: { kyc_status: 'approved' } });
  await SignalSDK.sendEvent('kyc_approved', {});
};


// --- When the FCM token rotates mid-session (Pitfall #7) ---
// `currentUserId` below is whatever your app already tracks as the active
// logged-in user (e.g. player.id from your own auth state) — substitute
// your app's actual source of truth.

useEffect(() => {
  const unsubscribe = messaging().onTokenRefresh(async newToken => {
    cachedFcmToken.current = newToken;
    if (currentUserId) { // only if a real user is already logged in
      const result = await SignalSDK.setIdentity({ user_id: currentUserId, fcm_token: newToken });
      if (!result.success) console.warn('[SignalSDK] setIdentity failed on token refresh:', result.error);
    }
  });
  return unsubscribe;
}, [currentUserId]);


// --- In your logout flow ---

const onLogout = async () => {
  await SignalSDK.sendEvent('logout', {});
  SignalSDK.clearIdentity();
  await SignalSDK.setIdentity({ user_id: 'anon-' + generateUUID() });
};
```

***

### 9. API Reference

#### `SignalSDK.initSDK(config)`

| Parameter      | Type     | Required | Description                               |
| -------------- | -------- | -------- | ----------------------------------------- |
| `clientId`     | string   | Yes      | Your Signal client ID                     |
| `clientSecret` | string   | Yes      | Your Signal client secret                 |
| `onApiLog`     | function | No       | Callback for API call logging             |
| `debug`        | boolean  | No       | Verbose console logging (default `false`) |

Returns: `Promise<void>`. Makes no network calls. Never gate this call behind a connectivity check (see §3).

There are no icon/color options here (unlike the native Android SDK's `smallIconResId` / `notificationColorResId`) — the Android notification icon is the `ic_notification_icon` drawable, see §2.2 f.

***

#### `SignalSDK.setIdentity(payload)`

All fields are optional individually, but a `user_id` must be available either in the payload or already stored from a previous call.

| Parameter      | Type         | Description                                                            |
| -------------- | ------------ | ---------------------------------------------------------------------- |
| `user_id`      | string       | Player ID or anonymous UUID                                            |
| `anonymous_id` | string       | Pre-login anonymous ID (used to stitch pre/post-login behaviour)       |
| `fcm_token`    | string       | Firebase Cloud Messaging token — stored and forwarded to backend       |
| `traits`       | PlayerTraits | Player attributes to set or update                                     |
| `unset_traits` | string\[]    | List of trait field names to explicitly remove from the player profile |
| `timestamp`    | string       | ISO 8601 datetime — defaults to `now` if omitted                       |

Returns: `Promise<SDKResponse>` — **resolves even on failure**; always check `result.success` (see Pitfall #2). Requires `initSDK()` to have completed first, or it resolves with `{ success: false, error: 'SDK not initialized...' }` (see Pitfall #3).

**PlayerTraits fields:**

| Trait               | Type   | Description                                      |
| ------------------- | ------ | ------------------------------------------------ |
| `email`             | string | Player's email address                           |
| `phone`             | string | Phone in E.164 format                            |
| `first_name`        | string | First name                                       |
| `last_name`         | string | Last name                                        |
| `date_of_birth`     | string | `YYYY-MM-DD`                                     |
| `country`           | string | ISO 3166-1 alpha-2 (e.g. `MT`, `GB`)             |
| `currency`          | string | ISO currency code (e.g. `EUR`, `GBP`)            |
| `language`          | string | Language code (e.g. `en`, `de`)                  |
| `kyc_status`        | string | `pending`, `approved`, `rejected`                |
| `vip_level`         | string | `bronze`, `silver`, `gold`, `platinum`           |
| `account_status`    | string | `active`, `suspended`, `self_excluded`, `closed` |
| `registration_date` | string | ISO 8601 datetime                                |
| `brand_id`          | string | Brand/operator identifier in multi-brand setups  |
| *(any key)*         | any    | Custom fields are forwarded as-is                |

***

#### `SignalSDK.clearIdentity()`

Clears the active `user_id`. The FCM token is kept.

Returns: `void`

***

#### `SignalSDK.sendEvent(eventName, properties?)`

| Parameter    | Type                     | Required | Description                  |
| ------------ | ------------------------ | -------- | ---------------------------- |
| `eventName`  | string                   | Yes      | Name of the event            |
| `properties` | Record\<string, unknown> | No       | Key-value data for the event |

Returns: `Promise<SDKResponse>` — same rule applies: check `result.success`.

***

#### `SignalSDK.handleBackgroundMessage`

Arrow function to pass directly to Firebase's `setBackgroundMessageHandler`. Handles data-only FCM messages when the app is killed or in the background — parses `remoteMessage.data` and renders it as a Standard/Branded/Hero Banner notification per the template payload contract (body text is read from `data.content`, falling back to `data.body`).

```javascript
// index.js
messaging().setBackgroundMessageHandler(SignalSDK.handleBackgroundMessage);
```

Returns: `Promise<void>`

***

#### `SDKResponse`

```typescript
{
  success: boolean;
  accepted?: number;  // number of events accepted (track calls)
  rejected?: number;  // number of events rejected (track calls)
  error?: string;     // error message if success is false
}
```

**This is the single most important type in this SDK to actually check.** See Pitfall #2 — nearly every silent integration failure traced back to code that never looked at `success`/`error` on this object.

***

### 10. TypeScript Types

```typescript
import type {
  InitSDKConfig,
  IdentityPayload,
  PlayerTraits,
  SDKResponse,
  TrackEvent,
  IdentifyRequest,
  IdentifyResponse,
  DeviceInfo,
  APIResponse,
} from 'signal-react-native-sdk';
```

***

### 11. Troubleshooting & Checklist

**Pitfalls** (each caused real push-notification failures — check every one before shipping):

1. **No internet at launch → SDK never initializes.** Call `initSDK()` unconditionally — it makes no network call itself, so never gate it behind a connectivity check.
2. **`setIdentity()`/`sendEvent()` silently "fail."** Always check `result.success` — they resolve, not throw, on expected failures.
3. **FCM registration races `initSDK()`.** `await` a shared "SDK ready" promise before calling `setIdentity()` from any separate effect/listener (§5.1, §8).
4. **One failed attempt = no push for the whole session.** Retry on `AppState` foreground if no token has registered yet (§5.3).
5. **Failures have zero visibility.** Log every failure branch to Crashlytics/Sentry — not just `console.warn`.
6. **Login sends a stale/missing token.** Fetch `messaging().getToken()` again at login and pass it explicitly (§5.2).
7. **Token rotates but the SDK never finds out.** If you have your own `onTokenRefresh` listener, also call `setIdentity({ user_id, fcm_token })` for the logged-in user.
8. **Push silently broken on iOS, or one client/brand build.** Verify a genuinely registered Firebase app in the Console for every bundle ID/brand — not a placeholder config file.

**Platform-specific checks:**

* **Android, OS blocking notifications:** `adb shell dumpsys notification` → if `importance=NONE`, grant `POST_NOTIFICATIONS`.
* **Android, notifications arrive silently:** notification channel must be `IMPORTANCE_HIGH`, matching the manifest's channel ID (§2.2).
* **iOS, nothing on simulator:** expected — FCM only delivers to physical devices.
* **iOS, token never registers, no error shown:** confirm the `aps-environment` entitlement is present (§2.3).

**Before you ship:**

* [ ] All 8 pitfalls above checked off.
* [ ] Native setup complete — Firebase apps registered in Console, Android manifest/channel configured, iOS capabilities + entitlement + Podfile headers set (§2).
* [ ] `handleBackgroundMessage` wired up in `index.js` (§6).

***

### Notes

* **`initSDK` must always be called first**, unconditionally, and awaited before any other SDK method — never gated behind a connectivity check (Pitfall #1).
* **`setIdentity` must be called after `initSDK`** to set the initial user ID before tracking events — and any call to it must wait for `initSDK()` to have actually settled (Pitfall #3).
* **`setIdentity`/`sendEvent` resolve even on failure** — always check `result.success` (Pitfall #2).
* **Events do not require the user to be logged in** — they only require `initSDK` + `setIdentity` (anonymous is fine).
* **`setIdentity` is additive by default** — only the fields you pass are updated; everything else stays as-is.
* **The FCM token survives logout** — you do not need to re-register it after a user logs back in, though fetching a fresh one at login is still recommended (Pitfall #6).
* **FCM token refresh is automatic on the SDK's side** — the SDK sets up its own internal listener; but if your app has its own `onTokenRefresh` listener for other purposes, make sure it also informs the SDK when a real user is logged in (Pitfall #7).
* **Add a retry, not just a single attempt** — for FCM registration specifically; see §5.3.
* **Verify Firebase config files are real, not placeholders** — for every platform and every client/brand variant if you run a multi-brand build (Pitfall #8).
