"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { toPng } from "html-to-image";
import {
  Award,
  BookOpen,
  ChevronLeft,
  ChevronRight,
  Download,
  Flame,
  Sparkles,
  Target,
  TrendingUp,
  Wallet,
  Zap,
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { useFocusStore } from "@/stores/focus-store";
import { useWorkspaceStore } from "@/stores/workspace-store";
import { cn } from "@/lib/utils";

/* ── Types ───────────────────────────────────────────────────────────────── */

interface WrappedStats {
  // Focus
  totalFocusMinutes: number;
  focusSessions: number;
  longestStreak: number;
  bestFocusDay: string | null;
  // Tasks
  tasksCompleted: number;
  bestProductivityDay: string | null;
  // Achievements
  achievementsUnlocked: number;
  topAchievement: string | null;
  topAchievementIcon: string | null;
  // Journal
  journalEntries: number;
  bestMoodDay: string | null;
  topMood: string | null;
  // Finance
  totalIncome: number;
  totalExpenses: number;
  netProfit: number;
  // Meta
  totalDaysActive: number;
  year: number;
}

interface WrappedTaskRow {
  completed_at: string | null;
  id: string;
  status: string | null;
}

interface WrappedAchievementRow {
  completed_at: string | null;
  icon: string | null;
  id: string;
  status: string | null;
  title: string | null;
}

interface WrappedJournalRow {
  entry_date: string;
  id: string;
  mood: string | null;
}

interface WrappedFinanceRow {
  amount_cents: number;
  id: string;
  transaction_date: string;
  type: string;
}

type SlideId = "intro" | "focus" | "tasks" | "achievements" | "journal" | "finance" | "legend";

const SLIDES: SlideId[] = ["intro", "focus", "tasks", "achievements", "journal", "finance", "legend"];

/* ── Helpers ────────────────────────────────────────────────────────────── */

function fmtHours(minutes: number) {
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  if (h === 0) return `${m}m`;
  if (m === 0) return `${h}h`;
  return `${h}h ${m}m`;
}

function fmtMoney(cents: number, withSign = false) {
  const abs = new Intl.NumberFormat("de-DE", {
    currency: "EUR",
    maximumFractionDigits: 0,
    minimumFractionDigits: 0,
    style: "currency",
  }).format(Math.abs(cents) / 100);

  if (cents < 0) return `−${abs}`;
  if (withSign && cents > 0) return `+${abs}`;
  return abs;
}

/* ── Slide components ───────────────────────────────────────────────────── */

function SlideWrapper({
  children,
  gradient,
  className,
}: {
  children: React.ReactNode;
  gradient: string;
  className?: string;
}) {
  return (
    <div
      className={cn("relative flex flex-col items-center justify-center min-h-[520px] rounded-[32px] overflow-hidden px-8 py-12 text-center", className)}
      style={{ background: gradient }}
    >
      {/* Noise texture overlay */}
      <div className="pointer-events-none absolute inset-0 opacity-[0.03]"
        style={{ backgroundImage: "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E\")" }} />
      {children}
    </div>
  );
}

function BigStat({ value, label, color = "text-white" }: { value: string; label: string; color?: string }) {
  return (
    <div className="flex flex-col items-center gap-1">
      <span className={cn("text-[72px] font-black leading-none tracking-tighter tabular-nums", color)}
        style={{ textShadow: "0 4px 32px rgba(0,0,0,0.4)" }}>
        {value}
      </span>
      <span className="text-white/50 text-sm font-medium uppercase tracking-widest">{label}</span>
    </div>
  );
}

function StatRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-6 rounded-2xl bg-white/[0.07] px-4 py-3">
      <span className="text-white/50 text-sm">{label}</span>
      <span className="text-white font-bold text-sm">{value}</span>
    </div>
  );
}

/* ── Individual slides ─────────────────────────────────────────────────── */

