File size: 10,486 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

import React, { useState, useEffect } from 'react';
import PageHeader from '../components/PageHeader';
import ContentGrid, { ContentItem } from '../components/ContentGrid';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/use-toast';
import { Trash2, DownloadCloud, Upload } from 'lucide-react';
import { getAllFromMyList } from '../lib/storage';

interface WatchHistoryItem {
  type: 'movie' | 'tvshow';
  title: string;
  lastWatched: string;
  progress: number;
  completed: boolean;
}

const ProfilePage = () => {
  const [watchHistory, setWatchHistory] = useState<WatchHistoryItem[]>([]);
  const [myListItems, setMyListItems] = useState<ContentItem[]>([]);
  const [activeTab, setActiveTab] = useState('history');
  const { toast } = useToast();

  // Load watch history from localStorage
  useEffect(() => {
    const loadWatchHistory = () => {
      try {
        const history: WatchHistoryItem[] = [];
        
        // Scan localStorage for movie progress
        for (let i = 0; i < localStorage.length; i++) {
          const key = localStorage.key(i);
          if (key?.startsWith('movie-progress-')) {
            const title = key.replace('movie-progress-', '');
            const data = JSON.parse(localStorage.getItem(key) || '{}');
            
            if (data && data.lastPlayed) {
              history.push({
                type: 'movie',
                title,
                lastWatched: data.lastPlayed,
                progress: Math.round((data.currentTime / data.duration) * 100) || 0,
                completed: data.completed || false
              });
            }
          }
          
          // Scan for TV show progress
          if (key?.startsWith('playback-')) {
            const showTitle = key.replace('playback-', '');
            const showData = JSON.parse(localStorage.getItem(key) || '{}');
            
            let lastEpisodeDate = '';
            let lastEpisodeProgress = 0;
            let anyEpisodeCompleted = false;
            
            // Find the most recently watched episode
            Object.entries(showData).forEach(([_, value]) => {
              const episodeData = value as {
                lastPlayed: string;
                currentTime: number;
                duration: number;
                completed: boolean;
              };
              
              if (!lastEpisodeDate || new Date(episodeData.lastPlayed) > new Date(lastEpisodeDate)) {
                lastEpisodeDate = episodeData.lastPlayed;
                lastEpisodeProgress = Math.round((episodeData.currentTime / episodeData.duration) * 100) || 0;
                if (episodeData.completed) anyEpisodeCompleted = true;
              }
            });
            
            if (lastEpisodeDate) {
              history.push({
                type: 'tvshow',
                title: showTitle,
                lastWatched: lastEpisodeDate,
                progress: lastEpisodeProgress,
                completed: anyEpisodeCompleted
              });
            }
          }
        }
        
        // Sort by most recently watched
        history.sort((a, b) => 
          new Date(b.lastWatched).getTime() - new Date(a.lastWatched).getTime()
        );
        
        setWatchHistory(history);
      } catch (error) {
        console.error('Error loading watch history:', error);
      }
    };
    
    loadWatchHistory();
  }, []);

  // Load My List items
  useEffect(() => {
    const loadMyList = async () => {
      try {
        const items = await getAllFromMyList();
        const contentItems: ContentItem[] = items.map(item => ({
          type: item.type,
          title: item.title,
          image: undefined // ContentCard component will fetch the image
        }));
        setMyListItems(contentItems);
      } catch (error) {
        console.error('Error loading my list:', error);
      }
    };
    
    loadMyList();
  }, []);

  const clearWatchHistory = () => {
    // Filter localStorage keys related to watch history
    const keysToRemove: string[] = [];
    
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && (key.startsWith('movie-progress-') || key.startsWith('playback-'))) {
        keysToRemove.push(key);
      }
    }
    
    // Remove the keys
    keysToRemove.forEach(key => localStorage.removeItem(key));
    
    // Update state
    setWatchHistory([]);
    
    toast({
      title: "Watch History Cleared",
      description: "Your watch history has been successfully cleared.",
    });
  };

  const exportUserData = () => {
    try {
      const userData = {
        watchHistory: {},
        myList: {}
      };
      
      // Export all localStorage data
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (!key) continue;
        
        if (key.startsWith('movie-progress-') || key.startsWith('playback-')) {
          userData.watchHistory[key] = JSON.parse(localStorage.getItem(key) || '{}');
        }
        
        if (key === 'myList') {
          userData.myList = JSON.parse(localStorage.getItem(key) || '[]');
        }
      }
      
      // Create downloadable JSON
      const dataStr = JSON.stringify(userData, null, 2);
      const blob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      // Create temporary link and trigger download
      const a = document.createElement('a');
      a.href = url;
      a.download = `streamflix-user-data-${new Date().toISOString().slice(0, 10)}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      
      toast({
        title: "Export Successful",
        description: "Your data has been exported successfully.",
      });
    } catch (error) {
      console.error('Error exporting user data:', error);
      toast({
        title: "Export Failed",
        description: "There was an error exporting your data.",
        variant: "destructive"
      });
    }
  };

  const renderWatchHistoryItems = (): ContentItem[] => {
    return watchHistory.map(item => ({
      type: item.type,
      title: item.title,
      image: undefined // ContentCard will fetch the image
    }));
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <PageHeader title="Your Profile" subtitle="Manage your preferences and data" />
      
      <div className="mt-8">
        <Tabs defaultValue={activeTab} onValueChange={setActiveTab}>
          <TabsList>
            <TabsTrigger value="history">Watch History</TabsTrigger>
            <TabsTrigger value="mylist">My List</TabsTrigger>
            <TabsTrigger value="settings">Settings</TabsTrigger>
          </TabsList>
          
          <TabsContent value="history" className="pt-6">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold">Watch History</h2>
              {watchHistory.length > 0 && (
                <Button 
                  variant="destructive" 
                  onClick={clearWatchHistory} 
                  className="flex items-center gap-2"
                >
                  <Trash2 size={16} />
                  <span>Clear History</span>
                </Button>
              )}
            </div>
            
            {watchHistory.length === 0 ? (
              <div className="text-center py-12">
                <p className="text-gray-400">You have no watch history yet.</p>
                <p className="text-sm text-gray-500 mt-2">Start watching movies and shows to build your history.</p>
              </div>
            ) : (
              <ContentGrid items={renderWatchHistoryItems()} />
            )}
          </TabsContent>
          
          <TabsContent value="mylist" className="pt-6">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold">My List</h2>
            </div>
            
            {myListItems.length === 0 ? (
              <div className="text-center py-12">
                <p className="text-gray-400">You haven't added anything to your list yet.</p>
                <p className="text-sm text-gray-500 mt-2">Browse content and click the "+" icon to add titles to your list.</p>
              </div>
            ) : (
              <ContentGrid items={myListItems} />
            )}
          </TabsContent>
          
          <TabsContent value="settings" className="pt-6">
            <div className="space-y-6">
              <div>
                <h2 className="text-xl font-bold mb-4">Data Management</h2>
                
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="bg-card rounded-lg p-4 border">
                    <h3 className="text-lg font-medium mb-2">Export Your Data</h3>
                    <p className="text-sm text-gray-400 mb-4">Download your watch history and list data as a JSON file.</p>
                    <Button 
                      onClick={exportUserData}
                      className="flex items-center gap-2"
                    >
                      <DownloadCloud size={16} />
                      <span>Export Data</span>
                    </Button>
                  </div>
                  
                  <div className="bg-card rounded-lg p-4 border">
                    <h3 className="text-lg font-medium mb-2">Import Your Data</h3>
                    <p className="text-sm text-gray-400 mb-4">Restore previously exported data (coming soon)</p>
                    <Button 
                      disabled
                      variant="outline"
                      className="flex items-center gap-2 opacity-50"
                    >
                      <Upload size={16} />
                      <span>Import Data</span>
                    </Button>
                  </div>
                </div>
              </div>
              
              <div>
                <h2 className="text-xl font-bold mb-4">Account Settings</h2>
                <p className="text-gray-400">Account management features coming soon.</p>
              </div>
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default ProfilePage;