# `@littoral/literally-firebase`

Firebase Firestore integration utilities and reactive listener lifecycle mixins for Lit web components.

[![npm](https://img.shields.io/npm/v/@littoral/literally-firebase?style=flat-square)](https://www.npmjs.com/package/@littoral/literally-firebase)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](LICENSE)

---

## Installation

Install the package along with its peer dependencies:

```bash
npm install @littoral/literally-firebase @littoral/literally lit firebase
```

---

## Features

### Reactive Firestore Controllers (Recommended)

Lit Reactive Controllers provide declarative document and query subscriptions without deep mixin inheritance hierarchies. They automatically manage connection lifecycles (`hostConnected`/`hostDisconnected`), dynamic reference updates, and reactive states (`data`, `loading`, `error`, `exists`, `count`, `isFromCache`, `hasPendingWrites`).

#### `FirestoreDocController`

Subscribes to a single Firestore document. Supports static `DocumentReference` objects or reactive getter functions that re-evaluate when component properties change.

```typescript
import { FirestoreDocController } from '@littoral/literally-firebase/firestore';
import { doc, getFirestore } from 'firebase/firestore';
import { LitElement, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import { userConverter, type UserProfile } from './models';

@customElement('user-profile-card')
export class UserProfileCard extends LitElement {
  @property() userId!: string;

  private user = new FirestoreDocController<UserProfile>(this, {
    ref: () =>
      this.userId
        ? doc(getFirestore(), 'users', this.userId).withConverter(userConverter)
        : null,
  });

  render() {
    if (this.user.loading) return html`<p>Loading user data...</p>`;
    if (this.user.error) return html`<p>Error: ${this.user.error.message}</p>`;
    if (!this.user.exists) return html`<p>User not found.</p>`;

    return html`
      <div>
        <h3>${this.user.data?.name}</h3>
        <p>${this.user.data?.email}</p>
        ${this.user.isFromCache ? html`<small>(offline cache)</small>` : ''}
      </div>
    `;
  }
}
```

#### `FirestoreQueryController`

Subscribes to Firestore collections or queries with automatic mapping to typed arrays.

```typescript
import { FirestoreQueryController } from '@littoral/literally-firebase/firestore';
import { collection, query, where, getFirestore } from 'firebase/firestore';
import { LitElement, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

import { taskConverter, type Task } from './models';

@customElement('task-list')
export class TaskList extends LitElement {
  @property({ type: Boolean }) completed = false;

  private tasks = new FirestoreQueryController<Task>(this, {
    query: () => {
      const col = collection(getFirestore(), 'tasks').withConverter(
        taskConverter,
      );
      return query(col, where('done', '==', this.completed));
    },
  });

  render() {
    if (this.tasks.loading) return html`<p>Loading tasks...</p>`;
    if (this.tasks.error)
      return html`<p>Error: ${this.tasks.error.message}</p>`;
    if (this.tasks.empty) return html`<p>No tasks found.</p>`;

    return html`
      <p>Count: ${this.tasks.count}</p>
      <ul>
        ${this.tasks.data.map((task) => html`<li>${task.title}</li>`)}
      </ul>
    `;
  }
}
```

---

### `FirestoreListenerMixin`

A LitElement mixin that simplifies managing Firebase Firestore real-time snapshot listeners (`onSnapshot`).

- Automatically tracks active unsubscribe functions by a unique key.
- Deduplicates watchers: re-registering a watcher under an existing key automatically unsubscribes the previous listener first.
- Prevents memory leaks by automatically unsubscribing all active listeners in the component's `disconnectedCallback` lifecycle hook.

#### Example Usage

```typescript
import { FirestoreListenerMixin } from '@littoral/literally-firebase/mixins/firestore-watchers.mixin';
import { doc, onSnapshot, getFirestore } from 'firebase/firestore';
import { LitElement, html } from 'lit';
import { customElement, state } from 'lit/decorators.js';

@customElement('user-profile-card')
export class UserProfileCard extends FirestoreListenerMixin(LitElement) {
  @state() private userData: any = null;

  connectedCallback() {
    super.connectedCallback();
    this.subscribeToUser('user-123');
  }

  private subscribeToUser(userId: string) {
    const db = getFirestore();
    const userRef = doc(db, 'users', userId);

    // Register listener with a unique name
    const unsubscribe = onSnapshot(userRef, (snapshot) => {
      this.userData = snapshot.data();
    });

    // Automatically tracked and unsubscribed on disconnectedCallback()
    this.addFirebaseWatcher('user-subscription', unsubscribe);
  }

  render() {
    if (!this.userData) {
      return html`<p>Loading user data...</p>`;
    }

    return html`
      <div>
        <h3>${this.userData.name}</h3>
        <p>${this.userData.email}</p>
      </div>
    `;
  }
}
```

#### Mixin API

- `addFirebaseWatcher(name: string, watcher: Unsubscribe | undefined): void` &mdash; Registers or replaces a listener by name.
- `hasFirebaseWatcher(name: string): boolean` &mdash; Checks if a listener is currently registered.
- `stopFirebaseWatcher(name: string): void` &mdash; Unsubscribes and cleans up a specific listener by name.
- `clearFirebaseWatchers(): void` &mdash; Unsubscribes and clears all registered listeners.

---

---

### Converter & Serialization Toolkit

`@littoral/literally-firebase/firestore` provides utilities to create type-safe converters, eliminate runtime `undefined` field errors, and streamline `Date` <-> `Timestamp` conversions.

#### `createConverter<T>()`

A factory function creating an `FBConverter<T>` (compatible with `withConverter()`) with automated document ID injection, date conversion, and undefined property removal.

```typescript
import { createConverter } from '@littoral/literally-firebase/firestore';

export interface CampInfo {
  id: string;
  name: string;
  startOn: Date;
  endOn: Date;
  notes?: string;
  meta?: { lastModified?: Date };
}

export const campConverter = createConverter<CampInfo>({
  idField: 'id', // Injects snapshot.id on read (default: 'id')
  dateFields: ['startOn', 'endOn', 'meta.lastModified'], // Converts Date <-> Timestamp automatically
  cleanUndefined: true, // Strips undefined fields before writing (default: true)
});
```

#### `cleanFirestoreData(data, options?)`

Recursively removes `undefined` properties from an object or array before sending it to Firestore (e.g. via `setDoc` or `updateDoc`), preventing `Unsupported field value: undefined` crashes.

Preserves Firestore types (`Timestamp`, `FieldValue`, `DocumentReference`, `GeoPoint`, `Bytes`) and native `Date` instances intact.

```typescript
import { cleanFirestoreData } from '@littoral/literally-firebase/firestore';
import {
  updateDoc,
  doc,
  serverTimestamp,
  getFirestore,
} from 'firebase/firestore';

const db = getFirestore();
const campRef = doc(db, 'camps', 'camp-123');

await updateDoc(
  campRef,
  cleanFirestoreData({
    notes: userNote || undefined, // undefined values safely stripped
    updatedAt: serverTimestamp(), // FieldValue sentinels preserved
  }),
);
```

#### Date Utilities: `toDate` & `toTimestamp`

```typescript
import { toDate, toTimestamp } from '@littoral/literally-firebase/firestore';

const date = toDate(snapshot.get('createdOn')); // Date from Timestamp, ISO string, or number
const timestamp = toTimestamp(new Date()); // Firestore Timestamp from Date or string
```

---

### Authentication (`@littoral/literally-firebase/auth`)

Reactive controller and helper functions for Firebase Authentication.

#### `AuthController`

A Reactive Controller tracking `user`, custom claims, and authentication loading state with automatic `onIdTokenChanged` listener management.

```typescript
import {
  AuthController,
  signInWithGoogleWithFallback,
} from '@littoral/literally-firebase/auth';
import { getAuth } from 'firebase/auth';
import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('user-menu')
export class UserMenu extends LitElement {
  private auth = new AuthController(this, { auth: getAuth() });

  private handleSignIn = async () => {
    await signInWithGoogleWithFallback(getAuth());
  };

  render() {
    if (this.auth.loading) return html`<p>Loading user...</p>`;

    if (!this.auth.isLoggedIn) {
      return html`<button @click=${this.handleSignIn}>
        Sign In with Google
      </button>`;
    }

    return html`
      <div>
        <span>Welcome, ${this.auth.displayName}</span>
        ${this.auth.hasClaim('admin') ? html`<span class="badge">Admin</span>` : ''}
        <button @click=${() => this.auth.signOut()}>Sign Out</button>
      </div>
    `;
  }
}
```

#### `signInWithGoogleWithFallback`

Attempts popup sign-in, automatically falling back to `signInWithRedirect` if popup blockers intercept the request on mobile Safari or iOS devices.

```typescript
import { signInWithGoogleWithFallback } from '@littoral/literally-firebase/auth';
import { getAuth } from 'firebase/auth';

await signInWithGoogleWithFallback(getAuth());
```

---

### Notifications (`@littoral/literally-firebase/notifications`)

Comprehensive push and in-app notifications system for Lit web applications. Combines real-time Firestore synchronization, in-tab arrival toast hooks, unread counters, and FCM Web Push device registration without token drift.

#### `NotificationController`

A Reactive Controller tracking in-app notifications, unread count, and device push status. Supports subcollection (`users/{uid}/notifications`) and root collection (`/notifications`) storage patterns.

```typescript
import { NotificationController } from '@littoral/literally-firebase/notifications';
import { getApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { LitElement, html } from 'lit';
import { customElement } from 'lit/decorators.js';

@customElement('app-notifications-bell')
export class AppNotificationsBell extends LitElement {
  private notif = new NotificationController(this, {
    firestore: getFirestore(),
    app: getApp(),
    uid: () => getAuth().currentUser?.uid,
    push: { vapidKey: 'YOUR_PUBLIC_VAPID_KEY' },
    onNotificationReceived: (notif) => {
      // Direct hook for butter-bar or toast notifications
      console.log('New notification arrived:', notif.title);
    },
  });

  render() {
    if (this.notif.loading) return html`<p>Loading...</p>`;

    return html`
      <div>
        <button @click=${() => this.notif.togglePush()}>
          Push: ${this.notif.pushState}
        </button>
        <span>Unread: ${this.notif.unreadCount}</span>
        ${
          this.notif.unreadCount > 0
            ? html`<button @click=${() => this.notif.markAllAsRead()}>
                Mark All Read
              </button>`
            : ''
        }
        <ul>
          ${this.notif.notifications.map(
            (n) => html`
              <li class="${n.readAt ? 'read' : 'unread'}">
                <strong>${n.title}</strong>: ${n.body}
                ${
                  !n.readAt
                    ? html`<button @click=${() => this.notif.markAsRead(n.id)}>
                        Read
                      </button>`
                    : ''
                }
              </li>
            `,
          )}
        </ul>
      </div>
    `;
  }
}
```

#### `PushMessagingService`

Utilities to manage FCM Web Push tokens, permission queries, silent re-registration, and shared-device cleanup.

- `PushMessagingService.isSupported()`: Check if browser supports Web Push and FCM.
- `PushMessagingService.isDeviceTokenRegistered(app, registeredTokens, options)`: Verifies if current device token exists in Firestore.
- `PushMessagingService.requestPermission(app, db, uid, options)`: Prompts for permission and registers token to Firestore profile.
- `PushMessagingService.ensureDeviceTokenRegistered(app, db, uid, registeredTokens, options)`: Silently auto-registers token if permission already granted (e.g. Chromebooks/PWAs).
- `PushMessagingService.disablePush(app, db, uid, options)`: Unregisters token and deletes FCM token.
- `PushMessagingService.forgetOnSignOut(app, db, uid, options)`: Best-effort token removal during logout on shared workstations.

---

### Feature Flags (`@littoral/literally-firebase/feature-flags`)

Firestore storage adapter and reactive controller for `@littoral/literally/feature-flags`, supporting namespaced collections (`canopy_feature_flags`), subcollections (`namespaces/canopy/feature_flags`), or document-prefixed keys (`canopy__flagId`).

#### `FirestoreFeatureFlagAdapter`

Implements `FeatureFlagStorageAdapter` backed by Firestore with automatic undefined-field cleaning (`featureFlagRuleConverter`) and real-time `onSnapshot` subscriptions.

```typescript
import { FirestoreFeatureFlagAdapter } from '@littoral/literally-firebase/feature-flags';
import { FeatureFlagManager } from '@littoral/literally/feature-flags';
import { getFirestore } from 'firebase/firestore';

const adapter = new FirestoreFeatureFlagAdapter({
  firestore: getFirestore(),
  namespace: 'canopy', // Resolves to collection 'canopy_feature_flags' by default
});

const flagManager = new FeatureFlagManager({
  adapter,
  context: {
    id: 'student@wilderland.academy',
    scope: 'wilderland',
    attributes: { bucket: 'high_school', cohort: 'class_2026' },
  },
});

flagManager.startListening();
```

#### `FirestoreFeatureFlagController`

A Lit Reactive Controller that connects a `FeatureFlagManager` directly to a namespaced Firestore collection and triggers host updates when rules or evaluation contexts change.

```typescript
import { provide } from '@lit/context';
import '@littoral/literally/feature-flags/er-feature-flag';
import { FirestoreFeatureFlagController } from '@littoral/literally-firebase/feature-flags';
import {
  featureFlagContext,
  type FeatureFlagManager,
} from '@littoral/literally/feature-flags';
import { getFirestore } from 'firebase/firestore';
import { LitElement, html } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('app-shell')
export class AppShell extends LitElement {
  @property() userEmail = '';
  @property() tenantId = 'wilderland';

  private flags = new FirestoreFeatureFlagController(this, {
    firestore: getFirestore(),
    namespace: 'canopy',
    context: () => ({
      id: this.userEmail,
      scope: this.tenantId,
    }),
  });

  @provide({ context: featureFlagContext })
  flagManager: FeatureFlagManager = this.flags.manager;

  render() {
    return html`
      <er-feature-flag flag="classroom_freeze">
        <classroom-freeze-panel></classroom-freeze-panel>
        <p slot="fallback">Classroom freeze is not active for your account.</p>
      </er-feature-flag>
    `;
  }
}
```

---

## Roadmap

See [ROADMAP.md](./ROADMAP.md) for planned features, reactive controllers, converter enhancements, and testing utilities.

---

## License

[MIT](LICENSE)