function IntroSlide({ stats, year }: { stats: WrappedStats; year: number }) {
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #0f0f1a 0%, #1a1033 50%, #0d1117 100%)">
      <div className="pointer-events-none absolute top-0 left-0 w-72 h-72 rounded-full opacity-20 blur-3xl"
        style={{ background: "radial-gradient(circle, #7c3aed, transparent 70%)" }} />
      <div className="pointer-events-none absolute bottom-0 right-0 w-64 h-64 rounded-full opacity-15 blur-3xl"
        style={{ background: "radial-gradient(circle, #4f46e5, transparent 70%)" }} />

      <div className="relative z-10 flex flex-col items-center gap-6">
        <div className="w-16 h-16 rounded-[18px] bg-white/10 border border-white/15 flex items-center justify-center">
          <Sparkles className="w-8 h-8 text-white" />
        </div>
        <div>
          <p className="text-white/40 text-xs uppercase tracking-[0.2em] font-bold mb-2">Mindavio</p>
          <h1 className="text-5xl font-black text-white tracking-tight">
            Your {year}<br />
            <span style={{ background: "linear-gradient(135deg,#a78bfa,#818cf8)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>
              Wrapped
            </span>
          </h1>
        </div>
        <p className="text-white/40 text-sm max-w-xs leading-relaxed">
          {stats.totalDaysActive} Tage aktiv. Ein Jahr in einem Blick.
        </p>
        <div className="flex gap-3 mt-2">
          {[
            { icon: <Zap className="w-3.5 h-3.5" />, label: `${stats.focusSessions} Sessions` },
            { icon: <Target className="w-3.5 h-3.5" />, label: `${stats.tasksCompleted} Tasks` },
            { icon: <Award className="w-3.5 h-3.5" />, label: `${stats.achievementsUnlocked} Achievements` },
          ].map(({ icon, label }) => (
            <div key={label} className="flex items-center gap-1.5 rounded-full bg-white/[0.07] border border-white/10 px-3 py-1.5 text-white/60 text-xs">
              {icon}
              {label}
            </div>
          ))}
        </div>
      </div>
    </SlideWrapper>
  );
}

function FocusSlide({ stats }: { stats: WrappedStats }) {
  const pct = Math.min(100, Math.round((stats.totalFocusMinutes / (365 * 120)) * 100));
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #0d0820 0%, #1a0d3d 50%, #0a0a0d 100%)">
      <div className="pointer-events-none absolute top-0 right-0 w-80 h-80 rounded-full opacity-25 blur-3xl"
        style={{ background: "radial-gradient(circle, #6d28d9, transparent 70%)" }} />
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">
        <div className="flex flex-col items-center gap-2">
          <div className="w-12 h-12 rounded-[14px] bg-violet-500/20 border border-violet-500/30 flex items-center justify-center">
            <Zap className="w-6 h-6 text-violet-300" />
          </div>
          <p className="text-violet-300/70 text-xs uppercase tracking-widest font-bold">Deep Work</p>
        </div>

        <BigStat
          value={fmtHours(stats.totalFocusMinutes)}
          label="im Flow"
          color="text-violet-200"
        />

        <div className="w-full space-y-3">
          <StatRow label="Focus Sessions" value={String(stats.focusSessions)} />
          <StatRow label="Längster Streak" value={`${stats.longestStreak} Tage`} />
          {stats.bestFocusDay && (
            <StatRow label="Bester Tag" value={new Date(stats.bestFocusDay).toLocaleDateString("de-DE", { day: "2-digit", month: "short" })} />
          )}
        </div>

        {pct > 0 && (
          <div className="w-full">
            <div className="flex justify-between text-xs text-white/30 mb-1.5">
              <span>Jahres-Fortschritt</span>
              <span>{pct}%</span>
            </div>
            <div className="h-1.5 rounded-full bg-white/[0.07] overflow-hidden">
              <div className="h-full rounded-full bg-gradient-to-r from-violet-600 to-violet-400 transition-all"
                style={{ width: `${pct}%` }} />
            </div>
          </div>
        )}
      </div>
    </SlideWrapper>
  );
}

