"use client"; import { useState, useRef, useEffect } from "react"; import { motion, AnimatePresence } from "motion/react"; import { Calendar } from "lucide-react"; import { type TimeRange } from "@/lib/utils"; import { useTimeRange } from "@/lib/time-range-context"; import { useI18n } from "@/lib/i18n"; export function TimeRangeSelector() { const { t } = useI18n(); const { range, setRange, customStart, customEnd, setCustomStart, setCustomEnd } = useTimeRange(); const [showPopover, setShowPopover] = useState(false); const [localStart, setLocalStart] = useState(customStart); const [localEnd, setLocalEnd] = useState(customEnd); const popoverRef = useRef(null); const containerRef = useRef(null); // Sync local state when context changes useEffect(() => { setLocalStart(customStart); }, [customStart]); useEffect(() => { setLocalEnd(customEnd); }, [customEnd]); // Close popover on click outside useEffect(() => { if (!showPopover) return; const handler = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setShowPopover(false); } }; document.addEventListener("mousedown", handler); return () => document.removeEventListener("mousedown", handler); }, [showPopover]); const presets: { label: string; value: TimeRange }[] = [ { label: t("time.today"), value: "today" }, { label: t("time.7d"), value: "7d" }, { label: t("time.30d"), value: "30d" }, { label: t("time.all"), value: "all" }, ]; function handlePreset(v: TimeRange) { setRange(v); setShowPopover(false); } function handleCustomClick() { if (range === "custom" && showPopover) { setShowPopover(false); } else { setRange("custom"); setShowPopover(true); } } function handleConfirm() { setCustomStart(localStart); setCustomEnd(localEnd); setShowPopover(false); } return (
{presets.map((r) => ( ))} {/* Custom button */}
{/* Popover */} {showPopover && (
setLocalStart(e.target.value)} className="input-glass w-full rounded-md px-3 py-1.5 text-xs font-[family-name:var(--font-geist-mono)]" />
setLocalEnd(e.target.value)} className="input-glass w-full rounded-md px-3 py-1.5 text-xs font-[family-name:var(--font-geist-mono)]" />
)}
); }