"use client";

import { useEffect, useState } from "react";
import type { SensorAdapter } from "@enode/core/ble/enode-sensor";
import { useTranslation } from "@enode/core/translations/hooks";
import { sensorDetailRows } from "./sensor-details";

// How often the open dialog re-reads the sensor. Device Status changes in place
// (charging, calibration, the ~30 s heartbeat), so the rows follow it live.
const REFRESH_MS = 1_000;

/**
 * Label/value rows for one sensor in the "Sensor details" dialog. Re-renders
 * on a timer because the adapter mutates outside React (like
 * `useSensorSnapshot` in the connect sheet).
 */
export function SensorDetailsList({
  sensor,
  heading,
}: {
  sensor: SensorAdapter;
  /** SmartBar side ("L" / "R"), when the station has two sensors. */
  heading: string | null;
}) {
  const { t } = useTranslation();
  const [, setTick] = useState(0);
  useEffect(() => {
    const id = window.setInterval(() => setTick((n) => n + 1), REFRESH_MS);
    return () => window.clearInterval(id);
  }, []);

  const rows = sensorDetailRows(sensor, t);
  return (
    <div className="flex flex-col gap-1.5">
      {heading && (
        <p className="body-small font-medium text-foreground-muted">{heading}</p>
      )}
      <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1">
        {rows.map((row) => (
          <div key={row.key} className="contents">
            <dt className="body-small text-foreground-muted">{row.label}</dt>
            <dd className="body-small tabular-nums text-right text-foreground-default">
              {row.value}
            </dd>
          </div>
        ))}
      </dl>
    </div>
  );
}
