"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  Rocket,
  Sparkles,
  AlertTriangle,
  CheckCircle2,
  Clock,
  CalendarDays,
  Bot,
  Zap,
  FileText,
  ArrowRight,
  Brain,
  BookOpen,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { createClient, getBrowserUser } from "@/lib/supabase/client";
import { getHabitStreak } from "@/lib/habits";
import { isTaskDeadlineDueToday, isTaskDeadlineOverdue } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { FocusModeCard } from "@/components/dashboard/focus-mode-card";
import { TasksToday } from "@/components/dashboard/tasks-today";
import { UpcomingEvents } from "@/components/dashboard/upcoming-events";
import { PinnedNotes } from "@/components/dashboard/pinned-notes";
import { HabitProgress } from "@/components/dashboard/habit-progress";
import { JournalToday } from "@/components/dashboard/journal-today";
import { GoalsWidget } from "@/components/dashboard/goals-widget";
import { AffirmationReminder } from "@/components/dashboard/affirmation-reminder";
import { OnboardingChecklist } from "@/components/dashboard/onboarding-checklist";
import { AchievementRewardsWidget } from "@/components/dashboard/achievement-rewards-widget";
import { useAchievements } from "@/hooks/use-achievements";
import type { Task, CalendarEvent, HabitCompletion } from "@/types";
import { useFocusStore } from "@/stores/focus-store";
import { useWorkspaceStore } from "@/stores/workspace-store";

interface PinnedNote {
  id: string;
  title: string;
  preview: string;
}

interface HabitItem {
  id: string;
  name: string;
  icon: string;
  color: string;
}

interface GoalItem {
  id: string;
  title: string;
  icon: string;
  color: string;
  progress: number;
  completed: boolean;
}

const PRIORITY_RANK: Record<string, number> = {
  urgent: 4,
  high: 3,
  medium: 2,
  low: 1,
  none: 0,
};

function rankTaskForFocus(task: Task) {
  const deadlineTime = task.deadline ? new Date(task.deadline).getTime() : null;
  const now = new Date();
  const isOverdue = task.deadline ? isTaskDeadlineOverdue(task.deadline, now) : false;
  const overdueBoost = isOverdue ? 1000 : 0;
  const dueTodayBoost =
    task.deadline && isTaskDeadlineDueToday(task.deadline, now) && !isOverdue ? 500 : 0;
  const priorityBoost = (PRIORITY_RANK[task.priority] || 0) * 100;

  return overdueBoost + dueTodayBoost + priorityBoost - (deadlineTime || Number.MAX_SAFE_INTEGER) / 1_000_000_000;
}

