import {
  mdiAccount,
  mdiArrowTopRight,
  mdiCalendarHeart,
  mdiChartTimelineVariant,
  mdiCheckCircleOutline,
  mdiHeartPulse,
  mdiLeafCircle,
  mdiScaleBathroom,
  mdiTargetVariant,
  mdiWaterOutline,
  mdiWeatherNight,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, {
  ReactElement,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';
import BaseIcon from '../components/BaseIcon';
import NotificationBar from '../components/NotificationBar';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { hasCompletedApexOnboarding } from '../helpers/apexOnboarding';
import { humanize } from '../helpers/humanize';
import { hasPermission } from '../helpers/userPermissions';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type MoodRow = {
  mood_score: number | null;
  energy_level: number | null;
  anxiety_level: number | null;
  emotion_tags_csv: string | null;
  logged_at: string | null;
};

type SleepRow = {
  bedtime: string | null;
  final_wake_time: string | null;
  total_sleep_minutes: number | null;
  sleep_quality: number | null;
  morning_energy: number | null;
};

type WeightRow = {
  measured_at: string | null;
  value_primary: number | string | null;
  unit: string | null;
  notes: string | null;
};

type GoalRow = {
  id: string;
  goal_type: string | null;
  follow_up_answer: string | null;
  target_date: string | null;
  is_active: boolean | null;
};

type PhysicalRow = {
  height_cm: number | null;
  weight_kg: number | null;
  dominant_hand: string | null;
  blood_type: string | null;
  body_frame_size: string | null;
  updated_at: string | null;
};

type LifestyleRow = {
  typical_bedtime: string | null;
  typical_wake_time: string | null;
  caffeine_servings_per_day: number | null;
  avg_daily_steps_estimate: number | null;
  typical_stress_level: number | null;
  currently_exercises: boolean | null;
  diet_pattern: string | null;
  alcohol_use: string | null;
  tobacco_nicotine_use: string | null;
  updated_at: string | null;
};

type ConditionRow = {
  id: string;
  condition_name: string | null;
  status: string | null;
  diagnosing_doctor: string | null;
  management_plan: string | null;
  updated_at: string | null;
};

type ActivityKind =
  | 'hydration'
  | 'mood'
  | 'sleep'
  | 'weight'
  | 'goal'
  | 'condition';

type ActivityEntry = {
  id: string;
  kind: ActivityKind;
  title: string;
  detail: string | null;
  happened_at: string | null;
};

type DashboardData = {
  hydrationTotalMl: number;
  hydrationLogsToday: number;
  moodToday: MoodRow | null;
  sleepLatest: SleepRow | null;
  weightLatest: WeightRow | null;
  activeGoalsCount: number;
  conditionsCount: number;
  latestGoal: GoalRow | null;
  latestPhysical: PhysicalRow | null;
  latestLifestyle: LifestyleRow | null;
  latestCondition: ConditionRow | null;
  recentActivity: ActivityEntry[];
};

type QuickAction = {
  href: string;
  title: string;
  description: string;
  icon: string;
};

type SummaryCard = {
  label: string;
  icon: string;
  value: string;
  detail: string;
  isComplete: boolean;
  isAvailable: boolean;
};

type CountRow = {
  count: number | string | null;
};

const WATER_GOAL_ML = 2000;

const palette = {
  pageBg: '#F5F0E8',
  panelBg: '#FFF9F0',
  panelAlt: '#FBF7F0',
  border: '#E1D6C5',
  borderStrong: '#D8CBB7',
  forest: '#4A6741',
  forestSoft: '#EDF4EA',
  charcoal: '#1C1C1C',
  body: '#4C5544',
  muted: '#7E725E',
  gold: '#C9A84C',
  goldSoft: 'rgba(201,168,76,0.16)',
};

const activityRouteByKind: Record<ActivityKind, string> = {
  hydration: '/hydration_logs/hydration_logs-view',
  mood: '/mood_logs/mood_logs-view',
  sleep: '/sleep_logs/sleep_logs-view',
  weight: '/health_metrics/health_metrics-view',
  goal: '/goals/goals-view',
  condition: '/conditions/conditions-view',
};

const activityIconByKind: Record<ActivityKind, string> = {
  hydration: mdiWaterOutline,
  mood: mdiHeartPulse,
  sleep: mdiWeatherNight,
  weight: mdiScaleBathroom,
  goal: mdiTargetVariant,
  condition: mdiLeafCircle,
};

const initialDashboardData: DashboardData = {
  hydrationTotalMl: 0,
  hydrationLogsToday: 0,
  moodToday: null,
  sleepLatest: null,
  weightLatest: null,
  activeGoalsCount: 0,
  conditionsCount: 0,
  latestGoal: null,
  latestPhysical: null,
  latestLifestyle: null,
  latestCondition: null,
  recentActivity: [],
};

function escapeSqlLiteral(value: string) {
  return value.replace(/'/g, "''");
}

async function runSql<T>(sql: string): Promise<T[]> {
  const response = await axios.post('/sql', { sql });
  return Array.isArray(response.data?.rows) ? response.data.rows : [];
}

function toCount(value: number | string | null | undefined) {
  if (value === null || value === undefined) {
    return 0;
  }

  const parsedValue = Number(value);
  return Number.isNaN(parsedValue) ? 0 : parsedValue;
}

function formatDateTime(value?: string | null) {
  if (!value) {
    return 'Not captured yet';
  }

  return new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(new Date(value));
}

function formatDate(value?: string | null) {
  if (!value) {
    return 'No target date set';
  }

  return new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(new Date(value));
}

function formatMinutes(total?: number | null) {
  if (!total || total <= 0) {
    return 'Not logged yet';
  }

  const hours = Math.floor(total / 60);
  const minutes = total % 60;

  if (!hours) {
    return `${minutes} min`;
  }

  return `${hours}h ${minutes}m`;
}

function formatClockTime(value?: string | null) {
  if (!value) {
    return 'Not set';
  }

  const timeMatch = value.match(/^(\d{2}):(\d{2})/);

  if (!timeMatch) {
    const parsedDate = new Date(value);

    if (Number.isNaN(parsedDate.getTime())) {
      return value;
    }

    return new Intl.DateTimeFormat(undefined, {
      hour: 'numeric',
      minute: '2-digit',
    }).format(parsedDate);
  }

  const hours = Number(timeMatch[1]);
  const minutes = Number(timeMatch[2]);
  const parsedDate = new Date();
  parsedDate.setHours(hours, minutes, 0, 0);

  return new Intl.DateTimeFormat(undefined, {
    hour: 'numeric',
    minute: '2-digit',
  }).format(parsedDate);
}

function formatNumber(value?: number | string | null, suffix = '') {
  if (value === null || value === undefined || value === '') {
    return 'Not set';
  }

  const parsedValue = Number(value);

  if (Number.isNaN(parsedValue)) {
    return suffix ? `${value} ${suffix}`.trim() : String(value);
  }

  const formattedValue = Number.isInteger(parsedValue)
    ? parsedValue.toLocaleString()
    : parsedValue.toLocaleString(undefined, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 1,
      });

  return suffix ? `${formattedValue} ${suffix}` : formattedValue;
}

function isToday(value?: string | null) {
  if (!value) {
    return false;
  }

  const today = new Date();
  const candidate = new Date(value);

  return today.toDateString() === candidate.toDateString();
}

function hasRecentSleep(value?: string | null) {
  if (!value) {
    return false;
  }

  const happenedAt = new Date(value).getTime();
  const now = Date.now();
  const hoursDiff = Math.abs(now - happenedAt) / (1000 * 60 * 60);

  return hoursDiff <= 36;
}

function truncateText(value?: string | null, maxLength = 120) {
  if (!value) {
    return '';
  }

  if (value.length <= maxLength) {
    return value;
  }

  return `${value.slice(0, maxLength).trim()}…`;
}

function getDisplayName(firstName?: string | null, email?: string | null) {
  if (firstName?.trim()) {
    return firstName.trim();
  }

  const emailPrefix = email?.split('@')[0];

  if (emailPrefix) {
    return humanize(emailPrefix.replace(/[._-]+/g, ' '));
  }

  return 'there';
}

function DashboardPage() {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [dashboardData, setDashboardData] = useState<DashboardData>(
    initialDashboardData,
  );
  const [loading, setLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [onboardingComplete, setOnboardingComplete] = useState(false);

  const permissions = useMemo(
    () => ({
      hydrationRead: hasPermission(currentUser, 'READ_HYDRATION_LOGS'),
      moodRead: hasPermission(currentUser, 'READ_MOOD_LOGS'),
      sleepRead: hasPermission(currentUser, 'READ_SLEEP_LOGS'),
      weightRead: hasPermission(currentUser, 'READ_HEALTH_METRICS'),
      goalsRead: hasPermission(currentUser, 'READ_GOALS'),
      conditionsRead: hasPermission(currentUser, 'READ_CONDITIONS'),
      physicalRead: hasPermission(currentUser, 'READ_USER_PHYSICAL_BASELINES'),
      lifestyleRead: hasPermission(currentUser, 'READ_USER_LIFESTYLE_BASELINES'),
    }),
    [currentUser],
  );

  useEffect(() => {
    setOnboardingComplete(hasCompletedApexOnboarding(currentUser?.id));
  }, [currentUser?.id]);

  const loadDashboard = useCallback(
    async (userId: string) => {
      const safeUserId = escapeSqlLiteral(userId);
      const activityQueries: string[] = [];

      if (permissions.hydrationRead) {
        activityQueries.push(`
          SELECT
            id,
            'hydration'::text AS kind,
            COALESCE(NULLIF(container_label, ''), INITCAP(REPLACE(beverage_type, '_', ' ')), 'Hydration') AS title,
            CONCAT(COALESCE(volume_ml::text, '0'), ' ml') AS detail,
            logged_at AS happened_at
          FROM hydration_logs
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
        `);
      }

      if (permissions.moodRead) {
        activityQueries.push(`
          SELECT
            id,
            'mood'::text AS kind,
            COALESCE(NULLIF(emotion_tags_csv, ''), 'Mood check-in') AS title,
            CONCAT('Mood ', COALESCE(mood_score::text, '-'), '/10') AS detail,
            logged_at AS happened_at
          FROM mood_logs
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
        `);
      }

      if (permissions.sleepRead) {
        activityQueries.push(`
          SELECT
            id,
            'sleep'::text AS kind,
            'Sleep log'::text AS title,
            CONCAT(COALESCE(total_sleep_minutes::text, '0'), ' min sleep') AS detail,
            COALESCE(final_wake_time, bedtime) AS happened_at
          FROM sleep_logs
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
        `);
      }

      if (permissions.weightRead) {
        activityQueries.push(`
          SELECT
            id,
            'weight'::text AS kind,
            'Weight check'::text AS title,
            CONCAT(COALESCE(value_primary::text, '0'), ' ', COALESCE(unit, '')) AS detail,
            measured_at AS happened_at
          FROM health_metrics
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
            AND metric_type = 'body_composition'
        `);
      }

      if (permissions.goalsRead) {
        activityQueries.push(`
          SELECT
            id,
            'goal'::text AS kind,
            COALESCE(INITCAP(REPLACE(goal_type, '_', ' ')), 'Goal') AS title,
            COALESCE(
              NULLIF(follow_up_answer, ''),
              CASE
                WHEN target_date IS NOT NULL THEN CONCAT('Target ', TO_CHAR(target_date, 'Mon DD, YYYY'))
                ELSE 'Goal updated'
              END
            ) AS detail,
            COALESCE(target_date::timestamp, "createdAt") AS happened_at
          FROM goals
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
        `);
      }

      if (permissions.conditionsRead) {
        activityQueries.push(`
          SELECT
            id,
            'condition'::text AS kind,
            COALESCE(NULLIF(condition_name, ''), 'Condition') AS title,
            COALESCE(INITCAP(REPLACE(status, '_', ' ')), 'Health context updated') AS detail,
            COALESCE("updatedAt", "createdAt") AS happened_at
          FROM conditions
          WHERE "userId" = '${safeUserId}'
            AND "deletedAt" IS NULL
        `);
      }

      setLoading(true);
      setErrorMessage(null);

      try {
        const [
          hydrationRows,
          moodRows,
          sleepRows,
          weightRows,
          goalCountRows,
          latestGoalRows,
          physicalRows,
          lifestyleRows,
          conditionCountRows,
          latestConditionRows,
          activityRows,
        ] = await Promise.all([
          permissions.hydrationRead
            ? runSql<{
                hydration_total_ml: number | string | null;
                hydration_logs_today: number | string | null;
              }>(`
                SELECT
                  COALESCE(SUM(CASE WHEN counts_toward_hydration THEN volume_ml ELSE 0 END), 0)::int AS hydration_total_ml,
                  COUNT(*)::int AS hydration_logs_today
                FROM hydration_logs
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                  AND logged_at::date = CURRENT_DATE
              `)
            : Promise.resolve([]),
          permissions.moodRead
            ? runSql<MoodRow>(`
                SELECT mood_score, energy_level, anxiety_level, emotion_tags_csv, logged_at
                FROM mood_logs
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                  AND logged_at::date = CURRENT_DATE
                ORDER BY logged_at DESC
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.sleepRead
            ? runSql<SleepRow>(`
                SELECT bedtime, final_wake_time, total_sleep_minutes, sleep_quality, morning_energy
                FROM sleep_logs
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                ORDER BY COALESCE(final_wake_time, bedtime) DESC NULLS LAST
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.weightRead
            ? runSql<WeightRow>(`
                SELECT measured_at, value_primary, unit, notes
                FROM health_metrics
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                  AND metric_type = 'body_composition'
                ORDER BY measured_at DESC NULLS LAST, "createdAt" DESC
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.goalsRead
            ? runSql<CountRow>(`
                SELECT COUNT(*)::int AS count
                FROM goals
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                  AND is_active = true
              `)
            : Promise.resolve([]),
          permissions.goalsRead
            ? runSql<GoalRow>(`
                SELECT id, goal_type, follow_up_answer, target_date, is_active
                FROM goals
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                ORDER BY
                  CASE WHEN is_active = true THEN 0 ELSE 1 END,
                  CASE WHEN target_date IS NULL THEN 1 ELSE 0 END,
                  target_date ASC,
                  "createdAt" DESC
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.physicalRead
            ? runSql<PhysicalRow>(`
                SELECT
                  height_cm,
                  weight_kg,
                  dominant_hand,
                  blood_type,
                  body_frame_size,
                  COALESCE("updatedAt", "createdAt") AS updated_at
                FROM user_physical_baselines
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                ORDER BY COALESCE("updatedAt", "createdAt") DESC NULLS LAST
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.lifestyleRead
            ? runSql<LifestyleRow>(`
                SELECT
                  typical_bedtime,
                  typical_wake_time,
                  caffeine_servings_per_day,
                  avg_daily_steps_estimate,
                  typical_stress_level,
                  currently_exercises,
                  diet_pattern,
                  alcohol_use,
                  tobacco_nicotine_use,
                  COALESCE("updatedAt", "createdAt") AS updated_at
                FROM user_lifestyle_baselines
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                ORDER BY COALESCE("updatedAt", "createdAt") DESC NULLS LAST
                LIMIT 1
              `)
            : Promise.resolve([]),
          permissions.conditionsRead
            ? runSql<CountRow>(`
                SELECT COUNT(*)::int AS count
                FROM conditions
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
              `)
            : Promise.resolve([]),
          permissions.conditionsRead
            ? runSql<ConditionRow>(`
                SELECT
                  id,
                  condition_name,
                  status,
                  diagnosing_doctor,
                  management_plan,
                  COALESCE("updatedAt", "createdAt") AS updated_at
                FROM conditions
                WHERE "userId" = '${safeUserId}'
                  AND "deletedAt" IS NULL
                ORDER BY COALESCE("updatedAt", "createdAt") DESC NULLS LAST
                LIMIT 1
              `)
            : Promise.resolve([]),
          activityQueries.length > 0
            ? runSql<ActivityEntry>(`
                SELECT *
                FROM (
                  ${activityQueries.join('\nUNION ALL\n')}
                ) AS dashboard_activity
                WHERE happened_at IS NOT NULL
                ORDER BY happened_at DESC
                LIMIT 8
              `)
            : Promise.resolve([]),
        ]);

        setDashboardData({
          hydrationTotalMl: toCount(hydrationRows[0]?.hydration_total_ml),
          hydrationLogsToday: toCount(hydrationRows[0]?.hydration_logs_today),
          moodToday: moodRows[0] ?? null,
          sleepLatest: sleepRows[0] ?? null,
          weightLatest: weightRows[0] ?? null,
          activeGoalsCount: toCount(goalCountRows[0]?.count),
          conditionsCount: toCount(conditionCountRows[0]?.count),
          latestGoal: latestGoalRows[0] ?? null,
          latestPhysical: physicalRows[0] ?? null,
          latestLifestyle: lifestyleRows[0] ?? null,
          latestCondition: latestConditionRows[0] ?? null,
          recentActivity: activityRows,
        });
      } catch (error) {
        console.error('Failed to load APEX BRAIN dashboard:', error);
        setErrorMessage(
          'We could not load your personalized home dashboard just now. Your saved data is still intact, so please refresh and try again.',
        );
      } finally {
        setLoading(false);
      }
    },
    [
      permissions.conditionsRead,
      permissions.goalsRead,
      permissions.hydrationRead,
      permissions.lifestyleRead,
      permissions.moodRead,
      permissions.physicalRead,
      permissions.sleepRead,
      permissions.weightRead,
    ],
  );

  useEffect(() => {
    if (!currentUser?.id) {
      return;
    }

    loadDashboard(currentUser.id).catch((error) => {
      console.error('Unhandled APEX BRAIN dashboard load error:', error);
    });
  }, [currentUser?.id, loadDashboard]);

  const greeting = useMemo(() => {
    const hour = new Date().getHours();

    if (hour < 12) {
      return 'Good morning';
    }

    if (hour < 18) {
      return 'Good afternoon';
    }

    return 'Good evening';
  }, []);

  const displayName = useMemo(
    () => getDisplayName(currentUser?.firstName, currentUser?.email),
    [currentUser?.email, currentUser?.firstName],
  );

  const summaryCards = useMemo<SummaryCard[]>(() => {
    const hydrationProgress = Math.min(
      dashboardData.hydrationTotalMl / WATER_GOAL_ML,
      1,
    );
    const sleepTimestamp =
      dashboardData.sleepLatest?.final_wake_time ||
      dashboardData.sleepLatest?.bedtime;
    const weightToday = isToday(dashboardData.weightLatest?.measured_at);
    const sleepLogged = hasRecentSleep(sleepTimestamp);
    const moodLogged = Boolean(dashboardData.moodToday?.logged_at);

    return [
      {
        label: 'Hydration',
        icon: mdiWaterOutline,
        value: permissions.hydrationRead
          ? `${dashboardData.hydrationTotalMl.toLocaleString()} ml`
          : 'Locked',
        detail: permissions.hydrationRead
          ? `${Math.min(
              100,
              Math.round(hydrationProgress * 100),
            )}% of your 2L hydration target`
          : 'View access for hydration logs is not enabled.',
        isComplete:
          permissions.hydrationRead && dashboardData.hydrationTotalMl > 0,
        isAvailable: permissions.hydrationRead,
      },
      {
        label: 'Mood',
        icon: mdiHeartPulse,
        value: permissions.moodRead
          ? dashboardData.moodToday?.mood_score
            ? `${dashboardData.moodToday.mood_score}/10 mood`
            : 'Not logged yet'
          : 'Locked',
        detail: permissions.moodRead
          ? dashboardData.moodToday?.energy_level ||
            dashboardData.moodToday?.anxiety_level
            ? `Energy ${dashboardData.moodToday?.energy_level ?? '-'} • Anxiety ${dashboardData.moodToday?.anxiety_level ?? '-'}`
            : 'Capture how you felt today'
          : 'View access for mood logs is not enabled.',
        isComplete: permissions.moodRead && moodLogged,
        isAvailable: permissions.moodRead,
      },
      {
        label: 'Sleep',
        icon: mdiWeatherNight,
        value: permissions.sleepRead
          ? formatMinutes(dashboardData.sleepLatest?.total_sleep_minutes)
          : 'Locked',
        detail: permissions.sleepRead
          ? dashboardData.sleepLatest?.sleep_quality
            ? `Quality ${dashboardData.sleepLatest.sleep_quality}/10 • Logged ${formatDateTime(sleepTimestamp)}`
            : 'Add your last sleep block'
          : 'View access for sleep logs is not enabled.',
        isComplete: permissions.sleepRead && sleepLogged,
        isAvailable: permissions.sleepRead,
      },
      {
        label: 'Weight',
        icon: mdiScaleBathroom,
        value: permissions.weightRead
          ? dashboardData.weightLatest?.value_primary
            ? `${dashboardData.weightLatest.value_primary} ${dashboardData.weightLatest.unit ?? ''}`.trim()
            : 'Not logged yet'
          : 'Locked',
        detail: permissions.weightRead
          ? dashboardData.weightLatest?.measured_at
            ? `Measured ${formatDateTime(dashboardData.weightLatest.measured_at)}`
            : 'Optional body-composition check'
          : 'View access for health metrics is not enabled.',
        isComplete: permissions.weightRead && weightToday,
        isAvailable: permissions.weightRead,
      },
    ];
  }, [
    dashboardData.hydrationTotalMl,
    dashboardData.moodToday,
    dashboardData.sleepLatest,
    dashboardData.weightLatest,
    permissions.hydrationRead,
    permissions.moodRead,
    permissions.sleepRead,
    permissions.weightRead,
  ]);

  const accessibleSummaryCards = useMemo(
    () => summaryCards.filter((card) => card.isAvailable),
    [summaryCards],
  );

  const completedCount = accessibleSummaryCards.filter(
    (card) => card.isComplete,
  ).length;

  const completionPercent = accessibleSummaryCards.length
    ? Math.round((completedCount / accessibleSummaryCards.length) * 100)
    : 0;

  const availablePulsePoints =
    (permissions.hydrationRead ? 25 : 0) +
    (permissions.moodRead ? 25 : 0) +
    (permissions.sleepRead ? 25 : 0) +
    (permissions.weightRead ? 25 : 0);

  const earnedPulsePoints =
    (permissions.hydrationRead
      ? Math.round(
          Math.min(dashboardData.hydrationTotalMl / WATER_GOAL_ML, 1) * 25,
        )
      : 0) +
    (summaryCards[1]?.isComplete ? 25 : 0) +
    (summaryCards[2]?.isComplete ? 25 : 0) +
    (summaryCards[3]?.isComplete ? 25 : 0);

  const pulseScore = availablePulsePoints
    ? Math.round((earnedPulsePoints / availablePulsePoints) * 100)
    : 0;

  const profileChecklist = useMemo(
    () => [
      {
        label: 'First name',
        isComplete: Boolean(currentUser?.firstName?.trim()),
      },
      {
        label: 'Phone number',
        isComplete: Boolean(currentUser?.phoneNumber?.trim()),
      },
      {
        label: 'Height baseline',
        isComplete:
          dashboardData.latestPhysical?.height_cm !== null &&
          dashboardData.latestPhysical?.height_cm !== undefined,
      },
      {
        label: 'Weight baseline',
        isComplete:
          dashboardData.latestPhysical?.weight_kg !== null &&
          dashboardData.latestPhysical?.weight_kg !== undefined,
      },
      {
        label: 'Typical bedtime',
        isComplete: Boolean(dashboardData.latestLifestyle?.typical_bedtime),
      },
      {
        label: 'Typical wake time',
        isComplete: Boolean(dashboardData.latestLifestyle?.typical_wake_time),
      },
      {
        label: 'Primary goal',
        isComplete: Boolean(dashboardData.latestGoal?.goal_type),
      },
      {
        label: 'Goal target date',
        isComplete: Boolean(dashboardData.latestGoal?.target_date),
      },
    ],
    [
      currentUser?.firstName,
      currentUser?.phoneNumber,
      dashboardData.latestGoal?.goal_type,
      dashboardData.latestGoal?.target_date,
      dashboardData.latestLifestyle?.typical_bedtime,
      dashboardData.latestLifestyle?.typical_wake_time,
      dashboardData.latestPhysical?.height_cm,
      dashboardData.latestPhysical?.weight_kg,
    ],
  );

  const profileCompleteness = Math.round(
    (profileChecklist.filter((item) => item.isComplete).length /
      profileChecklist.length) *
      100,
  );

  const missingProfileItems = profileChecklist
    .filter((item) => !item.isComplete)
    .slice(0, 3);

  const nextBestActions = useMemo(() => {
    const actions: QuickAction[] = [];

    if (!onboardingComplete || profileCompleteness < 100) {
      actions.push({
        href: '/onboarding',
        title: onboardingComplete ? 'Polish your setup' : 'Finish onboarding',
        description:
          'Complete your personal, baseline, and goal details so summaries feel truly personal.',
        icon: mdiAccount,
      });
    }

    const firstIncompleteDailyAnchor = accessibleSummaryCards.find(
      (card) => !card.isComplete,
    );

    if (firstIncompleteDailyAnchor) {
      actions.push({
        href: '/daily-pulse',
        title: `Complete today's ${firstIncompleteDailyAnchor.label.toLowerCase()} check-in`,
        description:
          'Open Daily Pulse to capture the missing piece and strengthen today’s wellness picture.',
        icon: mdiHeartPulse,
      });
    }

    if (!dashboardData.latestGoal && permissions.goalsRead) {
      actions.push({
        href: '/goals/goals-list',
        title: 'Choose a primary goal',
        description:
          'Anchor the app around one clear outcome so Daily Pulse and deeper modules stay purposeful.',
        icon: mdiTargetVariant,
      });
    } else if (dashboardData.latestGoal && permissions.goalsRead) {
      actions.push({
        href: '/goals/goals-list',
        title: 'Review your goal plan',
        description:
          'Open the goal vault to keep target dates and follow-up notes aligned with your current focus.',
        icon: mdiTargetVariant,
      });
    }

    if (
      (!dashboardData.latestPhysical || !dashboardData.latestLifestyle) &&
      (permissions.physicalRead || permissions.lifestyleRead)
    ) {
      actions.push({
        href: '/onboarding',
        title: 'Add your baseline context',
        description:
          'A stronger body and lifestyle baseline makes trends, summaries, and future reports more useful.',
        icon: mdiLeafCircle,
      });
    }

    if (dashboardData.recentActivity.length === 0) {
      actions.push({
        href: '/daily-pulse',
        title: 'Create your first health entry',
        description:
          'Start with one Daily Pulse check-in so your home dashboard has real momentum to build from.',
        icon: mdiArrowTopRight,
      });
    }

    if (actions.length === 0) {
      actions.push(
        {
          href: '/daily-pulse',
          title: 'Open Daily Pulse',
          description:
            'Keep today’s hydration, mood, sleep, and weight picture fresh.',
          icon: mdiHeartPulse,
        },
        {
          href: '/goals/goals-list',
          title: 'Review active goals',
          description:
            'Make sure your target dates and action plans still match what matters most right now.',
          icon: mdiTargetVariant,
        },
      );
    }

    const seenHrefs = new Set<string>();

    return actions.filter((action) => {
      if (seenHrefs.has(action.href)) {
        return false;
      }

      seenHrefs.add(action.href);
      return true;
    });
  }, [
    accessibleSummaryCards,
    dashboardData.latestGoal,
    dashboardData.latestLifestyle,
    dashboardData.latestPhysical,
    dashboardData.recentActivity.length,
    onboardingComplete,
    permissions.goalsRead,
    permissions.lifestyleRead,
    permissions.physicalRead,
    profileCompleteness,
  ]);

  const lifestyleHighlights = useMemo(() => {
    if (!dashboardData.latestLifestyle) {
      return [];
    }

    const highlights = [
      {
        label: 'Typical sleep window',
        value:
          dashboardData.latestLifestyle.typical_bedtime ||
          dashboardData.latestLifestyle.typical_wake_time
            ? `${formatClockTime(
                dashboardData.latestLifestyle.typical_bedtime,
              )} → ${formatClockTime(
                dashboardData.latestLifestyle.typical_wake_time,
              )}`
            : 'Not set',
      },
      {
        label: 'Stress baseline',
        value:
          dashboardData.latestLifestyle.typical_stress_level !== null &&
          dashboardData.latestLifestyle.typical_stress_level !== undefined
            ? `${dashboardData.latestLifestyle.typical_stress_level}/10`
            : 'Not set',
      },
      {
        label: 'Daily steps estimate',
        value: formatNumber(
          dashboardData.latestLifestyle.avg_daily_steps_estimate,
        ),
      },
      {
        label: 'Diet pattern',
        value: dashboardData.latestLifestyle.diet_pattern
          ? humanize(dashboardData.latestLifestyle.diet_pattern)
          : 'Not set',
      },
      {
        label: 'Exercises regularly',
        value:
          dashboardData.latestLifestyle.currently_exercises === null ||
          dashboardData.latestLifestyle.currently_exercises === undefined
            ? 'Not set'
            : dashboardData.latestLifestyle.currently_exercises
              ? 'Yes'
              : 'No',
      },
      {
        label: 'Caffeine / day',
        value: formatNumber(
          dashboardData.latestLifestyle.caffeine_servings_per_day,
        ),
      },
    ];

    return highlights.filter((highlight) => highlight.value !== 'Not set');
  }, [dashboardData.latestLifestyle]);

  const baselineHighlights = useMemo(() => {
    if (!dashboardData.latestPhysical) {
      return [];
    }

    const highlights = [
      {
        label: 'Height baseline',
        value: formatNumber(dashboardData.latestPhysical.height_cm, 'cm'),
      },
      {
        label: 'Weight baseline',
        value: formatNumber(dashboardData.latestPhysical.weight_kg, 'kg'),
      },
      {
        label: 'Dominant hand',
        value: dashboardData.latestPhysical.dominant_hand
          ? humanize(dashboardData.latestPhysical.dominant_hand)
          : 'Not set',
      },
      {
        label: 'Blood type',
        value: dashboardData.latestPhysical.blood_type
          ? humanize(dashboardData.latestPhysical.blood_type)
          : 'Not set',
      },
      {
        label: 'Body frame',
        value: dashboardData.latestPhysical.body_frame_size
          ? humanize(dashboardData.latestPhysical.body_frame_size)
          : 'Not set',
      },
    ];

    return highlights.filter((highlight) => highlight.value !== 'Not set');
  }, [dashboardData.latestPhysical]);

  return (
    <>
      <Head>
        <title>{getPageTitle('APEX BRAIN Home')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title="APEX BRAIN Home"
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <div
          className="rounded-[32px] border p-6 shadow-sm lg:p-8"
          style={{
            borderColor: palette.borderStrong,
            background:
              'linear-gradient(135deg, rgba(255,249,240,0.98) 0%, rgba(251,247,240,0.98) 50%, rgba(237,244,234,0.9) 100%)',
          }}
        >
          <div className="grid gap-8 xl:grid-cols-[1.15fr_0.85fr] xl:items-center">
            <div>
              <div className="flex flex-wrap items-center gap-3">
                <span
                  className="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em]"
                  style={{
                    borderColor: palette.borderStrong,
                    color: palette.forest,
                    backgroundColor: 'rgba(255,255,255,0.62)',
                  }}
                >
                  <BaseIcon path={mdiCheckCircleOutline} size={16} />
                  {onboardingComplete
                    ? 'Personalized setup ready'
                    : 'Setup still in progress'}
                </span>
                <span
                  className="inline-flex items-center gap-2 rounded-full px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em]"
                  style={{
                    color: palette.charcoal,
                    backgroundColor: palette.goldSoft,
                  }}
                >
                  Healthcare-first daily home
                </span>
              </div>

              <h2
                className="mt-5 text-4xl font-semibold tracking-tight md:text-5xl"
                style={{ color: palette.charcoal }}
              >
                {greeting}, {displayName}.
              </h2>
              <p
                className="mt-4 max-w-3xl text-base leading-7 md:text-lg"
                style={{ color: palette.body }}
              >
                This is your personalized APEX BRAIN home: a calm summary of
                today’s Daily Pulse, your setup progress, your current goal, and
                the latest health activity already stored in the app.
              </p>

              <div className="mt-6 flex flex-wrap gap-3">
                <Link
                  href="/daily-pulse"
                  className="inline-flex items-center justify-center rounded-full px-5 py-3 text-sm font-semibold text-white transition hover:-translate-y-0.5"
                  style={{ backgroundColor: palette.forest }}
                >
                  Open Daily Pulse
                </Link>
                <Link
                  href="/onboarding"
                  className="inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition hover:-translate-y-0.5"
                  style={{
                    borderColor: palette.borderStrong,
                    color: palette.forest,
                    backgroundColor: 'rgba(255,255,255,0.66)',
                  }}
                >
                  {onboardingComplete ? 'Review onboarding' : 'Finish onboarding'}
                </Link>
              </div>

              <div className="mt-8 grid gap-4 sm:grid-cols-3">
                <div
                  className="rounded-3xl border p-4"
                  style={{
                    borderColor: palette.border,
                    backgroundColor: 'rgba(255,255,255,0.74)',
                  }}
                >
                  <div
                    className="text-sm font-medium uppercase tracking-[0.18em]"
                    style={{ color: palette.muted }}
                  >
                    Setup completeness
                  </div>
                  <div
                    className="mt-2 text-3xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    {loading ? '…' : `${profileCompleteness}%`}
                  </div>
                  <p className="mt-2 text-sm" style={{ color: palette.body }}>
                    {loading
                      ? 'Reviewing your setup...'
                      : missingProfileItems.length > 0
                        ? `Still missing ${missingProfileItems
                            .map((item) => item.label.toLowerCase())
                            .join(', ')}.`
                        : 'Your core profile setup looks complete.'}
                  </p>
                </div>

                <div
                  className="rounded-3xl border p-4"
                  style={{
                    borderColor: palette.border,
                    backgroundColor: 'rgba(255,255,255,0.74)',
                  }}
                >
                  <div
                    className="text-sm font-medium uppercase tracking-[0.18em]"
                    style={{ color: palette.muted }}
                  >
                    Active goals
                  </div>
                  <div
                    className="mt-2 text-3xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    {loading ? '…' : dashboardData.activeGoalsCount}
                  </div>
                  <p className="mt-2 text-sm" style={{ color: palette.body }}>
                    {loading
                      ? 'Gathering your focus areas...'
                      : dashboardData.latestGoal?.goal_type
                        ? humanize(dashboardData.latestGoal.goal_type)
                        : 'No primary goal recorded yet.'}
                  </p>
                </div>

                <div
                  className="rounded-3xl border p-4"
                  style={{
                    borderColor: palette.border,
                    backgroundColor: 'rgba(255,255,255,0.74)',
                  }}
                >
                  <div
                    className="text-sm font-medium uppercase tracking-[0.18em]"
                    style={{ color: palette.muted }}
                  >
                    Conditions tracked
                  </div>
                  <div
                    className="mt-2 text-3xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    {loading ? '…' : dashboardData.conditionsCount}
                  </div>
                  <p className="mt-2 text-sm" style={{ color: palette.body }}>
                    {loading
                      ? 'Refreshing your care context...'
                      : dashboardData.latestCondition?.condition_name
                        ? `${dashboardData.latestCondition.condition_name}${dashboardData.latestCondition.status ? ` • ${humanize(dashboardData.latestCondition.status)}` : ''}`
                        : 'Add conditions only if they matter to your care context.'}
                  </p>
                </div>
              </div>
            </div>

            <div className="flex justify-center xl:justify-end">
              <div
                className="w-full max-w-sm rounded-[32px] border p-6 text-center shadow-sm"
                style={{
                  borderColor: palette.borderStrong,
                  backgroundColor: 'rgba(255,255,255,0.84)',
                }}
              >
                <div className="relative mx-auto h-56 w-56">
                  <div
                    className="absolute inset-0 rounded-full"
                    style={{
                      background: `conic-gradient(${palette.forest} ${completionPercent}%, #E9DDCC ${completionPercent}% 100%)`,
                    }}
                  />
                  <div
                    className="absolute inset-[16px] rounded-full"
                    style={{
                      backgroundColor: palette.panelBg,
                      boxShadow:
                        'inset 0 0 0 1px rgba(201, 168, 76, 0.18)',
                    }}
                  />
                  <div className="absolute inset-0 flex flex-col items-center justify-center">
                    <div
                      className="text-sm uppercase tracking-[0.2em]"
                      style={{ color: palette.muted }}
                    >
                      Today&apos;s readiness
                    </div>
                    <div
                      className="mt-2 text-5xl font-semibold"
                      style={{ color: palette.charcoal }}
                    >
                      {loading ? '…' : pulseScore}
                    </div>
                    <p
                      className="mt-3 max-w-[11rem] text-sm leading-6"
                      style={{ color: palette.forest }}
                    >
                      {loading
                        ? 'Refreshing your daily anchors...'
                        : accessibleSummaryCards.length === 0
                          ? 'No Daily Pulse modules are visible for your current role yet.'
                          : completedCount === accessibleSummaryCards.length
                            ? 'Every available daily anchor is captured.'
                            : `${completedCount} of ${accessibleSummaryCards.length} available anchors are captured.`}
                    </p>
                  </div>
                </div>
                <div
                  className="mt-6 flex items-center justify-center gap-2 text-sm font-medium"
                  style={{ color: palette.forest }}
                >
                  <BaseIcon path={mdiCalendarHeart} size={18} />
                  {new Intl.DateTimeFormat(undefined, {
                    weekday: 'long',
                    month: 'long',
                    day: 'numeric',
                  }).format(new Date())}
                </div>
              </div>
            </div>
          </div>
        </div>

        {errorMessage && (
          <div className="mt-6">
            <NotificationBar color="danger" icon={mdiHeartPulse}>
              {errorMessage}
            </NotificationBar>
          </div>
        )}

        <div className="mt-6 grid gap-6 xl:grid-cols-[1.45fr_0.95fr]">
          <div className="space-y-6">
            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
                <div>
                  <h3
                    className="text-2xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Today at a glance
                  </h3>
                  <p className="mt-2 text-sm leading-6" style={{ color: palette.body }}>
                    Four simple anchors — hydration, mood, sleep, and weight —
                    connected directly to your existing history screens.
                  </p>
                </div>
                <div
                  className="rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em]"
                  style={{ borderColor: palette.borderStrong, color: palette.forest }}
                >
                  {loading
                    ? 'Refreshing'
                    : accessibleSummaryCards.length === 0
                      ? 'No daily anchors visible'
                      : `${completedCount} / ${accessibleSummaryCards.length} anchors captured`}
                </div>
              </div>

              <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                {summaryCards.map((card) => (
                  <div
                    key={card.label}
                    className="rounded-[24px] border p-5 shadow-sm"
                    style={{
                      borderColor: palette.border,
                      backgroundColor: card.isAvailable
                        ? palette.panelAlt
                        : 'rgba(255,255,255,0.55)',
                    }}
                  >
                    <div className="flex items-center justify-between gap-3">
                      <div
                        className="flex h-12 w-12 items-center justify-center rounded-2xl"
                        style={{
                          backgroundColor: palette.goldSoft,
                          color: palette.forest,
                        }}
                      >
                        <BaseIcon path={card.icon} size={24} />
                      </div>
                      <span
                        className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]"
                        style={{
                          color: card.isAvailable
                            ? card.isComplete
                              ? '#2F5A35'
                              : palette.muted
                            : palette.muted,
                          backgroundColor: card.isAvailable && card.isComplete
                            ? 'rgba(74, 103, 65, 0.12)'
                            : 'rgba(201, 168, 76, 0.14)',
                        }}
                      >
                        {card.isAvailable
                          ? card.isComplete
                            ? 'captured'
                            : 'pending'
                          : 'locked'}
                      </span>
                    </div>
                    <h4
                      className="mt-5 text-lg font-semibold"
                      style={{ color: palette.charcoal }}
                    >
                      {card.label}
                    </h4>
                    <p className="mt-2 text-2xl font-semibold" style={{ color: palette.forest }}>
                      {loading ? 'Loading…' : card.value}
                    </p>
                    <p className="mt-3 text-sm leading-6" style={{ color: palette.muted }}>
                      {loading ? 'Refreshing this card...' : card.detail}
                    </p>
                  </div>
                ))}
              </div>
            </div>

            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
                <div>
                  <h3
                    className="text-2xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Recent health activity
                  </h3>
                  <p className="mt-2 text-sm leading-6" style={{ color: palette.body }}>
                    A real timeline pulled from your existing hydration, mood,
                    sleep, weight, goal, and condition records.
                  </p>
                </div>
                <Link
                  href="/daily-pulse"
                  className="text-sm font-semibold"
                  style={{ color: palette.forest }}
                >
                  Log something new →
                </Link>
              </div>

              <div className="mt-6 grid gap-4 md:grid-cols-2">
                {loading &&
                  Array.from({ length: 4 }).map((_, index) => (
                    <div
                      key={`activity-skeleton-${index}`}
                      className="min-h-[170px] rounded-2xl border p-5"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: 'rgba(255,255,255,0.72)',
                      }}
                    >
                      <div
                        className="h-4 w-24 rounded-full"
                        style={{ backgroundColor: '#EFE3D2' }}
                      />
                      <div
                        className="mt-4 h-7 w-3/4 rounded-full"
                        style={{ backgroundColor: '#F3E9DA' }}
                      />
                      <div
                        className="mt-3 h-4 w-1/2 rounded-full"
                        style={{ backgroundColor: '#F3E9DA' }}
                      />
                      <div
                        className="mt-8 h-4 w-2/3 rounded-full"
                        style={{ backgroundColor: '#EFE3D2' }}
                      />
                    </div>
                  ))}

                {!loading && dashboardData.recentActivity.length === 0 && (
                  <div
                    className="rounded-2xl border px-5 py-6 text-sm leading-6 md:col-span-2"
                    style={{
                      borderColor: palette.border,
                      backgroundColor: 'rgba(255,255,255,0.72)',
                      color: palette.body,
                    }}
                  >
                    There isn&apos;t recent activity to show yet. Start with one
                    Daily Pulse check-in or continue onboarding so your home
                    dashboard has something meaningful to reflect.
                  </div>
                )}

                {!loading &&
                  dashboardData.recentActivity.map((item) => {
                    const route = activityRouteByKind[item.kind];

                    return (
                      <Link
                        key={`${item.kind}-${item.id}`}
                        href={`${route}/?id=${item.id}`}
                        className="block rounded-2xl border p-5 transition hover:-translate-y-0.5"
                        style={{
                          borderColor: palette.border,
                          backgroundColor: 'rgba(255,255,255,0.72)',
                        }}
                      >
                        <div className="flex items-center justify-between gap-4">
                          <div
                            className="flex h-12 w-12 items-center justify-center rounded-2xl"
                            style={{
                              backgroundColor: palette.goldSoft,
                              color: palette.forest,
                            }}
                          >
                            <BaseIcon
                              path={activityIconByKind[item.kind]}
                              size={24}
                            />
                          </div>
                          <span
                            className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]"
                            style={{
                              backgroundColor: palette.goldSoft,
                              color: palette.forest,
                            }}
                          >
                            {humanize(item.kind)}
                          </span>
                        </div>
                        <div
                          className="mt-5 text-lg font-semibold"
                          style={{ color: palette.charcoal }}
                        >
                          {item.title}
                        </div>
                        <p className="mt-2 text-sm" style={{ color: palette.forest }}>
                          {item.detail || 'Open the detail view for more context.'}
                        </p>
                        <p
                          className="mt-4 text-xs font-semibold uppercase tracking-[0.18em]"
                          style={{ color: '#8A7C67' }}
                        >
                          {formatDateTime(item.happened_at)}
                        </p>
                      </Link>
                    );
                  })}
              </div>
            </div>
          </div>

          <div className="space-y-6">
            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex items-center gap-3">
                <div
                  className="flex h-12 w-12 items-center justify-center rounded-2xl"
                  style={{ backgroundColor: palette.goldSoft, color: palette.forest }}
                >
                  <BaseIcon path={mdiTargetVariant} size={24} />
                </div>
                <div>
                  <h3
                    className="text-xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Current focus
                  </h3>
                  <p className="text-sm" style={{ color: palette.body }}>
                    The goal shaping your home dashboard right now.
                  </p>
                </div>
              </div>

              {loading ? (
                <p className="mt-5 text-sm" style={{ color: palette.body }}>
                  Loading your current focus...
                </p>
              ) : !permissions.goalsRead ? (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  Goal visibility is not enabled for your current role.
                </div>
              ) : dashboardData.latestGoal ? (
                <>
                  <div className="mt-5 flex items-start justify-between gap-4">
                    <div>
                      <div
                        className="text-2xl font-semibold"
                        style={{ color: palette.charcoal }}
                      >
                        {dashboardData.latestGoal.goal_type
                          ? humanize(dashboardData.latestGoal.goal_type)
                          : 'Primary goal'}
                      </div>
                      <p className="mt-2 text-sm leading-6" style={{ color: palette.body }}>
                        {dashboardData.latestGoal.follow_up_answer
                          ? truncateText(
                              dashboardData.latestGoal.follow_up_answer,
                              150,
                            )
                          : 'Add a richer follow-up note in the goal vault whenever you want more context here.'}
                      </p>
                    </div>
                    <span
                      className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]"
                      style={{
                        color: dashboardData.latestGoal.is_active
                          ? '#2F5A35'
                          : palette.muted,
                        backgroundColor: dashboardData.latestGoal.is_active
                          ? 'rgba(74, 103, 65, 0.12)'
                          : 'rgba(201, 168, 76, 0.14)',
                      }}
                    >
                      {dashboardData.latestGoal.is_active ? 'active' : 'latest'}
                    </span>
                  </div>

                  <div className="mt-5 grid gap-3 sm:grid-cols-2">
                    <div
                      className="rounded-2xl border px-4 py-4"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: 'rgba(255,255,255,0.72)',
                      }}
                    >
                      <div
                        className="text-xs font-semibold uppercase tracking-[0.18em]"
                        style={{ color: palette.muted }}
                      >
                        Target date
                      </div>
                      <div className="mt-2 font-semibold" style={{ color: palette.forest }}>
                        {formatDate(dashboardData.latestGoal.target_date)}
                      </div>
                    </div>
                    <div
                      className="rounded-2xl border px-4 py-4"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: 'rgba(255,255,255,0.72)',
                      }}
                    >
                      <div
                        className="text-xs font-semibold uppercase tracking-[0.18em]"
                        style={{ color: palette.muted }}
                      >
                        Active goals total
                      </div>
                      <div className="mt-2 font-semibold" style={{ color: palette.forest }}>
                        {dashboardData.activeGoalsCount}
                      </div>
                    </div>
                  </div>

                  <Link
                    href="/goals/goals-list"
                    className="mt-5 inline-flex items-center gap-2 text-sm font-semibold"
                    style={{ color: palette.forest }}
                  >
                    Open goal vault
                    <BaseIcon path={mdiArrowTopRight} size={16} />
                  </Link>
                </>
              ) : (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  No goal has been saved yet. Use onboarding or the goal vault to
                  choose one clear north star for this dashboard.
                  <div className="mt-4">
                    <Link
                      href="/onboarding"
                      className="font-semibold"
                      style={{ color: palette.forest }}
                    >
                      Choose your first goal →
                    </Link>
                  </div>
                </div>
              )}
            </div>

            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex items-center gap-3">
                <div
                  className="flex h-12 w-12 items-center justify-center rounded-2xl"
                  style={{ backgroundColor: palette.goldSoft, color: palette.forest }}
                >
                  <BaseIcon path={mdiLeafCircle} size={24} />
                </div>
                <div>
                  <h3
                    className="text-xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Health baseline snapshot
                  </h3>
                  <p className="text-sm" style={{ color: palette.body }}>
                    Your most recent body and lifestyle baselines, surfaced for context.
                  </p>
                </div>
              </div>

              {loading ? (
                <p className="mt-5 text-sm" style={{ color: palette.body }}>
                  Loading your baseline snapshot...
                </p>
              ) : !permissions.physicalRead && !permissions.lifestyleRead ? (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  Baseline visibility is not enabled for your current role.
                </div>
              ) : baselineHighlights.length === 0 && lifestyleHighlights.length === 0 ? (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  Your body and lifestyle baseline still looks light. Continue
                  onboarding to give future trends and reports stronger context.
                </div>
              ) : (
                <div className="mt-5 space-y-4">
                  {baselineHighlights.length > 0 && (
                    <div>
                      <div
                        className="text-xs font-semibold uppercase tracking-[0.18em]"
                        style={{ color: palette.muted }}
                      >
                        Body baseline
                      </div>
                      <div className="mt-3 grid gap-3 sm:grid-cols-2">
                        {baselineHighlights.map((item) => (
                          <div
                            key={item.label}
                            className="rounded-2xl border px-4 py-4"
                            style={{
                              borderColor: palette.border,
                              backgroundColor: 'rgba(255,255,255,0.72)',
                            }}
                          >
                            <div className="text-xs font-semibold uppercase tracking-[0.16em]" style={{ color: palette.muted }}>
                              {item.label}
                            </div>
                            <div className="mt-2 font-semibold" style={{ color: palette.charcoal }}>
                              {item.value}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {lifestyleHighlights.length > 0 && (
                    <div>
                      <div
                        className="text-xs font-semibold uppercase tracking-[0.18em]"
                        style={{ color: palette.muted }}
                      >
                        Lifestyle baseline
                      </div>
                      <div className="mt-3 grid gap-3 sm:grid-cols-2">
                        {lifestyleHighlights.map((item) => (
                          <div
                            key={item.label}
                            className="rounded-2xl border px-4 py-4"
                            style={{
                              borderColor: palette.border,
                              backgroundColor: 'rgba(255,255,255,0.72)',
                            }}
                          >
                            <div className="text-xs font-semibold uppercase tracking-[0.16em]" style={{ color: palette.muted }}>
                              {item.label}
                            </div>
                            <div className="mt-2 font-semibold" style={{ color: palette.charcoal }}>
                              {item.value}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  <Link
                    href="/onboarding"
                    className="inline-flex items-center gap-2 text-sm font-semibold"
                    style={{ color: palette.forest }}
                  >
                    Update onboarding and baseline
                    <BaseIcon path={mdiArrowTopRight} size={16} />
                  </Link>
                </div>
              )}
            </div>

            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex items-center gap-3">
                <div
                  className="flex h-12 w-12 items-center justify-center rounded-2xl"
                  style={{ backgroundColor: palette.goldSoft, color: palette.forest }}
                >
                  <BaseIcon path={mdiArrowTopRight} size={24} />
                </div>
                <div>
                  <h3
                    className="text-xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Next best actions
                  </h3>
                  <p className="text-sm" style={{ color: palette.body }}>
                    Personalized shortcuts based on what your dashboard is missing.
                  </p>
                </div>
              </div>

              <div className="mt-5 space-y-3">
                {nextBestActions.map((action) => (
                  <Link
                    key={`${action.href}-${action.title}`}
                    href={action.href}
                    className="block rounded-2xl border px-4 py-4 transition hover:-translate-y-0.5"
                    style={{
                      borderColor: palette.border,
                      backgroundColor: 'rgba(255,255,255,0.72)',
                    }}
                  >
                    <div className="flex items-start gap-4">
                      <div
                        className="mt-1 flex h-10 w-10 items-center justify-center rounded-2xl"
                        style={{
                          backgroundColor: palette.goldSoft,
                          color: palette.forest,
                        }}
                      >
                        <BaseIcon path={action.icon} size={20} />
                      </div>
                      <div>
                        <div className="text-base font-semibold" style={{ color: palette.charcoal }}>
                          {action.title}
                        </div>
                        <p className="mt-1 text-sm leading-6" style={{ color: palette.body }}>
                          {action.description}
                        </p>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            </div>

            <div
              className="rounded-[28px] border p-6 shadow-sm"
              style={{
                borderColor: palette.borderStrong,
                backgroundColor: palette.panelBg,
              }}
            >
              <div className="flex items-center gap-3">
                <div
                  className="flex h-12 w-12 items-center justify-center rounded-2xl"
                  style={{ backgroundColor: palette.goldSoft, color: palette.forest }}
                >
                  <BaseIcon path={mdiHeartPulse} size={24} />
                </div>
                <div>
                  <h3
                    className="text-xl font-semibold"
                    style={{ color: palette.charcoal }}
                  >
                    Care context
                  </h3>
                  <p className="text-sm" style={{ color: palette.body }}>
                    The latest condition context currently visible on your account.
                  </p>
                </div>
              </div>

              {loading ? (
                <p className="mt-5 text-sm" style={{ color: palette.body }}>
                  Loading your care context...
                </p>
              ) : !permissions.conditionsRead ? (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  Condition visibility is not enabled for your current role.
                </div>
              ) : dashboardData.latestCondition ? (
                <>
                  <div className="mt-5 flex items-start justify-between gap-4">
                    <div>
                      <div className="text-2xl font-semibold" style={{ color: palette.charcoal }}>
                        {dashboardData.latestCondition.condition_name || 'Condition'}
                      </div>
                      <p className="mt-2 text-sm leading-6" style={{ color: palette.body }}>
                        {dashboardData.latestCondition.management_plan
                          ? truncateText(
                              dashboardData.latestCondition.management_plan,
                              140,
                            )
                          : 'Add a management plan in the conditions module when you want more clinical detail here.'}
                      </p>
                    </div>
                    <span
                      className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]"
                      style={{
                        color: palette.forest,
                        backgroundColor: 'rgba(74, 103, 65, 0.12)',
                      }}
                    >
                      {dashboardData.latestCondition.status
                        ? humanize(dashboardData.latestCondition.status)
                        : 'Tracked'}
                    </span>
                  </div>

                  <div className="mt-5 grid gap-3 sm:grid-cols-2">
                    <div
                      className="rounded-2xl border px-4 py-4"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: 'rgba(255,255,255,0.72)',
                      }}
                    >
                      <div className="text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: palette.muted }}>
                        Diagnosing doctor
                      </div>
                      <div className="mt-2 font-semibold" style={{ color: palette.forest }}>
                        {dashboardData.latestCondition.diagnosing_doctor || 'Not recorded'}
                      </div>
                    </div>
                    <div
                      className="rounded-2xl border px-4 py-4"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: 'rgba(255,255,255,0.72)',
                      }}
                    >
                      <div className="text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: palette.muted }}>
                        Last updated
                      </div>
                      <div className="mt-2 font-semibold" style={{ color: palette.forest }}>
                        {formatDateTime(dashboardData.latestCondition.updated_at)}
                      </div>
                    </div>
                  </div>

                  <Link
                    href="/conditions/conditions-list"
                    className="mt-5 inline-flex items-center gap-2 text-sm font-semibold"
                    style={{ color: palette.forest }}
                  >
                    Open conditions
                    <BaseIcon path={mdiArrowTopRight} size={16} />
                  </Link>
                </>
              ) : (
                <div
                  className="mt-5 rounded-2xl border px-4 py-5 text-sm leading-6"
                  style={{ borderColor: palette.border, color: palette.body }}
                >
                  No conditions are currently tracked on this account. That is
                  completely fine if there is nothing clinically relevant to add.
                </div>
              )}
            </div>
          </div>
        </div>
      </SectionMain>
    </>
  );
}

DashboardPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default DashboardPage;