function TasksSlide({ stats }: { stats: WrappedStats }) {
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #051a10 0%, #0a2d1a 50%, #0a0a0d 100%)">
      <div className="pointer-events-none absolute bottom-0 left-0 w-72 h-72 rounded-full opacity-20 blur-3xl"
        style={{ background: "radial-gradient(circle, #059669, transparent 70%)" }} />
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">
        <div className="flex flex-col items-center gap-2">
          <div className="w-12 h-12 rounded-[14px] bg-emerald-500/20 border border-emerald-500/30 flex items-center justify-center">
            <Target className="w-6 h-6 text-emerald-300" />
          </div>
          <p className="text-emerald-300/70 text-xs uppercase tracking-widest font-bold">Execution</p>
        </div>

        <BigStat
          value={String(stats.tasksCompleted)}
          label="Tasks erledigt"
          color="text-emerald-200"
        />

        <div className="w-full space-y-3">
          {stats.bestProductivityDay && (
            <StatRow label="Bester Tag" value={new Date(stats.bestProductivityDay).toLocaleDateString("de-DE", { day: "2-digit", month: "short", year: "numeric" })} />
          )}
          <StatRow label="Ø pro Monat" value={String(Math.round(stats.tasksCompleted / 12))} />
          <StatRow label="Ø pro Woche" value={String(Math.round(stats.tasksCompleted / 52))} />
        </div>
      </div>
    </SlideWrapper>
  );
}

function AchievementsSlide({ stats }: { stats: WrappedStats }) {
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #1c1508 0%, #2a1d06 50%, #0a0a0d 100%)">
      <div className="pointer-events-none absolute top-0 left-1/2 -translate-x-1/2 w-96 h-48 opacity-20 blur-3xl"
        style={{ background: "radial-gradient(ellipse, #d97706, transparent 70%)" }} />
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">
        <div className="flex flex-col items-center gap-2">
          <div className="w-12 h-12 rounded-[14px] bg-amber-500/20 border border-amber-500/30 flex items-center justify-center">
            <Award className="w-6 h-6 text-amber-300" />
          </div>
          <p className="text-amber-300/70 text-xs uppercase tracking-widest font-bold">Achievements</p>
        </div>

        {stats.topAchievementIcon && (
          <div className="w-20 h-20 rounded-[22px] bg-amber-500/15 border border-amber-500/25 flex items-center justify-center text-5xl"
            style={{ boxShadow: "0 0 40px rgba(245,158,11,0.2)" }}>
            {stats.topAchievementIcon}
          </div>
        )}

        <BigStat
          value={String(stats.achievementsUnlocked)}
          label="Achievements unlocked"
          color="text-amber-200"
        />

        {stats.topAchievement && (
          <div className="w-full rounded-2xl bg-amber-500/[0.08] border border-amber-500/15 px-4 py-3 text-center">
            <p className="text-amber-300/50 text-xs uppercase tracking-widest mb-1">Top Achievement</p>
            <p className="text-white font-bold text-sm">{stats.topAchievement}</p>
          </div>
        )}
      </div>
    </SlideWrapper>
  );
}

