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

type FeedbackState = {
  color: 'success' | 'danger';
  message: string;
} | null;

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;
  follow_up_answer: string | null;
  target_date: string | null;
};

type ActivityEntry = {
  id: string;
  kind: 'hydration' | 'mood' | 'sleep' | 'weight';
  title: string;
  detail: string | null;
  happened_at: string | null;
};

type SummaryState = {
  hydrationTotalMl: number;
  hydrationLogsToday: number;
  moodToday: MoodRow | null;
  sleepLatest: SleepRow | null;
  weightLatest: WeightRow | null;
};

type PulseFormState = {
  hydrationLoggedAt: string;
  volumeMl: string;
  beverageType: string;
  containerLabel: string;
  countsTowardHydration: boolean;
  moodLoggedAt: string;
  moodScore: string;
  moodTags: string;
  energyLevel: string;
  anxietyLevel: string;
  journalEntry: string;
  sleepBedtime: string;
  sleepWakeTime: string;
  sleepQuality: string;
  morningEnergy: string;
  sleepDisturbances: string;
  weightMeasuredAt: string;
  weightValue: string;
  weightUnit: 'kg' | 'lb';
  weightNotes: string;
};

const WATER_GOAL_ML = 2000;
const DAILY_PULSE_DEVICE = 'APEX BRAIN Daily Pulse';

const activityRouteByKind: Record<ActivityEntry['kind'], 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',
};

const quickLinks = [
  {
    href: '/hydration_logs/hydration_logs-list',
    title: 'Hydration history',
    description: 'Review every bottle, cup, and hydration pattern.',
    icon: mdiWaterOutline,
  },
  {
    href: '/mood_logs/mood_logs-list',
    title: 'Mood journal',
    description: 'See emotional trends and coaching notes over time.',
    icon: mdiEmoticonHappyOutline,
  },
  {
    href: '/sleep_logs/sleep_logs-list',
    title: 'Sleep trends',
    description: 'Open your bedtime, wake time, and recovery history.',
    icon: mdiWeatherNight,
  },
  {
    href: '/goals/goals-list',
    title: 'Goal vault',
    description: 'Keep active goals aligned with the habits that matter.',
    icon: mdiTargetVariant,
  },
];

function pad(value: number) {
  return String(value).padStart(2, '0');
}

