﻿"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 CALCULATION â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
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; bg: string; range: string } {
  if (bmi <= 0) return { label: "â€”", color: "text-zinc-400", bg: "bg-zinc-100", range: "" };
  if (bmi < 18.5) return { label: "Underweight", color: "text-blue-600", bg: "bg-blue-100", range: "< 18.5" };
  if (bmi < 25) return { label: "Normal (Ideal)", color: "text-emerald-600", bg: "bg-emerald-100", range: "18.5 - 24.9" };
  if (bmi < 30) return { label: "Overweight", color: "text-amber-600", bg: "bg-amber-100", range: "25.0 - 29.9" };
  return { label: "Obese", color: "text-red-600", bg: "bg-red-100", range: ">= 30.0" };
}

function bmiScalePercent(bmi: number): number {
  if (bmi <= 0) return 0;
  if (bmi >= 40) return 100;
  return ((bmi - 10) / 30) * 100;
}

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

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

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


// â”€â”€â”€ SVG MINI CHART (reused from SettingsPanel pattern) â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
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;
  const 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/BMI 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;
  const h = 180;
  const padL = 35;
  const padR = 10;
  const plotW = w - padL - padR;
  const divisor = Math.max(weights.length - 1, 1);

  function xPos(i: number) { return padL + (i / divisor) * plotW; }
  function yPos(v: number) { return 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 yTicks = 4;
  const yLabels: number[] = [];
  for (let i = 0; i <= yTicks; i++) {
    yLabels.push(minVal + (range / yTicks) * 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: number, i: number) => (
          <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, height: 0, borderTop: "1.5px dashed #6b7280", display: "inline-block" }}></span> Starting</span>}
        {targetWeight && <span className="flex items-center gap-1"><span style={{ width: 12, height: 0, borderTop: "1.5px dashed #dc2626", display: "inline-block" }}></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);

        // Auto-set target weight based on goals
        if (reportsData.weight?.starting) {
          const profile = profileData?.profile;
          const goals = profile?.goals
            ? (typeof profile.goals === "string" ? JSON.parse(profile.goals) : 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]);

  // â”€â”€â”€ Weight Log Handler â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
  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("");
        // Refresh reports data
        const reportsRes = await fetch(`/api/fitness/reports?userId=${encodeURIComponent(email)}`);
        if (reportsRes.ok) {
          const reportsData = await reportsRes.json();
          setData(reportsData);
        }
        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(() => {
    if (!currentBMI) return null;
    return bmiCategory(currentBMI);
  }, [currentBMI]);

  const startingBmiCatVal = useMemo(() => {
    if (!startingBMI) return null;
    return bmiCategory(startingBMI);
  }, [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) * 100 * 10) / 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>
    );
  }

        {/* â•â•â• 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>

          {/* Weight Log Form */}
          {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 text-emerald-900 dark:text-emerald-50 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>
          )}


  // â”€â”€â”€ 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 */}
      <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 transition-colors">
          <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>
      {/* Print-only 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 Stats 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>
      </main>
    </div>
  );
}


          {/* Weight + BMI Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Left: Weight */}
            <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>

            {/* Right: BMI */}
            <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>

              {/* BMI Scale */}
              {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>


          {/* Weight Trend Chart */}
          <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 completed</span>
                <span className="text-zinc-400">{stats.completionPercent || 0}% weekly target</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>
        )}

        {/* â•â•â• Weekly & Monthly 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 weekData = [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 daysDiff = Math.floor((now.getTime() - d.getTime()) / 86400000);
                    if (daysDiff >= 0 && daysDiff < 7) weekData[6 - daysDiff]++;
                  }
                });
              }
              return weekData;
            })()} 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 monthData: number[] = [];
              if (progress && progress.length > 0) {
                const grouped: Record<string, number> = {};
                progress.forEach((p: any) => {
                  if (p.date) {
                    const wk = Math.floor(new Date(p.date).getTime() / (86400000 * 7));
                    grouped[wk] = (grouped[wk] || 0) + (p.completed ? 1 : 0);
                  }
                });
                Object.values(grouped).slice(0, 12).forEach((v) => monthData.push(v));
              }
              return monthData.length > 0 ? monthData : [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 */}
      </main>
    </div>
  );
}

