import React, { useState, useCallback, useEffect } from 'react'
import { Box, Container, Typography, Paper, Button, Slider, Stack, Grid, Card, CardContent, LinearProgress, IconButton, Tooltip, useTheme, ToggleButton, ToggleButtonGroup, Select, MenuItem, FormControl } from '@mui/material'
import { useDropzone } from 'react-dropzone'
import imageCompression from 'browser-image-compression'
import { toast } from 'react-toastify'
import { useTranslation } from 'react-i18next'
import CloudUploadIcon from '@mui/icons-material/CloudUpload'
import DownloadIcon from '@mui/icons-material/Download'
import DeleteIcon from '@mui/icons-material/Delete'
import InfoIcon from '@mui/icons-material/Info'
import CompareArrowsIcon from '@mui/icons-material/CompareArrows'
import LightModeIcon from '@mui/icons-material/LightMode'
import DarkModeIcon from '@mui/icons-material/DarkMode'
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline'
import LanguageIcon from '@mui/icons-material/Language'
import ReactMarkdown from 'react-markdown'
import './i18n'

const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10MB
const ACCEPTED_TYPES = {
  'image/jpeg': ['.jpg', '.jpeg'],
  'image/png': ['.png'],
  'image/gif': ['.gif'],
  'image/svg+xml': ['.svg'],
  'image/webp': ['.webp']
}

const COMPRESSION_OPTIONS = [
  { value: 0.1, label: '10%' },  // 10% quality = 90% compression
  { value: 0.25, label: '25%' }, // 25% quality = 75% compression
  { value: 0.5, label: '50%' },  // 50% quality = 50% compression
  { value: 0.75, label: '75%' }, // 75% quality = 25% compression
  { value: 0.9, label: '90%' },  // 90% quality = 10% compression
]

// Add a helper component for markdown text
const MarkdownText = ({ children, ...props }) => (
  <ReactMarkdown
    components={{
      strong: ({ node, ...props }) => (
        <span style={{ fontWeight: 700 }} {...props} />
      ),
      p: ({ node, ...props }) => <span {...props} />
    }}
    {...props}
  >
    {children}
  </ReactMarkdown>
)

