File size: 14,456 Bytes
fe828ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import { useCallback, useEffect, useRef, useState } from "react";
import { Bot, User, Send, Loader2, Mic, MicOff, CheckCircle2, RotateCcw, AlertTriangle, RefreshCw, ArrowRight } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Components } from "react-markdown";
import AudioRecorder from "./AudioRecorder";
import { getInterviewResult, type InterviewResult } from "../../../services/interviewApi";
import {
  useInterviewSession,
  type InterviewMessage,
  type InterviewMode,
} from "../../../hooks/useInterviewSession";

const markdownComponents: Components = {
  p: ({ children }) => (
    <p className="text-sm mb-1.5 last:mb-0 leading-relaxed">{children}</p>
  ),
  ul: ({ children }) => (
    <ul className="list-disc pl-4 mb-1.5 space-y-0.5 text-sm">{children}</ul>
  ),
  ol: ({ children }) => (
    <ol className="list-decimal pl-4 mb-1.5 space-y-0.5 text-sm">{children}</ol>
  ),
  li: ({ children }) => <li>{children}</li>,
  strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
  em: ({ children }) => <em className="italic">{children}</em>,
};

interface InterviewPanelProps {
  roomId: string;
  userId: string;
  onComplete: () => void;
  onResultReady?: (result: InterviewResult) => void;
}

