import { useState, useEffect } from 'react';
import { ComposedChart, Area, Line, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine } from 'recharts';
import { Helmet } from 'react-helmet-async';
import { type Language, t } from '../translations';
import KpiCards from './KpiCards';
import { WeatherWidget } from './WeatherWidget';
import { WindChart } from './WindChart';
import { NAVIGATION_LIMITS } from '../utils/navigationLimits';
import { lakesConfig } from '../../scripts/lakesConfig';
import { FiAlertCircle, FiStar } from 'react-icons/fi';
import { TbSwimming, TbSailboat } from 'react-icons/tb';
import { useFavorites } from '../hooks/useFavorites';
import { Tooltip as IconTooltip } from './Tooltip';

interface LipnoData {
  timestamp: string;
  date: string;
  level: number;
  inflow: number;
  outflow: number;
  volume: number;
  fullness: number;
  temperature?: number | null;
  precipitation?: number | null;
  qn?: string;
}

interface LakeInfo {
  id: string;
  name: string;
  river: string;
  navigationForbidden?: boolean;
}

interface TooltipPayloadItem {
  value: number;
  dataKey: string;
  name: string;
  payload: Record<string, unknown>;
}

interface Props {
  language: Language;
  lakeId: string | null;
  windUnit?: 'kmh' | 'ms';
}

interface CustomTooltipProps {
  active?: boolean;
  payload?: TooltipPayloadItem[];
  label?: string;
  language: Language;
  isWeather?: boolean;
  isRiver?: boolean;
  coordinate?: { x: number; y: number };
  viewBox?: { width: number; height: number };
}

