// Real Internet Speed Test Implementation
const { useState, useEffect, useRef } = React;

const InternetSpeedTest = () => {
  const [testState, setTestState] = useState('idle');
  const [downloadSpeed, setDownloadSpeed] = useState(0);
  const [uploadSpeed, setUploadSpeed] = useState(0);
  const [ping, setPing] = useState(0);
  const [isp, setIsp] = useState('');
  const [location, setLocation] = useState('');
  const [showDetails, setShowDetails] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState([]);
  
  const needleRef = useRef(null);
  const canvasRef = useRef(null);
  
  // Constants for test
  const TEST_SERVER = 'https://www.beanormal.com/speed-test'; 
  const PING_TEST_COUNT = 5;
  const DOWNLOAD_SIZE = 96746791; // Gerçek dosya boyutu (96.7 MB)
  const UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB test upload
  
  // Fetch IP information on load
  useEffect(() => {
    const getNetworkInfo = async () => {
      try {
        const response = await fetch('https://ipapi.co/json/');
        const data = await response.json();
        setIsp(data.org?.split(' ')[0] || '');
        setLocation(`${data.city || ''}, ${data.region_code || ''}`);
      } catch (err) {
        console.error("Failed to get network info", err);
      }
    };
    
    getNetworkInfo();
    initCanvas();
  }, []);
  
  // Update needle position when download speed changes
  useEffect(() => {
    animateNeedle(downloadSpeed);
  }, [downloadSpeed]);
  
  // Draw the speed graph when download progress updates
  useEffect(() => {
    if (downloadProgress.length > 0) {
      drawSpeedGraph();
    }
  }, [downloadProgress]);
  
  // Initialize canvas
  const initCanvas = () => {
    if (!canvasRef.current) return;
    
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    canvas.width = canvas.offsetWidth * window.devicePixelRatio;
    canvas.height = canvas.offsetHeight * window.devicePixelRatio;
    
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  };
  
  // Draw speed graph with real data
  const drawSpeedGraph = () => {
    if (!canvasRef.current || !downloadProgress.length) return;
    
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    const width = canvas.offsetWidth;
    const height = canvas.offsetHeight;
    const maxSpeed = Math.max(...downloadProgress.map(p => p.speed)) * 1.2;
    
    // Draw the graph path
    ctx.beginPath();
    ctx.moveTo(0, height);
    
    downloadProgress.forEach((point, index) => {
      const x = (index / (downloadProgress.length - 1)) * width;
      const y = height - (point.speed / maxSpeed) * height;
      ctx.lineTo(x, y);
    });
    
    // Complete the path
    ctx.lineTo(width, height);
    ctx.lineTo(0, height);
    
    // Fill with gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, 'rgba(138, 143, 255, 0.7)');
    gradient.addColorStop(1, 'rgba(138, 143, 255, 0)');
    ctx.fillStyle = gradient;
    ctx.fill();
    
    // Draw the line
    ctx.beginPath();
    ctx.moveTo(0, height);
    
    downloadProgress.forEach((point, index) => {
      const x = (index / (downloadProgress.length - 1)) * width;
      const y = height - (point.speed / maxSpeed) * height;
      ctx.lineTo(x, y);
    });
    
    ctx.strokeStyle = '#22d3ee';
    ctx.lineWidth = 2;
    ctx.stroke();
  };
  
  // Animate needle movement
  const animateNeedle = (speed) => {
    if (!needleRef.current) return;
    
    // Calculate angle based on speed tiers
    let degrees;
    
    if (speed <= 50) {
      // 0-50 Mbps -> 0-90 degrees
      degrees = (speed / 50) * 90;
    } else if (speed <= 150) {
      // 50-150 Mbps -> 90-135 degrees
      degrees = 90 + ((speed - 50) / 100) * 45;
    } else {
      // 150-250+ Mbps -> 135-180 degrees (capped at 180)
      degrees = 135 + Math.min(((speed - 150) / 100) * 45, 45);
    }
    
    // Apply smooth animation
    const currentRotation = needleRef.current.style.transform
      ? parseFloat(needleRef.current.style.transform.replace('rotate(', '').replace('deg)', '')) || 0
      : 0;
    
    const duration = 300;
    const startTime = performance.now();
    
    const animate = (time) => {
      const elapsed = time - startTime;
      const progress = Math.min(elapsed / duration, 1);
      
      // Ease out cubic for natural movement
      const easing = 1 - Math.pow(1 - progress, 3);
      const currentDegrees = currentRotation + (degrees - currentRotation) * easing;
      
      needleRef.current.style.transform = `rotate(${currentDegrees}deg)`;
      
      if (progress < 1) {
        requestAnimationFrame(animate);
      }
    };
    
    requestAnimationFrame(animate);
  };
  
  // Test ping by sending multiple small requests
  const testPing = async () => {
    const pingUrl = `${TEST_SERVER}/ping-test.php`;
    const pings = [];
    
    for (let i = 0; i < PING_TEST_COUNT; i++) {
      const start = performance.now();
      
      try {
        await fetch(pingUrl, { 
          method: 'GET',
          cache: 'no-store',
          headers: { 'Cache-Control': 'no-cache' }
        });
        
        const end = performance.now();
        pings.push(end - start);
      } catch (err) {
        console.error("Ping test failed", err);
      }
    }
    
    // Calculate average ping
    const avgPing = pings.length ? Math.round(pings.reduce((a, b) => a + b, 0) / pings.length) : 0;
    setPing(avgPing);
    return avgPing;
  };
  
  // Test download speed
  const testDownload = async () => {
  const downloadUrl = `${TEST_SERVER}/download-test.php?size=${DOWNLOAD_SIZE}&cacheBust=${Date.now()}`;
      
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest();
        let startTime;
        let prevLoaded = 0;
        let prevTime = 0;
        const progressUpdates = [];
        
        xhr.open('GET', downloadUrl, true);
        xhr.responseType = 'arraybuffer';
        
        xhr.onloadstart = () => {
          startTime = performance.now();
          prevTime = startTime;
        };
        
        xhr.onprogress = (event) => {
    if (event.lengthComputable) {
      const currentTime = performance.now();
      const loadDiff = event.loaded - prevLoaded;
      const timeDiff = currentTime - prevTime;
      
      if (timeDiff > 0 && loadDiff > 0) {
        // Calculate current speed in Mbps
        const currentSpeed = (loadDiff * 8) / (timeDiff / 1000) / 1000000;
        
        progressUpdates.push({
          time: currentTime - startTime,
          loaded: event.loaded,
          total: event.total,
          speed: currentSpeed
        });
        
        // Son 5 değerin ortalamasını almak için (yumuşak artış)
        const last5 = progressUpdates.slice(-5);
        const avgSpeed = last5.reduce((sum, item) => sum + item.speed, 0) / last5.length;
        
        setDownloadProgress([...progressUpdates]);
        setDownloadSpeed(avgSpeed); // Ortalama hızı göster (daha yumuşak artış)
        
        prevLoaded = event.loaded;
        prevTime = currentTime;
      }
    }
  };
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          const endTime = performance.now();
          const duration = (endTime - startTime) / 1000; // seconds
          const size = xhr.response.byteLength * 8; // bits
          
          // Calculate final speed in Mbps
          const finalSpeed = size / duration / 1000000;
          
          resolve(finalSpeed);
        } else {
          console.error("Download test failed with status", xhr.status);
          resolve(0);
        }
      };
      
      xhr.onerror = () => {
        console.error("XHR download error");
        resolve(0);
      };
      
      xhr.send();
    });
  };
  
  // Test upload speed
  const testUpload = async () => {
    const uploadUrl = `${TEST_SERVER}/upload-test.php?cacheBust=${Date.now()}`;
    
    // Create data to upload (random binary data)
    const data = new ArrayBuffer(UPLOAD_SIZE);
    const view = new Uint8Array(data);
    for (let i = 0; i < UPLOAD_SIZE; i++) {
      view[i] = Math.floor(Math.random() * 256);
    }
    
    return new Promise((resolve) => {
      const xhr = new XMLHttpRequest();
      const startTime = performance.now();
      
      xhr.open('POST', uploadUrl, true);
      xhr.setRequestHeader('Content-Type', 'application/octet-stream');
      
      xhr.onload = () => {
        if (xhr.status === 200) {
          const endTime = performance.now();
          const duration = (endTime - startTime) / 1000; // seconds
          const size = UPLOAD_SIZE * 8; // bits
          
          // Calculate upload speed in Mbps
          const speed = size / duration / 1000000;
          resolve(speed);
        } else {
          console.error("Upload test failed with status", xhr.status);
          resolve(0);
        }
      };
      
      xhr.onerror = () => {
        console.error("XHR upload error");
        resolve(0);
      };
      
      xhr.send(data);
    });
  };
  
  // Start the complete speed test
  const startTest = async () => {
    if (testState === 'running') return;
    
    setTestState('running');
    setDownloadSpeed(0);
    setUploadSpeed(0);
    setPing(0);
    setDownloadProgress([]);
    
    try {
      // 1. Test ping
      await testPing();
      
      // 2. Test download speed
      const dlSpeed = await testDownload();
      setDownloadSpeed(dlSpeed);
      
      // 3. Test upload speed
      const ulSpeed = await testUpload();
      setUploadSpeed(ulSpeed);
      
      setTestState('completed');
    } catch (err) {
      console.error("Speed test failed", err);
      setTestState('error');
    }
  };
  
  return (
    <div style={{ 
      background: 'linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 50%, #ddd6fe 100%)',
      minHeight: '100vh',
      padding: '20px'
    }}>
      <div style={{ maxWidth: '800px', margin: '0 auto', textAlign: 'center' }}>
        <h1 style={{ 
          fontSize: '2rem', 
          fontWeight: 'bold', 
          marginBottom: '0.5rem',
          color: '#4f46e5'
        }}>Internet Speed Test</h1>
        <p style={{ 
          color: 'rgba(79, 70, 229, 0.8)',
          marginBottom: '2rem'
        }}>
          Test your connection speed to optimize your online experience
        </p>
        
        <div style={{ 
          backgroundColor: 'white',
          borderRadius: '1rem',
          boxShadow: '0 10px 25px rgba(99, 102, 241, 0.1)',
          padding: '2rem',
          marginBottom: '2rem'
        }}>
          {/* Top metrics row */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: '2rem',
            marginBottom: '2rem'
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ color: 'rgba(79, 70, 229, 0.6)', fontSize: '0.875rem', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Ping</div>
              <div style={{ color: '#fb923c', fontSize: '1.875rem', fontWeight: 'bold', marginTop: '0.25rem' }}>{ping} <span style={{ fontSize: '1rem' }}>ms</span></div>
            </div>
            
            <div style={{ textAlign: 'center' }}>
              <div style={{ color: 'rgba(79, 70, 229, 0.6)', fontSize: '0.875rem', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Download</div>
              <div style={{ color: '#4f46e5', fontSize: '1.875rem', fontWeight: 'bold', marginTop: '0.25rem' }}>{downloadSpeed.toFixed(2)} <span style={{ fontSize: '1rem' }}>Mbps</span></div>
            </div>
            
            <div style={{ textAlign: 'center' }}>
              <div style={{ color: 'rgba(79, 70, 229, 0.6)', fontSize: '0.875rem', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Upload</div>
              <div style={{ color: '#8b5cf6', fontSize: '1.875rem', fontWeight: 'bold', marginTop: '0.25rem' }}>{uploadSpeed.toFixed(2)} <span style={{ fontSize: '1rem' }}>Mbps</span></div>
            </div>
          </div>
          
          {/* Speed chart */}
          <div style={{ 
            height: '7rem',
            marginBottom: '2rem'
          }}>
            <canvas 
              ref={canvasRef} 
              style={{ width: '100%', height: '100%' }}
            ></canvas>
          </div>
          
          {/* Custom speedometer */}
          <div style={{ 
            display: 'flex', 
            justifyContent: 'center',
            marginBottom: '2rem', 
            position: 'relative' 
          }}>
            <div style={{ position: 'relative', width: '400px', height: '200px' }}>
              {/* Speedometer gauge background */}
              <img 
                src="https://beanormal.com/assets/img/speed-test/gosterge.png" 
                alt="Speedometer" 
                style={{ width: '100%' }}
              />
              
              {/* Needle - positioned absolute and rotated around center bottom point */}
              <div style={{
                position: 'absolute',
                left: '50%',
                bottom: '0',
                transformOrigin: 'bottom',
                transform: 'rotate(0deg)',
              }} ref={needleRef}>
                <img 
                  src="https://beanormal.com/assets/img/speed-test/ibre.png" 
                  alt="Needle" 
                  style={{ height: '160px', marginLeft: '-5px' }}
                />
              </div>
              
              {/* Speed value */}
              <div style={{
                position: 'absolute',
                bottom: '1rem',
                left: '0',
                right: '0',
                textAlign: 'center'
              }}>
                <div style={{ fontSize: '3rem', fontWeight: 'bold' }}>{downloadSpeed.toFixed(2)}</div>
                <div style={{ color: '#4f46e5', fontSize: '0.875rem' }}>Mbps</div>
              </div>
            </div>
          </div>
          
          {/* Start button */}
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '1.5rem' }}>
            <button
              onClick={startTest}
              disabled={testState === 'running'}
              style={{
                padding: '0.75rem 3rem',
                borderRadius: '9999px', 
                fontSize: '1.125rem',
                fontWeight: 'bold',
                transition: 'all 0.3s ease',
                background: testState === 'running' 
                  ? '#9ca3af' 
                  : 'linear-gradient(to right, #4f46e5, #8b5cf6)',
                color: 'white',
                border: 'none',
                cursor: testState === 'running' ? 'not-allowed' : 'pointer',
                boxShadow: testState === 'running' 
                  ? 'none'
                  : '0 4px 14px rgba(99, 102, 241, 0.4)'
              }}
            >
              {testState === 'running' ? (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" style={{ 
                    animation: 'spin 1s linear infinite',
                    marginRight: '0.75rem',
                    height: '1.25rem',
                    width: '1.25rem'
                  }}>
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Testing...
                </div>
              ) : 'Start Test'}
            </button>
          </div>
          
          {/* Provider info */}
          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center', 
            marginTop: '1.5rem', 
            paddingTop: '1.5rem', 
            borderTop: '1px solid #e5e7eb'
          }}>
            <div>
              <div style={{ fontSize: '0.75rem', color: 'rgba(79, 70, 229, 0.6)', marginBottom: '0.25rem' }}>SERVICE PROVIDER</div>
              <div style={{ fontWeight: '600', display: 'flex', alignItems: 'center' }}>
                {isp || 'Detecting...'}
              </div>
            </div>
            
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: '0.75rem', color: 'rgba(79, 70, 229, 0.6)', marginBottom: '0.25rem' }}>LOCATION</div>
              <div style={{ fontWeight: '600' }}>{location || 'Detecting...'}</div>
            </div>
          </div>
        </div>
        
        {/* Details section toggle */}
        <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
          <button 
            onClick={() => setShowDetails(!showDetails)}
            style={{ 
              color: '#4f46e5', 
              fontWeight: '500',
              background: 'none',
              border: 'none',
              cursor: 'pointer'
            }}
          >
            {showDetails ? 'Hide Details' : 'Show More Details'}
          </button>
        </div>
        
        {/* Details section */}
        {showDetails && (
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.75rem',
            padding: '1.5rem',
            marginBottom: '2rem'
          }}>
            <h2 style={{ fontSize: '1.25rem', fontWeight: '600', marginBottom: '1rem', textAlign: 'left' }}>Test Details</h2>
            
            <div style={{ textAlign: 'left' }}>
              <p style={{ marginBottom: '0.75rem' }}>
                <strong>Test Method:</strong> XMLHttpRequest with real file transfer
              </p>
              <p style={{ marginBottom: '0.75rem' }}>
                <strong>Test Server:</strong> {TEST_SERVER.replace(/^https?:\/\//, '')}
              </p>
              <p style={{ marginBottom: '0.75rem' }}>
                <strong>Download Test Size:</strong> {DOWNLOAD_SIZE / (1024 * 1024)} MB
              </p>
              <p>
                <strong>Upload Test Size:</strong> {UPLOAD_SIZE / (1024 * 1024)} MB
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Global access
window.InternetSpeedTest = InternetSpeedTest;