Matthias Nott
2026-03-07 af1543135d42adc2e97dc5243aeef7418cd3b00d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import React, { useCallback, useEffect, useRef, useState } from "react";
import { ActionSheetIOS, Alert, KeyboardAvoidingView, Platform, Pressable, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router } from "expo-router";
import { useChat } from "../contexts/ChatContext";
import { useConnection } from "../contexts/ConnectionContext";
import { useTheme } from "../contexts/ThemeContext";
import { MessageList } from "../components/chat/MessageList";
import { InputBar } from "../components/chat/InputBar";
import { CommandBar, TextModeCommandBar } from "../components/chat/CommandBar";
import { ImageCaptionModal } from "../components/chat/ImageCaptionModal";
import { StatusDot } from "../components/ui/StatusDot";
import { SessionDrawer } from "../components/SessionDrawer";
import { playAudio, stopPlayback, isPlaying, onPlayingChange } from "../services/audio";
interface StagedImage {
  base64: string;
  uri: string;
  mimeType: string;
}
export default function ChatScreen() {
  const { messages, sendTextMessage, sendVoiceMessage, sendImageMessage, clearMessages, requestScreenshot, sessions } =
    useChat();
  const { status } = useConnection();
  const { colors, mode, cycleMode } = useTheme();
  const themeIcon = mode === "dark" ? "🌙" : mode === "light" ? "☀️" : "📱";
  const activeSessionName = sessions.find((s) => s.isActive)?.name ?? "PAILot";
  const [isTextMode, setIsTextMode] = useState(false);
  const [showSessions, setShowSessions] = useState(false);
  const [audioPlaying, setAudioPlaying] = useState(false);
  const [stagedImage, setStagedImage] = useState<StagedImage | null>(null);
  useEffect(() => {
    return onPlayingChange(setAudioPlaying);
  }, []);
  const handleScreenshot = useCallback(() => {
    requestScreenshot();
  }, [requestScreenshot]);
  const handleHelp = useCallback(() => {
    sendTextMessage("/h");
  }, [sendTextMessage]);
  const handleNavigate = useCallback(() => {
    router.push("/navigate");
  }, []);
  const handleClear = useCallback(() => {
    clearMessages();
  }, [clearMessages]);
  // Resolve a picked asset into a StagedImage
  const stageAsset = useCallback(async (asset: { base64?: string | null; uri: string; mimeType?: string | null }) => {
    const mimeType = asset.mimeType ?? (asset.uri.endsWith(".png") ? "image/png" : "image/jpeg");
    let base64 = asset.base64 ?? "";
    if (!base64 && asset.uri) {
      const { readAsStringAsync } = await import("expo-file-system/legacy");
      base64 = await readAsStringAsync(asset.uri, { encoding: "base64" });
    }
    if (base64) {
      setStagedImage({ base64, uri: asset.uri, mimeType });
    }
  }, []);
  const pickFromLibrary = useCallback(async () => {
    try {
      const ImagePicker = await import("expo-image-picker");
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== "granted") {
        Alert.alert("Permission needed", "Please allow photo library access in Settings.");
        return;
      }
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ["images"],
        quality: 0.7,
        base64: true,
      });
      if (result.canceled || !result.assets?.[0]) return;
      await stageAsset(result.assets[0]);
    } catch (err: any) {
      Alert.alert("Image Error", err?.message ?? String(err));
    }
  }, [stageAsset]);
  const pickFromCamera = useCallback(async () => {
    try {
      const ImagePicker = await import("expo-image-picker");
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      if (status !== "granted") {
        Alert.alert("Permission needed", "Please allow camera access in Settings.");
        return;
      }
      const result = await ImagePicker.launchCameraAsync({
        quality: 0.7,
        base64: true,
      });
      if (result.canceled || !result.assets?.[0]) return;
      await stageAsset(result.assets[0]);
    } catch (err: any) {
      Alert.alert("Camera Error", err?.message ?? String(err));
    }
  }, [stageAsset]);
  const handlePickImage = useCallback(() => {
    if (Platform.OS === "ios") {
      ActionSheetIOS.showActionSheetWithOptions(
        {
          options: ["Cancel", "Take Photo", "Choose from Library"],
          cancelButtonIndex: 0,
        },
        (index) => {
          if (index === 1) pickFromCamera();
          else if (index === 2) pickFromLibrary();
        },
      );
    } else {
      // Android: just open library (camera is accessible from there)
      pickFromLibrary();
    }
  }, [pickFromCamera, pickFromLibrary]);
  const handleImageSend = useCallback(
    (caption: string) => {
      if (!stagedImage) return;
      sendImageMessage(stagedImage.base64, caption, stagedImage.mimeType);
      setStagedImage(null);
    },
    [stagedImage, sendImageMessage],
  );
  const handleReplay = useCallback(() => {
    if (isPlaying()) {
      stopPlayback();
      return;
    }
    for (let i = messages.length - 1; i >= 0; i--) {
      const msg = messages[i];
      if (msg.role === "assistant") {
        if (msg.audioUri) {
          playAudio(msg.audioUri).catch(() => {});
        }
        return;
      }
    }
  }, [messages]);
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: colors.bg }} edges={["top", "bottom"]}>
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === "ios" ? "padding" : undefined}
      keyboardVerticalOffset={0}
    >
      {/* Header */}
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          paddingHorizontal: 16,
          paddingVertical: 12,
          borderBottomWidth: 1,
          borderBottomColor: colors.border,
        }}
      >
        <View style={{ flexDirection: "row", alignItems: "center", flex: 1, gap: 10 }}>
          <Pressable
            onPress={() => setShowSessions(true)}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
            style={({ pressed }) => ({
              width: 36,
              height: 36,
              alignItems: "center",
              justifyContent: "center",
              borderRadius: 18,
              backgroundColor: pressed ? colors.bgTertiary : colors.bgTertiary + "80",
            })}
          >
            <Text style={{ color: colors.textSecondary, fontSize: 18 }}>☰</Text>
          </Pressable>
          <Pressable
            onPress={() => setShowSessions(true)}
            style={{ flexDirection: "row", alignItems: "center", gap: 8, flex: 1 }}
            hitSlop={{ top: 6, bottom: 6, left: 0, right: 6 }}
          >
            <Text
              style={{
                color: colors.text,
                fontSize: 22,
                fontWeight: "800",
                letterSpacing: -0.5,
                flexShrink: 1,
              }}
              numberOfLines={1}
            >
              {activeSessionName}
            </Text>
            <StatusDot status={status} size={8} />
          </Pressable>
        </View>
        <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
          <Pressable
            onPress={cycleMode}
            hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
            style={({ pressed }) => ({
              width: 36,
              height: 36,
              alignItems: "center",
              justifyContent: "center",
              borderRadius: 18,
              backgroundColor: pressed ? colors.bgTertiary : colors.bgTertiary + "80",
            })}
          >
            <Text style={{ fontSize: 15 }}>{themeIcon}</Text>
          </Pressable>
          <Pressable
            onPress={() => router.push("/settings")}
            hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
            style={{
              width: 36,
              height: 36,
              alignItems: "center",
              justifyContent: "center",
              borderRadius: 18,
              backgroundColor: colors.bgTertiary,
            }}
          >
            <Text style={{ fontSize: 15 }}>⚙️</Text>
          </Pressable>
        </View>
      </View>
      {/* Message list */}
      <View style={{ flex: 1 }}>
        {messages.length === 0 ? (
          <View style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 16 }}>
            <View
              style={{
                width: 80,
                height: 80,
                borderRadius: 40,
                backgroundColor: colors.bgTertiary,
                alignItems: "center",
                justifyContent: "center",
                borderWidth: 1,
                borderColor: colors.border,
              }}
            >
              <Text style={{ fontSize: 36 }}>🛩</Text>
            </View>
            <View style={{ alignItems: "center", gap: 6 }}>
              <Text style={{ color: colors.text, fontSize: 20, fontWeight: "700" }}>
                PAILot
              </Text>
              <Text
                style={{
                  color: colors.textMuted,
                  fontSize: 14,
                  textAlign: "center",
                  paddingHorizontal: 40,
                  lineHeight: 20,
                }}
              >
                Voice-first AI communicator.{"\n"}Tap the mic to start talking.
              </Text>
            </View>
          </View>
        ) : (
          <MessageList messages={messages} />
        )}
      </View>
      {/* Command bar */}
      {isTextMode ? (
        <TextModeCommandBar
          onScreenshot={handleScreenshot}
          onNavigate={handleNavigate}
          onPhoto={handlePickImage}
          onHelp={handleHelp}
          onClear={handleClear}
        />
      ) : (
        <CommandBar
          onScreenshot={handleScreenshot}
          onNavigate={handleNavigate}
          onPhoto={handlePickImage}
          onClear={handleClear}
        />
      )}
      {/* Input bar */}
      <InputBar
        onSendText={sendTextMessage}
        onVoiceRecorded={sendVoiceMessage}
        onReplay={handleReplay}
        isTextMode={isTextMode}
        onToggleMode={() => setIsTextMode((v) => !v)}
        audioPlaying={audioPlaying}
      />
    </KeyboardAvoidingView>
    {/* Image caption modal — WhatsApp-style full-screen preview */}
    <ImageCaptionModal
      visible={!!stagedImage}
      imageUri={stagedImage ? `data:${stagedImage.mimeType};base64,${stagedImage.base64}` : ""}
      onSend={handleImageSend}
      onCancel={() => setStagedImage(null)}
    />
    {/* Session drawer — absolute overlay outside KAV */}
    <SessionDrawer
      visible={showSessions}
      onClose={() => setShowSessions(false)}
    />
    </SafeAreaView>
  );
}