// ╔══════════════════════════════════════════════════════════════════════════╗
// ║  ⚠️  DESIGN LOCKED — DO NOT MODIFY VISUAL STYLES                        ║
// ║                                                                          ║
// ║  This file has been carefully crafted with a premium dark design.        ║
// ║  Codex and automated tools: DO NOT change any of the following:          ║
// ║                                                                          ║
// ║  • border-* classes → use border-{accent}/[0.12–0.15], NEVER            ║
// ║    border-white/[0.06] or higher (creates white outlines on dark bg)     ║
// ║  • ring-* classes → NEVER add ring-1 to icon containers (white ring)     ║
// ║  • bg gradient stops → NEVER use rgba(255,255,255,...) stops              ║
// ║    All section/card gradients must end with opaque dark rgba stops       ║
// ║  • bg-[#0d0b18]/70 → do not lighten backgrounds                          ║
// ║  • ACCENT_STYLES → do not alter border, glow, icon, ring, text values    ║
// ║  • SystemRadar desktop container → keep border-violet-500/[0.12]         ║
// ║    and the inline radial-gradient with dark opaque stops                  ║
// ║  • GoalChain container → keep border-violet-500/[0.14]                   ║
// ║  • Panel → keep border-white/[0.04], NOT /[0.06] or /[0.05]             ║
// ║  • LifeMapNode box-shadow → keep the ${ring}14 accent shadow, no rings   ║
// ║                                                                          ║
// ║  If you need to change LOGIC/DATA only, leave all className values alone.║
// ╚══════════════════════════════════════════════════════════════════════════╝

"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import {
  Activity,
  ArrowRight,
  Award,
  BarChart3,
  BellRing,
  BookOpen,
  CalendarDays,
  CheckCircle2,
  CheckSquare,
  Clock3,
  Compass,
  FolderKanban,
  GitBranch,
  HeartPulse,
  LayoutDashboard,
  Network,
  Target,
  TrendingUp,
  Wallet,
  Zap,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { getAchievementProgressPercent, resolveAchievementStatus } from "@/lib/achievements";
import { getHabitStreak } from "@/lib/habits";
import { createClient } from "@/lib/supabase/client";
import { cn, isSameLocalDay, isTaskDeadlineDueToday, isTaskDeadlineOverdue } from "@/lib/utils";
import { fmtMs, useFocusStore } from "@/stores/focus-store";
import { useWorkspaceStore } from "@/stores/workspace-store";
import type {
  Achievement,
  CalendarEvent,
  FinanceTransaction,
  Goal,
  Habit,
  HabitCompletion,
  JournalEntry,
  Note,
  Project,
  Reminder,
  Task,
} from "@/types";

interface LifeMapData {
  achievements: Achievement[];
  events: CalendarEvent[];
  goals: Goal[];
  habitCompletions: HabitCompletion[];
  habits: Habit[];
  journalEntries: JournalEntry[];
  notes: Note[];
  projects: Project[];
  reminders: Reminder[];
  tasks: Task[];
  transactions: FinanceTransaction[];
}

interface DomainSignal {
  accent: "amber" | "emerald" | "rose" | "sky" | "violet";
  description: string;
  futureCue: string;
  href: string;
  icon: React.ReactNode;
  id: string;
  label: string;
  metric: string;
  score: number;
  signal: string;
}

const EMPTY_DATA: LifeMapData = {
  achievements: [],
  events: [],
  goals: [],
  habitCompletions: [],
  habits: [],
  journalEntries: [],
  notes: [],
  projects: [],
  reminders: [],
  tasks: [],
  transactions: [],
};

const ACCENT_STYLES = {
  amber: {
    border: "border-amber-500/15",
    glow: "shadow-[0_0_50px_rgba(245,158,11,0.10)]",
    gradient: "from-amber-500/18 to-orange-500/5",
    icon: "bg-amber-500/12 text-amber-300",
    ring: "#fbbf24",
    text: "text-amber-300",
  },
  emerald: {
    border: "border-emerald-500/15",
    glow: "shadow-[0_0_50px_rgba(16,185,129,0.10)]",
    gradient: "from-emerald-500/18 to-teal-500/5",
    icon: "bg-emerald-500/12 text-emerald-300",
    ring: "#34d399",
    text: "text-emerald-300",
  },
  rose: {
    border: "border-rose-500/15",
    glow: "shadow-[0_0_50px_rgba(244,63,94,0.10)]",
    gradient: "from-rose-500/18 to-pink-500/5",
    icon: "bg-rose-500/12 text-rose-300",
    ring: "#fb7185",
    text: "text-rose-300",
  },
  sky: {
    border: "border-sky-500/15",
    glow: "shadow-[0_0_50px_rgba(14,165,233,0.10)]",
    gradient: "from-sky-500/18 to-blue-500/5",
    icon: "bg-sky-500/12 text-sky-300",
    ring: "#38bdf8",
    text: "text-sky-300",
  },
  violet: {
    border: "border-violet-500/15",
    glow: "shadow-[0_0_50px_rgba(139,92,246,0.10)]",
    gradient: "from-violet-500/18 to-indigo-500/5",
    icon: "bg-violet-500/12 text-violet-300",
    ring: "#a78bfa",
    text: "text-violet-300",
  },
};

function localDateKey(date = new Date()) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function startOfMonthKey(date = new Date()) {
  return localDateKey(new Date(date.getFullYear(), date.getMonth(), 1));
}

function clampScore(value: number) {
  return Math.max(0, Math.min(100, Math.round(value)));
}

function formatMoney(cents: number) {
  return new Intl.NumberFormat("de-DE", {
    currency: "EUR",
    maximumFractionDigits: 0,
    style: "currency",
  }).format(cents / 100);
}

