"use client";
import { useMemo, useState, type PointerEvent } from "react";
import { House } from "lucide-react";
import { AnimatedCounter, Badge, SegmentedControl, WidgetCard, WidgetChart } from "@lumo/ui";
import { compactMoney } from "./compact-money";
import { PropertyValuePlot } from "./PropertyValuePlot";
import { plotValuations } from "./property-valuation-plot";
import { monthsByRange, propertyChart, propertyDefaults, propertyHistory, propertyRanges } from "./property-value.constants";
import type { PropertyRange, PropertyValueWidgetProps } from "./property-value.types";
import styles from "./PropertyValueWidget.module.css";
export function PropertyValueWidget({
title = propertyDefaults.title, subtitle = propertyDefaults.subtitle,
history = propertyHistory, currency = propertyDefaults.currency, initialRange = propertyDefaults.initialRange,
}: PropertyValueWidgetProps = {}) {
const [range, setRange] = useState(initialRange);
const [position, setPosition] = useState<number | null>(null);
const [pinned, setPinned] = useState<number | null>(null);
const { money, exactMoney } = useMemo(() => ({
money: new Intl.NumberFormat("en-US", { style: "currency", currency, notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: 2 }),
exactMoney: new Intl.NumberFormat("en-US", { style: "currency", currency, currencyDisplay: "code", minimumFractionDigits: 0, maximumFractionDigits: 3 }),
}), [currency]);
const data = useMemo(() => history.filter(({ value }) => Number.isFinite(value) && value >= 0).slice(-monthsByRange[range]), [history, range]);
const chart = useMemo(() => plotValuations(data), [data]);
const inspected = position ?? pinned;
const index = Math.min(inspected ?? data.length - 1, data.length - 1);
const point = data[index];
const marker = chart.points[index];
const first = data[0];
const change = first?.value && point && index > 0 ? (point.value - first.value) / first.value * 100 : null;
const percent = change === null || !Number.isFinite(change) ? null : Math.round(change * 10) / 10;
const baseLabel = percent === null ? "No comparison" : `vs ${first.date}`;
const pointLabel = point && `${point.date}, ${exactMoney.format(point.value)}`;
const { width, height, inset } = propertyChart;
const interactive = data.length > 1;
function inspect(event: PointerEvent<HTMLElement>) {
const bounds = event.currentTarget.getBoundingClientRect();
if (bounds.width <= 0) return null;
const x = (event.clientX - bounds.left) / bounds.width * width;
const progress = Math.min(1, Math.max(0, (x - inset) / (width - 2 * inset)));
return Math.round(progress * (data.length - 1));
}
return <div className={styles.frame}>
<WidgetCard size="medium" className={styles.card} title={title} description={subtitle} icon={<House />}
action={<SegmentedControl label="Valuation range" className={styles.periods} size="sm" value={range} options={propertyRanges}
onValueChange={(value) => { setRange(value as PropertyRange); setPosition(null); setPinned(null); }} />}>
<div className={styles.summary}>
<div className={styles.estimate}>
<span className={styles.amount} title={pointLabel}>
{point ? <AnimatedCounter {...compactMoney(point.value, money)} blur={false} /> : "—"}
</span>
<span className={styles.caption} title={point?.date}>{point?.date ?? "Estimate"}</span>
</div>
<div className={styles.comparison}>
<Badge tone={percent === null || percent === 0 ? "neutral" : percent > 0 ? "success" : "danger"} pill>
{percent === null ? "—" : <AnimatedCounter className={styles.change} value={percent}
decimals={Number.isInteger(percent) ? 0 : 1} prefix={percent > 0 ? "+" : ""} suffix="%" blur={false} />}
</Badge>
<span className={styles.caption} title={baseLabel}>{baseLabel}</span>
</div>
</div>
{point && marker ? <WidgetChart className={styles.chart}
{...interactive ? { role: "slider", tabIndex: 0, "aria-label": "Valuation history", "aria-valuemin": 1, "aria-valuemax": data.length,
"aria-valuenow": index + 1, "aria-valuetext": pointLabel } : { role: "img", "aria-label": pointLabel }}
onPointerDown={(event) => {
if (!interactive || event.button !== 0) return;
const next = inspect(event);
setPosition(null);
setPinned((current) => current === next ? null : next);
}}
onPointerMove={(event) => {
if (!interactive || event.pointerType === "touch") return;
if (pinned !== null) {
if (event.buttons === 1) setPinned(inspect(event));
return;
}
setPosition(inspect(event));
}}
onPointerLeave={() => setPosition(null)} onBlur={() => setPosition(null)}
onKeyDown={(event) => {
if (event.key === "Escape") { setPosition(null); setPinned(null); return; }
const next = event.key === "ArrowLeft" ? index - 1 : event.key === "ArrowRight" ? index + 1
: event.key === "Home" ? 0 : event.key === "End" ? data.length - 1 : null;
if (next === null) return;
event.preventDefault();
setPosition(null);
setPinned(Math.max(0, Math.min(data.length - 1, next)));
}}>
<svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
<PropertyValuePlot chart={chart} range={range} />
{inspected !== null && <line x1={marker.x} x2={marker.x} y2={height} stroke="var(--text-muted)" strokeDasharray="3 3" />}
</svg>
<span aria-hidden="true" className={styles.marker} style={{ left: `${marker.x / width * 100}%`, top: `${marker.y / height * 100}%` }} />
</WidgetChart> : <div className={styles.empty}>No valuation history</div>}
</WidgetCard>
</div>;
}