function JournalSlide({ stats }: { stats: WrappedStats }) {
  const moodEmoji: Record<string, string> = {
    great: "🤩", good: "😊", neutral: "😐", bad: "😞", terrible: "😢",
  };
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #080f1a 0%, #0c1a2e 50%, #0a0a0d 100%)">
      <div className="pointer-events-none absolute top-0 right-0 w-72 h-72 opacity-20 blur-3xl"
        style={{ background: "radial-gradient(circle, #0ea5e9, transparent 70%)" }} />
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">
        <div className="flex flex-col items-center gap-2">
          <div className="w-12 h-12 rounded-[14px] bg-sky-500/20 border border-sky-500/30 flex items-center justify-center">
            <BookOpen className="w-6 h-6 text-sky-300" />
          </div>
          <p className="text-sky-300/70 text-xs uppercase tracking-widest font-bold">Journal</p>
        </div>

        <BigStat value={String(stats.journalEntries)} label="Einträge geschrieben" color="text-sky-200" />

        <div className="w-full space-y-3">
          {stats.topMood && (
            <StatRow
              label="Häufigste Stimmung"
              value={`${moodEmoji[stats.topMood] ?? ""} ${stats.topMood}`}
            />
          )}
          <StatRow label="Ø pro Monat" value={String(Math.round(stats.journalEntries / 12))} />
          <StatRow label="Konsistenz" value={`${Math.min(100, Math.round((stats.journalEntries / 365) * 100))}%`} />
        </div>
      </div>
    </SlideWrapper>
  );
}

function FinanceSlide({ stats }: { stats: WrappedStats }) {
  const isProfit = stats.netProfit >= 0;
  const margeRaw = stats.totalIncome > 0
    ? Math.round((stats.netProfit / stats.totalIncome) * 100)
    : null;
  const margeStr = margeRaw !== null
    ? `${margeRaw >= 0 ? "+" : ""}${margeRaw}%`
    : "—";

  return (
    <SlideWrapper gradient={isProfit
      ? "linear-gradient(145deg, #051a10 0%, #0a2d1a 50%, #0a0a0d 100%)"
      : "linear-gradient(145deg, #1a0505 0%, #2d0a0a 50%, #0a0a0d 100%)"
    }>
      <div className="pointer-events-none absolute top-0 right-0 w-72 h-72 opacity-15 blur-3xl"
        style={{ background: `radial-gradient(circle, ${isProfit ? "#059669" : "#dc2626"}, transparent 70%)` }} />
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">

        {/* Header */}
        <div className="flex flex-col items-center gap-2">
          <div className={cn("w-12 h-12 rounded-[14px] border flex items-center justify-center",
            isProfit ? "bg-emerald-500/20 border-emerald-500/30" : "bg-red-500/20 border-red-500/30")}>
            <Wallet className={cn("w-6 h-6", isProfit ? "text-emerald-300" : "text-red-300")} />
          </div>
          <p className={cn("text-xs uppercase tracking-widest font-bold",
            isProfit ? "text-emerald-300/70" : "text-red-300/70")}>Finance</p>
        </div>

        {/* Net result */}
        <BigStat
          value={fmtMoney(stats.netProfit, true)}
          label={isProfit ? "Netto Gewinn" : "Netto Verlust"}
          color={isProfit ? "text-emerald-200" : "text-red-200"}
        />

        {/* Breakdown */}
        <div className="w-full space-y-3">
          <StatRow label="↑ Einnahmen" value={fmtMoney(stats.totalIncome)} />
          <StatRow label="↓ Ausgaben"  value={`−${fmtMoney(stats.totalExpenses)}`} />
          <div className="flex items-center justify-between gap-6 rounded-2xl bg-white/[0.10] px-4 py-3 border border-white/[0.08]">
            <span className="text-white/60 text-sm font-semibold">Marge</span>
            <span className={cn("font-black text-sm tabular-nums",
              margeRaw !== null && margeRaw >= 0 ? "text-emerald-300" : "text-red-300")}>
              {margeStr}
            </span>
          </div>
        </div>
      </div>
    </SlideWrapper>
  );
}