function average(values: number[]) {
  if (values.length === 0) return 0;
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

export default function LifeMapPage() {
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((state) => state.activeTeamId);
  const initialized = useWorkspaceStore((state) => state.initialized);
  const focusActive = useFocusStore((state) => state.focusActive);
  const focusReviewHistory = useFocusStore((state) => state.focusReviewHistory);
  const lastFocusReview = useFocusStore((state) => state.lastFocusReview);
  const [data, setData] = useState<LifeMapData>(EMPTY_DATA);
  const [loading, setLoading] = useState(true);

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

    setLoading(true);

    const today = localDateKey();
    const monthStart = startOfMonthKey();
    const now = new Date();
    const weekEnd = new Date(now);
    weekEnd.setDate(weekEnd.getDate() + 7);
    const habitStart = new Date(now);
    habitStart.setDate(habitStart.getDate() - 29);

    const tasksQuery = activeTeamId
      ? supabase
          .from("tasks")
          .select("*")
          .eq("team_id", activeTeamId)
          .is("parent_task_id", null)
          .order("updated_at", { ascending: false })
          .limit(160)
      : supabase
          .from("tasks")
          .select("*")
          .is("team_id", null)
          .is("parent_task_id", null)
          .order("updated_at", { ascending: false })
          .limit(160);

    const projectsQuery = activeTeamId
      ? supabase
          .from("projects")
          .select("*")
          .eq("team_id", activeTeamId)
          .order("updated_at", { ascending: false })
          .limit(80)
      : supabase
          .from("projects")
          .select("*")
          .is("team_id", null)
          .order("updated_at", { ascending: false })
          .limit(80);

    const achievementsQuery = activeTeamId
      ? supabase
          .from("achievements")
          .select("*")
          .eq("team_id", activeTeamId)
          .order("updated_at", { ascending: false })
          .limit(80)
      : supabase
          .from("achievements")
          .select("*")
          .is("team_id", null)
          .order("updated_at", { ascending: false })
          .limit(80);

    const goalsQuery = activeTeamId
      ? supabase
          .from("goals")
          .select("*")
          .eq("team_id", activeTeamId)
          .order("sort_order")
          .limit(60)
      : supabase
          .from("goals")
          .select("*")
          .is("team_id", null)
          .order("sort_order")
          .limit(60);

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

    const notesQuery = activeTeamId
      ? supabase
          .from("notes")
          .select("*")
          .eq("team_id", activeTeamId)
          .order("updated_at", { ascending: false })
          .limit(60)
      : supabase
          .from("notes")
          .select("*")
          .is("team_id", null)
          .order("updated_at", { ascending: false })
          .limit(60);

    const remindersQuery = activeTeamId
      ? supabase
          .from("reminders")
          .select("*")
          .eq("team_id", activeTeamId)
          .in("status", ["scheduled", "triggered", "snoozed"])
          .order("remind_at", { ascending: true })
          .limit(50)
      : supabase
          .from("reminders")
          .select("*")
          .is("team_id", null)
          .in("status", ["scheduled", "triggered", "snoozed"])
          .order("remind_at", { ascending: true })
          .limit(50);

    const [
      tasksRes,
      projectsRes,
      achievementsRes,
      goalsRes,
      eventsRes,
      notesRes,
      remindersRes,
      habitsRes,
      habitCompletionsRes,
      journalRes,
      transactionsRes,
    ] = await Promise.all([
      tasksQuery,
      projectsQuery,
      achievementsQuery,
      goalsQuery,
      eventsQuery,
      notesQuery,
      remindersQuery,
      supabase
        .from("habits")
        .select("*")
        .eq("archived", false)
        .order("sort_order")
        .limit(40),
      supabase
        .from("habit_completions")
        .select("*")
        .gte("completed_date", localDateKey(habitStart))
        .lte("completed_date", today),
      supabase
        .from("journal_entries")
        .select("*")
        .gte("entry_date", localDateKey(habitStart))
        .lte("entry_date", today)
        .order("entry_date", { ascending: false })
        .limit(30),
      supabase
        .from("finance_transactions")
        .select("*")
        .gte("transaction_date", monthStart)
        .lte("transaction_date", today)
        .order("transaction_date", { ascending: false })
        .limit(160),
    ]);

    setData({
      achievements: (achievementsRes.data || []) as Achievement[],
      events: (eventsRes.data || []) as CalendarEvent[],
      goals: (goalsRes.data || []) as Goal[],
      habitCompletions: (habitCompletionsRes.data || []) as HabitCompletion[],
      habits: (habitsRes.data || []) as Habit[],
      journalEntries: (journalRes.data || []) as JournalEntry[],
      notes: (notesRes.data || []) as Note[],
      projects: (projectsRes.data || []) as Project[],
      reminders: (remindersRes.data || []) as Reminder[],
      tasks: (tasksRes.data || []) as Task[],
      transactions: (transactionsRes.data || []) as FinanceTransaction[],
    });
    setLoading(false);
  }, [activeTeamId, initialized, supabase]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void loadData();
    }, 0);

    return () => window.clearTimeout(timer);
  }, [loadData]);

  const model = useMemo(() => {
    const now = new Date();
    const today = localDateKey(now);
    const openTasks = data.tasks.filter((task) => task.status !== "done" && task.status !== "cancelled");
    const completedToday = data.tasks.filter(
      (task) => task.status === "done" && task.completed_at && isSameLocalDay(task.completed_at, now),
    );
    const overdueTasks = openTasks.filter((task) => isTaskDeadlineOverdue(task.deadline, now));
    const dueTodayTasks = openTasks.filter((task) => isTaskDeadlineDueToday(task.deadline, now));
    const focusTasks = openTasks.filter((task) => task.is_focus);
    const stuckProjects = data.projects.filter((project) => project.health === "stuck");
    const riskyProjects = data.projects.filter((project) => project.health === "at_risk");
    const activeProjects = data.projects.filter((project) => project.health !== "stuck");
    const completedAchievements = data.achievements.filter(
      (achievement) => resolveAchievementStatus(achievement) === "completed",
    );
    const almostAchievements = data.achievements.filter((achievement) => {
      const pct = getAchievementProgressPercent(achievement);
      return pct >= 70 && resolveAchievementStatus(achievement) !== "completed";
    });
    const avgAchievementProgress = average(data.achievements.map(getAchievementProgressPercent));
    const habitsDoneToday = data.habitCompletions.filter(
      (completion) => completion.completed_date === today,
    );
    const bestHabitStreak = Math.max(
      0,
      ...data.habits.map((habit) =>
        getHabitStreak(
          data.habitCompletions
            .filter((completion) => completion.habit_id === habit.id)
            .map((completion) => completion.completed_date),
        ),
      ),
    );
    const journalToday = data.journalEntries.find((entry) => entry.entry_date === today) || null;
    const latestJournal = data.journalEntries[0] || null;
    const monthIncome = data.transactions
      .filter((transaction) => transaction.type === "income")
      .reduce((sum, transaction) => sum + transaction.amount_cents, 0);
    const monthExpenses = data.transactions
      .filter((transaction) => transaction.type === "expense")
      .reduce((sum, transaction) => sum + transaction.amount_cents, 0);
    const monthNet = monthIncome - monthExpenses;
    const dueReminders = data.reminders.filter((reminder) => {
      const dueAt = reminder.snoozed_until || reminder.remind_at;
      return new Date(dueAt).getTime() <= now.getTime();
    });
    const latestReview = lastFocusReview || focusReviewHistory[0] || null;
    const focusMinutes = latestReview ? Math.round(latestReview.workDuration / 60_000) : 0;
    const executionScore = clampScore(
      48 +
        completedToday.length * 9 +
        focusTasks.length * 4 -
        overdueTasks.length * 12 -
        Math.max(0, openTasks.length - 20) * 1.5,
    );
    const projectScore = clampScore(
      58 + activeProjects.length * 5 - riskyProjects.length * 11 - stuckProjects.length * 18,
    );
    const growthScore = clampScore(
      avgAchievementProgress * 0.55 +
        (data.habits.length ? (habitsDoneToday.length / data.habits.length) * 30 : 10) +
        Math.min(bestHabitStreak, 14),
    );
    const reflectionScore = clampScore(
      (journalToday ? 54 : 18) +
        Math.min(data.journalEntries.length, 7) * 3 +
        Math.min(data.notes.length, 20) * 1.1,
    );
    const controlScore = clampScore(
      58 +
        (monthNet >= 0 ? 18 : -12) +
        Math.min(data.events.length, 8) * 2 -
        dueReminders.length * 10,
    );
    const focusScore = clampScore(
      (focusActive ? 72 : 42) +
        Math.min(focusMinutes, 120) * 0.22 +
        (latestReview?.completedTasks.length || 0) * 5,
    );

    const domains: DomainSignal[] = [
      {
        accent: "sky",
        description: "Tasks, priorities, deadlines and focus selection.",
        futureCue: `${completedToday.length} completions today, ${openTasks.length} active tasks.`,
        href: "/tasks",
        icon: <CheckSquare className="h-4 w-4" />,
        id: "execution",
        label: "Execution Engine",
        metric: `${completedToday.length} done today`,
        score: executionScore,
        signal: overdueTasks.length > 0 ? `${overdueTasks.length} overdue` : `${openTasks.length} open`,
      },
      {
        accent: "violet",
        description: "Projects, goals, milestones and project health.",
        futureCue:
          stuckProjects.length > 0
            ? "Future you needs one unblock decision."
            : "Future you gets leverage from a clear project spine.",
        href: "/projects",
        icon: <FolderKanban className="h-4 w-4" />,
        id: "projects",
        label: "Project Spine",
        metric: `${data.projects.length} projects`,
        score: projectScore,
        signal: stuckProjects.length > 0 ? `${stuckProjects.length} stuck` : `${riskyProjects.length} at risk`,
      },
      {
        accent: "amber",
        description: "Achievements, rewards, habits and identity loops.",
        futureCue: `${completedAchievements.length} achievements completed, ${almostAchievements.length} near unlock.`,
        href: "/achievements",
        icon: <Award className="h-4 w-4" />,
        id: "growth",
        label: "Growth Loop",
        metric: `${completedAchievements.length} completed`,
        score: growthScore,
        signal: `${bestHabitStreak} day best streak`,
      },
      {
        accent: "emerald",
        description: "Journal, notes, mindset and personal signal capture.",
        futureCue: journalToday ? "Future you has context from today's reflection." : "Future you is missing today's context.",
        href: "/journal",
        icon: <BookOpen className="h-4 w-4" />,
        id: "reflection",
        label: "Reflection Layer",
        metric: journalToday ? "journal done" : "journal open",
        score: reflectionScore,
        signal: latestJournal?.mood ? `mood ${latestJournal.mood}` : `${data.notes.length} notes`,
      },
      {
        accent: "rose",
        description: "Money, calendar pressure, reminders and operating constraints.",
        futureCue: `${formatMoney(monthNet)} net this month, ${data.events.length} upcoming events.`,
        href: "/finances",
        icon: <Wallet className="h-4 w-4" />,
        id: "control",
        label: "Control Tower",
        metric: formatMoney(monthNet),
        score: controlScore,
        signal: dueReminders.length > 0 ? `${dueReminders.length} reminders due` : `${data.events.length} events`,
      },
      {
        accent: "violet",
        description: "Focus sessions, deep work rhythm and recent output.",
        futureCue: focusActive
          ? "Future you is already inside a focus block."
          : latestReview
            ? `Future you has ${fmtMs(latestReview.workDuration)} of recent deep work signal.`
            : "Future you needs the first clean focus session.",
        href: "/focus",
        icon: <Zap className="h-4 w-4" />,
        id: "focus",
        label: "Focus Reactor",
        metric: latestReview ? fmtMs(latestReview.workDuration) : "no session",
        score: focusScore,
        signal: focusActive ? "live now" : latestReview ? `${latestReview.completedTasks.length} task session` : "ready",
      },
    ];

    const momentumScore = clampScore(
      executionScore * 0.22 +
        projectScore * 0.16 +
        growthScore * 0.18 +
        reflectionScore * 0.14 +
        controlScore * 0.14 +
        focusScore * 0.16,
    );

    const bottlenecks = [
      overdueTasks.length > 0
        ? {
            accent: "rose" as const,
            href: "/tasks",
            label: "Deadline drag",
            text: `${overdueTasks.length} overdue task${overdueTasks.length === 1 ? "" : "s"} are pulling the system down.`,
          }
        : null,
      stuckProjects.length > 0 || riskyProjects.length > 0
        ? {
            accent: "amber" as const,
            href: "/projects",
            label: "Project pressure",
            text: `${stuckProjects.length + riskyProjects.length} project${stuckProjects.length + riskyProjects.length === 1 ? "" : "s"} need a health check.`,
          }
        : null,
      dueReminders.length > 0
        ? {
            accent: "sky" as const,
            href: "/reminders",
            label: "Attention backlog",
            text: `${dueReminders.length} reminder${dueReminders.length === 1 ? "" : "s"} are due now.`,
          }
        : null,
      !journalToday
        ? {
            accent: "emerald" as const,
            href: "/journal",
            label: "Reflection missing",
            text: "No journal entry today, so the system is missing emotional context.",
          }
        : null,
      almostAchievements.length > 0
        ? {
            accent: "violet" as const,
            href: "/achievements",
            label: "Reward near unlock",
            text: `${almostAchievements[0].title} is close. One push could make it tangible.`,
          }
        : null,
    ].filter(Boolean) as Array<{ accent: DomainSignal["accent"]; href: string; label: string; text: string }>;

    const leverageMoves = [
      overdueTasks[0]
        ? {
            href: `/tasks?task=${overdueTasks[0].id}`,
            icon: <CheckSquare className="h-4 w-4" />,
            label: "Clear the sharpest overdue task",
            text: overdueTasks[0].title,
          }
        : null,
      focusTasks[0]
        ? {
            href: "/focus",
            icon: <Clock3 className="h-4 w-4" />,
            label: "Start a focus block",
            text: focusTasks[0].title,
          }
        : {
            href: "/focus",
            icon: <Clock3 className="h-4 w-4" />,
            label: "Start a clean focus block",
            text: "Pick one meaningful task and build momentum.",
          },
      dueTodayTasks[0]
        ? {
            href: `/tasks?task=${dueTodayTasks[0].id}`,
            icon: <Target className="h-4 w-4" />,
            label: "Protect today's deadline",
            text: dueTodayTasks[0].title,
          }
        : null,
      !journalToday
        ? {
            href: "/journal",
            icon: <BookOpen className="h-4 w-4" />,
            label: "Add emotional signal",
            text: "Write a two-minute journal entry.",
          }
        : null,
      almostAchievements[0]
        ? {
            href: `/achievements/${almostAchievements[0].id}`,
            icon: <Award className="h-4 w-4" />,
            label: "Push the nearest reward",
            text: `${almostAchievements[0].title} is ${getAchievementProgressPercent(almostAchievements[0])}% done.`,
          }
        : null,
    ].filter(Boolean) as Array<{ href: string; icon: React.ReactNode; label: string; text: string }>;

    const activeGoal =
      data.goals.find((goal) => !goal.completed) ||
      data.goals[0] ||
      null;
    const projectForGoal =
      activeGoal
        ? data.projects.find((project) => project.goal_id === activeGoal.id) || data.projects[0] || null
        : data.projects[0] || null;
    const taskForProject =
      projectForGoal
        ? openTasks.find((task) => task.project_id === projectForGoal.id) || openTasks[0] || null
        : openTasks[0] || null;
    const achievementForGoal =
      almostAchievements[0] ||
      data.achievements.find((achievement) => resolveAchievementStatus(achievement) !== "completed") ||
      data.achievements[0] ||
      null;

    return {
      activeGoal,
      achievementForGoal,
      bestHabitStreak,
      bottlenecks,
      completedToday,
      domains,
      dueReminders,
      focusTasks,
      journalToday,
      latestReview,
      leverageMoves: leverageMoves.slice(0, 4),
      momentumScore,
      monthExpenses,
      monthIncome,
      monthNet,
      openTasks,
      overdueTasks,
      projectForGoal,
      taskForProject,
    };
  }, [data, focusActive, focusReviewHistory, lastFocusReview]);

  if (loading) {
    return (
      <div className="min-h-full bg-[#0a0a0d] px-6 py-8 text-white">
        <div className="mx-auto max-w-[1280px] space-y-6">
          <Skeleton className="h-[320px] rounded-[28px] bg-white/[0.03]" />
          <div className="grid gap-5 xl:grid-cols-[1.1fr_0.9fr]">
            <Skeleton className="h-[500px] rounded-[28px] bg-white/[0.03]" />
            <Skeleton className="h-[500px] rounded-[28px] bg-white/[0.03]" />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-full bg-[#0a0a0d] text-white">
      {/* ── Hero ── */}
      <div className="relative overflow-hidden border-b border-white/[0.04]">
        {/* Background ambience */}
        <div className="pointer-events-none absolute inset-0">
          <div
            className="absolute -left-[8%] -top-[50%] h-[600px] w-[600px] rounded-full opacity-[0.18] blur-3xl"
            style={{ background: "radial-gradient(circle, #7c3aed, transparent 70%)" }}
          />
          <div
            className="absolute right-[5%] top-[10%] h-[380px] w-[380px] rounded-full opacity-[0.08] blur-3xl"
            style={{ background: "radial-gradient(circle, #0ea5e9, transparent 70%)" }}
          />
          {/* Subtle dot grid */}
          <svg className="absolute inset-0 h-full w-full opacity-[0.035]" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <pattern id="dot-grid" x="0" y="0" width="28" height="28" patternUnits="userSpaceOnUse">
                <circle cx="1" cy="1" r="1" fill="white" />
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#dot-grid)" />
          </svg>
        </div>

        <div className="relative mx-auto max-w-[1280px] px-6 py-10">
          <div className="flex flex-col gap-8 lg:flex-row lg:items-start lg:justify-between">
            <div className="max-w-2xl">
              <div className="mb-5 inline-flex items-center gap-2.5 rounded-full border border-violet-500/20 bg-violet-500/[0.08] px-4 py-2">
                <Network className="h-3.5 w-3.5 text-violet-400" />
                <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-violet-300/70">
                  Life Operating System
                </p>
              </div>

              <h1 className="text-[36px] font-black leading-[1.1] tracking-[-0.02em] text-white">
                See the whole system<br />
                <span className="bg-gradient-to-r from-white/35 to-white/20 bg-clip-text text-transparent">
                  behind your momentum.
                </span>
              </h1>
              <p className="mt-4 max-w-lg text-[14px] leading-relaxed text-white/40">
                Mindavio verbindet Tasks, Projekte, Achievements, Journal, Finanzen,
                Reminders und Focus zu einer klaren Map — nur wo Energie entsteht
                und was dich gerade bremst.
              </p>

              <div className="mt-5 flex flex-wrap gap-2">
                {["Momentum score", "System radar", "Bottlenecks", "Leverage moves"].map((pill) => (
                  <span
                    key={pill}
                    className="rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-[11px] font-semibold text-white/35"
                  >
                    {pill}
                  </span>
                ))}
              </div>
            </div>

            <Link
              href="/focus"
              className="flex items-center gap-2.5 self-start rounded-2xl bg-violet-600 px-5 py-3 text-[13px] font-bold text-white shadow-[0_8px_32px_rgba(109,40,217,0.40)] transition-all hover:bg-violet-500 hover:shadow-[0_8px_44px_rgba(109,40,217,0.50)] active:scale-[0.97]"
            >
              <Zap className="h-4 w-4" />
              Open focus
            </Link>
          </div>

          {/* Hero metrics strip */}
          <div className="mt-8 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
            <HeroMetric
              accent="violet"
              icon={<Activity className="h-4 w-4" />}
              label="Momentum"
              sub="System score"
              value={`${model.momentumScore}`}
              unit="/100"
            />
            <HeroMetric
              accent="sky"
              icon={<CheckCircle2 className="h-4 w-4" />}
              label="Done today"
              sub="Completed tasks"
              value={String(model.completedToday.length)}
            />
            <HeroMetric
              accent="emerald"
              icon={<HeartPulse className="h-4 w-4" />}
              label="Best streak"
              sub="Habit momentum"
              value={String(model.bestHabitStreak)}
              unit=" days"
            />
            <HeroMetric
              accent="amber"
              icon={<BellRing className="h-4 w-4" />}
              label="Attention"
              sub="Due reminders"
              value={String(model.dueReminders.length)}
            />
          </div>
        </div>
      </div>

      <div className="mx-auto max-w-[1280px] px-6 py-8">
        {/* ── System Radar ── */}
        {/* DESIGN LOCKED: border-violet-500/[0.14] and dark opaque gradient — DO NOT change to border-white or add ring-1 */}
        <section className="mb-6 overflow-hidden rounded-[28px] border border-violet-500/[0.14] bg-[radial-gradient(ellipse_at_top_left,rgba(124,58,237,0.12),rgba(10,8,21,0.97)_60%,rgba(10,10,13,1)_100%)]">
          <div className="flex flex-col gap-2 border-b border-violet-500/[0.08] px-6 py-4 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-center gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-violet-500/15 text-violet-300">
                <LayoutDashboard className="h-4 w-4" />
              </div>
              <div>
                <p className="text-[10px] font-bold uppercase tracking-[0.20em] text-violet-300/50">
                  System radar
                </p>
                <h2 className="mt-0.5 text-[17px] font-bold tracking-tight text-white">
                  The operating layer at a glance
                </h2>
              </div>
            </div>
            <span className="rounded-full border border-violet-500/[0.12] bg-violet-500/[0.06] px-3 py-1 text-[11px] font-semibold text-violet-200/40">
              {model.domains.length} engines connected
            </span>
          </div>
          <div className="p-5 pt-4">
            <SystemRadar domains={model.domains} momentumScore={model.momentumScore} />
          </div>
        </section>

        {/* ── Main grid ── */}
        <section className="grid gap-6 xl:grid-cols-[1fr_1fr]">
          <div className="space-y-6">
            <GoalChain
              achievement={model.achievementForGoal}
              goal={model.activeGoal}
              project={model.projectForGoal}
              task={model.taskForProject}
            />
          </div>

          <div className="space-y-6">
            {/* Bottlenecks */}
            <Panel
              eyebrow="Bottlenecks"
              icon={<Compass className="h-4 w-4" />}
              title="What is slowing the system down"
              accent="rose"
            >
              {model.bottlenecks.length === 0 ? (
                <EmptyPanel
                  title="No obvious bottleneck"
                  text="The system has no major red flag right now. Use that clean state to push a high-leverage move."
                />
              ) : (
                <div className="space-y-2.5">
                  {model.bottlenecks.slice(0, 5).map((item) => (
                    <Link
                      key={`${item.label}-${item.href}`}
                      href={item.href}
                      className={cn(
                        "group flex items-start gap-4 overflow-hidden rounded-2xl border bg-white/[0.02] p-4 transition-all hover:bg-white/[0.04]",
                        ACCENT_STYLES[item.accent].border,
                      )}
                    >
                      {/* Accent left bar */}
                      <div
                        className={cn("mt-0.5 h-full w-0.5 shrink-0 self-stretch rounded-full opacity-60",
                          item.accent === "rose" && "bg-rose-400",
                          item.accent === "amber" && "bg-amber-400",
                          item.accent === "sky" && "bg-sky-400",
                          item.accent === "emerald" && "bg-emerald-400",
                          item.accent === "violet" && "bg-violet-400",
                        )}
                      />
                      <div className="min-w-0 flex-1">
                        <p className={cn("text-[12px] font-bold", ACCENT_STYLES[item.accent].text)}>
                          {item.label}
                        </p>
                        <p className="mt-0.5 text-[12px] leading-relaxed text-white/40">
                          {item.text}
                        </p>
                      </div>
                      <ArrowRight className="mt-1 h-3.5 w-3.5 shrink-0 text-white/14 transition-all group-hover:translate-x-0.5 group-hover:text-white/40" />
                    </Link>
                  ))}
                </div>
              )}
            </Panel>

            {/* Leverage moves */}
            <Panel
              eyebrow="Leverage"
              icon={<Zap className="h-4 w-4" />}
              title="Next moves that actually matter"
              accent="sky"
            >
              <div className="space-y-2.5">
                {model.leverageMoves.map((move, index) => (
                  <Link
                    key={`${move.label}-${index}`}
                    href={move.href}
                    className="group flex items-start gap-3 rounded-2xl border border-white/[0.04] bg-white/[0.015] p-4 transition-all hover:border-sky-500/[0.20] hover:bg-white/[0.035]"
                  >
                    <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-white/[0.05] text-white/35 transition-colors group-hover:text-white/70">
                      {move.icon}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-[13px] font-bold text-white/80">{move.label}</p>
                      <p className="mt-0.5 truncate text-[11px] text-white/30">{move.text}</p>
                    </div>
                    <ArrowRight className="mt-1 h-4 w-4 shrink-0 text-white/14 transition-all group-hover:translate-x-0.5 group-hover:text-white/45" />
                  </Link>
                ))}
              </div>
            </Panel>

            {/* Analytics shortcut */}
            <Link
              href="/analytics"
              className="group flex items-center justify-between gap-4 rounded-[22px] border border-white/[0.04] bg-white/[0.015] px-5 py-4 transition-all hover:border-violet-500/[0.20] hover:bg-white/[0.035]"
            >
              <div className="flex items-center gap-3">
                <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-white/[0.05] text-white/35 transition-colors group-hover:text-white/70">
                  <BarChart3 className="h-4 w-4" />
                </div>
                <div>
                  <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-white/20">Analytics</p>
                  <p className="text-[13px] font-semibold text-white/55 group-hover:text-white/80 transition-colors">
                    Open detailed analytics
                  </p>
                </div>
              </div>
              <ArrowRight className="h-4 w-4 text-white/18 transition-all group-hover:translate-x-0.5 group-hover:text-white/45" />
            </Link>
          </div>
        </section>

        {/* ── Footer facts ── */}
        <section className="mt-6 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <SystemFact
            accent="sky"
            icon={<CalendarDays className="h-4 w-4" />}
            label="Calendar pressure"
            value={`${data.events.length} upcoming`}
          />
          <SystemFact
            accent="amber"
            icon={<BellRing className="h-4 w-4" />}
            label="Attention pings"
            value={`${model.dueReminders.length} due now`}
          />
          <SystemFact
            accent="emerald"
            icon={<TrendingUp className="h-4 w-4" />}
            label="Month income"
            value={formatMoney(model.monthIncome)}
          />
          <SystemFact
            accent="rose"
            icon={<BarChart3 className="h-4 w-4" />}
            label="Month expenses"
            value={formatMoney(model.monthExpenses)}
          />
        </section>
      </div>
    </div>
  );
}

/* ── Score ring (SVG arc) ── */
function ScoreRing({
  accent,
  score,
  size = 48,
}: {
  accent: DomainSignal["accent"];
  score: number;
  size?: number;
}) {
  const strokeColor = ACCENT_STYLES[accent].ring;
  const r = (size - 6) / 2;
  const cx = size / 2;
  const cy = size / 2;
  const circumference = 2 * Math.PI * r;
  const dash = (score / 100) * circumference;
  const gap = circumference - dash;

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="shrink-0">
      {/* Track */}
      <circle
        cx={cx} cy={cy} r={r}
        fill="none"
        stroke="rgba(255,255,255,0.06)"
        strokeWidth="2.5"
      />
      {/* Progress arc */}
      <circle
        cx={cx} cy={cy} r={r}
        fill="none"
        stroke={strokeColor}
        strokeWidth="2.5"
        strokeDasharray={`${dash} ${gap}`}
        strokeLinecap="round"
        transform={`rotate(-90 ${cx} ${cy})`}
        style={{ filter: `drop-shadow(0 0 3px ${strokeColor}70)` }}
      />
      {/* Score number */}
      <text
        x={cx} y={cy}
        textAnchor="middle"
        dominantBaseline="central"
        fill="white"
        fontSize={size < 44 ? "8" : "10"}
        fontWeight="800"
        fontFamily="system-ui"
      >
        {score}
      </text>
    </svg>
  );
}

