"use client";

import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import Link from "next/link";
import gsap from "gsap";

interface ReportsData {
  stats: any;
  progress: any[];
  sessions: any[];
  weight: {
    history: any[];
    latest: any | null;
    starting: number | null;
    height: number | null;
  };
  bests: any[];
  achievements: {
    achievements: any[];
    totalWorkouts: number;
    longestStreak: number;
    currentStreak: number;
  };
}

// BMI = weight(kg) / (height(m))^2 where height is stored in feet
function calcBMI(weightKg: number, heightFt: number): number {
  if (!weightKg || !heightFt || weightKg <= 0 || heightFt <= 0) return 0;
  const heightM = heightFt * 0.3048;
  return Math.round((weightKg / (heightM * heightM)) * 10) / 10;
}

function bmiCategory(bmi: number): { label: string; color: string } {
  if (bmi <= 0) return { label: "-", color: "text-zinc-400" };
  if (bmi < 18.5) return { label: "Underweight", color: "text-blue-600" };
  if (bmi < 25) return { label: "Normal (Ideal)", color: "text-emerald-600" };
  if (bmi < 30) return { label: "Overweight", color: "text-amber-600" };
  return { label: "Obese", color: "text-red-600" };
}

function formatDuration(seconds: number): string {
  if (!seconds) return "0m";
  const hrs = Math.floor(seconds / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  return hrs > 0 ? `${hrs}h ${mins}m` : `${mins}m`;
}

function formatDate(dateStr: string): string {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

function formatFullDate(dateStr: string): string {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

// SVG Mini Chart (reuses SettingsPanel pattern with divisor fix)
function MiniChart({ data, color, height = 60 }: { data: number[]; color: string; height?: number }) {
  if (!data || data.length < 2) {
    return <div className="text-zinc-400 text-xs text-center py-4">Not enough data yet</div>;
  }
  const w = 200, h = height;
  const max = Math.max(...data, 1);
  const divisor = Math.max(data.length - 1, 1);
  const points = data.map((v, i) => `${(i / divisor) * w},${h - (v / max) * (h - 10)}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="reports-chart" style={{ height }}>
      <defs>
        <linearGradient id="gradMini" x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={color} stopOpacity="0.3" />
          <stop offset="100%" stopColor={color} stopOpacity="0.02" />
        </linearGradient>
      </defs>
      <polyline points={points} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      <polygon points={`0,${h} ${points} ${w},${h}`} fill={`url(#gradMini)`} />
    </svg>
  );
}

// Weight Trend SVG Chart
function WeightTrendChart({ history, startingWeight, targetWeight }: {
  history: any[]; startingWeight: number | null; targetWeight?: number | null;
}) {
  if (!history || history.length < 2) {
    return <div className="text-zinc-400 text-xs text-center py-8">Log your weight over time to see your trend here</div>;
  }
  const sorted = [...history].sort((a: any, b: any) =>
    new Date(a.logged_date).getTime() - new Date(b.logged_date).getTime()
  );
  const weights = sorted.map((w: any) => parseFloat(w.weight_kg));
  const minVal = Math.min(...weights, startingWeight || 999, targetWeight || 999) - 2;
  const maxVal = Math.max(...weights, startingWeight || 0, targetWeight || 0) + 2;
  const range = maxVal - minVal || 1;
  const w = 500, h = 180, padL = 35, padR = 10;
  const plotW = w - padL - padR;
  const divisor = Math.max(weights.length - 1, 1);
  const xPos = (i: number) => padL + (i / divisor) * plotW;
  const yPos = (v: number) => h - ((v - minVal) / range) * (h - 20) - 10;
  const linePoints = weights.map((v: number, i: number) => `${xPos(i)},${yPos(v)}`).join(" ");
  const areaPoints = `${padL},${h - 10} ${linePoints} ${xPos(weights.length - 1)},${h - 10}`;
  const yLabels: number[] = [];
  for (let i = 0; i <= 4; i++) yLabels.push(minVal + (range / 4) * i);

  return (
    <div className="relative">
      <svg viewBox={`0 0 ${w} ${h}`} className="reports-chart w-full" style={{ height: 200 }}>
        <defs>
          <linearGradient id="weightGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor="#059669" stopOpacity="0.25" />
            <stop offset="100%" stopColor="#059669" stopOpacity="0.02" />
          </linearGradient>
        </defs>
        {yLabels.map((v, i) => (
          <g key={`y-${i}`}>
            <line x1={padL} y1={yPos(v)} x2={w - padR} y2={yPos(v)} stroke="#e4e4e7" strokeWidth="1" />
            <text x={padL - 4} y={yPos(v) + 4} textAnchor="end" className="text-[10px]" fill="#a1a1aa">{Math.round(v)}</text>
          </g>
        ))}
        {startingWeight && <line x1={padL} y1={yPos(startingWeight)} x2={w - padR} y2={yPos(startingWeight)} className="starting-line" />}
        {targetWeight && <line x1={padL} y1={yPos(targetWeight)} x2={w - padR} y2={yPos(targetWeight)} className="target-line" />}
        <polygon points={areaPoints} fill="url(#weightGradient)" />
        <polyline points={linePoints} className="chart-line" />
        {weights.map((v, i) => <circle key={i} cx={xPos(i)} cy={yPos(v)} className="chart-dot" />)}
      </svg>
      <div className="flex gap-4 text-[10px] text-zinc-500 mt-1 flex-wrap">
        <span className="flex items-center gap-1"><span className="w-3 h-0.5 bg-emerald-600 inline-block"></span> Weight</span>
        {startingWeight && <span className="flex items-center gap-1"><span style={{ width: 12, borderTop: "1.5px dashed #6b7280", display: "inline-block", height: 0 }}></span> Starting</span>}
        {targetWeight && <span className="flex items-center gap-1"><span style={{ width: 12, borderTop: "1.5px dashed #dc2626", display: "inline-block", height: 0 }}></span> Target</span>}
      </div>
    </div>
  );
}

// ─── MAIN REPORTS PAGE ───────────────────────────────────────────
export default function ReportsPage() {
  const [data, setData] = useState<ReportsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showWeightForm, setShowWeightForm] = useState(false);
  const [weightInput, setWeightInput] = useState("");
  const [weightNotes, setWeightNotes] = useState("");
  const [weightSaving, setWeightSaving] = useState(false);
  const [targetWeight, setTargetWeight] = useState<number | null>(null);
  const [weightSaved, setWeightSaved] = useState(false);
  const hasLoaded = useRef(false);
  const hasAnimated = useRef(false);

  const runCardAnimation = useCallback(() => {
    if (hasAnimated.current) return;
    hasAnimated.current = true;
    requestAnimationFrame(() => {
      const cards = document.querySelectorAll(".dashboard-card");
      if (cards.length > 0) {
        gsap.fromTo(cards,
          { opacity: 0, y: 30 },
          { opacity: 1, y: 0, stagger: 0.08, duration: 0.6, ease: "power4.out" }
        );
      }
    });
  }, []);

  useEffect(() => {
    document.title = "My Progress & Reports | Marich Wellness";
    if (hasLoaded.current) return;
    hasLoaded.current = true;
    async function loadReports() {
      setIsLoading(true);
      try {
        const profileRes = await fetch("/api/user/profile");
        if (!profileRes.ok) { setError("Please complete the fitness questionnaire first."); setIsLoading(false); return; }
        const profileData = await profileRes.json();
        const email = profileData?.profile?.user_email;
        if (!email) { setError("Please log in to view your reports."); setIsLoading(false); return; }
        const reportsRes = await fetch(`/api/fitness/reports?userId=${encodeURIComponent(email)}`);
        if (!reportsRes.ok) throw new Error("Failed to load reports");
        const reportsData = await reportsRes.json();
        setData(reportsData);
        if (reportsData.weight?.starting) {
          const goals = profileData?.profile?.goals
            ? (typeof profileData.profile.goals === "string" ? JSON.parse(profileData.profile.goals) : profileData.profile.goals) : [];
          if (Array.isArray(goals) && goals.includes("weight-loss"))
            setTargetWeight(Math.round((reportsData.weight.starting - 5) * 10) / 10);
          else if (Array.isArray(goals) && goals.includes("muscle-gain"))
            setTargetWeight(Math.round((reportsData.weight.starting + 2) * 10) / 10);
        }
      } catch (err: any) { setError(err.message); }
      finally { setIsLoading(false); setTimeout(() => runCardAnimation(), 100); }
    }
    loadReports();
  }, [runCardAnimation]);

  async function handleLogWeight() {
    const w = parseFloat(weightInput);
    if (!w || isNaN(w) || w <= 0) return;
    setWeightSaving(true);
    try {
      const profileRes = await fetch("/api/user/profile");
      const profileData = await profileRes.json();
      const email = profileData?.profile?.user_email;
      if (!email) return;
      const res = await fetch("/api/fitness/weight", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ user_email: email, weight_kg: w, notes: weightNotes }),
      });
      if (res.ok) {
        setWeightSaved(true); setShowWeightForm(false); setWeightInput(""); setWeightNotes("");
        const reportsRes = await fetch(`/api/fitness/reports?userId=${encodeURIComponent(email)}`);
        if (reportsRes.ok) setData(await reportsRes.json());
        setTimeout(() => setWeightSaved(false), 3000);
      }
    } catch (err: any) { alert("Failed to log weight: " + err.message); }
    finally { setWeightSaving(false); }
  }

  // BMI computations
  const startingBMI = useMemo(() => {
    if (!data?.weight?.starting || !data?.weight?.height) return null;
    return calcBMI(data.weight.starting, data.weight.height);
  }, [data?.weight?.starting, data?.weight?.height]);
  const currentBMI = useMemo(() => {
    if (!data?.weight?.latest || !data?.weight?.height) return null;
    return calcBMI(parseFloat(data.weight.latest.weight_kg), data.weight.height);
  }, [data?.weight?.latest, data?.weight?.height]);
  const bmiCatVal = useMemo(() => currentBMI ? bmiCategory(currentBMI) : null, [currentBMI]);
  const startingBmiCatVal = useMemo(() => startingBMI ? bmiCategory(startingBMI) : null, [startingBMI]);
  const weightDiff = useMemo(() => {
    if (!data?.weight?.starting || !data?.weight?.latest) return null;
    const start = data.weight.starting;
    const curr = parseFloat(data.weight.latest.weight_kg);
    return { diff: Math.round((curr - start) * 10) / 10, pct: Math.round(((curr - start) / start) * 1000) / 10 };
  }, [data?.weight?.starting, data?.weight?.latest]);


  // ─── Loading State ─────────────────────────────────────────────
  if (isLoading) {
    return (
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center">
        <div className="text-emerald-600 font-bold uppercase tracking-widest text-xs">Loading Reports...</div>
      </div>
    );
  }

  // ─── Error State ─────────────────────────────────────────────
  if (error) {
    return (
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center">
        <div className="text-center px-6 max-w-lg">
          <span className="material-symbols-outlined text-6xl text-red-400 block mb-4">error</span>
          <h2 className="text-3xl font-serif text-emerald-900 dark:text-emerald-50 italic mb-4">Unable to Load Reports</h2>
          <p className="text-black dark:text-white text-lg mb-8">{error}</p>
          <Link href="/fitness-planner/dashboard" className="px-8 py-4 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs inline-block">Back to Dashboard</Link>
        </div>
      </div>
    );
  }

  // ─── Empty State ─────────────────────────────────────────────
  if (!data || (data.stats?.totalWorkouts === 0 && (!data.weight?.history || data.weight.history.length === 0))) {
    return (
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950">
        <nav className="px-6 py-6 max-w-7xl mx-auto flex items-center justify-between">
          <Link href="/fitness-planner/dashboard" className="flex items-center gap-2 text-zinc-400 hover:text-emerald-600 transition-colors">
            <span className="material-symbols-outlined">arrow_back</span>
            <span className="text-xs font-bold uppercase tracking-widest">Dashboard</span>
          </Link>
          <Link href="/fitness-planner" className="text-2xl font-serif text-emerald-900 dark:text-emerald-50 italic">Marich Wellness</Link>
        </nav>
        <main className="max-w-3xl mx-auto px-6 py-12 text-center">
          <span className="material-symbols-outlined text-7xl text-zinc-300 dark:text-zinc-600 block mb-6">bar_chart</span>
          <h2 className="text-3xl font-serif text-emerald-900 dark:text-emerald-50 italic mb-4">No Progress Data Yet</h2>
          <p className="text-black dark:text-white text-lg mb-4">Start your fitness journey and come back here to see your progress!</p>
          <div className="flex gap-4 justify-center mt-8">
            <Link href="/fitness-planner/my-plans" className="px-8 py-4 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs">Browse Plans</Link>
            <Link href="/fitness-planner/library" className="px-8 py-4 border-2 border-emerald-900 text-emerald-900 dark:text-emerald-50 dark:border-emerald-50 font-bold uppercase tracking-widest text-xs">Program Library</Link>
          </div>
        </main>
      </div>
    );
  }


  // ─── MAIN RENDER ──────────────────────────────────────────────
  const { stats, weight, bests, achievements, sessions, progress } = data;

  return (
    <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 reports-print-section">
      <header className="px-6 py-6 max-w-7xl mx-auto flex items-center justify-between no-print">
        <Link href="/fitness-planner/dashboard" className="flex items-center gap-2 text-zinc-400 hover:text-emerald-600">
          <span className="material-symbols-outlined">arrow_back</span>
          <span className="text-xs font-bold uppercase tracking-widest">Dashboard</span>
        </Link>
        <h1 className="text-xl font-serif text-emerald-900 dark:text-emerald-50 italic">My Progress & Reports</h1>
        <button onClick={() => window.print()} className="flex items-center gap-2 text-xs font-bold uppercase tracking-widest bg-emerald-900 text-white px-4 py-3 hover:bg-emerald-800 transition-all print-hide">
          <span className="material-symbols-outlined text-sm">download</span> PDF Report
        </button>
      </header>
      <div className="print-only text-center mb-8 hidden">
        <h1 className="text-2xl font-bold text-emerald-900">Marich Wellness</h1>
        <p className="text-zinc-500">Progress Report &mdash; {new Date().toLocaleDateString()}</p>
        <hr className="my-4 border-zinc-300" />
      </div>

      <main className="max-w-7xl mx-auto px-6 pb-24 space-y-8">
        {/* Summary Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
            <span className="text-3xl font-bold text-emerald-600">{stats?.totalWorkouts || 0}</span>
            <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Workouts Done</p>
          </div>
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
            <span className="text-3xl font-bold text-emerald-600">{formatDuration(stats?.totalTimeSeconds || 0)}</span>
            <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Total Time</p>
          </div>
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
            <span className="text-3xl font-bold text-emerald-600">{formatDuration(stats?.avgTimeSeconds || 0)}</span>
            <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Avg Duration</p>
          </div>
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
            <span className="text-3xl font-bold text-emerald-600">{achievements?.currentStreak || 0}</span>
            <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Day Streak</p>
          </div>
        </div>

        {/* Body Composition */}
        <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 md:p-8">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-lg font-bold text-emerald-900 dark:text-emerald-50 flex items-center gap-2">
              <span className="material-symbols-outlined text-emerald-600">monitor_weight</span> Body Composition
            </h2>
            <button onClick={() => setShowWeightForm(!showWeightForm)}
              className="text-xs font-bold uppercase tracking-widest bg-emerald-900 text-white px-4 py-2 hover:bg-emerald-800 transition-all print-hide">
              {showWeightForm ? "Cancel" : "+ Log Weight"}
            </button>
          </div>
          {showWeightForm && (
            <div className="mb-6 p-4 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded-xl">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="text-[10px] uppercase font-bold tracking-widest text-emerald-600 block mb-1">Weight (kg)</label>
                  <input type="number" step="0.1" min="20" max="300" value={weightInput}
                    onChange={(e) => setWeightInput(e.target.value)} placeholder="e.g. 70.5"
                    className="w-full p-3 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-600 text-emerald-900 dark:text-emerald-50 font-bold focus:outline-none focus:border-emerald-600" />
                </div>
                <div>
                  <label className="text-[10px] uppercase font-bold tracking-widest text-emerald-600 block mb-1">Notes</label>
                  <input type="text" value={weightNotes} onChange={(e) => setWeightNotes(e.target.value)}
                    placeholder="Feeling great!" className="w-full p-3 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-600 focus:outline-none focus:border-emerald-600" />
                </div>
                <div className="flex items-end">
                  <button onClick={handleLogWeight} disabled={weightSaving || !weightInput}
                    className="w-full p-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs hover:bg-emerald-800 transition-all disabled:opacity-50">
                    {weightSaving ? "Saving..." : "Save"}
                  </button>
                </div>
              </div>
              {weightSaved && <p className="text-emerald-600 text-xs font-bold mt-2">Weight logged!</p>}
            </div>
          )}


          {/* Weight + BMI Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="space-y-4">
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 text-center rounded-xl">
                  <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500">Starting</p>
                  <p className="text-2xl font-bold text-emerald-900 dark:text-emerald-50">{weight?.starting || "-"} <span className="text-xs font-normal text-zinc-400">kg</span></p>
                </div>
                <div className="bg-emerald-50 dark:bg-emerald-900/20 p-4 text-center rounded-xl">
                  <p className="text-[10px] uppercase font-bold tracking-widest text-emerald-600">Current</p>
                  <p className="text-2xl font-bold text-emerald-600">{weight?.latest ? parseFloat(weight.latest.weight_kg) : "-"} <span className="text-xs font-normal text-emerald-400">kg</span></p>
                </div>
                <div className={`p-4 text-center rounded-xl ${weightDiff && weightDiff.diff <= 0 ? 'bg-green-50' : 'bg-amber-50'}`}>
                  <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500">Change</p>
                  <p className={`text-2xl font-bold ${weightDiff && weightDiff.diff <= 0 ? 'text-green-600' : 'text-amber-600'}`}>
                    {weightDiff ? `${weightDiff.diff > 0 ? '+' : ''}${weightDiff.diff}` : "-"}
                    <span className="text-xs font-normal text-zinc-400 ml-1">({weightDiff ? `${weightDiff.pct > 0 ? '+' : ''}${weightDiff.pct}%` : "-"})</span>
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <span className="text-xs font-bold uppercase tracking-widest text-zinc-500">Target:</span>
                <input type="number" step="0.1" min="20" max="300" value={targetWeight || ""}
                  onChange={(e) => setTargetWeight(e.target.value ? parseFloat(e.target.value) : null)}
                  className="w-20 p-2 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-600 text-emerald-900 dark:text-emerald-50 font-bold text-center focus:outline-none focus:border-emerald-600" />
                <span className="text-xs text-zinc-400">kg</span>
              </div>
            </div>
            <div className="space-y-4">
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 text-center rounded-xl">
                  <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500">Starting BMI</p>
                  <p className="text-2xl font-bold text-zinc-500">{startingBMI || "-"}</p>
                  {startingBmiCatVal && <p className={`text-[10px] font-bold uppercase tracking-widest ${startingBmiCatVal.color}`}>{startingBmiCatVal.label}</p>}
                </div>
                <div className="bg-emerald-50 dark:bg-emerald-900/20 p-4 text-center rounded-xl">
                  <p className="text-[10px] uppercase font-bold tracking-widest text-emerald-600">Current BMI</p>
                  <p className="text-2xl font-bold text-emerald-600">{currentBMI || "-"}</p>
                  {bmiCatVal && <p className={`text-[10px] font-bold uppercase tracking-widest ${bmiCatVal.color}`}>{bmiCatVal.label}</p>}
                </div>
                <div className="bg-zinc-50 dark:bg-zinc-800/50 p-4 text-center rounded-xl">
                  <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500">BMI Change</p>
                  <p className={`text-2xl font-bold ${startingBMI && currentBMI ? (currentBMI < startingBMI ? 'text-green-600' : 'text-amber-600') : 'text-zinc-400'}`}>
                    {startingBMI && currentBMI ? `${(currentBMI - startingBMI) > 0 ? '+' : ''}${Math.round((currentBMI - startingBMI) * 10) / 10}` : "-"}
                  </p>
                </div>
              </div>
              {currentBMI && (<div>
                <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mb-2">BMI Scale</p>
                <div className="flex h-2 rounded-full overflow-hidden">
                  <div className="bg-blue-300" style={{flex:8.5}}/><div className="bg-emerald-300" style={{flex:6.5}}/>
                  <div className="bg-amber-300" style={{flex:5}}/><div className="bg-red-300" style={{flex:10}}/>
                </div>
                <div className="flex justify-between text-[8px] mt-1">
                  <span className="text-blue-600 font-bold">Underweight</span>
                  <span className="text-emerald-600 font-bold">Normal</span>
                  <span className="text-amber-600 font-bold">Overweight</span>
                  <span className="text-red-600 font-bold">Obese</span>
                </div>
                <div className="relative h-8 mt-1">
                  <div className="bmi-marker" style={{left:`${Math.min(95,Math.max(5,((currentBMI-10)/30)*100))}%`,background: currentBMI<18.5?'#2563eb':currentBMI<25?'#059669':currentBMI<30?'#d97706':'#dc2626'}}/>
                  {startingBMI&&<div className="bmi-start-marker" style={{left:`${Math.min(95,Math.max(5,((startingBMI-10)/30)*100))}%`}}/>}
                  <div className="flex justify-between text-[8px] text-zinc-400 mt-5"><span>10</span><span>18.5</span><span>25</span><span>30</span><span>40</span></div>
                </div>
              </div>)}
            </div>
          </div>

          <div className="mt-6 pt-6 border-t border-zinc-200 dark:border-zinc-700">
            <h3 className="text-sm font-bold text-zinc-500 uppercase tracking-widest mb-4">Weight Trend</h3>
            <WeightTrendChart history={weight?.history || []} startingWeight={weight?.starting} targetWeight={targetWeight} />
          </div>
        </div>


        {/* Program Progress */}
        {stats && stats.totalWorkouts > 0 && (
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 md:p-8">
            <h2 className="text-lg font-bold text-emerald-900 dark:text-emerald-50 flex items-center gap-2 mb-4">
              <span className="material-symbols-outlined text-emerald-600">trending_up</span> Program Progress
            </h2>
            <div className="space-y-3">
              <div className="flex justify-between text-sm">
                <span className="font-bold text-zinc-600 dark:text-zinc-300">{stats.totalWorkouts} workouts</span>
                <span className="text-zinc-400">{stats.completionPercent || 0}% weekly</span>
              </div>
              <div className="w-full h-3 bg-zinc-100 dark:bg-zinc-800 rounded-full overflow-hidden">
                <div className="h-full bg-emerald-600 rounded-full transition-all duration-1000" style={{ width: `${Math.min(100, stats.completionPercent || 0)}%` }} />
              </div>
            </div>
          </div>
        )}

        {/* Charts */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6">
            <h3 className="text-xs font-bold uppercase tracking-widest text-zinc-500 mb-3">Weekly Activity</h3>
            <MiniChart data={(() => {
              const wd = [0, 0, 0, 0, 0, 0, 0];
              if (sessions) {
                const now = new Date();
                sessions.forEach((s: any) => {
                  if (s.started_at) { const d = new Date(s.started_at); const diff = Math.floor((now.getTime() - d.getTime()) / 86400000); if (diff >= 0 && diff < 7) wd[6 - diff]++; }
                });
              }
              return wd;
            })()} color="#059669" />
          </div>
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6">
            <h3 className="text-xs font-bold uppercase tracking-widest text-zinc-500 mb-3">Monthly Activity</h3>
            <MiniChart data={(() => {
              const md: number[] = [];
              if (progress && progress.length > 0) {
                const g: Record<string, number> = {};
                progress.forEach((p: any) => { if (p.date) { const wk = Math.floor(new Date(p.date).getTime() / (86400000 * 7)); g[wk] = (g[wk] || 0) + (p.completed ? 1 : 0); } });
                Object.values(g).slice(0, 12).forEach((v) => md.push(v));
              }
              return md.length > 0 ? md : [0, 0, 0, 0];
            })()} color="#7c3aed" />
          </div>
        </div>

        {/* Personal Bests */}
        {bests && bests.length > 0 && (
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 md:p-8">
            <h2 className="text-lg font-bold text-emerald-900 dark:text-emerald-50 flex items-center gap-2 mb-4">
              <span className="material-symbols-outlined text-emerald-600">military_tech</span> Personal Bests
            </h2>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b border-zinc-200 dark:border-zinc-700 text-[10px] uppercase tracking-widest font-bold text-zinc-500">
                  <th className="text-left py-2 pr-4">Exercise</th><th className="text-right py-2 px-2">Best</th>
                  <th className="text-right py-2 px-2">Reps</th><th className="text-right py-2 px-2">RPE</th><th className="text-right py-2 pl-2">Date</th>
                </tr></thead>
                <tbody>
                  {bests.slice(0, 8).map((b: any, i: number) => (
                    <tr key={i} className="border-b border-zinc-100 dark:border-zinc-800">
                      <td className="py-3 pr-4 font-bold text-emerald-900 dark:text-emerald-50">{b.exercise_name}</td>
                      <td className="py-3 px-2 text-right font-bold text-emerald-600">{b.best_weight} kg</td>
                      <td className="py-3 px-2 text-right text-zinc-600 dark:text-zinc-400">{b.reps}</td>
                      <td className="py-3 px-2 text-right text-zinc-600 dark:text-zinc-400">{b.rpe || "-"}</td>
                      <td className="py-3 pl-2 text-right text-zinc-400 text-xs">{formatDate(b.achieved_at)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}


        {/* Achievements */}
        {achievements && achievements.achievements && achievements.achievements.length > 0 && (
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 md:p-8">
            <h2 className="text-lg font-bold text-emerald-900 dark:text-emerald-50 flex items-center gap-2 mb-4">
              <span className="material-symbols-outlined text-emerald-600">stars</span> Achievements
            </h2>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {achievements.achievements.map((a: any) => (
                <div key={a.id} className={`p-4 text-center rounded-xl border-2 transition-all ${a.unlocked ? 'bg-emerald-50 dark:bg-emerald-900/20 border-emerald-300 dark:border-emerald-700 badge-unlocked' : 'bg-zinc-50 dark:bg-zinc-800/30 border-zinc-200 dark:border-zinc-700 opacity-50'}`}>
                  <span className="text-3xl block mb-1">{a.icon}</span>
                  <p className={`text-xs font-bold uppercase tracking-widest ${a.unlocked ? 'text-emerald-700 dark:text-emerald-300' : 'text-zinc-400'}`}>{a.label}</p>
                  <p className="text-[8px] text-zinc-400 mt-1">{a.unlocked ? a.description : "Locked"}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Workout History */}
        {sessions && sessions.length > 0 && (
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 md:p-8">
            <h2 className="text-lg font-bold text-emerald-900 dark:text-emerald-50 flex items-center gap-2 mb-4">
              <span className="material-symbols-outlined text-emerald-600">history</span> Workout History
            </h2>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b border-zinc-200 dark:border-zinc-700 text-[10px] uppercase tracking-widest font-bold text-zinc-500">
                  <th className="text-left py-2 pr-4">Date</th><th className="text-left py-2 px-2">Day</th>
                  <th className="text-right py-2 px-2">Duration</th><th className="text-right py-2 px-2">Ex</th>
                  <th className="text-right py-2 px-2">Sets</th><th className="text-right py-2 pl-2">Cal</th>
                </tr></thead>
                <tbody>
                  {sessions.slice(0, 15).map((s: any, i: number) => (
                    <tr key={i} className="border-b border-zinc-100 dark:border-zinc-800">
                      <td className="py-3 pr-4 font-bold text-emerald-900 dark:text-emerald-50">{formatFullDate(s.started_at)}</td>
                      <td className="py-3 px-2 text-zinc-600 dark:text-zinc-400">Day {s.day_number || "-"}</td>
                      <td className="py-3 px-2 text-right text-zinc-600 dark:text-zinc-400">{formatDuration(s.duration_seconds || 0)}</td>
                      <td className="py-3 px-2 text-right font-bold">{s.exercises_completed || "-"}</td>
                      <td className="py-3 px-2 text-right font-bold">{s.sets_completed || `${s.total_sets || "-"}`}</td>
                      <td className="py-3 pl-2 text-right text-zinc-400">{s.calories_burned || "-"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Print Footer */}
        <div className="print-only text-center mt-8 pt-4 border-t border-zinc-300 hidden">
          <p className="text-[10px] text-zinc-400">Generated by Marich Wellness &mdash; {new Date().toLocaleDateString()}</p>
        </div>
      </main>
    </div>
  );
}