function App({ mode, setMode }) {
  const { t, i18n } = useTranslation()
  const theme = useTheme()
  const [files, setFiles] = useState([])
  const [compressionLevel, setCompressionLevel] = useState(0.5)
  const [isCompressing, setIsCompressing] = useState(false)
  const [originalSizes, setOriginalSizes] = useState({})
  const [autoDownload, setAutoDownload] = useState(true)
  const [originalFiles, setOriginalFiles] = useState([])
  const [compressionProgress, setCompressionProgress] = useState({})
  const [language, setLanguage] = useState(i18n.language || 'en')
  const [isLoading, setIsLoading] = useState(false)
  const [compressionStats, setCompressionStats] = useState({
    totalSize: 0,
    savedSize: 0,
    totalFiles: 0
  })
  const [previewUrls, setPreviewUrls] = useState({})
  const [errors, setErrors] = useState({})

  const languages = [
    { code: 'en', name: 'English' },
    { code: 'es', name: 'Español' },
    { code: 'fr', name: 'Français' },
    { code: 'hi', name: 'हिंदी' },
    { code: 'zh', name: '中文' },
    { code: 'ja', name: '日本語' },
    { code: 'ar', name: 'العربية' }
  ]

  const handleLanguageChange = (event) => {
    const newLang = event.target.value
    setLanguage(newLang)
    i18n.changeLanguage(newLang)
  }

  const onDrop = useCallback((acceptedFiles) => {
    const validFiles = acceptedFiles.filter(file => file.size <= MAX_FILE_SIZE)
    if (validFiles.length !== acceptedFiles.length) {
      toast.error('Some files were too large (max 10MB)')
    }
    setFiles(validFiles)
    setOriginalFiles(validFiles)
    setErrors({})
    
    // Store original sizes
    const sizes = {}
    validFiles.forEach(file => {
      sizes[file.name] = file.size
    })
    setOriginalSizes(sizes)

    // Create preview URLs
    const previews = {}
    validFiles.forEach(file => {
      previews[file.name] = URL.createObjectURL(file)
    })
    setPreviewUrls(previews)
  }, [])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: ACCEPTED_TYPES,
    maxSize: MAX_FILE_SIZE,
    multiple: true
  })

  // Cleanup preview URLs on unmount
  useEffect(() => {
    return () => {
      Object.values(previewUrls).forEach(url => URL.revokeObjectURL(url))
    }
  }, [previewUrls])

  const compressImage = async (file) => {
    const quality = 1 - compressionLevel
    const options = {
      maxSizeMB: 1,
      maxWidthOrHeight: 1920,
      useWebWorker: true,
      quality: quality,
      fileType: file.type,
      initialQuality: quality,
      alwaysKeepResolution: true,
      maxIteration: 5,
      exifOrientation: -1,
      checkOrientation: true,
      preserveExif: false,
      progressive: true,
      chromaSubsampling: '4:2:0',
      stripMetadata: true,
      optimization: true,
      progressiveLoading: true,
      interlacing: true,
      qualityBasedCompression: true,
      sizeBasedCompression: true,
      formatBasedCompression: true,
      contentBasedCompression: true,
      perceptualCompression: true,
      losslessCompression: true,
      lossyCompression: true,
      hybridCompression: true,
      adaptiveCompression: true,
      dynamicCompression: true,
      intelligentCompression: true,
      smartCompression: true,
      optimalCompression: true,
      maximumCompression: true,
      minimumCompression: true,
      balancedCompression: true,
    }

    try {
      const compressedFile = await imageCompression(file, options)
      return compressedFile
    } catch (error) {
      console.error('Error compressing image:', error)
      throw error
    }
  }

  const handleCompressionChange = (_, value) => {
    if (value !== null) {
      setCompressionLevel(value)
    }
  }

  const handleSliderChange = (_, value) => {
    setCompressionLevel(value)
  }

  const handleCompress = async () => {
    if (files.length === 0) {
      toast.error('Please select files to compress')
      return
    }

    setIsCompressing(true)
    setIsLoading(true)
    setCompressionProgress({})
    setErrors({})
    
    try {
      const compressedFiles = await Promise.all(
        originalFiles.map(async (file, index) => {
          try {
            setCompressionProgress(prev => ({ ...prev, [index]: 0 }))
            const compressed = await compressImage(file)
            setCompressionProgress(prev => ({ ...prev, [index]: 100 }))
            return compressed
          } catch (error) {
            setErrors(prev => ({
              ...prev,
              [file.name]: 'Failed to compress image. Please try again.'
            }))
            return null
          }
        })
      )

      const validCompressedFiles = compressedFiles.filter(file => file !== null)
      
      if (validCompressedFiles.length === 0) {
        toast.error('No files were compressed successfully')
        return
      }

      setFiles(validCompressedFiles)
      
      // Calculate compression stats
      const totalOriginalSize = originalFiles.reduce((acc, file) => acc + file.size, 0)
      const totalCompressedSize = validCompressedFiles.reduce((acc, file) => acc + file.size, 0)
      setCompressionStats({
        totalSize: totalOriginalSize,
        savedSize: totalOriginalSize - totalCompressedSize,
        totalFiles: validCompressedFiles.length
      })
      
      // Auto-download if enabled
      if (autoDownload) {
        validCompressedFiles.forEach((file, index) => {
          const url = URL.createObjectURL(file)
          const link = document.createElement('a')
          const fileName = file.name.replace(/\.[^/.]+$/, '')
          const fileExtension = file.name.split('.').pop()
          const newFileName = `${fileName}.usingfreecompressor.${fileExtension}`
          link.href = url
          link.download = newFileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          URL.revokeObjectURL(url)
        })
      }
      
      toast.success(`Successfully compressed ${validCompressedFiles.length} images!`)
    } catch (error) {
      console.error('Compression error:', error)
      toast.error('Error compressing images')
    } finally {
      setIsCompressing(false)
      setIsLoading(false)
      setCompressionProgress({})
    }
  }

  // Memoize expensive calculations
  const calculateCompressionStats = useCallback((originalFiles, compressedFiles) => {
    const totalOriginalSize = originalFiles.reduce((acc, file) => acc + file.size, 0)
    const totalCompressedSize = compressedFiles.reduce((acc, file) => acc + file.size, 0)
    return {
      totalSize: totalOriginalSize,
      savedSize: totalOriginalSize - totalCompressedSize,
      totalFiles: compressedFiles.length
    }
  }, [])

  // Optimize cleanup
  useEffect(() => {
    const cleanup = () => {
      const urls = [...Object.values(previewUrls)]
      urls.forEach(url => {
        try {
          URL.revokeObjectURL(url)
        } catch (error) {
          console.warn('Failed to revoke URL:', error)
        }
      })
    }

    window.addEventListener('beforeunload', cleanup)
    return () => {
      cleanup()
      window.removeEventListener('beforeunload', cleanup)
    }
  }, [previewUrls])

  const handleDownload = (file, index) => {
    const url = URL.createObjectURL(file)
    const link = document.createElement('a')
    link.href = url
    link.download = `compressed_${index + 1}_${file.name}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  const handleDelete = (index) => {
    const file = files[index]
    if (previewUrls[file.name]) {
      URL.revokeObjectURL(previewUrls[file.name])
    }
    setFiles(files.filter((_, i) => i !== index))
    setOriginalFiles(originalFiles.filter((_, i) => i !== index))
    setErrors(prev => {
      const newErrors = { ...prev }
      delete newErrors[file.name]
      return newErrors
    })
  }

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const calculateReduction = (originalSize, currentSize) => {
    return ((originalSize - currentSize) / originalSize * 100).toFixed(1)
  }

  return (
    <Box sx={{ 
      minHeight: '100vh', 
      bgcolor: 'background.default',
      backgroundImage: mode === 'light'
        ? 'radial-gradient(circle at 50% 50%, rgba(239, 68, 68, 0.1) 0%, rgba(255, 255, 255, 0) 100%)'
        : 'radial-gradient(circle at 50% 50%, rgba(59, 130, 246, 0.1) 0%, rgba(0, 0, 0, 0) 100%)',
      py: 4,
      display: 'flex',
      flexDirection: 'column'
    }}>
      {/* Header with Theme and Language Controls */}
      <Box sx={{ 
        position: 'fixed', 
        top: 0, 
        right: 0,
        left: 0,
        p: 2, 
        zIndex: 1000,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        bgcolor: mode === 'light' 
          ? 'rgba(255, 255, 255, 0.9)'
          : 'rgba(0, 0, 0, 0.9)',
        backdropFilter: 'blur(8px)',
        borderBottom: mode === 'light'
          ? '1px solid rgba(239, 68, 68, 0.1)'
          : '1px solid rgba(59, 130, 246, 0.1)',
      }}>
        <Box>
          <img
            src={mode === 'light' ? '/images/kreativelogoforlightmode.svg' : '/images/Kreativelogofordarkmode.svg'}
            alt="Kreative Logo"
            style={{
              height: '32px',
              width: 'auto',
              filter: mode === 'light' ? 'invert(32%) sepia(93%) saturate(7471%) hue-rotate(353deg) brightness(97%) contrast(93%)' : 'none',
              display: 'block'
            }}
          />
        </Box>
        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
          <FormControl size="small">
            <Select
              value={language}
              onChange={handleLanguageChange}
              startAdornment={<LanguageIcon sx={{ mr: 1, color: mode === 'light' ? '#64748b' : '#94a3b8' }} />}
              sx={{
                bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.1)' : 'rgba(59, 130, 246, 0.1)',
                color: mode === 'light' ? '#1e293b' : '#fff',
                '& .MuiOutlinedInput-notchedOutline': {
                  border: 'none',
                },
                '&:hover': {
                  bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.2)' : 'rgba(59, 130, 246, 0.2)',
                },
                '& .MuiSelect-icon': {
                  color: mode === 'light' ? '#64748b' : '#94a3b8',
                },
                minWidth: '120px',
                borderRadius: 2,
                '& .MuiSelect-select': {
                  py: 1,
                }
              }}
            >
              {languages.map((lang) => (
                <MenuItem key={lang.code} value={lang.code}>
                  {lang.name}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <IconButton
            onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}
            sx={{
              bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.1)' : 'rgba(59, 130, 246, 0.1)',
              '&:hover': {
                bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.2)' : 'rgba(59, 130, 246, 0.2)',
              }
            }}
          >
            {mode === 'light' ? <DarkModeIcon /> : <LightModeIcon />}
          </IconButton>
        </Box>
      </Box>

      <Container maxWidth="md" sx={{ flex: 1, mt: { xs: 12, sm: 10 } }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
          <Box>
            <Typography 
              variant="h2" 
              component="h1" 
              sx={{ 
                fontWeight: 800,
                color: mode === 'light' ? '#1e293b' : '#fff',
                textShadow: mode === 'light' ? 'none' : '0 2px 4px rgba(0,0,0,0.2)',
                mb: 2
              }}
            >
              {t('title')}
            </Typography>
            <Typography
              variant="h6"
              sx={{
                color: mode === 'light' ? '#64748b' : '#94a3b8',
                fontWeight: 400,
                maxWidth: '800px',
                lineHeight: 1.6
              }}
            >
              <MarkdownText>{t('subtitle')}</MarkdownText>
            </Typography>
          </Box>
        </Box>

        <Paper 
          sx={{ 
            p: 4, 
            mb: 4,
            background: mode === 'light'
              ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(249, 115, 22, 0.1) 100%)'
              : 'linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(37, 99, 235, 0.1) 100%)',
            backdropFilter: 'blur(10px)',
            border: mode === 'light'
              ? '1px solid rgba(239, 68, 68, 0.1)'
              : '1px solid rgba(59, 130, 246, 0.1)',
            borderRadius: 2,
          }}
        >
          <Box sx={{ textAlign: 'center', mb: 4 }}>
            <Button
              variant="contained"
              color="secondary"
              size="large"
              startIcon={<CloudUploadIcon />}
              {...getRootProps()}
              sx={{
                background: mode === 'light'
                  ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                  : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
                '&:hover': {
                  background: mode === 'light'
                    ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)'
                    : 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)',
                },
                px: 6,
                py: 2,
                borderRadius: 2,
                fontSize: '1.1rem'
              }}
            >
              {t('uploadButton')}
            </Button>
            <input {...getInputProps()} />
            <Tooltip title={t('supportedFormats')}>
              <IconButton>
                <InfoIcon />
              </IconButton>
            </Tooltip>
          </Box>

          {files.length > 0 && (
            <>
              <Typography variant="h6" gutterBottom sx={{ fontWeight: 600 }}>
                {t('quickCompression')}
              </Typography>
              <ToggleButtonGroup
                value={compressionLevel}
                exclusive
                onChange={handleCompressionChange}
                sx={{ 
                  mb: 4,
                  display: 'flex',
                  gap: 1,
                  '& .MuiToggleButton-root': {
                    flex: 1,
                    px: 2,
                    py: 1.5,
                    borderRadius: '8px !important',
                    border: 'none',
                    bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.05)' : 'rgba(59, 130, 246, 0.05)',
                    color: mode === 'light' ? 'text.primary' : 'text.secondary',
                    transition: 'all 0.2s ease-in-out',
                    '&.Mui-selected': {
                      color: '#fff',
                      bgcolor: mode === 'light' 
                        ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                        : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
                      transform: 'scale(1.05)',
                      boxShadow: mode === 'light'
                        ? '0 4px 12px rgba(239, 68, 68, 0.2)'
                        : '0 4px 12px rgba(59, 130, 246, 0.2)',
                      '&:hover': {
                        bgcolor: mode === 'light'
                          ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)'
                          : 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)',
                      }
                    },
                    '&:hover': {
                      bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.1)' : 'rgba(59, 130, 246, 0.1)',
                      transform: 'scale(1.02)',
                    }
                  }
                }}
              >
                {COMPRESSION_OPTIONS.map((option) => (
                  <ToggleButton 
                    key={option.value} 
                    value={option.value}
                  >
                    {option.label}
                  </ToggleButton>
                ))}
              </ToggleButtonGroup>
              <Typography variant="h6" gutterBottom sx={{ fontWeight: 600, mb: 2 }}>
                {t('fineTuneCompression')}
              </Typography>
              <Slider
                value={compressionLevel}
                onChange={handleSliderChange}
                min={0.1}
                max={0.9}
                step={0.01}
                marks={[
                  { value: 0.1, label: '10%' },
                  { value: 0.25, label: '25%' },
                  { value: 0.5, label: '50%' },
                  { value: 0.75, label: '75%' },
                  { value: 0.9, label: '90%' }
                ]}
                valueLabelDisplay="auto"
                valueLabelFormat={(value) => `${Math.round(value * 100)}%`}
                sx={{ 
                  mb: 4,
                  '& .MuiSlider-markLabel': {
                    color: mode === 'light' ? 'text.secondary' : 'text.primary',
                  },
                  '& .MuiSlider-valueLabel': {
                    bgcolor: mode === 'light' ? 'primary.main' : 'secondary.main',
                    color: '#fff',
                  }
                }}
              />
              <Stack direction="row" spacing={2} alignItems="center" sx={{ mb: 4 }}>
                <Button
                  variant="contained"
                  onClick={handleCompress}
                  disabled={isCompressing}
                  fullWidth
                  size="large"
                  sx={{
                    background: mode === 'light'
                      ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                      : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
                    '&:hover': {
                      background: mode === 'light'
                        ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)'
                        : 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)',
                    },
                    py: 2,
                    borderRadius: 2,
                    boxShadow: mode === 'light'
                      ? '0 4px 12px rgba(239, 68, 68, 0.2)'
                      : '0 4px 12px rgba(59, 130, 246, 0.2)',
                  }}
                >
                  {isCompressing ? (
                    <>
                      <LinearProgress sx={{ width: '100%', mr: 2 }} />
                      {t('compressing')}
                    </>
                  ) : (
                    t('compressButton')
                  )}
                </Button>
                <Button
                  variant="contained"
                  onClick={() => setAutoDownload(!autoDownload)}
                  startIcon={autoDownload ? <DownloadIcon /> : <DownloadIcon sx={{ opacity: 0.5 }} />}
                  sx={{
                    minWidth: '200px',
                    background: autoDownload
                      ? mode === 'light'
                        ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                        : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
                      : mode === 'light'
                        ? 'linear-gradient(135deg, #6b7280 0%, #4b5563 100%)'
                        : 'linear-gradient(135deg, #4b5563 0%, #374151 100%)',
                    py: 2,
                    borderRadius: 2,
                    boxShadow: autoDownload
                      ? mode === 'light'
                        ? '0 4px 12px rgba(239, 68, 68, 0.2)'
                        : '0 4px 12px rgba(59, 130, 246, 0.2)'
                      : '0 4px 12px rgba(107, 114, 128, 0.2)',
                    transition: 'all 0.3s ease-in-out',
                    '&:hover': {
                      background: autoDownload
                        ? mode === 'light'
                          ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)'
                          : 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)'
                        : mode === 'light'
                          ? 'linear-gradient(135deg, #4b5563 0%, #374151 100%)'
                          : 'linear-gradient(135deg, #374151 0%, #1f2937 100%)',
                      transform: 'translateY(-1px)'
                    }
                  }}
                >
                  {autoDownload ? t('autoDownloadOn') : t('autoDownloadOff')}
                </Button>
              </Stack>
            </>
          )}
        </Paper>

        {files.length > 0 && (
          <Grid container spacing={3}>
            {compressionStats.totalFiles > 0 && (
              <Grid item xs={12} md={4}>
                <Paper 
                  sx={{ 
                    p: 2,
                    height: '100%',
                    background: mode === 'light'
                      ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.05), rgba(249, 115, 22, 0.05) 100%)'
                      : 'linear-gradient(135deg, rgba(59, 130, 246, 0.05), rgba(37, 99, 235, 0.05) 100%)',
                    border: mode === 'light'
                      ? '1px solid rgba(239, 68, 68, 0.1)'
                      : '1px solid rgba(59, 130, 246, 0.1)',
                  }}
                >
                  <Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 600, mb: 2 }}>
                    {t('compressionSummary')}
                  </Typography>
                  <Stack spacing={1.5}>
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
                        {t('totalFiles')}
                      </Typography>
                      <Typography 
                        variant="h6" 
                        sx={{ 
                          fontWeight: 600,
                          color: mode === 'light' ? '#059669' : '#10B981'
                        }}
                      >
                        {compressionStats.totalFiles}
                      </Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
                        {t('totalSizeSaved')}
                      </Typography>
                      <Typography 
                        variant="h6" 
                        sx={{ 
                          fontWeight: 600,
                          color: mode === 'light' ? '#059669' : '#10B981'
                        }}
                      >
                        {formatFileSize(compressionStats.savedSize)}
                      </Typography>
                    </Box>
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
                        {t('averageReduction')}
                      </Typography>
                      <Typography 
                        variant="h6" 
                        sx={{ 
                          fontWeight: 600,
                          color: mode === 'light' ? '#059669' : '#10B981'
                        }}
                      >
                        {((compressionStats.savedSize / compressionStats.totalSize) * 100).toFixed(1)}%
                      </Typography>
                    </Box>
                  </Stack>
                </Paper>
              </Grid>
            )}
            <Grid item xs={12} md={compressionStats.totalFiles > 0 ? 8 : 12}>
              <Paper 
                sx={{ 
                  p: 3,
                  background: mode === 'light'
                    ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.05), rgba(249, 115, 22, 0.05) 100%)'
                    : 'linear-gradient(135deg, rgba(59, 130, 246, 0.05), rgba(37, 99, 235, 0.05) 100%)',
                  border: mode === 'light'
                    ? '1px solid rgba(239, 68, 68, 0.1)'
                    : '1px solid rgba(59, 130, 246, 0.1)',
                }}
              >
                <Typography variant="h6" gutterBottom sx={{ fontWeight: 600, mb: 3 }}>
                  {t('selectedFiles')}
                </Typography>
                <Stack spacing={2}>
                  {files.map((file, index) => (
                    <Box
                      key={index}
                      sx={{
                        p: 2,
                        borderRadius: 2,
                        border: mode === 'light'
                          ? '1px solid rgba(239, 68, 68, 0.1)'
                          : '1px solid rgba(59, 130, 246, 0.1)',
                        transition: 'all 0.2s ease-in-out',
                        '&:hover': {
                          transform: 'translateY(-2px)',
                          boxShadow: '0 8px 24px rgba(0,0,0,0.1)',
                        },
                        position: 'relative',
                        overflow: 'hidden',
                      }}
                    >
                      {compressionProgress[index] !== undefined && (
                        <LinearProgress 
                          variant="determinate" 
                          value={compressionProgress[index]}
                          sx={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            height: '3px',
                            bgcolor: mode === 'light' ? 'rgba(239, 68, 68, 0.1)' : 'rgba(59, 130, 246, 0.1)',
                            '& .MuiLinearProgress-bar': {
                              bgcolor: mode === 'light' ? '#ef4444' : '#3b82f6',
                            }
                          }}
                        />
                      )}
                      <Grid container spacing={2} alignItems="center">
                        {previewUrls[file.name] && (
                          <Grid item xs={12} sm={3}>
                            <Box
                              sx={{
                                width: '100%',
                                paddingTop: '100%',
                                position: 'relative',
                                borderRadius: 2,
                                overflow: 'hidden',
                                border: mode === 'light'
                                  ? '1px solid rgba(239, 68, 68, 0.1)'
                                  : '1px solid rgba(59, 130, 246, 0.1)',
                              }}
                            >
                              <img
                                src={previewUrls[file.name]}
                                alt={file.name}
                                style={{
                                  position: 'absolute',
                                  top: 0,
                                  left: 0,
                                  width: '100%',
                                  height: '100%',
                                  objectFit: 'cover'
                                }}
                              />
                            </Box>
                          </Grid>
                        )}
                        <Grid item xs={12} sm={previewUrls[file.name] ? 6 : 7}>
                          <Box>
                            <Typography variant="h6" gutterBottom sx={{ fontWeight: 500, mb: 2 }}>
                              {file.name}
                            </Typography>
                            {errors[file.name] && (
                              <Typography variant="body2" color="error" sx={{ mb: 2 }}>
                                {errors[file.name]}
                              </Typography>
                            )}
                            <Stack spacing={2}>
                              <Stack direction="row" spacing={2} alignItems="center">
                                <Typography variant="body1" color="text.secondary">
                                  {t('original')}: {formatFileSize(originalSizes[file.name])}
                                </Typography>
                                <CompareArrowsIcon sx={{ fontSize: 20, color: 'text.secondary' }} />
                                <Typography variant="body1" color="text.secondary">
                                  {t('compressed')}: {formatFileSize(file.size)}
                                </Typography>
                              </Stack>
                              <Typography 
                                variant="body1" 
                                sx={{ 
                                  color: mode === 'light' ? '#059669' : '#3b82f6',
                                  fontWeight: 600,
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: 0.5,
                                }}
                              >
                                {calculateReduction(originalSizes[file.name], file.size)}% {t('smaller')}
                                {compressionProgress[index] === 100 && (
                                  <span style={{ color: mode === 'light' ? '#059669' : '#3b82f6' }}>✓</span>
                                )}
                              </Typography>
                            </Stack>
                          </Box>
                        </Grid>
                        <Grid item xs={12} sm={previewUrls[file.name] ? 3 : 2}>
                          <Stack spacing={2} alignItems="stretch">
                            <Button
                              variant="contained"
                              startIcon={<DownloadIcon />}
                              onClick={() => handleDownload(file, index)}
                              fullWidth
                              sx={{
                                background: mode === 'light'
                                  ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
                                  : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
                                boxShadow: mode === 'light'
                                  ? '0 4px 12px rgba(239, 68, 68, 0.2)'
                                  : '0 4px 12px rgba(59, 130, 246, 0.2)',
                                transition: 'all 0.3s ease-in-out',
                                '&:hover': {
                                  background: mode === 'light'
                                    ? 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)'
                                    : 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)',
                                  transform: 'translateY(-1px)'
                                }
                              }}
                            >
                              {t('download')}
                            </Button>
                            <Button
                              variant="outlined"
                              startIcon={<DeleteIcon />}
                              onClick={() => handleDelete(index)}
                              fullWidth
                              sx={{
                                borderColor: mode === 'light' ? 'rgba(239, 68, 68, 0.5)' : 'rgba(239, 68, 68, 0.5)',
                                color: mode === 'light' ? '#ef4444' : '#ef4444',
                                '&:hover': {
                                  borderColor: mode === 'light' ? '#ef4444' : '#ef4444',
                                  background: 'rgba(239, 68, 68, 0.1)',
                                }
                              }}
                            >
                              {t('delete')}
                            </Button>
                          </Stack>
                        </Grid>
                      </Grid>
                    </Box>
                  ))}
                </Stack>
              </Paper>
            </Grid>
          </Grid>
        )}

        {/* SEO Content Section */}
        <Box sx={{ mt: 8, mb: 4 }}>
          <Typography 
            variant="h3" 
            component="h2" 
            gutterBottom
            sx={{ 
              fontWeight: 700,
              color: mode === 'light' ? '#1e293b' : '#fff',
              mb: 4,
              textAlign: 'center'
            }}
          >
            {t('howToTitle')}
          </Typography>

          <Grid container spacing={4}>
            {[
              'compression',
              'whyChoose',
              'howItWorks',
              'safety',
              'features',
              'usage'
            ].map((section) => (
              <Grid item xs={12} md={6} key={section}>
                <Paper 
                  sx={{ 
                    p: 4,
                    height: '100%',
                    background: mode === 'light'
                      ? 'linear-gradient(135deg, rgba(239, 68, 68, 0.05), rgba(249, 115, 22, 0.05) 100%)'
                      : 'linear-gradient(135deg, rgba(59, 130, 246, 0.05), rgba(37, 99, 235, 0.05) 100%)',
                    border: mode === 'light'
                      ? '1px solid rgba(239, 68, 68, 0.1)'
                      : '1px solid rgba(59, 130, 246, 0.1)',
                    transition: 'all 0.3s ease-in-out',
                    '&:hover': {
                      transform: 'translateY(-4px)',
                      boxShadow: '0 8px 24px rgba(0,0,0,0.1)',
                    }
                  }}
                >
                  <Typography 
                    variant="h5" 
                    gutterBottom 
                    sx={{ 
                      fontWeight: 600,
                      color: mode === 'light' ? '#1e293b' : '#fff',
                      mb: 2
                    }}
                  >
                    {t(`sections.${section}.title`)}
                  </Typography>
                  <Typography 
                    variant="body1" 
                    color="text.secondary" 
                    paragraph
                    sx={{ mb: 3 }}
                  >
                    {t(`sections.${section}.description`)}
                  </Typography>
                  <Stack spacing={1.5}>
                    {t(`sections.${section}.features`, { returnObjects: true }).map((feature, idx) => (
                      <Typography 
                        key={idx}
                        variant="body2" 
                        color="text.secondary"
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                          '&:before': {
                            content: '"•"',
                            color: mode === 'light' ? '#ef4444' : '#3b82f6',
                            mr: 1,
                            fontWeight: 'bold'
                          }
                        }}
                      >
                        {feature}
                      </Typography>
                    ))}
                  </Stack>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Box>
      </Container>

      {/* Footer with Copyright */}
      <Box 
        component="footer" 
        sx={{ 
          mt: 'auto',
          py: 3,
          textAlign: 'center',
          borderTop: mode === 'light' 
            ? '1px solid rgba(239, 68, 68, 0.1)' 
            : '1px solid rgba(59, 130, 246, 0.1)'
        }}
      >
        <Typography variant="body2" color="text.secondary">
          {t('footer', { year: new Date().getFullYear() })}
        </Typography>
      </Box>
    </Box>
  )
}

export default App 