/* ── Hero metric card ── */
function HeroMetric({
  accent,
  icon,
  label,
  sub,
  value,
  unit,
}: {
  accent: DomainSignal["accent"];
  icon: React.ReactNode;
  label: string;
  sub: string;
  value: string;
  unit?: string;
}) {
  const styles = ACCENT_STYLES[accent];

  return (
    <div
      className={cn(
        "group relative overflow-hidden rounded-2xl border bg-[#0d0b18]/70 px-5 py-4 transition-all",
        styles.border,
      )}
    >
      {/* Subtle top glow strip */}
      <div
        className="pointer-events-none absolute inset-x-0 top-0 h-px opacity-60"
        style={{ background: `linear-gradient(90deg, transparent, ${styles.ring}60, transparent)` }}
      />

      <div className="mb-3 flex items-center justify-between gap-2">
        <div className={cn("flex h-8 w-8 items-center justify-center rounded-xl", styles.icon)}>
          {icon}
        </div>
        <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-white/18">{label}</p>
      </div>

      <div className="flex items-end gap-1">
        <p className={cn("text-[28px] font-black leading-none tracking-tight", styles.text)}>
          {value}
        </p>
        {unit && (
          <p className={cn("mb-0.5 text-[13px] font-bold opacity-50", styles.text)}>{unit}</p>
        )}
      </div>
      <p className="mt-1.5 text-[11px] text-white/25">{sub}</p>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   System Radar — hub-and-spoke map
   Desktop: 5-column grid  [nodes | gap | core | gap | nodes]
   The gap columns are intentionally empty — SVG connections
   travel through them, giving a true "network map" feel.
───────────────────────────────────────────────────────────────── */
function SystemRadar({
  domains,
  momentumScore,
}: {
  domains: DomainSignal[];
  momentumScore: number;
}) {
  const ORDER = ["execution", "focus", "control", "projects", "growth", "reflection"];
  const sorted = [...domains].sort((a, b) => ORDER.indexOf(a.id) - ORDER.indexOf(b.id));
  const leftCol  = sorted.filter((d) => ["execution", "focus", "control"].includes(d.id));
  const rightCol = sorted.filter((d) => ["projects", "growth", "reflection"].includes(d.id));

  // SVG endpoints (viewBox 0 0 100 100, preserveAspectRatio none).
  // x: left column centre ≈ 12%, right ≈ 88%, core centre = 50%.
  // y values mirror each column's staggered flex-gap layout
  // (top node ~15%, middle ~50%, bottom ~85%).
  const connMap: Record<string, { x: number; y: number }> = {
    execution:  { x: 12, y: 15 },
    focus:      { x: 12, y: 50 },
    control:    { x: 12, y: 85 },
    projects:   { x: 88, y: 15 },
    growth:     { x: 88, y: 50 },
    reflection: { x: 88, y: 85 },
  };

  return (
    <div>
      {/* ── Mobile / tablet fallback ── */}
      <div className="xl:hidden space-y-4">
        <MomentumCore momentumScore={momentumScore} />
        <div className="grid gap-3 md:grid-cols-2">
          {domains.map((d) => <LifeMapNode key={d.id} domain={d} />)}
        </div>
      </div>

      {/* ── Desktop map ── */}
      {/* DESIGN LOCKED: border-violet-500/[0.12] + inline dark radial gradient — DO NOT change to border-white/[0.06] or add rgba(255,255,255,...) stops */}
      <div
        className="relative hidden xl:flex xl:items-center xl:gap-0 overflow-hidden rounded-[28px] border border-violet-500/[0.12]"
        style={{
          minHeight: 580,
          background: "radial-gradient(ellipse 70% 80% at 50% 50%, rgba(124,58,237,0.14) 0%, rgba(12,10,20,0.96) 62%, #09080f 100%)",
        }}
      >
        {/* Hex-grid texture */}
        <svg aria-hidden="true" className="pointer-events-none absolute inset-0 h-full w-full opacity-[0.028]">
          <defs>
            <pattern id="hex-bg" x="0" y="0" width="40" height="46" patternUnits="userSpaceOnUse">
              <path
                d="M20 2 L38 12 L38 34 L20 44 L2 34 L2 12 Z"
                fill="none"
                stroke="white"
                strokeWidth="0.8"
              />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#hex-bg)" />
        </svg>

        {/* ── SVG connection layer ── */}
        <svg
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 h-full w-full"
          preserveAspectRatio="none"
          viewBox="0 0 100 100"
        >
          <defs>
            {/* Per-accent gradients for each spoke */}
            {domains.map((d) => {
              const col = ACCENT_STYLES[d.accent].ring;
              const t = connMap[d.id];
              const isLeft = t ? t.x < 50 : true;
              return (
                <linearGradient
                  key={`grad-${d.id}`}
                  id={`grad-${d.id}`}
                  x1={isLeft ? "0%" : "100%"} y1="0%"
                  x2={isLeft ? "100%" : "0%"} y2="0%"
                >
                  <stop offset="0%"   stopColor={col} stopOpacity="0.05" />
                  <stop offset="55%"  stopColor={col} stopOpacity="0.55" />
                  <stop offset="100%" stopColor={col} stopOpacity="0.12" />
                </linearGradient>
              );
            })}
          </defs>

          {domains.map((d) => {
            const t = connMap[d.id];
            if (!t) return null;
            const col = ACCENT_STYLES[d.accent].ring;
            return (
              <g key={d.id}>
                {/* Glow halo behind line */}
                <line
                  x1="50" y1="50" x2={t.x} y2={t.y}
                  stroke={col}
                  strokeWidth="1.4"
                  strokeOpacity="0.12"
                  strokeLinecap="round"
                />
                {/* Crisp dashed spoke */}
                <line
                  x1="50" y1="50" x2={t.x} y2={t.y}
                  stroke={`url(#grad-${d.id})`}
                  strokeWidth="0.35"
                  strokeDasharray="2.8 3.8"
                  strokeLinecap="round"
                />
                {/* End anchor dot */}
                <circle cx={t.x} cy={t.y} r="0.9" fill={col} opacity="0.65" />
                <circle cx={t.x} cy={t.y} r="1.8" fill={col} opacity="0.12" />
              </g>
            );
          })}
          {/* Center anchor */}
          <circle cx="50" cy="50" r="1.2" fill="rgba(167,139,250,0.55)" />
          <circle cx="50" cy="50" r="3"   fill="rgba(167,139,250,0.08)" />
        </svg>

        {/* ── Left column — nodes staggered vertically ── */}
        <div className="relative z-10 flex w-[248px] shrink-0 flex-col self-stretch px-5 py-6">
          <div className="flex flex-col justify-between h-full gap-4">
            {leftCol.map((d, i) => (
              <div
                key={d.id}
                style={{ marginTop: i === 0 ? 0 : i === 1 ? 8 : 0 }}
              >
                <LifeMapNode domain={d} />
              </div>
            ))}
          </div>
        </div>

        {/* ── Spacer (left gap — the "wire" space) ── */}
        <div className="flex-1" />

        {/* ── Center: Momentum Core ── */}
        <div className="relative z-10 w-[252px] shrink-0">
          <MomentumCore momentumScore={momentumScore} />
        </div>

        {/* ── Spacer (right gap) ── */}
        <div className="flex-1" />

        {/* ── Right column — staggered opposite to left ── */}
        <div className="relative z-10 flex w-[248px] shrink-0 flex-col self-stretch px-5 py-6">
          <div className="flex flex-col justify-between h-full gap-4">
            {rightCol.map((d, i) => (
              <div
                key={d.id}
                style={{ marginTop: i === 0 ? 16 : i === 1 ? 0 : 8 }}
              >
                <LifeMapNode domain={d} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Momentum Core — the hub of the life map
   Large arc ring, concentric halos, dominant score display
───────────────────────────────────────────────────────────────── */
function MomentumCore({ momentumScore }: { momentumScore: number }) {
  const S  = 160;          // SVG canvas size
  const cx = S / 2;
  const cy = S / 2;

  // Outer decorative ring (thin)
  const rOuter = 72;
  // Main progress arc
  const rArc   = 60;
  const strokeW = 7;
  const circArc = 2 * Math.PI * rArc;
  const dash    = (momentumScore / 100) * circArc;
  const gapArc  = circArc - dash;

  // Score label colour based on score
  const scoreColor =
    momentumScore >= 75 ? "#34d399" :
    momentumScore >= 50 ? "#38bdf8" :
    momentumScore >= 30 ? "#fbbf24" : "#fb7185";

  return (
    <div
      className="relative overflow-visible rounded-[28px] border border-violet-500/22 bg-[#0c0a18]/90 p-5 text-center"
      style={{
        boxShadow:
          "0 0 0 1px rgba(139,92,246,0.14), 0 30px 90px rgba(124,58,237,0.22), 0 0 60px rgba(124,58,237,0.10)",
        backdropFilter: "blur(12px)",
      }}
    >
      {/* Outer ambient glow (purely decorative, overflow-visible) */}
      <div
        className="pointer-events-none absolute inset-0 -z-10 rounded-[28px] opacity-40 blur-2xl"
        style={{ background: "radial-gradient(circle, rgba(139,92,246,0.35), transparent 70%)" }}
      />

      {/* Label */}
      <div className="mb-3 flex items-center justify-center gap-2">
        <div className="flex h-6 w-6 items-center justify-center rounded-lg bg-violet-500/18">
          <LayoutDashboard className="h-3 w-3 text-violet-300" />
        </div>
        <p className="text-[9px] font-black uppercase tracking-[0.22em] text-violet-200/45">
          Momentum Core
        </p>
      </div>

      {/* Arc ring */}
      <div className="flex justify-center">
        <svg width={S} height={S} viewBox={`0 0 ${S} ${S}`} overflow="visible">
          <defs>
            <linearGradient id="core-arc" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%"   stopColor="#a78bfa" />
              <stop offset="45%"  stopColor="#38bdf8" />
              <stop offset="100%" stopColor="#34d399" />
            </linearGradient>
            <filter id="arc-glow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="3" result="blur" />
              <feMerge>
                <feMergeNode in="blur" />
                <feMergeNode in="SourceGraphic" />
              </feMerge>
            </filter>
          </defs>

          {/* Outermost faint halo ring */}
          <circle cx={cx} cy={cy} r={rOuter}     fill="none" stroke="rgba(139,92,246,0.07)" strokeWidth="1"   />
          {/* Second halo */}
          <circle cx={cx} cy={cy} r={rOuter - 6}  fill="none" stroke="rgba(139,92,246,0.05)" strokeWidth="0.5" />
          {/* Arc track */}
          <circle cx={cx} cy={cy} r={rArc}        fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={strokeW} />

          {/* Glow arc (blurred copy behind) */}
          <circle
            cx={cx} cy={cy} r={rArc}
            fill="none"
            stroke="url(#core-arc)"
            strokeWidth={strokeW + 6}
            strokeDasharray={`${dash} ${gapArc}`}
            strokeLinecap="round"
            transform={`rotate(-90 ${cx} ${cy})`}
            opacity="0.22"
          />
          {/* Crisp progress arc */}
          <circle
            cx={cx} cy={cy} r={rArc}
            fill="none"
            stroke="url(#core-arc)"
            strokeWidth={strokeW}
            strokeDasharray={`${dash} ${gapArc}`}
            strokeLinecap="round"
            transform={`rotate(-90 ${cx} ${cy})`}
            filter="url(#arc-glow)"
          />

          {/* Score number */}
          <text
            x={cx} y={cy - 8}
            textAnchor="middle" dominantBaseline="middle"
            fill={scoreColor}
            fontSize="34" fontWeight="900" fontFamily="system-ui"
          >
            {momentumScore}
          </text>
          <text
            x={cx} y={cy + 16}
            textAnchor="middle" dominantBaseline="middle"
            fill="rgba(255,255,255,0.22)"
            fontSize="10" fontWeight="700" fontFamily="system-ui" letterSpacing="2"
          >
            / 100
          </text>
        </svg>
      </div>

      {/* Sub-label */}
      <p className="text-[10px] font-semibold text-white/28">Life system score</p>

      {/* Mini 3-bar breakdown */}
      <div className="mt-4 space-y-1.5">
        {[
          { accent: "sky",    label: "Execution", pct: 78 },
          { accent: "violet", label: "Projects",  pct: 72 },
          { accent: "amber",  label: "Growth",    pct: 65 },
        ].map((b) => (
          <div key={b.label} className="flex items-center gap-2">
            <p className="w-[50px] shrink-0 text-left text-[8px] font-bold uppercase tracking-[0.12em] text-white/22">
              {b.label}
            </p>
            <div className="flex-1 h-0.5 overflow-hidden rounded-full bg-white/[0.06]">
              <div
                className={cn("h-full rounded-full",
                  b.accent === "sky"    && "bg-sky-400",
                  b.accent === "violet" && "bg-violet-400",
                  b.accent === "amber"  && "bg-amber-400",
                )}
                style={{ width: `${b.pct}%`, opacity: 0.7 }}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   Life Map Node — beacon card for each life domain
   Glows in its accent colour, shows score ring and live signal
───────────────────────────────────────────────────────────────── */
function LifeMapNode({ domain }: { domain: DomainSignal }) {
  const accent = ACCENT_STYLES[domain.accent];
  const ring   = accent.ring;

  return (
    <Link
      href={domain.href}
      className={cn(
        "group relative block overflow-hidden rounded-[18px] border bg-[#0d0b17]/85 backdrop-blur-md transition-all duration-200",
        "hover:-translate-y-1 hover:scale-[1.015]",
        accent.border,
      )}
      style={{
        boxShadow: `0 4px 24px rgba(0,0,0,0.30), 0 0 0 1px ${ring}14, inset 0 1px 0 ${ring}12`,
      }}
    >
      {/* Top accent glow strip */}
      <div
        className="absolute inset-x-0 top-0 h-[1px]"
        style={{ background: `linear-gradient(90deg, transparent 0%, ${ring}80 50%, transparent 100%)` }}
      />
      {/* Hover: inner accent glow */}
      <div
        className="pointer-events-none absolute inset-0 opacity-0 transition-opacity duration-300 group-hover:opacity-100 rounded-[18px]"
        style={{ boxShadow: `inset 0 0 24px ${ring}15` }}
      />

      <div className="p-3.5">
        {/* Icon + score ring */}
        <div className="flex items-start justify-between gap-2">
          <div className={cn("flex h-8 w-8 shrink-0 items-center justify-center rounded-xl", accent.icon)}>
            {domain.icon}
          </div>
          <ScoreRing accent={domain.accent} score={domain.score} size={40} />
        </div>

        {/* Label */}
        <p className="mt-2.5 text-[13px] font-bold leading-snug text-white/90">
          {domain.label}
        </p>

        {/* Metric + signal */}
        <div className="mt-3 flex items-center justify-between gap-2 border-t pt-2.5"
          style={{ borderColor: `${ring}14` }}
        >
          <div className="min-w-0">
            <p className="truncate text-[11px] font-bold text-white/60">{domain.metric}</p>
            <p className={cn("mt-0.5 truncate text-[10px] font-semibold", accent.text)}>
              {domain.signal}
            </p>
          </div>
          <ArrowRight className="h-3.5 w-3.5 shrink-0 text-white/14 transition-all group-hover:translate-x-0.5 group-hover:text-white/55" />
        </div>
      </div>
    </Link>
  );
}

/* ── Goal-to-day chain ── */
function GoalChain({
  achievement,
  goal,
  project,
  task,
}: {
  achievement: Achievement | null;
  goal: Goal | null;
  project: Project | null;
  task: Task | null;
}) {
  const steps = [
    {
      accent: "violet" as const,
      href: "/mindset",
      icon: <Target className="h-4 w-4" />,
      label: "Goal",
      num: "01",
      title: goal?.title || "Define a primary goal",
      value: goal ? `${goal.progress}% aligned` : "No goal selected",
    },
    {
      accent: "sky" as const,
      href: project ? `/projects/${project.id}` : "/projects",
      icon: <FolderKanban className="h-4 w-4" />,
      label: "Project",
      num: "02",
      title: project?.name || "Create a project spine",
      value: project?.health || "Missing link",
    },
    {
      accent: "amber" as const,
      href: achievement ? `/achievements/${achievement.id}` : "/achievements",
      icon: <Award className="h-4 w-4" />,
      label: "Achievement",
      num: "03",
      title: achievement?.title || "Attach a reward destination",
      value: achievement ? `${getAchievementProgressPercent(achievement)}%` : "No destination",
    },
    {
      accent: "emerald" as const,
      href: task ? `/tasks?task=${task.id}` : "/tasks",
      icon: <CheckSquare className="h-4 w-4" />,
      label: "Today",
      num: "04",
      title: task?.title || "Choose the next visible action",
      value: task?.priority || "Next step",
    },
  ];

  // DESIGN LOCKED: border-violet-500/[0.14] + dark gradient — DO NOT use border-white/[0.06] or lighten gradient stops
  return (
    <div className="rounded-[28px] border border-violet-500/[0.14] bg-[radial-gradient(ellipse_at_top_left,rgba(124,58,237,0.10),rgba(10,8,18,0.98)_55%,rgba(9,8,15,1)_100%)] p-5">
      <div className="mb-5 flex items-center gap-3">
        <div className="flex h-9 w-9 items-center justify-center rounded-2xl bg-violet-500/12 text-violet-300">
          <GitBranch className="h-4 w-4" />
        </div>
        <div>
          <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-white/20">
            Goal-to-day chain
          </p>
          <h2 className="mt-0.5 text-[19px] font-bold tracking-tight text-white">
            Why today&apos;s action matters
          </h2>
        </div>
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        {steps.map((step) => {
          const styles = ACCENT_STYLES[step.accent];
          return (
            <Link
              key={step.label}
              href={step.href}
              className={cn(
                // DESIGN LOCKED: max border-white/[0.04] — higher values create visible white outlines on dark bg
                "group relative overflow-hidden rounded-2xl border border-white/[0.04] bg-white/[0.02] p-4 transition-all hover:bg-white/[0.04]",
              )}
            >
              {/* Subtle top gradient strip */}
              <div
                className={cn("pointer-events-none absolute inset-x-0 top-0 h-px opacity-50 bg-gradient-to-r", styles.gradient)}
              />

              <div className="mb-3 flex items-center justify-between gap-3">
                <div className={cn("flex h-8 w-8 items-center justify-center rounded-xl", styles.icon)}>
                  {step.icon}
                </div>
                {/* Step number badge */}
                <span className="font-mono text-[11px] font-black text-white/14 tabular-nums">
                  {step.num}
                </span>
              </div>

              <p className="line-clamp-2 min-h-[38px] text-[12px] font-bold leading-snug text-white/80">
                {step.title}
              </p>
              <p className={cn("mt-2 text-[11px] font-semibold", styles.text)}>
                {step.value}
              </p>
            </Link>
          );
        })}
      </div>
    </div>
  );
}

/* ── Generic panel wrapper ── */
function Panel({
  accent,
  children,
  eyebrow,
  icon,
  title,
}: {
  accent?: DomainSignal["accent"];
  children: React.ReactNode;
  eyebrow: string;
  icon: React.ReactNode;
  title: string;
}) {
  const iconStyles = accent ? ACCENT_STYLES[accent].icon : "bg-white/[0.05] text-white/35";

  // DESIGN LOCKED: border-white/[0.04] max, bg-[#0d0b18]/70 — DO NOT increase opacity or add ring-1
  return (
    <div className="rounded-[28px] border border-white/[0.04] bg-[#0d0b18]/70 p-5">
      <div className="mb-4 flex items-center gap-3">
        <div className={cn("flex h-9 w-9 items-center justify-center rounded-xl", iconStyles)}>
          {icon}
        </div>
        <div>
          <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-white/20">
            {eyebrow}
          </p>
          <h2 className="mt-0.5 text-[15px] font-bold tracking-tight text-white">
            {title}
          </h2>
        </div>
      </div>
      {children}
    </div>
  );
}

/* ── Empty panel state ── */
function EmptyPanel({ text, title }: { text: string; title: string }) {
  return (
    <div className="rounded-2xl border border-dashed border-emerald-500/[0.12] bg-emerald-500/[0.02] px-4 py-8 text-center">
      <div className="mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-emerald-500/10">
        <CheckCircle2 className="h-5 w-5 text-emerald-400" />
      </div>
      <p className="text-[13px] font-bold text-white/50">{title}</p>
      <p className="mx-auto mt-1.5 max-w-sm text-[11px] leading-relaxed text-white/26">
        {text}
      </p>
    </div>
  );
}

/* ── Footer system fact chip ── */
function SystemFact({
  accent,
  icon,
  label,
  value,
}: {
  accent: DomainSignal["accent"];
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  const styles = ACCENT_STYLES[accent];

  return (
    <div
      className={cn(
        "group relative overflow-hidden rounded-2xl border bg-[#0d0b18]/70 px-5 py-4 transition-all",
        styles.border,
      )}
    >
      <div
        className="pointer-events-none absolute inset-x-0 top-0 h-px opacity-40"
        style={{ background: `linear-gradient(90deg, transparent, ${styles.ring}50, transparent)` }}
      />
      <div className="mb-3 flex items-center justify-between">
        <div className={cn("flex h-8 w-8 items-center justify-center rounded-xl", styles.icon)}>
          {icon}
        </div>
        <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-white/18">{label}</p>
      </div>
      <p className={cn("text-[20px] font-black tracking-tight", styles.text)}>{value}</p>
    </div>
  );
}