const CustomTooltip = ({ active, payload, label, language, isWeather, isRiver, coordinate, viewBox }: CustomTooltipProps) => {
  if (active && payload && payload.length) {
    const dict = t[language as Language].chart;
    const isLeft = coordinate && viewBox && coordinate.x > viewBox.width / 2;
    const tooltipClass = `chart-tooltip ${isLeft ? 'tooltip-left' : 'tooltip-right'}`;
    if (isWeather) {
      return (
        <div className={tooltipClass} style={{ backgroundColor: 'var(--bg-card)', padding: '0.4rem 0.6rem', border: '1px solid var(--border-color)', borderRadius: '0.5rem', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)', fontSize: '0.8rem' }}>
          <p style={{ margin: '0 0 0.25rem 0', fontWeight: 'bold', color: 'var(--text-main)', fontSize: '0.85rem' }}>{label}</p>
          {payload.map((entry: TooltipPayloadItem, index: number) => {
            const isTemp = entry.name === 'temperature' || entry.dataKey === 'temperature';
            return (
              <p key={index} style={{ margin: 0, color: 'var(--text-main)' }}>
                {isTemp ? (language === 'cs' ? 'Teplota' : 'Temperature') : (language === 'cs' ? 'Srážky' : 'Precipitation')}: <span style={{ fontWeight: 'bold' }}>{entry.value !== undefined && entry.value !== null ? entry.value.toFixed(1) : 'N/A'} {isTemp ? '°C' : 'mm'}</span>
              </p>
            );
          })}
        </div>
      );
    }
    return (
      <div className={tooltipClass} style={{ backgroundColor: 'var(--bg-card)', padding: '0.4rem 0.6rem', border: '1px solid var(--border-color)', borderRadius: '0.5rem', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)', fontSize: '0.8rem' }}>
        <p style={{ margin: '0 0 0.25rem 0', fontWeight: 'bold', color: 'var(--text-main)', fontSize: '0.85rem' }}>{label}</p>
        {[...payload].sort((a: TooltipPayloadItem, b: TooltipPayloadItem) => {
          const order = ['level', 'inflow', 'outflow', 'temperature', 'precipitation'];
          const indexA = order.indexOf(a.dataKey);
          const indexB = order.indexOf(b.dataKey);
          return (indexA === -1 ? 99 : indexA) - (indexB === -1 ? 99 : indexB);
        }).map((entry: TooltipPayloadItem, index: number) => {
           let labelStr = '';
           let unit = '';
           let color = '';
           if (entry.dataKey === 'level') { 
             labelStr = isRiver ? (language === 'cs' ? 'Vodní stav' : 'Water level') : dict.level; 
             unit = isRiver ? 'cm' : 'm n. m.'; 
             color = 'var(--color-cyan)'; 
           }
           else if (entry.dataKey === 'outflow') { 
             labelStr = isRiver ? (language === 'cs' ? 'Průtok' : 'Flow') : dict.outflow; 
             unit = 'm³/s'; 
             color = 'var(--color-red)'; 
           }
           else if (entry.dataKey === 'inflow') { 
             labelStr = dict.inflow; 
             unit = 'm³/s'; 
             color = 'var(--color-green)'; 
           }
           else if (entry.dataKey === 'temperature') { 
             labelStr = language === 'cs' ? 'Teplota' : 'Temperature'; 
             unit = '°C'; 
             color = 'var(--color-red)'; 
           }
           else if (entry.dataKey === 'precipitation') { 
             labelStr = language === 'cs' ? 'Srážky' : 'Precipitation'; 
             unit = 'mm'; 
             color = 'var(--color-cyan)'; 
           }
           
           if (!labelStr || entry.value === null || entry.value === undefined) return null;
           
           return (
              <div key={index} style={{ margin: 0, color: 'var(--text-main)', display: 'flex', alignItems: 'center', marginBottom: '2px' }}>
                <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', backgroundColor: color, marginRight: '6px' }}></span>
                {labelStr}: <span style={{ fontWeight: 'bold', marginLeft: '4px' }}>{entry.value.toFixed(entry.dataKey === 'level' ? (isRiver ? 0 : 2) : 1)} {unit}</span>
              </div>
            );
        })}
        {payload[0]?.payload?.qn ? (
           <div style={{ marginTop: '3px', paddingTop: '3px', borderTop: '1px solid var(--border-color)', fontSize: '0.75rem', color: '#f59e0b', display: 'flex', alignItems: 'center', gap: '4px', lineHeight: '1' }}>
             ⚠️ {language === 'cs' ? 'Neověřené měření' : 'Unverified measurement'}
           </div>
         ) : (
           <div style={{ marginTop: '3px', paddingTop: '3px', borderTop: '1px solid var(--border-color)', fontSize: '0.75rem', color: 'var(--color-green)', display: 'flex', alignItems: 'center', gap: '4px', lineHeight: '1' }}>
             ✓ {language === 'cs' ? 'Měření ověřeno' : 'Measurement verified'}
           </div>
         )}
      </div>
    );
  }
  return null;
};

const LakeDetail = ({ language, lakeId, windUnit = 'kmh' }: Props) => {
  const [data, setData] = useState<LipnoData[]>([]);
  const [loading, setLoading] = useState(true);
  const [lakeInfo, setLakeInfo] = useState<LakeInfo | null>(null);
  const [isSmoothed, setIsSmoothed] = useState(true);
  const [timeRange, setTimeRange] = useState<'24h' | '7d' | '30d' | '1y' | 'all'>('24h');
  const [visibleSeries, setVisibleSeries] = useState({
    level: true,
    outflow: true,
    inflow: true
  });
  const [visibleWeatherSeries, setVisibleWeatherSeries] = useState({
    temp: true,
    precip: true
  });
  const [isMobile, setIsMobile] = useState(false);
  const [leftCustomDomain, setLeftCustomDomain] = useState<[number, number] | null>(null);
  const [rightCustomDomain, setRightCustomDomain] = useState<[number, number] | null>(null);
  const [tooltipY, setTooltipY] = useState<number | undefined>(undefined);
  const [weatherTooltipY, setWeatherTooltipY] = useState<number | undefined>(undefined);
  const { isFavorite, toggleFavorite } = useFavorites();

  useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth <= 768);
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const [prevDeps, setPrevDeps] = useState({ timeRange, lakeId });
  if (prevDeps.timeRange !== timeRange || prevDeps.lakeId !== lakeId) {
    setPrevDeps({ timeRange, lakeId });
    setLeftCustomDomain(null);
    setRightCustomDomain(null);
  }

  const dict = t[language].chart;
  const topbarDict = t[language].topbar;

  useEffect(() => {
    const loadData = () => {
      fetch(`/data/lakes_index.json?t=${Date.now()}`)
        .then(res => res.json())
        .then(indexData => {
          const found = indexData.find((l: LakeInfo) => l.id === lakeId);
          setLakeInfo(found || { name: 'Lipno 1', river: 'Vltava' });
        })
        .catch(err => console.error(err));

      const internalId = lakeId ? lakeId.split('|')[0] : 'VLL1';
      const staticConfig = lakesConfig.find(l => l.id.split('|')[0] === internalId);

      fetch(`/data/${internalId}.json?t=${Date.now()}`)
        .then(res => res.json())
        .then(json => {
          let lastValidLevel: number | null = null;
          const formattedData = json.map((item: { timestamp: string, level?: number, flow?: number, inflow?: number, volume?: number, temperature?: number, precipitation?: number, qn?: string }) => {
            const outflow = item.flow === null || isNaN(item.flow) ? 0 : item.flow;
            let level = item.level === null || isNaN(item.level) ? 0 : item.level;

            // Outlier/sensor glitch detection
            if (level > 0) {
              if (staticConfig && staticConfig.minLevel && staticConfig.maxLevel) {
                const minAllowed = staticConfig.minLevel - 5;
                const maxAllowed = staticConfig.maxLevel + 5;
                if (level < minAllowed || level > maxAllowed) {
                  // Glitch detected, fallback to last known valid level
                  level = lastValidLevel !== null ? lastValidLevel : (staticConfig.minLevel + staticConfig.maxLevel) / 2;
                } else {
                  lastValidLevel = level;
                }
              } else {
                lastValidLevel = level;
              }
            } else if (lastValidLevel !== null) {
              // Level is 0 or less, fallback
              level = lastValidLevel;
            }

            return {
              timestamp: item.timestamp,
              date: new Date(item.timestamp).toLocaleString(language === 'cs' ? 'cs-CZ' : 'en-GB', {
                day: '2-digit', month: '2-digit', year: 'numeric',
                hour: '2-digit', minute: '2-digit'
              }),
              level: level,
              outflow: outflow,
              inflow: item.inflow || 0,
              volume: item.volume || 0,
              fullness: 0,
              temperature: item.temperature,
              precipitation: item.precipitation === null ? undefined : item.precipitation,
              qn: item.qn || ''
            };
          });
          setData(formattedData);
          setLoading(false);
        })
        .catch(err => {
          console.error('Failed to load data', err);
          setLoading(false);
        });
    };

    loadData();
    const intervalId = setInterval(loadData, 60 * 1000); // Poll every 1 minute
    return () => clearInterval(intervalId);
  }, [language, lakeId]);

  if (loading) {
    return (
      <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: 'var(--bg-dark)', color: 'var(--text-main)' }}>
        <div style={{ fontSize: '1.25rem' }}>Loading HLADINATOR...</div>
      </div>
    );
  }

  const latestData = data[data.length - 1] || { level: 0, inflow: 0, outflow: 0, volume: 0, fullness: 0 };
  const curveType = isSmoothed ? 'monotone' : 'linear';

  // Find last valid values for KPIs, including 0
  const lastValidFlowData = [...data].reverse().find(d => d.outflow !== null && !isNaN(d.outflow) && d.outflow >= 0) || latestData;

  const now = new Date().getTime();
  const getCutoff = () => {
    switch (timeRange) {
      case '24h': return now - 24 * 60 * 60 * 1000;
      case '7d': return now - 7 * 24 * 60 * 60 * 1000;
      case '30d': return now - 30 * 24 * 60 * 60 * 1000;
      case '1y': return now - 365 * 24 * 60 * 60 * 1000;
      default: return 0;
    }
  };

  const cutoff = getCutoff();
  const filteredData = data.filter(d => new Date(d.timestamp).getTime() >= cutoff);

  // Downsample data for large time ranges to prevent stuttering
  let chartData = filteredData;
  if (timeRange === '30d' && filteredData.length > 200) {
    chartData = filteredData.filter((_, i) => i % 4 === 0 || i === filteredData.length - 1);
  } else if ((timeRange === '1y' || timeRange === 'all') && filteredData.length > 200) {
    chartData = filteredData.filter((_, i) => i % 24 === 0 || i === filteredData.length - 1);
  }

  const animate = chartData.length < 150;

  // Find record from 24h, 7d, 30d ago
  const nowMs = new Date(latestData.timestamp).getTime();
  const targetMs24h = nowMs - 24 * 60 * 60 * 1000;
  const targetMs7d = nowMs - 7 * 24 * 60 * 60 * 1000;
  const targetMs30d = nowMs - 30 * 24 * 60 * 60 * 1000;
  
  const isFav = lakeId ? isFavorite(lakeId) : false;
  
  let level24hAgo = latestData.level;
  let level7dAgo = latestData.level;
  let level30dAgo = latestData.level;
  
  let minDiff24h = Infinity;
  let minDiff7d = Infinity;
  let minDiff30d = Infinity;
  
  let inflowSum24h = 0;
  let outflowSum24h = 0;
  let flowCount24h = 0;
  
  for (const d of data) {
    const t = new Date(d.timestamp).getTime();
    
    const diff24h = Math.abs(t - targetMs24h);
    if (diff24h < minDiff24h) {
      minDiff24h = diff24h;
      level24hAgo = d.level;
    }
    
    const diff7d = Math.abs(t - targetMs7d);
    if (diff7d < minDiff7d) {
      minDiff7d = diff7d;
      level7dAgo = d.level;
    }
    
    const diff30d = Math.abs(t - targetMs30d);
    if (diff30d < minDiff30d) {
      minDiff30d = diff30d;
      level30dAgo = d.level;
    }
    
    if (t >= targetMs24h && d.inflow !== undefined && d.outflow !== undefined) {
      inflowSum24h += d.inflow;
      outflowSum24h += d.outflow;
      flowCount24h++;
    }
  }
  
  const levelDiff24h = latestData.level - level24hAgo;
  const levelDiff7d = latestData.level - level7dAgo;
  const levelDiff30d = latestData.level - level30dAgo;
  
  const avgInflow24h = flowCount24h > 0 ? inflowSum24h / flowCount24h : undefined;
  const avgOutflow24h = flowCount24h > 0 ? outflowSum24h / flowCount24h : undefined;

  const limits = lakeInfo ? NAVIGATION_LIMITS[lakeInfo.id] : undefined;
  const staticConfig = lakeInfo ? lakesConfig.find(l => l.id === lakeInfo.id) : undefined;
  const isRiver = lakeInfo?.type === 'river';

  const kpiData = {
    level: latestData.level,
    levelDiff24h,
    levelDiff7d,
    levelDiff30d,
    inflow: lastValidFlowData.inflow,
    outflow: lastValidFlowData.outflow,
    volume: lakeInfo?.maxVolume || lakeInfo?.volume || 0,
    currentVolume: latestData.volume,
    fullness: lakeInfo?.capacity || 0,
    storageDiff: lakeInfo?.storageDiff,
    minDiff: (limits && limits.length > 0) ? latestData.level - limits[0].level : (staticConfig?.minLevel ? latestData.level - staticConfig.minLevel : undefined),
    minDiffLabelCs: limits && limits.length > 0 ? limits[0].labelCs : undefined,
    minDiffLabelEn: limits && limits.length > 0 ? limits[0].labelEn : undefined,
    avgInflow24h,
    avgOutflow24h
  };

  const getDefaultLeftDomain = (): [number, number] => {
    const levels = chartData.map(d => d.level).filter(v => v !== null && v !== undefined && !isNaN(v));
    if (levels.length === 0) return [0, 100];
    const dataMin = Math.min(...levels);
    const dataMax = Math.max(...levels);
    
    if (isRiver) {
      return [Math.max(0, Math.floor(dataMin - 10)), Math.ceil(dataMax + 10)];
    } else {
      let min = dataMin;
      if (limits) limits.forEach(l => { if (l.level < min) min = l.level; });
      let max = dataMax;
      if (staticConfig?.maxLevel && staticConfig.maxLevel > max) max = staticConfig.maxLevel;
      if (staticConfig?.storageLevel && staticConfig.storageLevel > max) max = staticConfig.storageLevel;
      return [min - 0.5, max + 0.5];
    }
  };

  const getDefaultRightDomain = (): [number, number] => {
    const flows = chartData.flatMap(d => [d.outflow, d.inflow]).filter(v => v !== null && v !== undefined && !isNaN(v));
    if (flows.length === 0) return [0, 10];
    const dataMax = Math.max(...flows);
    return [0, Math.max(dataMax, 1)];
  };

  const handleAxisDragStart = (
    e: React.MouseEvent | React.TouchEvent,
    axis: 'left' | 'right'
  ) => {
    e.preventDefault();
    const isTouchEvent = 'touches' in e;
    
    if (isTouchEvent && e.touches.length === 2) {
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const dist = Math.abs(touch1.clientY - touch2.clientY);
      
      const currentDomain = axis === 'left' 
        ? (leftCustomDomain || getDefaultLeftDomain())
        : (rightCustomDomain || getDefaultRightDomain());
        
      const onTouchMove = (moveEvent: TouchEvent) => {
        if (moveEvent.touches.length === 2) {
          moveEvent.preventDefault(); // Stop native page zooming
          const mTouch1 = moveEvent.touches[0];
          const mTouch2 = moveEvent.touches[1];
          const currentDist = Math.abs(mTouch1.clientY - mTouch2.clientY);
          if (currentDist > 5) {
            const factor = dist / currentDist;
            const center = (currentDomain[0] + currentDomain[1]) / 2;
            const range = currentDomain[1] - currentDomain[0];
            const newMin = center - (range * factor) / 2;
            const newMax = center + (range * factor) / 2;
            
            if (axis === 'left') {
              setLeftCustomDomain([newMin, newMax]);
            } else {
              setRightCustomDomain([Math.max(0, newMin), newMax]);
            }
          }
        }
      };
      
      const onTouchEnd = () => {
        window.removeEventListener('touchmove', onTouchMove);
        window.removeEventListener('touchend', onTouchEnd);
      };
      
      window.addEventListener('touchmove', onTouchMove, { passive: false });
      window.addEventListener('touchend', onTouchEnd);
      return;
    }

    const startY = isTouchEvent ? e.touches[0].clientY : e.clientY;
    const currentDomain = axis === 'left' 
      ? (leftCustomDomain || getDefaultLeftDomain())
      : (rightCustomDomain || getDefaultRightDomain());
      
    const initialRange = currentDomain[1] - currentDomain[0];
    const center = (currentDomain[1] + currentDomain[0]) / 2;

    const onMove = (moveEvent: MouseEvent | TouchEvent) => {
      if ('touches' in moveEvent) {
        moveEvent.preventDefault(); // Stop native page scrolling
      }
      const clientY = 'touches' in moveEvent ? moveEvent.touches[0].clientY : moveEvent.clientY;
      const deltaY = clientY - startY;
      
      const factor = Math.pow(2.5, deltaY / 150);
      const newMin = center - (initialRange * factor) / 2;
      const newMax = center + (initialRange * factor) / 2;

      if (axis === 'left') {
        setLeftCustomDomain([newMin, newMax]);
      } else {
        setRightCustomDomain([Math.max(0, newMin), newMax]);
      }
    };

    const onEnd = () => {
      if (isTouchEvent) {
        window.removeEventListener('touchmove', onMove);
        window.removeEventListener('touchend', onEnd);
      } else {
        window.removeEventListener('mousemove', onMove);
        window.removeEventListener('mouseup', onEnd);
      }
    };

    if (isTouchEvent) {
      window.addEventListener('touchmove', onMove, { passive: false });
      window.addEventListener('touchend', onEnd);
    } else {
      window.addEventListener('mousemove', onMove);
      window.addEventListener('mouseup', onEnd);
    }
  };

  const leftYAxisDomain = isRiver
    ? [
        (dataMin: number) => Math.max(0, Math.floor(dataMin - 10)),
        (dataMax: number) => Math.ceil(dataMax + 10)
      ]
    : [
        (dataMin: number) => {
          let min = dataMin;
          if (limits) limits.forEach(l => { if (l.level < min) min = l.level; });
          return min - 0.5;
        },
        (dataMax: number) => {
          let max = dataMax;
          if (staticConfig?.maxLevel && staticConfig.maxLevel > max) max = staticConfig.maxLevel;
          if (staticConfig?.storageLevel && staticConfig.storageLevel > max) max = staticConfig.storageLevel;
          return max + 0.5;
        }
      ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem', width: '100%' }}>
      {lakeInfo && (
        <>
          <Helmet>
            <title>{t[language].seo.lakeTitle.replace('{name}', lakeInfo.name)}</title>
            <meta name="description" content={t[language].seo.lakeDesc.replace('{name}', lakeInfo.name)} />
            <meta property="og:title" content={t[language].seo.lakeTitle.replace('{name}', lakeInfo.name)} />
            <meta property="og:description" content={t[language].seo.lakeDesc.replace('{name}', lakeInfo.name)} />
          </Helmet>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', margin: '0 0 0.5rem 0' }}>
              <h1 style={{ fontSize: '2rem', fontWeight: 'bold', margin: 0, color: 'var(--text-main)' }}>
                {lakeInfo.name}
              </h1>
              <button 
                onClick={(e) => { e.preventDefault(); if (lakeId) toggleFavorite(lakeId); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', padding: '0.25rem' }}
                title={isFav ? (language === 'cs' ? "Odebrat z oblíbených" : "Remove from favorites") : (language === 'cs' ? "Přidat do oblíbených" : "Add to favorites")}
              >
                <FiStar size={24} fill={isFav ? '#f59e0b' : 'none'} color={isFav ? '#f59e0b' : 'var(--text-muted)'} />
              </button>
              
              <div style={{ display: 'flex', gap: '0.5rem', marginLeft: 'auto' }}>
                <IconTooltip content={lakeInfo.navigationForbidden ? (language === 'cs' ? 'Koupání zakázáno' : 'Swimming forbidden') : (language === 'cs' ? 'Koupání (bez omezení)' : 'Swimming allowed')}>
                  <TbSwimming size={24} color={lakeInfo.navigationForbidden ? 'var(--color-red)' : 'var(--color-green)'} style={{ opacity: lakeInfo.navigationForbidden ? 0.5 : 0.8 }} />
                </IconTooltip>
                <IconTooltip content={lakeInfo.navigationForbidden ? (language === 'cs' ? 'Plavba zakázána' : 'Navigation forbidden') : (language === 'cs' ? 'Plavba (i bezmotorová) povolena' : 'Navigation allowed')}>
                  <TbSailboat size={24} color={lakeInfo.navigationForbidden ? 'var(--color-red)' : 'var(--color-green)'} style={{ opacity: lakeInfo.navigationForbidden ? 0.5 : 0.8 }} />
                </IconTooltip>
              </div>
            </div>
            <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: '0.95rem', lineHeight: '1.5' }}>
              {t[language].seo.lakeDesc.replace('{name}', lakeInfo.name)}
            </p>
          </div>
        </>
      )}

      <div style={{ 
        color: 'var(--text-muted)', 
        fontSize: isMobile ? '0.75rem' : '0.9rem', 
        marginTop: isMobile ? '-1.1rem' : '-0.5rem', 
        marginBottom: isMobile ? '-0.5rem' : '0', 
        display: 'flex', 
        alignItems: 'center', 
        gap: isMobile ? '0.4rem' : '0.75rem', 
        flexWrap: 'wrap' 
      }}>
        <span>{topbarDict.updated} {new Date().toLocaleDateString(language === 'cs' ? 'cs-CZ' : 'en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })}, {new Date().toLocaleTimeString(language === 'cs' ? 'cs-CZ' : 'en-GB', { hour: '2-digit', minute: '2-digit' })} UTC</span>
        <div className="status-dot"></div>
        {latestData.qn ? (
          <span style={{ 
            fontSize: isMobile ? '0.65rem' : '0.75rem', 
            padding: isMobile ? '0.1rem 0.3rem' : '0.15rem 0.4rem', 
            borderRadius: '4px', 
            backgroundColor: 'rgba(245, 158, 11, 0.1)', 
            color: '#f59e0b', 
            border: '1px solid rgba(245, 158, 11, 0.2)',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.2rem'
          }}>
            ⚠️ {language === 'cs' ? 'Neověřená data' : 'Unverified data'}
          </span>
        ) : (
          <span style={{ 
            fontSize: isMobile ? '0.65rem' : '0.75rem', 
            padding: isMobile ? '0.1rem 0.3rem' : '0.15rem 0.4rem', 
            borderRadius: '4px', 
            backgroundColor: 'rgba(34, 197, 94, 0.1)', 
            color: 'var(--color-green)', 
            border: '1px solid rgba(34, 197, 94, 0.2)',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.2rem'
          }}>
            ✓ {language === 'cs' ? 'Měření ověřeno' : 'Data verified'}
          </span>
        )}
      </div>

      <div className="kpi-grid-container">
        <KpiCards data={kpiData} language={language} lakeName={lakeInfo ? lakeInfo.name : 'Lipno 1'} isRiver={isRiver} />
        
        {lakeInfo && lakeInfo.lat && lakeInfo.lng && (
          <WeatherWidget lat={lakeInfo.lat} lng={lakeInfo.lng} language={language} windUnit={windUnit} sensorTemp={latestData.temperature ?? undefined} />
        )}
      </div>
      
      {limits && limits.map((limit, idx) => {
        const diff = latestData.level - limit.level;
        if (diff < 0.3) {
          const isBelow = diff < 0;
          return (
            <div key={idx} style={{ padding: '1rem', borderRadius: '8px', backgroundColor: isBelow ? 'rgba(248, 113, 113, 0.1)' : 'rgba(245, 158, 11, 0.1)', border: `1px solid ${isBelow ? 'var(--color-red)' : '#f59e0b'}`, color: isBelow ? 'var(--color-red)' : '#f59e0b', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <FiAlertCircle style={{ flexShrink: 0, fontSize: '1.5rem' }} />
              <div>
                <strong>{language === 'cs' ? limit.labelCs : limit.labelEn} ({limit.level.toFixed(2)} m n.m.):</strong>
                <br/>
                {isBelow 
                  ? (language === 'cs' ? `Hladina je ${Math.abs(diff).toFixed(2)} m POD limitem! Přerušení provozu.` : `Level is ${Math.abs(diff).toFixed(2)} m BELOW limit! Operations suspended.`)
                  : (language === 'cs' ? `Hladina se blíží k limitu (zbývá ${diff.toFixed(2)} m).` : `Level is approaching limit (${diff.toFixed(2)} m remaining).`)
                }
              </div>
            </div>
          );
        }
        return null;
      })}
      
      {/* CHART SECTION */}
      <div className="chart-card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.25rem', flexWrap: 'wrap', gap: '1rem', padding: isMobile ? '0 0.75rem' : '0' }}>
          <h3 style={{ margin: 0, fontSize: '1.1rem', color: 'var(--text-main)' }}>{dict.title} {lakeInfo ? `${lakeInfo.name} ${lakeInfo.river ? `- ${lakeInfo.river}` : ''}` : 'Lipno 1 - Vltava'}</h3>
          <div className="top-time-controls" style={{ margin: 0, display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '0.5rem' }}>
            <button className={timeRange === '24h' ? 'active' : ''} onClick={() => setTimeRange('24h')}>24h</button>
            <button className={timeRange === '7d' ? 'active' : ''} onClick={() => setTimeRange('7d')}>7d</button>
            <button className={timeRange === '30d' ? 'active' : ''} onClick={() => setTimeRange('30d')}>30d</button>
            <button className={timeRange === '1y' ? 'active' : ''} onClick={() => setTimeRange('1y')}>{dict.year}</button>
            <button className={timeRange === 'all' ? 'active' : ''} onClick={() => setTimeRange('all')}>{dict.all}</button>
            {(leftCustomDomain !== null || rightCustomDomain !== null) && (
              <button 
                onClick={() => { setLeftCustomDomain(null); setRightCustomDomain(null); }}
                style={{ 
                  backgroundColor: 'rgba(239, 68, 68, 0.15)', 
                  color: '#ef4444', 
                  border: '1px solid rgba(239, 68, 68, 0.3)',
                  borderRadius: '0.375rem',
                  padding: '0.4rem 0.75rem',
                  fontSize: '0.85rem',
                  cursor: 'pointer',
                  fontWeight: 500,
                  transition: 'all 0.2s'
                }}
              >
                Reset
              </button>
            )}
          </div>
        </div>

        <div style={{ flex: 1, minHeight: '300px', width: '100%', marginTop: '0', position: 'relative' }}>
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart 
              data={chartData} 
              margin={isMobile ? { top: 5, right: 5, left: 5, bottom: 0 } : { top: 5, right: 0, left: 10, bottom: 0 }}
              onMouseMove={(state: { chartY?: number } | null | undefined) => {
                if (state && state.chartY !== undefined) {
                  const isBottomHalf = state.chartY > 150;
                  const targetY = isBottomHalf ? 5 : 180;
                  if (tooltipY !== targetY) setTooltipY(targetY);
                }
              }}
              onMouseLeave={() => setTooltipY(undefined)}
            >
              <defs>
                <linearGradient id="colorLevel" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="var(--color-cyan)" stopOpacity={0.5}/>
                  <stop offset="95%" stopColor="var(--color-cyan)" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <XAxis dataKey="date" stroke="var(--text-muted)" tick={{fill: 'var(--text-muted)', fontSize: isMobile ? 10 : 12}} minTickGap={50} />
              <YAxis yAxisId="left" domain={leftCustomDomain || (leftYAxisDomain as [number, number] | ['auto', 'auto'])} stroke={visibleSeries.level ? "var(--text-muted)" : "transparent"} tick={{fill: visibleSeries.level ? 'var(--text-muted)' : 'transparent', fontSize: isMobile ? 10 : 12}} tickLine={visibleSeries.level ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} axisLine={visibleSeries.level ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} width={isMobile ? 42 : 60} tickFormatter={(v) => v.toFixed(isRiver ? 0 : 2)} />
              <YAxis yAxisId="right" orientation="right" domain={rightCustomDomain || [0, (dataMax: number) => Math.max(dataMax, 1)]} stroke={(visibleSeries.outflow || visibleSeries.inflow) ? "var(--text-muted)" : "transparent"} tick={{fill: (visibleSeries.outflow || visibleSeries.inflow) ? 'var(--text-muted)' : 'transparent', fontSize: isMobile ? 10 : 12}} tickLine={(visibleSeries.outflow || visibleSeries.inflow) ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} axisLine={(visibleSeries.outflow || visibleSeries.inflow) ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} width={isMobile ? 35 : 60} tickFormatter={(v) => v.toFixed(1)} />
              
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
              <Tooltip 
                content={<CustomTooltip language={language} isRiver={isRiver} />} 
                position={tooltipY !== undefined ? { y: tooltipY } : undefined}
              />
              
              {/* Data Series */}
              {visibleSeries.level && limits && limits.map((limit, idx) => (
                <ReferenceLine key={idx} yAxisId="left" y={limit.level} stroke={limit.type === 'danger' ? 'var(--color-red)' : '#f59e0b'} strokeDasharray="3 3" label={{ position: 'insideBottomLeft', value: language === 'cs' ? `${limit.labelCs} (${limit.level.toFixed(2)} m n. m.)` : `${limit.labelEn} (${limit.level.toFixed(2)} m a.s.l.)`, fill: limit.type === 'danger' ? 'var(--color-red)' : '#f59e0b', fontSize: 11, className: 'chart-ref-label' }} />
              ))}
              {visibleSeries.level && !isRiver && staticConfig?.maxLevel && staticConfig?.storageLevel && Math.abs(staticConfig.maxLevel - staticConfig.storageLevel) < 0.05 ? (
                <ReferenceLine 
                  yAxisId="left" 
                  y={staticConfig.maxLevel} 
                  stroke="var(--color-orange)" 
                  strokeDasharray="3 3" 
                  label={{ 
                    position: 'insideBottomRight', 
                    value: language === 'cs' 
                      ? `Max. retenční / zásobní hladina (${staticConfig.maxLevel.toFixed(2)} m n. m.)` 
                      : `Max retention / storage level (${staticConfig.maxLevel.toFixed(2)} m a.s.l.)`, 
                    fill: 'var(--color-orange)', 
                    fontSize: 11,
                    className: 'chart-ref-label'
                  }} 
                />
              ) : (
                <>
                  {visibleSeries.level && !isRiver && staticConfig?.maxLevel && (
                    <ReferenceLine 
                      yAxisId="left" 
                      y={staticConfig.maxLevel} 
                      stroke="var(--color-orange)" 
                      strokeDasharray="3 3" 
                      label={{ 
                        position: 'insideBottomRight', 
                        value: language === 'cs' 
                          ? `Maximální retenční hladina (${staticConfig.maxLevel.toFixed(2)} m n. m.)` 
                          : `Max retention level (${staticConfig.maxLevel.toFixed(2)} m a.s.l.)`, 
                        fill: 'var(--color-orange)', 
                        fontSize: 11,
                        className: 'chart-ref-label'
                      }} 
                    />
                  )}
                  {visibleSeries.level && !isRiver && staticConfig?.storageLevel && (
                    <ReferenceLine 
                      yAxisId="left" 
                      y={staticConfig.storageLevel} 
                      stroke="#a855f7" 
                      strokeDasharray="3 3" 
                      label={{ 
                        position: 'insideBottomLeft', 
                        value: language === 'cs' 
                          ? `Hladina zásobního prostoru (${staticConfig.storageLevel.toFixed(2)} m n. m.)` 
                          : `Storage space level (${staticConfig.storageLevel.toFixed(2)} m a.s.l.)`, 
                        fill: '#a855f7', 
                        fontSize: 11,
                        className: 'chart-ref-label'
                      }} 
                    />
                  )}
                </>
              )}
              <Area yAxisId="left" type={curveType} dataKey="level" stroke="var(--color-cyan)" strokeWidth={2} fillOpacity={1} fill="url(#colorLevel)" isAnimationActive={animate} hide={!visibleSeries.level} />
              <Line yAxisId="right" type={curveType} dataKey="outflow" stroke="var(--color-red)" strokeWidth={2} dot={false} isAnimationActive={animate} hide={!visibleSeries.outflow} />
              {!isRiver && <Line yAxisId="right" type={curveType} dataKey="inflow" stroke="var(--color-green)" strokeWidth={2} dot={false} isAnimationActive={animate} hide={!visibleSeries.inflow} />}
            </ComposedChart>
          </ResponsiveContainer>
          <div 
            onMouseDown={(e) => handleAxisDragStart(e, 'left')}
            onTouchStart={(e) => handleAxisDragStart(e, 'left')}
            style={{ 
              position: 'absolute', 
              left: 0, 
              top: 0, 
              bottom: isMobile ? 25 : 35, 
              width: isMobile ? 42 : 60, 
              cursor: 'ns-resize', 
              zIndex: 10,
              background: 'transparent'
            }}
            title={language === 'cs' ? 'Táhněte pro změnu měřítka osy hladiny' : 'Drag to scale level axis'}
          />
          <div 
            onMouseDown={(e) => handleAxisDragStart(e, 'right')}
            onTouchStart={(e) => handleAxisDragStart(e, 'right')}
            style={{ 
              position: 'absolute', 
              right: 0, 
              top: 0, 
              bottom: isMobile ? 25 : 35, 
              width: isMobile ? 35 : 60, 
              cursor: 'ns-resize', 
              zIndex: 10,
              background: 'transparent'
            }}
            title={language === 'cs' ? 'Táhněte pro změnu měřítka osy průtoku' : 'Drag to scale flow axis'}
          />
        </div>
        
        {/* Chart Legend */}
        <div className="chart-legend-container" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: '1.5rem', marginTop: '1rem', fontSize: '0.85rem', color: 'var(--text-main)', padding: isMobile ? '0 0.75rem' : '0' }}>
          <span 
            onClick={() => setVisibleSeries(prev => ({ ...prev, level: !prev.level }))}
            style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', opacity: visibleSeries.level ? 1 : 0.4, transition: 'opacity 0.2s', userSelect: 'none' }}
          >
            <div style={{ width: '12px', height: '4px', backgroundColor: 'var(--color-cyan)' }}></div> 
            {isRiver ? (language === 'cs' ? 'Vodní stav' : 'Water level') : dict.level}
          </span>
          <span 
            onClick={() => setVisibleSeries(prev => ({ ...prev, outflow: !prev.outflow }))}
            style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', opacity: visibleSeries.outflow ? 1 : 0.4, transition: 'opacity 0.2s', userSelect: 'none' }}
          >
            <div style={{ width: '12px', height: '4px', backgroundColor: 'var(--color-red)' }}></div> 
            {isRiver ? (language === 'cs' ? 'Průtok' : 'Flow') : dict.outflow}
          </span>
          {!isRiver && (
            <span 
              onClick={() => setVisibleSeries(prev => ({ ...prev, inflow: !prev.inflow }))}
              style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', opacity: visibleSeries.inflow ? 1 : 0.4, transition: 'opacity 0.2s', userSelect: 'none' }}
            >
              <div style={{ width: '12px', height: '4px', backgroundColor: 'var(--color-green)' }}></div> 
              {dict.inflow}
            </span>
          )}
        </div>

        {/* WEATHER CHART SECTION */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.25rem', marginTop: '1.5rem', flexWrap: 'wrap', gap: '1rem', padding: isMobile ? '0 0.75rem' : '0' }}>
          <h3 style={{ margin: 0, fontSize: '1.1rem', color: 'var(--text-main)' }}>{language === 'cs' ? 'Počasí (Teplota a Srážky)' : 'Weather (Temperature & Precipitation)'}</h3>
        </div>

        <div style={{ flex: 1, minHeight: '200px', width: '100%', marginTop: '0' }}>
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart 
              data={chartData} 
              margin={isMobile ? { top: 5, right: 5, left: 5, bottom: 0 } : { top: 5, right: 0, left: 10, bottom: 0 }}
              onMouseMove={(state: { chartY?: number } | null | undefined) => {
                if (state && state.chartY !== undefined) {
                  const isBottomHalf = state.chartY > 100;
                  const targetY = isBottomHalf ? 5 : 110;
                  if (weatherTooltipY !== targetY) setWeatherTooltipY(targetY);
                }
              }}
              onMouseLeave={() => setWeatherTooltipY(undefined)}
            >
              <XAxis dataKey="date" stroke="var(--text-muted)" tick={{fill: 'var(--text-muted)', fontSize: isMobile ? 10 : 12}} minTickGap={50} />
              <YAxis yAxisId="temp" domain={['auto', 'auto']} stroke={visibleWeatherSeries.temp ? "var(--text-muted)" : "transparent"} tick={{fill: visibleWeatherSeries.temp ? 'var(--text-muted)' : 'transparent', fontSize: isMobile ? 10 : 12}} tickLine={visibleWeatherSeries.temp ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} axisLine={visibleWeatherSeries.temp ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} width={isMobile ? 42 : 60} tickFormatter={(v) => v.toFixed(1)} />
              <YAxis yAxisId="precip" orientation="right" domain={[0, 'auto']} stroke={visibleWeatherSeries.precip ? "var(--text-muted)" : "transparent"} tick={{fill: visibleWeatherSeries.precip ? 'var(--text-muted)' : 'transparent', fontSize: isMobile ? 10 : 12}} tickLine={visibleWeatherSeries.precip ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} axisLine={visibleWeatherSeries.precip ? { stroke: 'var(--text-muted)' } : { stroke: 'transparent' }} width={isMobile ? 35 : 60} />
              
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
              <Tooltip 
                content={<CustomTooltip language={language} isWeather={true} />} 
                position={weatherTooltipY !== undefined ? { y: weatherTooltipY } : undefined}
              />
              
              <Bar yAxisId="precip" dataKey="precipitation" fill="var(--color-cyan)" fillOpacity={0.6} isAnimationActive={animate} hide={!visibleWeatherSeries.precip} />
              <Line yAxisId="temp" type="basis" dataKey="temperature" stroke="var(--color-red)" strokeWidth={3} dot={false} isAnimationActive={animate} hide={!visibleWeatherSeries.temp} />
            </ComposedChart>
          </ResponsiveContainer>
        </div>
        
        <div className="chart-legend-container" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: '1rem', marginTop: '1rem', fontSize: '0.85rem', color: 'var(--text-main)', padding: isMobile ? '0 0.75rem' : '0' }}>
          <span 
            onClick={() => setVisibleWeatherSeries(prev => ({ ...prev, temp: !prev.temp }))}
            style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', opacity: visibleWeatherSeries.temp ? 1 : 0.4, transition: 'opacity 0.2s', userSelect: 'none' }}
          >
            <div style={{ width: '12px', height: '4px', backgroundColor: 'var(--color-red)' }}></div> 
            {language === 'cs' ? 'Teplota vzduchu' : 'Temperature'} [°C]
          </span>
          <span 
            onClick={() => setVisibleWeatherSeries(prev => ({ ...prev, precip: !prev.precip }))}
            style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', opacity: visibleWeatherSeries.precip ? 1 : 0.4, transition: 'opacity 0.2s', userSelect: 'none' }}
          >
            <div style={{ width: '12px', height: '12px', backgroundColor: 'var(--color-cyan)', opacity: 0.6 }}></div> 
            {language === 'cs' ? 'Srážky' : 'Precipitation'} [mm]
          </span>
        </div>

        {/* Wind Chart placed inside the main card below the weather graph */}
        {lakeInfo && lakeInfo.lat && lakeInfo.lng && (
          <WindChart lat={lakeInfo.lat} lng={lakeInfo.lng} language={language} timeRange={timeRange} windUnit={windUnit} />
        )}

        {/* Smoothed Toggle Control */}
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: '1rem', marginTop: '3rem', marginBottom: '1rem' }}>
          <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>{dict.view}</span>
          <div style={{ display: 'flex', alignItems: 'center', fontSize: '0.9rem' }}>
            <span style={{ color: !isSmoothed ? 'var(--text-main)' : 'var(--text-muted)', transition: '0.2s', marginRight: '0.5rem' }}>{dict.raw}</span>
            <div 
              className={`toggle-switch ${isSmoothed ? 'on' : ''}`}
              onClick={() => setIsSmoothed(!isSmoothed)}
            ></div>
            <span style={{ color: isSmoothed ? 'var(--text-main)' : 'var(--text-muted)', transition: '0.2s', marginLeft: '0.5rem' }}>{dict.smoothed}</span>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LakeDetail;