function LegendSlide({ stats, year }: { stats: WrappedStats; year: number }) {
  return (
    <SlideWrapper gradient="linear-gradient(145deg, #0f0f1a 0%, #1a1033 50%, #0d1117 100%)">
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute top-0 left-0 w-72 h-72 opacity-15 blur-3xl"
          style={{ background: "radial-gradient(circle, #7c3aed, transparent 70%)" }} />
        <div className="absolute bottom-0 right-0 w-64 h-64 opacity-15 blur-3xl"
          style={{ background: "radial-gradient(circle, #d97706, transparent 70%)" }} />
      </div>
      <div className="relative z-10 flex flex-col items-center gap-8 w-full max-w-xs">
        <div className="w-12 h-12 rounded-[14px] bg-white/10 border border-white/15 flex items-center justify-center">
          <TrendingUp className="w-6 h-6 text-white" />
        </div>

        <div className="text-center">
          <p className="text-white/30 text-xs uppercase tracking-widest mb-2">{year} in Zahlen</p>
          <h2 className="text-3xl font-black text-white">Das warst du.</h2>
        </div>

        <div className="w-full grid grid-cols-2 gap-3">
          {[
            { label: "Focus", value: fmtHours(stats.totalFocusMinutes), color: "text-violet-300" },
            { label: "Tasks", value: String(stats.tasksCompleted), color: "text-emerald-300" },
            { label: "Achievements", value: String(stats.achievementsUnlocked), color: "text-amber-300" },
            { label: "Journal", value: String(stats.journalEntries), color: "text-sky-300" },
            {
              label: "Net PnL",
              value: fmtMoney(stats.netProfit, true),
              color: stats.netProfit >= 0 ? "text-emerald-300" : "text-red-300",
            },
            { label: "Aktive Tage", value: String(stats.totalDaysActive), color: "text-white/80" },
          ].map(({ label, value, color }) => (
            <div key={label} className="rounded-2xl bg-white/[0.05] border border-white/[0.07] p-4 text-center">
              <p className={cn("text-lg font-black tabular-nums leading-tight", color)}>{value}</p>
              <p className="text-white/35 text-xs mt-0.5">{label}</p>
            </div>
          ))}
        </div>

        <div className="flex items-center gap-2 mt-2">
          <Flame className="w-4 h-4 text-orange-400" />
          <p className="text-white/50 text-sm">
            {stats.longestStreak} Tage längster Streak
          </p>
        </div>

        <p className="text-white/20 text-xs">mindavio.app · {year}</p>
      </div>
    </SlideWrapper>
  );
}

/* ── Main page ──────────────────────────────────────────────────────────── */

