"use client"
import React, { useState, useEffect, useCallback, useRef } from "react"
import { motion, AnimatePresence } from "framer-motion"
import type { AnalysisResult } from "@/app/page"
import { HealthTrendChart } from "./health-trend-chart"
import { apiGet, apiPost } from "@/lib/api"
interface SavedAnalysis {
id: string
summary: string
findings: AnalysisResult["findings"]
report: AnalysisResult["report"]
created_at: string
}
interface AnalysisHistoryProps {
sessionId?: string
refreshTrigger?: number
onSelect: (a: SavedAnalysis) => void
onCompare: (a: SavedAnalysis, b: SavedAnalysis) => void
mockData?: SavedAnalysis[]
inline?: boolean
}
function formatDate(s: string) {
if (!s) return "—"
return new Date(s).toLocaleDateString("ar-SA", { day: "numeric", month: "long", year: "numeric" })
}
function formatDateShort(s: string) {
if (!s) return "—"
return new Date(s).toLocaleDateString("ar-SA", { day: "numeric", month: "short" })
}
function calcPct(value: string, range: string) {
const nums = range?.match(/[\d.]+/g)
if (!nums || nums.length < 2) return null
const lo = parseFloat(nums[0]), hi = parseFloat(nums[1]), val = parseFloat(value)
if (isNaN(val) || isNaN(lo) || isNaN(hi) || hi === lo) return null
return Math.max(4, Math.min(96, ((val - lo) / (hi - lo)) * 100))
}
const STATUS = {
high: { label: "مرتفع", textCls: "text-destructive", bgCls: "bg-destructive/10", barCls: "bg-destructive" },
low: { label: "منخفض", textCls: "text-warning", bgCls: "bg-warning/10", barCls: "bg-warning" },
normal: { label: "طبيعي", textCls: "text-success", bgCls: "bg-success/10", barCls: "bg-success" },
} as const
const getS = (s: string) => STATUS[s as keyof typeof STATUS] ?? STATUS.normal
function counts(a: SavedAnalysis) {
const f = a.findings ?? []
return {
total: f.length,
high: f.filter(x => x.status === "high").length,
low: f.filter(x => x.status === "low").length,
normal: f.filter(x => x.status === "normal").length,
}
}
/* ─── Icons ─── */
function ScalesIcon({ className = "w-3.5 h-3.5" }: { className?: string }) {
return (
)
}
function ChevronIcon({ className = "w-3.5 h-3.5" }: { className?: string }) {
return (
)
}
/* ─────────────────────────────────────────────
Compare Hint
───────────────────────────────────────────── */
function CompareHint() {
return (
اضغط «قارن» على أي تحليلين لمتابعة تغيّراتك الصحية
)
}
/* ─────────────────────────────────────────────
Floating Compare Bar
───────────────────────────────────────────── */
function FloatingCompareBar({
selected, onCompare, onCancel, fixed = false,
}: {
selected: SavedAnalysis[]
onCompare: () => void
onCancel: () => void
fixed?: boolean
}) {
return (
{selected.length === 1 ? (
حدد تحليلاً ثانياً لبدء المقارنة
) : (
{selected.map((s, i) => (
{i + 1}
{s.summary}
{formatDateShort(s.created_at)}
))}
قارن الآن
)}
)
}
/* ─────────────────────────────────────────────
Inline Detail Panel
───────────────────────────────────────────── */
function InlineDetail({
item, onUse,
}: {
item: SavedAnalysis
onUse: (a: SavedAnalysis) => void
}) {
const c = counts(item)
return (
{/* Header mini */}
{c.high > 0 && (
{c.high} مرتفع
)}
{c.low > 0 && (
{c.low} منخفض
)}
{c.high === 0 && c.low === 0 && (
كل القيم طبيعية ✓
)}
{formatDate(item.created_at)}
{/* Stats row */}
{[
{ num: c.normal, label: "طبيعي", bg: "bg-success/8 border-success/20", text: "text-success" },
{ num: c.high, label: "مرتفع", bg: "bg-destructive/8 border-destructive/20", text: "text-destructive" },
{ num: c.low, label: "منخفض", bg: "bg-warning/8 border-warning/20", text: "text-warning" },
].map((s, i) => (
{s.num}
{s.label}
))}
{/* Summary */}
{item.summary && (
الملخص
{item.summary}
)}
{/* Mini-cards grid */}
{item.findings && item.findings.length > 0 && (
{item.findings.map((f, i) => {
const s = getS(f.status)
const pct = calcPct(f.value, f.range ?? "")
return (
{f.value}
{f.unit && {f.unit}}
{pct !== null && (
)}
{f.range && (
طبيعي: {f.range}
)}
)
})}
)}
{(!item.findings || item.findings.length === 0) && (
لا توجد بيانات فحوصات
)}
{/* Use button */}
onUse(item)}
className="w-full py-4 rounded-2xl text-sm font-bold gradient-primary text-primary-foreground shadow-glow-primary hover:opacity-90 transition-opacity"
>
استخدم هذا التحليل
)
}
/* ─────────────────────────────────────────────
Shared Card List (used in both inline & drawer)
───────────────────────────────────────────── */
function AnalysisCardList({
analyses,
loading,
selected,
expandedId,
cardRefs,
listRef,
toggleExpand,
toggleSelect,
handleUse,
containerClassName = "space-y-2",
}: {
analyses: SavedAnalysis[]
loading: boolean
selected: SavedAnalysis[]
expandedId: string | null
cardRefs: React.RefObject