# Web Integration Guide

Complete guide for integrating the Lilith API into web applications using modern
JavaScript frameworks.

## Installation

### Package Installation

```bash
npm install @lilith/sdk-ts
# or
yarn add @lilith/sdk-ts
```

### CDN Usage

```html
<script src="https://cdn.jsdelivr.net/npm/@lilith/sdk-ts@latest/dist/lilith-sdk.umd.js"></script>
<script>
  const client = new LilithSDK.LilithClient({
    apiKey: 'your-api-key',
  });
</script>
```

## Configuration

### React Configuration

```typescript
import React, { createContext, useContext, useEffect, useState } from 'react';
import { LilithClient } from '@lilith/sdk-ts';

interface LilithContextType {
  client: LilithClient | null;
  isAuthenticated: boolean;
  user: any | null;
}

const LilithContext = createContext<LilithContextType>({
  client: null,
  isAuthenticated: false,
  user: null
});

export const LilithProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [client, setClient] = useState<LilithClient | null>(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);

  useEffect(() => {
    const lilithClient = new LilithClient({
      apiKey: process.env.REACT_APP_LILITH_API_KEY!,
      baseURL: 'https://api.lilith.app'
    });

    setClient(lilithClient);

    // Check for existing token
    const token = localStorage.getItem('lilith_token');
    if (token) {
      lilithClient.setToken(token);
      setIsAuthenticated(true);
    }
  }, []);

  return (
    <LilithContext.Provider value={{ client, isAuthenticated, user }}>
      {children}
    </LilithContext.Provider>
  );
};

export const useLilith = () => useContext(LilithContext);
```

### Vue Configuration

```typescript
import { createApp } from 'vue';
import { LilithClient } from '@lilith/sdk-ts';

const app = createApp(App);

// Create global Lilith client
const lilithClient = new LilithClient({
  apiKey: process.env.VUE_APP_LILITH_API_KEY!,
  baseURL: 'https://api.lilith.app',
});

app.provide('lilithClient', lilithClient);
app.mount('#app');
```

## Basic Usage

### Simple Chat Widget

```typescript
import React, { useState } from 'react';
import { useLilith } from './LilithProvider';

const ChatWidget: React.FC = () => {
  const { client } = useLilith();
  const [messages, setMessages] = useState<any[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const sendMessage = async () => {
    if (!client || !input.trim()) return;

    setIsLoading(true);
    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);

    try {
      const response = await client.chat.create({
        persona: 'zen_master',
        input: { text: input },
        mode: 'text',
        options: { stream: false, cite: true }
      });

      const aiMessage = {
        role: 'assistant',
        content: response.text,
        citations: response.citations
      };

      setMessages(prev => [...prev, aiMessage]);
    } catch (error) {
      console.error('Chat error:', error);
    } finally {
      setInput('');
      setIsLoading(false);
    }
  };

  return (
    <div className="chat-widget">
      <div className="messages">
        {messages.map((msg, idx) => (
          <div key={idx} className={`message ${msg.role}`}>
            <div className="content">{msg.content}</div>
            {msg.citations && (
              <div className="citations">
                {msg.citations.map((cite, cidx) => (
                  <a key={cidx} href={cite.source_uri} className="citation">
                    {cite.title || cite.source_uri}
                  </a>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="input-area">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          placeholder="Ask a wisdom question..."
          disabled={isLoading}
        />
        <button onClick={sendMessage} disabled={!input.trim() || isLoading}>
          {isLoading ? 'Thinking...' : 'Send'}
        </button>
      </div>
    </div>
  );
};
```

### Audio Streaming

```typescript
import React, { useRef, useState } from 'react';
import { useLilith } from './LilithProvider';

const AudioChatWidget: React.FC = () => {
  const { client } = useLilith();
  const [isRecording, setIsRecording] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const mediaRecorder = new MediaRecorder(stream);
      const chunks: Blob[] = [];

      mediaRecorder.ondataavailable = (event) => {
        chunks.push(event.data);
      };

      mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(chunks, { type: 'audio/wav' });
        await sendAudioMessage(audioBlob);
      };

      mediaRecorderRef.current = mediaRecorder;
      mediaRecorder.start();
      setIsRecording(true);
    } catch (error) {
      console.error('Recording failed:', error);
    }
  };

  const stopRecording = () => {
    mediaRecorderRef.current?.stop();
    setIsRecording(false);
  };

  const sendAudioMessage = async (audioBlob: Blob) => {
    if (!client) return;

    try {
      const reader = new FileReader();
      reader.onloadend = async () => {
        const base64Audio = (reader.result as string).split(',')[1];

        const response = await client.chat.create({
          persona: 'zen_master',
          input: { audio: base64Audio },
          mode: 'voice'
        });

        // Play response audio
        if (response.audioUrl && audioRef.current) {
          audioRef.current.src = response.audioUrl;
          audioRef.current.play();
          setIsPlaying(true);
        }
      };

      reader.readAsDataURL(audioBlob);
    } catch (error) {
      console.error('Audio message failed:', error);
    }
  };

  return (
    <div className="audio-chat-widget">
      <audio
        ref={audioRef}
        onEnded={() => setIsPlaying(false)}
        controls
        style={{ display: isPlaying ? 'block' : 'none' }}
      />

      <button
        onMouseDown={startRecording}
        onMouseUp={stopRecording}
        onTouchStart={startRecording}
        onTouchEnd={stopRecording}
        className={`record-button ${isRecording ? 'recording' : ''}`}
        disabled={isPlaying}
      >
        {isRecording ? 'Recording...' : 'Hold to Record'}
      </button>
    </div>
  );
};
```

## Advanced Features

### WebSocket Integration

```typescript
class WebSocketChatManager {
  private ws: WebSocket | null = null;
  private client: LilithClient;

  constructor(client: LilithClient) {
    this.client = client;
  }

  connect() {
    const token = this.client.getToken();
    this.ws = new WebSocket('wss://api.lilith.app/ws', ['lilith-chat'], {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    this.ws.onopen = () => {
      console.log('WebSocket connected');
    };

    this.ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.handleMessage(message);
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };

    this.ws.onclose = () => {
      console.log('WebSocket disconnected');
      // Implement reconnection logic
      setTimeout(() => this.connect(), 5000);
    };
  }

  sendMessage(data: any) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(
        JSON.stringify({
          type: 'chat',
          data,
        })
      );
    }
  }

  private handleMessage(message: any) {
    switch (message.type) {
      case 'token':
        this.onToken(message.data);
        break;
      case 'citation':
        this.onCitation(message.data);
        break;
      case 'done':
        this.onDone(message.data);
        break;
      case 'error':
        this.onError(message.data);
        break;
    }
  }

  private onToken(data: any) {
    // Handle streaming token
  }

  private onCitation(data: any) {
    // Handle citation
  }

  private onDone(data: any) {
    // Handle completion
  }

  private onError(data: any) {
    // Handle error
  }
}
```
