import React, { useState, useEffect } from 'react';
import { DeviceFrameWrapper } from './components/DeviceFrameWrapper';
import { I18nProvider } from './context/I18nContext';
import { WallpaperProvider } from './context/WallpaperContext';
import { ThemeProvider } from './context/ThemeContext';
import { AuthProvider } from './context/AuthContext';

// 1. كلمة السر الرئيسية الموحدة
const MASTER_PASSWORD = "123"; 

// 2. تغيير هذا الرقم (مثلاً v3.0) سيطرد فوراً جميع الأجهزة القديمة
const SECURITY_VERSION = "v3.0"; 

export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [passwordInput, setPasswordInput] = useState('');
  const [error, setError] = useState(false);

  useEffect(() => {
    const savedVersion = localStorage.getItem('app_sec_version');
    const savedAuth = localStorage.getItem('is_app_authenticated');

    // طرد أي جهاز لا يمتلك نفس رقم الإصدار الحالي
    if (savedAuth === 'true' && savedVersion === SECURITY_VERSION) {
      setIsAuthenticated(true);
    } else {
      localStorage.removeItem('is_app_authenticated');
      localStorage.removeItem('app_sec_version');
      setIsAuthenticated(false);
    }
  }, []);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (passwordInput === MASTER_PASSWORD) {
      localStorage.setItem('is_app_authenticated', 'true');
      localStorage.setItem('app_sec_version', SECURITY_VERSION);
      setIsAuthenticated(true);
      setError(false);
    } else {
      setError(true);
    }
  };

  if (!isAuthenticated) {
    return (
      <div style={{
        display: 'flex', 
        height: '100vh', 
        justifyContent: 'center', 
        alignItems: 'center', 
        backgroundColor: '#0f172a', 
        color: '#fff', 
        dir: 'rtl',
        fontFamily: 'sans-serif',
        position: 'relative',
        overflow: 'hidden'
      }}>
        {/* أنيميشن التوهج والدوران */}
        <style dangerouslySetInnerHTML={{__html: `
          @keyframes pulseGlow {
            0% { transform: scale(1); box-shadow: 0 0 15px rgba(99, 102, 241, 0.4); }
            50% { transform: scale(1.08); box-shadow: 0 0 35px rgba(99, 102, 241, 0.8), 0 0 45px rgba(6, 182, 212, 0.5); }
            100% { transform: scale(1); box-shadow: 0 0 15px rgba(99, 102, 241, 0.4); }
          }
          @keyframes rotateRing {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `}} />

        <form onSubmit={handleLogin} style={{
          background: 'linear-gradient(135deg, #1e293b 0%, #0f172a 100%)', 
          padding: '2.5rem 2rem', 
          borderRadius: '24px', 
          textAlign: 'center',
          boxShadow: '0 20px 40px rgba(0,0,0,0.5)',
          border: '1px solid rgba(255, 255, 255, 0.08)',
          width: '90%',
          maxWidth: '360px',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}>
          {/* الشعار المتحرك */}
          <div style={{
            position: 'relative',
            width: '100px',
            height: '100px',
            marginBottom: '1.5rem',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}>
            <div style={{
              position: 'absolute',
              width: '108px',
              height: '108px',
              borderRadius: '50%',
              border: '2px dashed rgba(99, 102, 241, 0.6)',
              animation: 'rotateRing 12s linear infinite'
            }} />
            
            <div style={{
              width: '88px',
              height: '88px',
              borderRadius: '50%',
              background: 'linear-gradient(135deg, #06b6d4 0%, #6366f1 100%)',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              fontWeight: 'bold',
              fontSize: '1.35rem',
              color: '#ffffff',
              animation: 'pulseGlow 2.5s ease-in-out infinite'
            }}>
              Kwenki
            </div>
          </div>

          <h2 style={{ marginBottom: '0.5rem', fontSize: '1.35rem', fontWeight: 'bold' }}>🔒 تطبيق خاص</h2>
          <p style={{ fontSize: '0.85rem', color: '#94a3b8', marginBottom: '1.5rem' }}>
            يرجى إدخال رمز المرور للوصول
          </p>

          <input
            type="password"
            placeholder="كلمة السر..."
            value={passwordInput}
            onChange={(e) => setPasswordInput(e.target.value)}
            style={{
              padding: '0.75rem 1rem',
              borderRadius: '12px',
              border: error ? '1.5px solid #ef4444' : '1.5px solid #334155',
              backgroundColor: '#0f172a',
              color: '#fff',
              outline: 'none',
              width: '100%',
              boxSizing: 'border-box',
              marginBottom: '1rem',
              textAlign: 'center',
              fontSize: '1rem'
            }}
          />

          {error && <p style={{ color: '#ef4444', fontSize: '0.85rem', marginBottom: '1rem' }}>كلمة السر غير صحيحة!</p>}

          <button type="submit" style={{
            width: '100%',
            padding: '0.75rem',
            borderRadius: '12px',
            border: 'none',
            background: 'linear-gradient(135deg, #6366f1 0%, #4f46e5 100%)',
            color: '#fff',
            fontWeight: 'bold',
            cursor: 'pointer',
            boxShadow: '0 4px 15px rgba(99, 102, 241, 0.4)'
          }}>
            دخول
          </button>
        </form>
      </div>
    );
  }

  return (
    <ThemeProvider>
      <AuthProvider>
        <I18nProvider>
          <WallpaperProvider>
            <DeviceFrameWrapper />
          </WallpaperProvider>
        </I18nProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}