export default function DashboardPage() {
  const router       = useRouter();
  const searchParams = useSearchParams();
  const focusMode    = searchParams.get("focus") === "1";
  const [loading, setLoading] = useState(true);
  const [todayTasks, setTodayTasks] = useState<Task[]>([]);
  const [focusTasks, setFocusTasks] = useState<Task[]>([]);
  const [focusAutoGenerated, setFocusAutoGenerated] = useState(true);
  const [openTasks, setOpenTasks] = useState<Task[]>([]);
  const [completedCount, setCompletedCount] = useState(0);
  const [overdueCount, setOverdueCount] = useState(0);
  const [reviewQueueCount, setReviewQueueCount] = useState(0);
  const [approvalQueueCount, setApprovalQueueCount] = useState(0);
  const [upcomingEvents, setUpcomingEvents] = useState<CalendarEvent[]>([]);
  const [pinnedNotes, setPinnedNotes] = useState<PinnedNote[]>([]);
  const [habits, setHabits] = useState<HabitItem[]>([]);
  const [habitCompletions, setHabitCompletions] = useState<Set<string>>(new Set());
  const [habitHistory, setHabitHistory] = useState<
    Array<Pick<HabitCompletion, "habit_id" | "completed_date">>
  >([]);
  const [journalEntry, setJournalEntry] = useState<{
    exists: boolean;
    mood?: string | null;
    preview?: string;
  }>({ exists: false });
  const [goals, setGoals] = useState<GoalItem[]>([]);
  const [affirmations, setAffirmations] = useState<{ id: string; text: string }[]>([]);
  const [seeding, setSeeding] = useState(false);
  const [hasProjects, setHasProjects] = useState(true);
  const [quickNote, setQuickNote] = useState("");
  const [quickNoteSaving, setQuickNoteSaving] = useState(false);
  const [quickNoteSaved, setQuickNoteSaved] = useState(false);

  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);
  const focusActive = useFocusStore((state) => state.focusActive);
  const {
    achievements,
    claimAchievementReward,
    loading: achievementsLoading,
  } = useAchievements();

  const fetchData = useCallback(async () => {
    if (!initialized) return;

    const now = new Date();
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).toISOString();
    const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).toISOString();
    const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7).toISOString();
    const todayDate = now.toISOString().split("T")[0];
    const habitHistoryStart = new Date(now);
    habitHistoryStart.setDate(habitHistoryStart.getDate() - 364);
    const habitHistoryStartDate = habitHistoryStart.toISOString().split("T")[0];

    const openTasksQuery = activeTeamId
      ? supabase
          .from("tasks")
          .select("*")
          .eq("team_id", activeTeamId)
          .is("parent_task_id", null)
          .in("status", ["todo", "in_progress"])
          .order("is_focus", { ascending: false })
          .order("focus_order")
          .order("deadline", { ascending: true, nullsFirst: false })
          .order("created_at", { ascending: false })
          .limit(50)
      : supabase
          .from("tasks")
          .select("*")
          .is("team_id", null)
          .is("parent_task_id", null)
          .in("status", ["todo", "in_progress"])
          .order("is_focus", { ascending: false })
          .order("focus_order")
          .order("deadline", { ascending: true, nullsFirst: false })
          .order("created_at", { ascending: false })
          .limit(50);

    const completedTasksQuery = activeTeamId
      ? supabase
          .from("tasks")
          .select("id", { count: "exact" })
          .eq("team_id", activeTeamId)
          .eq("status", "done")
          .gte("completed_at", todayStart)
          .lt("completed_at", todayEnd)
      : supabase
          .from("tasks")
          .select("id", { count: "exact" })
          .is("team_id", null)
          .eq("status", "done")
          .gte("completed_at", todayStart)
          .lt("completed_at", todayEnd);

    const eventsQuery = activeTeamId
      ? supabase
          .from("events")
          .select("*")
          .eq("team_id", activeTeamId)
          .gte("start_time", todayStart)
          .lte("start_time", weekEnd)
          .order("start_time")
          .limit(10)
      : supabase
          .from("events")
          .select("*")
          .is("team_id", null)
          .gte("start_time", todayStart)
          .lte("start_time", weekEnd)
          .order("start_time")
          .limit(10);

    const reviewQueueQuery = activeTeamId
      ? supabase
          .from("tasks")
          .select("id", { count: "exact", head: true })
          .eq("team_id", activeTeamId)
          .eq("review_status", "pending_review")
      : supabase
          .from("tasks")
          .select("id", { count: "exact", head: true })
          .is("team_id", null)
          .eq("review_status", "pending_review");

    const approvalQueueQuery = activeTeamId
      ? supabase
          .from("projects")
          .select("id", { count: "exact", head: true })
          .eq("team_id", activeTeamId)
          .eq("approval_status", "pending_approval")
      : supabase
          .from("projects")
          .select("id", { count: "exact", head: true })
          .is("team_id", null)
          .eq("approval_status", "pending_approval");

    const pinnedNotesQuery = activeTeamId
      ? supabase
          .from("notes")
          .select("id, title, content")
          .eq("team_id", activeTeamId)
          .eq("is_pinned", true)
          .order("updated_at", { ascending: false })
          .limit(4)
      : supabase
          .from("notes")
          .select("id, title, content")
          .is("team_id", null)
          .eq("is_pinned", true)
          .order("updated_at", { ascending: false })
          .limit(4);

    const goalsQuery = activeTeamId
      ? supabase
          .from("goals")
          .select("id, title, icon, color, progress, completed")
          .eq("team_id", activeTeamId)
          .order("completed")
          .order("sort_order")
          .limit(10)
      : supabase
          .from("goals")
          .select("id, title, icon, color, progress, completed")
          .is("team_id", null)
          .order("completed")
          .order("sort_order")
          .limit(10);

    const [tasksRes, completedRes, eventsRes, notesRes, habitsRes, completionsRes, habitHistoryRes, journalRes, goalsRes, affRes, reviewQueueRes, approvalQueueRes] =
      await Promise.all([
        openTasksQuery,
        completedTasksQuery,
        eventsQuery,
        pinnedNotesQuery,
        supabase.from("habits").select("id, name, icon, color").eq("archived", false).order("sort_order"),
        supabase.from("habit_completions").select("habit_id").eq("completed_date", todayDate),
        supabase
          .from("habit_completions")
          .select("habit_id, completed_date")
          .gte("completed_date", habitHistoryStartDate)
          .lte("completed_date", todayDate),
        supabase.from("journal_entries").select("mood, content").eq("entry_date", todayDate).maybeSingle(),
        goalsQuery,
        supabase.from("affirmations").select("id, text").order("sort_order").limit(10),
        reviewQueueQuery,
        approvalQueueQuery,
      ]);

    const allOpen = (tasksRes.data || []) as Task[];
    const dueToday = allOpen.filter(
      (task: Task) => task.deadline && isTaskDeadlineDueToday(task.deadline)
    );
    const overdue = allOpen.filter(
      (task: Task) => task.deadline && isTaskDeadlineOverdue(task.deadline)
    );
    const pinnedFocus = [...allOpen]
      .filter((task) => task.is_focus)
      .sort((a, b) => a.focus_order - b.focus_order || a.created_at.localeCompare(b.created_at));
    const autoFocus = [...allOpen]
      .sort((a, b) => rankTaskForFocus(b) - rankTaskForFocus(a))
      .slice(0, 3);

    setTodayTasks(dueToday.length > 0 ? dueToday : allOpen.slice(0, 6));
    setFocusTasks((pinnedFocus.length > 0 ? pinnedFocus : autoFocus).slice(0, 3));
    setFocusAutoGenerated(pinnedFocus.length === 0);
    setOpenTasks(allOpen);
    setCompletedCount(completedRes.count || 0);
    setOverdueCount(overdue.length);
    setReviewQueueCount(reviewQueueRes.count || 0);
    setApprovalQueueCount(approvalQueueRes.count || 0);
    setUpcomingEvents(eventsRes.data || []);

    const notes: PinnedNote[] = ((notesRes.data || []) as Array<{ id: string; title: string; content: Record<string, unknown> }>).map((n) => {
      let preview = "";
      try {
        const doc = n.content as { content?: Array<{ content?: Array<{ text?: string }> }> };
        if (doc?.content) {
          for (const block of doc.content) {
            if (block.content) {
              for (const inline of block.content) {
                if (inline.text) preview += inline.text + " ";
              }
            }
            if (preview.length > 80) break;
          }
        }
      } catch {}
      return { id: n.id, title: n.title, preview: preview.trim().slice(0, 100) };
    });
    setPinnedNotes(notes);
    setHabits(habitsRes.data || []);
    setHabitCompletions(new Set((completionsRes.data || []).map((c: { habit_id: string }) => c.habit_id)));
    setHabitHistory(
      ((habitHistoryRes.data || []) as Array<Pick<HabitCompletion, "habit_id" | "completed_date">>),
    );

    if (journalRes.data) {
      let preview = "";
      try {
        const doc = journalRes.data.content as { content?: Array<{ content?: Array<{ text?: string }> }> };
        if (doc?.content) {
          for (const block of doc.content) {
            if (block.content) {
              for (const inline of block.content) {
                if (inline.text) preview += inline.text + " ";
              }
            }
            if (preview.length > 80) break;
          }
        }
      } catch {}
      setJournalEntry({ exists: true, mood: journalRes.data.mood, preview: preview.trim().slice(0, 120) });
    } else {
      setJournalEntry({ exists: false });
    }

    setGoals(goalsRes.data || []);
    setAffirmations(affRes.data || []);

    const projectsCountQuery = activeTeamId
      ? supabase
          .from("projects")
          .select("id", { count: "exact", head: true })
          .eq("team_id", activeTeamId)
      : supabase
          .from("projects")
          .select("id", { count: "exact", head: true })
          .is("team_id", null);
    const { count } = await projectsCountQuery;
    setHasProjects((count || 0) > 0);

    setLoading(false);
  }, [activeTeamId, initialized, supabase]);

  useEffect(() => {
    if (!initialized) return;
    const timer = window.setTimeout(() => { void fetchData(); }, 0);
    return () => window.clearTimeout(timer);
  }, [fetchData, initialized]);

  useEffect(() => {
    if (!focusMode) return;
    router.replace("/focus");
  }, [focusMode, router]);

  async function handleToggleTask(id: string, currentStatus: string) {
    const newStatus = currentStatus === "done" ? "todo" : "done";
    await supabase.from("tasks").update({ status: newStatus, completed_at: newStatus === "done" ? new Date().toISOString() : null }).eq("id", id);
    fetchData();
  }

  async function handleToggleFocus(task: Task) {
    const nextIsFocus = !task.is_focus;
    const maxFocusOrder = openTasks.filter((c) => c.is_focus).reduce((max, c) => Math.max(max, c.focus_order), 0);
    await supabase.from("tasks").update({ is_focus: nextIsFocus, focus_order: nextIsFocus ? maxFocusOrder + 1 : 0 }).eq("id", task.id);
    fetchData();
  }

  async function handleToggleHabit(habitId: string) {
    const todayDate = new Date().toISOString().split("T")[0];
    const isDone = habitCompletions.has(habitId);
    if (isDone) {
      await supabase.from("habit_completions").delete().eq("habit_id", habitId).eq("completed_date", todayDate);
      setHabitCompletions((prev) => { const next = new Set(prev); next.delete(habitId); return next; });
      setHabitHistory((prev) =>
        prev.filter(
          (completion) =>
            !(completion.habit_id === habitId && completion.completed_date === todayDate),
        ),
      );
    } else {
      const user = await getBrowserUser();
      if (!user) return;
      await supabase.from("habit_completions").insert({ habit_id: habitId, user_id: user.id, completed_date: todayDate });
      setHabitCompletions((prev) => new Set(prev).add(habitId));
      setHabitHistory((prev) => {
        if (
          prev.some(
            (completion) =>
              completion.habit_id === habitId && completion.completed_date === todayDate,
          )
        ) {
          return prev;
        }
        return [...prev, { habit_id: habitId, completed_date: todayDate }];
      });
    }
  }

  async function handleQuickNote() {
    const text = quickNote.trim();
    if (!text || quickNoteSaving) return;
    setQuickNoteSaving(true);
    const user = await getBrowserUser();
    if (!user) { setQuickNoteSaving(false); return; }
    const title = text.split("\n")[0].slice(0, 80) || "Schnellnotiz";
    const body = JSON.stringify({
      type: "doc",
      content: [{ type: "paragraph", content: [{ type: "text", text }] }],
    });
    const { data } = await supabase
      .from("notes")
      .insert({ title, content: JSON.parse(body), user_id: user.id, team_id: activeTeamId ?? null })
      .select("id")
      .single();
    setQuickNoteSaving(false);
    setQuickNote("");
    setQuickNoteSaved(true);
    setTimeout(() => setQuickNoteSaved(false), 2000);
    if (data?.id) router.push(`/notes/${data.id}`);
  }

  if (loading) {
    return (
      <div className="min-h-full">
        <div className="border-b border-white/[0.04] px-6 py-4">
          <div className="mx-auto max-w-[1280px] flex items-center justify-between">
            <Skeleton className="h-5 w-44 rounded-lg bg-muted/50" />
            <Skeleton className="h-9 w-28 rounded-lg bg-muted/40" />
          </div>
        </div>
        <div className="mx-auto max-w-[1280px] px-6 py-6 space-y-5">
          <Skeleton className="h-[96px] rounded-2xl bg-muted/30" />
          <Skeleton className="h-[52px] rounded-2xl bg-muted/20" />
          <div className="grid gap-5 lg:grid-cols-3">
            <div className="lg:col-span-2 space-y-4">
              <Skeleton className="h-[180px] rounded-2xl bg-muted/30" />
              <Skeleton className="h-[220px] rounded-2xl bg-muted/30" />
              <Skeleton className="h-[160px] rounded-2xl bg-muted/30" />
            </div>
            <div className="space-y-4">
              <Skeleton className="h-[180px] rounded-2xl bg-muted/30" />
              <Skeleton className="h-[160px] rounded-2xl bg-muted/30" />
              <Skeleton className="h-[120px] rounded-2xl bg-muted/30" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  const todayEventsCount = upcomingEvents.filter((e) => {
    const start = new Date(e.start_time);
    const now = new Date();
    return start.getFullYear() === now.getFullYear() && start.getMonth() === now.getMonth() && start.getDate() === now.getDate();
  }).length;

  const tasksDueToday = openTasks.filter((t) => {
    if (!t.deadline) return false;
    const d = new Date(t.deadline);
    const now = new Date();
    return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate();
  }).length;

  const habitStreaks = habits.reduce<Record<string, number>>((acc, habit) => {
    acc[habit.id] = getHabitStreak(
      habitHistory
        .filter((completion) => completion.habit_id === habit.id)
        .map((completion) => completion.completed_date),
    );
    return acc;
  }, {});

  const habitsCompletedToday = habits.filter((h) => habitCompletions.has(h.id)).length;

  const todayFormatted = new Date().toLocaleDateString("de-DE", { weekday: "long", day: "numeric", month: "long" });

  function handleFocusAction() {
    router.push("/focus");
  }

  return (
    <div className="min-h-full bg-background text-foreground">

      <div className="mx-auto max-w-[1280px] px-6 py-5 space-y-5">

        {/* ── Morning Brief ────────────────────────────────────────────── */}
        <div className="relative overflow-hidden rounded-2xl border border-white/[0.05] bg-gradient-to-br from-indigo-500/[0.07] via-background to-background p-5">
          <div className="absolute inset-0 pointer-events-none">
            <div className="absolute -top-1/2 -left-1/4 w-1/2 h-full rounded-full opacity-[0.05] blur-3xl" style={{ background: "radial-gradient(circle, #6366f1, transparent 70%)" }} />
          </div>
          <div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-indigo-400/50">Dein Tag</p>
              <h2 className="mt-1 text-[24px] font-bold tracking-tight text-white">{getGreeting()} 👋</h2>
              <p className="mt-0.5 text-[13px] text-white/35">{todayFormatted}</p>
              <div className="mt-3 flex items-center gap-2">
                <button
                  onClick={handleFocusAction}
                  className={`flex items-center gap-2 rounded-xl border px-3.5 py-2 text-[12px] font-semibold transition-all cursor-pointer ${
                    focusActive
                      ? "border-violet-500/40 bg-violet-500/15 text-violet-300 shadow-lg shadow-violet-500/10"
                      : "border-violet-500/20 bg-violet-500/[0.07] text-violet-400/80 hover:border-violet-400/30 hover:bg-violet-500/[0.12]"
                  }`}
                >
                  <Zap className="h-3.5 w-3.5" />
                  {focusActive ? "Focus Center" : "Focus Mode"}
                </button>
                <button
                  onClick={() => router.push("/ai")}
                  className="flex items-center gap-2 rounded-xl border border-indigo-500/20 bg-indigo-500/[0.07] px-3.5 py-2 text-[12px] font-semibold text-indigo-400/80 transition-all hover:border-indigo-500/30 hover:bg-indigo-500/10 cursor-pointer"
                >
                  <Bot className="h-3.5 w-3.5" />
                  Ask AI
                </button>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <MorningBriefStat
                icon={<Clock className="h-3.5 w-3.5" />}
                label="Fällig"
                value={tasksDueToday}
                colorClass="text-sky-400"
                bgClass="bg-sky-500/10"
                onClick={() => router.push("/tasks")}
              />
              <MorningBriefStat
                icon={<CalendarDays className="h-3.5 w-3.5" />}
                label="Events"
                value={todayEventsCount}
                colorClass="text-violet-400"
                bgClass="bg-violet-500/10"
                onClick={() => router.push("/calendar")}
              />
              <MorningBriefStat
                icon={<CheckCircle2 className="h-3.5 w-3.5" />}
                label="Erledigt"
                value={completedCount}
                colorClass="text-emerald-400"
                bgClass="bg-emerald-500/10"
                onClick={() => router.push("/tasks?filter=done")}
              />
              {overdueCount > 0 && (
                <MorningBriefStat
                  icon={<AlertTriangle className="h-3.5 w-3.5" />}
                  label="Überfällig"
                  value={overdueCount}
                  colorClass="text-red-400"
                  bgClass="bg-red-500/10"
                  onClick={() => router.push("/tasks?filter=overdue")}
                />
              )}
            </div>
          </div>
        </div>

        {/* ── Setup Banner ─────────────────────────────────────────────── */}
        {!hasProjects && activeTeamId === null && (
          <div className="relative overflow-hidden rounded-2xl border border-indigo-500/15 bg-gradient-to-br from-indigo-500/[0.06] to-violet-500/[0.04] p-8 text-center">
            <div className="absolute inset-0 pointer-events-none">
              <div className="absolute -top-[30%] left-[20%] w-[50%] h-[80%] rounded-full opacity-[0.06] blur-3xl" style={{ background: "radial-gradient(circle, #6366f1, transparent 70%)" }} />
            </div>
            <div className="relative">
              <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-indigo-500/20 to-violet-500/20 flex items-center justify-center mx-auto mb-4 ring-1 ring-indigo-500/15">
                <Rocket className="h-5 w-5 text-indigo-400" />
              </div>
              <h3 className="text-[15px] font-bold tracking-tight text-white mb-1.5">Starte deinen Plan</h3>
              <p className="text-[13px] text-white/40 mb-5 max-w-sm mx-auto leading-relaxed">
                Lade deinen personalisierten Plan mit Projekten, Tasks, Habits und Journal-Vorlage.
              </p>
              <Button
                onClick={async () => { setSeeding(true); await fetch("/api/seed-plan", { method: "POST" }); setSeeding(false); setHasProjects(true); fetchData(); }}
                disabled={seeding}
                className="rounded-xl px-5 h-9 bg-gradient-to-r from-indigo-500 to-violet-500 hover:from-indigo-600 hover:to-violet-600 text-white border-0 text-[13px] shadow-lg shadow-indigo-500/20"
              >
                <Rocket className="h-3.5 w-3.5" />
                {seeding ? "Wird erstellt…" : "Plan erstellen"}
              </Button>
            </div>
          </div>
        )}

        <OnboardingChecklist />

        {/* ── AI Command Center CTA ─────────────────────────────────────── */}
        <button
          type="button"
          onClick={() => router.push("/command-center")}
          className="group relative w-full overflow-hidden rounded-[20px] border border-cyan-500/15 bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.10),rgba(124,58,237,0.05)_42%,rgba(255,255,255,0.01)_100%)] px-5 py-4 text-left transition-all hover:border-cyan-400/25 hover:bg-cyan-500/[0.04]"
        >
          <div className="flex items-center gap-4">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-cyan-500/10 ring-1 ring-cyan-500/15">
              <Sparkles className="h-4 w-4 text-cyan-300" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-cyan-200/50">AI Daily Command Center</p>
              <p className="mt-0.5 text-[14px] font-bold tracking-tight text-white">Öffne dein Personal OS für heute</p>
            </div>
            <div className="hidden sm:flex items-center gap-2 shrink-0">
              <CommandMiniStat label="Due" value={tasksDueToday} />
              <CommandMiniStat label="Overdue" value={overdueCount} danger={overdueCount > 0} />
              <CommandMiniStat label="Done" value={completedCount} />
            </div>
            <ArrowRight className="h-4 w-4 text-white/20 group-hover:text-cyan-400/50 transition-colors shrink-0" />
          </div>
        </button>

        {/* ── Quick Capture ─────────────────────────────────────────────── */}
        <div className="relative overflow-hidden rounded-2xl border border-white/[0.05] bg-white/[0.02]">
          <div className="flex items-center gap-3 px-4 py-3 border-b border-white/[0.04]">
            <FileText className="h-3.5 w-3.5 text-indigo-400/60 shrink-0" />
            <span className="text-[11px] font-bold uppercase tracking-[0.16em] text-white/20">Schnell erfassen</span>
            <div className="ml-auto flex items-center gap-2">
              <button
                onClick={() => router.push("/notes")}
                className="flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[11px] text-white/25 transition-colors hover:bg-white/[0.05] hover:text-white/60 cursor-pointer"
              >
                Alle Notes <ArrowRight className="h-3 w-3" />
              </button>
              <button
                onClick={() => router.push("/mind-map")}
                className="flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-[11px] text-white/25 transition-colors hover:bg-white/[0.05] hover:text-white/60 cursor-pointer"
              >
                Mind Map <Brain className="h-3 w-3" />
              </button>
            </div>
          </div>
          <div className="flex items-end gap-3 p-4">
            <textarea
              value={quickNote}
              onChange={(e) => setQuickNote(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void handleQuickNote(); }}
              placeholder="Gedanke, Idee oder Notiz… (⌘↵ zum Speichern)"
              rows={2}
              className="flex-1 resize-none rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3 text-[13px] text-white/70 placeholder:text-white/20 outline-none focus:border-indigo-500/30 focus:ring-1 focus:ring-indigo-500/15 transition-all"
            />
            <button
              onClick={() => void handleQuickNote()}
              disabled={!quickNote.trim() || quickNoteSaving}
              className="shrink-0 flex items-center gap-2 rounded-xl bg-indigo-500/90 px-4 py-3 text-[13px] font-semibold text-white shadow-lg shadow-indigo-500/20 transition-all hover:bg-indigo-500 disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
            >
              {quickNoteSaving ? <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" /> : <FileText className="h-4 w-4" />}
              {quickNoteSaved ? "Gespeichert ✓" : "Notiz"}
            </button>
          </div>
        </div>

        {/* ── Two-Column Workspace ──────────────────────────────────────── */}
        <div className="grid gap-5 lg:grid-cols-3">

          {/* Left — Do column (2/3 width) */}
          <div className="lg:col-span-2 space-y-4">
            <ColumnHeader icon={<Zap className="h-3.5 w-3.5" />} label="Heute erledigen" colorClass="text-sky-400/70" />

            <FocusModeCard
              tasks={focusTasks}
              autoGenerated={focusAutoGenerated}
              focusActive={focusActive}
              reviewQueueCount={reviewQueueCount}
              approvalQueueCount={approvalQueueCount}
              overdueCount={overdueCount}
              onFocusAction={handleFocusAction}
              onToggleTask={handleToggleTask}
              onToggleFocus={handleToggleFocus}
            />

            <TasksToday tasks={todayTasks} onToggle={handleToggleTask} onToggleFocus={handleToggleFocus} />

            <GoalsWidget goals={goals} />
          </div>

          {/* Right — Know column (1/3 width) */}
          <div className="space-y-4">
            <ColumnHeader icon={<BookOpen className="h-3.5 w-3.5" />} label="Im Blick behalten" colorClass="text-violet-400/70" />

            <UpcomingEvents events={upcomingEvents} />

            <HabitProgress
              habits={habits}
              completions={habitCompletions}
              streaks={habitStreaks}
              onToggle={handleToggleHabit}
            />

            <JournalToday hasEntry={journalEntry.exists} mood={journalEntry.mood} preview={journalEntry.preview} />

            <PinnedNotes notes={pinnedNotes} />
          </div>

        </div>

        {/* ── Full-width Bottom Row ──────────────────────────────────────── */}
        <div className="grid gap-4 md:grid-cols-2">
          <AchievementRewardsWidget
            achievements={achievements}
            loading={achievementsLoading}
            onClaimReward={claimAchievementReward}
          />
          <AffirmationReminder affirmations={affirmations} />
        </div>

      </div>
    </div>
  );
}

/* ── Column Header ───────────────────────────────────────────────────────── */

function ColumnHeader({ label, colorClass, icon }: { label: string; colorClass: string; icon: React.ReactNode }) {
  return (
    <div className={`flex items-center gap-2 ${colorClass}`}>
      {icon}
      <span className="text-[11px] font-bold uppercase tracking-[0.15em]">{label}</span>
      <div className="h-px flex-1 bg-white/[0.04]" />
    </div>
  );
}

/* ── Morning Brief Stat ──────────────────────────────────────────────────── */

function MorningBriefStat({
  icon,
  label,
  value,
  colorClass,
  bgClass,
  onClick,
}: {
  icon: React.ReactNode;
  label: string;
  value: number;
  colorClass: string;
  bgClass: string;
  onClick?: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className={`flex flex-col items-center gap-1 rounded-2xl border border-white/[0.06] ${bgClass} px-4 py-3 transition-all hover:border-white/[0.1] cursor-pointer min-w-[64px]`}
    >
      <div className={`${colorClass}`}>{icon}</div>
      <p className={`text-[22px] font-bold leading-none ${colorClass}`}>{value}</p>
      <p className="text-[10px] font-medium text-white/35">{label}</p>
    </button>
  );
}

/* ── Command Mini Stat ───────────────────────────────────────────────────── */

function CommandMiniStat({ danger, label, value }: { danger?: boolean; label: string; value: number }) {
  return (
    <div className="rounded-xl border border-border/60 bg-card/80 px-3 py-2">
      <p className="text-[9px] font-bold uppercase tracking-[0.15em] text-muted-foreground/70">{label}</p>
      <p className={`mt-0.5 text-[18px] font-bold leading-none ${danger ? "text-red-400" : "text-foreground"}`}>
        {value}
      </p>
    </div>
  );
}

function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 5) return "Gute Nacht";
  if (hour < 12) return "Guten Morgen";
  if (hour < 17) return "Guten Tag";
  if (hour < 21) return "Guten Abend";
  return "Gute Nacht";
}
