import { useState, useEffect, useMemo, useRef } from 'react';
import { useWebSocket } from './hooks/useWebSocket';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { TitleBar } from './components/TitleBar';

const TIME_RANGES = [
  { label: '6H', value: '6h' },
  { label: '24H', value: '24h' },
  { label: '3D', value: '3d' },
  { label: '7D', value: '7d' },
  { label: '1M', value: '1mo' },
  { label: 'YTD', value: 'ytd' },
];

const COLORS = [
  '#8884d8', '#82ca9d', '#ffc658', '#ff7c7c', '#a28fd0', '#f5a623',
  '#50e3c2', '#ff6b9d', '#4a90e2', '#7ed321', '#d0021b', '#f8e71c'
];

interface ZoomState {
  xStart: number;
  xEnd: number;
  yMin: number;
  yMax: number;
}

interface PriceAlert {
  id: string;
  auecAmount: number;
  maxPrice: number;
  enabled: boolean;
}

interface AlertNotification {
  id: string;
  message: string;
  sellerName: string;
  platform: string;
  price: number;
}

export function App() {
  const { status, latestPrice, historyData, requestHistory, fetchInitialData } = useWebSocket();
  const [selectedRange, setSelectedRange] = useState('7d');
  const [zoomState, setZoomState] = useState<ZoomState | null>(null);
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const [animateChart, setAnimateChart] = useState(true);
  const [hoveredSeller, setHoveredSeller] = useState<string | null>(null);
  
  // Price Alert State
  const [alerts, setAlerts] = useState<PriceAlert[]>([]);
  const [newAlertAuec, setNewAlertAuec] = useState('');
  const [newAlertPrice, setNewAlertPrice] = useState('');
  const [alertNotification, setAlertNotification] = useState<AlertNotification | null>(null);
  const alertAudioRef = useRef<HTMLAudioElement | null>(null);

  // Custom AUEC Amount State
  const [customAuecAmount, setCustomAuecAmount] = useState<number | null>(null);
  const [customAuecInput, setCustomAuecInput] = useState('');

  // Load alerts from database on mount
  useEffect(() => {
    const loadAlerts = async () => {
      try {
        const savedAlerts = await window.electron.ipcRenderer.invoke('alerts:getAll');
        setAlerts(savedAlerts);
      } catch (error) {
        console.error('Failed to load alerts:', error);
      }
    };
    loadAlerts();
  }, []);

  // Load custom AUEC amount from database on mount
  useEffect(() => {
    const loadCustomAmount = async () => {
      try {
        const amount = await window.electron.ipcRenderer.invoke('settings:getCustomAuecAmount');
        if (amount) {
          setCustomAuecAmount(amount);
          setCustomAuecInput(amount.toString());
        }
      } catch (error) {
        console.error('Failed to load custom AUEC amount:', error);
      }
    };
    loadCustomAmount();
  }, []);

  // Fetch initial data on mount
  useEffect(() => {
    fetchInitialData();
  }, [fetchInitialData]);

  // Request historical data when range changes
  useEffect(() => {
    requestHistory(selectedRange);
  }, [selectedRange, requestHistory]);

  // Check for price alerts
  useEffect(() => {
    if (!latestPrice || alerts.length === 0) return;

    alerts.forEach(alert => {
      if (!alert.enabled) return;

      // Check if any seller meets the alert criteria
      const matchingSeller = latestPrice.allPrices.find(price => {
        const totalPrice = (alert.auecAmount / 1000000) * price.pricePerMillion;
        return totalPrice <= alert.maxPrice;
      });

      if (matchingSeller) {
        const totalPrice = (alert.auecAmount / 1000000) * matchingSeller.pricePerMillion;
        
        // Show notification
        const notification = {
          id: Date.now().toString(),
          message: `${alert.auecAmount.toLocaleString()} AUEC available for $${totalPrice.toFixed(2)}`,
          sellerName: matchingSeller.sellerName,
          platform: matchingSeller.platform,
          price: totalPrice,
        };
        
        setAlertNotification(notification);
        
        // Play alert sound
        if (alertAudioRef.current) {
          alertAudioRef.current.play().catch(e => console.error('Audio play failed:', e));
        }
        
        // OS notification
        if (window.Notification && Notification.permission === 'granted') {
          new Notification('Price Alert - rmtPocketWatcher', {
            body: `${notification.message}\nSeller: ${matchingSeller.sellerName} (${matchingSeller.platform})`,
            icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y="75" font-size="75">💰</text></svg>'
          });
        }
        
        // Disable alert after triggering
        const disabledAlert = { ...alert, enabled: false };
        window.electron.ipcRenderer.invoke('alerts:update', disabledAlert).catch(err => 
          console.error('Failed to update alert in DB:', err)
        );
        setAlerts(prev => prev.map(a => 
          a.id === alert.id ? disabledAlert : a
        ));
      }
    });
  }, [latestPrice, alerts]);

  // Request notification permission on mount
  useEffect(() => {
    if (window.Notification && Notification.permission === 'default') {
      Notification.requestPermission();
    }
  }, []);

  // Helper function to format dates elegantly
  const formatDate = (timestamp: number) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffHours = diffMs / (1000 * 60 * 60);
    const diffDays = diffMs / (1000 * 60 * 60 * 24);

    // If within last 24 hours, show time
    if (diffHours < 24) {
      return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    }
    // If within last 7 days, show day and time
    else if (diffDays < 7) {
      return date.toLocaleDateString('en-US', { weekday: 'short', hour: '2-digit', minute: '2-digit' });
    }
    // Otherwise show date
    else {
      return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    }
  };

  const fullChartData = useMemo(() => {
    if (!historyData?.prices) return [];

    // Group by timestamp and seller
    const grouped = new Map<string, any>();
    
    historyData.prices.forEach(price => {
      const time = new Date(price.timestamp).getTime();
      const key = time.toString();
      
      if (!grouped.has(key)) {
        grouped.set(key, { 
          timestamp: time, 
          time: formatDate(time),
          fullTime: new Date(price.timestamp).toLocaleString()
        });
      }
      
      const entry = grouped.get(key);
      const sellerKey = `${price.sellerName}`;
      entry[sellerKey] = price.pricePerMillion;
    });

    return Array.from(grouped.values()).sort((a, b) => a.timestamp - b.timestamp);
  }, [historyData]);

  const chartData = useMemo(() => {
    if (!fullChartData.length) return [];
    if (!zoomState) return fullChartData;

    // Find data points within the zoom range, plus one point on each side for continuity
    const filtered = fullChartData.filter(d => 
      d.timestamp >= zoomState.xStart && d.timestamp <= zoomState.xEnd
    );

    // If we have filtered data, return it
    if (filtered.length > 0) return filtered;

    // If no exact matches, find the closest points to show something
    // This prevents empty chart when zoomed between data points
    const closestBefore = fullChartData.filter(d => d.timestamp < zoomState.xStart).slice(-2);
    const closestAfter = fullChartData.filter(d => d.timestamp > zoomState.xEnd).slice(0, 2);
    
    return [...closestBefore, ...closestAfter];
  }, [fullChartData, zoomState]);

  const sellers = useMemo(() => {
    if (!historyData?.prices) return [];
    const uniqueSellers = new Set(historyData.prices.map(p => p.sellerName));
    return Array.from(uniqueSellers);
  }, [historyData]);

  const yAxisDomain = useMemo(() => {
    // Use zoom state if available
    if (zoomState) {
      return [zoomState.yMin, zoomState.yMax];
    }

    // Default calculation
    if (!historyData?.prices || historyData.prices.length === 0) {
      return [0, 1];
    }
    
    // Get all prices and sort them
    const allPrices = historyData.prices.map(p => p.pricePerMillion).sort((a, b) => a - b);
    
    // Find the 90th percentile to focus on competitive prices
    const percentile90Index = Math.floor(allPrices.length * 0.90);
    const percentile90 = allPrices[percentile90Index];
    
    // Get the minimum price
    const minPrice = allPrices[0];
    
    // Base max Y on 90th percentile with padding
    const baseMaxY = Math.max(percentile90 * 1.1, minPrice * 2);
    
    return [0, baseMaxY];
  }, [historyData, zoomState]);

  useEffect(() => {
    const chartContainer = chartContainerRef.current;
    if (!chartContainer || !fullChartData.length) return;

    const handleWheel = (e: WheelEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setAnimateChart(false);
      
      const isZoomIn = e.deltaY < 0;
      const zoomFactor = isZoomIn ? 0.8 : 1.25; // Zoom in = smaller range, zoom out = larger range
      
      // Get mouse position relative to chart
      const rect = chartContainer.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      
      // Calculate mouse X position as percentage of chart area
      const xPercent = mouseX / rect.width;
      
      // Get current ranges
      const currentXStart = zoomState?.xStart ?? fullChartData[0].timestamp;
      const currentXEnd = zoomState?.xEnd ?? fullChartData[fullChartData.length - 1].timestamp;
      const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
      
      // Calculate current X range
      const xRange = currentXEnd - currentXStart;
      
      // Calculate new X range centered on mouse position
      let newXRange = xRange * zoomFactor;
      
      // Prevent zooming in too much - ensure minimum time range
      // Calculate minimum based on data density
      const fullDataRange = fullChartData[fullChartData.length - 1].timestamp - fullChartData[0].timestamp;
      const minTimeRange = fullDataRange / 1000; // Allow up to 1000x zoom
      
      if (isZoomIn && newXRange < minTimeRange) {
        newXRange = minTimeRange;
      }
      
      // Calculate mouse position in X data coordinates
      const mouseXData = currentXStart + xRange * xPercent;
      
      // Calculate new X bounds centered on mouse position
      let newXStart = mouseXData - newXRange * xPercent;
      let newXEnd = mouseXData + newXRange * (1 - xPercent);
      
      // Constrain X to data bounds
      const dataXStart = fullChartData[0].timestamp;
      const dataXEnd = fullChartData[fullChartData.length - 1].timestamp;
      
      if (newXStart < dataXStart) {
        newXEnd += dataXStart - newXStart;
        newXStart = dataXStart;
      }
      if (newXEnd > dataXEnd) {
        newXStart -= newXEnd - dataXEnd;
        newXEnd = dataXEnd;
      }
      newXStart = Math.max(dataXStart, newXStart);
      newXEnd = Math.min(dataXEnd, newXEnd);
      
      // Y-axis: always zoom from 0, just adjust the max
      const newYMax = currentYMax * zoomFactor;
      
      setZoomState({
        xStart: newXStart,
        xEnd: newXEnd,
        yMin: 0,
        yMax: newYMax,
      });
    };

    chartContainer.addEventListener('wheel', handleWheel, { passive: false });
    
    return () => {
      chartContainer.removeEventListener('wheel', handleWheel);
    };
  }, [fullChartData, zoomState, yAxisDomain]);

  const handleRangeChange = (range: string) => {
    setAnimateChart(true);
    setSelectedRange(range);
    setZoomState(null);
  };

  const resetZoom = () => {
    setAnimateChart(false);
    setZoomState(null);
  };

  const addAlert = async () => {
    const auec = parseFloat(newAlertAuec);
    const price = parseFloat(newAlertPrice);
    
    if (isNaN(auec) || isNaN(price) || auec <= 0 || price <= 0) {
      alert('Please enter valid amounts');
      return;
    }
    
    const newAlert: PriceAlert = {
      id: Date.now().toString(),
      auecAmount: auec,
      maxPrice: price,
      enabled: true,
    };
    
    try {
      await window.electron.ipcRenderer.invoke('alerts:add', newAlert);
      setAlerts(prev => [...prev, newAlert]);
      setNewAlertAuec('');
      setNewAlertPrice('');
    } catch (error) {
      console.error('Failed to add alert:', error);
      alert('Failed to add alert');
    }
  };

  const toggleAlert = async (id: string) => {
    const alert = alerts.find(a => a.id === id);
    if (!alert) return;
    
    const updatedAlert = { ...alert, enabled: !alert.enabled };
    
    try {
      await window.electron.ipcRenderer.invoke('alerts:update', updatedAlert);
      setAlerts(prev => prev.map(a => 
        a.id === id ? updatedAlert : a
      ));
    } catch (error) {
      console.error('Failed to toggle alert:', error);
    }
  };

  const deleteAlert = async (id: string) => {
    try {
      await window.electron.ipcRenderer.invoke('alerts:delete', id);
      setAlerts(prev => prev.filter(a => a.id !== id));
    } catch (error) {
      console.error('Failed to delete alert:', error);
    }
  };

  const saveCustomAuecAmount = async () => {
    const amount = parseFloat(customAuecInput);
    if (isNaN(amount) || amount <= 0) {
      alert('Please enter a valid AUEC amount');
      return;
    }

    try {
      await window.electron.ipcRenderer.invoke('settings:setCustomAuecAmount', amount);
      setCustomAuecAmount(amount);
    } catch (error) {
      console.error('Failed to save custom AUEC amount:', error);
    }
  };

  const dismissNotification = () => {
    setAlertNotification(null);
  };

  const handleZoomIn = () => {
    if (!fullChartData.length) return;
    setAnimateChart(false);
    
    // Keep current X range, only adjust Y max
    const currentXStart = zoomState?.xStart ?? fullChartData[0].timestamp;
    const currentXEnd = zoomState?.xEnd ?? fullChartData[fullChartData.length - 1].timestamp;
    const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
    
    // Y-axis: decrease max to zoom in (show less range)
    const newYMax = currentYMax * 0.8;
    
    setZoomState({
      xStart: currentXStart,
      xEnd: currentXEnd,
      yMin: 0,
      yMax: newYMax,
    });
  };

  const handleZoomOut = () => {
    if (!fullChartData.length) return;
    setAnimateChart(false);
    
    // Keep current X range, only adjust Y max
    const currentXStart = zoomState?.xStart ?? fullChartData[0].timestamp;
    const currentXEnd = zoomState?.xEnd ?? fullChartData[fullChartData.length - 1].timestamp;
    const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
    
    // Y-axis: increase max to zoom out (show more range)
    const newYMax = currentYMax * 1.25;
    
    setZoomState({
      xStart: currentXStart,
      xEnd: currentXEnd,
      yMin: 0,
      yMax: newYMax,
    });
  };

  const handleTimelineCompress = () => {
    if (!fullChartData.length) return;
    setAnimateChart(false);
    
    const currentXStart = zoomState?.xStart ?? fullChartData[0].timestamp;
    const currentXEnd = zoomState?.xEnd ?? fullChartData[fullChartData.length - 1].timestamp;
    const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
    
    const xRange = currentXEnd - currentXStart;
    const newXRange = xRange * 0.8; // Compress = show less time
    const xCenter = (currentXStart + currentXEnd) / 2;
    
    // Constrain to data bounds
    const dataXStart = fullChartData[0].timestamp;
    const dataXEnd = fullChartData[fullChartData.length - 1].timestamp;
    
    let newXStart = xCenter - newXRange / 2;
    let newXEnd = xCenter + newXRange / 2;
    
    // Ensure we stay within data bounds
    if (newXStart < dataXStart) {
      newXEnd += dataXStart - newXStart;
      newXStart = dataXStart;
    }
    if (newXEnd > dataXEnd) {
      newXStart -= newXEnd - dataXEnd;
      newXEnd = dataXEnd;
    }
    newXStart = Math.max(dataXStart, newXStart);
    newXEnd = Math.min(dataXEnd, newXEnd);
    
    setZoomState({
      xStart: newXStart,
      xEnd: newXEnd,
      yMin: 0,
      yMax: currentYMax,
    });
  };

  const handleTimelineExpand = () => {
    if (!fullChartData.length) return;
    setAnimateChart(false);
    
    const currentXStart = zoomState?.xStart ?? fullChartData[0].timestamp;
    const currentXEnd = zoomState?.xEnd ?? fullChartData[fullChartData.length - 1].timestamp;
    const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
    
    const xRange = currentXEnd - currentXStart;
    const newXRange = xRange * 1.25; // Expand = show more time
    const xCenter = (currentXStart + currentXEnd) / 2;
    
    // Constrain to data bounds
    const dataXStart = fullChartData[0].timestamp;
    const dataXEnd = fullChartData[fullChartData.length - 1].timestamp;
    
    const newXStart = Math.max(dataXStart, xCenter - newXRange / 2);
    const newXEnd = Math.min(dataXEnd, xCenter + newXRange / 2);
    
    setZoomState({
      xStart: newXStart,
      xEnd: newXEnd,
      yMin: 0,
      yMax: currentYMax,
    });
  };

  const getZoomLevel = () => {
    if (!zoomState || !fullChartData.length) return 1;
    
    const fullXRange = fullChartData[fullChartData.length - 1].timestamp - fullChartData[0].timestamp;
    const currentXRange = zoomState.xEnd - zoomState.xStart;
    
    return fullXRange / currentXRange;
  };

  // Timeline slider position (0-100)
  const sliderPosition = useMemo(() => {
    if (!fullChartData.length) return 50;
    
    const dataXStart = fullChartData[0].timestamp;
    const dataXEnd = fullChartData[fullChartData.length - 1].timestamp;
    const fullRange = dataXEnd - dataXStart;
    
    if (!zoomState || fullRange === 0) return 50;
    
    const viewCenter = (zoomState.xStart + zoomState.xEnd) / 2;
    const position = ((viewCenter - dataXStart) / fullRange) * 100;
    
    return Math.max(0, Math.min(100, position));
  }, [fullChartData, zoomState]);

  const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!fullChartData.length) return;
    setAnimateChart(false);
    
    const position = parseFloat(e.target.value);
    const dataXStart = fullChartData[0].timestamp;
    const dataXEnd = fullChartData[fullChartData.length - 1].timestamp;
    const fullRange = dataXEnd - dataXStart;
    
    // Calculate new center based on slider position
    const newCenter = dataXStart + (position / 100) * fullRange;
    
    // Keep current view width or use full range if no zoom
    const currentXStart = zoomState?.xStart ?? dataXStart;
    const currentXEnd = zoomState?.xEnd ?? dataXEnd;
    const currentYMax = zoomState?.yMax ?? yAxisDomain[1];
    const viewWidth = currentXEnd - currentXStart;
    
    // Calculate new bounds centered on slider position
    let newXStart = newCenter - viewWidth / 2;
    let newXEnd = newCenter + viewWidth / 2;
    
    // Constrain to data bounds
    if (newXStart < dataXStart) {
      newXEnd += dataXStart - newXStart;
      newXStart = dataXStart;
    }
    if (newXEnd > dataXEnd) {
      newXStart -= newXEnd - dataXEnd;
      newXEnd = dataXEnd;
    }
    newXStart = Math.max(dataXStart, newXStart);
    newXEnd = Math.min(dataXEnd, newXEnd);
    
    setZoomState({
      xStart: newXStart,
      xEnd: newXEnd,
      yMin: 0,
      yMax: currentYMax,
    });
  };

  return (
    <div style={{ 
      fontFamily: 'system-ui', 
      backgroundColor: '#0a0e27', 
      color: '#fff', 
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column',
    }}>
      <TitleBar />
      
      <div style={{ padding: '20px', flex: 1 }}>
      
      <div style={{ display: 'flex', gap: '20px', marginBottom: '20px' }}>
        <div style={{ flex: 1, backgroundColor: '#1a1f3a', padding: '15px', borderRadius: '8px' }}>
          <div style={{ fontSize: '12px', color: '#888', marginBottom: '5px' }}>CONNECTION</div>
          <div style={{ fontSize: '18px', fontWeight: 'bold', color: status.connected ? '#50e3c2' : '#ff6b9d' }}>
            {status.state}
          </div>
        </div>
        
        {latestPrice && (
          <>
            <div style={{ flex: 1, backgroundColor: '#1a1f3a', padding: '15px', borderRadius: '8px' }}>
              <div style={{ fontSize: '12px', color: '#888', marginBottom: '5px' }}>LOWEST PRICE</div>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#50e3c2' }}>
                ${latestPrice.lowestPrice.toFixed(9)}
              </div>
              <div style={{ fontSize: '12px', color: '#888' }}>per 1M AUEC</div>
            </div>
            
            <div style={{ flex: 1, backgroundColor: '#1a1f3a', padding: '15px', borderRadius: '8px' }}>
              <div style={{ fontSize: '12px', color: '#888', marginBottom: '5px' }}>SELLER</div>
              <div style={{ fontSize: '18px', fontWeight: 'bold' }}>{latestPrice.sellerName}</div>
              <div style={{ fontSize: '12px', color: '#888' }}>{latestPrice.platform}</div>
            </div>
          </>
        )}
      </div>

      <div style={{ backgroundColor: '#1a1f3a', padding: '20px', borderRadius: '8px', marginBottom: '20px' }}>
        <h2 style={{ margin: '0 0 15px 0' }}>Price Alerts</h2>
        
        <div style={{ display: 'flex', gap: '10px', marginBottom: '15px', flexWrap: 'wrap' }}>
          <input
            type="number"
            placeholder="AUEC Amount"
            value={newAlertAuec}
            onChange={(e) => setNewAlertAuec(e.target.value)}
            style={{
              padding: '10px',
              backgroundColor: '#2a2f4a',
              color: '#fff',
              border: '1px solid #50e3c2',
              borderRadius: '4px',
              fontSize: '14px',
              flex: '1',
              minWidth: '150px',
            }}
          />
          <input
            type="number"
            placeholder="Max USD Price"
            value={newAlertPrice}
            onChange={(e) => setNewAlertPrice(e.target.value)}
            style={{
              padding: '10px',
              backgroundColor: '#2a2f4a',
              color: '#fff',
              border: '1px solid #50e3c2',
              borderRadius: '4px',
              fontSize: '14px',
              flex: '1',
              minWidth: '150px',
            }}
          />
          <button
            onClick={addAlert}
            style={{
              padding: '10px 20px',
              backgroundColor: '#50e3c2',
              color: '#0a0e27',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontWeight: 'bold',
              fontSize: '14px',
            }}
          >
            Add Alert
          </button>
        </div>

        {alerts.length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
            {alerts.map(alert => (
              <div
                key={alert.id}
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  padding: '12px',
                  backgroundColor: '#2a2f4a',
                  borderRadius: '4px',
                  border: `2px solid ${alert.enabled ? '#50e3c2' : '#888'}`,
                }}
              >
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: '16px', fontWeight: 'bold' }}>
                    {alert.auecAmount.toLocaleString()} AUEC for ${alert.maxPrice.toFixed(2)}
                  </div>
                  <div style={{ fontSize: '12px', color: '#888' }}>
                    ${(alert.maxPrice / (alert.auecAmount / 1000000)).toFixed(9)} per 1M AUEC
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '8px' }}>
                  <button
                    onClick={() => toggleAlert(alert.id)}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: alert.enabled ? '#50e3c2' : '#888',
                      color: '#0a0e27',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '12px',
                      fontWeight: 'bold',
                    }}
                  >
                    {alert.enabled ? 'Enabled' : 'Disabled'}
                  </button>
                  <button
                    onClick={() => deleteAlert(alert.id)}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#ff6b9d',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '12px',
                      fontWeight: 'bold',
                    }}
                  >
                    Delete
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: '20px', color: '#888' }}>
            No alerts set. Add an alert to get notified when prices meet your criteria.
          </div>
        )}
      </div>

      <div style={{ backgroundColor: '#1a1f3a', padding: '20px', borderRadius: '8px', marginBottom: '20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
          <h2 style={{ margin: 0 }}>Price History</h2>
          <div style={{ display: 'flex', gap: '8px' }}>
            {TIME_RANGES.map(range => (
              <button
                key={range.value}
                onClick={() => handleRangeChange(range.value)}
                style={{
                  padding: '6px 14px',
                  backgroundColor: selectedRange === range.value ? '#50e3c2' : '#2a2f4a',
                  color: selectedRange === range.value ? '#0a0e27' : '#fff',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontWeight: selectedRange === range.value ? 'bold' : 'normal',
                  fontSize: '13px',
                  transition: 'all 0.2s',
                }}
              >
                {range.label}
              </button>
            ))}
          </div>
        </div>

        {historyData && historyData.prices && historyData.prices.length > 0 ? (
          chartData.length > 0 ? (
            <div>
              <div style={{ 
                marginBottom: '12px', 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                gap: '15px',
                flexWrap: 'wrap'
              }}>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <button 
                    onClick={handleZoomOut}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#2a2f4a',
                      color: '#fff',
                      border: '1px solid #50e3c2',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 'bold',
                    }}
                    title="Zoom Out"
                  >
                    −
                  </button>
                  <button 
                    onClick={handleZoomIn}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#2a2f4a',
                      color: '#fff',
                      border: '1px solid #50e3c2',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 'bold',
                    }}
                    title="Zoom In"
                  >
                    +
                  </button>
                  <button 
                    onClick={resetZoom}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#2a2f4a',
                      color: '#fff',
                      border: '1px solid #50e3c2',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '12px',
                    }}
                  >
                    Reset (×{getZoomLevel().toFixed(1)})
                  </button>
                  <button 
                    onClick={handleTimelineExpand}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#2a2f4a',
                      color: '#fff',
                      border: '1px solid #50e3c2',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 'bold',
                    }}
                    title="Expand Timeline"
                  >
                    &lt;
                  </button>
                  <button 
                    onClick={handleTimelineCompress}
                    style={{
                      padding: '6px 12px',
                      backgroundColor: '#2a2f4a',
                      color: '#fff',
                      border: '1px solid #50e3c2',
                      borderRadius: '4px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      fontWeight: 'bold',
                    }}
                    title="Compress Timeline"
                  >
                    &gt;
                  </button>
                </div>

                <div style={{ color: '#888', fontSize: '11px', fontStyle: 'italic' }}>
                  Scroll on chart to zoom into area • Outliers may be clipped
                </div>
              </div>

              <div 
                ref={chartContainerRef}
                style={{ 
                  width: '100%', 
                  height: '500px', 
                  minHeight: '400px',
                  cursor: 'ns-resize',
                  border: '1px solid #2a2f4a',
                  borderRadius: '4px',
                  backgroundColor: '#0f1329',
                }}
              >
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={chartData} margin={{ top: 10, right: 30, left: 10, bottom: 60 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#2a2f4a" />
                    <XAxis 
                      dataKey="time" 
                      stroke="#888"
                      tick={{ fill: '#888', fontSize: 10 }}
                      angle={-45}
                      textAnchor="end"
                      height={80}
                    />
                    <YAxis 
                      stroke="#888"
                      tick={{ fill: '#888', fontSize: 12 }}
                      label={{ value: 'USD per 1M AUEC', angle: -90, position: 'insideLeft', fill: '#888' }}
                      domain={yAxisDomain}
                      allowDataOverflow={true}
                    />
                    <Tooltip
                      content={({ active, payload }) => {
                        if (!active || !payload || payload.length === 0) return null;
                        const data = payload[0]?.payload;
                        if (!data) return null;
                        const seenNames = new Set<string>();
                        const validSellers = payload
                          .filter((p: any) => {
                            if (p.value === undefined || p.value === null || isNaN(p.value)) return false;
                            if (!p.name || String(p.name).trim() === '') return false;
                            if (p.stroke === 'transparent') return false;
                            // Deduplicate by name
                            if (seenNames.has(p.name)) return false;
                            seenNames.add(p.name);
                            return true;
                          })
                          .sort((a: any, b: any) => a.value - b.value);
                        if (validSellers.length === 0) return null;
                        
                        // If hovering over a specific line, show that seller and others with same price
                        let displaySellers = validSellers;
                        if (hoveredSeller) {
                          const hoveredData = validSellers.find((s: any) => s.name === hoveredSeller);
                          if (hoveredData) {
                            const hoveredPrice = hoveredData.value;
                            // Show hovered seller and any with same price (within 0.0001 tolerance)
                            displaySellers = validSellers.filter((s: any) => 
                              s.name === hoveredSeller || Math.abs(s.value - hoveredPrice) < 0.0001
                            );
                          }
                        }
                        
                        return (
                          <div style={{ backgroundColor: "#1a1f3a", border: "1px solid #50e3c2", borderRadius: "6px", padding: "12px", maxHeight: "300px", overflowY: "auto", minWidth: "200px" }}>
                            <div style={{ color: "#fff", fontWeight: "bold", marginBottom: "8px", borderBottom: "1px solid #2a2f4a", paddingBottom: "6px" }}>
                              {data.fullTime || data.time}
                            </div>
                            {!hoveredSeller && (
                              <div style={{ fontSize: "11px", color: "#888", marginBottom: "6px" }}>
                                {validSellers.length} seller{validSellers.length !== 1 ? "s" : ""} - Sorted by price
                              </div>
                            )}
                            {displaySellers.slice(0, hoveredSeller ? 20 : 10).map((seller: any, idx: number) => (
                              <div key={`${seller.name}-${idx}`} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "4px 0", borderBottom: idx < displaySellers.length - 1 ? "1px solid #2a2f4a" : "none" }}>
                                <span style={{ color: seller.color, fontSize: "12px", fontWeight: seller.name === hoveredSeller ? "bold" : "normal" }}>{seller.name}</span>
                                <span style={{ color: "#50e3c2", fontWeight: "bold", fontSize: "12px", marginLeft: "10px" }}>${Number(seller.value).toFixed(4)}</span>
                              </div>
                            ))}
                            {!hoveredSeller && validSellers.length > 10 && (
                              <div style={{ color: "#888", fontSize: "11px", marginTop: "6px", textAlign: "center" }}>+{validSellers.length - 10} more sellers</div>
                            )}
                          </div>
                        );
                      }}
                      wrapperStyle={{ zIndex: 1000 }}
                    />
                    <Legend 
                      wrapperStyle={{ 
                        color: '#fff', 
                        maxHeight: '100px', 
                        overflowY: 'auto', 
                        zIndex: 1,
                        paddingRight: '5px'
                      }}
                      iconType="line"
                    />
                    {/* Invisible wider lines for better hover detection */}
                    {sellers.map((seller) => (
                      <Line
                        key={`${seller}-hitarea`}
                        type="linear"
                        dataKey={seller}
                        stroke="transparent"
                        strokeWidth={15}
                        dot={false}
                        connectNulls
                        isAnimationActive={false}
                        onMouseEnter={() => setHoveredSeller(seller)}
                        onMouseLeave={() => setHoveredSeller(null)}
                        style={{ cursor: 'pointer' }}
                        legendType="none"
                      />
                    ))}
                    {/* Visible lines */}
                    {sellers.map((seller) => (
                      <Line
                        key={seller}
                        type="linear"
                        dataKey={seller}
                        stroke={COLORS[sellers.indexOf(seller) % COLORS.length]}
                        strokeWidth={hoveredSeller === seller ? 4 : 2}
                        dot={false}
                        activeDot={{ r: 6 }}
                        connectNulls
                        isAnimationActive={animateChart}
                        style={{ pointerEvents: 'none' }}
                        legendType="line"
                      />
                    ))}
                  </LineChart>
                </ResponsiveContainer>
              </div>

              {/* Timeline Slider */}
              <div style={{ 
                marginTop: '15px', 
                padding: '10px 15px',
                backgroundColor: '#0f1329',
                borderRadius: '4px',
                border: '1px solid #2a2f4a',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
                  <span style={{ color: '#888', fontSize: '12px', minWidth: '60px' }}>
                    {fullChartData.length > 0 ? new Date(fullChartData[0].timestamp).toLocaleDateString() : ''}
                  </span>
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={sliderPosition}
                    onChange={handleSliderChange}
                    style={{
                      flex: 1,
                      height: '8px',
                      cursor: 'pointer',
                      accentColor: '#50e3c2',
                    }}
                  />
                  <span style={{ color: '#888', fontSize: '12px', minWidth: '60px', textAlign: 'right' }}>
                    {fullChartData.length > 0 ? new Date(fullChartData[fullChartData.length - 1].timestamp).toLocaleDateString() : ''}
                  </span>
                </div>
              </div>
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '40px', color: '#ff6b9d' }}>
              Data received but chart data is empty. Check console for details.
            </div>
          )
        ) : (
          <div style={{ textAlign: 'center', padding: '40px', color: '#888' }}>
            {status.connected ? 'Loading historical data...' : 'Connect to view historical data'}
          </div>
        )}
      </div>

      {latestPrice && (
        <div style={{ backgroundColor: '#1a1f3a', padding: '20px', borderRadius: '8px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}>
            <h2 style={{ margin: 0 }}>Current Listings ({latestPrice.allPrices.length})</h2>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
              <input
                type="number"
                placeholder="Enter AUEC amount"
                value={customAuecInput}
                onChange={(e) => setCustomAuecInput(e.target.value)}
                style={{
                  padding: '8px 12px',
                  backgroundColor: '#0a0e27',
                  border: '1px solid #2a2f4a',
                  borderRadius: '4px',
                  color: '#fff',
                  fontSize: '14px',
                  width: '180px',
                }}
              />
              <button
                onClick={saveCustomAuecAmount}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#50e3c2',
                  color: '#0a0e27',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontWeight: 'bold',
                  fontSize: '14px',
                }}
              >
                Set Amount
              </button>
            </div>
          </div>
          <div style={{ 
            overflowX: 'auto', 
            overflowY: 'auto', 
            maxHeight: '400px',
            border: '1px solid #2a2f4a',
            borderRadius: '4px',
          }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1f3a', zIndex: 1 }}>
                <tr style={{ borderBottom: '2px solid #2a2f4a' }}>
                  <th style={{ textAlign: 'left', padding: '12px', color: '#888', fontWeight: 'normal' }}>Platform</th>
                  <th style={{ textAlign: 'left', padding: '12px', color: '#888', fontWeight: 'normal' }}>Seller</th>
                  <th style={{ textAlign: 'right', padding: '12px', color: '#888', fontWeight: 'normal' }}>Price/1M AUEC</th>
                  {customAuecAmount && (
                    <th style={{ textAlign: 'right', padding: '12px', color: '#888', fontWeight: 'normal' }}>
                      Price for {customAuecAmount.toLocaleString()} AUEC
                    </th>
                  )}
                </tr>
              </thead>
              <tbody>
                {[...latestPrice.allPrices]
                  .sort((a, b) => a.pricePerMillion - b.pricePerMillion)
                  .map((price) => (
                    <tr key={price.id} style={{ borderBottom: '1px solid #2a2f4a' }}>
                      <td style={{ padding: '12px' }}>{price.platform}</td>
                      <td style={{ padding: '12px' }}>{price.sellerName}</td>
                      <td style={{ textAlign: 'right', padding: '12px', color: '#50e3c2', fontWeight: 'bold' }}>
                        ${price.pricePerMillion.toFixed(9)}
                      </td>
                      {customAuecAmount && (
                        <td style={{ textAlign: 'right', padding: '12px', color: '#50e3c2', fontWeight: 'bold' }}>
                          ${((price.pricePerMillion * customAuecAmount) / 1000000).toFixed(2)}
                        </td>
                      )}
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
      </div>

      {/* Alert Notification Popup */}
      {alertNotification && (
        <div style={{
          position: 'fixed',
          top: '80px',
          right: '20px',
          backgroundColor: '#1a1f3a',
          border: '2px solid #50e3c2',
          borderRadius: '8px',
          padding: '20px',
          maxWidth: '400px',
          boxShadow: '0 4px 20px rgba(80, 227, 194, 0.4)',
          zIndex: 9999,
          animation: 'slideIn 0.3s ease-out',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
            <h3 style={{ margin: 0, color: '#50e3c2', fontSize: '18px' }}>🎯 Price Alert!</h3>
            <button
              onClick={dismissNotification}
              style={{
                background: 'none',
                border: 'none',
                color: '#888',
                fontSize: '20px',
                cursor: 'pointer',
                padding: '0',
                lineHeight: '1',
              }}
            >
              ×
            </button>
          </div>
          <div style={{ fontSize: '16px', marginBottom: '8px', fontWeight: 'bold' }}>
            {alertNotification.message}
          </div>
          <div style={{ fontSize: '14px', color: '#888' }}>
            Seller: <span style={{ color: '#fff' }}>{alertNotification.sellerName}</span>
          </div>
          <div style={{ fontSize: '14px', color: '#888' }}>
            Platform: <span style={{ color: '#fff' }}>{alertNotification.platform}</span>
          </div>
        </div>
      )}

      {/* Alert Audio */}
      <audio ref={alertAudioRef} src="./notifcation.mp3" />
    </div>
  );
}