export default function WrappedPage() {
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((s) => s.activeTeamId);
  const initialized  = useWorkspaceStore((s) => s.initialized);
  const focusHistory = useFocusStore((s) => s.focusReviewHistory);

  const [stats,   setStats]   = useState<WrappedStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [slide,   setSlide]   = useState(0);
  const [year,    setYear]    = useState(() => new Date().getFullYear());
  const [exporting, setExporting] = useState(false);
  const slideRef = useRef<HTMLDivElement>(null);

  const fetchStats = useCallback(async () => {
    if (!initialized) return;
    setLoading(true);

    const yearStart = `${year}-01-01`;
    const yearEnd   = `${year}-12-31`;

    let tasksQuery = supabase
      .from("tasks")
      .select("id,completed_at,status")
      .eq("status", "done")
      .gte("completed_at", yearStart)
      .lte("completed_at", `${yearEnd}T23:59:59`);

    let achievementsQuery = supabase
      .from("achievements")
      .select("id,title,icon,completed_at,status")
      .eq("status", "completed")
      .gte("completed_at", yearStart)
      .lte("completed_at", `${yearEnd}T23:59:59`);

    // finance_transactions uses user_id + RLS — no team_id column exists
    const financeQuery = supabase
      .from("finance_transactions")
      .select("id,type,amount_cents,transaction_date")
      .gte("transaction_date", yearStart)
      .lte("transaction_date", yearEnd);

    if (activeTeamId) {
      tasksQuery = tasksQuery.eq("team_id", activeTeamId);
      achievementsQuery = achievementsQuery.eq("team_id", activeTeamId);
    } else {
      tasksQuery = tasksQuery.is("team_id", null);
      achievementsQuery = achievementsQuery.is("team_id", null);
    }

    const [
      { data: tasks },
      { data: achievements },
      { data: journals },
      { data: finance },
    ] = await Promise.all([
      tasksQuery,
      achievementsQuery,
      supabase.from("journal_entries").select("id,entry_date,mood").gte("entry_date", yearStart).lte("entry_date", yearEnd),
      financeQuery,
    ]);
    const taskRows = (tasks || []) as WrappedTaskRow[];
    const achievementRows = (achievements || []) as WrappedAchievementRow[];
    const journalRows = (journals || []) as WrappedJournalRow[];
    const financeRows = (finance || []) as WrappedFinanceRow[];

    // Focus stats from store (filtered by year)
    const yearFocusSessions = focusHistory.filter(r => {
      const d = new Date(r.endedAt);
      return d.getFullYear() === year;
    });
    const totalFocusMinutes = Math.round(yearFocusSessions.reduce((s, r) => s + r.workDuration, 0) / 60_000);

    // Longest streak from store
    let longestStreak = 0, currentStreak = 0;
    const focusDays = Array.from(new Set(yearFocusSessions.map(r => new Date(r.endedAt).toISOString().split("T")[0]))).sort();
    for (let i = 0; i < focusDays.length; i++) {
      if (i === 0) { currentStreak = 1; continue; }
      const prev = new Date(focusDays[i-1]);
      const curr = new Date(focusDays[i]);
      const diff = (curr.getTime() - prev.getTime()) / 86_400_000;
      currentStreak = diff === 1 ? currentStreak + 1 : 1;
      if (currentStreak > longestStreak) longestStreak = currentStreak;
    }
    if (currentStreak > longestStreak) longestStreak = currentStreak;

    // Best focus day
    const focusByDay: Record<string, number> = {};
    yearFocusSessions.forEach(r => {
      const d = new Date(r.endedAt).toISOString().split("T")[0];
      focusByDay[d] = (focusByDay[d] || 0) + r.workDuration;
    });
    const bestFocusDay = Object.entries(focusByDay).sort((a,b) => b[1]-a[1])[0]?.[0] ?? null;

    // Tasks
    const tasksByDay: Record<string, number> = {};
    taskRows.forEach((t) => {
      if (!t.completed_at) return;
      const d = t.completed_at.split("T")[0];
      tasksByDay[d] = (tasksByDay[d] || 0) + 1;
    });
    const bestProductivityDay = Object.entries(tasksByDay).sort((a,b) => b[1]-a[1])[0]?.[0] ?? null;

    // Top achievement
    const sorted = [...achievementRows].sort((a, b) => new Date(b.completed_at ?? 0).getTime() - new Date(a.completed_at ?? 0).getTime());
    const topAchievement = sorted[0]?.title ?? null;
    const topAchievementIcon = sorted[0]?.icon ?? null;

    // Journal mood frequency
    const moodCount: Record<string, number> = {};
    journalRows.forEach((j) => {
      if (j.mood) moodCount[j.mood] = (moodCount[j.mood] || 0) + 1;
    });
    const topMood = Object.entries(moodCount).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
    const bestMoodDay = journalRows.find((j) => j.mood === "great")?.entry_date ?? null;

    // Finance
    const totalIncome   = financeRows.filter((t) => t.type === "income").reduce((s, t) => s + t.amount_cents, 0);
    const totalExpenses = financeRows.filter((t) => t.type === "expense").reduce((s, t) => s + t.amount_cents, 0);

    // Days active
    const activeDays = new Set([
      ...Object.keys(focusByDay),
      ...Object.keys(tasksByDay),
      ...journalRows.map((j) => j.entry_date),
    ]);

    setStats({
      totalFocusMinutes,
      focusSessions: yearFocusSessions.length,
      longestStreak,
      bestFocusDay,
      tasksCompleted: taskRows.length,
      bestProductivityDay,
      achievementsUnlocked: achievementRows.length,
      topAchievement,
      topAchievementIcon,
      journalEntries: journalRows.length,
      bestMoodDay,
      topMood,
      totalIncome,
      totalExpenses,
      netProfit: totalIncome - totalExpenses,
      totalDaysActive: activeDays.size,
      year,
    });
    setLoading(false);
  }, [activeTeamId, focusHistory, initialized, supabase, year]);

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

  const currentSlideId = SLIDES[slide];
  const total = SLIDES.length;

  async function handleExport() {
    if (!slideRef.current) return;
    setExporting(true);
    try {
      const url = await toPng(slideRef.current, { pixelRatio: 3 });
      const a = document.createElement("a");
      a.href = url;
      a.download = `mindavio-wrapped-${year}-${currentSlideId}.png`;
      a.click();
    } finally {
      setExporting(false);
    }
  }

  function renderSlide() {
    if (!stats) return null;
    switch (currentSlideId) {
      case "intro":        return <IntroSlide stats={stats} year={year} />;
      case "focus":        return <FocusSlide stats={stats} />;
      case "tasks":        return <TasksSlide stats={stats} />;
      case "achievements": return <AchievementsSlide stats={stats} />;
      case "journal":      return <JournalSlide stats={stats} />;
      case "finance":      return <FinanceSlide stats={stats} />;
      case "legend":       return <LegendSlide stats={stats} year={year} />;
    }
  }

  return (
    <div className="min-h-full bg-[#0a0a0d] text-white flex flex-col items-center justify-center px-4 py-12">

      {/* Year selector */}
      <div className="flex items-center gap-3 mb-8">
        {[new Date().getFullYear() - 1, new Date().getFullYear()].map(y => (
          <button key={y} onClick={() => { setYear(y); setSlide(0); }}
            className={cn(
              "px-4 py-1.5 rounded-full text-sm font-bold border transition-all",
              year === y
                ? "border-white/20 bg-white/10 text-white"
                : "border-white/[0.06] bg-transparent text-white/30 hover:text-white/60",
            )}>
            {y}
          </button>
        ))}
      </div>

      {/* Slide container */}
      <div className="w-full max-w-sm">
        {/* Progress dots */}
        <div className="flex gap-1.5 mb-4 justify-center">
          {SLIDES.map((_, i) => (
            <button key={i} onClick={() => setSlide(i)}
              className={cn(
                "h-1 rounded-full transition-all",
                i === slide ? "bg-white w-6" : "bg-white/20 w-1.5",
              )} />
          ))}
        </div>

        {/* Slide */}
        <div ref={slideRef}>
          {loading ? (
            <div className="flex items-center justify-center min-h-[520px] rounded-[32px] bg-white/[0.03] border border-white/[0.05]">
              <div className="text-white/30 text-sm">Lädt…</div>
            </div>
          ) : renderSlide()}
        </div>

        {/* Navigation */}
        <div className="flex items-center justify-between mt-5">
          <button
            onClick={() => setSlide(s => Math.max(0, s - 1))}
            disabled={slide === 0}
            className="w-10 h-10 rounded-xl border border-white/[0.08] bg-white/[0.04] flex items-center justify-center text-white/40 hover:text-white/70 disabled:opacity-20 transition-all">
            <ChevronLeft className="w-5 h-5" />
          </button>

          <button onClick={handleExport} disabled={loading || exporting}
            className="flex items-center gap-2 px-4 py-2 rounded-xl border border-white/[0.08] bg-white/[0.04] text-white/50 text-sm hover:text-white/80 hover:bg-white/[0.07] transition-all disabled:opacity-30">
            <Download className="w-4 h-4" />
            {exporting ? "…" : "Speichern"}
          </button>

          <button
            onClick={() => setSlide(s => Math.min(total - 1, s + 1))}
            disabled={slide === total - 1}
            className="w-10 h-10 rounded-xl border border-white/[0.08] bg-white/[0.04] flex items-center justify-center text-white/40 hover:text-white/70 disabled:opacity-20 transition-all">
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>

        <p className="text-center text-white/15 text-xs mt-3">{slide + 1} / {total}</p>
      </div>
    </div>
  );
}