export default function InterviewPanel({ roomId, userId, onComplete, onResultReady }: InterviewPanelProps) {
  const {
    status,
    messages,
    isSending,
    isStarting,
    startError,
    interviewResult,
    isLoaded,
    startSession,
    sendTextMessage,
    connectAudio,
    disconnectAudio,
    sendAudioChunk,
    sendEndUtterance,
    switchMode,
    resetSession,
  } = useInterviewSession(roomId, userId);

  const [input, setInput] = useState("");
  const [audioMode, setAudioMode] = useState<InterviewMode>("text");
  const [audioStreamingText, setAudioStreamingText] = useState("");
  const [isAudioConnected, setIsAudioConnected] = useState(false);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const audioContextRef = useRef<AudioContext | null>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // Auto-scroll to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, audioStreamingText]);

  // Auto-start hanya setelah localStorage selesai dimuat dan status benar-benar idle
  useEffect(() => {
    if (isLoaded && status === "idle") {
      startSession("text");
    }
  }, [isLoaded, status]); // eslint-disable-line react-hooks/exhaustive-deps

  // Notify parent when result is ready (from hook or re-fetched)
  useEffect(() => {
    if (status === "completed" && interviewResult) {
      onResultReady?.(interviewResult);
    } else if (status === "completed" && !interviewResult) {
      getInterviewResult(roomId)
        .then((r) => onResultReady?.(r))
        .catch(() => {});
    }
  }, [status, interviewResult]); // eslint-disable-line react-hooks/exhaustive-deps

  // Setup audio WebSocket when audio mode is active
  useEffect(() => {
    if (audioMode !== "audio" || status !== "active") return;
    if (isAudioConnected) return;

    setIsAudioConnected(true);
    connectAudio(
      (token) => setAudioStreamingText((prev) => prev + token),
      (fullText) => {
        setAudioStreamingText("");
        // The hook handles adding the message internally, but for audio we add it here
        // since audio messages arrive differently
        void fullText; // handled via useInterviewSession internal state if needed
      },
      async (audioBuf) => {
        // Play TTS audio
        try {
          if (!audioContextRef.current || audioContextRef.current.state === "closed") {
            audioContextRef.current = new AudioContext();
          }
          const ctx = audioContextRef.current;
          const decoded = await ctx.decodeAudioData(audioBuf.slice(0));
          const source = ctx.createBufferSource();
          source.buffer = decoded;
          source.connect(ctx.destination);
          source.start();
        } catch {
          // ignore playback errors
        }
      },
      () => {
        setIsAudioConnected(false);
        onComplete();
      }
    );

    return () => {
      disconnectAudio();
      setIsAudioConnected(false);
    };
  }, [audioMode, status]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleSendText = useCallback(async () => {
    const text = input.trim();
    if (!text || isSending || status !== "active") return;
    setInput("");
    await sendTextMessage(text);
    inputRef.current?.focus();
  }, [input, isSending, status, sendTextMessage]);

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendText();
    }
  };

  const handleModeToggle = () => {
    const next: InterviewMode = audioMode === "text" ? "audio" : "text";
    setAudioMode(next);
    switchMode(next);
    setIsAudioConnected(false);
    setAudioStreamingText("");
  };

  const handleRestart = () => {
    setAudioMode("text");
    setIsAudioConnected(false);
    setAudioStreamingText("");
    resetSession();
    startSession("text");
  };

  // Loading state saat memanggil API untuk membuat sesi
  if (isStarting) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center gap-3 text-slate-500">
        <Loader2 className="w-6 h-6 animate-spin text-emerald-600" />
        <p className="text-sm">Memulai sesi interview…</p>
      </div>
    );
  }

  // Error state — backend tidak bisa dijangkau
  if (startError && status === "idle") {
    return (
      <div className="flex-1 flex flex-col items-center justify-center gap-4 px-6">
        <div className="flex flex-col items-center gap-2 text-center">
          <AlertTriangle className="w-8 h-8 text-amber-400" />
          <p className="text-sm font-medium text-slate-700">Tidak dapat terhubung ke server interview</p>
          <p className="text-xs text-slate-400 max-w-xs">
            Pastikan backend interview berjalan di <code className="bg-slate-100 px-1 py-0.5 rounded text-xs">localhost:8080</code>
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => startSession("text")}
            className="flex items-center gap-1.5 px-3 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-xs rounded-lg transition"
          >
            <RefreshCw className="w-3.5 h-3.5" />
            Coba Lagi
          </button>
          <button
            onClick={onComplete}
            className="flex items-center gap-1.5 px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs rounded-lg transition"
          >
            Lanjut ke Analytics
            <ArrowRight className="w-3.5 h-3.5" />
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col min-h-0">
      {/* Mode toggle bar */}
      <div className="flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-white/60 backdrop-blur-sm">
        <p className="text-xs text-slate-500">
          {status === "completed"
            ? "Interview selesai — lihat hasil di bawah"
            : "Jawab pertanyaan untuk membantu analisis data Anda"}
        </p>
        <div className="flex items-center gap-2">
          {status === "completed" && (
            <button
              onClick={handleRestart}
              className="flex items-center gap-1 text-xs text-slate-400 hover:text-slate-600 transition"
            >
              <RotateCcw className="w-3 h-3" />
              Mulai ulang
            </button>
          )}
          {status === "active" && (
            <button
              onClick={handleModeToggle}
              title={audioMode === "text" ? "Beralih ke mode audio" : "Beralih ke mode teks"}
              className={`flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-full border transition-all duration-200 ${
                audioMode === "audio"
                  ? "bg-emerald-50 border-emerald-200 text-emerald-700"
                  : "bg-slate-50 border-slate-200 text-slate-500 hover:border-slate-300"
              }`}
            >
              {audioMode === "audio" ? (
                <Mic className="w-3 h-3" />
              ) : (
                <MicOff className="w-3 h-3" />
              )}
              <span>{audioMode === "audio" ? "Audio" : "Teks"}</span>
            </button>
          )}
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-3">
        {messages.map((msg) => (
          <MessageBubble key={msg.id} message={msg} />
        ))}

        {/* Live audio streaming text */}
        {audioStreamingText && (
          <div className="flex gap-2.5 max-w-[85%]">
            <div className="w-7 h-7 rounded-full bg-emerald-100 flex items-center justify-center flex-shrink-0 mt-0.5">
              <Bot className="w-4 h-4 text-emerald-600" />
            </div>
            <div className="bg-white border border-slate-200 rounded-2xl rounded-tl-sm px-3.5 py-2.5 shadow-sm">
              <p className="text-sm text-slate-700 leading-relaxed">
                {audioStreamingText}
                <span className="inline-block w-1 h-3.5 bg-emerald-500 ml-0.5 animate-pulse rounded-sm" />
              </p>
            </div>
          </div>
        )}

        {/* Completed state */}
        {status === "completed" && (
          <div className="flex justify-center py-4">
            <div className="flex items-center gap-2 text-emerald-600 bg-emerald-50 border border-emerald-200 rounded-full px-4 py-2 text-sm">
              <CheckCircle2 className="w-4 h-4" />
              <span>Interview selesai!</span>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* CTA setelah interview selesai */}
      {status === "completed" && (
        <div className="border-t border-slate-100 px-4 py-3 flex justify-end">
          <button
            onClick={onComplete}
            className="flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm rounded-xl transition"
          >
            Lanjut ke Analytics
            <ArrowRight className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Input area */}
      {status === "active" && (
        <div className="border-t border-slate-200 bg-white/80 backdrop-blur-sm p-3">
          {audioMode === "audio" ? (
            <div className="flex items-center justify-center gap-3 py-2">
              <p className="text-sm text-slate-500">
                Tahan tombol mikrofon lalu bicara
              </p>
              <AudioRecorder
                onChunk={sendAudioChunk}
                onEndUtterance={sendEndUtterance}
                disabled={isSending}
              />
            </div>
          ) : (
            <div className="flex items-end gap-2">
              <textarea
                ref={inputRef}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={handleKeyPress}
                placeholder="Ketik jawaban Anda…"
                rows={1}
                disabled={isSending}
                className="flex-1 resize-none bg-slate-50 border border-slate-200 rounded-xl px-3.5 py-2.5 text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-emerald-400 focus:border-transparent transition max-h-32 disabled:opacity-60"
                style={{ minHeight: "42px" }}
                onInput={(e) => {
                  const el = e.currentTarget;
                  el.style.height = "auto";
                  el.style.height = `${Math.min(el.scrollHeight, 128)}px`;
                }}
              />
              <button
                onClick={handleSendText}
                disabled={!input.trim() || isSending}
                className="w-9 h-9 rounded-full bg-emerald-600 hover:bg-emerald-700 disabled:bg-slate-200 disabled:cursor-not-allowed text-white flex items-center justify-center flex-shrink-0 transition-all duration-200 hover:scale-105 disabled:scale-100"
              >
                {isSending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Send className="w-4 h-4" />
                )}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function MessageBubble({ message }: { message: InterviewMessage }) {
  const isUser = message.role === "user";

  if (isUser) {
    return (
      <div className="flex gap-2.5 max-w-[85%] ml-auto flex-row-reverse">
        <div className="w-7 h-7 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0 mt-0.5">
          <User className="w-4 h-4 text-white" />
        </div>
        <div className="bg-blue-600 text-white rounded-2xl rounded-tr-sm px-3.5 py-2.5 shadow-sm">
          <p className="text-sm leading-relaxed whitespace-pre-wrap">{message.content}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex gap-2.5 max-w-[85%]">
      <div className="w-7 h-7 rounded-full bg-emerald-100 flex items-center justify-center flex-shrink-0 mt-0.5">
        <Bot className="w-4 h-4 text-emerald-600" />
      </div>
      <div className="bg-white border border-slate-200 rounded-2xl rounded-tl-sm px-3.5 py-2.5 shadow-sm">
        {message.isStreaming && !message.content ? (
          <div className="flex gap-1 py-1">
            <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-bounce [animation-delay:0ms]" />
            <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-bounce [animation-delay:150ms]" />
            <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-bounce [animation-delay:300ms]" />
          </div>
        ) : (
          <div className="text-slate-700">
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              components={markdownComponents}
            >
              {message.content}
            </ReactMarkdown>
            {message.isStreaming && (
              <span className="inline-block w-1 h-3.5 bg-emerald-500 ml-0.5 animate-pulse rounded-sm" />
            )}
          </div>
        )}
      </div>
    </div>
  );
}