function toLocalDateTimeValue(date: Date) {
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

function initialPulseForm(): PulseFormState {
  const now = new Date();

  return {
    hydrationLoggedAt: toLocalDateTimeValue(now),
    volumeMl: '',
    beverageType: 'water',
    containerLabel: '',
    countsTowardHydration: true,
    moodLoggedAt: toLocalDateTimeValue(now),
    moodScore: '',
    moodTags: '',
    energyLevel: '',
    anxietyLevel: '',
    journalEntry: '',
    sleepBedtime: '',
    sleepWakeTime: '',
    sleepQuality: '',
    morningEnergy: '',
    sleepDisturbances: '',
    weightMeasuredAt: toLocalDateTimeValue(now),
    weightValue: '',
    weightUnit: 'kg',
    weightNotes: '',
  };
}

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 formatDateTime(value?: string | null) {
  if (!value) {
    return 'Not recorded 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';
  }

  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 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 toIsoString(value: string) {
  return new Date(value).toISOString();
}

function DailyPulsePage() {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [form, setForm] = useState<PulseFormState>(initialPulseForm);
  const [feedback, setFeedback] = useState<FeedbackState>(null);
  const [summary, setSummary] = useState<SummaryState>({
    hydrationTotalMl: 0,
    hydrationLogsToday: 0,
    moodToday: null,
    sleepLatest: null,
    weightLatest: null,
  });
  const [goals, setGoals] = useState<GoalRow[]>([]);
  const [recentActivity, setRecentActivity] = useState<ActivityEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const permissions = useMemo(
    () => ({
      hydrationRead: hasPermission(currentUser, 'READ_HYDRATION_LOGS'),
      hydrationCreate: hasPermission(currentUser, 'CREATE_HYDRATION_LOGS'),
      moodRead: hasPermission(currentUser, 'READ_MOOD_LOGS'),
      moodCreate: hasPermission(currentUser, 'CREATE_MOOD_LOGS'),
      sleepRead: hasPermission(currentUser, 'READ_SLEEP_LOGS'),
      sleepCreate: hasPermission(currentUser, 'CREATE_SLEEP_LOGS'),
      weightRead: hasPermission(currentUser, 'READ_HEALTH_METRICS'),
      weightCreate: hasPermission(currentUser, 'CREATE_HEALTH_METRICS'),
      goalsRead: hasPermission(currentUser, 'READ_GOALS'),
    }),
    [currentUser],
  );

  const loadPulse = 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'
          AND device_used = '${escapeSqlLiteral(DAILY_PULSE_DEVICE)}'
      `);
    }

    setLoading(true);

    try {
      const [hydrationRows, moodRows, sleepRows, weightRows, goalRows, activityRows] = await Promise.all([
        permissions.hydrationRead
          ? runSql<{ hydration_total_ml: number; hydration_logs_today: number }>(`
              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, "createdAt" DESC
              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'
                AND device_used = '${escapeSqlLiteral(DAILY_PULSE_DEVICE)}'
              ORDER BY measured_at DESC NULLS LAST, "createdAt" DESC
              LIMIT 1
            `)
          : Promise.resolve([]),
        permissions.goalsRead
          ? runSql<GoalRow>(`
              SELECT id, goal_type, follow_up_answer, target_date
              FROM goals
              WHERE "userId" = '${safeUserId}'
                AND "deletedAt" IS NULL
                AND is_active = true
              ORDER BY "createdAt" DESC
              LIMIT 3
            `)
          : Promise.resolve([]),
        activityQueries.length
          ? runSql<ActivityEntry>(`
              SELECT *
              FROM (
                ${activityQueries.join('\n                UNION ALL\n')}
              ) AS activity
              WHERE happened_at IS NOT NULL
              ORDER BY happened_at DESC
              LIMIT 8
            `)
          : Promise.resolve([]),
      ]);

      const hydrationTotals = hydrationRows[0];

      setSummary({
        hydrationTotalMl: Number(hydrationTotals?.hydration_total_ml ?? 0),
        hydrationLogsToday: Number(hydrationTotals?.hydration_logs_today ?? 0),
        moodToday: moodRows[0] ?? null,
        sleepLatest: sleepRows[0] ?? null,
        weightLatest: weightRows[0] ?? null,
      });
      setGoals(goalRows);
      setRecentActivity(activityRows);
    } catch (error) {
      console.error('Failed to load APEX BRAIN Daily Pulse:', error);
      setFeedback({
        color: 'danger',
        message: 'We could not load your Daily Pulse data right now. Please refresh and try again.',
      });
    } finally {
      setLoading(false);
    }
  }, [permissions.goalsRead, permissions.hydrationRead, permissions.moodRead, permissions.sleepRead, permissions.weightRead]);

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

    loadPulse(currentUser.id).catch((error) => {
      console.error('Unhandled Daily Pulse load error:', error);
    });
  }, [currentUser?.id, loadPulse]);

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

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

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

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

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

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

  const completedCount = summaryCards.filter((card) => card.isComplete).length;
  const completionPercent = Math.round((completedCount / summaryCards.length) * 100);
  const hydrationScore = Math.round(Math.min(summary.hydrationTotalMl / WATER_GOAL_ML, 1) * 25);
  const pulseScore = hydrationScore + (summaryCards[1].isComplete ? 25 : 0) + (summaryCards[2].isComplete ? 25 : 0) + (summaryCards[3].isComplete ? 25 : 0);
  const hasAnyCreatePermission =
    permissions.hydrationCreate || permissions.moodCreate || permissions.sleepCreate || permissions.weightCreate;
  const accessibleQuickLinks = quickLinks.filter((link) => {
    if (link.href.startsWith('/hydration_logs')) {
      return permissions.hydrationRead;
    }

    if (link.href.startsWith('/mood_logs')) {
      return permissions.moodRead;
    }

    if (link.href.startsWith('/sleep_logs')) {
      return permissions.sleepRead;
    }

    if (link.href.startsWith('/goals')) {
      return permissions.goalsRead;
    }

    return false;
  });

  const handleChange = <K extends keyof PulseFormState>(field: K, value: PulseFormState[K]) => {
    setForm((previous) => ({
      ...previous,
      [field]: value,
    }));
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!currentUser?.id) {
      setFeedback({
        color: 'danger',
        message: 'Your session is not ready yet. Please wait a moment and try again.',
      });
      return;
    }

    const errors: string[] = [];
    const hasHydrationEntry = permissions.hydrationCreate && form.volumeMl.trim() !== '';
    const hasMoodEntry =
      permissions.moodCreate &&
      [form.moodScore, form.energyLevel, form.anxietyLevel, form.moodTags, form.journalEntry].some((value) => value.trim() !== '');
    const hasSleepEntry =
      permissions.sleepCreate &&
      [form.sleepBedtime, form.sleepWakeTime, form.sleepQuality, form.morningEnergy, form.sleepDisturbances].some((value) => value.trim() !== '');
    const hasWeightEntry = permissions.weightCreate && form.weightValue.trim() !== '';

    if (!hasHydrationEntry && !hasMoodEntry && !hasSleepEntry && !hasWeightEntry) {
      errors.push('Add at least one check-in before saving your Daily Pulse.');
    }

    if (hasHydrationEntry) {
      const volume = Number(form.volumeMl);

      if (!Number.isFinite(volume) || volume <= 0) {
        errors.push('Hydration volume must be greater than zero.');
      }
    }

    if (hasMoodEntry) {
      const moodScore = Number(form.moodScore);
      const energyLevel = form.energyLevel ? Number(form.energyLevel) : null;
      const anxietyLevel = form.anxietyLevel ? Number(form.anxietyLevel) : null;

      if (!Number.isFinite(moodScore) || moodScore < 1 || moodScore > 10) {
        errors.push('Mood score must be between 1 and 10.');
      }

      if (energyLevel && (energyLevel < 1 || energyLevel > 10)) {
        errors.push('Energy level must be between 1 and 10.');
      }

      if (anxietyLevel && (anxietyLevel < 1 || anxietyLevel > 10)) {
        errors.push('Anxiety level must be between 1 and 10.');
      }
    }

    if (hasSleepEntry) {
      if (!form.sleepBedtime || !form.sleepWakeTime) {
        errors.push('Sleep entries need both a bedtime and a wake time.');
      } else {
        const totalMinutes = Math.round((new Date(form.sleepWakeTime).getTime() - new Date(form.sleepBedtime).getTime()) / 60000);

        if (totalMinutes <= 0 || totalMinutes > 24 * 60) {
          errors.push('Sleep duration must be a realistic positive value.');
        }
      }

      if (form.sleepQuality && (Number(form.sleepQuality) < 1 || Number(form.sleepQuality) > 10)) {
        errors.push('Sleep quality must be between 1 and 10.');
      }

      if (form.morningEnergy && (Number(form.morningEnergy) < 1 || Number(form.morningEnergy) > 10)) {
        errors.push('Morning energy must be between 1 and 10.');
      }
    }

    if (hasWeightEntry) {
      const weight = Number(form.weightValue);

      if (!Number.isFinite(weight) || weight <= 0) {
        errors.push('Weight must be greater than zero.');
      }
    }

    if (errors.length) {
      setFeedback({
        color: 'danger',
        message: errors.join(' '),
      });
      return;
    }

    setIsSubmitting(true);
    setFeedback(null);

    const savedSections: string[] = [];
    const failedSections: string[] = [];

    try {
      if (hasHydrationEntry) {
        try {
          await axios.post('/hydration_logs', {
            data: {
              user: currentUser.id,
              logged_at: toIsoString(form.hydrationLoggedAt),
              beverage_type: form.beverageType,
              volume_ml: Number(form.volumeMl),
              counts_toward_hydration: form.countsTowardHydration,
              container_label: form.containerLabel || null,
            },
          });
          savedSections.push('hydration');
        } catch (error) {
          console.error('Failed to save hydration entry:', error);
          failedSections.push('hydration');
        }
      }

      if (hasMoodEntry) {
        try {
          await axios.post('/mood_logs', {
            data: {
              user: currentUser.id,
              logged_at: toIsoString(form.moodLoggedAt),
              mood_score: Number(form.moodScore),
              emotion_tags_csv: form.moodTags || null,
              energy_level: form.energyLevel ? Number(form.energyLevel) : null,
              anxiety_level: form.anxietyLevel ? Number(form.anxietyLevel) : null,
              journal_entry: form.journalEntry || null,
            },
          });
          savedSections.push('mood');
        } catch (error) {
          console.error('Failed to save mood entry:', error);
          failedSections.push('mood');
        }
      }

      if (hasSleepEntry) {
        const totalMinutes = Math.round((new Date(form.sleepWakeTime).getTime() - new Date(form.sleepBedtime).getTime()) / 60000);

        try {
          await axios.post('/sleep_logs', {
            data: {
              user: currentUser.id,
              bedtime: toIsoString(form.sleepBedtime),
              final_wake_time: toIsoString(form.sleepWakeTime),
              total_sleep_minutes: totalMinutes,
              sleep_quality: form.sleepQuality ? Number(form.sleepQuality) : null,
              morning_energy: form.morningEnergy ? Number(form.morningEnergy) : null,
              disturbances: form.sleepDisturbances || null,
            },
          });
          savedSections.push('sleep');
        } catch (error) {
          console.error('Failed to save sleep entry:', error);
          failedSections.push('sleep');
        }
      }

      if (hasWeightEntry) {
        try {
          await axios.post('/health_metrics', {
            data: {
              user: currentUser.id,
              measured_at: toIsoString(form.weightMeasuredAt),
              metric_type: 'body_composition',
              value_primary: Number(form.weightValue),
              unit: form.weightUnit,
              device_used: DAILY_PULSE_DEVICE,
              notes: form.weightNotes || null,
            },
          });
          savedSections.push('weight');
        } catch (error) {
          console.error('Failed to save weight entry:', error);
          failedSections.push('weight');
        }
      }

      if (!savedSections.length) {
        setFeedback({
          color: 'danger',
          message: 'Nothing was saved. Please review your inputs and try again.',
        });
        return;
      }

      if (failedSections.length) {
        setFeedback({
          color: 'danger',
          message: `Saved ${savedSections.join(', ')}, but ${failedSections.join(', ')} still need attention. Please retry those sections.`,
        });
      } else {
        setFeedback({
          color: 'success',
          message: `Saved your ${savedSections.join(', ')} check-in${savedSections.length > 1 ? 's' : ''}. Your Daily Pulse is up to date.`,
        });
        setForm(initialPulseForm());
      }

      await loadPulse(currentUser.id);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Daily Pulse')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiHeartPulse} title="Daily Pulse" main>
          <div className="flex flex-wrap items-center gap-3">
            <Link
              href="/dashboard"
              className="inline-flex items-center rounded-full border px-4 py-2 text-sm font-semibold transition hover:-translate-y-0.5"
              style={{ borderColor: '#D6C8B4', color: '#4A6741', backgroundColor: '#FFF9F0' }}
            >
              Overview
            </Link>
            <Link
              href="/goals/goals-list"
              className="inline-flex items-center rounded-full px-4 py-2 text-sm font-semibold text-white transition hover:-translate-y-0.5"
              style={{ backgroundColor: '#4A6741' }}
            >
              Goals
            </Link>
          </div>
        </SectionTitleLineWithButton>

        <div
          className="mb-6 overflow-hidden rounded-[28px] border p-6 shadow-sm lg:p-8"
          style={{
            borderColor: '#D8CBB7',
            background:
              'linear-gradient(135deg, rgba(245,240,232,1) 0%, rgba(255,249,240,1) 55%, rgba(236,229,214,1) 100%)',
          }}
        >
          <div className="grid gap-6 lg:grid-cols-[1.35fr_0.9fr] lg:items-center">
            <div>
              <div
                className="mb-4 inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-semibold"
                style={{ borderColor: '#D6C8B4', color: '#4A6741', backgroundColor: 'rgba(255, 255, 255, 0.66)' }}
              >
                <BaseIcon path={mdiTrophyOutline} size={18} />
                APEX BRAIN signature workflow
              </div>
              <h2 className="max-w-3xl text-3xl font-semibold tracking-tight md:text-4xl" style={{ color: '#1C1C1C' }}>
                {greeting}, {currentUser?.firstName || 'there'}. Here&apos;s your calm, clear view of today.
              </h2>
              <p className="mt-4 max-w-2xl text-base leading-7 md:text-lg" style={{ color: '#3F4B35' }}>
                Save water, mood, sleep, and weight in one elegant ritual, then jump straight into your detailed history and active goals.
              </p>

              <div className="mt-6 grid gap-4 sm:grid-cols-3">
                <div className="rounded-3xl border p-4" style={{ borderColor: '#E1D6C5', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                  <div className="text-sm font-medium uppercase tracking-[0.18em]" style={{ color: '#6A6A55' }}>
                    Today&apos;s pulse score
                  </div>
                  <div className="mt-2 text-4xl font-semibold" style={{ color: '#1C1C1C' }}>
                    {pulseScore}
                    <span className="text-lg font-medium" style={{ color: '#6A6A55' }}>
                      /100
                    </span>
                  </div>
                </div>
                <div className="rounded-3xl border p-4" style={{ borderColor: '#E1D6C5', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                  <div className="text-sm font-medium uppercase tracking-[0.18em]" style={{ color: '#6A6A55' }}>
                    Live hydration
                  </div>
                  <div className="mt-2 text-2xl font-semibold" style={{ color: '#1C1C1C' }}>
                    {summary.hydrationTotalMl.toLocaleString()} ml
                  </div>
                  <p className="mt-1 text-sm" style={{ color: '#6A6A55' }}>
                    {summary.hydrationLogsToday} entries captured today
                  </p>
                </div>
                <div className="rounded-3xl border p-4" style={{ borderColor: '#E1D6C5', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                  <div className="text-sm font-medium uppercase tracking-[0.18em]" style={{ color: '#6A6A55' }}>
                    Focus cadence
                  </div>
                  <div className="mt-2 text-2xl font-semibold" style={{ color: '#1C1C1C' }}>
                    {completedCount} / {summaryCards.length} anchors
                  </div>
                  <p className="mt-1 text-sm" style={{ color: '#6A6A55' }}>
                    Hydration, mood, sleep, and weight all in one view
                  </p>
                </div>
              </div>
            </div>

            <div className="flex justify-center lg:justify-end">
              <div className="rounded-[32px] border p-6 text-center shadow-sm" style={{ borderColor: '#D8CBB7', backgroundColor: 'rgba(255,255,255,0.82)' }}>
                <div className="relative mx-auto h-56 w-56">
                  <div
                    className="absolute inset-0 rounded-full"
                    style={{
                      background: `conic-gradient(#4A6741 ${completionPercent}%, #E9DDCC ${completionPercent}% 100%)`,
                    }}
                  />
                  <div
                    className="absolute inset-[16px] rounded-full"
                    style={{ backgroundColor: '#FFF9F0', 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: '#6A6A55' }}>
                      Daily ring
                    </div>
                    <div className="mt-2 text-5xl font-semibold" style={{ color: '#1C1C1C' }}>
                      {completionPercent}%
                    </div>
                    <p className="mt-3 max-w-[11rem] text-sm leading-6" style={{ color: '#4A6741' }}>
                      {completedCount === summaryCards.length
                        ? 'Everything core is captured for today.'
                        : 'Keep logging to complete your premium health snapshot.'}
                    </p>
                  </div>
                </div>
                <div className="mt-6 flex items-center justify-center gap-2 text-sm font-medium" style={{ color: '#4A6741' }}>
                  <BaseIcon path={mdiCalendarHeart} size={18} />
                  {new Intl.DateTimeFormat(undefined, {
                    weekday: 'long',
                    month: 'long',
                    day: 'numeric',
                  }).format(new Date())}
                </div>
              </div>
            </div>
          </div>
        </div>

        {feedback && (
          <NotificationBar color={feedback.color} icon={feedback.color === 'success' ? mdiCheckCircleOutline : mdiHeartPulse}>
            {feedback.message}
          </NotificationBar>
        )}

        <div className="mb-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 transition hover:-translate-y-0.5"
              style={{ borderColor: '#E1D6C5', backgroundColor: '#FFF9F0' }}
            >
              <div className="flex items-center justify-between gap-3">
                <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                  <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.isComplete ? '#2F5A35' : '#7A7062',
                    backgroundColor: card.isComplete ? 'rgba(74, 103, 65, 0.12)' : 'rgba(201, 168, 76, 0.14)',
                  }}
                >
                  {card.isComplete ? 'captured' : 'pending'}
                </span>
              </div>
              <h3 className="mt-5 text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                {card.label}
              </h3>
              <p className="mt-2 text-2xl font-semibold" style={{ color: '#4A6741' }}>
                {loading ? 'Loading...' : card.value}
              </p>
              <p className="mt-3 text-sm leading-6" style={{ color: '#6A6A55' }}>
                {loading ? 'Refreshing your summary...' : card.detail}
              </p>
            </div>
          ))}
        </div>

        <div className="grid gap-6 xl:grid-cols-[1.55fr_0.85fr]">
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="rounded-[28px] border p-6 shadow-sm lg:p-7" style={{ borderColor: '#D8CBB7', backgroundColor: '#FFF9F0' }}>
              <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: '#1C1C1C' }}>
                    Daily capture ritual
                  </h3>
                  <p className="mt-2 max-w-2xl text-sm leading-6" style={{ color: '#6A6A55' }}>
                    Add any combination of water, mood, sleep, and weight in one save. Every item lands in its existing history screen automatically.
                  </p>
                </div>
                <div className="rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em]" style={{ borderColor: '#D8CBB7', color: '#4A6741' }}>
                  First MVP workflow
                </div>
              </div>

              <div className="mt-6 grid gap-5 xl:grid-cols-2">
                {!hasAnyCreatePermission && (
                  <div className="rounded-[24px] border px-5 py-6 text-sm leading-6 xl:col-span-2" style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)', color: '#6A6A55' }}>
                    Your current role can view this Daily Pulse workspace, but it does not have create access for the quick-capture records yet. You can still explore your existing history and goals from the cards on the right.
                  </div>
                )}

                {permissions.hydrationCreate && (
                  <div className="rounded-[24px] border p-5" style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                    <div className="flex items-center gap-3">
                      <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                        <BaseIcon path={mdiWaterOutline} size={24} />
                      </div>
                      <div>
                        <h4 className="text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                          Hydration log
                        </h4>
                        <p className="text-sm" style={{ color: '#6A6A55' }}>
                          Water first, with room for coffee, tea, and other beverages.
                        </p>
                      </div>
                    </div>
                    <div className="mt-5 grid gap-4 md:grid-cols-2">
                      <FormField label="Logged at">
                        <input
                          type="datetime-local"
                          value={form.hydrationLoggedAt}
                          onChange={(event) => handleChange('hydrationLoggedAt', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Volume (ml)">
                        <input
                          type="number"
                          min="0"
                          placeholder="500"
                          value={form.volumeMl}
                          onChange={(event) => handleChange('volumeMl', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Beverage">
                        <select
                          value={form.beverageType}
                          onChange={(event) => handleChange('beverageType', event.target.value)}
                        >
                          <option value="water">Water</option>
                          <option value="coffee">Coffee</option>
                          <option value="tea">Tea</option>
                          <option value="juice">Juice</option>
                          <option value="sports_drink">Sports drink</option>
                          <option value="alcohol">Alcohol</option>
                          <option value="other">Other</option>
                        </select>
                      </FormField>
                      <FormField label="Container label">
                        <input
                          type="text"
                          placeholder="Morning bottle"
                          value={form.containerLabel}
                          onChange={(event) => handleChange('containerLabel', event.target.value)}
                        />
                      </FormField>
                    </div>
                    <label className="mt-4 flex cursor-pointer items-center gap-3 rounded-2xl border px-4 py-3 text-sm font-medium" style={{ borderColor: '#E5DAC9', color: '#4A6741' }}>
                      <input
                        type="checkbox"
                        className="h-4 w-4"
                        checked={form.countsTowardHydration}
                        onChange={(event) => handleChange('countsTowardHydration', event.target.checked)}
                      />
                      Count this toward today&apos;s hydration target
                    </label>
                  </div>
                )}

                {permissions.moodCreate && (
                  <div className="rounded-[24px] border p-5" style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                    <div className="flex items-center gap-3">
                      <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                        <BaseIcon path={mdiEmoticonHappyOutline} size={24} />
                      </div>
                      <div>
                        <h4 className="text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                          Mood check-in
                        </h4>
                        <p className="text-sm" style={{ color: '#6A6A55' }}>
                          Capture feelings, energy, and anything that shaped your day.
                        </p>
                      </div>
                    </div>
                    <div className="mt-5 grid gap-4 md:grid-cols-2">
                      <FormField label="Logged at">
                        <input
                          type="datetime-local"
                          value={form.moodLoggedAt}
                          onChange={(event) => handleChange('moodLoggedAt', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Mood score (1–10)">
                        <input
                          type="number"
                          min="1"
                          max="10"
                          placeholder="8"
                          value={form.moodScore}
                          onChange={(event) => handleChange('moodScore', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Energy (1–10)">
                        <input
                          type="number"
                          min="1"
                          max="10"
                          placeholder="7"
                          value={form.energyLevel}
                          onChange={(event) => handleChange('energyLevel', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Anxiety (1–10)">
                        <input
                          type="number"
                          min="1"
                          max="10"
                          placeholder="3"
                          value={form.anxietyLevel}
                          onChange={(event) => handleChange('anxietyLevel', event.target.value)}
                        />
                      </FormField>
                    </div>
                    <div className="mt-1 grid gap-4">
                      <FormField label="Emotion tags">
                        <input
                          type="text"
                          placeholder="Calm, focused, optimistic"
                          value={form.moodTags}
                          onChange={(event) => handleChange('moodTags', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Quick note">
                        <textarea
                          placeholder="What contributed most to your mood today?"
                          value={form.journalEntry}
                          onChange={(event) => handleChange('journalEntry', event.target.value)}
                        />
                      </FormField>
                    </div>
                  </div>
                )}

                {permissions.sleepCreate && (
                  <div className="rounded-[24px] border p-5" style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                    <div className="flex items-center gap-3">
                      <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                        <BaseIcon path={mdiWeatherNight} size={24} />
                      </div>
                      <div>
                        <h4 className="text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                          Sleep recap
                        </h4>
                        <p className="text-sm" style={{ color: '#6A6A55' }}>
                          Turn last night&apos;s recovery into a visible trend.
                        </p>
                      </div>
                    </div>
                    <div className="mt-5 grid gap-4 md:grid-cols-2">
                      <FormField label="Bedtime">
                        <input
                          type="datetime-local"
                          value={form.sleepBedtime}
                          onChange={(event) => handleChange('sleepBedtime', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Final wake time">
                        <input
                          type="datetime-local"
                          value={form.sleepWakeTime}
                          onChange={(event) => handleChange('sleepWakeTime', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Sleep quality (1–10)">
                        <input
                          type="number"
                          min="1"
                          max="10"
                          placeholder="8"
                          value={form.sleepQuality}
                          onChange={(event) => handleChange('sleepQuality', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Morning energy (1–10)">
                        <input
                          type="number"
                          min="1"
                          max="10"
                          placeholder="7"
                          value={form.morningEnergy}
                          onChange={(event) => handleChange('morningEnergy', event.target.value)}
                        />
                      </FormField>
                    </div>
                    <div className="mt-1 grid gap-4">
                      <FormField label="Disturbances">
                        <textarea
                          placeholder="Night wakings, noise, dreams, temperature, or anything else worth remembering"
                          value={form.sleepDisturbances}
                          onChange={(event) => handleChange('sleepDisturbances', event.target.value)}
                        />
                      </FormField>
                    </div>
                  </div>
                )}

                {permissions.weightCreate && (
                  <div className="rounded-[24px] border p-5" style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}>
                    <div className="flex items-center gap-3">
                      <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                        <BaseIcon path={mdiScaleBathroom} size={24} />
                      </div>
                      <div>
                        <h4 className="text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                          Weight check
                        </h4>
                        <p className="text-sm" style={{ color: '#6A6A55' }}>
                          Optional body composition anchor for the days you want it.
                        </p>
                      </div>
                    </div>
                    <div className="mt-5 grid gap-4 md:grid-cols-2">
                      <FormField label="Measured at">
                        <input
                          type="datetime-local"
                          value={form.weightMeasuredAt}
                          onChange={(event) => handleChange('weightMeasuredAt', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Weight">
                        <input
                          type="number"
                          min="0"
                          step="0.1"
                          placeholder={form.weightUnit === 'kg' ? '74.5' : '164.2'}
                          value={form.weightValue}
                          onChange={(event) => handleChange('weightValue', event.target.value)}
                        />
                      </FormField>
                      <FormField label="Unit">
                        <select
                          value={form.weightUnit}
                          onChange={(event) => handleChange('weightUnit', event.target.value as 'kg' | 'lb')}
                        >
                          <option value="kg">Kilograms</option>
                          <option value="lb">Pounds</option>
                        </select>
                      </FormField>
                      <FormField label="Note">
                        <input
                          type="text"
                          placeholder="Fasted weigh-in, after training, etc."
                          value={form.weightNotes}
                          onChange={(event) => handleChange('weightNotes', event.target.value)}
                        />
                      </FormField>
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-6 flex flex-col gap-3 border-t pt-6 sm:flex-row sm:items-center sm:justify-between" style={{ borderColor: '#E1D6C5' }}>
                <p className="text-sm leading-6" style={{ color: '#6A6A55' }}>
                  One save, four possible records, and instant links back to the existing detail screens.
                </p>
                {hasAnyCreatePermission ? (
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="inline-flex items-center justify-center rounded-full px-6 py-3 text-sm font-semibold text-white transition hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-70"
                    style={{ backgroundColor: '#4A6741' }}
                  >
                    {isSubmitting ? 'Saving your pulse...' : 'Save today\'s pulse'}
                  </button>
                ) : (
                  <Link href="/dashboard" className="text-sm font-semibold" style={{ color: '#4A6741' }}>
                    Return to overview →
                  </Link>
                )}
              </div>
            </div>
          </form>

          <div className="space-y-6">
            <div className="rounded-[28px] border p-6 shadow-sm" style={{ borderColor: '#D8CBB7', backgroundColor: '#FFF9F0' }}>
              <div className="flex items-center gap-3">
                <div className="flex h-12 w-12 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                  <BaseIcon path={mdiTargetVariant} size={24} />
                </div>
                <div>
                  <h3 className="text-xl font-semibold" style={{ color: '#1C1C1C' }}>
                    Focus goals
                  </h3>
                  <p className="text-sm" style={{ color: '#6A6A55' }}>
                    Your active priorities, surfaced beside today&apos;s check-in.
                  </p>
                </div>
              </div>

              <div className="mt-5 space-y-4">
                {!permissions.goalsRead && (
                  <div className="rounded-2xl border px-4 py-5 text-sm leading-6" style={{ borderColor: '#E5DAC9', color: '#6A6A55' }}>
                    Goal visibility is not enabled for your current role.
                  </div>
                )}

                {permissions.goalsRead && !loading && goals.length === 0 && (
                  <div className="rounded-2xl border px-4 py-5 text-sm leading-6" style={{ borderColor: '#E5DAC9', color: '#6A6A55' }}>
                    No active goals yet. Set one up to turn Daily Pulse into a more purposeful ritual.
                    <div className="mt-4">
                      <Link href="/goals/goals-new" className="font-semibold" style={{ color: '#4A6741' }}>
                        Create your first goal →
                      </Link>
                    </div>
                  </div>
                )}

                {permissions.goalsRead && goals.map((goal) => (
                  <Link
                    key={goal.id}
                    href={`/goals/goals-view/?id=${goal.id}`}
                    className="block rounded-2xl border px-4 py-4 transition hover:-translate-y-0.5"
                    style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div>
                        <div className="text-base font-semibold" style={{ color: '#1C1C1C' }}>
                          {humanize(goal.goal_type)}
                        </div>
                        <p className="mt-2 text-sm leading-6" style={{ color: '#6A6A55' }}>
                          {goal.follow_up_answer || 'Add more detail to make this goal feel tangible and measurable.'}
                        </p>
                      </div>
                      <BaseIcon path={mdiArrowTopRight} size={20} className="shrink-0" />
                    </div>
                    <div className="mt-4 text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: '#4A6741' }}>
                      Target {formatDate(goal.target_date)}
                    </div>
                  </Link>
                ))}
              </div>
            </div>

            <div className="rounded-[28px] border p-6 shadow-sm" style={{ borderColor: '#D8CBB7', backgroundColor: '#FFF9F0' }}>
              <h3 className="text-xl font-semibold" style={{ color: '#1C1C1C' }}>
                Explore the full records
              </h3>
              <p className="mt-2 text-sm leading-6" style={{ color: '#6A6A55' }}>
                Daily Pulse is the shortcut. These links take you straight into the deeper CRUD views already available in the app.
              </p>
              <div className="mt-5 space-y-3">
                {accessibleQuickLinks.length === 0 && (
                  <div className="rounded-2xl border px-4 py-5 text-sm leading-6" style={{ borderColor: "#E5DAC9", color: "#6A6A55" }}>
                    Your current role does not expose any of the linked history screens yet.
                  </div>
                )}

                {accessibleQuickLinks.map((link) => (
                  <Link
                    key={link.href}
                    href={link.href}
                    className="flex items-start gap-4 rounded-2xl border px-4 py-4 transition hover:-translate-y-0.5"
                    style={{ borderColor: '#E5DAC9', backgroundColor: 'rgba(255,255,255,0.72)' }}
                  >
                    <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                      <BaseIcon path={link.icon} size={22} />
                    </div>
                    <div>
                      <div className="text-base font-semibold" style={{ color: '#1C1C1C' }}>
                        {link.title}
                      </div>
                      <p className="mt-1 text-sm leading-6" style={{ color: '#6A6A55' }}>
                        {link.description}
                      </p>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="mt-6 rounded-[28px] border p-6 shadow-sm" style={{ borderColor: '#D8CBB7', backgroundColor: '#FFF9F0' }}>
          <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: '#1C1C1C' }}>
                Recent activity
              </h3>
              <p className="mt-2 text-sm leading-6" style={{ color: '#6A6A55' }}>
                Every Daily Pulse save lands here and links back to its detailed record screen.
              </p>
            </div>
            <Link href="/dashboard" className="text-sm font-semibold" style={{ color: '#4A6741' }}>
              Back to the wider overview →
            </Link>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            {!loading && recentActivity.length === 0 && (
              <div className="rounded-2xl border px-5 py-6 text-sm leading-6 md:col-span-2 xl:col-span-4" style={{ borderColor: '#E5DAC9', color: '#6A6A55' }}>
                Your activity feed is still empty. Save your first Daily Pulse above and it will appear here instantly.
              </div>
            )}

            {(loading ? Array.from({ length: 4 }) : recentActivity).map((item, index) => {
              if (loading) {
                return (
                  <div
                    key={`activity-skeleton-${index}`}
                    className="min-h-[168px] rounded-2xl border p-5"
                    style={{ borderColor: '#E5DAC9', 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>
                );
              }

              const route = activityRouteByKind[item.kind];
              const iconByKind = {
                hydration: mdiWaterOutline,
                mood: mdiEmoticonHappyOutline,
                sleep: mdiWeatherNight,
                weight: mdiScaleBathroom,
              };

              return (
                <Link
                  key={item.id}
                  href={`${route}/?id=${item.id}`}
                  className="block rounded-2xl border p-5 transition hover:-translate-y-0.5"
                  style={{ borderColor: '#E5DAC9', 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: '#F1E7D8', color: '#4A6741' }}>
                      <BaseIcon path={iconByKind[item.kind]} size={24} />
                    </div>
                    <span className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]" style={{ backgroundColor: '#F1E7D8', color: '#4A6741' }}>
                      {item.kind}
                    </span>
                  </div>
                  <div className="mt-5 text-lg font-semibold" style={{ color: '#1C1C1C' }}>
                    {item.title}
                  </div>
                  <p className="mt-2 text-sm" style={{ color: '#4A6741' }}>
                    {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>
      </SectionMain>
    </>
  );
}

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

export default DailyPulsePage;
