
import React from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import MoviePlayer from '../components/MoviePlayer';

const MoviePlayerPage = () => {
  const { title } = useParams<{ title: string }>();
  const navigate = useNavigate();

  const handleBack = () => {
    navigate(`/movie/${encodeURIComponent(title || '')}`);
  };

  // Save playback progress to localStorage
  const savePlaybackProgress = (currentTime: number, duration: number) => {
    if (!title) return;
    
    try {
      const progressKey = `movie-progress-${title}`;
      const isCompleted = (currentTime / duration) > 0.9; // Mark as completed if 90% watched
      
      localStorage.setItem(progressKey, JSON.stringify({
        currentTime,
        duration,
        lastPlayed: new Date().toISOString(),
        completed: isCompleted
      }));
    } catch (error) {
      console.error('Error saving playback progress:', error);
    }
  };

  // Fetch stored playback progress from localStorage
  const getPlaybackProgress = () => {
    if (!title) return 0;
    
    try {
      const progressKey = `movie-progress-${title}`;
      const storedProgress = localStorage.getItem(progressKey);
      
      if (storedProgress) {
        const progress = JSON.parse(storedProgress);
        if (progress && progress.currentTime && !progress.completed) {
          return progress.currentTime;
        }
      }
    } catch (error) {
      console.error('Error reading playback progress:', error);
    }
    
    return 0;
  };

  return (
    <div className="fixed inset-0 h-screen w-screen overflow-hidden bg-black">
      <MoviePlayer 
        movieTitle={title || ''}
        startTime={getPlaybackProgress()}
        onClosePlayer={handleBack}
        onProgressUpdate={savePlaybackProgress}
      />
    </div>
  );
};

export default MoviePlayerPage;
