File size: 9,902 Bytes
cc2caf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Users, Link, Copy, CheckCircle, Send } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface WatchTogetherProps {
  title: string;
  currentTime: number;
  duration: number;
  onSeek?: (time: number) => void;
}

interface Message {
  id: string;
  name: string;
  text: string;
  timestamp: number;
  type: 'chat' | 'system' | 'timestamp';
}

const WatchTogether: React.FC<WatchTogetherProps> = ({ title, currentTime, duration, onSeek }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [roomId, setRoomId] = useState<string>('');
  const [userName, setUserName] = useState<string>('');
  const [message, setMessage] = useState<string>('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [userCount, setUserCount] = useState(1);
  const [isHost, setIsHost] = useState(true);
  const [linkCopied, setLinkCopied] = useState(false);
  
  const { toast } = useToast();
  
  // Generate room ID on mount
  useEffect(() => {
    const id = `room-${Math.random().toString(36).substring(2, 8)}`;
    setRoomId(id);
    
    // If no username set, use a default
    if (!userName) {
      setUserName(`User${Math.floor(Math.random() * 10000)}`);
    }
    
    // Initial system message
    addSystemMessage(`Watch Party started for "${title}"`);
  }, [title]);
  
  // Function to add system message
  const addSystemMessage = (text: string) => {
    const newMessage: Message = {
      id: `sys-${Date.now()}`,
      name: 'System',
      text,
      timestamp: Date.now(),
      type: 'system'
    };
    setMessages(prev => [...prev, newMessage]);
  };
  
  // Function to add user message
  const addUserMessage = () => {
    if (!message.trim()) return;
    
    // If message starts with '/seek ', treat as seek command
    if (message.startsWith('/seek ')) {
      const seekTime = parseInt(message.replace('/seek ', ''));
      if (!isNaN(seekTime) && seekTime >= 0 && seekTime <= duration) {
        handleSeek(seekTime);
        setMessage('');
        return;
      }
    }
    
    // Regular message
    const newMessage: Message = {
      id: `msg-${Date.now()}`,
      name: userName,
      text: message,
      timestamp: Date.now(),
      type: 'chat'
    };
    
    setMessages(prev => [...prev, newMessage]);
    setMessage('');
  };
  
  // Function to handle seeking
  const handleSeek = (time: number) => {
    if (onSeek) {
      onSeek(time);
      
      // Add timestamp message
      const newMessage: Message = {
        id: `time-${Date.now()}`,
        name: userName,
        text: `Seeked to ${formatTime(time)}`,
        timestamp: Date.now(),
        type: 'timestamp'
      };
      setMessages(prev => [...prev, newMessage]);
    }
  };
  
  // Function to share current timestamp
  const shareCurrentTime = () => {
    const newMessage: Message = {
      id: `time-${Date.now()}`,
      name: userName,
      text: `Current position: ${formatTime(currentTime)}`,
      timestamp: Date.now(),
      type: 'timestamp'
    };
    setMessages(prev => [...prev, newMessage]);
  };
  
  // Function to format time
  const formatTime = (timeInSeconds: number) => {
    const minutes = Math.floor(timeInSeconds / 60);
    const seconds = Math.floor(timeInSeconds % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };
  
  // Function to copy invite link
  const copyInviteLink = () => {
    const inviteLink = `${window.location.href}?room=${roomId}&host=false`;
    navigator.clipboard.writeText(inviteLink);
    setLinkCopied(true);
    
    toast({
      title: "Link Copied",
      description: "Share this link with friends to watch together",
    });
    
    setTimeout(() => setLinkCopied(false), 2000);
  };
  
  // Simulate someone joining after a delay
  useEffect(() => {
    if (isOpen && isHost) {
      const timer = setTimeout(() => {
        setUserCount(2);
        addSystemMessage("Alice has joined the watch party");
      }, 5000);
      
      return () => clearTimeout(timer);
    }
  }, [isOpen, isHost]);
  
  // Add mock message after some delays
  useEffect(() => {
    if (isOpen && userCount > 1) {
      const timer1 = setTimeout(() => {
        setMessages(prev => [
          ...prev, 
          {
            id: `msg-alice-1`,
            name: "Alice",
            text: "Hey, thanks for inviting me!",
            timestamp: Date.now(),
            type: 'chat'
          }
        ]);
      }, 3000);
      
      const timer2 = setTimeout(() => {
        setMessages(prev => [
          ...prev, 
          {
            id: `msg-alice-2`,
            name: "Alice",
            text: "I love this part coming up!",
            timestamp: Date.now(),
            type: 'chat'
          }
        ]);
      }, 15000);
      
      return () => {
        clearTimeout(timer1);
        clearTimeout(timer2);
      };
    }
  }, [isOpen, userCount]);
  
  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button 
          variant="outline" 
          size="sm" 
          className="fixed top-4 right-36 z-50 bg-gray-800/80 hover:bg-gray-700/80 text-white border-gray-600"
          onClick={() => setIsOpen(true)}
        >
          <Users className="mr-2 h-4 w-4" />
          Watch Together
        </Button>
      </DialogTrigger>
      
      <DialogContent className="sm:max-w-[425px] bg-gray-900 text-white border-gray-700">
        <DialogHeader>
          <DialogTitle>Watch Together</DialogTitle>
        </DialogHeader>
        
        <div className="flex items-center justify-between py-2 px-4 bg-gray-800 rounded-lg">
          <div className="flex items-center">
            <Users className="h-5 w-5 mr-2 text-theme-primary" />
            <span>{userCount} {userCount === 1 ? 'viewer' : 'viewers'}</span>
          </div>
          
          <div className="flex items-center space-x-2">
            <Link className="h-4 w-4 text-gray-400" />
            <button
              onClick={copyInviteLink}
              className="text-sm text-theme-primary hover:text-theme-primary-light flex items-center"
            >
              {linkCopied ? (
                <><CheckCircle className="h-4 w-4 mr-1" /> Copied</>
              ) : (
                <><Copy className="h-4 w-4 mr-1" /> Copy Invite Link</>
              )}
            </button>
          </div>
        </div>
        
        {/* Chat messages */}
        <div className="flex flex-col space-y-4 h-[250px] overflow-y-auto py-2 px-1">
          {messages.map((msg) => (
            <div 
              key={msg.id}
              className={`flex flex-col ${msg.name === userName ? 'items-end' : 'items-start'}`}
            >
              {msg.type === 'system' ? (
                <div className="bg-gray-800/50 text-gray-300 py-1 px-3 rounded-md text-xs w-full text-center">
                  {msg.text}
                </div>
              ) : msg.type === 'timestamp' ? (
                <div 
                  className={`bg-theme-primary/20 text-theme-primary py-1 px-3 rounded-md text-xs cursor-pointer hover:bg-theme-primary/30 ${
                    msg.name === userName ? 'self-end' : 'self-start'
                  }`}
                  onClick={() => {
                    const timeMatch = msg.text.match(/(\d+):(\d+)/);
                    if (timeMatch) {
                      const minutes = parseInt(timeMatch[1]);
                      const seconds = parseInt(timeMatch[2]);
                      const totalSeconds = minutes * 60 + seconds;
                      onSeek?.(totalSeconds);
                    }
                  }}
                >
                  {msg.text}
                </div>
              ) : (
                <>
                  <span className="text-xs text-gray-400 mb-1">
                    {msg.name === userName ? 'You' : msg.name}
                  </span>
                  <div 
                    className={`py-2 px-3 rounded-lg max-w-[80%] ${
                      msg.name === userName 
                        ? 'bg-theme-primary text-white' 
                        : 'bg-gray-800 text-gray-200'
                    }`}
                  >
                    <p className="text-sm">{msg.text}</p>
                  </div>
                </>
              )}
            </div>
          ))}
        </div>
        
        {/* Share current timestamp button */}
        <button 
          onClick={shareCurrentTime}
          className="text-sm text-theme-primary hover:text-theme-primary-light flex items-center self-center"
        >
          Share current timestamp ({formatTime(currentTime)})
        </button>
        
        {/* Chat input */}
        <div className="flex space-x-2 mt-2">
          <Input
            placeholder="Type a message..."
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            className="bg-gray-800 border-gray-700 text-white"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                addUserMessage();
              }
            }}
          />
          <Button 
            size="icon"
            onClick={addUserMessage}
            className="bg-theme-primary hover:bg-theme-primary-hover"
          >
            <Send className="h-4 w-4" />
          </Button>
        </div>
        
        <p className="text-xs text-gray-400 mt-2">
          Pro tip: Type '/seek 10' to jump to 10 seconds, or click on any shared timestamp to seek.
        </p>
      </DialogContent>
    </Dialog>
  );
};

export default WatchTogether;