'use client';

import { useState, useEffect, useMemo } from 'react';
import { 
  Users, 
  Crown, 
  UserMinus, 
  Clock, 
  Receipt, 
  DollarSign, 
  RefreshCw, 
  AlertCircle,
  TrendingUp,
  Activity,
  BarChart3,
  LineChart as LineChartIcon,
  PieChart,
  Layers,
  FileSpreadsheet,
  ArrowUpRight
} from 'lucide-react';
import { apiFetch } from '@/lib/csrf/client';

interface DashboardStats {
  users: {
    total: number;
    proWeekly: number;
    proAnnual: number;
    proLifetime: number;
    free: number;
    waitlist: number;
    newToday: number;
    new7d: number;
    new30d: number;
  };
  activity: {
    totalScans: number;
    activeSessions: number;
    conversionRate: number;
  };
  growth: {
    users: { date: string; count: number }[];
    scans: { date: string; count: number }[];
  };
  onboarding?: {
    completedCount: number;
    personas: { key: string; count: number }[];
    volumes: { key: string; count: number }[];
    exportFormats: { key: string; count: number }[];
    referrals: { key: string; count: number }[];
  };
}

export default function AdminOverviewPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const res = await apiFetch('/api/admin/stats');
      if (!res.ok) throw new Error('Failed to fetch stats');
      const data = await res.json();
      setStats(data);
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, []);

  if (isLoading) {
    return (
      <div className="space-y-6 animate-pulse">
        <div className="flex items-center justify-between">
          <div className="h-8 w-56 bg-slate-200 rounded-lg"></div>
          <div className="h-9 w-28 bg-slate-200 rounded-lg"></div>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="h-32 bg-white rounded-2xl border border-slate-200"></div>
          ))}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
          <div className="h-96 bg-white rounded-2xl border border-slate-200"></div>
          <div className="h-96 bg-white rounded-2xl border border-slate-200"></div>
        </div>
      </div>
    );
  }

  if (error || !stats) {
    return (
      <div className="p-6 bg-red-50 border border-red-200 rounded-2xl flex items-center justify-between text-red-700">
        <div className="flex items-center gap-4">
          <div className="w-10 h-10 rounded-xl bg-red-100 flex items-center justify-center text-red-600">
            <AlertCircle size={22} />
          </div>
          <div>
            <h3 className="font-semibold text-base text-red-900">Fehler beim Laden des Dashboards</h3>
            <p className="text-xs text-red-600 mt-0.5">{error}</p>
          </div>
        </div>
        <button 
          onClick={fetchStats}
          className="px-4 py-2 bg-red-600 text-white hover:bg-red-700 font-medium rounded-xl transition-all flex items-center gap-2 shadow-xs text-xs"
        >
          <RefreshCw size={14} />
          Erneut laden
        </button>
      </div>
    );
  }

  const proUsersCount = stats.users.proWeekly + stats.users.proAnnual + stats.users.proLifetime;
  const proRatio = stats.users.total > 0 ? ((proUsersCount / stats.users.total) * 100).toFixed(1) : '0';
  const mrrProxy = (stats.users.proWeekly * 4.99 * 4.33) + (stats.users.proAnnual * 39.99 / 12);
  const avgScansPerUser = stats.users.total > 0 ? (stats.activity.totalScans / stats.users.total).toFixed(1) : '0';

  const formatNumber = (num: number) => num.toLocaleString('de-DE');
  const formatCurrency = (num: number) => 
    new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(num);

  const kpis = [
    { 
      label: 'Registrierte User', 
      value: formatNumber(stats.users.total), 
      badge: `+${stats.users.newToday} heute`,
      badgeStyle: 'bg-emerald-50 text-emerald-700 border-emerald-200',
      icon: Users, 
      color: 'text-emerald-600',
      iconBg: 'bg-emerald-50 border-emerald-200'
    },
    { 
      label: 'Pro Abonnenten', 
      value: formatNumber(proUsersCount), 
      badge: `${proRatio}% aller User`,
      badgeStyle: 'bg-amber-50 text-amber-700 border-amber-200',
      icon: Crown, 
      color: 'text-amber-600',
      iconBg: 'bg-amber-50 border-amber-200'
    },
    { 
      label: 'Kostenlose Konten', 
      value: formatNumber(stats.users.free), 
      badge: `${stats.users.total - proUsersCount} Free`,
      badgeStyle: 'bg-slate-100 text-slate-700 border-slate-200',
      icon: UserMinus, 
      color: 'text-slate-600',
      iconBg: 'bg-slate-100 border-slate-200'
    },
    { 
      label: 'Warteliste', 
      value: formatNumber(stats.users.waitlist), 
      badge: 'Early Access',
      badgeStyle: 'bg-indigo-50 text-indigo-700 border-indigo-200',
      icon: Clock, 
      color: 'text-indigo-600',
      iconBg: 'bg-indigo-50 border-indigo-200'
    },
    { 
      label: 'Scans Gesamt', 
      value: formatNumber(stats.activity.totalScans), 
      badge: `Ø ${avgScansPerUser} / User`,
      badgeStyle: 'bg-sky-50 text-sky-700 border-sky-200',
      icon: Receipt, 
      color: 'text-sky-600',
      iconBg: 'bg-sky-50 border-sky-200'
    },
    { 
      label: 'MRR Schätzung', 
      value: formatCurrency(mrrProxy), 
      badge: 'Run-Rate',
      badgeStyle: 'bg-emerald-50 text-emerald-700 border-emerald-200',
      icon: DollarSign, 
      color: 'text-emerald-600',
      iconBg: 'bg-emerald-50 border-emerald-200'
    },
  ];

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      {/* Top Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-2 border-b border-slate-200">
        <div>
          <div className="flex items-center gap-2.5">
            <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans">
              Admin Cockpit
            </h1>
            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-mono font-semibold bg-emerald-100 text-emerald-800 border border-emerald-200">
              Live DB
            </span>
          </div>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">
            Echtzeit-Metriken, Benutzerwachstum und Beleganalyse.
          </p>
        </div>
        
        <div className="flex items-center gap-3">
          <button 
            onClick={fetchStats}
            className="inline-flex items-center gap-2 px-3.5 py-2 text-xs sm:text-sm font-semibold text-slate-700 hover:text-slate-900 bg-white hover:bg-slate-50 border border-slate-200 rounded-xl transition-all shadow-xs active:scale-95"
            title="Daten aktualisieren"
          >
            <RefreshCw size={14} className={isLoading ? "animate-spin" : ""} />
            <span>Aktualisieren</span>
          </button>
        </div>
      </div>

      {/* KPI Cards Grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
        {kpis.map((kpi, i) => {
          const Icon = kpi.icon;
          return (
            <div 
              key={i} 
              className="group bg-white border border-slate-200 hover:border-slate-300 rounded-2xl p-4 sm:p-5 flex flex-col justify-between transition-all duration-200 shadow-xs hover:shadow-md"
            >
              <div className="flex items-center justify-between mb-3">
                <span className="text-xs font-semibold text-slate-500 leading-tight">
                  {kpi.label}
                </span>
                <div className={`p-2 rounded-xl border ${kpi.iconBg}`}>
                  <Icon size={16} className={kpi.color} />
                </div>
              </div>

              <div>
                <div className="text-2xl sm:text-3xl font-mono font-bold tracking-tight text-slate-900">
                  {kpi.value}
                </div>
                <div className="mt-2.5">
                  <span className={`inline-block text-[11px] font-mono font-medium px-2 py-0.5 rounded-md border ${kpi.badgeStyle}`}>
                    {kpi.badge}
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Main Charts Section (Light Mode with Beautiful Bars) */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <LightAnalyticsChart 
          title="User Neuregistrierungen" 
          subtitle="Tägliche Neuanmeldungen im gewählten Zeitraum"
          data={stats.growth.users} 
          theme="emerald" 
          icon={Users}
        />
        <LightAnalyticsChart 
          title="Beleg Scan-Aktivität" 
          subtitle="Täglich erfasste und verarbeitete Belege"
          data={stats.growth.scans} 
          theme="sky" 
          icon={Receipt}
        />
      </div>

      {/* Secondary Metrics & Conversion Row */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* User Velocity */}
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                <TrendingUp size={16} className="text-emerald-600" />
                Registrierungs-Dynamik
              </h3>
              <span className="text-xs font-mono text-slate-400">Kohorten</span>
            </div>
            
            <div className="space-y-3">
              <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50 border border-slate-100">
                <span className="text-xs font-medium text-slate-600">Heute neu</span>
                <div className="flex items-center gap-2">
                  <span className="font-mono font-bold text-emerald-600">+{formatNumber(stats.users.newToday)}</span>
                  <span className="text-xs text-slate-400">Accounts</span>
                </div>
              </div>
              <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50 border border-slate-100">
                <span className="text-xs font-medium text-slate-600">Letzte 7 Tage</span>
                <div className="flex items-center gap-2">
                  <span className="font-mono font-bold text-slate-900">+{formatNumber(stats.users.new7d)}</span>
                  <span className="text-xs text-slate-400">Accounts</span>
                </div>
              </div>
              <div className="flex items-center justify-between p-3 rounded-xl bg-slate-50 border border-slate-100">
                <span className="text-xs font-medium text-slate-600">Letzte 30 Tage</span>
                <div className="flex items-center gap-2">
                  <span className="font-mono font-bold text-slate-900">+{formatNumber(stats.users.new30d)}</span>
                  <span className="text-xs text-slate-400">Accounts</span>
                </div>
              </div>
            </div>
          </div>

          <div className="mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
            <span>30-Tage-Anteil:</span>
            <span className="font-mono text-emerald-700 font-bold">
              {stats.users.total > 0 ? ((stats.users.new30d / stats.users.total) * 100).toFixed(0) : '0'}% aller User
            </span>
          </div>
        </div>
        
        {/* Conversion Card */}
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                <Activity size={16} className="text-emerald-600" />
                Gast-zu-User Conversion
              </h3>
              <span className="text-xs font-mono text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200 font-medium">
                Funnel
              </span>
            </div>
            
            <div className="py-2 text-center">
              <div className="text-4xl font-mono font-extrabold text-slate-900">
                {stats.activity.conversionRate.toFixed(1)}%
              </div>
              <p className="text-xs text-slate-500 mt-1">Konvertierungsrate Gast → Registriert</p>
            </div>

            {/* Visual Bar */}
            <div className="mt-4 space-y-1.5">
              <div className="w-full bg-slate-100 rounded-full h-3 overflow-hidden p-0.5 border border-slate-200">
                <div 
                  className="bg-gradient-to-r from-emerald-500 to-teal-400 h-full rounded-full transition-all duration-500"
                  style={{ width: `${Math.min(100, Math.max(4, stats.activity.conversionRate))}%` }}
                />
              </div>
              <div className="flex justify-between text-[11px] text-slate-400 font-mono">
                <span>0%</span>
                <span>Ziel: &gt;15%</span>
                <span>100%</span>
              </div>
            </div>
          </div>

          <div className="mt-4 pt-4 border-t border-slate-100 text-xs text-slate-500 flex items-center justify-between">
            <span>Aktive Sitzungen:</span>
            <span className="font-mono text-slate-900 font-bold">{formatNumber(stats.activity.activeSessions)} online</span>
          </div>
        </div>

        {/* Plan Breakdown Card */}
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                <Crown size={16} className="text-amber-600" />
                Tarifverteilung
              </h3>
              <span className="text-xs font-mono text-amber-800 bg-amber-50 px-2 py-0.5 rounded-md border border-amber-200 font-medium">
                Monetarisierung
              </span>
            </div>

            <div className="space-y-3">
              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="text-slate-600 font-medium">Lifetime Lizenz</span>
                  <span className="font-mono text-amber-700 font-bold">{stats.users.proLifetime}</span>
                </div>
                <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden border border-slate-200">
                  <div 
                    className="bg-amber-500 h-full rounded-full" 
                    style={{ width: `${stats.users.total > 0 ? (stats.users.proLifetime / stats.users.total) * 100 : 0}%` }}
                  />
                </div>
              </div>

              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="text-slate-600 font-medium">Jahres-Abo (39,99 €)</span>
                  <span className="font-mono text-emerald-700 font-bold">{stats.users.proAnnual}</span>
                </div>
                <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden border border-slate-200">
                  <div 
                    className="bg-emerald-500 h-full rounded-full" 
                    style={{ width: `${stats.users.total > 0 ? (stats.users.proAnnual / stats.users.total) * 100 : 0}%` }}
                  />
                </div>
              </div>

              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="text-slate-600 font-medium">Wochen-Pass (4,99 €)</span>
                  <span className="font-mono text-sky-700 font-bold">{stats.users.proWeekly}</span>
                </div>
                <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden border border-slate-200">
                  <div 
                    className="bg-sky-500 h-full rounded-full" 
                    style={{ width: `${stats.users.total > 0 ? (stats.users.proWeekly / stats.users.total) * 100 : 0}%` }}
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
            <span>Free vs. Paid</span>
            <span className="font-mono font-bold text-slate-800">
              {stats.users.free} Free / {proUsersCount} Paid
            </span>
          </div>
        </div>
      </div>

      {/* Onboarding Personas & Insights (if available) */}
      {stats.onboarding && stats.onboarding.personas.length > 0 && (
        <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-xs">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                <PieChart size={18} className="text-indigo-600" />
                Zielgruppen & Onboarding-Insights
              </h3>
              <p className="text-xs text-slate-500 mt-0.5">
                Ausgewertete Personas und Präferenzen aus dem Onboarding ({stats.onboarding.completedCount} ausgefüllt)
              </p>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Personas */}
            <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
              <h4 className="text-xs font-mono uppercase tracking-wider text-slate-600 mb-3 flex items-center gap-1.5 font-bold">
                <Users size={14} className="text-indigo-600" />
                Nutzer-Segment
              </h4>
              <div className="space-y-2.5">
                {stats.onboarding.personas.map((p, idx) => {
                  const maxP = Math.max(...stats.onboarding!.personas.map(item => item.count), 1);
                  const labels: Record<string, string> = {
                    freelancer: 'Freelancer / Solo',
                    small_business: 'KMU / Gewerbe',
                    accountant: 'Team / Organisation',
                    personal: 'Privat / Finanzen',
                    unassigned: 'Nicht angegeben'
                  };
                  return (
                    <div key={idx}>
                      <div className="flex justify-between text-xs mb-1">
                        <span className="text-slate-700 font-medium">{labels[p.key] || p.key}</span>
                        <span className="font-mono text-slate-500 font-semibold">{p.count}</span>
                      </div>
                      <div className="w-full bg-slate-200 rounded-full h-1.5">
                        <div 
                          className="bg-indigo-600 h-full rounded-full" 
                          style={{ width: `${(p.count / maxP) * 100}%` }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Export Format */}
            <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
              <h4 className="text-xs font-mono uppercase tracking-wider text-slate-600 mb-3 flex items-center gap-1.5 font-bold">
                <FileSpreadsheet size={14} className="text-emerald-600" />
                Gewünschtes Exportformat
              </h4>
              <div className="space-y-2.5">
                {stats.onboarding.exportFormats.map((f, idx) => {
                  const maxF = Math.max(...stats.onboarding!.exportFormats.map(item => item.count), 1);
                  const labels: Record<string, string> = {
                    xlsx: 'Excel (.xlsx)',
                    csv: 'CSV',
                    pdf: 'PDF-Report',
                    excel_csv: 'Excel (.xlsx) / CSV',
                    datev: 'CSV',
                    lexoffice_sevdesk: 'Lexoffice / SevDesk',
                    pdf_bundle: 'PDF Sammelakte',
                    google_sheets: 'Google Sheets',
                    unassigned: 'Nicht angegeben'
                  };
                  return (
                    <div key={idx}>
                      <div className="flex justify-between text-xs mb-1">
                        <span className="text-slate-700 font-medium">{labels[f.key] || f.key}</span>
                        <span className="font-mono text-slate-500 font-semibold">{f.count}</span>
                      </div>
                      <div className="w-full bg-slate-200 rounded-full h-1.5">
                        <div 
                          className="bg-emerald-600 h-full rounded-full" 
                          style={{ width: `${(f.count / maxF) * 100}%` }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Referral Source */}
            <div className="bg-slate-50 border border-slate-200 rounded-xl p-4">
              <h4 className="text-xs font-mono uppercase tracking-wider text-slate-600 mb-3 flex items-center gap-1.5 font-bold">
                <Layers size={14} className="text-sky-600" />
                Akquise-Kanal
              </h4>
              <div className="space-y-2.5">
                {stats.onboarding.referrals.map((r, idx) => {
                  const maxR = Math.max(...stats.onboarding!.referrals.map(item => item.count), 1);
                  const labels: Record<string, string> = {
                    google: 'Google Suche',
                    social: 'Social Media',
                    recommendation: 'Empfehlung',
                    article_blog: 'Blog / Artikel',
                    community: 'Community',
                    unassigned: 'Direkt / Unbekannt'
                  };
                  return (
                    <div key={idx}>
                      <div className="flex justify-between text-xs mb-1">
                        <span className="text-slate-700 font-medium">{labels[r.key] || r.key}</span>
                        <span className="font-mono text-slate-500 font-semibold">{r.count}</span>
                      </div>
                      <div className="w-full bg-slate-200 rounded-full h-1.5">
                        <div 
                          className="bg-sky-600 h-full rounded-full" 
                          style={{ width: `${(r.count / maxR) * 100}%` }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

interface LightAnalyticsChartProps {
  title: string;
  subtitle?: string;
  data: { date: string; count: number }[];
  theme: 'emerald' | 'sky';
  icon: any;
}

function LightAnalyticsChart({ title, subtitle, data, theme, icon: Icon }: LightAnalyticsChartProps) {
  const [timeRange, setTimeRange] = useState<7 | 14 | 30>(30);
  const [chartMode, setChartMode] = useState<'bar' | 'area'>('bar');
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);

  // Fill in complete continuous dates for the selected timeRange
  const normalizedData = useMemo(() => {
    const map = new Map<string, number>();
    (data || []).forEach(d => {
      const key = d.date.includes('T') ? d.date.split('T')[0] : d.date;
      map.set(key, (map.get(key) || 0) + d.count);
    });

    const result: { date: string; shortDate: string; fullDate: string; count: number }[] = [];
    const now = new Date();

    for (let i = timeRange - 1; i >= 0; i--) {
      const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
      const isoDate = d.toISOString().split('T')[0];
      const shortDate = d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' });
      const fullDate = d.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: 'short' });
      result.push({
        date: isoDate,
        shortDate,
        fullDate,
        count: map.get(isoDate) || 0
      });
    }

    return result;
  }, [data, timeRange]);

  const totalInPeriod = useMemo(() => normalizedData.reduce((acc, curr) => acc + curr.count, 0), [normalizedData]);
  const maxCount = useMemo(() => Math.max(...normalizedData.map(d => d.count), 1), [normalizedData]);
  const avgCount = useMemo(() => (totalInPeriod / timeRange).toFixed(1), [totalInPeriod, timeRange]);
  const peakDay = useMemo(() => {
    let peak = normalizedData[0];
    normalizedData.forEach(d => {
      if (d.count > (peak?.count || 0)) peak = d;
    });
    return peak;
  }, [normalizedData]);

  // Color config in Light Mode
  const colors = theme === 'emerald' ? {
    solid: '#059669',
    gradientFrom: '#10B981',
    gradientTo: '#047857',
    accentText: 'text-emerald-700',
    accentBg: 'bg-emerald-50',
    borderAccent: 'border-emerald-200',
    svgFill: 'rgba(16, 185, 129, 0.12)',
    svgStroke: '#059669'
  } : {
    solid: '#0284C7',
    gradientFrom: '#38BDF8',
    gradientTo: '#0369A1',
    accentText: 'text-sky-700',
    accentBg: 'bg-sky-50',
    borderAccent: 'border-sky-200',
    svgFill: 'rgba(14, 165, 233, 0.12)',
    svgStroke: '#0284C7'
  };

  // SVG Area path generator
  const svgPath = useMemo(() => {
    if (normalizedData.length < 2) return { area: '', line: '' };
    const width = 600;
    const height = 180;
    const paddingBottom = 12;
    const usableHeight = height - paddingBottom;

    const points = normalizedData.map((d, i) => {
      const x = (i / (normalizedData.length - 1)) * width;
      const y = usableHeight - (d.count / maxCount) * (usableHeight - 15);
      return { x, y };
    });

    let lineD = `M ${points[0].x} ${points[0].y}`;
    for (let i = 0; i < points.length - 1; i++) {
      const curr = points[i];
      const next = points[i + 1];
      const cp1x = curr.x + (next.x - curr.x) / 2;
      const cp1y = curr.y;
      const cp2x = curr.x + (next.x - curr.x) / 2;
      const cp2y = next.y;
      lineD += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${next.x} ${next.y}`;
    }

    const areaD = `${lineD} L ${width} ${height} L 0 ${height} Z`;
    return { area: areaD, line: lineD };
  }, [normalizedData, maxCount]);

  const activeItem = hoveredIndex !== null ? normalizedData[hoveredIndex] : null;

  return (
    <div className="bg-white border border-slate-200 rounded-2xl p-5 sm:p-6 flex flex-col justify-between shadow-xs">
      {/* Header */}
      <div>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4">
          <div className="flex items-center gap-2.5">
            <div className={`p-2 rounded-xl border ${colors.accentBg} ${colors.borderAccent}`}>
              <Icon size={18} className={colors.accentText} />
            </div>
            <div>
              <h3 className="text-base font-bold text-slate-900 tracking-tight">{title}</h3>
              {subtitle && <p className="text-xs text-slate-500">{subtitle}</p>}
            </div>
          </div>

          {/* Controls: TimeRange & Mode Toggle */}
          <div className="flex items-center gap-2 self-start sm:self-auto">
            {/* View Mode Toggle (Bar vs Area) */}
            <div className="flex items-center bg-slate-100 p-1 rounded-xl border border-slate-200">
              <button
                onClick={() => setChartMode('bar')}
                className={`p-1.5 rounded-lg text-xs transition-all ${
                  chartMode === 'bar' 
                    ? 'bg-white text-slate-900 font-bold shadow-xs' 
                    : 'text-slate-500 hover:text-slate-800'
                }`}
                title="Balkenansicht"
              >
                <BarChart3 size={15} />
              </button>
              <button
                onClick={() => setChartMode('area')}
                className={`p-1.5 rounded-lg text-xs transition-all ${
                  chartMode === 'area' 
                    ? 'bg-white text-slate-900 font-bold shadow-xs' 
                    : 'text-slate-500 hover:text-slate-800'
                }`}
                title="Trend-Linie"
              >
                <LineChartIcon size={15} />
              </button>
            </div>

            {/* Timeframe Selector */}
            <div className="flex items-center bg-slate-100 p-1 rounded-xl border border-slate-200 font-mono text-xs">
              {([7, 14, 30] as const).map(days => (
                <button
                  key={days}
                  onClick={() => setTimeRange(days)}
                  className={`px-2.5 py-1 rounded-lg transition-all ${
                    timeRange === days 
                      ? 'bg-white text-slate-900 font-bold shadow-xs' 
                      : 'text-slate-500 hover:text-slate-800'
                  }`}
                >
                  {days}d
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Highlight Summary Stats Bar (Light Mode) */}
        <div className="grid grid-cols-3 gap-2 py-3 px-3.5 bg-slate-50 rounded-xl border border-slate-200 mb-6">
          <div>
            <span className="text-[11px] text-slate-500 block font-medium">Gesamt im Zeitraum</span>
            <span className="text-lg font-mono font-bold text-slate-900">{totalInPeriod}</span>
          </div>
          <div>
            <span className="text-[11px] text-slate-500 block font-medium">Tagesdurchschnitt</span>
            <span className="text-lg font-mono font-bold text-slate-800">Ø {avgCount}</span>
          </div>
          <div>
            <span className="text-[11px] text-slate-500 block font-medium">Spitzenwert</span>
            <span className={`text-lg font-mono font-bold ${colors.accentText}`}>
              {peakDay?.count || 0} <span className="text-xs font-normal text-slate-500 font-sans">am {peakDay?.shortDate}</span>
            </span>
          </div>
        </div>
      </div>

      {/* Chart Canvas Area */}
      <div className="relative h-56 w-full flex flex-col justify-end pt-4 select-none">
        {/* Background Y-Grid lines */}
        <div className="absolute inset-0 flex flex-col justify-between pointer-events-none opacity-40">
          <div className="border-b border-dashed border-slate-300 w-full flex justify-between text-[10px] font-mono text-slate-400">
            <span>{maxCount}</span>
          </div>
          <div className="border-b border-dashed border-slate-300 w-full flex justify-between text-[10px] font-mono text-slate-400">
            <span>{Math.round(maxCount / 2)}</span>
          </div>
          <div className="border-b border-slate-200 w-full flex justify-between text-[10px] font-mono text-slate-400">
            <span>0</span>
          </div>
        </div>

        {/* Hover Inspector Tooltip */}
        {activeItem && (
          <div className="absolute top-0 right-0 z-20 bg-white border border-slate-200 text-xs px-3 py-1.5 rounded-xl shadow-lg flex items-center gap-2 pointer-events-none animate-fade-in">
            <span className="text-slate-500 font-medium">{activeItem.fullDate}:</span>
            <span className={`font-mono font-bold ${colors.accentText} text-sm`}>
              {activeItem.count}
            </span>
          </div>
        )}

        {/* BAR CHART MODE (Light Mode with Sleek Columns) */}
        {chartMode === 'bar' && (
          <div className="relative z-10 h-44 flex items-end justify-between gap-1 sm:gap-1.5 w-full">
            {normalizedData.map((item, i) => {
              const heightPercent = maxCount > 0 ? (item.count / maxCount) * 100 : 0;
              const isHovered = hoveredIndex === i;

              return (
                <div 
                  key={item.date} 
                  className="relative flex-1 h-full flex flex-col justify-end group cursor-pointer"
                  onMouseEnter={() => setHoveredIndex(i)}
                  onMouseLeave={() => setHoveredIndex(null)}
                >
                  {/* Subtle column background track */}
                  <div className={`absolute inset-x-0 bottom-0 top-0 rounded-t-md transition-colors ${
                    isHovered ? 'bg-slate-200/80' : 'bg-slate-100/60'
                  }`} />

                  {/* Animated Bar with gradient */}
                  <div 
                    className={`relative w-full rounded-t-md transition-all duration-200 ${
                      isHovered ? 'brightness-110 scale-y-[1.02] shadow-xs' : 'opacity-95'
                    }`}
                    style={{ 
                      height: `${Math.max(heightPercent, item.count > 0 ? 8 : 3)}%`,
                      background: item.count > 0 
                        ? `linear-gradient(to top, ${colors.gradientTo}, ${colors.gradientFrom})` 
                        : '#CBD5E1'
                    }}
                  >
                    {/* Glowing top line indicator on active bars */}
                    {item.count > 0 && (
                      <div className="w-full h-1 bg-white/50 rounded-t-md" />
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* AREA / LINE CHART MODE */}
        {chartMode === 'area' && (
          <div 
            className="relative z-10 h-44 w-full"
            onMouseLeave={() => setHoveredIndex(null)}
          >
            <svg 
              viewBox="0 0 600 180" 
              className="w-full h-full overflow-visible"
              preserveAspectRatio="none"
            >
              <defs>
                <linearGradient id={`light-gradient-${theme}`} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={colors.solid} stopOpacity="0.25" />
                  <stop offset="100%" stopColor={colors.solid} stopOpacity="0.0" />
                </linearGradient>
              </defs>

              {/* Area */}
              <path d={svgPath.area} fill={`url(#light-gradient-${theme})`} />

              {/* Smooth Line */}
              <path 
                d={svgPath.line} 
                fill="none" 
                stroke={colors.svgStroke} 
                strokeWidth="2.5" 
                strokeLinecap="round"
                strokeLinejoin="round"
              />

              {/* Interactive Hit Areas */}
              {normalizedData.map((d, i) => {
                const x = (i / (normalizedData.length - 1)) * 600;
                const y = 168 - (d.count / maxCount) * 150;
                const isHovered = hoveredIndex === i;

                return (
                  <g key={i} onMouseEnter={() => setHoveredIndex(i)}>
                    <rect 
                      x={x - 10} 
                      y={0} 
                      width={20} 
                      height={180} 
                      fill="transparent" 
                      className="cursor-pointer"
                    />
                    {isHovered && (
                      <>
                        <line 
                          x1={x} 
                          y1={0} 
                          x2={x} 
                          y2={180} 
                          stroke="#94A3B8" 
                          strokeDasharray="3 3"
                        />
                        <circle 
                          cx={x} 
                          cy={y} 
                          r="5" 
                          fill="#ffffff" 
                          stroke={colors.solid} 
                          strokeWidth="3" 
                        />
                      </>
                    )}
                  </g>
                );
              })}
            </svg>
          </div>
        )}

        {/* X-Axis Date Labels */}
        <div className="flex justify-between mt-3 text-[11px] text-slate-500 font-mono border-t border-slate-200 pt-2">
          <span>{normalizedData[0]?.fullDate}</span>
          <span>{normalizedData[Math.floor(normalizedData.length / 2)]?.shortDate}</span>
          <span>{normalizedData[normalizedData.length - 1]?.fullDate}</span>
        </div>
      </div>
    </div>
  );
}
