"use client";

import { type FormEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import dynamic from "next/dynamic";
import { useRouter } from "next/navigation";
import { createPortal } from "react-dom";
import { io, type Socket } from "socket.io-client";

import {
  DEFAULT_VEHICLE_COLOR_KEY,
  VEHICLE_COLOR_OPTIONS,
  getVehicleColorHex,
} from "@tracker/shared";
import type { HistoryPoint, PositionSnapshot, VehicleAlertSummary, VehicleColorKey, VehicleKind, VehicleSummary } from "@tracker/shared";

import {
  acknowledgeAlert,
  ApiError,
  clearSession,
  createUser,
  createDevice,
  createVehicle,
  deleteDevice,
  deleteUser,
  fetchCompanyRoute,
  fetchCompanySettings,
  fetchDevices,
  fetchInspectionEmailSettings,
  fetchVehicleStatsOverview,
  fetchVehicleTrips,
  fetchUsers,
  fetchActiveAlerts,
  fetchRecentAlerts,
  deleteVehicle,
  fetchVehicleHistory,
  fetchVehiclePreviousPosition,
  fetchVehicles,
  loadSession,
  reverseGeocode,
  saveSession,
  sendTestTrackingEmail,
  updateCompanySettings,
  updateInspectionEmailSettings,
  type AdminDeviceSummary,
  type AdminUserSummary,
  type CompanyRouteSummary,
  type CompanySettingsSummary,
  type InspectionEmailSettingsSummary,
  type VehicleStatsOverview,
  type VehicleTripSummary,
  updateDevice,
  updateUser,
  updateVehicle,
  updateVehicleInspection,
} from "../../lib/api";
import { StatsPanel } from "./_components/stats-panel";
import { UserAccessCard } from "./_components/user-access-card";
import { VehicleDetailsPanel } from "./_components/vehicle-details-panel";
import { VehicleEditModal } from "./_components/vehicle-edit-modal";

const DynamicMap = dynamic(
  () => import("../../components/map-view").then((module) => module.MapView),
  { ssr: false },
);

const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const PLAYBACK_FRAME_MS = 100;
const PLAYBACK_STOP_PREVIEW_MS = 1500;
const TELEMETRY_FLUSH_MS = 1000;
const DASHBOARD_REFRESH_CONNECTED_MS = 5 * 60 * 1000;
const DASHBOARD_REFRESH_DISCONNECTED_MS = 30 * 1000;
const DEFAULT_HISTORY_RANGE_MS = 1000 * 60 * 60 * 8;
const ADDRESS_REUSE_DISTANCE_METERS = 100;
const LIVE_INTERPOLATION_MAX_SPEED_KMH = 200;
const LIVE_PREDICTION_INTERVAL_MS = 200;
const LIVE_PREDICTION_MAX_AGE_MS = 15_000;
const LIVE_PREDICTION_MIN_SPEED_KMH = 1;
const LIVE_INTERPOLATION_MIN_DURATION_MS = 700;
const COMPANY_ROUTE_REFRESH_MS = 60 * 1000;
const COMPANY_ROUTE_REFRESH_DISTANCE_METERS = 500;

type LiveInterpolationSegment = {
  from: PositionSnapshot;
  to: PositionSnapshot;
  startedAtMs: number;
  durationMs: number;
};

type SelectedVehicleAddressMode = "parked" | "driving";

type SelectedVehicleAddressCacheEntry = {
  lat: number;
  lon: number;
  label: string;
  key: string;
};

type StampedHistoryPoint = {
  point: HistoryPoint;
  timestamp: number;
};

const isSafariBrowser = () => {
  if (typeof navigator === "undefined") {
    return false;
  }

  const userAgent = navigator.userAgent;
  return /Safari/i.test(userAgent) && !/Chrome|CriOS|Chromium|Android/i.test(userAgent);
};

const toTripStreetLabel = (label?: string | null) => {
  if (!label) {
    return "Brak adresu";
  }

  const compact = label
    .split(",")
    .map((segment) => segment.trim())
    .filter(Boolean)
    .slice(0, 2)
    .join(", ");

  return compact || label;
};

const formatSpeedKmh = (speed?: number | null) => {
  if (speed == null || Number.isNaN(speed) || !Number.isFinite(speed)) {
    return "0 km/h";
  }

  const normalized = clamp(Math.ceil(speed), 0, 240);
  return `${normalized} km/h`;
};

const getVehicleOptionLabel = (vehicle: Pick<VehicleSummary, "name">) =>
  vehicle.name;

const normalizeInspectionDateInput = (value?: string | null) => {
  if (!value) {
    return "";
  }

  return value.trim().match(/^(\d{4}-\d{2}-\d{2})/)?.[1] ?? "";
};

type InspectionAlertState = "ok" | "missing" | "due_soon" | "overdue";

type ServiceNotice = {
  key: string;
  label: string;
  state: InspectionAlertState;
  editable: boolean;
};

const getInspectionAlertState = (value?: string | null): InspectionAlertState => {
  const normalizedValue = normalizeInspectionDateInput(value);
  if (!normalizedValue) {
    return "missing";
  }

  const today = new Date();
  const todayUtc = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
  const due = new Date(`${normalizedValue}T00:00:00`);
  const dueUtc = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());

  if (Number.isNaN(dueUtc)) {
    return "missing";
  }

  const dayDiff = Math.floor((dueUtc - todayUtc) / 86400000);
  if (dayDiff < 0) {
    return "overdue";
  }

  return dayDiff <= 14 ? "due_soon" : "ok";
};

const getLocalInspectionStatus = (value?: string | null): VehicleSummary["inspectionStatus"] => {
  const state = getInspectionAlertState(value);
  if (state === "missing") {
    return "missing";
  }

  return state === "ok" ? "ok" : "due_soon";
};

const formatDateOnly = (value?: string | null) => {
  const normalizedValue = normalizeInspectionDateInput(value);
  if (!normalizedValue) {
    return "Brak";
  }

  const date = new Date(`${normalizedValue}T00:00:00`);
  if (Number.isNaN(date.getTime())) {
    return normalizedValue;
  }

  return new Intl.DateTimeFormat("pl-PL", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(date);
};

const getInspectionNoticeLabel = (value?: string | null) => {
  const state = getInspectionAlertState(value);
  if (state === "missing") {
    return "WPISZ TERMIN PRZEGLĄDU";
  }

  if (state === "overdue") {
    return `PRZEGLĄD ${formatDateOnly(value)}`;
  }

  if (state === "due_soon") {
    return `PRZEGLĄD ${formatDateOnly(value)}`;
  }

  return null;
};

const getServiceNotice = (label: string, value?: string | null, missingLabel?: string): ServiceNotice | null => {
  const state = getInspectionAlertState(value);
  if (state === "ok") {
    return null;
  }

  return {
    key: label,
    label: state === "missing" ? (missingLabel ?? `WPISZ TERMIN ${label.toUpperCase()}`) : `${label.toUpperCase()} ${formatDateOnly(value)}`,
    state,
    editable: state === "missing",
  };
};

const getTireServiceState = (tireChangedAt?: string | null, nextTireChangeDueDate?: string | null): InspectionAlertState => {
  if (!normalizeInspectionDateInput(tireChangedAt) || !normalizeInspectionDateInput(nextTireChangeDueDate)) {
    return "missing";
  }

  return getInspectionAlertState(nextTireChangeDueDate);
};

const getOilServiceState = (
  oilChangeDueDate?: string | null,
  oilChangeOdometer?: number | null,
  oilChangeIntervalKm?: number | null,
): InspectionAlertState => {
  if (
    !normalizeInspectionDateInput(oilChangeDueDate)
    || oilChangeOdometer == null
    || Number.isNaN(oilChangeOdometer)
    || oilChangeIntervalKm == null
    || Number.isNaN(oilChangeIntervalKm)
  ) {
    return "missing";
  }

  return getInspectionAlertState(oilChangeDueDate);
};

const getVehicleServiceNotices = (vehicle?: VehicleSummary | null) => {
  if (!vehicle) {
    return [] as ServiceNotice[];
  }

  const notices: ServiceNotice[] = [];
  const inspectionNotice = getServiceNotice("Przegląd", vehicle.inspectionDueDate, "WPISZ TERMIN PRZEGLĄDU");
  if (inspectionNotice) notices.push(inspectionNotice);

  const oilState = getOilServiceState(
    vehicle.oilChangeDueDate,
    vehicle.oilChangeOdometer,
    vehicle.oilChangeIntervalKm,
  );
  if (oilState !== "ok") {
    notices.push({
      key: "oil",
      label: oilState === "missing"
        ? "UZUPEŁNIJ WYMIANĘ OLEJU"
        : `WYMIANA OLEJU ${formatDateOnly(vehicle.oilChangeDueDate)}`,
      state: oilState,
      editable: oilState === "missing",
    });
  }

  const tireState = getTireServiceState(vehicle.tireChangedAt, vehicle.nextTireChangeDueDate);
  if (tireState !== "ok") {
    notices.push({
      key: "opony",
      label: tireState === "missing"
        ? "WPISZ DATY WYMIANY OPON"
        : `OPONY ${formatDateOnly(vehicle.nextTireChangeDueDate)}`,
      state: tireState,
      editable: tireState === "missing",
    });
  }

  return notices;
};

const getVehicleInspectionVisualState = (vehicle?: VehicleSummary | null): InspectionAlertState => {
  const notices = getVehicleServiceNotices(vehicle);
  if (notices.some((notice) => notice.state === "overdue")) {
    return "overdue";
  }
  if (notices.some((notice) => notice.state === "missing")) {
    return "missing";
  }
  if (notices.some((notice) => notice.state === "due_soon")) {
    return "due_soon";
  }
  return "ok";
};

const getVehicleStatusTextColor = (status: VehicleSummary["status"]) => (
  status === "online"
    ? "text-mint"
    : status === "offline"
      ? "text-coral"
      : "text-amber"
);

function VehicleStatusTruckIcon({ status, className = "h-3 w-3" }: { status: VehicleSummary["status"]; className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={`${className} ${getVehicleStatusTextColor(status)}`} fill="currentColor" aria-hidden="true">
      <path d="M20 8H17V4H1V17H3A3 3 0 0 0 6 20A3 3 0 0 0 9 17H15A3 3 0 0 0 18 20A3 3 0 0 0 21 17H23V12L20 8M6 18.5A1.5 1.5 0 1 1 7.5 17A1.5 1.5 0 0 1 6 18.5M18 18.5A1.5 1.5 0 1 1 19.5 17A1.5 1.5 0 0 1 18 18.5M17 9.5H19.5L21.46 12H17V9.5Z" />
    </svg>
  );
}

const OFFLINE_ALERT_THRESHOLD_MS = 60 * 60 * 1000;
const WARSAW_BOUNDS = {
  south: 52.06,
  west: 20.85,
  north: 52.37,
  east: 21.28,
};

type TimelineScrubberProps = {
  min: number;
  max: number;
  value: number;
  color: string;
  drivingRanges: Array<{ start: number; end: number }>;
  overspeedRanges: Array<{ start: number; end: number }>;
  maxSpeedPoint: { timestamp: number; speed: number } | null;
  active: boolean;
  onChange: (nextValue: number) => void;
};

const isVehicleInWarsaw = (vehicle: Pick<VehicleSummary, "lastPosition">) => {
  const point = vehicle.lastPosition;
  if (!point) {
    return false;
  }

  return point.lat >= WARSAW_BOUNDS.south
    && point.lat <= WARSAW_BOUNDS.north
    && point.lon >= WARSAW_BOUNDS.west
    && point.lon <= WARSAW_BOUNDS.east;
};

type DesktopDateTimeFieldProps = {
  label: string;
  value: string;
  min?: string | null;
  max?: string | null;
  isOpen: boolean;
  focusTarget?: "date" | "time" | null;
  onToggle: () => void;
  onClose: () => void;
  onChange: (nextValue: string) => void;
  onTimeTabForward?: () => void;
};

function DesktopDateTimeField({
  label,
  value,
  min,
  max,
  isOpen,
  focusTarget,
  onToggle,
  onClose,
  onChange,
  onTimeTabForward,
}: DesktopDateTimeFieldProps) {
  const fieldRef = useRef<HTMLDivElement | null>(null);
  const dateInputRef = useRef<HTMLInputElement | null>(null);
  const hourSelectRef = useRef<HTMLSelectElement | null>(null);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const handlePointerDown = (event: MouseEvent) => {
      const target = event.target as Node | null;
      if (fieldRef.current && target && !fieldRef.current.contains(target)) {
        onClose();
      }
    };

    document.addEventListener("mousedown", handlePointerDown);
    return () => document.removeEventListener("mousedown", handlePointerDown);
  }, [isOpen, onClose]);

  useEffect(() => {
    if (!isOpen || !focusTarget) {
      return;
    }

    const targetRef = focusTarget === "time" ? hourSelectRef : dateInputRef;
    const timer = window.setTimeout(() => {
      targetRef.current?.focus();
      if ("showPicker" in (targetRef.current ?? {})) {
        (targetRef.current as HTMLInputElement | null)?.showPicker?.();
      }
    }, 0);

    return () => window.clearTimeout(timer);
  }, [focusTarget, isOpen]);

  return (
    <label className="flex min-w-0 flex-col items-start gap-1">
      <span className="text-sm font-medium text-slate-200">{label}</span>
      <div ref={fieldRef} className="relative w-full">
        <button
          type="button"
          onClick={onToggle}
          className="neo-field flex h-10 w-full items-center justify-between rounded-xl px-3 text-left text-[13px] text-white"
        >
          <span className="truncate">{formatDateTimeLocalLabel(value)}</span>
          <svg
            viewBox="0 0 24 24"
            className={`ml-2 h-4 w-4 shrink-0 text-cyan-200 transition-transform ${isOpen ? "rotate-180" : ""}`}
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
          >
            <path d="m6 9 6 6 6-6" />
          </svg>
        </button>
        {isOpen ? (
          <div className={`absolute top-[calc(100%+8px)] z-[80] w-[260px] rounded-2xl border border-cyan-300/25 bg-[#121b2a] p-3 shadow-[0_18px_40px_rgba(2,8,23,0.72)] ${label === "Do" ? "right-0" : "left-0"}`}>
            <div className="grid gap-2">
              <input
                ref={dateInputRef}
                type="date"
                value={getDatePartFromDateTimeLocalValue(value)}
                min={getDatePartFromDateTimeLocalValue(min) || undefined}
                max={getDatePartFromDateTimeLocalValue(max) || undefined}
                onChange={(event) => {
                  onChange(
                    clampDateTimeLocalValue(
                      mergeDateAndTimeParts(event.target.value, getTimePartFromDateTimeLocalValue(value)),
                      min,
                      max,
                    ),
                  );
                }}
                className="neo-field h-10 w-full rounded-xl px-3 text-[13px] text-white"
              />
              <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-2">
                <select
                  ref={hourSelectRef}
                  value={getHourPartFromDateTimeLocalValue(value)}
                  onChange={(event) => {
                    onChange(
                      clampDateTimeLocalValue(
                        mergeDateAndTimeParts(
                          getDatePartFromDateTimeLocalValue(value),
                          `${event.target.value}:${getMinutePartFromDateTimeLocalValue(value)}`,
                        ),
                        min,
                        max,
                      ),
                    );
                  }}
                  className="neo-field h-10 w-full rounded-xl px-3 text-[13px] text-white"
                >
                  {Array.from({ length: 24 }, (_, index) => String(index).padStart(2, "0")).map((hour) => (
                    <option key={hour} value={hour} className="bg-slate-900 text-white">
                      {hour}
                    </option>
                  ))}
                </select>
                <span className="text-sm font-semibold text-slate-300">:</span>
                <select
                  value={getMinutePartFromDateTimeLocalValue(value)}
                  onChange={(event) => {
                    onChange(
                      clampDateTimeLocalValue(
                        mergeDateAndTimeParts(
                          getDatePartFromDateTimeLocalValue(value),
                          `${getHourPartFromDateTimeLocalValue(value)}:${event.target.value}`,
                        ),
                        min,
                        max,
                      ),
                    );
                  }}
                  onKeyDown={(event) => {
                    if (event.key === "Tab" && !event.shiftKey && onTimeTabForward) {
                      event.preventDefault();
                      onTimeTabForward();
                    }
                  }}
                  className="neo-field h-10 w-full rounded-xl px-3 text-[13px] text-white"
                >
                  {Array.from({ length: 60 }, (_, index) => String(index).padStart(2, "0")).map((minute) => (
                    <option key={minute} value={minute} className="bg-slate-900 text-white">
                      {minute}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </label>
  );
}

function TimelineScrubber({ min, max, value, color, drivingRanges, overspeedRanges, maxSpeedPoint, active, onChange }: TimelineScrubberProps) {
  const trackRef = useRef<HTMLDivElement | null>(null);
  const draggingRef = useRef(false);
  const safeRange = Math.max(1, max - min);
  const progress = ((value - min) / safeRange) * 100;

  const updateFromClientX = (clientX: number) => {
    const track = trackRef.current;
    if (!track) {
      return;
    }

    const rect = track.getBoundingClientRect();
    if (rect.width <= 0) {
      return;
    }

    const ratio = clamp((clientX - rect.left) / rect.width, 0, 1);
    const rawValue = min + ratio * safeRange;
    onChange(Math.round(rawValue));
  };

  return (
    <div
      ref={trackRef}
      className="timeline-scrubber"
      style={
        {
          "--timeline-progress": `${progress}%`,
          "--timeline-color": color,
        } as React.CSSProperties
      }
      onPointerDown={(event) => {
        event.preventDefault();
        event.stopPropagation();
        draggingRef.current = true;
        event.currentTarget.setPointerCapture(event.pointerId);
        updateFromClientX(event.clientX);
      }}
      onPointerMove={(event) => {
        if (!draggingRef.current) {
          return;
        }

        event.preventDefault();
        event.stopPropagation();
        updateFromClientX(event.clientX);
      }}
      onPointerUp={(event) => {
        draggingRef.current = false;
        event.stopPropagation();
        if (event.currentTarget.hasPointerCapture(event.pointerId)) {
          event.currentTarget.releasePointerCapture(event.pointerId);
        }
      }}
      onPointerCancel={(event) => {
        draggingRef.current = false;
        if (event.currentTarget.hasPointerCapture(event.pointerId)) {
          event.currentTarget.releasePointerCapture(event.pointerId);
        }
      }}
      role="slider"
      aria-valuemin={min}
      aria-valuemax={max}
      aria-valuenow={value}
      aria-label="Timeline historii pojazdu"
      tabIndex={0}
      onKeyDown={(event) => {
        const step = 1000;
        if (event.key === "ArrowLeft" || event.key === "ArrowDown") {
          event.preventDefault();
          onChange(Math.max(min, value - step));
        }

        if (event.key === "ArrowRight" || event.key === "ArrowUp") {
          event.preventDefault();
          onChange(Math.min(max, value + step));
        }

        if (event.key === "Home") {
          event.preventDefault();
          onChange(min);
        }

        if (event.key === "End") {
          event.preventDefault();
          onChange(max);
        }
      }}
    >
      {drivingRanges.map((range, index) => {
        const rangeStart = clamp((range.start - min) / safeRange, 0, 1) * 100;
        const rangeEnd = clamp((range.end - min) / safeRange, 0, 1) * 100;

        if (rangeEnd <= rangeStart) {
          return null;
        }

        return (
          <div
            key={`${range.start}-${range.end}-${index}`}
            className="timeline-scrubber__driving-range"
            style={{ left: `${rangeStart}%`, width: `${rangeEnd - rangeStart}%` }}
          />
        );
      })}
      {overspeedRanges.map((range, index) => {
        const rangeStart = clamp((range.start - min) / safeRange, 0, 1) * 100;
        const rangeEnd = clamp((range.end - min) / safeRange, 0, 1) * 100;

        if (rangeEnd <= rangeStart) {
          return null;
        }

        return (
          <div
            key={`overspeed-${range.start}-${range.end}-${index}`}
            className="timeline-scrubber__overspeed-range"
            style={{ left: `${rangeStart}%`, width: `${rangeEnd - rangeStart}%` }}
          />
        );
      })}
      {maxSpeedPoint && maxSpeedPoint.timestamp >= min && maxSpeedPoint.timestamp <= max ? (
        <>
          <div
            className="timeline-scrubber__max-speed-point"
            style={{ left: `${clamp((maxSpeedPoint.timestamp - min) / safeRange, 0, 1) * 100}%` }}
            title={`Maksymalna prędkość: ${formatSpeedKmh(maxSpeedPoint.speed)}`}
          />
          <div
            className="timeline-scrubber__max-speed-triangle"
            style={{ left: `${clamp((maxSpeedPoint.timestamp - min) / safeRange, 0, 1) * 100}%` }}
            title={`Maksymalna prędkość: ${formatSpeedKmh(maxSpeedPoint.speed)}`}
          />
        </>
      ) : null}
      <div className={`timeline-scrubber__thumb ${active ? "timeline-scrubber__thumb--active" : "timeline-scrubber__thumb--inactive"}`} />
    </div>
  );
}

const getPointTimeMs = (point?: Pick<HistoryPoint, "deviceTime" | "serverTime"> | null) => {
  if (!point) {
    return null;
  }

  const rawValue = point.deviceTime ?? point.serverTime;
  if (!rawValue) {
    return null;
  }

  const timestamp = new Date(rawValue).getTime();
  return Number.isNaN(timestamp) ? null : timestamp;
};

const projectPointByHeadingMeters = (
  lat: number,
  lon: number,
  heading: number,
  distanceMetersValue: number,
) => {
  const earthRadius = 6_378_137;
  const headingRad = (heading * Math.PI) / 180;
  const northMeters = Math.cos(headingRad) * distanceMetersValue;
  const eastMeters = Math.sin(headingRad) * distanceMetersValue;
  const dLat = (northMeters / earthRadius) * (180 / Math.PI);
  const dLon = (eastMeters / (earthRadius * Math.cos((lat * Math.PI) / 180))) * (180 / Math.PI);

  return {
    lat: lat + dLat,
    lon: lon + dLon,
  };
};

const interpolateLivePosition = (
  from: PositionSnapshot,
  to: PositionSnapshot,
  progress: number,
): PositionSnapshot => ({
  ...to,
  lat: from.lat + (to.lat - from.lat) * progress,
  lon: from.lon + (to.lon - from.lon) * progress,
  speed: from.speed != null && to.speed != null
    ? from.speed + (to.speed - from.speed) * progress
    : to.speed ?? from.speed ?? null,
  heading: to.heading ?? from.heading ?? null,
});

const buildLiveInterpolationSegment = (
  from: VehicleSummary["lastPosition"] | null | undefined,
  to: VehicleSummary["lastPosition"] | null | undefined,
  ignitionOn: boolean,
): LiveInterpolationSegment | null => {
  if (!from || !to || !ignitionOn) {
    return null;
  }

  const previousTimestamp = getPointTimeMs(from);
  const nextTimestamp = getPointTimeMs(to);
  const moved = from.lat !== to.lat || from.lon !== to.lon;
  const speedKmh = clamp(to.speed ?? 0, 0, LIVE_INTERPOLATION_MAX_SPEED_KMH);

  if (
    !moved
    || speedKmh < LIVE_PREDICTION_MIN_SPEED_KMH
    || to.gpsValid === false
    || previousTimestamp == null
    || nextTimestamp == null
    || nextTimestamp <= previousTimestamp
  ) {
    return null;
  }

  return {
    from,
    to,
    startedAtMs: Date.now(),
    durationMs: clamp(
      nextTimestamp - previousTimestamp,
      LIVE_INTERPOLATION_MIN_DURATION_MS,
      LIVE_PREDICTION_MAX_AGE_MS,
    ),
  };
};

const toDateTimeLocalValue = (value?: string | null) => {
  if (!value) {
    return "";
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return "";
  }

  const offsetMs = date.getTimezoneOffset() * 60_000;
  return new Date(date.getTime() - offsetMs).toISOString().slice(0, 16);
};

const parseDateTimeLocalValue = (value?: string | null) => {
  if (!value) {
    return null;
  }

  const match = value.trim().match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/);
  if (!match) {
    return null;
  }

  const [, year, month, day, hour, minute] = match;
  const date = new Date(
    Number(year),
    Number(month) - 1,
    Number(day),
    Number(hour),
    Number(minute),
    0,
    0,
  );

  return Number.isNaN(date.getTime()) ? null : date;
};

const getDateTimeLocalTimestamp = (value?: string | null) =>
  parseDateTimeLocalValue(value)?.getTime() ?? Number.NaN;

const toIsoFromDateTimeLocalValue = (value?: string | null) =>
  parseDateTimeLocalValue(value)?.toISOString() ?? "";

const getDatePartFromDateTimeLocalValue = (value?: string | null) =>
  value?.split("T")[0] ?? "";

const getTimePartFromDateTimeLocalValue = (value?: string | null) =>
  value?.split("T")[1]?.slice(0, 5) ?? "00:00";

const getHourPartFromDateTimeLocalValue = (value?: string | null) =>
  getTimePartFromDateTimeLocalValue(value).split(":")[0] ?? "00";

const getMinutePartFromDateTimeLocalValue = (value?: string | null) =>
  getTimePartFromDateTimeLocalValue(value).split(":")[1] ?? "00";

const mergeDateAndTimeParts = (datePart?: string | null, timePart?: string | null) => {
  if (!datePart) {
    return "";
  }

  return `${datePart}T${timePart || "00:00"}`;
};

const formatDateTimeLocalLabel = (value?: string | null) => {
  const parsed = parseDateTimeLocalValue(value);
  if (!parsed) {
    return "";
  }

  return parsed.toLocaleString("pl-PL", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const clampDateTimeLocalValue = (value: string, minValue?: string | null, maxValue?: string | null) => {
  if (!value) {
    return value;
  }

  if (minValue && value < minValue) {
    return minValue;
  }

  if (maxValue && value > maxValue) {
    return maxValue;
  }

  return value;
};

const MAX_HISTORY_RANGE_MS = 1000 * 60 * 60 * 48;

const getDefaultHistoryRangeValues = (
  minValue?: string | null,
  maxValue?: string | null,
  rangeMs = DEFAULT_HISTORY_RANGE_MS,
) => {
  const fallbackMaxTimestamp = Date.now();
  const maxTimestamp = maxValue
    ? getDateTimeLocalTimestamp(maxValue)
    : fallbackMaxTimestamp;
  const safeMaxTimestamp = Number.isNaN(maxTimestamp) ? fallbackMaxTimestamp : maxTimestamp;
  const minTimestamp = minValue
    ? getDateTimeLocalTimestamp(minValue)
    : Number.NaN;
  const safeMinTimestamp = Number.isNaN(minTimestamp)
    ? safeMaxTimestamp - rangeMs
    : minTimestamp;
  const nextFromTimestamp = Math.max(safeMinTimestamp, safeMaxTimestamp - rangeMs);

  return {
    from: toDateTimeLocalValue(new Date(nextFromTimestamp).toISOString()),
    to: toDateTimeLocalValue(new Date(safeMaxTimestamp).toISOString()),
  };
};
const selectedVehicleStorageKey = (userId: string) => `tracker.selectedVehicle.${userId}`;
const dailyOverviewStorageKey = (userId: string) => `tracker.dailyOverview.${userId}`;
const mapTileModeStorageKey = (userId: string) => `tracker.mapTileMode.${userId}`;

const getLocalDateKey = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const isNetworkLoadError = (error: unknown) => {
  if (!(error instanceof Error)) {
    return false;
  }

  const normalizedMessage = error.message.trim().toLowerCase();
  return (
    normalizedMessage === "load failed"
    || normalizedMessage === "failed to fetch"
    || normalizedMessage.includes("networkerror")
  );
};

const getFriendlyLoadErrorMessage = (error: unknown, fallback: string) => {
  if (isNetworkLoadError(error)) {
    return fallback;
  }

  if (error instanceof Error && error.message.trim()) {
    return error.message;
  }

  return fallback;
};

const getHeadingLabel = (heading?: number | null) => {
  if (heading == null || Number.isNaN(heading)) {
    return "N";
  }

  const normalized = ((heading % 360) + 360) % 360;
  const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
  return directions[Math.round(normalized / 45) % 8];
};

const getBearingBetweenPoints = (
  start: Pick<HistoryPoint, "lat" | "lon">,
  end: Pick<HistoryPoint, "lat" | "lon">,
) => {
  const toRad = (value: number) => (value * Math.PI) / 180;
  const toDeg = (value: number) => (value * 180) / Math.PI;
  const lat1 = toRad(start.lat);
  const lat2 = toRad(end.lat);
  const deltaLon = toRad(end.lon - start.lon);

  const y = Math.sin(deltaLon) * Math.cos(lat2);
  const x = Math.cos(lat1) * Math.sin(lat2)
    - Math.sin(lat1) * Math.cos(lat2) * Math.cos(deltaLon);

  return (toDeg(Math.atan2(y, x)) + 360) % 360;
};

const getPlaybackPosition = (
  stampedPoints: StampedHistoryPoint[],
  playbackTimestamp: number | null,
  playbackDirection: "forward" | "backward",
): PositionSnapshot | null => {
  if (stampedPoints.length === 0) {
    return null;
  }

  if (stampedPoints.length === 1 || playbackTimestamp == null) {
    return stampedPoints[stampedPoints.length - 1]?.point ?? null;
  }

  if (playbackTimestamp <= stampedPoints[0].timestamp) {
    const heading = playbackDirection === "backward"
      ? getBearingBetweenPoints(stampedPoints[1].point, stampedPoints[0].point)
      : getBearingBetweenPoints(stampedPoints[0].point, stampedPoints[1].point);
    return { ...stampedPoints[0].point, heading };
  }

  const lastStampedPoint = stampedPoints[stampedPoints.length - 1];
  if (playbackTimestamp >= lastStampedPoint.timestamp) {
    const previousStampedPoint = stampedPoints[stampedPoints.length - 2];
    const heading = playbackDirection === "backward"
      ? getBearingBetweenPoints(lastStampedPoint.point, previousStampedPoint.point)
      : getBearingBetweenPoints(previousStampedPoint.point, lastStampedPoint.point);
    return { ...lastStampedPoint.point, heading };
  }

  let low = 0;
  let high = stampedPoints.length - 2;
  while (low <= high) {
    const index = Math.floor((low + high) / 2);
    const current = stampedPoints[index];
    const next = stampedPoints[index + 1];

    if (playbackTimestamp < current.timestamp) {
      high = index - 1;
      continue;
    }
    if (playbackTimestamp > next.timestamp) {
      low = index + 1;
      continue;
    }

    const segmentDuration = next.timestamp - current.timestamp;
    const progress = segmentDuration === 0 ? 0 : (playbackTimestamp - current.timestamp) / segmentDuration;
    const lat = current.point.lat + (next.point.lat - current.point.lat) * progress;
    const lon = current.point.lon + (next.point.lon - current.point.lon) * progress;
    const heading = playbackDirection === "backward"
      ? getBearingBetweenPoints(next.point, current.point)
      : getBearingBetweenPoints(current.point, next.point);
    const referencePoint = progress < 0.5 ? current.point : next.point;

    return {
      ...referencePoint,
      lat,
      lon,
      heading,
      speed: current.point.speed != null && next.point.speed != null
        ? current.point.speed + (next.point.speed - current.point.speed) * progress
        : referencePoint.speed ?? null,
      serverTime: new Date(playbackTimestamp).toISOString(),
      deviceTime: new Date(playbackTimestamp).toISOString(),
    };
  }

  return lastStampedPoint.point;
};

const sortHistoryPoints = (points: HistoryPoint[]) => {
  const sortedPoints = points
    .slice()
    .sort((left, right) => {
      const leftTimestamp = getPointTimeMs(left) ?? 0;
      const rightTimestamp = getPointTimeMs(right) ?? 0;

      if (leftTimestamp !== rightTimestamp) {
        return leftTimestamp - rightTimestamp;
      }

      return left.id - right.id;
    });

  const deduplicatedPoints: HistoryPoint[] = [];
  for (const point of sortedPoints) {
    const pointTimestamp = getPointTimeMs(point);
    const previousPoint = deduplicatedPoints[deduplicatedPoints.length - 1];
    const previousTimestamp = previousPoint ? getPointTimeMs(previousPoint) : null;

    if (pointTimestamp != null && previousTimestamp != null && pointTimestamp === previousTimestamp) {
      deduplicatedPoints[deduplicatedPoints.length - 1] = point;
      continue;
    }

    deduplicatedPoints.push(point);
  }

  return deduplicatedPoints;
};

const getTimelineStartTimestamp = (points: HistoryPoint[], fromIso: string) => {
  if (points.length === 0) {
    return null;
  }

  const firstPointTimestamp = getPointTimeMs(points[0]) ?? null;
  const fromTimestamp = new Date(fromIso).getTime();

  if (firstPointTimestamp == null) {
    return Number.isNaN(fromTimestamp) ? null : fromTimestamp;
  }

  if (Number.isNaN(fromTimestamp)) {
    return firstPointTimestamp;
  }

  return Math.max(firstPointTimestamp, fromTimestamp);
};

const getPlaybackStartTimestamp = (
  points: HistoryPoint[],
  fromIso: string,
  direction: "forward" | "backward",
  skipStops: boolean,
) => {
  const baseTimestamp = direction === "backward"
    ? (getPointTimeMs(points[points.length - 1]) ?? null)
    : getTimelineStartTimestamp(points, fromIso);

  if (!skipStops || baseTimestamp == null) {
    return baseTimestamp;
  }

  return findIgnitionResumeTimestamp(points, baseTimestamp, direction) ?? baseTimestamp;
};

const getStampedHistoryPoints = (points: HistoryPoint[]) =>
  points
    .map((point) => ({
      point,
      timestamp: getPointTimeMs(point),
    }))
    .filter((entry): entry is StampedHistoryPoint => entry.timestamp != null);

const isStoppedHistoryPoint = (point?: Pick<HistoryPoint, "ignition"> | null) =>
  point?.ignition === false;

const findIgnitionResumeTimestamp = (
  points: HistoryPoint[],
  targetTimestamp: number,
  direction: "forward" | "backward",
) => {
  const stampedPoints = getStampedHistoryPoints(points);
  if (stampedPoints.length === 0) {
    return targetTimestamp;
  }

  let currentIndex = 0;
  for (let index = 1; index < stampedPoints.length; index += 1) {
    if (stampedPoints[index].timestamp > targetTimestamp) {
      break;
    }
    currentIndex = index;
  }

  const currentPoint = stampedPoints[currentIndex]?.point;
  if (!isStoppedHistoryPoint(currentPoint)) {
    return targetTimestamp;
  }

  if (direction === "forward") {
    for (let index = currentIndex + 1; index < stampedPoints.length; index += 1) {
      if (stampedPoints[index].point.ignition === true) {
        return stampedPoints[index].timestamp;
      }
    }
    return null;
  }

  for (let index = currentIndex - 1; index >= 0; index -= 1) {
    if (stampedPoints[index].point.ignition === true) {
      return stampedPoints[index].timestamp;
    }
  }

  return null;
};

const getStoppedSegmentPreview = (
  stampedPoints: StampedHistoryPoint[],
  targetTimestamp: number,
  direction: "forward" | "backward",
) => {
  if (stampedPoints.length === 0) {
    return null;
  }

  let currentIndex = 0;
  for (let index = 1; index < stampedPoints.length; index += 1) {
    if (stampedPoints[index].timestamp > targetTimestamp) {
      break;
    }
    currentIndex = index;
  }

  if (!isStoppedHistoryPoint(stampedPoints[currentIndex]?.point)) {
    return null;
  }

  if (direction === "forward") {
    let holdIndex = currentIndex;
    while (holdIndex > 0 && isStoppedHistoryPoint(stampedPoints[holdIndex - 1]?.point)) {
      holdIndex -= 1;
    }

    let resumeTimestamp: number | null = null;
    for (let index = currentIndex + 1; index < stampedPoints.length; index += 1) {
      if (stampedPoints[index].point.ignition === true) {
        resumeTimestamp = stampedPoints[index].timestamp;
        break;
      }
    }

    return {
      holdTimestamp: stampedPoints[holdIndex].timestamp,
      resumeTimestamp,
    };
  }

  let holdIndex = currentIndex;
  while (
    holdIndex < stampedPoints.length - 1
    && isStoppedHistoryPoint(stampedPoints[holdIndex + 1]?.point)
  ) {
    holdIndex += 1;
  }

  let resumeTimestamp: number | null = null;
  for (let index = currentIndex - 1; index >= 0; index -= 1) {
    if (stampedPoints[index].point.ignition === true) {
      resumeTimestamp = stampedPoints[index].timestamp;
      break;
    }
  }

  return {
    holdTimestamp: stampedPoints[holdIndex].timestamp,
    resumeTimestamp,
  };
};

const distanceMeters = (
  start: { lat: number; lon: number },
  end: { lat: number; lon: number },
) => {
  const toRad = (value: number) => (value * Math.PI) / 180;
  const earthRadius = 6_371_000;
  const dLat = toRad(end.lat - start.lat);
  const dLon = toRad(end.lon - start.lon);
  const lat1 = toRad(start.lat);
  const lat2 = toRad(end.lat);
  const haversine = Math.sin(dLat / 2) ** 2
    + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;

  return 2 * earthRadius * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine));
};

const getAddressReachedTimestamp = (
  stampedPoints: StampedHistoryPoint[],
  currentPoint?: PositionSnapshot | null,
  thresholdMeters = 50,
) => {
  if (!currentPoint) {
    return null;
  }

  const currentTimestamp = getPointTimeMs(currentPoint);
  if (currentTimestamp == null) {
    return null;
  }

  if (stampedPoints.length === 0) {
    return currentTimestamp;
  }

  let reachedAt = currentTimestamp;

  for (let index = stampedPoints.length - 1; index >= 0; index -= 1) {
    const candidate = stampedPoints[index];

    if (candidate.timestamp > currentTimestamp) {
      continue;
    }

    if (
      distanceMeters(
        { lat: candidate.point.lat, lon: candidate.point.lon },
        { lat: currentPoint.lat, lon: currentPoint.lon },
      ) > thresholdMeters
    ) {
      break;
    }

    reachedAt = candidate.timestamp;
  }

  return reachedAt;
};

export default function DashboardPage() {
  const router = useRouter();
  const [isDocumentVisible, setIsDocumentVisible] = useState(true);
  const [isSocketConnected, setIsSocketConnected] = useState(false);
  const [token, setToken] = useState<string | null>(null);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  const [currentUserEmail, setCurrentUserEmail] = useState<string | null>(null);
  const [currentUserFirstName, setCurrentUserFirstName] = useState<string | null>(null);
  const [currentUserLastName, setCurrentUserLastName] = useState<string | null>(null);
  const [userRole, setUserRole] = useState<"admin" | "user">("user");
  const [canEditVehicleInspection, setCanEditVehicleInspection] = useState(false);
  const [canViewStats, setCanViewStats] = useState(false);
  const [vehicles, setVehicles] = useState<VehicleSummary[]>([]);
  const [mapViewportBounds, setMapViewportBounds] = useState<{
    south: number;
    west: number;
    north: number;
    east: number;
  } | null>(null);
  const [selectedVehicleId, setSelectedVehicleId] = useState<string | null>(null);
  const [vehicleFocusNonce, setVehicleFocusNonce] = useState(0);
  const [suppressVehicleAutoCenter, setSuppressVehicleAutoCenter] = useState<{
    vehicleId: string | null;
    until: number;
  }>({
    vehicleId: null,
    until: 0,
  });
  const [historyFocusNonce, setHistoryFocusNonce] = useState(0);
  const [dailyOverviewKey, setDailyOverviewKey] = useState<string | null>(null);
  const [overviewMode, setOverviewMode] = useState<"all" | "warsaw" | "company" | null>(null);
  const [mapTileMode, setMapTileMode] = useState<"standard" | "satellite">("standard");
  const [history, setHistory] = useState<HistoryPoint[]>([]);
  const [playbackTimestamp, setPlaybackTimestamp] = useState<number | null>(null);
  const [playbackDirection, setPlaybackDirection] = useState<"forward" | "backward">("forward");
  const [isPlaybackRunning, setIsPlaybackRunning] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState<2 | 5 | 10 | 50>(2);
  const [skipStopsDuringPlayback, setSkipStopsDuringPlayback] = useState(true);
  const [selectedPositionAddress, setSelectedPositionAddress] = useState<string | null>(null);
  const [selectedPositionAddressLoading, setSelectedPositionAddressLoading] = useState(false);
  const selectedPositionAddressKeyRef = useRef<string | null>(null);
  const [addressLookupNonce, setAddressLookupNonce] = useState(0);
  const selectedVehicleAddressCacheRef = useRef<
    Record<string, Partial<Record<SelectedVehicleAddressMode, SelectedVehicleAddressCacheEntry>>>
  >({});
  const globalAddressCacheRef = useRef<Map<string, string>>(new Map());
  const selectedVehicleIgnitionRef = useRef<{ vehicleId: string | null; ignition: boolean | null }>({
    vehicleId: null,
    ignition: null,
  });
  const [isTimelineVisible, setIsTimelineVisible] = useState(false);
  const [isTimelineActivated, setIsTimelineActivated] = useState(false);
  const [alertPlaybackRange, setAlertPlaybackRange] = useState<{
    vehicleId: string;
    from: number;
    to: number;
  } | null>(null);
  const [pendingAlertPlayback, setPendingAlertPlayback] = useState<{
    vehicleId: string;
    from: string;
    to: string;
    fetchFromIso: string;
    fetchToIso: string;
    fromTimestamp: number;
    toTimestamp: number;
  } | null>(null);
  const [selectedPositionDetailsEnabled, setSelectedPositionDetailsEnabled] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [adminMessage, setAdminMessage] = useState<string | null>(null);
  const [vehicleSuccessMessage, setVehicleSuccessMessage] = useState<string | null>(null);
  const [from, setFrom] = useState(() => toDateTimeLocalValue(new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString()));
  const [to, setTo] = useState(() => toDateTimeLocalValue(new Date().toISOString()));
  const [vehicleName, setVehicleName] = useState("");
  const [vehiclePlateNumber, setVehiclePlateNumber] = useState("");
  const [vehicleColorKey, setVehicleColorKey] = useState<VehicleColorKey>(DEFAULT_VEHICLE_COLOR_KEY);
  const [vehicleKind, setVehicleKind] = useState<VehicleKind>("passenger");
  const [deviceImei, setDeviceImei] = useState("");
  const [devicePhoneNumber, setDevicePhoneNumber] = useState("");
  const [deviceVehicleId, setDeviceVehicleId] = useState("");
  const [activeAlerts, setActiveAlerts] = useState<VehicleAlertSummary[]>([]);
  const [recentAlerts, setRecentAlerts] = useState<VehicleAlertSummary[]>([]);
  const [systemUsers, setSystemUsers] = useState<AdminUserSummary[]>([]);
  const [systemDevices, setSystemDevices] = useState<AdminDeviceSummary[]>([]);
  const [companySettings, setCompanySettings] = useState<CompanySettingsSummary>(null);
  const [companyAddressInput, setCompanyAddressInput] = useState("");
  const [companyRouteSummary, setCompanyRouteSummary] = useState<CompanyRouteSummary | null>(null);
  const [vehicleStatsOverview, setVehicleStatsOverview] = useState<VehicleStatsOverview | null>(null);
  const [vehicleStatsError, setVehicleStatsError] = useState<string | null>(null);
  const [isStatsPanelOpen, setIsStatsPanelOpen] = useState(false);
  const [isAlertsListOpen, setIsAlertsListOpen] = useState(false);
  const [isRecentTripsOpen, setIsRecentTripsOpen] = useState(false);
  const [recentTrips, setRecentTrips] = useState<VehicleTripSummary[]>([]);
  const [recentTripsError, setRecentTripsError] = useState<string | null>(null);
  const [isRecentTripsLoading, setIsRecentTripsLoading] = useState(false);
  const [isRecentTripsLoadingMore, setIsRecentTripsLoadingMore] = useState(false);
  const [recentTripsHasMore, setRecentTripsHasMore] = useState(false);
  const [recentTripsNextBefore, setRecentTripsNextBefore] = useState<string | null>(null);
  const [recentTripsCanScrollUp, setRecentTripsCanScrollUp] = useState(false);
  const [recentTripsCanScrollDown, setRecentTripsCanScrollDown] = useState(false);
  const recentTripsScrollRef = useRef<HTMLDivElement | null>(null);
  const recentTripsPendingBottomRetryRef = useRef(false);
  const [isSendingTestEmail, setIsSendingTestEmail] = useState(false);
  const [companySettingsMessage, setCompanySettingsMessage] = useState<string | null>(null);
  const [inspectionEmailSettings, setInspectionEmailSettings] = useState<InspectionEmailSettingsSummary | null>(null);
  const [inspectionEmailRecipientsInput, setInspectionEmailRecipientsInput] = useState("");
  const [inspectionEmailSettingsMessage, setInspectionEmailSettingsMessage] = useState<string | null>(null);
  const [deviceVehicleAssignments, setDeviceVehicleAssignments] = useState<Record<string, string>>({});
  const [isSystemSettingsOpen, setIsSystemSettingsOpen] = useState(false);
  const [systemSettingsTab, setSystemSettingsTab] = useState<"users" | "vehicles" | "devices" | "company" | "inspectionEmail">("users");
  const [isInfoPanelOpen, setIsInfoPanelOpen] = useState(false);
  const [isDetailsPanelOpen, setIsDetailsPanelOpen] = useState(true);
  const [isMobileViewport, setIsMobileViewport] = useState(false);
  const [isMobileLiveOpen, setIsMobileLiveOpen] = useState(false);
  const [isMobileHistoryOpen, setIsMobileHistoryOpen] = useState(false);
  const [isMobileGpsOpen, setIsMobileGpsOpen] = useState(false);
  const [isCompanyVehiclesOpen, setIsCompanyVehiclesOpen] = useState(false);
  const [isMovingVehiclesOpen, setIsMovingVehiclesOpen] = useState(false);
  const [isHeaderPanelOpen, setIsHeaderPanelOpen] = useState(true);
  const [isHeaderPanelHovered, setIsHeaderPanelHovered] = useState(false);
  const [isSelectedVehicleMenuOpen, setIsSelectedVehicleMenuOpen] = useState(false);
  const [openDesktopHistoryPicker, setOpenDesktopHistoryPicker] = useState<"from" | "to" | null>(null);
  const [desktopHistoryFocusTarget, setDesktopHistoryFocusTarget] = useState<"date" | "time" | null>(null);
  const [newUserEmail, setNewUserEmail] = useState("");
  const [newUserFirstName, setNewUserFirstName] = useState("");
  const [newUserLastName, setNewUserLastName] = useState("");
  const [newUserPassword, setNewUserPassword] = useState("");
  const [newUserRole, setNewUserRole] = useState<"admin" | "user">("user");
  const [newUserCanEditVehicleInspection, setNewUserCanEditVehicleInspection] = useState(false);
  const [newUserCanViewStats, setNewUserCanViewStats] = useState(false);
  const [newUserVehicleIds, setNewUserVehicleIds] = useState<string[]>([]);
  const [savedUserId, setSavedUserId] = useState<string | null>(null);
  const [isVehicleFormOpen, setIsVehicleFormOpen] = useState(false);
  const [isDeviceFormOpen, setIsDeviceFormOpen] = useState(false);
  const [isEditVehicleFormOpen, setIsEditVehicleFormOpen] = useState(false);
  const [editVehicleName, setEditVehicleName] = useState("");
  const [editVehiclePlateNumber, setEditVehiclePlateNumber] = useState("");
  const [editVehicleColorKey, setEditVehicleColorKey] = useState<VehicleColorKey>(DEFAULT_VEHICLE_COLOR_KEY);
  const [editVehicleKind, setEditVehicleKind] = useState<VehicleKind>("passenger");
  const [editVehicleInspectionDueDate, setEditVehicleInspectionDueDate] = useState("");
  const [editVehicleOilChangeDueDate, setEditVehicleOilChangeDueDate] = useState("");
  const [editVehicleOilChangeOdometer, setEditVehicleOilChangeOdometer] = useState("");
  const [editVehicleOilChangeIntervalKm, setEditVehicleOilChangeIntervalKm] = useState("");
  const [editVehicleTireChangedAt, setEditVehicleTireChangedAt] = useState("");
  const [editVehicleNextTireChangeDueDate, setEditVehicleNextTireChangeDueDate] = useState("");
  const [editAssignedDeviceId, setEditAssignedDeviceId] = useState("");
  const [editDeviceImei, setEditDeviceImei] = useState("");
  const [editDevicePhoneNumber, setEditDevicePhoneNumber] = useState("");
  const editVehicleOverlayPanelRef = useRef<HTMLDivElement | null>(null);
  const defaultHistoryRangeRef = useRef<{
    vehicleId: string;
    from: string;
    to: string;
  } | null>(null);
  const historyRequestKeyRef = useRef<string | null>(null);
  const companyRouteKeyRef = useRef<string | null>(null);
  const companyRouteRequestRef = useRef<{ lat: number; lon: number; requestedAt: number } | null>(null);
  const companyRouteAbortRef = useRef<AbortController | null>(null);
  const liveSeedRequestKeyRef = useRef<string | null>(null);
  const hasHydratedSelectedVehicleRef = useRef(false);
  const playbackFrameRef = useRef<number | null>(null);
  const playbackLastTickRef = useRef<number | null>(null);
  const playbackLastRenderAtRef = useRef<number | null>(null);
  const playbackStoppedPreviewRef = useRef<{
    holdTimestamp: number;
    previewStartedAt: number;
    resumeTimestamp: number | null;
  } | null>(null);
  const headerAutoCollapseTimeoutRef = useRef<number | null>(null);
  const selectedVehicleMenuRef = useRef<HTMLDivElement | null>(null);
  const pendingTelemetryUpdatesRef = useRef<
    Map<
      string,
      {
        status: VehicleSummary["status"];
        telemetry: {
          lat: number;
          lon: number;
          speed?: number | null;
          heading?: number | null;
          deviceTime?: string | null;
          serverTime: string;
          ignition?: boolean | null;
          battery?: number | null;
          gsmSignal?: number | null;
          satelliteCount?: number | null;
          gpsValid?: boolean | null;
          charging?: boolean | null;
          defense?: boolean | null;
          positionType?: string | null;
        };
      }
    >
  >(new Map());
  const telemetryFlushTimeoutRef = useRef<number | null>(null);
  const dashboardRefreshInFlightRef = useRef<Promise<void> | null>(null);
  const liveInterpolationSegmentsRef = useRef<Map<string, LiveInterpolationSegment>>(new Map());
  const [animatedVehiclePosition, setAnimatedVehiclePosition] = useState<PositionSnapshot | null>(null);
  const displayVehicles = useMemo(
    () => vehicles.map((vehicle) =>
      isEditVehicleFormOpen && vehicle.id === selectedVehicleId
        ? {
            ...vehicle,
            colorKey: editVehicleColorKey,
          }
        : vehicle,
    ),
    [editVehicleColorKey, isEditVehicleFormOpen, selectedVehicleId, vehicles],
  );
  const warsawVehicleIds = useMemo(
    () => displayVehicles.filter((vehicle) => isVehicleInWarsaw(vehicle)).map((vehicle) => vehicle.id),
    [displayVehicles],
  );
  const offlineVehicles = useMemo(
    () => displayVehicles.filter((vehicle) => vehicle.status === "offline"),
    [displayVehicles],
  );
  const offlineAlertVehicles = useMemo(
    () => offlineVehicles.filter((vehicle) => {
      if (!vehicle.lastSeen) {
        return true;
      }

      const lastSeenTimestamp = new Date(vehicle.lastSeen).getTime();
      if (Number.isNaN(lastSeenTimestamp)) {
        return true;
      }

      return Date.now() - lastSeenTimestamp >= OFFLINE_ALERT_THRESHOLD_MS;
    }),
    [offlineVehicles],
  );
  const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
  const shiftHex = (hex: string, amount: number) => {
    const normalized = hex.replace("#", "");
    const safeHex = normalized.length === 6 ? normalized : "4068F8";
    const [r, g, b] = [0, 2, 4].map((offset) => Number.parseInt(safeHex.slice(offset, offset + 2), 16));
    const shifted = [r, g, b]
      .map((channel) => clamp(channel + amount, 0, 255).toString(16).padStart(2, "0"))
      .join("");

    return `#${shifted}`;
  };
  const previewVehicleColor = getVehicleColorHex(editVehicleColorKey);
  const currentUserDisplayName = [currentUserFirstName, currentUserLastName].filter(Boolean).join(" ").trim();
  const currentUserPrimaryName = currentUserFirstName?.trim() || currentUserDisplayName || currentUserEmail || "Użytkownik";
  const canManageVehicleInspection = userRole === "admin" || canEditVehicleInspection;
  const canAccessStats = userRole === "admin" || canViewStats;
  const hasInfoAttention = offlineAlertVehicles.length > 0 || activeAlerts.length > 0;
  const activeMobileSection = isMobileLiveOpen
    ? "live"
    : isMobileHistoryOpen
      ? "history"
      : isMobileGpsOpen
        ? "gps"
        : null;
  const isMobileTimelineMode = isMobileViewport
    && activeMobileSection === "history"
    && isTimelineVisible;
  const handleVehicleSelection = useCallback((
    vehicleId: string | null,
    options?: { focusMap?: boolean },
  ) => {
    const isSameVehicle = vehicleId != null && vehicleId === selectedVehicleId;
    const selectedFromHeaderList = isMovingVehiclesOpen || isCompanyVehiclesOpen;
    const shouldFocusMap = options?.focusMap !== false;
    setDailyOverviewKey(null);
    setOverviewMode(null);
    setIsSelectedVehicleMenuOpen(false);
    setIsMovingVehiclesOpen(false);
    setIsCompanyVehiclesOpen(false);
    setIsDetailsPanelOpen(true);
    if (selectedFromHeaderList) {
      setIsHeaderPanelOpen(false);
    }

    if (isSameVehicle) {
      return;
    }

    historyRequestKeyRef.current = null;
    setHistory([]);
    setIsPlaybackRunning(false);
    setPlaybackTimestamp(null);
    setPlaybackDirection("forward");
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setAlertPlaybackRange(null);
    setSelectedPositionDetailsEnabled(false);
    setSelectedPositionAddress(null);
    setSelectedPositionAddressLoading(false);
    setCompanyRouteSummary(null);
    selectedPositionAddressKeyRef.current = null;
    companyRouteKeyRef.current = null;
    setSelectedVehicleId(vehicleId);
    setSuppressVehicleAutoCenter(
      vehicleId && !shouldFocusMap
        ? { vehicleId, until: Date.now() + 1500 }
        : { vehicleId: null, until: 0 },
    );
    if (vehicleId && shouldFocusMap) {
      setVehicleFocusNonce((current) => current + 1);
    }
    if (vehicleId) {
      setAddressLookupNonce((current) => current + 1);
    }
  }, [isCompanyVehiclesOpen, isMovingVehiclesOpen, selectedVehicleId]);
  const handleShowAllVehicles = useCallback(() => {
    setOverviewMode("all");
    setSelectedVehicleId(null);
    setHistory([]);
    setIsPlaybackRunning(false);
    setPlaybackTimestamp(null);
    setPlaybackDirection("forward");
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setAlertPlaybackRange(null);
    setIsSelectedVehicleMenuOpen(false);
    setIsMovingVehiclesOpen(false);
    setIsCompanyVehiclesOpen(false);
    setDailyOverviewKey(`manual:${Date.now()}`);
  }, []);
  const handleShowWarsawVehicles = useCallback(() => {
    setOverviewMode("warsaw");
    setSelectedVehicleId(null);
    setHistory([]);
    setIsPlaybackRunning(false);
    setPlaybackTimestamp(null);
    setPlaybackDirection("forward");
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setAlertPlaybackRange(null);
    setIsSelectedVehicleMenuOpen(false);
    setIsMovingVehiclesOpen(false);
    setIsCompanyVehiclesOpen(false);
    setDailyOverviewKey(`warsaw:${Date.now()}`);
  }, []);
  const handleShowCompanyOverview = useCallback(() => {
    if (!companySettings) {
      return;
    }

    setOverviewMode("company");
    setSelectedVehicleId(null);
    setHistory([]);
    setIsPlaybackRunning(false);
    setPlaybackTimestamp(null);
    setPlaybackDirection("forward");
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setAlertPlaybackRange(null);
    setIsSelectedVehicleMenuOpen(false);
    setIsMovingVehiclesOpen(false);
    setIsCompanyVehiclesOpen(false);
    setDailyOverviewKey(`company:${Date.now()}`);
  }, [companySettings]);
  const toggleMobileSection = (section: "live" | "history" | "gps") => {
    const isCurrentlyOpen =
      (section === "live" && isMobileLiveOpen)
      || (section === "history" && isMobileHistoryOpen)
      || (section === "gps" && isMobileGpsOpen);

    setIsMobileLiveOpen(section === "live" ? !isCurrentlyOpen : false);
    setIsMobileHistoryOpen(section === "history" ? !isCurrentlyOpen : false);
    setIsMobileGpsOpen(section === "gps" ? !isCurrentlyOpen : false);
  };

  const toggleMovingVehiclesPanel = () => {
    setIsMovingVehiclesOpen((current) => {
      const next = !current;
      if (next) {
        setIsCompanyVehiclesOpen(false);
      }
      return next;
    });
  };

  const toggleCompanyVehiclesPanel = () => {
    setIsCompanyVehiclesOpen((current) => {
      const next = !current;
      if (next) {
        setIsMovingVehiclesOpen(false);
      }
      return next;
    });
  };

  useEffect(() => {
    if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
      return;
    }

    const mediaQuery = window.matchMedia("(max-width: 767px)");
    const updateViewportMode = () => {
      setIsMobileViewport(mediaQuery.matches);
    };

    updateViewportMode();
    if (typeof mediaQuery.addEventListener === "function") {
      mediaQuery.addEventListener("change", updateViewportMode);
      return () => mediaQuery.removeEventListener("change", updateViewportMode);
    }

    mediaQuery.addListener(updateViewportMode);
    return () => mediaQuery.removeListener(updateViewportMode);
  }, []);

  useEffect(() => {
    const isPointInViewport = (lat: number, lon: number) => {
      if (!mapViewportBounds) {
        return true;
      }

      return lat >= mapViewportBounds.south
        && lat <= mapViewportBounds.north
        && lon >= mapViewportBounds.west
        && lon <= mapViewportBounds.east;
    };

    if (!selectedVehicleId) {
      setAnimatedVehiclePosition(null);
      return;
    }

    const selectedVehicle = displayVehicles.find((vehicle) => vehicle.id === selectedVehicleId) ?? null;
    const point = selectedVehicle?.lastPosition ?? null;

    if (!selectedVehicle || !point || !isDocumentVisible) {
      setAnimatedVehiclePosition(null);
      return;
    }

    const buildInterpolatedPosition = (nowMs: number) => {
      const segment = liveInterpolationSegmentsRef.current.get(selectedVehicleId);
      if (!segment || !isPointInViewport(point.lat, point.lon)) {
        return null;
      }

      const elapsedMs = Math.max(0, nowMs - segment.startedAtMs);
      const progress = clamp(elapsedMs / segment.durationMs, 0, 1);
      const nextPosition = interpolateLivePosition(segment.from, segment.to, progress);

      if (progress >= 1) {
        liveInterpolationSegmentsRef.current.delete(selectedVehicleId);
      }

      const speedKmh = clamp(nextPosition.speed ?? 0, 0, LIVE_INTERPOLATION_MAX_SPEED_KMH);
      const ignitionOn = selectedVehicle.deviceState?.ignition === true || nextPosition.ignition === true;
      const canInterpolate = Boolean(
        ignitionOn
          && speedKmh >= LIVE_PREDICTION_MIN_SPEED_KMH
          && nextPosition.gpsValid !== false
          && Number.isFinite(nextPosition.lat)
          && Number.isFinite(nextPosition.lon),
      );

      return canInterpolate ? nextPosition : null;
    };

    const applyInterpolation = () => {
      const nextPosition = buildInterpolatedPosition(Date.now());
      setAnimatedVehiclePosition(nextPosition);
      return nextPosition != null;
    };

    const hasInitialAnimation = applyInterpolation();
    if (!hasInitialAnimation) {
      return;
    }

    const intervalId = window.setInterval(() => {
      const stillAnimating = applyInterpolation();
      if (!stillAnimating) {
        window.clearInterval(intervalId);
      }
    }, LIVE_PREDICTION_INTERVAL_MS);

    return () => window.clearInterval(intervalId);
  }, [displayVehicles, isDocumentVisible, mapViewportBounds, selectedVehicleId]);

  useEffect(() => {
    document.documentElement.classList.add("dashboard-page");
    document.body.classList.add("dashboard-page");

    return () => {
      document.documentElement.classList.remove("dashboard-page");
      document.body.classList.remove("dashboard-page");
    };
  }, []);

  useEffect(() => {
    if (!isSelectedVehicleMenuOpen) {
      return;
    }

    const handlePointerDown = (event: MouseEvent | TouchEvent) => {
      const target = event.target as Node | null;
      if (selectedVehicleMenuRef.current && target && !selectedVehicleMenuRef.current.contains(target)) {
        setIsSelectedVehicleMenuOpen(false);
      }
    };

    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("touchstart", handlePointerDown, { passive: true });

    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("touchstart", handlePointerDown);
    };
  }, [isSelectedVehicleMenuOpen]);

  useEffect(() => {
    if (!isVehicleFormOpen && !isDeviceFormOpen && !isEditVehicleFormOpen && !isSystemSettingsOpen && !isAlertsListOpen) {
      return;
    }

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsVehicleFormOpen(false);
        setIsDeviceFormOpen(false);
        setIsEditVehicleFormOpen(false);
        setIsSystemSettingsOpen(false);
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [isAlertsListOpen, isDeviceFormOpen, isEditVehicleFormOpen, isSystemSettingsOpen, isVehicleFormOpen]);

  useEffect(() => {
    if (!isEditVehicleFormOpen || !editVehicleOverlayPanelRef.current) {
      return;
    }

    const panel = editVehicleOverlayPanelRef.current;
    const preventZoomGesture = (event: Event) => {
      event.preventDefault();
    };
    const preventPinchTouch = (event: TouchEvent) => {
      if (event.touches.length > 1) {
        event.preventDefault();
      }
    };
    const preventCtrlWheelZoom = (event: WheelEvent) => {
      if (event.ctrlKey) {
        event.preventDefault();
      }
    };

    panel.addEventListener("gesturestart", preventZoomGesture, { passive: false });
    panel.addEventListener("gesturechange", preventZoomGesture, { passive: false });
    panel.addEventListener("gestureend", preventZoomGesture, { passive: false });
    panel.addEventListener("touchmove", preventPinchTouch, { passive: false });
    panel.addEventListener("wheel", preventCtrlWheelZoom, { passive: false });

    return () => {
      panel.removeEventListener("gesturestart", preventZoomGesture);
      panel.removeEventListener("gesturechange", preventZoomGesture);
      panel.removeEventListener("gestureend", preventZoomGesture);
      panel.removeEventListener("touchmove", preventPinchTouch);
      panel.removeEventListener("wheel", preventCtrlWheelZoom);
    };
  }, [isEditVehicleFormOpen]);

  useEffect(() => {
    if (typeof document === "undefined") {
      return;
    }

    const syncVisibility = () => {
      setIsDocumentVisible(document.visibilityState !== "hidden");
    };

    syncVisibility();
    document.addEventListener("visibilitychange", syncVisibility);
    return () => document.removeEventListener("visibilitychange", syncVisibility);
  }, []);

  useEffect(() => {
    if (headerAutoCollapseTimeoutRef.current != null) {
      window.clearTimeout(headerAutoCollapseTimeoutRef.current);
      headerAutoCollapseTimeoutRef.current = null;
    }

    if (!isHeaderPanelOpen || isHeaderPanelHovered) {
      return;
    }

    headerAutoCollapseTimeoutRef.current = window.setTimeout(() => {
      setIsHeaderPanelOpen(false);
      headerAutoCollapseTimeoutRef.current = null;
    }, 3000);

    return () => {
      if (headerAutoCollapseTimeoutRef.current != null) {
        window.clearTimeout(headerAutoCollapseTimeoutRef.current);
        headerAutoCollapseTimeoutRef.current = null;
      }
    };
  }, [isHeaderPanelHovered, isHeaderPanelOpen]);

  useEffect(() => {
    if (typeof document === "undefined") {
      return;
    }

    const enableLowPowerSafariMode = isSafariBrowser();
    document.documentElement.classList.toggle("safari-low-power", enableLowPowerSafariMode);
    document.body.classList.toggle("safari-low-power", enableLowPowerSafariMode);

    return () => {
      document.documentElement.classList.remove("safari-low-power");
      document.body.classList.remove("safari-low-power");
    };
  }, []);

  useEffect(() => {
    if (!savedUserId) {
      return;
    }

    const timeoutId = window.setTimeout(() => {
      setSavedUserId(null);
    }, 3000);

    return () => window.clearTimeout(timeoutId);
  }, [savedUserId]);

  useEffect(() => {
    if (!companySettingsMessage) {
      return;
    }

    const timeoutId = window.setTimeout(() => {
      setCompanySettingsMessage(null);
    }, 5000);

    return () => window.clearTimeout(timeoutId);
  }, [companySettingsMessage]);

  useEffect(() => {
    if (!vehicleSuccessMessage) {
      return;
    }

    const timeoutId = window.setTimeout(() => {
      setVehicleSuccessMessage(null);
    }, 5000);

    return () => window.clearTimeout(timeoutId);
  }, [vehicleSuccessMessage]);

  useEffect(() => {
    setDeviceVehicleAssignments(
      Object.fromEntries(systemDevices.map((device) => [device.id, device.vehicle_id ?? ""])),
    );
  }, [systemDevices]);

  useEffect(() => {
    if (!isVehicleFormOpen && !isDeviceFormOpen && !isEditVehicleFormOpen && !isSystemSettingsOpen) {
      return;
    }

    const previousBodyOverflow = document.body.style.overflow;
    const previousHtmlOverflow = document.documentElement.style.overflow;
    document.body.style.overflow = "hidden";
    document.documentElement.style.overflow = "hidden";

    return () => {
      document.body.style.overflow = previousBodyOverflow;
      document.documentElement.style.overflow = previousHtmlOverflow;
    };
  }, [isDeviceFormOpen, isEditVehicleFormOpen, isSystemSettingsOpen, isVehicleFormOpen]);

  const formatDateTime = (value?: string | null) => {
    if (!value) {
      return "Brak";
    }

    const date = new Date(value);
    if (Number.isNaN(date.getTime())) {
      return value;
    }

    return new Intl.DateTimeFormat("pl-PL", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    }).format(date);
  };

  const formatToggle = (value?: boolean | null, onLabel = "On", offLabel = "Off") => {
    if (value == null) {
      return "Brak";
    }
    return value ? onLabel : offLabel;
  };

  const formatDistanceKm = (value?: number | null) => {
    if (value == null || !Number.isFinite(value)) {
      return "Brak";
    }

    const decimals = value >= 100 ? 0 : 1;
    return `${value.toFixed(decimals).replace(".", ",")} km`;
  };

  const formatMileageKm = (value?: number | null) => {
    if (value == null || !Number.isFinite(value)) {
      return "Brak";
    }

    return `${Math.round(value).toLocaleString("pl-PL")} km`;
  };

  const formatDurationMinutes = (value?: number | null) => {
    if (value == null || !Number.isFinite(value)) {
      return "Brak";
    }

    const roundedMinutes = Math.max(1, Math.round(value));
    if (roundedMinutes < 60) {
      return `${roundedMinutes} min`;
    }

    const hours = Math.floor(roundedMinutes / 60);
    const minutes = roundedMinutes % 60;
    return minutes > 0 ? `${hours} h ${minutes} min` : `${hours} h`;
  };

  const formatArrivalTime = (value?: number | null) => {
    if (value == null || !Number.isFinite(value)) {
      return "Brak";
    }

    const arrivalDate = new Date(Date.now() + Math.max(0, value) * 60 * 1000);
    return new Intl.DateTimeFormat("pl-PL", {
      hour: "2-digit",
      minute: "2-digit",
    }).format(arrivalDate);
  };

  const normalizePhoneNumber = (value?: string | null) => {
    const trimmed = (value ?? "").trim();
    if (!trimmed) {
      return null;
    }

    const hasLeadingPlus = trimmed.startsWith("+");
    const digits = trimmed.replace(/\D+/g, "");
    if (!digits) {
      return null;
    }

    if (hasLeadingPlus) {
      return `+${digits}`;
    }

    const firstThreeDigits = digits.slice(0, 3);
    if (firstThreeDigits.includes("48")) {
      if (digits.startsWith("048")) {
        return `+${digits.slice(1)}`;
      }
      if (digits.startsWith("48")) {
        return `+${digits}`;
      }
      return `+${digits}`;
    }

    return `+48${digits}`;
  };

  const handleFromDateTimeChange = (rawValue: string) => {
    const nextValue = clampDateTimeLocalValue(rawValue, historyMinInput, historyMaxInput);
    setFrom(nextValue);
  };

  const handleToDateTimeChange = (rawValue: string) => {
    const nextValue = clampDateTimeLocalValue(rawValue, historyMinInput, historyMaxInput);
    setTo(nextValue);
  };

  const getDeviceById = (deviceId?: string | null) =>
    systemDevices.find((device) => device.id === deviceId) ?? null;

  const getDeviceByImei = (imei?: string | null) =>
    systemDevices.find((device) => device.imei === (imei ?? "").trim()) ?? null;

  const detachDevice = async (currentToken: string, deviceId?: string | null) => {
    if (!deviceId) {
      return;
    }

    const device = getDeviceById(deviceId);
    if (!device) {
      return;
    }

    await updateDevice(currentToken, device.id, {
      imei: device.imei,
      phoneNumber: normalizePhoneNumber(device.phone_number),
      vehicleId: null,
    });
  };

  const assignDeviceToVehicle = async (
    currentToken: string,
    deviceId: string,
    vehicleId: string | null,
    overrides?: {
      imei?: string;
      phoneNumber?: string | null;
    },
  ) => {
    const device = getDeviceById(deviceId);
    if (!device) {
      throw new Error("Urządzenie nie istnieje");
    }

    if (vehicleId) {
      const currentVehicleDevice = vehicles.find(
        (vehicle) => vehicle.id === vehicleId && vehicle.deviceId && vehicle.deviceId !== deviceId,
      );
      if (currentVehicleDevice?.deviceId) {
        await detachDevice(currentToken, currentVehicleDevice.deviceId);
      }
    }

    await updateDevice(currentToken, deviceId, {
      imei: overrides?.imei?.trim() || device.imei,
      phoneNumber: normalizePhoneNumber(overrides?.phoneNumber ?? device.phone_number),
      vehicleId,
    });
  };

  const getPointTimestamp = (point?: Pick<HistoryPoint, "deviceTime" | "serverTime"> | null) => {
    if (!point) {
      return null;
    }

    const rawValue = point.deviceTime ?? point.serverTime;
    if (!rawValue) {
      return null;
    }

    const timestamp = new Date(rawValue).getTime();
    return Number.isNaN(timestamp) ? null : timestamp;
  };

  const getStationaryStartTimestamp = (stampedPoints: StampedHistoryPoint[], currentPoint?: PositionSnapshot | null) => {
    if (!currentPoint || (currentPoint.speed ?? 0) > 0) {
      return null;
    }

    const currentTimestamp = getPointTimestamp(currentPoint);
    if (currentTimestamp == null) {
      return null;
    }

    let stationaryStartTimestamp = currentTimestamp;

    for (let index = stampedPoints.length - 1; index >= 0; index -= 1) {
      const candidate = stampedPoints[index];
      const candidateTimestamp = candidate.timestamp;

      if (candidateTimestamp > currentTimestamp) {
        continue;
      }

      if ((candidate.point.speed ?? 0) > 0) {
        break;
      }

      stationaryStartTimestamp = candidateTimestamp;
    }

    return stationaryStartTimestamp;
  };

  useEffect(() => {
    const session = loadSession();
    if (!session) {
      router.replace("/login");
      return;
    }

    setToken(session.token);
    setCurrentUserId(session.user.id);
    setCurrentUserEmail(session.user.email);
    setCurrentUserFirstName(session.user.firstName);
    setCurrentUserLastName(session.user.lastName);
    setUserRole(session.user.role);
    setCanEditVehicleInspection(Boolean(session.user.canEditVehicleInspection));
    setCanViewStats(Boolean(session.user.canViewStats));
  }, [router]);

  useEffect(() => {
    if (typeof window === "undefined" || !currentUserId || hasHydratedSelectedVehicleRef.current) {
      return;
    }

    const storedVehicleId = window.localStorage.getItem(selectedVehicleStorageKey(currentUserId));
    if (storedVehicleId) {
      setSelectedVehicleId(storedVehicleId);
      setVehicleFocusNonce((current) => current + 1);
    }

    hasHydratedSelectedVehicleRef.current = true;
  }, [currentUserId]);

  useEffect(() => {
    if (typeof window === "undefined" || !currentUserId) {
      return;
    }

    const storedTileMode = window.localStorage.getItem(mapTileModeStorageKey(currentUserId));
    if (storedTileMode === "standard" || storedTileMode === "satellite") {
      setMapTileMode(storedTileMode);
      return;
    }

    setMapTileMode("standard");
  }, [currentUserId]);

  useEffect(() => {
    if (typeof window === "undefined" || !currentUserId) {
      return;
    }

    const todayKey = getLocalDateKey();
    const storageKey = dailyOverviewStorageKey(currentUserId);
    const storedDayKey = window.localStorage.getItem(storageKey);

    if (storedDayKey !== todayKey) {
      window.localStorage.setItem(storageKey, todayKey);
      setDailyOverviewKey(todayKey);
      return;
    }

    setDailyOverviewKey(null);
  }, [currentUserId]);

  const handleExpiredSession = useCallback(() => {
    clearSession();
    setToken(null);
    setCurrentUserId(null);
    setCurrentUserEmail("");
    setCurrentUserFirstName("");
    setCurrentUserLastName("");
    setUserRole("user");
    setCanEditVehicleInspection(false);
    setSelectedVehicleId(null);
    setVehicles([]);
    setActiveAlerts([]);
    setRecentAlerts([]);
    setSystemUsers([]);
    setSystemDevices([]);
    setCompanySettings(null);
    setCompanyAddressInput("");
    setIsAlertsListOpen(false);
    setIsRecentTripsOpen(false);
    setRecentTrips([]);
    setRecentTripsError(null);
    setRecentTripsHasMore(false);
    setRecentTripsNextBefore(null);
    setRecentTripsCanScrollUp(false);
    setRecentTripsCanScrollDown(false);
    recentTripsPendingBottomRetryRef.current = false;
    router.replace("/login");
  }, [router]);

  const refreshDashboardData = useCallback(
    async (options?: { silent?: boolean }) => {
      if (!token) {
        return;
      }

      if (dashboardRefreshInFlightRef.current) {
        await dashboardRefreshInFlightRef.current;
        return;
      }

      const refreshPromise = (async () => {
        try {
        const vehiclesPromise = fetchVehicles(token);
        const auxiliaryPromise = Promise.allSettled([
          userRole === "admin" ? fetchUsers(token) : Promise.resolve({ items: [] }),
          userRole === "admin" ? fetchDevices(token) : Promise.resolve({ items: [] }),
          fetchActiveAlerts(token),
          fetchRecentAlerts(token),
          fetchCompanySettings(token),
          userRole === "admin"
            ? fetchInspectionEmailSettings(token)
            : Promise.resolve({ item: { recipients: [], updatedAt: null } }),
        ]);

        const { items: nextVehicles } = await vehiclesPromise;
        setVehicles((current) => {
          const currentVehiclesById = new Map(current.map((vehicle) => [vehicle.id, vehicle]));

          return nextVehicles.map((nextVehicle) => {
            const currentVehicle = currentVehiclesById.get(nextVehicle.id);
            if (!currentVehicle) {
              return nextVehicle;
            }

            const currentPoint = currentVehicle.lastPosition;
            const nextPoint = nextVehicle.lastPosition;
            const currentTimestamp = getPointTimeMs(currentPoint);
            const nextTimestamp = getPointTimeMs(nextPoint);

            if (
              currentPoint
              && nextPoint
              && currentTimestamp != null
              && nextTimestamp != null
              && nextTimestamp <= currentTimestamp
            ) {
              return {
                ...nextVehicle,
                lastPosition: currentPoint,
                lastSeen: currentVehicle.lastSeen,
                deviceState: {
                  ...(nextVehicle.deviceState ?? {}),
                  deviceTime: currentVehicle.deviceState?.deviceTime ?? nextVehicle.deviceState?.deviceTime ?? null,
                  battery: currentVehicle.deviceState?.battery ?? nextVehicle.deviceState?.battery ?? null,
                  gsmSignal: currentVehicle.deviceState?.gsmSignal ?? nextVehicle.deviceState?.gsmSignal ?? null,
                  ignition: currentVehicle.deviceState?.ignition ?? nextVehicle.deviceState?.ignition ?? null,
                  charging: currentVehicle.deviceState?.charging ?? nextVehicle.deviceState?.charging ?? null,
                  defense: currentVehicle.deviceState?.defense ?? nextVehicle.deviceState?.defense ?? null,
                  gpsValid: currentVehicle.deviceState?.gpsValid ?? nextVehicle.deviceState?.gpsValid ?? null,
                  satelliteCount: currentVehicle.deviceState?.satelliteCount ?? nextVehicle.deviceState?.satelliteCount ?? null,
                  positionType: currentVehicle.deviceState?.positionType ?? nextVehicle.deviceState?.positionType ?? null,
                },
              };
            }

            const segment = buildLiveInterpolationSegment(
              currentPoint,
              nextPoint,
              nextVehicle.deviceState?.ignition === true || nextPoint?.ignition === true,
            );

            if (segment) {
              liveInterpolationSegmentsRef.current.set(nextVehicle.id, segment);
            } else if (
              !currentPoint
              || !nextPoint
              || currentTimestamp == null
              || nextTimestamp == null
              || nextTimestamp > currentTimestamp
            ) {
              liveInterpolationSegmentsRef.current.delete(nextVehicle.id);
            }

            return nextVehicle;
          });
        });
        setSelectedVehicleId((current) => {
          const currentVehicleId = current?.trim() || null;
          const storedVehicleId = typeof window !== "undefined" && currentUserId
            ? window.localStorage.getItem(selectedVehicleStorageKey(currentUserId))
            : null;
          const preferredVehicleId = currentVehicleId ?? storedVehicleId;

          return preferredVehicleId && nextVehicles.some((vehicle) => vehicle.id === preferredVehicleId)
            ? preferredVehicleId
            : null;
        });

        const [
          usersResult,
          devicesResult,
          alertsResult,
          recentAlertsResult,
          companySettingsResult,
          inspectionEmailSettingsResult,
        ] = await auxiliaryPromise;

        const auxiliaryErrors = [
          usersResult,
          devicesResult,
          alertsResult,
          recentAlertsResult,
          companySettingsResult,
          inspectionEmailSettingsResult,
        ]
          .filter((result): result is PromiseRejectedResult => result.status === "rejected")
          .map((result) => result.reason);

        const unauthorizedError = auxiliaryErrors.find(
          (error) => error instanceof ApiError && error.status === 401,
        );
        if (unauthorizedError) {
          handleExpiredSession();
          return;
        }

        const usersResponse = usersResult.status === "fulfilled" ? usersResult.value : { items: [] };
        const devicesResponse = devicesResult.status === "fulfilled" ? devicesResult.value : { items: [] };
        const alertsResponse = alertsResult.status === "fulfilled" ? alertsResult.value : { items: [] };
        const recentAlertsResponse = recentAlertsResult.status === "fulfilled" ? recentAlertsResult.value : { items: [] };
        const companySettingsResponse = companySettingsResult.status === "fulfilled" ? companySettingsResult.value : { item: null };
        const inspectionEmailSettingsResponse = inspectionEmailSettingsResult.status === "fulfilled"
          ? inspectionEmailSettingsResult.value
          : { item: { recipients: [], updatedAt: null } };

        setSystemUsers(usersResponse.items);
        setSystemDevices(devicesResponse.items);
        setActiveAlerts(alertsResponse.items);
        setRecentAlerts(recentAlertsResponse.items);
        setCompanySettings(companySettingsResponse.item);
        setCompanyAddressInput(companySettingsResponse.item?.addressInput ?? "");
        setInspectionEmailSettings(inspectionEmailSettingsResponse.item);
        setInspectionEmailRecipientsInput(inspectionEmailSettingsResponse.item.recipients.join("\n"));
        setLoadError(null);
        } catch (error) {
          if (error instanceof ApiError && error.status === 401) {
            handleExpiredSession();
            return;
          }

          if (!options?.silent) {
            setLoadError(getFriendlyLoadErrorMessage(error, "Nie udało się odświeżyć danych panelu."));
          }
        }
      })();

      dashboardRefreshInFlightRef.current = refreshPromise;
      try {
        await refreshPromise;
      } finally {
        if (dashboardRefreshInFlightRef.current === refreshPromise) {
          dashboardRefreshInFlightRef.current = null;
        }
      }
    },
    [currentUserId, handleExpiredSession, token, userRole],
  );

  const loadVehicleStatsOverview = useCallback(
    async (options?: { silent?: boolean }) => {
      if (!token) {
        return;
      }

      try {
        const response = await fetchVehicleStatsOverview(token, selectedVehicleId);
        setVehicleStatsOverview(response.item);
        setVehicleStatsError(null);
      } catch (error) {
        if (error instanceof ApiError && error.status === 401) {
          handleExpiredSession();
          return;
        }

        if (!options?.silent) {
          setVehicleStatsError(getFriendlyLoadErrorMessage(error, "Nie udało się wczytać statystyk."));
        }
      }
    },
    [handleExpiredSession, selectedVehicleId, token],
  );

  const loadRecentTrips = useCallback(
    async (
      vehicleId: string,
      options?: {
        append?: boolean;
        before?: string | null;
      },
    ) => {
      if (!token) {
        return;
      }

      const append = Boolean(options?.append);
      setRecentTripsError(null);
      if (append) {
        setIsRecentTripsLoadingMore(true);
      } else {
        setIsRecentTripsLoading(true);
      }

      try {
        const response = await fetchVehicleTrips(token, vehicleId, 14, 20, options?.before ?? undefined);
        setRecentTrips((current) => append ? [...current, ...response.items] : response.items);
        setRecentTripsHasMore(response.hasMore);
        setRecentTripsNextBefore(response.nextBefore);
      } catch (error) {
        if (error instanceof ApiError && error.status === 401) {
          handleExpiredSession();
          return;
        }

        setRecentTripsError(getFriendlyLoadErrorMessage(error, "Nie udało się wczytać listy kursów."));
      } finally {
        recentTripsPendingBottomRetryRef.current = false;
        if (append) {
          setIsRecentTripsLoadingMore(false);
        } else {
          setIsRecentTripsLoading(false);
        }
      }
    },
    [handleExpiredSession, token],
  );

  useEffect(() => {
    if (!token || !isDocumentVisible) {
      return;
    }

    void refreshDashboardData();
  }, [isDocumentVisible, refreshDashboardData, token]);

  useEffect(() => {
    if (typeof window === "undefined" || !currentUserId) {
      return;
    }

    const storageKey = selectedVehicleStorageKey(currentUserId);
    if (selectedVehicleId) {
      window.localStorage.setItem(storageKey, selectedVehicleId);
      return;
    }

    window.localStorage.removeItem(storageKey);
  }, [currentUserId, selectedVehicleId]);

  useEffect(() => {
    if (typeof window === "undefined" || !currentUserId) {
      return;
    }

    window.localStorage.setItem(mapTileModeStorageKey(currentUserId), mapTileMode);
  }, [currentUserId, mapTileMode]);

  useEffect(() => {
    setIsRecentTripsOpen(false);
    setRecentTrips([]);
    setRecentTripsError(null);
    setRecentTripsHasMore(false);
    setRecentTripsNextBefore(null);
    setRecentTripsCanScrollUp(false);
    setRecentTripsCanScrollDown(false);
    recentTripsPendingBottomRetryRef.current = false;
  }, [selectedVehicleId]);

  useEffect(() => {
    if (!token || !selectedVehicleId) {
      setHistory([]);
      setPlaybackTimestamp(null);
      setLoadError(null);
      return;
    }

    if (
      !isTimelineVisible
      || pendingAlertPlayback?.vehicleId === selectedVehicleId
      || alertPlaybackRange?.vehicleId === selectedVehicleId
    ) {
      return;
    }

    const fromMs = getDateTimeLocalTimestamp(from);
    const toMs = getDateTimeLocalTimestamp(to);
    if (Number.isNaN(fromMs) || Number.isNaN(toMs) || fromMs > toMs) {
      setHistory([]);
      setPlaybackTimestamp(null);
      return;
    }

    const load = async () => {
      const fetchFromIso = toIsoFromDateTimeLocalValue(from);
      const fetchToIso = toIsoFromDateTimeLocalValue(to);
      const requestKey = `${selectedVehicleId}|${fetchFromIso}|${fetchToIso}`;
      if (historyRequestKeyRef.current === requestKey) {
        return;
      }
      historyRequestKeyRef.current = requestKey;

      try {
        const response = await fetchVehicleHistory(
          token,
          selectedVehicleId,
          fetchFromIso,
          fetchToIso,
        );
        setHistory(sortHistoryPoints(response.items));
        setLoadError(null);
      } catch (historyError) {
        if (historyRequestKeyRef.current === requestKey) {
          historyRequestKeyRef.current = null;
        }
        setLoadError(getFriendlyLoadErrorMessage(historyError, "Nie udało się wczytać historii pojazdu."));
      }
    };

    void load();
  }, [alertPlaybackRange, from, isTimelineVisible, pendingAlertPlayback, selectedVehicleId, to, token]);

  useEffect(() => {
    if (history.length === 0) {
      setPlaybackTimestamp(null);
      return;
    }

    const firstPointTimestamp = getTimelineStartTimestamp(history, from);
    setPlaybackTimestamp((current) => current ?? firstPointTimestamp);
  }, [from, history]);

  useEffect(() => {
    if (!token || !isDocumentVisible) {
      setIsSocketConnected(false);
      return;
    }

    if (typeof window === "undefined") {
      setIsSocketConnected(false);
      return;
    }

    const wsBaseUrl = window.location.origin;

    const socket: Socket = io(wsBaseUrl, {
      path: "/ws/socket.io",
      transports: ["websocket", "polling"],
      timeout: 5_000,
      reconnectionDelay: 60_000,
      reconnectionDelayMax: 5 * 60_000,
      randomizationFactor: 0.25,
      auth: {
        token,
      },
    });

    const flushTelemetryUpdates = () => {
      telemetryFlushTimeoutRef.current = null;
      if (pendingTelemetryUpdatesRef.current.size === 0) {
        return;
      }

      const pendingUpdates = new Map(pendingTelemetryUpdatesRef.current);
      pendingTelemetryUpdatesRef.current.clear();

      setVehicles((current) =>
        current.map((vehicle) => {
          const pending = vehicle.imei ? pendingUpdates.get(vehicle.imei) : undefined;
          if (!pending) {
            return vehicle;
          }

          const wasIgnitionOff = vehicle.deviceState?.ignition === false;
          const staysIgnitionOff = pending.telemetry.ignition === false;
          const shouldFreezePosition = wasIgnitionOff && staysIgnitionOff && vehicle.lastPosition != null;
          const nextLastPosition: VehicleSummary["lastPosition"] = shouldFreezePosition
            ? {
                ...vehicle.lastPosition!,
                ignition: false,
              }
            : {
                lat: pending.telemetry.lat,
                lon: pending.telemetry.lon,
                speed: pending.telemetry.speed ?? null,
                heading: pending.telemetry.heading ?? null,
                deviceTime: pending.telemetry.deviceTime ?? null,
                serverTime: pending.telemetry.serverTime,
                ignition: pending.telemetry.ignition ?? null,
                battery: pending.telemetry.battery ?? null,
                gsmSignal: pending.telemetry.gsmSignal ?? null,
                satelliteCount: pending.telemetry.satelliteCount ?? null,
                gpsValid: pending.telemetry.gpsValid ?? null,
                charging: pending.telemetry.charging ?? null,
                defense: pending.telemetry.defense ?? null,
                positionType: pending.telemetry.positionType ?? null,
              };

          if (vehicle.lastPosition && nextLastPosition && !shouldFreezePosition) {
            const segment = buildLiveInterpolationSegment(
              vehicle.lastPosition,
              nextLastPosition,
              pending.telemetry.ignition === true || nextLastPosition.ignition === true,
            );

            if (segment) {
              liveInterpolationSegmentsRef.current.set(vehicle.id, segment);
            } else {
              liveInterpolationSegmentsRef.current.delete(vehicle.id);
            }
          } else {
            liveInterpolationSegmentsRef.current.delete(vehicle.id);
          }

          return {
            ...vehicle,
            status: pending.status,
            lastSeen: pending.telemetry.serverTime,
            lastPosition: nextLastPosition,
            deviceState: {
              ...(vehicle.deviceState ?? {}),
              phoneNumber: vehicle.phoneNumber ?? null,
              deviceTime: pending.telemetry.deviceTime ?? vehicle.deviceState?.deviceTime ?? null,
              battery: pending.telemetry.battery ?? vehicle.deviceState?.battery ?? null,
              gsmSignal: pending.telemetry.gsmSignal ?? vehicle.deviceState?.gsmSignal ?? null,
              ignition: pending.telemetry.ignition ?? vehicle.deviceState?.ignition ?? null,
              charging: pending.telemetry.charging ?? vehicle.deviceState?.charging ?? null,
              defense: pending.telemetry.defense ?? vehicle.deviceState?.defense ?? null,
              gpsValid: pending.telemetry.gpsValid ?? vehicle.deviceState?.gpsValid ?? null,
              satelliteCount: pending.telemetry.satelliteCount ?? vehicle.deviceState?.satelliteCount ?? null,
              positionType: pending.telemetry.positionType ?? vehicle.deviceState?.positionType ?? null,
            },
          };
        }),
      );
    };

    const scheduleTelemetryFlush = () => {
      if (telemetryFlushTimeoutRef.current != null) {
        return;
      }

      telemetryFlushTimeoutRef.current = window.setTimeout(flushTelemetryUpdates, TELEMETRY_FLUSH_MS);
    };

    socket.on("connect", () => {
      setIsSocketConnected(true);
    });

    socket.on("disconnect", () => {
      setIsSocketConnected(false);
    });

    socket.on("telemetry:update", (event) => {
      pendingTelemetryUpdatesRef.current.set(event.imei, {
        status: event.status,
        telemetry: {
          lat: event.telemetry.lat,
          lon: event.telemetry.lon,
          speed: event.telemetry.speed ?? null,
          heading: event.telemetry.heading ?? null,
          deviceTime: event.telemetry.deviceTime ?? null,
          serverTime: event.telemetry.serverTime,
          ignition: event.telemetry.ignition ?? null,
          battery: event.telemetry.battery ?? null,
          gsmSignal: event.telemetry.gsmSignal ?? null,
          satelliteCount: event.telemetry.satelliteCount ?? null,
          gpsValid: event.telemetry.gpsValid ?? null,
          charging: event.telemetry.charging ?? null,
          defense: event.telemetry.defense ?? null,
          positionType: event.telemetry.positionType ?? null,
        },
      });
      scheduleTelemetryFlush();
    });

    socket.on("vehicle-alert:update", (alert: VehicleAlertSummary) => {
      setActiveAlerts((current) => {
        const existingIndex = current.findIndex((item) => item.id === alert.id);
        if (existingIndex >= 0) {
          return current.map((item) => item.id === alert.id ? alert : item);
        }

        return [alert, ...current];
      });
      setRecentAlerts((current) => {
        const existingIndex = current.findIndex((item) => item.id === alert.id);
        if (existingIndex >= 0) {
          return current.map((item) => item.id === alert.id ? alert : item);
        }

        return [alert, ...current];
      });
    });

    socket.on("connect_error", (socketError) => {
      setIsSocketConnected(false);
      if (process.env.NODE_ENV !== "production") {
        console.warn("socket connect error", socketError.message);
      }
    });

    return () => {
      if (telemetryFlushTimeoutRef.current != null) {
        window.clearTimeout(telemetryFlushTimeoutRef.current);
        telemetryFlushTimeoutRef.current = null;
      }
      pendingTelemetryUpdatesRef.current.clear();
      setIsSocketConnected(false);
      socket.close();
    };
  }, [isDocumentVisible, token]);

  useEffect(() => {
    if (!token || !isDocumentVisible) {
      return;
    }

    const intervalMs = isSocketConnected
      ? DASHBOARD_REFRESH_CONNECTED_MS
      : DASHBOARD_REFRESH_DISCONNECTED_MS;
    const intervalId = window.setInterval(() => {
      void refreshDashboardData({ silent: true });
    }, intervalMs);

    return () => window.clearInterval(intervalId);
  }, [isDocumentVisible, isSocketConnected, refreshDashboardData, token]);

  useEffect(() => {
    if (typeof window === "undefined" || !token) {
      return;
    }

    const refreshIfVisible = () => {
      if (document.visibilityState !== "hidden") {
        void refreshDashboardData({ silent: true });
        if (isStatsPanelOpen) {
          void loadVehicleStatsOverview({ silent: true });
        }
      }
    };

    const refreshOnVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        void refreshDashboardData({ silent: true });
        if (isStatsPanelOpen) {
          void loadVehicleStatsOverview({ silent: true });
        }
      }
    };

    window.addEventListener("focus", refreshIfVisible);
    window.addEventListener("pageshow", refreshIfVisible);
    window.addEventListener("online", refreshIfVisible);
    document.addEventListener("visibilitychange", refreshOnVisibilityChange);

    return () => {
      window.removeEventListener("focus", refreshIfVisible);
      window.removeEventListener("pageshow", refreshIfVisible);
      window.removeEventListener("online", refreshIfVisible);
      document.removeEventListener("visibilitychange", refreshOnVisibilityChange);
    };
  }, [canAccessStats, isStatsPanelOpen, loadVehicleStatsOverview, refreshDashboardData, token]);

  useEffect(() => {
    if (!canAccessStats && isStatsPanelOpen) {
      setIsStatsPanelOpen(false);
    }
  }, [canAccessStats, isStatsPanelOpen]);

  useEffect(() => {
    if (!canAccessStats || !isStatsPanelOpen || !token) {
      return;
    }

    void loadVehicleStatsOverview();
  }, [canAccessStats, isStatsPanelOpen, loadVehicleStatsOverview, token]);

  useEffect(() => {
    if (!canAccessStats || !isStatsPanelOpen || !token) {
      return;
    }

    const intervalId = window.setInterval(() => {
      void loadVehicleStatsOverview({ silent: true });
    }, 60 * 60 * 1000);

    return () => window.clearInterval(intervalId);
  }, [canAccessStats, isStatsPanelOpen, loadVehicleStatsOverview, token]);

  const selectedVehicle = useMemo(
    () => displayVehicles.find((vehicle) => vehicle.id === selectedVehicleId) ?? null,
    [displayVehicles, selectedVehicleId],
  );
  useEffect(() => {
    if (!token || !selectedVehicleId || !selectedVehicle?.lastPosition || isTimelineVisible) {
      return;
    }

    const currentPosition = selectedVehicle.lastPosition;
    const currentTimestamp = getPointTimeMs(currentPosition);
    const ignitionOn = selectedVehicle.deviceState?.ignition === true || currentPosition.ignition === true;
    const speedKmh = clamp(currentPosition.speed ?? 0, 0, LIVE_INTERPOLATION_MAX_SPEED_KMH);

    if (
      !ignitionOn
      || speedKmh < LIVE_PREDICTION_MIN_SPEED_KMH
      || currentPosition.gpsValid === false
      || currentTimestamp == null
    ) {
      return;
    }

    const requestKey = `${selectedVehicleId}:${currentPosition.serverTime}`;
    if (liveSeedRequestKeyRef.current === requestKey) {
      return;
    }

    liveSeedRequestKeyRef.current = requestKey;
    let cancelled = false;

    void fetchVehiclePreviousPosition(token, selectedVehicleId, currentPosition.serverTime)
      .then((response) => {
        if (cancelled || !response.item) {
          return;
        }

        const segment = buildLiveInterpolationSegment(
          response.item,
          currentPosition,
          true,
        );

        if (!segment) {
          return;
        }

        setAnimatedVehiclePosition(response.item);
        liveInterpolationSegmentsRef.current.set(selectedVehicleId, segment);
      })
      .catch(() => {
        if (cancelled) {
          return;
        }

        liveSeedRequestKeyRef.current = null;
      });

    return () => {
      cancelled = true;
    };
  }, [isTimelineVisible, selectedVehicle, selectedVehicleId, token]);
  const onlineVehiclesCount = useMemo(
    () => displayVehicles.filter((vehicle) => vehicle.status === "online").length,
    [displayVehicles],
  );
  const movingVehicles = useMemo(
    () => displayVehicles.filter((vehicle) => {
      const ignition = vehicle.deviceState?.ignition ?? vehicle.lastPosition?.ignition;
      const speed = vehicle.lastPosition?.speed ?? 0;
      return ignition === true && speed > 0;
    }),
    [displayVehicles],
  );
  const movingVehiclesCount = movingVehicles.length;
  const vehiclesAtCompany = useMemo(
    () => (companySettings
      ? displayVehicles.filter((vehicle) => {
          const point = vehicle.lastPosition;
          if (!point) {
            return false;
          }

          return distanceMeters(
            { lat: point.lat, lon: point.lon },
            { lat: companySettings.lat, lon: companySettings.lon },
          ) <= 50;
        })
      : []),
    [companySettings, displayVehicles],
  );
  const vehiclesAtCompanyCount = vehiclesAtCompany.length;
  const selectedDeviceState = selectedVehicle?.deviceState ?? null;
  const historyMinInput = toDateTimeLocalValue(selectedVehicle?.firstHistoryAt ?? null);
  const historyMaxInput = toDateTimeLocalValue(
    selectedVehicle?.lastPosition?.serverTime ?? selectedVehicle?.lastSeen ?? null,
  );

  useEffect(() => {
    if (!selectedVehicleId) {
      defaultHistoryRangeRef.current = null;
      historyRequestKeyRef.current = null;
      return;
    }

    if (!historyMaxInput) {
      return;
    }

    if (defaultHistoryRangeRef.current?.vehicleId === selectedVehicleId) {
      return;
    }

    const defaultRange = getDefaultHistoryRangeValues(historyMinInput, historyMaxInput);
    defaultHistoryRangeRef.current = {
      vehicleId: selectedVehicleId,
      ...defaultRange,
    };
    setFrom(defaultRange.from);
    setTo(defaultRange.to);
    historyRequestKeyRef.current = null;
    setHistory([]);
    setPlaybackTimestamp(null);
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setIsPlaybackRunning(false);
  }, [historyMaxInput, historyMinInput, selectedVehicleId]);

  const activeAlertPlaybackRange = alertPlaybackRange?.vehicleId === selectedVehicleId
    ? alertPlaybackRange
    : null;
  const sliderMinTimestamp = activeAlertPlaybackRange
    ? activeAlertPlaybackRange.from
    : history.length > 0
    ? Math.max(
        getPointTimeMs(history[0]) ?? 0,
        getDateTimeLocalTimestamp(from),
      )
    : isTimelineVisible
      ? getDateTimeLocalTimestamp(from)
      : null;
  const sliderMaxTimestamp = activeAlertPlaybackRange
    ? activeAlertPlaybackRange.to
    : history.length > 0
    ? Math.min(
        getPointTimeMs(history[history.length - 1]) ?? 0,
        getDateTimeLocalTimestamp(to),
      )
    : isTimelineVisible
      ? getDateTimeLocalTimestamp(to)
      : null;
  const stampedHistory = useMemo(() => getStampedHistoryPoints(history), [history]);
  const playbackPoint = stampedHistory.length > 0
    ? getPlaybackPosition(stampedHistory, playbackTimestamp, playbackDirection)
    : null;
  const hasDrivingHistory = useMemo(
    () => history.some((point) => (point.speed ?? 0) > 0 || point.ignition === true),
    [history],
  );
  const shouldShowNoDrivingHistoryMessage = isTimelineVisible && history.length > 0 && !hasDrivingHistory;
  const selectedPosition = (isTimelineVisible && isTimelineActivated ? playbackPoint : null) ?? selectedVehicle?.lastPosition ?? null;
  const selectedPositionTimestamp = getPointTimestamp(selectedPosition);
  const stationaryStartTimestamp = getStationaryStartTimestamp(
    stampedHistory,
    playbackPoint ?? null,
  );
  const selectedPositionReachedTimestamp = getAddressReachedTimestamp(
    stampedHistory,
    selectedPosition,
  );
  const timelineProgress = sliderMinTimestamp != null
    && sliderMaxTimestamp != null
    && playbackTimestamp != null
    && sliderMaxTimestamp > sliderMinTimestamp
    ? ((playbackTimestamp - sliderMinTimestamp) / (sliderMaxTimestamp - sliderMinTimestamp)) * 100
    : 0;
  const playbackPointTime = playbackPoint?.deviceTime ?? playbackPoint?.serverTime ?? null;
  const isPlaybackDriving = (playbackPoint?.ignition === true) || ((playbackPoint?.speed ?? 0) > 0);
  const companyDistanceLabel = formatDistanceKm(companyRouteSummary?.distanceKm);
  const companyDurationLabel = formatDurationMinutes(companyRouteSummary?.durationMinutes);
  const effectivePositionReachedTimestamp = stationaryStartTimestamp ?? selectedPositionReachedTimestamp;
  const selectedPositionReachedLabel = effectivePositionReachedTimestamp != null
    ? formatDateTime(new Date(effectivePositionReachedTimestamp).toISOString())
    : null;
  const selectedServiceNotices = getVehicleServiceNotices(selectedVehicle);
  const selectedPositionIgnitionOn = isTimelineVisible && isTimelineActivated
    ? selectedPosition?.ignition === true
    : selectedDeviceState?.ignition === true || selectedPosition?.ignition === true;
  const selectedPositionAddressMode: SelectedVehicleAddressMode = selectedPositionIgnitionOn ? "driving" : "parked";

  useEffect(() => {
    if (
      !isTimelineVisible
      || !isPlaybackRunning
      || sliderMinTimestamp == null
      || sliderMaxTimestamp == null
      || !isDocumentVisible
    ) {
      if (playbackFrameRef.current != null) {
        window.cancelAnimationFrame(playbackFrameRef.current);
        playbackFrameRef.current = null;
      }
      playbackLastTickRef.current = null;
      playbackLastRenderAtRef.current = null;
      playbackStoppedPreviewRef.current = null;
      return;
    }

    const tick = (frameTime: number) => {
      if (
        playbackLastRenderAtRef.current != null
        && frameTime - playbackLastRenderAtRef.current < PLAYBACK_FRAME_MS
      ) {
        playbackFrameRef.current = window.requestAnimationFrame(tick);
        return;
      }

      playbackLastRenderAtRef.current = frameTime;

      if (playbackLastTickRef.current == null) {
        playbackLastTickRef.current = frameTime;
      }

      const deltaMs = Math.min(120, frameTime - playbackLastTickRef.current);
      playbackLastTickRef.current = frameTime;

      let shouldStop = false;

      setPlaybackTimestamp((current) => {
        const currentTimestamp = current
          ?? (playbackDirection === "backward" ? sliderMaxTimestamp : sliderMinTimestamp);
        let nextTimestamp = currentTimestamp + (
          playbackDirection === "backward"
            ? -deltaMs * playbackSpeed
            : deltaMs * playbackSpeed
        );

        if (skipStopsDuringPlayback) {
          const stoppedPreview = getStoppedSegmentPreview(stampedHistory, nextTimestamp, playbackDirection);

          if (stoppedPreview != null) {
            const currentPreview = playbackStoppedPreviewRef.current;
            if (currentPreview?.holdTimestamp !== stoppedPreview.holdTimestamp) {
              playbackStoppedPreviewRef.current = {
                holdTimestamp: stoppedPreview.holdTimestamp,
                previewStartedAt: frameTime,
                resumeTimestamp: stoppedPreview.resumeTimestamp,
              };
            }

            const activePreview = playbackStoppedPreviewRef.current;
            if (
              activePreview?.resumeTimestamp != null
              && frameTime - activePreview.previewStartedAt >= PLAYBACK_STOP_PREVIEW_MS
            ) {
              nextTimestamp = activePreview.resumeTimestamp;
              playbackStoppedPreviewRef.current = null;
            } else {
              return stoppedPreview.holdTimestamp;
            }
          } else {
            playbackStoppedPreviewRef.current = null;
          }
        }

        if (nextTimestamp <= sliderMinTimestamp) {
          shouldStop = true;
          return sliderMinTimestamp;
        }

        if (nextTimestamp >= sliderMaxTimestamp) {
          shouldStop = true;
          return sliderMaxTimestamp;
        }

        return nextTimestamp;
      });

      if (shouldStop) {
        setIsPlaybackRunning(false);
        playbackLastTickRef.current = null;
        playbackLastRenderAtRef.current = null;
        playbackFrameRef.current = null;
        return;
      }

      playbackFrameRef.current = window.requestAnimationFrame(tick);
    };

    playbackFrameRef.current = window.requestAnimationFrame(tick);

    return () => {
      if (playbackFrameRef.current != null) {
        window.cancelAnimationFrame(playbackFrameRef.current);
        playbackFrameRef.current = null;
      }
      playbackLastTickRef.current = null;
      playbackLastRenderAtRef.current = null;
    };
  }, [
    isPlaybackRunning,
    isDocumentVisible,
    isTimelineVisible,
    playbackDirection,
    playbackSpeed,
    stampedHistory,
    skipStopsDuringPlayback,
    sliderMaxTimestamp,
    sliderMinTimestamp,
  ]);

  useEffect(() => {
    if (!selectedVehicle) {
      return;
    }

    if (historyMinInput) {
      setFrom((current) => clampDateTimeLocalValue(current, historyMinInput, historyMaxInput));
    }

    if (historyMaxInput) {
      setTo((current) => clampDateTimeLocalValue(current, historyMinInput, historyMaxInput));
    }
  }, [historyMaxInput, historyMinInput, selectedVehicle]);

  useEffect(() => {
    if (!from || !to) {
      return;
    }

    const fromMs = getDateTimeLocalTimestamp(from);
    const toMs = getDateTimeLocalTimestamp(to);
    if (Number.isNaN(fromMs) || Number.isNaN(toMs)) {
      return;
    }
  }, [from, to]);

  useEffect(() => {
    if (sliderMinTimestamp == null || sliderMaxTimestamp == null) {
      return;
    }

    setPlaybackTimestamp((current) => {
      if (current == null) {
        return sliderMinTimestamp;
      }

      return Math.min(Math.max(current, sliderMinTimestamp), sliderMaxTimestamp);
    });
  }, [sliderMaxTimestamp, sliderMinTimestamp]);

  useEffect(() => {
    if (!selectedVehicleId) {
      selectedVehicleIgnitionRef.current = { vehicleId: null, ignition: null };
      return;
    }

    const currentIgnition = isTimelineVisible
      ? (selectedPosition?.ignition ?? null)
      : (selectedDeviceState?.ignition ?? selectedVehicle?.lastPosition?.ignition ?? null);
    const previous = selectedVehicleIgnitionRef.current;

    if (
      previous.vehicleId === selectedVehicleId
      && previous.ignition === true
      && currentIgnition === false
    ) {
      setAddressLookupNonce((current) => current + 1);
    }

    selectedVehicleIgnitionRef.current = {
      vehicleId: selectedVehicleId,
      ignition: currentIgnition,
    };
  }, [
    isTimelineVisible,
    selectedDeviceState?.ignition,
    selectedPosition?.ignition,
    selectedVehicle?.lastPosition?.ignition,
    selectedVehicleId,
  ]);

  useEffect(() => {
    if (!selectedPositionDetailsEnabled || !token || !selectedPosition) {
      setSelectedPositionAddress(null);
      setSelectedPositionAddressLoading(false);
      selectedPositionAddressKeyRef.current = null;
      return;
    }

    if (!selectedVehicleId) {
      setSelectedPositionAddress(null);
      setSelectedPositionAddressLoading(false);
      selectedPositionAddressKeyRef.current = null;
      return;
    }

    const currentLat = selectedPosition.lat;
    const currentLon = selectedPosition.lon;
    const roundedKey = `${currentLat.toFixed(5)}:${currentLon.toFixed(5)}`;
    const vehicleCache = selectedVehicleAddressCacheRef.current[selectedVehicleId] ?? {};
    const modeCache = vehicleCache[selectedPositionAddressMode];

    if (
      modeCache
      && distanceMeters(
        { lat: modeCache.lat, lon: modeCache.lon },
        { lat: currentLat, lon: currentLon },
      ) <= ADDRESS_REUSE_DISTANCE_METERS
    ) {
      setSelectedPositionAddress(modeCache.label);
      setSelectedPositionAddressLoading(false);
      return;
    }

    const globalCachedAddress = globalAddressCacheRef.current.get(roundedKey);
    if (globalCachedAddress) {
      selectedVehicleAddressCacheRef.current[selectedVehicleId] = {
        ...vehicleCache,
        [selectedPositionAddressMode]: {
          lat: currentLat,
          lon: currentLon,
          label: globalCachedAddress,
          key: roundedKey,
        },
      };
      setSelectedPositionAddress(globalCachedAddress);
      setSelectedPositionAddressLoading(false);
      return;
    }

    const requestKey = `${selectedVehicleId}:${selectedPositionAddressMode}:${addressLookupNonce}`;
    if (selectedPositionAddressKeyRef.current === requestKey) {
      return;
    }

    let cancelled = false;
    const timeoutId = window.setTimeout(() => {
      if (cancelled) {
        return;
      }

      setSelectedPositionAddressLoading(true);
      setSelectedPositionAddress(null);
      selectedPositionAddressKeyRef.current = requestKey;

      void reverseGeocode(token, currentLat, currentLon)
        .then((response) => {
          if (cancelled) {
            return;
          }

          globalAddressCacheRef.current.set(roundedKey, response.item.label);
          selectedVehicleAddressCacheRef.current[selectedVehicleId] = {
            ...(selectedVehicleAddressCacheRef.current[selectedVehicleId] ?? {}),
            [selectedPositionAddressMode]: {
              lat: currentLat,
              lon: currentLon,
              label: response.item.label,
              key: roundedKey,
            },
          };
          setSelectedPositionAddress((current) =>
            current === response.item.label ? current : response.item.label,
          );
        })
        .catch(() => {
          if (cancelled) {
            return;
          }
          setSelectedPositionAddress("Brak adresu");
        })
        .finally(() => {
          if (cancelled) {
            return;
          }
          setSelectedPositionAddressLoading(false);
        });
    }, isPlaybackRunning ? 400 : 120);

    return () => {
      cancelled = true;
      window.clearTimeout(timeoutId);
    };
  }, [addressLookupNonce, selectedPosition, selectedPositionAddressMode, selectedPositionDetailsEnabled, selectedVehicleId, token]);

  const handleVehiclePopupOpen = useCallback((vehicleId: string) => {
    if (vehicleId !== selectedVehicleId) {
      return;
    }

    setSelectedPositionDetailsEnabled(true);
    setAddressLookupNonce((current) => current + 1);
  }, [selectedVehicleId]);

  const handleVehiclePopupClose = useCallback((vehicleId: string) => {
    if (vehicleId !== selectedVehicleId) {
      return;
    }

    setSelectedPositionDetailsEnabled(false);
    setSelectedPositionAddress(null);
    setSelectedPositionAddressLoading(false);
    setCompanyRouteSummary(null);
    selectedPositionAddressKeyRef.current = null;
    companyRouteKeyRef.current = null;
    companyRouteRequestRef.current = null;
    companyRouteAbortRef.current?.abort();
    companyRouteAbortRef.current = null;
  }, [selectedVehicleId]);

  useEffect(() => {
    if (!isDocumentVisible || !selectedPositionDetailsEnabled || !token || !selectedPosition || !companySettings) {
      companyRouteAbortRef.current?.abort();
      companyRouteAbortRef.current = null;
      setCompanyRouteSummary(null);
      companyRouteKeyRef.current = null;
      companyRouteRequestRef.current = null;
      return;
    }

    const nextKey = [
      selectedPosition.lat.toFixed(4),
      selectedPosition.lon.toFixed(4),
      companySettings.lat.toFixed(4),
      companySettings.lon.toFixed(4),
    ].join(":");

    const now = Date.now();
    const previousRequest = companyRouteRequestRef.current;
    if (
      previousRequest
      && now - previousRequest.requestedAt < COMPANY_ROUTE_REFRESH_MS
      && distanceMeters(
        { lat: previousRequest.lat, lon: previousRequest.lon },
        { lat: selectedPosition.lat, lon: selectedPosition.lon },
      ) < COMPANY_ROUTE_REFRESH_DISTANCE_METERS
    ) {
      return;
    }

    companyRouteAbortRef.current?.abort();
    const controller = new AbortController();
    companyRouteAbortRef.current = controller;
    companyRouteKeyRef.current = nextKey;
    companyRouteRequestRef.current = {
      lat: selectedPosition.lat,
      lon: selectedPosition.lon,
      requestedAt: now,
    };

    void fetchCompanyRoute(token, selectedPosition.lat, selectedPosition.lon, controller.signal)
      .then((response) => {
        if (controller.signal.aborted || companyRouteKeyRef.current !== nextKey) {
          return;
        }

        setCompanyRouteSummary(response.item);
      })
      .catch((error) => {
        if (controller.signal.aborted || (error instanceof DOMException && error.name === "AbortError")) {
          return;
        }

        companyRouteKeyRef.current = null;
        companyRouteRequestRef.current = null;
        setCompanyRouteSummary(null);
      })
      .finally(() => {
        if (companyRouteAbortRef.current === controller) {
          companyRouteAbortRef.current = null;
        }
      });
  }, [companySettings, isDocumentVisible, selectedPosition, selectedPositionDetailsEnabled, token]);

  useEffect(() => () => {
    companyRouteAbortRef.current?.abort();
  }, []);

  useEffect(() => {
    if (isEditVehicleFormOpen) {
      return;
    }

    const sourceVehicle = vehicles.find((vehicle) => vehicle.id === selectedVehicleId) ?? null;
    if (!sourceVehicle) {
      setEditVehicleName("");
      setEditVehiclePlateNumber("");
      setEditVehicleColorKey(DEFAULT_VEHICLE_COLOR_KEY);
      setEditVehicleKind("passenger");
      setEditVehicleInspectionDueDate("");
      setEditVehicleOilChangeDueDate("");
      setEditVehicleOilChangeOdometer("");
      setEditVehicleOilChangeIntervalKm("");
      setEditVehicleTireChangedAt("");
      setEditVehicleNextTireChangeDueDate("");
      setEditDeviceImei("");
      setEditDevicePhoneNumber("");
      return;
    }

    setEditVehicleName(sourceVehicle.name);
    setEditVehiclePlateNumber(sourceVehicle.plateNumber ?? "");
    setEditVehicleColorKey(sourceVehicle.colorKey ?? DEFAULT_VEHICLE_COLOR_KEY);
    setEditVehicleKind(sourceVehicle.vehicleKind ?? "passenger");
    setEditVehicleInspectionDueDate(normalizeInspectionDateInput(sourceVehicle.inspectionDueDate));
    setEditVehicleOilChangeDueDate(normalizeInspectionDateInput(sourceVehicle.oilChangeDueDate));
    setEditVehicleOilChangeOdometer(sourceVehicle.oilChangeOdometer != null ? String(sourceVehicle.oilChangeOdometer) : "");
    setEditVehicleOilChangeIntervalKm(sourceVehicle.oilChangeIntervalKm != null ? String(sourceVehicle.oilChangeIntervalKm) : "");
    setEditVehicleTireChangedAt(normalizeInspectionDateInput(sourceVehicle.tireChangedAt));
    setEditVehicleNextTireChangeDueDate(normalizeInspectionDateInput(sourceVehicle.nextTireChangeDueDate));
    setEditAssignedDeviceId(sourceVehicle.deviceId ?? "");
    setEditDeviceImei(sourceVehicle.imei ?? "");
    setEditDevicePhoneNumber(sourceVehicle.phoneNumber ?? "");
  }, [isEditVehicleFormOpen, selectedVehicleId, vehicles]);

  const reloadAdminData = async (currentToken: string) => {
    const [{ items: nextVehicles }, usersResponse, devicesResponse, alertsResponse, recentAlertsResponse, companySettingsResponse] = await Promise.all([
      fetchVehicles(currentToken),
      userRole === "admin" ? fetchUsers(currentToken) : Promise.resolve({ items: [] }),
      userRole === "admin" ? fetchDevices(currentToken) : Promise.resolve({ items: [] }),
      fetchActiveAlerts(currentToken),
      fetchRecentAlerts(currentToken),
      fetchCompanySettings(currentToken),
    ]);

    setVehicles(nextVehicles);
    setSelectedVehicleId((current) =>
      current && nextVehicles.some((vehicle) => vehicle.id === current) ? current : null,
    );
    setSystemUsers(usersResponse.items);
    setSystemDevices(devicesResponse.items);
    setActiveAlerts(alertsResponse.items);
    setRecentAlerts(recentAlertsResponse.items);
    setCompanySettings(companySettingsResponse.item);
    setCompanyAddressInput(companySettingsResponse.item?.addressInput ?? "");
  };

  const onLogout = () => {
    clearSession();
    setToken(null);
    setCurrentUserId(null);
    setCurrentUserEmail("");
    setCurrentUserFirstName("");
    setCurrentUserLastName("");
    setUserRole("user");
    setCanEditVehicleInspection(false);
    setSelectedVehicleId(null);
    setVehicles([]);
    setActiveAlerts([]);
    setRecentAlerts([]);
    setSystemUsers([]);
    setSystemDevices([]);
    setCompanySettings(null);
    setCompanyAddressInput("");
    setInspectionEmailSettings(null);
    setInspectionEmailRecipientsInput("");
    setInspectionEmailSettingsMessage(null);

    if (typeof window !== "undefined") {
      window.location.assign("/login");
      return;
    }

    router.replace("/login");
  };

  const onSendTestEmail = async () => {
    if (!token || userRole !== "admin" || isSendingTestEmail) {
      return;
    }

    setActionError(null);
    setIsSendingTestEmail(true);

    try {
      await sendTestTrackingEmail(token);
      window.alert("Mail testowy został wysłany na pr@visau.pl");
    } catch (error) {
      setActionError(getFriendlyLoadErrorMessage(error, "Nie udało się wysłać maila testowego."));
    } finally {
      setIsSendingTestEmail(false);
    }
  };

  const onSaveCompanySettings = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token) {
      return;
    }

    setActionError(null);
    setCompanySettingsMessage(null);

    try {
      const response = await updateCompanySettings(token, {
        address: companyAddressInput.trim(),
      });
      setCompanySettings(response.item);
      setCompanyAddressInput(response.item?.addressInput ?? "");
      companyRouteKeyRef.current = null;
      setCompanySettingsMessage("Adres firmy zapisany.");
    } catch (saveError) {
      setActionError(saveError instanceof Error ? saveError.message : "Nie udało się zapisać adresu firmy");
    }
  };

  const onSaveInspectionEmailSettings = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token || userRole !== "admin") {
      return;
    }

    setActionError(null);
    setInspectionEmailSettingsMessage(null);

    const recipients = Array.from(
      new Set(
        inspectionEmailRecipientsInput
          .split(/[\n,;]+/)
          .map((entry) => entry.trim())
          .filter(Boolean),
      ),
    );

    try {
      const response = await updateInspectionEmailSettings(token, { recipients });
      setInspectionEmailSettings(response.item);
      setInspectionEmailRecipientsInput(response.item.recipients.join("\n"));
      setInspectionEmailSettingsMessage("Adresy mailowe zapisane.");
    } catch (error) {
      setActionError(getFriendlyLoadErrorMessage(error, "Nie udało się zapisać adresów mailowych."));
    }
  };

  const openVehicleEditor = (vehicle: VehicleSummary) => {
    setIsSystemSettingsOpen(false);
    setIsVehicleFormOpen(false);
    setIsDeviceFormOpen(false);
    setSelectedVehicleId(vehicle.id);
    setEditVehicleName(vehicle.name);
    setEditVehiclePlateNumber(vehicle.plateNumber ?? "");
    setEditVehicleColorKey(vehicle.colorKey ?? DEFAULT_VEHICLE_COLOR_KEY);
    setEditVehicleKind(vehicle.vehicleKind ?? "passenger");
    setEditVehicleInspectionDueDate(normalizeInspectionDateInput(vehicle.inspectionDueDate));
    setEditVehicleOilChangeDueDate(normalizeInspectionDateInput(vehicle.oilChangeDueDate));
    setEditVehicleOilChangeOdometer(vehicle.oilChangeOdometer != null ? String(vehicle.oilChangeOdometer) : "");
    setEditVehicleOilChangeIntervalKm(vehicle.oilChangeIntervalKm != null ? String(vehicle.oilChangeIntervalKm) : "");
    setEditVehicleTireChangedAt(normalizeInspectionDateInput(vehicle.tireChangedAt));
    setEditVehicleNextTireChangeDueDate(normalizeInspectionDateInput(vehicle.nextTireChangeDueDate));
    setEditAssignedDeviceId(vehicle.deviceId ?? "");
    setEditDeviceImei(vehicle.imei ?? "");
    setEditDevicePhoneNumber(vehicle.phoneNumber ?? "");
    setIsEditVehicleFormOpen(true);
  };

  const onCreateVehicle = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      await createVehicle(token, {
        name: vehicleName.trim(),
        plateNumber: vehiclePlateNumber.trim() || undefined,
        colorKey: vehicleColorKey,
        vehicleKind,
      });
      setVehicleName("");
      setVehiclePlateNumber("");
      setVehicleColorKey(DEFAULT_VEHICLE_COLOR_KEY);
      setVehicleKind("passenger");
      setIsVehicleFormOpen(false);
      await reloadAdminData(token);
      setAdminMessage("Pojazd dodany.");
    } catch (createError) {
      setActionError(createError instanceof Error ? createError.message : "Nie udało się dodać pojazdu");
    }
  };

  const onCreateDevice = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      await createDevice(token, {
        imei: deviceImei.trim(),
        phoneNumber: normalizePhoneNumber(devicePhoneNumber.trim()) ?? undefined,
        vehicleId: deviceVehicleId || undefined,
      });
      setDeviceImei("");
      setDevicePhoneNumber("");
      setDeviceVehicleId("");
      setIsDeviceFormOpen(false);
      await reloadAdminData(token);
      setAdminMessage("Urządzenie dodane.");
    } catch (createError) {
      setActionError(createError instanceof Error ? createError.message : "Nie udało się dodać urządzenia");
    }
  };

  const onCreateSystemUser = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      await createUser(token, {
        email: newUserEmail.trim(),
        firstName: newUserFirstName.trim(),
        lastName: newUserLastName.trim(),
        password: newUserPassword,
        role: newUserRole,
        canEditVehicleInspection: newUserCanEditVehicleInspection,
        canViewStats: newUserCanViewStats,
        vehicleIds: newUserVehicleIds,
      });
      setNewUserEmail("");
      setNewUserFirstName("");
      setNewUserLastName("");
      setNewUserPassword("");
      setNewUserRole("user");
      setNewUserCanEditVehicleInspection(false);
      setNewUserCanViewStats(false);
      setNewUserVehicleIds([]);
      await reloadAdminData(token);
      setAdminMessage("Użytkownik dodany.");
    } catch (createError) {
      setActionError(createError instanceof Error ? createError.message : "Nie udało się dodać użytkownika");
    }
  };

  const onUpdateSystemUser = async (
    userId: string,
    firstName: string,
    lastName: string,
    role: "admin" | "user",
    canEditVehicleInspectionValue: boolean,
    canViewStatsValue: boolean,
    vehicleIds: string[],
    password?: string,
  ) => {
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      const response = await updateUser(token, userId, { firstName, lastName, password, role, canEditVehicleInspection: canEditVehicleInspectionValue, canViewStats: canViewStatsValue, vehicleIds });
      setSystemUsers((current) =>
        current.map((user) => (user.id === userId ? response.item : user)),
      );
      if (currentUserId === userId) {
        setCurrentUserFirstName(response.item.firstName);
        setCurrentUserLastName(response.item.lastName);
        setCanEditVehicleInspection(response.item.canEditVehicleInspection);
        setCanViewStats(response.item.canViewStats);
        saveSession({
          token,
          user: {
            id: userId,
            email: response.item.email,
            firstName: response.item.firstName,
            lastName: response.item.lastName,
            role,
            canEditVehicleInspection: response.item.canEditVehicleInspection,
            canViewStats: response.item.canViewStats,
          },
        });
      }
      setSavedUserId(userId);
      setAdminMessage("Uprawnienia użytkownika zapisane.");
    } catch (updateError) {
      setActionError(updateError instanceof Error ? updateError.message : "Nie udało się zapisać użytkownika");
    }
  };

  const onDeleteSystemUser = async (userId: string, email: string) => {
    if (!token) {
      return;
    }

    const confirmed = window.confirm(`Usunąć użytkownika ${email}?`);
    if (!confirmed) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);
    setSavedUserId(null);

    try {
      await deleteUser(token, userId);
      await reloadAdminData(token);
      setAdminMessage("Użytkownik usunięty.");
    } catch (deleteError) {
      setActionError(deleteError instanceof Error ? deleteError.message : "Nie udało się usunąć użytkownika");
    }
  };

  const onUpdateVehicle = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!token || !selectedVehicle || !canManageVehicleInspection) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);
    setVehicleSuccessMessage(null);

    const applyInspectionUpdateLocally = (
      inspectionDueDate: string | null,
      oilChangeDueDate: string | null,
      oilChangeOdometer: number | null,
      oilChangeIntervalKm: number | null,
      tireChangedAt: string | null,
      nextTireChangeDueDate: string | null,
    ) => {
      const normalizedInspectionDueDate = normalizeInspectionDateInput(inspectionDueDate);
      const normalizedOilChangeDueDate = normalizeInspectionDateInput(oilChangeDueDate);
      const normalizedTireChangedAt = normalizeInspectionDateInput(tireChangedAt);
      const normalizedNextTireChangeDueDate = normalizeInspectionDateInput(nextTireChangeDueDate);
      const nextInspectionStatus = getLocalInspectionStatus(normalizedInspectionDueDate);
      const nextOilChangeState = getOilServiceState(
        normalizedOilChangeDueDate,
        oilChangeOdometer,
        oilChangeIntervalKm,
      );
      const nextOilChangeStatus = nextOilChangeState === "ok"
        ? "ok"
        : nextOilChangeState === "missing"
          ? "missing"
          : "due_soon";
      const nextTireChangeStatus = !normalizedTireChangedAt || !normalizedNextTireChangeDueDate
        ? "missing"
        : getLocalInspectionStatus(normalizedNextTireChangeDueDate);

      setVehicles((current) =>
        current.map((vehicle) => (
          vehicle.id === selectedVehicle.id
            ? {
                ...vehicle,
                inspectionDueDate: normalizedInspectionDueDate || null,
                inspectionStatus: nextInspectionStatus,
                oilChangeDueDate: normalizedOilChangeDueDate || null,
                oilChangeOdometer,
                oilChangeIntervalKm,
                nextOilChangeOdometer: oilChangeOdometer != null && oilChangeIntervalKm != null
                  ? oilChangeOdometer + oilChangeIntervalKm
                  : null,
                estimatedCurrentOdometer: oilChangeOdometer != null
                  ? oilChangeOdometer
                  : vehicle.estimatedCurrentOdometer ?? null,
                oilChangeStatus: nextOilChangeStatus,
                tireChangedAt: normalizedTireChangedAt || null,
                nextTireChangeDueDate: normalizedNextTireChangeDueDate || null,
                tireChangeStatus: nextTireChangeStatus,
              }
            : vehicle
        )),
      );
    };

    try {
      if (userRole !== "admin") {
        const normalizedOilChangeOdometer = editVehicleOilChangeOdometer.trim();
        const normalizedOilChangeIntervalKm = editVehicleOilChangeIntervalKm.trim();
        await updateVehicleInspection(token, selectedVehicle.id, {
          inspectionDueDate: editVehicleInspectionDueDate || null,
          oilChangeDueDate: editVehicleOilChangeDueDate || null,
          oilChangeOdometer: normalizedOilChangeOdometer ? Number(normalizedOilChangeOdometer) : null,
          oilChangeIntervalKm: normalizedOilChangeIntervalKm ? Number(normalizedOilChangeIntervalKm) : null,
          tireChangedAt: editVehicleTireChangedAt || null,
          nextTireChangeDueDate: editVehicleNextTireChangeDueDate || null,
        });
        applyInspectionUpdateLocally(
          editVehicleInspectionDueDate || null,
          editVehicleOilChangeDueDate || null,
          normalizedOilChangeOdometer ? Number(normalizedOilChangeOdometer) : null,
          normalizedOilChangeIntervalKm ? Number(normalizedOilChangeIntervalKm) : null,
          editVehicleTireChangedAt || null,
          editVehicleNextTireChangeDueDate || null,
        );
        await reloadAdminData(token);
        setIsEditVehicleFormOpen(false);
        setVehicleSuccessMessage("Terminy serwisowe zapisane.");
        return;
      }

      const normalizedOilChangeOdometer = editVehicleOilChangeOdometer.trim();
      const normalizedOilChangeIntervalKm = editVehicleOilChangeIntervalKm.trim();
      await updateVehicle(token, selectedVehicle.id, {
        name: editVehicleName.trim(),
        plateNumber: editVehiclePlateNumber.trim() || null,
        colorKey: editVehicleColorKey,
        vehicleKind: editVehicleKind,
        inspectionDueDate: editVehicleInspectionDueDate || null,
        oilChangeDueDate: editVehicleOilChangeDueDate || null,
        oilChangeOdometer: normalizedOilChangeOdometer ? Number(normalizedOilChangeOdometer) : null,
        oilChangeIntervalKm: normalizedOilChangeIntervalKm ? Number(normalizedOilChangeIntervalKm) : null,
        tireChangedAt: editVehicleTireChangedAt || null,
        nextTireChangeDueDate: editVehicleNextTireChangeDueDate || null,
      });
      applyInspectionUpdateLocally(
        editVehicleInspectionDueDate || null,
        editVehicleOilChangeDueDate || null,
        normalizedOilChangeOdometer ? Number(normalizedOilChangeOdometer) : null,
        normalizedOilChangeIntervalKm ? Number(normalizedOilChangeIntervalKm) : null,
        editVehicleTireChangedAt || null,
        editVehicleNextTireChangeDueDate || null,
      );

      const normalizedPhoneNumber = normalizePhoneNumber(editDevicePhoneNumber);
      const trimmedImei = editDeviceImei.trim();

      if (editAssignedDeviceId) {
        if (!trimmedImei) {
          throw new Error("IMEI nie może być puste dla przypisanego urządzenia");
        }

        if (selectedVehicle.deviceId && selectedVehicle.deviceId !== editAssignedDeviceId) {
          await detachDevice(token, selectedVehicle.deviceId);
        }

        await assignDeviceToVehicle(token, editAssignedDeviceId, selectedVehicle.id, {
          imei: trimmedImei,
          phoneNumber: normalizedPhoneNumber,
        });
      } else if (selectedVehicle.deviceId) {
        if (trimmedImei) {
          await updateDevice(token, selectedVehicle.deviceId, {
            imei: trimmedImei,
            phoneNumber: normalizedPhoneNumber,
            vehicleId: selectedVehicle.id,
          });
        } else {
          await detachDevice(token, selectedVehicle.deviceId);
        }
      } else if (trimmedImei) {
        await createDevice(token, {
          imei: trimmedImei,
          phoneNumber: normalizedPhoneNumber ?? undefined,
          vehicleId: selectedVehicle.id,
        });
      }

      await reloadAdminData(token);
      setIsEditVehicleFormOpen(false);
      setVehicleSuccessMessage("Pojazd zaktualizowany.");
    } catch (updateError) {
      setActionError(updateError instanceof Error ? updateError.message : "Nie udało się zapisać zmian");
    }
  };

  const onAssignSystemDevice = async (deviceId: string) => {
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      const nextVehicleId = deviceVehicleAssignments[deviceId] || null;
      await assignDeviceToVehicle(token, deviceId, nextVehicleId);
      await reloadAdminData(token);
      setAdminMessage("Powiązanie IMEI zapisane.");
    } catch (assignError) {
      setActionError(assignError instanceof Error ? assignError.message : "Nie udało się zapisać powiązania IMEI");
    }
  };

  const onDeleteSystemDevice = async (deviceId: string, imei: string) => {
    if (!token) {
      return;
    }

    const confirmed = window.confirm(`Usunąć numer IMEI ${imei}?`);
    if (!confirmed) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      await deleteDevice(token, deviceId);
      await reloadAdminData(token);
      setAdminMessage("IMEI usunięty.");
    } catch (deleteError) {
      setActionError(deleteError instanceof Error ? deleteError.message : "Nie udało się usunąć IMEI");
    }
  };

  const onDeleteVehicle = async () => {
    if (!token || !selectedVehicle) {
      return;
    }

    const confirmed = window.confirm(`Usunąć pojazd ${selectedVehicle.name}?`);
    if (!confirmed) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      const removedVehicleId = selectedVehicle.id;
      await deleteVehicle(token, selectedVehicle.id);
      setVehicles((current) => current.filter((vehicle) => vehicle.id !== removedVehicleId));
      setSelectedVehicleId(null);
      setHistory([]);
      setPlaybackTimestamp(null);
      setAdminMessage("Pojazd usunięty.");
    } catch (deleteError) {
      setActionError(deleteError instanceof Error ? deleteError.message : "Nie udało się usunąć pojazdu");
    }
  };

  const onAcknowledgeAlert = async (alertId: string) => {
    if (!token) {
      return;
    }

    setActionError(null);
    setAdminMessage(null);

    try {
      const response = await acknowledgeAlert(token, alertId);
      setActiveAlerts((current) => current.filter((alert) => alert.id !== alertId));
      setRecentAlerts((current) => current.map((alert) =>
        alert.id === alertId
          ? { ...alert, acknowledgedAt: response.item.acknowledgedAt }
          : alert,
      ));
      setAdminMessage("Informacja oznaczona jako odczytana.");
    } catch (ackError) {
      setActionError(ackError instanceof Error ? ackError.message : "Nie udało się potwierdzić informacji");
    }
  };

  const loadHistoryRange = useCallback(async (
    rangeFrom: string,
    rangeTo: string,
    options?: {
      autoStartPlayback?: boolean;
      activateTimeline?: boolean;
      emptyMessage?: string;
      singlePointMessage?: string;
      showTimelineWhenEmpty?: boolean;
      fetchFromIso?: string;
      fetchToIso?: string;
    },
  ) => {
    if (!token || !selectedVehicleId) {
      return false;
    }

    const fromMs = getDateTimeLocalTimestamp(rangeFrom);
    const toMs = getDateTimeLocalTimestamp(rangeTo);
    if (Number.isNaN(fromMs) || Number.isNaN(toMs)) {
      setActionError("Ustaw poprawną datę i godzinę zakresu historii.");
      return false;
    }
    if (fromMs > toMs) {
      setActionError("Data 'Od' nie może być późniejsza niż 'Do'.");
      return false;
    }
    if (toMs - fromMs > MAX_HISTORY_RANGE_MS) {
      setActionError("Zakres historii może obejmować maksymalnie 48 godzin.");
      return false;
    }

    try {
      const fetchFromIso = options?.fetchFromIso ?? toIsoFromDateTimeLocalValue(rangeFrom);
      const fetchToIso = options?.fetchToIso ?? toIsoFromDateTimeLocalValue(rangeTo);
      const requestKey = `${selectedVehicleId}|${fetchFromIso}|${fetchToIso}`;
      historyRequestKeyRef.current = requestKey;
      const response = await fetchVehicleHistory(
        token,
        selectedVehicleId,
        fetchFromIso,
        fetchToIso,
      );
      const nextHistory = sortHistoryPoints(response.items);
      setHistory(nextHistory);
      setPlaybackDirection("forward");
      setIsPlaybackRunning((options?.autoStartPlayback ?? true) && nextHistory.length > 1);
      setLoadError(null);
      setIsTimelineVisible(nextHistory.length > 0 || options?.showTimelineWhenEmpty === true);
      setIsTimelineActivated(options?.activateTimeline === true && nextHistory.length > 0);
      setPlaybackTimestamp(getPlaybackStartTimestamp(nextHistory, rangeFrom, "forward", skipStopsDuringPlayback));
      if (nextHistory.length > 0) {
        setHistoryFocusNonce((current) => current + 1);
      }
      if (nextHistory.length === 0) {
        setActionError(options?.emptyMessage ?? "Brak historii w wybranym zakresie.");
      } else if (nextHistory.length === 1) {
        setActionError(options?.singlePointMessage ?? "W wybranym zakresie jest tylko jeden punkt historii.");
      } else {
        setActionError(null);
      }
      return nextHistory.length > 0;
    } catch (historyError) {
      historyRequestKeyRef.current = null;
      setLoadError(getFriendlyLoadErrorMessage(historyError, "Nie udało się wczytać historii pojazdu."));
      setIsTimelineVisible(false);
      setIsPlaybackRunning(false);
      return false;
    }
  }, [selectedVehicleId, skipStopsDuringPlayback, token]);

  const onToggleTimeline = async () => {
    setActionError(null);
    setAlertPlaybackRange(null);
    await loadHistoryRange(from, to);
  };

  useEffect(() => {
    const defaultRange = defaultHistoryRangeRef.current;

    if (
      !selectedVehicleId
      || !token
      || isTimelineVisible
      || defaultRange?.vehicleId !== selectedVehicleId
      || defaultRange.from !== from
      || defaultRange.to !== to
      || (isMobileViewport && !isMobileHistoryOpen)
    ) {
      return;
    }

    void loadHistoryRange(from, to, {
      autoStartPlayback: false,
      emptyMessage: "Brak historii z ostatnich 8 godzin.",
      singlePointMessage: "W ostatnich 8 godzinach jest tylko jeden punkt historii.",
      showTimelineWhenEmpty: !isMobileViewport,
    });
  }, [from, isMobileHistoryOpen, isMobileViewport, isTimelineVisible, loadHistoryRange, selectedVehicleId, to, token]);

  useEffect(() => {
    if (
      !pendingAlertPlayback
      || !token
      || selectedVehicleId !== pendingAlertPlayback.vehicleId
    ) {
      return;
    }

    let cancelled = false;

    const loadAlertPlayback = async () => {
      setFrom(pendingAlertPlayback.from);
      setTo(pendingAlertPlayback.to);
      setIsDetailsPanelOpen(true);
      setActionError(null);

      const loaded = await loadHistoryRange(pendingAlertPlayback.from, pendingAlertPlayback.to, {
        autoStartPlayback: false,
        emptyMessage: "Brak danych GPS dla przekroczenia prędkości.",
        singlePointMessage: "Dla przekroczenia prędkości dostępny jest tylko jeden punkt GPS.",
        fetchFromIso: pendingAlertPlayback.fetchFromIso,
        fetchToIso: pendingAlertPlayback.fetchToIso,
      });

      if (cancelled) {
        return;
      }

      if (loaded) {
        setAlertPlaybackRange({
          vehicleId: pendingAlertPlayback.vehicleId,
          from: pendingAlertPlayback.fromTimestamp,
          to: pendingAlertPlayback.toTimestamp,
        });
        setPlaybackDirection("forward");
        setPlaybackTimestamp(pendingAlertPlayback.fromTimestamp);
        setIsTimelineActivated(true);
        setHistoryFocusNonce((current) => current + 1);
        setIsPlaybackRunning(true);
      }

      setPendingAlertPlayback(null);
    };

    void loadAlertPlayback();

    return () => {
      cancelled = true;
    };
  }, [loadHistoryRange, pendingAlertPlayback, selectedVehicleId, token]);

  const openSpeedAlertPlayback = (alert: VehicleAlertSummary) => {
    const triggeredAt = new Date(alert.speedRecordedAt ?? alert.triggeredAt).getTime();
    if (Number.isNaN(triggeredAt)) {
      setActionError("Nieprawidłowy czas alertu prędkości.");
      return;
    }

    const fromTimestamp = triggeredAt - 3_000;
    const toTimestamp = triggeredAt + 3_000;
    setAlertPlaybackRange(null);
    setPendingAlertPlayback({
      vehicleId: alert.vehicleId,
      from: toDateTimeLocalValue(new Date(fromTimestamp).toISOString()),
      to: toDateTimeLocalValue(new Date(toTimestamp).toISOString()),
      fetchFromIso: new Date(triggeredAt - 30_000).toISOString(),
      fetchToIso: new Date(triggeredAt + 30_000).toISOString(),
      fromTimestamp,
      toTimestamp,
    });
    setIsAlertsListOpen(false);
    setIsInfoPanelOpen(false);
    handleVehicleSelection(alert.vehicleId);
  };

  const handleRecentTripSelect = useCallback(
    async (trip: VehicleTripSummary) => {
      if (!selectedVehicleId) {
        return;
      }

      const nextFrom = toDateTimeLocalValue(trip.startTime);
      const nextTo = toDateTimeLocalValue(trip.endTime);

      setAlertPlaybackRange(null);
      setFrom(nextFrom);
      setTo(nextTo);
      setIsRecentTripsOpen(false);
      setActionError(null);

      await loadHistoryRange(nextFrom, nextTo, {
        autoStartPlayback: true,
        activateTimeline: true,
        emptyMessage: "Brak historii dla wybranego kursu.",
        singlePointMessage: "Wybrany kurs zawiera tylko jeden punkt historii.",
      });
    },
    [loadHistoryRange, selectedVehicleId],
  );

  const openRecentTripsList = () => {
    if (!selectedVehicleId) {
      return;
    }

    setIsRecentTripsOpen(true);
    setRecentTrips([]);
    setRecentTripsError(null);
    setRecentTripsHasMore(false);
    setRecentTripsNextBefore(null);
    setRecentTripsCanScrollUp(false);
    setRecentTripsCanScrollDown(false);
    recentTripsPendingBottomRetryRef.current = false;
    void loadRecentTrips(selectedVehicleId, { before: new Date().toISOString() });
  };

  const updateRecentTripsScrollIndicators = useCallback(() => {
    const container = recentTripsScrollRef.current;
    if (!container) {
      setRecentTripsCanScrollUp(false);
      setRecentTripsCanScrollDown(false);
      return;
    }

    const canScroll = container.scrollHeight - container.clientHeight > 12;
    setRecentTripsCanScrollUp(canScroll && container.scrollTop > 8);
    setRecentTripsCanScrollDown(canScroll && container.scrollTop + container.clientHeight < container.scrollHeight - 8);
  }, []);

  const handleRecentTripsScroll = useCallback(() => {
    updateRecentTripsScrollIndicators();

    const container = recentTripsScrollRef.current;
    if (!container || !selectedVehicleId) {
      return;
    }

    const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 12;
    if (!isNearBottom) {
      recentTripsPendingBottomRetryRef.current = false;
      return;
    }

    if (!recentTripsHasMore || !recentTripsNextBefore || isRecentTripsLoading || isRecentTripsLoadingMore) {
      return;
    }

    if (recentTripsPendingBottomRetryRef.current) {
      return;
    }

    recentTripsPendingBottomRetryRef.current = true;
    void loadRecentTrips(selectedVehicleId, {
      append: true,
      before: recentTripsNextBefore,
    });
  }, [
    isRecentTripsLoading,
    isRecentTripsLoadingMore,
    loadRecentTrips,
    recentTripsHasMore,
    recentTripsNextBefore,
    selectedVehicleId,
    updateRecentTripsScrollIndicators,
  ]);

  useEffect(() => {
    if (!isRecentTripsOpen) {
      return;
    }

    const timer = window.setTimeout(() => {
      updateRecentTripsScrollIndicators();
    }, 40);

    return () => window.clearTimeout(timer);
  }, [isRecentTripsOpen, recentTrips, updateRecentTripsScrollIndicators]);

  const startPlayback = (direction: "forward" | "backward") => {
    if (sliderMinTimestamp == null || sliderMaxTimestamp == null) {
      return;
    }

    playbackStoppedPreviewRef.current = null;
    setPlaybackDirection(direction);
    setPlaybackTimestamp((current) => {
      let nextTimestamp = current;
      if (nextTimestamp == null) {
        nextTimestamp = direction === "backward" ? sliderMaxTimestamp : sliderMinTimestamp;
      } else if (direction === "forward" && nextTimestamp >= sliderMaxTimestamp) {
        nextTimestamp = sliderMinTimestamp;
      } else if (direction === "backward" && nextTimestamp <= sliderMinTimestamp) {
        nextTimestamp = sliderMaxTimestamp;
      }

      if (skipStopsDuringPlayback && nextTimestamp != null) {
        const resumedTimestamp = findIgnitionResumeTimestamp(history, nextTimestamp, direction);
        if (resumedTimestamp != null) {
          return resumedTimestamp;
        }
      }
      return nextTimestamp;
    });
    setIsPlaybackRunning(true);
  };

  const skipAndContinuePlayback = (direction: "forward" | "backward") => {
    if (sliderMinTimestamp == null || sliderMaxTimestamp == null) {
      return;
    }

    const stepMs = 60_000;
    playbackStoppedPreviewRef.current = null;
    playbackLastTickRef.current = null;
    setPlaybackDirection(direction);
    setPlaybackTimestamp((current) => {
      let baseTimestamp = current;
      if (baseTimestamp == null) {
        baseTimestamp = direction === "backward" ? sliderMaxTimestamp : sliderMinTimestamp;
      }

      let nextTimestamp = direction === "backward"
        ? Math.max(sliderMinTimestamp, baseTimestamp - stepMs)
        : Math.min(sliderMaxTimestamp, baseTimestamp + stepMs);

      if (skipStopsDuringPlayback) {
        const resumedTimestamp = findIgnitionResumeTimestamp(history, nextTimestamp, direction);
        if (resumedTimestamp != null) {
          nextTimestamp = resumedTimestamp;
        }
      }

      return nextTimestamp;
    });
    setHistoryFocusNonce((current) => current + 1);
    setIsPlaybackRunning(true);
  };

  const pausePlayback = () => {
    playbackStoppedPreviewRef.current = null;
    setIsPlaybackRunning(false);
  };

  const activateTimelinePlayback = (nextTimestamp: number) => {
    playbackStoppedPreviewRef.current = null;
    playbackLastTickRef.current = null;
    setIsTimelineActivated(true);
    setPlaybackDirection("forward");
    setPlaybackTimestamp(nextTimestamp);
    setHistoryFocusNonce((current) => current + 1);
    setIsPlaybackRunning(history.length > 1 && sliderMaxTimestamp != null && nextTimestamp < sliderMaxTimestamp);
  };

  const stopTimelinePlayback = () => {
    playbackStoppedPreviewRef.current = null;
    setIsPlaybackRunning(false);
    setIsTimelineVisible(false);
    setIsTimelineActivated(false);
    setAlertPlaybackRange(null);
    setHistory([]);
    setPlaybackTimestamp(null);
    setPlaybackDirection("forward");
  };

  const clearHeaderAutoCollapseTimer = () => {
    if (headerAutoCollapseTimeoutRef.current != null) {
      window.clearTimeout(headerAutoCollapseTimeoutRef.current);
      headerAutoCollapseTimeoutRef.current = null;
    }
  };

  const handleHeaderLogoClick = () => {
    clearHeaderAutoCollapseTimer();
    setIsHeaderPanelOpen(true);
    if (!isHeaderPanelHovered) {
      headerAutoCollapseTimeoutRef.current = window.setTimeout(() => {
        setIsHeaderPanelOpen(false);
        headerAutoCollapseTimeoutRef.current = null;
      }, 3000);
    }
  };

  const companyOverviewCenter = useMemo(
    () => (overviewMode === "company" && companySettings ? { lat: companySettings.lat, lon: companySettings.lon } : null),
    [companySettings, overviewMode],
  );
  const companyCenter = useMemo(
    () => (companySettings ? { lat: companySettings.lat, lon: companySettings.lon } : null),
    [companySettings],
  );
  const handleMapViewportChange = useCallback((nextBounds: {
    south: number;
    west: number;
    north: number;
    east: number;
  }) => {
    setMapViewportBounds((current) => {
      if (
        current
        && Math.abs(current.south - nextBounds.south) < 1e-7
        && Math.abs(current.west - nextBounds.west) < 1e-7
        && Math.abs(current.north - nextBounds.north) < 1e-7
        && Math.abs(current.east - nextBounds.east) < 1e-7
      ) {
        return current;
      }

      return nextBounds;
    });
  }, []);
  const handleInspectionNoticeClick = useCallback((vehicleId: string) => {
    const vehicle = vehicles.find((candidate) => candidate.id === vehicleId);
    if (vehicle) {
      openVehicleEditor(vehicle);
    }
  }, [vehicles]);
  if (!token) {
    return null;
  }

  const overlayRoot = typeof document !== "undefined" ? document.body : null;

  return (
    <main className="brand-shell h-[100dvh] overflow-hidden p-3 md:min-h-screen md:h-auto md:overflow-visible md:p-4">
      <div className="brand-map-background">
        <DynamicMap
          vehicles={displayVehicles}
          animatedVehiclePosition={animatedVehiclePosition}
          activeVehicleId={selectedVehicleId}
          focusVehicleKey={selectedVehicleId && vehicleFocusNonce > 0 ? `${selectedVehicleId}:${vehicleFocusNonce}` : null}
          suppressVehicleAutoCenter={suppressVehicleAutoCenter}
          historyFocusKey={selectedVehicleId && isTimelineVisible && isTimelineActivated ? `${selectedVehicleId}:${historyFocusNonce}` : null}
          isBottomPanelExpanded={activeMobileSection !== null}
          closePopupKey={isSelectedVehicleMenuOpen ? "vehicle-menu-open" : "vehicle-menu-closed"}
          history={history}
          playbackTimestamp={playbackTimestamp}
          playbackDirection={playbackDirection}
          showHistoryPath={isTimelineVisible && isTimelineActivated}
          overviewKey={dailyOverviewKey}
          overviewMode={overviewMode}
          overviewVehicleIds={overviewMode === "warsaw" ? warsawVehicleIds : null}
          companyCenter={companyCenter}
          companyOverviewCenter={companyOverviewCenter}
          tileMode={mapTileMode}
          popupAddress={selectedPositionAddress}
          popupAddressLoading={selectedPositionAddressLoading}
          companyDistanceKm={companyRouteSummary?.distanceKm}
          companyDurationMinutes={companyRouteSummary?.durationMinutes}
          onTileModeChange={setMapTileMode}
          onViewportChange={handleMapViewportChange}
          onVehicleSelect={handleVehicleSelection}
          onVehiclePopupOpen={handleVehiclePopupOpen}
          onVehiclePopupClose={handleVehiclePopupClose}
          onInspectionNoticeClick={canManageVehicleInspection ? handleInspectionNoticeClick : undefined}
        />
      </div>
      {isSystemSettingsOpen && overlayRoot ? createPortal((
        <div
          className="fixed inset-0 z-[920] flex items-start justify-center overflow-y-auto bg-slate-950/48 px-3 py-4 backdrop-blur-sm md:items-center md:py-6"
          onClick={() => setIsSystemSettingsOpen(false)}
        >
          <div
            className="panel relative my-auto w-full max-w-5xl overflow-hidden rounded-[2rem] p-4 shadow-panel md:p-5"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setIsSystemSettingsOpen(false)}
              className="absolute right-4 top-4 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-lg font-semibold text-ink"
              aria-label="Zamknij"
            >
              ×
            </button>
            <div className="pr-12">
              <p className="text-xs uppercase tracking-[0.3em] text-sky">Admin</p>
              <h3 className="mt-2 text-2xl font-bold text-ink">Ustawienia systemu</h3>
            </div>
            <div className="visible-scrollbar mt-5 max-h-[calc(100dvh-8.5rem)] overflow-y-auto pr-1 md:max-h-[calc(100dvh-12rem)]">
              <div className="flex flex-wrap gap-2">
                {[
                  { key: "users", label: "Użytkownicy" },
                  { key: "vehicles", label: "Samochody" },
                  { key: "devices", label: "Numery IMEI" },
                  { key: "company", label: "Adres firmy" },
                  { key: "inspectionEmail", label: "Maile przeglądów" },
                ].map((tab) => (
                  <button
                    key={tab.key}
                    type="button"
                    onClick={() => setSystemSettingsTab(tab.key as "users" | "vehicles" | "devices" | "company" | "inspectionEmail")}
                    className={`rounded-full px-4 py-2 text-sm font-semibold transition ${
                      systemSettingsTab === tab.key
                        ? "bg-slate-900 text-white"
                        : "border border-slate-200 bg-white text-ink"
                    }`}
                  >
                    {tab.label}
                  </button>
                ))}
              </div>
              {systemSettingsTab === "users" ? (
                <div className="mt-5 grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]">
                <form onSubmit={onCreateSystemUser} className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="text-sm font-semibold text-ink">Dodaj użytkownika</div>
                  <div className="mt-3 space-y-2.5">
                    <input
                      type="email"
                      placeholder="Email"
                      value={newUserEmail}
                      onChange={(event) => setNewUserEmail(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                      required
                    />
                    <div className="grid gap-2 sm:grid-cols-2">
                      <input
                        type="text"
                        placeholder="Imię"
                        value={newUserFirstName}
                        onChange={(event) => setNewUserFirstName(event.target.value)}
                        className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                        required
                      />
                      <input
                        type="text"
                        placeholder="Nazwisko"
                        value={newUserLastName}
                        onChange={(event) => setNewUserLastName(event.target.value)}
                        className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                        required
                      />
                    </div>
                    <input
                      type="password"
                      placeholder="Hasło"
                      value={newUserPassword}
                      onChange={(event) => setNewUserPassword(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                      minLength={8}
                      required
                    />
                    <select
                      value={newUserRole}
                      onChange={(event) => setNewUserRole(event.target.value as "admin" | "user")}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                    >
                      <option value="user">User</option>
                      <option value="admin">Admin</option>
                    </select>
                    <label className="flex items-center gap-2 rounded-2xl border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-ink">
                      <input
                        type="checkbox"
                        checked={newUserCanEditVehicleInspection}
                        onChange={(event) => setNewUserCanEditVehicleInspection(event.target.checked)}
                        className="h-4 w-4 rounded border-slate-300"
                      />
                      Może edytować termin przeglądu
                    </label>
                    <label className="flex items-center gap-2 rounded-2xl border border-mint/30 bg-mint/10 px-3.5 py-2.5 text-sm text-ink">
                      <input
                        type="checkbox"
                        checked={newUserCanViewStats}
                        onChange={(event) => setNewUserCanViewStats(event.target.checked)}
                        className="h-4 w-4 rounded border-mint/40"
                      />
                      Ma dostęp do Stats
                    </label>
                  </div>
                  <div className="mt-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-steel">
                    Dostęp do pojazdów
                  </div>
                  <div className="mt-2 flex max-h-[280px] flex-wrap gap-2 overflow-y-auto pr-1">
                    {vehicles.map((vehicle) => {
                      const isActive = newUserVehicleIds.includes(vehicle.id);
                      return (
                        <button
                          key={vehicle.id}
                          type="button"
                          onClick={() =>
                            setNewUserVehicleIds((current) =>
                              current.includes(vehicle.id)
                                ? current.filter((currentId) => currentId !== vehicle.id)
                                : [...current, vehicle.id],
                            )
                          }
                          className={`rounded-full border px-3 py-1 text-xs font-medium transition ${
                            isActive
                              ? "border-slate-900 bg-slate-900 text-white"
                              : "border-slate-200 bg-white text-ink"
                          }`}
                        >
                          {vehicle.name}
                        </button>
                      );
                    })}
                  </div>
                  <button
                    type="submit"
                    className="mt-4 w-full rounded-2xl bg-ink px-4 py-2.5 text-sm font-semibold text-white"
                  >
                    Dodaj użytkownika
                  </button>
                </form>

                <div className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-semibold text-ink">Użytkownicy i uprawnienia</div>
                    <div className="rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold text-white">
                      {systemUsers.length}
                    </div>
                  </div>
                  <div className="mt-4 h-[348px] overflow-y-auto px-1 pt-3">
                    <div className="grid gap-3 md:grid-cols-2">
                      {systemUsers.map((user) => (
                        <UserAccessCard
                          key={user.id}
                          currentUserId={currentUserId ?? ""}
                          user={user}
                          vehicles={vehicles}
                          isSaved={savedUserId === user.id}
                          onSave={onUpdateSystemUser}
                          onDelete={onDeleteSystemUser}
                        />
                      ))}
                    </div>
                  </div>
                </div>
                </div>
              ) : null}

              {systemSettingsTab === "vehicles" ? (
                <div className="mt-5 grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]">
                <form onSubmit={onCreateVehicle} className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="text-sm font-semibold text-ink">Dodaj samochód</div>
                  <div className="mt-3 space-y-2.5">
                    <input
                      type="text"
                      placeholder="Nazwa pojazdu"
                      value={vehicleName}
                      onChange={(event) => setVehicleName(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                      required
                    />
                    <input
                      type="text"
                      placeholder="Nr rej."
                      value={vehiclePlateNumber}
                      onChange={(event) => setVehiclePlateNumber(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                    />
                    <div className="grid grid-cols-2 gap-2">
                      <button
                        type="button"
                        onClick={() => setVehicleKind("passenger")}
                        className={`h-10 rounded-2xl border text-sm font-semibold transition ${
                          vehicleKind === "passenger"
                            ? "border-slate-900 bg-slate-900 text-white"
                            : "border-slate-200 bg-white text-ink"
                        }`}
                      >
                        Osobowe
                      </button>
                      <button
                        type="button"
                        onClick={() => setVehicleKind("delivery")}
                        className={`h-10 rounded-2xl border text-sm font-semibold transition ${
                          vehicleKind === "delivery"
                            ? "border-slate-900 bg-slate-900 text-white"
                            : "border-slate-200 bg-white text-ink"
                        }`}
                      >
                        Dostawcze
                      </button>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {VEHICLE_COLOR_OPTIONS.map((option) => (
                        <button
                          key={option.key}
                          type="button"
                          onClick={() => setVehicleColorKey(option.key)}
                          className={`h-7 w-7 rounded-full border-2 transition ${
                            vehicleColorKey === option.key ? "scale-110 border-slate-950 shadow-md" : "border-white/80 shadow-sm"
                          }`}
                          style={{ backgroundColor: option.hex }}
                          aria-label={option.label}
                          title={option.label}
                        />
                      ))}
                    </div>
                  </div>
                  <button
                    type="submit"
                    className="mt-4 w-full rounded-2xl bg-ink px-4 py-2.5 text-sm font-semibold text-white"
                  >
                    Dodaj samochód
                  </button>
                </form>

                <div className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-semibold text-ink">Samochody w systemie</div>
                    <div className="rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold text-white">
                      {vehicles.length}
                    </div>
                  </div>
                  <div className="visible-scrollbar mt-4 h-[348px] overflow-y-scroll pr-2 pl-1 pt-2">
                    <div className="grid gap-3 md:grid-cols-2">
                      {vehicles.map((vehicle) => (
                        <div key={vehicle.id} className="rounded-[1.4rem] border border-slate-200 bg-white/80 p-4">
                          <div className="flex items-start justify-between gap-3">
                            <div className="min-w-0">
                              <div
                                className="truncate text-sm font-semibold"
                                style={{ color: getVehicleColorHex(vehicle.colorKey) }}
                              >
                                {vehicle.name}
                              </div>
                              <div className="mt-1 text-xs text-steel">
                                {vehicle.vehicleKind === "delivery" ? "Dostawcze" : "Osobowe"}
                                {vehicle.plateNumber ? ` | ${vehicle.plateNumber}` : ""}
                              </div>
                            </div>
                            <div
                              className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] ${
                                vehicle.status === "online"
                                  ? "bg-mint/15 text-mint shadow-[0_0_14px_rgba(74,222,128,0.35)]"
                                  : "bg-coral/15 text-coral shadow-[0_0_14px_rgba(251,113,133,0.35)]"
                              }`}
                            >
                              {vehicle.status === "online" ? "Online" : "Offline"}
                            </div>
                          </div>
                          <div className="mt-3 text-xs text-steel">
                            {vehicle.imei ? `IMEI: ${vehicle.imei}` : "Brak przypisanego IMEI"}
                          </div>
                          <div className="mt-1 text-xs text-steel">
                            Przegląd: {vehicle.inspectionDueDate ? formatDateOnly(vehicle.inspectionDueDate) : "Brak daty"}
                          </div>
                          <button
                            type="button"
                            onClick={() => openVehicleEditor(vehicle)}
                            className="mt-3 rounded-full border border-slate-300 px-3 py-1.5 text-[11px] font-semibold text-ink"
                          >
                            Edytuj
                          </button>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
                </div>
              ) : null}

              {systemSettingsTab === "devices" ? (
                <div className="mt-5 grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]">
                <form onSubmit={onCreateDevice} className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="text-sm font-semibold text-ink">Dodaj numer IMEI</div>
                  <div className="mt-3 space-y-2.5">
                    <input
                      type="text"
                      inputMode="numeric"
                      pattern="\d{14,17}"
                      placeholder="IMEI"
                      value={deviceImei}
                      onChange={(event) => setDeviceImei(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                      required
                    />
                    <input
                      type="text"
                      placeholder="Telefon"
                      value={devicePhoneNumber}
                      onChange={(event) => setDevicePhoneNumber(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                    />
                    <select
                      value={deviceVehicleId}
                      onChange={(event) => setDeviceVehicleId(event.target.value)}
                      className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm"
                    >
                      <option value="">Tylko do bazy, bez podpinania</option>
                      {vehicles.map((vehicle) => (
                        <option key={vehicle.id} value={vehicle.id}>
                          {getVehicleOptionLabel(vehicle)}
                        </option>
                      ))}
                    </select>
                  </div>
                  <button
                    type="submit"
                    className="mt-4 w-full rounded-2xl bg-sky px-4 py-2.5 text-sm font-semibold text-white"
                  >
                    Dodaj IMEI
                  </button>
                </form>

                <div className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-semibold text-ink">Numery IMEI w bazie</div>
                    <div className="rounded-full bg-slate-900 px-3 py-1 text-xs font-semibold text-white">
                      {systemDevices.length}
                    </div>
                  </div>
                  <div className="mt-4 max-h-[230px] overflow-y-auto pr-1">
                    <div className="grid gap-3 md:grid-cols-2">
                      {systemDevices.map((device) => {
                        const assignedVehicle = vehicles.find((vehicle) => vehicle.id === device.vehicle_id);
                        const isLinked = Boolean(assignedVehicle);

                        return (
                          <div key={device.id} className="relative rounded-[1.4rem] border border-slate-200 bg-white/80 p-4">
                            <button
                              type="button"
                              onClick={() => void onDeleteSystemDevice(device.id, device.imei)}
                              className="absolute right-2 top-2 z-10 flex h-5 w-5 items-center justify-center rounded-full bg-coral text-[13px] font-bold leading-none text-white shadow-md transition hover:scale-105"
                              aria-label={`Usuń IMEI ${device.imei}`}
                              title="Usuń IMEI"
                            >
                              ×
                            </button>
                            <div className="flex items-start justify-between gap-3">
                              <div className="min-w-0">
                                <div className="text-sm font-semibold text-ink">{device.imei}</div>
                                <div className="mt-1 text-xs text-steel">
                                  {device.phone_number ?? "Bez numeru"}
                                </div>
                              </div>
                              <div
                                className={`mt-0.5 flex shrink-0 items-center gap-1.5 rounded-full px-2 py-1 text-[11px] font-medium ${
                                  isLinked ? "bg-mint/10 text-mint" : "bg-slate-100 text-steel"
                                }`}
                                title={isLinked ? "Podłączony" : "Niepodłączony"}
                              >
                                <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="currentColor" aria-hidden="true">
                                  {isLinked ? (
                                    <path d="M10.59,13.41C11.37,14.19 12.63,14.19 13.41,13.41L18.59,8.24C19.37,7.46 19.37,6.19 18.59,5.41C17.81,4.63 16.54,4.63 15.76,5.41L12.35,8.83L10.94,7.41L14.35,4C15.91,2.44 18.44,2.44 20,4C21.56,5.56 21.56,8.09 20,9.65L14.83,14.83C13.27,16.39 10.74,16.39 9.18,14.83L9.17,14.82M13.06,16.59L9.65,20C8.09,21.56 5.56,21.56 4,20C2.44,18.44 2.44,15.91 4,14.35L9.17,9.17C10.73,7.61 13.26,7.61 14.82,9.17L14.83,9.18L13.41,10.59L13.4,10.58C12.62,9.8 11.35,9.8 10.57,10.58L5.41,15.76C4.63,16.54 4.63,17.81 5.41,18.59C6.19,19.37 7.46,19.37 8.24,18.59L11.65,15.17L13.06,16.59Z" />
                                  ) : (
                                    <>
                                      <path d="M10.59,13.41C11.37,14.19 12.63,14.19 13.41,13.41L18.59,8.24C19.37,7.46 19.37,6.19 18.59,5.41C17.81,4.63 16.54,4.63 15.76,5.41L12.35,8.83L10.94,7.41L14.35,4C15.91,2.44 18.44,2.44 20,4C21.56,5.56 21.56,8.09 20,9.65L14.83,14.83C13.27,16.39 10.74,16.39 9.18,14.83L9.17,14.82M13.06,16.59L9.65,20C8.09,21.56 5.56,21.56 4,20C2.44,18.44 2.44,15.91 4,14.35L9.17,9.17C10.73,7.61 13.26,7.61 14.82,9.17L14.83,9.18L13.41,10.59L13.4,10.58C12.62,9.8 11.35,9.8 10.57,10.58L5.41,15.76C4.63,16.54 4.63,17.81 5.41,18.59C6.19,19.37 7.46,19.37 8.24,18.59L11.65,15.17L13.06,16.59Z" />
                                      <path d="M3.27 2L2 3.27L8.73 10L10.14 8.59L3.27 2M20.73 22L22 20.73L15.19 13.92L13.78 15.33L20.73 22Z" />
                                    </>
                                  )}
                                </svg>
                                {isLinked ? <span>{assignedVehicle?.name}</span> : null}
                              </div>
                            </div>
                            <select
                              value={deviceVehicleAssignments[device.id] ?? ""}
                              onChange={(event) =>
                                setDeviceVehicleAssignments((current) => ({
                                  ...current,
                                  [device.id]: event.target.value,
                                }))
                              }
                              className="mt-3 h-9 w-full rounded-2xl border border-slate-200 bg-white px-3 text-sm"
                            >
                              <option value="">Tylko w bazie, bez podpinania</option>
                              {vehicles.map((vehicle) => (
                                <option key={vehicle.id} value={vehicle.id}>
                                  {getVehicleOptionLabel(vehicle)}
                                </option>
                              ))}
                            </select>
                            <button
                              type="button"
                              onClick={() => void onAssignSystemDevice(device.id)}
                              className="mt-3 rounded-full border border-slate-300 px-3 py-1.5 text-[11px] font-semibold text-ink"
                            >
                              Zapisz powiązanie
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>
                </div>
              ) : null}

              {systemSettingsTab === "company" ? (
                <div className="mt-5">
                  <form onSubmit={onSaveCompanySettings} className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                    <div className="text-sm font-semibold text-ink">Adres firmy</div>
                    <div className="mt-3 grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]">
                      <input
                        type="text"
                        value={companyAddressInput}
                        onChange={(event) => setCompanyAddressInput(event.target.value)}
                        placeholder="Wpisz adres firmy"
                        className="h-10 w-full rounded-2xl border border-slate-200 bg-white px-3.5 text-sm text-ink"
                      />
                      <button
                        type="submit"
                        className="rounded-2xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white"
                      >
                        Zapisz adres firmy
                      </button>
                    </div>
                    <div className="mt-3 min-h-[16px] text-[11px] leading-tight">
                      {companySettingsMessage ? (
                        <span className="font-semibold text-mint">{companySettingsMessage}</span>
                      ) : companySettings?.addressLabel ? (
                        <span className="text-steel">{companySettings.addressLabel}</span>
                      ) : null}
                    </div>
                  </form>
                </div>
              ) : null}

              {systemSettingsTab === "inspectionEmail" ? (
                <div className="mt-5">
                  <form onSubmit={onSaveInspectionEmailSettings} className="rounded-[1.5rem] border border-slate-200 bg-white/75 p-4">
                    <div className="text-sm font-semibold text-ink">Odbiorcy maili o przeglądach</div>
                    <div className="mt-1 text-xs leading-5 text-steel">
                      System wysyła mail jednokrotnie, gdy pojazd wchodzi w próg 14 dni do terminu przeglądu.
                      Wpisz jeden adres w linii lub rozdziel adresy przecinkami.
                    </div>
                    <textarea
                      value={inspectionEmailRecipientsInput}
                      onChange={(event) => setInspectionEmailRecipientsInput(event.target.value)}
                      placeholder={"ag@notebooking.pl\npr@visau.pl"}
                      className="mt-3 min-h-[180px] w-full rounded-[1.4rem] border border-slate-200 bg-white px-4 py-3 text-sm text-ink outline-none transition focus:border-sky focus:ring-2 focus:ring-sky/20"
                    />
                    <div className="mt-3 flex flex-wrap items-center justify-between gap-3">
                      <div className="min-h-[16px] text-[11px] leading-tight">
                        {inspectionEmailSettingsMessage ? (
                          <span className="font-semibold text-mint">{inspectionEmailSettingsMessage}</span>
                        ) : inspectionEmailSettings?.updatedAt ? (
                          <span className="text-steel">
                            Ostatni zapis: {formatDateTime(inspectionEmailSettings.updatedAt)}
                          </span>
                        ) : (
                          <span className="text-steel">Brak zapisanej konfiguracji.</span>
                        )}
                      </div>
                      <div className="flex flex-wrap items-center gap-2">
                        <button
                          type="button"
                          onClick={onSendTestEmail}
                          disabled={isSendingTestEmail}
                          className="inline-flex items-center gap-2 rounded-2xl border border-mint/35 bg-mint/10 px-4 py-2.5 text-sm font-semibold text-emerald-700 transition hover:bg-mint/15 disabled:cursor-wait disabled:opacity-60"
                          aria-label="Wyślij mail testowy"
                        >
                          <svg viewBox="0 0 24 24" className="h-4 w-4 fill-current" aria-hidden="true">
                            <path d="M20 8L12 13L4 8V6L12 11L20 6M20 18H4V8L12 13L20 8M20 4H4C2.89 4 2 4.89 2 6V18A2 2 0 0 0 4 20H20A2 2 0 0 0 22 18V6C22 4.89 21.1 4 20 4Z" />
                          </svg>
                          {isSendingTestEmail ? "Wysyłanie..." : "Wyślij test"}
                        </button>
                        <button
                          type="submit"
                          className="rounded-2xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white"
                        >
                          Zapisz odbiorców
                        </button>
                      </div>
                    </div>
                  </form>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      ), overlayRoot) : null}

      {isAlertsListOpen && overlayRoot ? createPortal((
        <div
          className="fixed inset-0 z-[935] flex items-start justify-center overflow-y-auto bg-slate-950/55 px-3 py-4 backdrop-blur-sm md:items-center md:py-6"
          onClick={() => setIsAlertsListOpen(false)}
        >
          <div
            className="neo-panel relative my-auto w-full max-w-4xl overflow-hidden rounded-[1.6rem] p-4 shadow-panel md:p-5"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setIsAlertsListOpen(false)}
              className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full border border-slate-400/25 bg-white/5 text-lg font-semibold text-white"
              aria-label="Zamknij listę alertów"
            >
              ×
            </button>
            <div className="pr-12">
              <p className="text-[10px] font-semibold uppercase tracking-[0.26em] text-coral">Lista alertów</p>
              <div className="mt-1 flex items-center gap-2 text-xs text-slate-300">
                <span>Ostatnie 7 dni</span>
                <span className="rounded-full bg-coral/12 px-2 py-0.5 font-semibold text-coral">{recentAlerts.length}</span>
              </div>
            </div>
            <div className="visible-scrollbar mt-4 max-h-[calc(100dvh-10rem)] overflow-auto overscroll-contain rounded-xl border border-white/10 bg-slate-950/35 p-1.5 md:max-h-[70vh]">
              {recentAlerts.length === 0 ? (
                <div className="px-3 py-8 text-center text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">
                  Brak alertów z ostatnich 7 dni
                </div>
              ) : (
                <div className="min-w-[620px] space-y-1">
                  {recentAlerts.map((alert) => (
                    <button
                      key={`alert-list-${alert.id}`}
                      type="button"
                      onClick={() => openSpeedAlertPlayback(alert)}
                      className="grid w-full grid-cols-[76px_94px_minmax(210px,1fr)_96px_84px] items-center gap-2 rounded-lg border border-white/8 bg-white/[0.035] px-2.5 py-1.5 text-left text-[11px] text-white transition hover:border-sky/35 hover:bg-sky/10"
                      aria-label={`Odtwórz alert ${alert.vehicleName}, ${Math.round(alert.speed)} km/h`}
                    >
                      <span className="truncate font-bold text-cyan-100">{alert.vehicleName}</span>
                      <span className="font-semibold text-coral">{Math.round(alert.speed)} km/h</span>
                      <span className="truncate text-slate-300">{formatDateTime(alert.speedRecordedAt ?? alert.triggeredAt)}</span>
                      <span className={`text-[9px] font-semibold uppercase tracking-[0.12em] ${alert.acknowledgedAt ? "text-mint" : "text-amber"}`}>
                        {alert.acknowledgedAt ? "Odczytany" : "Nowy"}
                      </span>
                      <span className="text-right text-[9px] font-semibold uppercase tracking-[0.12em] text-sky">Playback</span>
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      ), overlayRoot) : null}

      {isRecentTripsOpen && overlayRoot ? createPortal((
        <div
          className="fixed inset-0 z-[930] flex items-start justify-center overflow-y-auto bg-slate-950/55 px-3 py-4 backdrop-blur-sm md:items-center md:py-6"
          onClick={() => setIsRecentTripsOpen(false)}
        >
          <div
            className="panel relative my-auto w-full max-w-5xl rounded-[2rem] p-4 shadow-panel md:p-5"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setIsRecentTripsOpen(false)}
              className="absolute right-4 top-4 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-lg font-semibold text-ink"
              aria-label="Zamknij listę kursów"
            >
              ×
            </button>
            <div className="pr-12">
              <p className="text-xs uppercase tracking-[0.3em] text-sky">Kursy pojazdu</p>
              <h3 className="mt-2 text-2xl font-bold text-ink">
                {selectedVehicle?.name ?? "Wybrany pojazd"}
              </h3>
              <p className="mt-1 text-sm text-steel">Ostatnie kursy z ostatnich 14 dni.</p>
            </div>
            <div className="relative mt-5">
            <div
              ref={recentTripsScrollRef}
              onScroll={handleRecentTripsScroll}
              className="visible-scrollbar max-h-[calc(100dvh-10rem)] overflow-auto rounded-[1.5rem] border border-slate-200 bg-white/75 p-3"
            >
              {isRecentTripsLoading ? (
                <div className="px-2 py-10 text-center text-sm font-semibold text-steel">Ładowanie kursów...</div>
              ) : recentTripsError && recentTrips.length === 0 ? (
                <div className="px-2 py-10 text-center text-sm font-semibold text-coral">{recentTripsError}</div>
              ) : recentTrips.length === 0 ? (
                <div className="px-2 py-10 text-center text-sm font-semibold text-steel">Brak kursów dla wybranego pojazdu.</div>
              ) : (
                <table className="min-w-[860px] w-full border-separate border-spacing-y-1.5 text-left">
                  <thead>
                    <tr className="text-[11px] uppercase tracking-[0.18em] text-steel">
                      <th className="px-3 py-1">Start</th>
                      <th className="px-3 py-1">Stop</th>
                      <th className="px-3 py-1">Od</th>
                      <th className="px-3 py-1">Do</th>
                      <th className="px-3 py-1">Min</th>
                      <th className="px-3 py-1">Km</th>
                    </tr>
                  </thead>
                  <tbody>
                    {recentTrips.map((trip) => {
                      return (
                        <tr
                          key={trip.tripId}
                          onClick={() => {
                            void handleRecentTripSelect(trip);
                          }}
                          className="cursor-pointer overflow-hidden rounded-[1rem] bg-slate-950/70 text-[12px] text-white transition hover:bg-slate-900/85"
                        >
                          <td className="rounded-l-[1rem] px-3 py-2.5 align-top">
                            <div className="font-semibold text-cyan-100">{toTripStreetLabel(trip.startLabel)}</div>
                          </td>
                          <td className="px-3 py-2.5 align-top">
                            <div className="font-semibold text-cyan-100">{toTripStreetLabel(trip.endLabel)}</div>
                          </td>
                          <td className="px-3 py-2.5 align-top text-slate-200">{formatDateTime(trip.startTime)}</td>
                          <td className="px-3 py-2.5 align-top text-slate-200">{formatDateTime(trip.endTime)}</td>
                          <td className="px-3 py-2.5 align-top font-semibold text-mint">{trip.durationMinutes ?? "—"}</td>
                          <td className="rounded-r-[1rem] px-3 py-2.5 align-top font-semibold text-mint">
                            {trip.distanceKm != null ? trip.distanceKm.toFixed(1) : "—"}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              )}
              {recentTripsError && recentTrips.length > 0 ? (
                <div className="px-2 py-3 text-center text-xs font-semibold text-coral">
                  {recentTripsError} Przewiń ponownie, aby spróbować jeszcze raz.
                </div>
              ) : null}
              {isRecentTripsLoadingMore ? (
                <div className="px-2 py-3 text-center text-xs font-semibold uppercase tracking-[0.18em] text-steel">
                  Dociągam starsze kursy...
                </div>
              ) : null}
            </div>
            {recentTrips.length > 10 ? (
              <div className="pointer-events-none absolute right-1 top-1/2 flex -translate-y-1/2 flex-col items-center gap-2 text-white/80">
                <span className={`${recentTripsCanScrollUp ? "opacity-100" : "opacity-35"} rounded-full bg-slate-950/70 p-1 shadow-lg`}>
                  <svg viewBox="0 0 24 24" className="h-4 w-4" fill="currentColor" aria-hidden="true">
                    <path d="m7 14 5-5 5 5H7Z" />
                  </svg>
                </span>
                <span className={`${recentTripsCanScrollDown || recentTripsHasMore ? "opacity-100" : "opacity-35"} rounded-full bg-slate-950/70 p-1 shadow-lg`}>
                  <svg viewBox="0 0 24 24" className="h-4 w-4" fill="currentColor" aria-hidden="true">
                    <path d="m7 10 5 5 5-5H7Z" />
                  </svg>
                </span>
              </div>
            ) : null}
            </div>
          </div>
        </div>
      ), overlayRoot) : null}

      {isVehicleFormOpen && overlayRoot ? createPortal((
        <div
          className="fixed inset-0 z-[900] flex items-center justify-center bg-slate-950/45 px-3 backdrop-blur-sm"
          onClick={() => setIsVehicleFormOpen(false)}
        >
          <div
            className="panel relative w-full max-w-lg rounded-[2rem] p-5 shadow-panel"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setIsVehicleFormOpen(false)}
              className="absolute right-4 top-4 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-lg font-semibold text-ink"
              aria-label="Zamknij"
            >
              ×
            </button>
            <div className="pr-12">
              <p className="text-xs uppercase tracking-[0.3em] text-sky">Nowy pojazd</p>
              <h3 className="mt-2 text-2xl font-bold text-ink">Dodaj pojazd</h3>
            </div>
            <form onSubmit={onCreateVehicle} className="mt-5 space-y-3">
              <input
                type="text"
                placeholder="Nazwa pojazdu"
                value={vehicleName}
                onChange={(event) => setVehicleName(event.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm"
                required
              />
              <input
                type="text"
                placeholder="Nr rej."
                value={vehiclePlateNumber}
                onChange={(event) => setVehiclePlateNumber(event.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm"
              />
              <div>
                <div className="mb-2 text-xs font-semibold uppercase tracking-[0.2em] text-steel">
                  Typ pojazdu
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <button
                    type="button"
                    onClick={() => setVehicleKind("passenger")}
                    className={`h-10 rounded-2xl border text-sm font-semibold transition ${
                      vehicleKind === "passenger"
                        ? "border-slate-900 bg-slate-900 text-white"
                        : "border-slate-200 bg-white text-ink"
                    }`}
                  >
                    Osobowe
                  </button>
                  <button
                    type="button"
                    onClick={() => setVehicleKind("delivery")}
                    className={`h-10 rounded-2xl border text-sm font-semibold transition ${
                      vehicleKind === "delivery"
                        ? "border-slate-900 bg-slate-900 text-white"
                        : "border-slate-200 bg-white text-ink"
                    }`}
                  >
                    Dostawcze
                  </button>
                </div>
              </div>
              <div>
                <div className="mb-3 text-xs font-semibold uppercase tracking-[0.2em] text-steel">
                  Kolor pojazdu
                </div>
                <div className="flex flex-wrap gap-2">
                  {VEHICLE_COLOR_OPTIONS.map((option) => (
                    <button
                      key={option.key}
                      type="button"
                      onClick={() => setVehicleColorKey(option.key)}
                      className={`h-7 w-7 rounded-full border-2 transition ${
                        vehicleColorKey === option.key ? "scale-110 border-slate-950 shadow-md" : "border-white/80 shadow-sm"
                      }`}
                      style={{ backgroundColor: option.hex }}
                      aria-label={option.label}
                      title={option.label}
                    />
                  ))}
                </div>
              </div>
              <button
                type="submit"
                className="w-full rounded-2xl bg-ink px-4 py-3 text-sm font-semibold text-white"
              >
                Dodaj pojazd
              </button>
            </form>
          </div>
        </div>
      ), overlayRoot) : null}

      {isDeviceFormOpen && overlayRoot ? createPortal((
        <div
          className="fixed inset-0 z-[900] flex items-center justify-center bg-slate-950/45 px-3 backdrop-blur-sm"
          onClick={() => setIsDeviceFormOpen(false)}
        >
          <div
            className="panel relative w-full max-w-lg rounded-[2rem] p-5 shadow-panel"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setIsDeviceFormOpen(false)}
              className="absolute right-4 top-4 flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-lg font-semibold text-ink"
              aria-label="Zamknij"
            >
              ×
            </button>
            <div className="pr-12">
              <p className="text-xs uppercase tracking-[0.3em] text-sky">Nowe urządzenie</p>
              <h3 className="mt-2 text-2xl font-bold text-ink">Dodaj IMEI</h3>
            </div>
            <form onSubmit={onCreateDevice} className="mt-5 space-y-3">
              <input
                type="text"
                inputMode="numeric"
                pattern="\d{14,17}"
                placeholder="IMEI"
                value={deviceImei}
                onChange={(event) => setDeviceImei(event.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm"
                required
              />
              <input
                type="text"
                placeholder="Telefon"
                value={devicePhoneNumber}
                onChange={(event) => setDevicePhoneNumber(event.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm"
              />
              <select
                value={deviceVehicleId}
                onChange={(event) => setDeviceVehicleId(event.target.value)}
                className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm"
              >
                <option value="">Tylko do bazy, bez podpinania</option>
                {vehicles.map((vehicle) => (
                  <option key={vehicle.id} value={vehicle.id}>
                    {getVehicleOptionLabel(vehicle)}
                  </option>
                ))}
              </select>
              <button
                type="submit"
                className="w-full rounded-2xl bg-sky px-4 py-3 text-sm font-semibold text-white"
              >
                Dodaj IMEI
              </button>
            </form>
          </div>
        </div>
      ), overlayRoot) : null}

      <VehicleEditModal
        isOpen={isEditVehicleFormOpen}
        overlayRoot={overlayRoot}
        panelRef={editVehicleOverlayPanelRef}
        selectedVehicle={selectedVehicle}
        userRole={userRole}
        onClose={() => setIsEditVehicleFormOpen(false)}
        onSubmit={onUpdateVehicle}
        onDeleteVehicle={onDeleteVehicle}
        editVehicleInspectionDueDate={editVehicleInspectionDueDate}
        setEditVehicleInspectionDueDate={setEditVehicleInspectionDueDate}
        editVehicleOilChangeDueDate={editVehicleOilChangeDueDate}
        setEditVehicleOilChangeDueDate={setEditVehicleOilChangeDueDate}
        editVehicleOilChangeOdometer={editVehicleOilChangeOdometer}
        setEditVehicleOilChangeOdometer={setEditVehicleOilChangeOdometer}
        editVehicleOilChangeIntervalKm={editVehicleOilChangeIntervalKm}
        setEditVehicleOilChangeIntervalKm={setEditVehicleOilChangeIntervalKm}
        editVehicleTireChangedAt={editVehicleTireChangedAt}
        setEditVehicleTireChangedAt={setEditVehicleTireChangedAt}
        editVehicleNextTireChangeDueDate={editVehicleNextTireChangeDueDate}
        setEditVehicleNextTireChangeDueDate={setEditVehicleNextTireChangeDueDate}
        formatMileageKm={formatMileageKm}
        systemDevices={systemDevices}
        editDeviceImei={editDeviceImei}
        setEditDeviceImei={setEditDeviceImei}
        editAssignedDeviceId={editAssignedDeviceId}
        setEditAssignedDeviceId={setEditAssignedDeviceId}
        editDevicePhoneNumber={editDevicePhoneNumber}
        setEditDevicePhoneNumber={setEditDevicePhoneNumber}
        editVehicleName={editVehicleName}
        setEditVehicleName={setEditVehicleName}
        editVehiclePlateNumber={editVehiclePlateNumber}
        setEditVehiclePlateNumber={setEditVehiclePlateNumber}
        editVehicleKind={editVehicleKind}
        setEditVehicleKind={setEditVehicleKind}
        editVehicleColorKey={editVehicleColorKey}
        setEditVehicleColorKey={setEditVehicleColorKey}
        previewVehicleColor={previewVehicleColor}
        shiftHex={shiftHex}
        getDeviceByImei={getDeviceByImei}
        getDeviceById={getDeviceById}
      />

      <StatsPanel
        isOpen={isStatsPanelOpen}
        error={vehicleStatsError}
        overview={vehicleStatsOverview}
        onClose={() => setIsStatsPanelOpen(false)}
        onSelectVehicle={(vehicleId) => {
          handleVehicleSelection(vehicleId);
          setIsStatsPanelOpen(false);
        }}
      />

      <div className="brand-shell__content pointer-events-none grid min-h-[calc(100vh-1.5rem)] gap-3 md:grid-cols-[320px_minmax(0,1fr)] md:items-start md:grid-rows-[auto] xl:grid-cols-[320px_minmax(0,1fr)_360px]">
        <aside className="pointer-events-none mx-3 mt-3 flex w-auto max-h-[calc(100dvh-24px)] max-w-none flex-col gap-3 overflow-y-auto pr-0 md:ml-0 md:mr-0 md:mt-0 md:w-auto md:max-h-none md:max-w-none md:self-start md:overflow-visible md:pr-0 md:gap-5">
          <div
            className="pointer-events-none relative w-full md:w-fit"
            onMouseEnter={() => setIsHeaderPanelHovered(true)}
            onMouseLeave={() => setIsHeaderPanelHovered(false)}
          >
          <div data-map-top-overlay className={`neo-panel dashboard-header-panel pointer-events-auto flex min-h-[76px] flex-col rounded-[0.7rem] px-4 pt-3 transition-all duration-200 ${isHeaderPanelOpen ? "w-full max-w-none self-stretch gap-3 pb-3 md:w-fit md:min-w-[460px] md:max-w-[520px]" : "w-[138px] max-w-[138px] self-start pb-3 md:w-[128px] md:min-w-[128px] md:max-w-[128px]"}`}>
            <div className={`flex items-start ${isHeaderPanelOpen ? "justify-between gap-4" : "justify-between gap-3"}`}>
              <button
                type="button"
                onClick={handleHeaderLogoClick}
                className="w-[106px] shrink-0 text-left md:w-[97px]"
                aria-label="Pokaż menu na 3 sekundy"
                title="Pokaż menu na 3 sekundy"
              >
                <img
                  src="/VISAU-LOGO.png"
                  alt="VISAU"
                  className="block h-auto w-[106px] md:w-[97px]"
                />
                <div className="mt-1 flex w-[106px] justify-between whitespace-nowrap text-[7.9px] font-medium uppercase leading-none text-sky md:w-[97px] md:text-[7.6px]">
                  {"AUTOTRACKING".split("").map((letter, index) => (
                    <span key={`${letter}-${index}`}>{letter}</span>
                  ))}
                </div>
              </button>
              {!isHeaderPanelOpen ? (
                <button
                  type="button"
                  onClick={() => {
                    clearHeaderAutoCollapseTimer();
                    setIsHeaderPanelOpen(true);
                  }}
                  className="inline-flex h-7 w-7 shrink-0 self-start items-center justify-center rounded-full border border-mint/35 bg-slate-950/80 text-white shadow-[0_0_10px_rgba(74,222,128,0.14)]"
                  aria-label="Rozwiń górne menu"
                  title="Rozwiń górne menu"
                >
                  <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="m9 6 6 6-6 6" />
                  </svg>
                </button>
              ) : null}
              {isHeaderPanelOpen ? (
                <div className="ml-auto flex min-w-0 flex-1 flex-col items-end gap-1.5 self-start text-right">
                  <div className="flex min-w-0 items-center justify-end gap-1.5">
                  <div className="min-w-0 max-w-[68px] truncate text-[12px] font-semibold text-white md:max-w-[120px]">
                    {currentUserPrimaryName}
                  </div>
                  {userRole === "admin" ? (
                    <button
                      type="button"
                      onClick={() => {
                        setSystemSettingsTab("users");
                        setIsSystemSettingsOpen(true);
                      }}
                      className="flex h-9 w-9 items-center justify-center rounded-full border border-cyan-300/20 bg-white/5 text-cyan-100 shadow-sm"
                      aria-label="Ustawienia"
                      title="Ustawienia"
                    >
                      <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M12 8.75A3.25 3.25 0 1 0 12 15.25A3.25 3.25 0 0 0 12 8.75Z" />
                        <path d="M19.4 15A1 1 0 0 0 19.6 16.1L19.7 16.2A1.2 1.2 0 0 1 19.7 17.9L17.9 19.7A1.2 1.2 0 0 1 16.2 19.7L16.1 19.6A1 1 0 0 0 15 19.4A1 1 0 0 0 14.4 20.3V20.7A1.3 1.3 0 0 1 13.1 22H10.9A1.3 1.3 0 0 1 9.6 20.7V20.5A1 1 0 0 0 8.95 19.55A1 1 0 0 0 7.9 19.75L7.6 19.9A1.2 1.2 0 0 1 6.1 19.65L4.3 17.9A1.2 1.2 0 0 1 4.3 16.2L4.4 16.1A1 1 0 0 0 4.6 15A1 1 0 0 0 3.7 14.4H3.3A1.3 1.3 0 0 1 2 13.1V10.9A1.3 1.3 0 0 1 3.3 9.6H3.5A1 1 0 0 0 4.45 8.95A1 1 0 0 0 4.25 7.9L4.1 7.6A1.2 1.2 0 0 1 4.35 6.1L6.1 4.3A1.2 1.2 0 0 1 7.8 4.3L7.9 4.4A1 1 0 0 0 9 4.6A1 1 0 0 0 9.6 3.7V3.3A1.3 1.3 0 0 1 10.9 2H13.1A1.3 1.3 0 0 1 14.4 3.3V3.5A1 1 0 0 0 15.05 4.45A1 1 0 0 0 16.1 4.25L16.4 4.1A1.2 1.2 0 0 1 17.9 4.35L19.7 6.1A1.2 1.2 0 0 1 19.7 7.8L19.6 7.9A1 1 0 0 0 19.4 9A1 1 0 0 0 20.3 9.6H20.7A1.3 1.3 0 0 1 22 10.9V13.1A1.3 1.3 0 0 1 20.7 14.4H20.5A1 1 0 0 0 19.55 15.05Z" />
                      </svg>
                    </button>
                  ) : null}
                  {canAccessStats ? (
                    <button
                      type="button"
                      onClick={() => setIsStatsPanelOpen((current) => !current)}
                      className={`inline-flex h-7 shrink-0 items-center justify-center rounded-full border px-2 text-[8px] font-semibold uppercase tracking-[0.14em] transition ${
                        isStatsPanelOpen
                          ? "border-mint/45 bg-mint/20 text-mint shadow-[0_0_18px_rgba(24,184,104,0.22)]"
                          : "border-mint/30 bg-mint/10 text-mint hover:border-mint/45 hover:bg-mint/15"
                      }`}
                      aria-label="Stats"
                      title="Stats"
                    >
                      Stats
                    </button>
                  ) : null}
                  <button
                    type="button"
                    onClick={onLogout}
                    className="flex h-9 w-9 items-center justify-center rounded-full border border-[#7858D0]/40 bg-white/5 text-[#b795ff] shadow-sm"
                    aria-label="Wyloguj"
                    title="Wyloguj"
                  >
                    <svg viewBox="0 0 24 24" className="h-5 w-5 fill-current" aria-hidden="true">
                      <path d="M14.08 15.59L16.67 13H7V11H16.67L14.08 8.41L15.5 7L20.5 12L15.5 17L14.08 15.59M4 19H12V21H4A2 2 0 0 1 2 19V5A2 2 0 0 1 4 3H12V5H4V19Z" />
                    </svg>
                  </button>
                  </div>
                  <div className="flex min-w-max items-center justify-end gap-2 whitespace-nowrap text-[8px] uppercase tracking-[0.08em] text-mint md:text-[10px]">
                    <span className="shrink-0">
                      Online: <span className="font-semibold">{onlineVehiclesCount}</span>
                    </span>
                    <button
                      type="button"
                      onClick={toggleMovingVehiclesPanel}
                      className="inline-flex shrink-0 items-center gap-0.5 transition hover:text-white"
                      aria-expanded={isMovingVehiclesOpen}
                      aria-label="Pokaż auta w ruchu"
                    >
                      <span>W trasie: <span className="font-semibold">{movingVehiclesCount}</span></span>
                      <svg viewBox="0 0 24 24" className={`h-3 w-3 transition-transform ${isMovingVehiclesOpen ? "rotate-180" : ""}`} fill="currentColor" aria-hidden="true">
                        <path d="M7 10l5 5 5-5H7Z" />
                      </svg>
                    </button>
                    <button
                      type="button"
                      onClick={toggleCompanyVehiclesPanel}
                      className="inline-flex shrink-0 items-center gap-0.5 font-bold underline underline-offset-4 transition hover:text-white"
                      aria-expanded={isCompanyVehiclesOpen}
                      aria-label="Pokaż auta w firmie"
                    >
                      <span>P20: <span className="font-semibold">{vehiclesAtCompanyCount}</span></span>
                      <svg viewBox="0 0 24 24" className={`h-3 w-3 text-slate-300 transition-transform ${isCompanyVehiclesOpen ? "rotate-180" : ""}`} fill="currentColor" aria-hidden="true">
                        <path d="M7 10l5 5 5-5H7Z" />
                      </svg>
                    </button>
                  </div>
                </div>
              ) : null}
            </div>
            {isHeaderPanelOpen && (isMovingVehiclesOpen || isCompanyVehiclesOpen) ? (
              <div className="border-t border-white/10 pt-1 text-[10px] text-slate-200 md:text-[11px]">
                {isMovingVehiclesOpen ? (
                  <div className="mt-2 flex w-full justify-end">
                    <div className="max-w-full overflow-x-auto">
                      <div className="flex min-w-max items-center justify-end gap-x-1.5 text-right text-[11px] uppercase tracking-[0.12em] text-slate-300">
                        {movingVehicles.length > 0 ? movingVehicles.map((vehicle) => (
                          <button
                            key={`moving-${vehicle.id}`}
                            type="button"
                            onClick={() => handleVehicleSelection(vehicle.id)}
                            className="truncate text-mint transition hover:text-white"
                          >
                            {vehicle.name}
                          </button>
                        )) : (
                          <span className="text-slate-500">Brak</span>
                        )}
                      </div>
                    </div>
                  </div>
                ) : null}
                {isCompanyVehiclesOpen ? (
                  <div className="mt-2 flex w-full justify-end">
                    <div className="max-w-full overflow-x-auto">
                      <div className="flex min-w-max items-center justify-end gap-x-1.5 text-right text-[11px] uppercase tracking-[0.12em] text-slate-300">
                      {vehiclesAtCompany.length > 0 ? vehiclesAtCompany.map((vehicle) => (
                        <button
                          key={`company-${vehicle.id}`}
                          type="button"
                          onClick={() => handleVehicleSelection(vehicle.id)}
                          className="truncate text-mint transition hover:text-white"
                        >
                          {vehicle.name}
                        </button>
                      )) : (
                        <span className="text-slate-500">Brak</span>
                      )}
                      </div>
                    </div>
                  </div>
                ) : null}
              </div>
            ) : null}
          </div>
          {isHeaderPanelOpen ? (
            <button
              type="button"
              onClick={() => {
                clearHeaderAutoCollapseTimer();
                setIsHeaderPanelOpen(false);
              }}
              className="pointer-events-auto absolute right-[-44px] top-3 flex h-9 w-9 items-center justify-center rounded-full border border-mint/35 bg-slate-950/80 text-white shadow-[0_0_10px_rgba(74,222,128,0.14)]"
              aria-label="Zwiń górne menu"
              title="Zwiń górne menu"
            >
              <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="m15 6-6 6 6 6" />
              </svg>
            </button>
          ) : null}
          </div>

          {hasInfoAttention || recentAlerts.length > 0 ? (
          <div
            className={`neo-panel pointer-events-auto relative overflow-hidden rounded-[0.7rem] shadow-panel transition-all duration-200 ${
              isInfoPanelOpen ? "w-full p-4" : "h-9 w-9 p-0 md:h-12 md:w-12"
            } ${hasInfoAttention ? "border-coral/80 shadow-[0_0_0_1px_rgba(251,113,133,0.25),0_0_18px_rgba(251,113,133,0.25),0_0_42px_rgba(251,113,133,0.16),0_18px_40px_rgba(2,8,23,0.46)]" : ""}`}
          >
            <button
              type="button"
              onClick={() => setIsInfoPanelOpen((current) => !current)}
              className={`${isInfoPanelOpen ? "neo-panel__titlebar w-full text-left" : "flex h-full w-full items-center justify-center"}`}
              aria-label={isInfoPanelOpen ? "Zwiń informacje" : "Rozwiń informacje"}
              title={isInfoPanelOpen ? "Zwiń informacje" : "Rozwiń informacje"}
            >
              {isInfoPanelOpen ? (
                <>
                  <span className="neo-panel__titlegroup">
                    <span
                      className={`neo-panel__icon ${hasInfoAttention ? "bg-coral/15 text-coral shadow-[inset_0_0_0_1px_rgba(251,113,133,0.35),0_0_18px_rgba(251,113,133,0.24)]" : ""}`}
                      aria-hidden="true"
                    >
                      <svg viewBox="0 0 24 24" className="h-4 w-4" fill="currentColor" aria-hidden="true">
                        <path d="M11,9H13V7H11M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20M11,17H13V11H11V17M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
                      </svg>
                    </span>
                    <span className={`neo-panel__title ${hasInfoAttention ? "text-coral" : ""}`}>Informacje</span>
                  </span>
                  <span className="neo-panel__toggle" aria-hidden="true">
                    <svg
                      viewBox="0 0 24 24"
                      className="h-4 w-4"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <path d="m15 6-6 6 6 6" />
                    </svg>
                  </span>
                </>
              ) : (
                <span
                  className={`flex h-9 w-9 items-center justify-center md:h-12 md:w-12 ${
                    hasInfoAttention ? "text-coral" : "text-mint"
                  }`}
                  aria-hidden="true"
                >
                  <svg viewBox="0 0 24 24" className="h-6 w-6 md:h-[1.35rem] md:w-[1.35rem]" fill="currentColor" aria-hidden="true">
                    <path d="M11,9H13V7H11M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20M11,17H13V11H11V17M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
                  </svg>
                </span>
              )}
            </button>

            {isInfoPanelOpen ? (
              <button
                type="button"
                onClick={() => setIsAlertsListOpen(true)}
                className="absolute right-14 top-4 z-10 inline-flex h-7 items-center justify-center rounded-full border border-coral/45 bg-coral/10 px-3 text-[9px] font-semibold uppercase tracking-[0.16em] text-coral transition hover:bg-coral/20"
                aria-label="Otwórz listę alertów"
                title="Lista alertów z ostatnich 7 dni"
              >
                Lista
              </button>
            ) : null}

            {isInfoPanelOpen ? (
              <div className="neo-panel__body visible-scrollbar max-h-[calc(100dvh-12rem)] space-y-3 overflow-y-auto overscroll-contain pr-1">
                {offlineAlertVehicles.length > 0 || activeAlerts.length > 0 ? (
                  <div className="space-y-3">
                    {offlineAlertVehicles.length > 0 ? (
                      <div className="neo-subcard rounded-[1.4rem] px-4 py-3">
                        <div className="flex items-center justify-between gap-3">
                          <div className="text-sm font-medium text-white">Pojazdy Offline</div>
                          <span className="min-w-[2.9rem] rounded-full bg-coral/15 px-3 py-1 text-center text-xs font-semibold uppercase text-coral">
                            {offlineAlertVehicles.length}
                          </span>
                        </div>
                        <div className="mt-2 space-y-1.5">
                          {offlineAlertVehicles.map((vehicle) => (
                            <div key={`offline-${vehicle.id}`} className="neo-subcard rounded-xl px-3 py-2 text-[12px] text-white">
                              <span className="font-semibold">{vehicle.name}</span>
                              {vehicle.lastSeen ? (
                                <>
                                  <span className="text-slate-400"> · </span>
                                  <span className="text-slate-300">{formatDateTime(vehicle.lastSeen)}</span>
                                </>
                              ) : null}
                            </div>
                          ))}
                        </div>
                      </div>
                    ) : null}
                    {activeAlerts.length > 0 ? (
                      <div className="space-y-2">
                        {activeAlerts.map((alert) => (
                          <div
                            key={alert.id}
                            className="neo-subcard neo-outline-amber rounded-2xl px-3 py-3"
                          >
                            <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-amber">
                              Alert prędkości
                            </div>
                            <div className="mt-1 text-sm font-semibold text-white">
                              {alert.vehicleName} przekroczył {Math.round(alert.speed)} km/h
                            </div>
                            <div className="mt-1 text-xs text-slate-300">
                              {Math.round(alert.speed)} km/h · {formatDateTime(alert.speedRecordedAt ?? alert.triggeredAt)}
                            </div>
                            <div className="mt-2 flex items-center justify-between gap-2">
                              <label className="inline-flex cursor-pointer items-center gap-2 text-[11px] font-semibold text-white">
                                <input
                                  type="checkbox"
                                  onChange={() => onAcknowledgeAlert(alert.id)}
                                  className="h-3.5 w-3.5 rounded border border-cyan-300/30 bg-white/5 accent-mint"
                                />
                                <span>Odczytane</span>
                              </label>
                              <button
                                type="button"
                                onClick={() => openSpeedAlertPlayback(alert)}
                                className="hidden h-7 items-center justify-center rounded-full border border-sky/45 bg-sky/12 px-2.5 text-[9px] font-semibold uppercase tracking-[0.12em] text-sky transition hover:bg-sky/20 md:inline-flex"
                                aria-label={`Odtwórz przekroczenie prędkości pojazdu ${alert.vehicleName}`}
                                title="Odtwórz 3 s przed i 3 s po przekroczeniu"
                              >
                                PLAYBACK
                              </button>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : null}
                  </div>
                ) : (
                  <div className="neo-subcard rounded-xl px-3 py-2 text-[11px] text-slate-300">
                    Brak aktywnych alertów.
                  </div>
                )}
              </div>
            ) : null}
          </div>
          ) : null}
        </aside>

        <section className="pointer-events-none relative min-h-[44vh] overflow-hidden rounded-[0.7rem] md:min-h-0" />

        <aside
          data-map-bottom-overlay
          className={`neo-panel pointer-events-auto fixed inset-x-3 bottom-3 ${
            isSelectedVehicleMenuOpen ? "z-[840]" : "z-[500]"
          } rounded-[0.7rem] shadow-panel md:static md:inset-auto md:block ${
            isMobileTimelineMode
              ? "max-h-[56vh] overflow-visible px-3 pb-3 pt-2 md:max-h-none md:overflow-visible md:p-4"
              : isDetailsPanelOpen || isSelectedVehicleMenuOpen
              ? "max-h-[56vh] overflow-visible p-4 md:max-h-none md:overflow-visible"
              : "overflow-hidden p-3 md:self-start"
          }`}
        >
          <div className="mx-auto max-w-3xl">
            {!isMobileTimelineMode ? (
            <div className="neo-panel__titlebar" style={{ gap: isMobileViewport ? "4px" : undefined }}>
              <span className="min-w-0 flex-1">
                <div className="flex items-center gap-1 md:gap-2">
                    <div ref={selectedVehicleMenuRef} className="relative">
                      <button
                        type="button"
                        onClick={() => setIsSelectedVehicleMenuOpen((current) => {
                          const next = !current;
                          if (next && selectedVehicleId) {
                            setSelectedPositionDetailsEnabled(true);
                            setAddressLookupNonce((value) => value + 1);
                          }
                          return next;
                        })}
                        className="neo-field flex h-9 min-w-[112px] max-w-[122px] items-center gap-2 rounded-full px-3 text-left md:h-8 md:min-w-[98px] md:max-w-[142px]"
                        aria-label="Wybierz pojazd"
                        aria-expanded={isSelectedVehicleMenuOpen}
                      >
                        {selectedVehicle ? (
                          <VehicleStatusTruckIcon status={selectedVehicle.status} className="h-3.5 w-3.5 shrink-0" />
                        ) : null}
                        <span className="min-w-0 flex-1 truncate text-[12px] font-semibold text-white">
                          {selectedVehicle?.name ?? "Wybierz"}
                        </span>
                        <svg
                          viewBox="0 0 24 24"
                          className={`h-4 w-4 shrink-0 text-cyan-200 transition-transform ${isSelectedVehicleMenuOpen ? "rotate-180" : ""}`}
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          aria-hidden="true"
                        >
                          <path d="m6 9 6 6 6-6" />
                        </svg>
                      </button>
                      {isSelectedVehicleMenuOpen ? (
                        <div className="absolute bottom-[calc(100%+8px)] left-0 z-[120] isolate w-[200px] max-w-[76vw] rounded-2xl border border-cyan-300/25 bg-[#121b2a] p-2 shadow-[0_18px_40px_rgba(2,8,23,0.72)] md:bottom-auto md:top-[calc(100%+8px)] md:w-[172px]">
                          <div className="max-h-[260px] space-y-1 overflow-y-auto md:max-h-none md:overflow-visible">
                            {vehicles.map((vehicle) => (
                              <button
                                key={vehicle.id}
                                type="button"
                                onClick={() => handleVehicleSelection(vehicle.id)}
                                className={`flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left transition ${
                                  vehicle.id === selectedVehicleId ? "bg-cyan-300/10" : "hover:bg-white/5"
                                }`}
                              >
                                <VehicleStatusTruckIcon status={vehicle.status} className="h-3.5 w-3.5 shrink-0" />
                                <span className="truncate text-[12px] font-semibold text-white">
                                  {vehicle.name}
                                </span>
                              </button>
                            ))}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  <button
                    type="button"
                    onClick={handleShowAllVehicles}
                    className={`neo-field flex h-9 items-center rounded-full px-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] md:h-8 md:px-2 ${
                      overviewMode === "all" ? "text-mint" : "text-cyan-100"
                    }`}
                  >
                    All
                  </button>
                  <button
                    type="button"
                    onClick={handleShowWarsawVehicles}
                    className={`neo-field flex h-9 items-center rounded-full px-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] md:h-8 md:px-2 ${
                      overviewMode === "warsaw" ? "text-mint" : "text-cyan-100"
                    }`}
                  >
                    WAW
                  </button>
                  <button
                    type="button"
                    onClick={handleShowCompanyOverview}
                    className={`neo-field flex h-9 items-center rounded-full px-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] md:h-8 md:px-2 ${
                      overviewMode === "company" ? "text-mint" : "text-cyan-100"
                    }`}
                  >
                    P20
                  </button>
                </div>
              </span>
              <span className="flex items-center gap-1 md:gap-2">
                {canManageVehicleInspection && selectedVehicle ? (
                  <button
                    type="button"
                    onClick={() => openVehicleEditor(selectedVehicle)}
                    className="hidden h-8 w-8 items-center justify-center rounded-full border border-cyan-300/20 bg-white/5 text-cyan-100 shadow-sm md:flex"
                    aria-label="Edytuj pojazd"
                    title="Edytuj pojazd"
                  >
                    <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 8.75A3.25 3.25 0 1 0 12 15.25A3.25 3.25 0 1 0 12 8.75Z" />
                      <path d="M19.4 15A1 1 0 0 0 19.6 16.1L19.7 16.2A1.2 1.2 0 0 1 19.7 17.9L17.9 19.7A1.2 1.2 0 0 1 16.2 19.7L16.1 19.6A1 1 0 0 0 15 19.4A1 1 0 0 0 14.4 20.3V20.7A1.3 1.3 0 0 1 13.1 22H10.9A1.3 1.3 0 0 1 9.6 20.7V20.5A1 1 0 0 0 8.95 19.55A1 1 0 0 0 7.9 19.75L7.6 19.9A1.2 1.2 0 0 1 6.1 19.65L4.3 17.9A1.2 1.2 0 0 1 4.3 16.2L4.4 16.1A1 1 0 0 0 4.6 15A1 1 0 0 0 3.7 14.4H3.3A1.3 1.3 0 0 1 2 13.1V10.9A1.3 1.3 0 0 1 3.3 9.6H3.5A1 1 0 0 0 4.45 8.95A1 1 0 0 0 4.25 7.9L4.1 7.6A1.2 1.2 0 0 1 4.35 6.1L6.1 4.3A1.2 1.2 0 0 1 7.8 4.3L7.9 4.4A1 1 0 0 0 9 4.6A1 1 0 0 0 9.6 3.7V3.3A1.3 1.3 0 0 1 10.9 2H13.1A1.3 1.3 0 0 1 14.4 3.3V3.5A1 1 0 0 0 15.05 4.45A1 1 0 0 0 16.1 4.25L16.4 4.1A1.2 1.2 0 0 1 17.9 4.35L19.7 6.1A1.2 1.2 0 0 1 19.7 7.8L19.6 7.9A1 1 0 0 0 19.4 9A1 1 0 0 0 20.3 9.6H20.7A1.3 1.3 0 0 1 22 10.9V13.1A1.3 1.3 0 0 1 20.7 14.4H20.5A1 1 0 0 0 19.55 15.05Z" />
                    </svg>
                  </button>
                ) : null}
                <button
                  type="button"
                  onClick={() => setIsDetailsPanelOpen((current) => !current)}
                  className="neo-panel__toggle"
                  aria-label={isDetailsPanelOpen ? "Zwiń szczegóły pojazdu" : "Rozwiń szczegóły pojazdu"}
                  title={isDetailsPanelOpen ? "Zwiń szczegóły pojazdu" : "Rozwiń szczegóły pojazdu"}
                >
                  <svg
                    viewBox="0 0 24 24"
                    className={`h-4 w-4 transition-transform ${isDetailsPanelOpen ? "" : "rotate-180"}`}
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="m6 9 6 6 6-6" />
                  </svg>
                </button>
                {canManageVehicleInspection && selectedVehicle ? (
                  <button
                    type="button"
                    onClick={() => openVehicleEditor(selectedVehicle)}
                    className="flex h-8 w-8 items-center justify-center rounded-full border border-cyan-300/20 bg-white/5 text-cyan-100 shadow-sm md:hidden"
                    aria-label="Edytuj pojazd"
                    title="Edytuj pojazd"
                  >
                    <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 8.75A3.25 3.25 0 1 0 12 15.25A3.25 3.25 0 1 0 12 8.75Z" />
                      <path d="M19.4 15A1 1 0 0 0 19.6 16.1L19.7 16.2A1.2 1.2 0 0 1 19.7 17.9L17.9 19.7A1.2 1.2 0 0 1 16.2 19.7L16.1 19.6A1 1 0 0 0 15 19.4A1 1 0 0 0 14.4 20.3V20.7A1.3 1.3 0 0 1 13.1 22H10.9A1.3 1.3 0 0 1 9.6 20.7V20.5A1 1 0 0 0 8.95 19.55A1 1 0 0 0 7.9 19.75L7.6 19.9A1.2 1.2 0 0 1 6.1 19.65L4.3 17.9A1.2 1.2 0 0 1 4.3 16.2L4.4 16.1A1 1 0 0 0 4.6 15A1 1 0 0 0 3.7 14.4H3.3A1.3 1.3 0 0 1 2 13.1V10.9A1.3 1.3 0 0 1 3.3 9.6H3.5A1 1 0 0 0 4.45 8.95A1 1 0 0 0 4.25 7.9L4.1 7.6A1.2 1.2 0 0 1 4.35 6.1L6.1 4.3A1.2 1.2 0 0 1 7.8 4.3L7.9 4.4A1 1 0 0 0 9 4.6A1 1 0 0 0 9.6 3.7V3.3A1.3 1.3 0 0 1 10.9 2H13.1A1.3 1.3 0 0 1 14.4 3.3V3.5A1 1 0 0 0 15.05 4.45A1 1 0 0 0 16.1 4.25L16.4 4.1A1.2 1.2 0 0 1 17.9 4.35L19.7 6.1A1.2 1.2 0 0 1 19.7 7.8L19.6 7.9A1 1 0 0 0 19.4 9A1 1 0 0 0 20.3 9.6H20.7A1.3 1.3 0 0 1 22 10.9V13.1A1.3 1.3 0 0 1 20.7 14.4H20.5A1 1 0 0 0 19.55 15.05Z" />
                    </svg>
                  </button>
                ) : null}
              </span>
            </div>
            ) : null}
            {isDetailsPanelOpen ? (
              <div className={`${isMobileTimelineMode ? "max-h-[calc(56vh-20px)]" : "max-h-[calc(56vh-64px)]"} space-y-4 overflow-y-auto pr-1 md:max-h-none md:overflow-visible md:pr-0`}>
                <VehicleDetailsPanel
                  selectedVehicle={selectedVehicle}
                  currentUserFirstName={currentUserFirstName}
                  canManageVehicleInspection={canManageVehicleInspection}
                  onOpenVehicleEditor={() => {
                    if (selectedVehicle) {
                      openVehicleEditor(selectedVehicle);
                    }
                  }}
                  selectedPosition={selectedPosition}
                  selectedDeviceState={selectedDeviceState}
                  selectedServiceNotices={selectedServiceNotices}
                  selectedPositionAddressLoading={selectedPositionAddressLoading}
                  selectedPositionAddress={selectedPositionAddress}
                  selectedPositionReachedLabel={selectedPositionReachedLabel}
                  companySettings={companySettings}
                  companyRouteSummary={companyRouteSummary}
                  companyDurationLabel={companyDurationLabel}
                  companyDistanceLabel={companyDistanceLabel}
                  formatArrivalTime={formatArrivalTime}
                  formatSpeedKmh={formatSpeedKmh}
                  getHeadingLabel={getHeadingLabel}
                  formatMileageKm={formatMileageKm}
                  formatToggle={formatToggle}
                  formatDateTime={formatDateTime}
                  history={history}
                  isTimelineVisible={isTimelineVisible}
                  isTimelineActivated={isTimelineActivated}
                  shouldShowNoDrivingHistoryMessage={shouldShowNoDrivingHistoryMessage}
                  from={from}
                  to={to}
                  historyMinInput={historyMinInput}
                  historyMaxInput={historyMaxInput}
                  openDesktopHistoryPicker={openDesktopHistoryPicker}
                  desktopHistoryFocusTarget={desktopHistoryFocusTarget}
                  onToggleDesktopFrom={() => {
                    setDesktopHistoryFocusTarget(null);
                    setOpenDesktopHistoryPicker((current) => current === "from" ? null : "from");
                  }}
                  onCloseDesktopFrom={() => {
                    setDesktopHistoryFocusTarget(null);
                    setOpenDesktopHistoryPicker((current) => current === "from" ? null : current);
                  }}
                  onChangeFrom={(nextValue) => setFrom(clampDateTimeLocalValue(nextValue, historyMinInput, historyMaxInput))}
                  onFromTimeTabForward={() => {
                    setDesktopHistoryFocusTarget("date");
                    setOpenDesktopHistoryPicker("to");
                  }}
                  onToggleDesktopTo={() => {
                    setDesktopHistoryFocusTarget(null);
                    setOpenDesktopHistoryPicker((current) => current === "to" ? null : "to");
                  }}
                  onCloseDesktopTo={() => {
                    setDesktopHistoryFocusTarget(null);
                    setOpenDesktopHistoryPicker((current) => current === "to" ? null : current);
                  }}
                  onChangeTo={(nextValue) => setTo(clampDateTimeLocalValue(nextValue, historyMinInput, historyMaxInput))}
                  onOpenRecentTripsList={openRecentTripsList}
                  onToggleTimeline={onToggleTimeline}
                  onActivateTimeline={activateTimelinePlayback}
                  sliderMinTimestamp={sliderMinTimestamp}
                  sliderMaxTimestamp={sliderMaxTimestamp}
                  playbackTimestamp={playbackTimestamp}
                  playbackPoint={playbackPoint}
                  playbackPointTime={playbackPointTime}
                  playbackDirection={playbackDirection}
                  setPlaybackDirection={setPlaybackDirection}
                  setPlaybackTimestamp={setPlaybackTimestamp}
                  startPlayback={startPlayback}
                  stopTimelinePlayback={stopTimelinePlayback}
                  pausePlayback={pausePlayback}
                  skipAndContinuePlayback={skipAndContinuePlayback}
                  playbackSpeed={playbackSpeed}
                  setPlaybackSpeed={setPlaybackSpeed}
                  skipStopsDuringPlayback={skipStopsDuringPlayback}
                  toggleSkipStopsDuringPlayback={() => setSkipStopsDuringPlayback((current) => !current)}
                  isPlaybackDriving={isPlaybackDriving}
                  activeMobileSection={activeMobileSection}
                  toggleMobileSection={toggleMobileSection}
                  isMobileLiveOpen={isMobileLiveOpen}
                  isMobileHistoryOpen={isMobileHistoryOpen}
                  isMobileGpsOpen={isMobileGpsOpen}
                  DesktopDateTimeField={DesktopDateTimeField}
                  TimelineScrubber={TimelineScrubber}
                />

                {selectedVehicle && vehicleSuccessMessage ? (
                  <div className="rounded-2xl bg-mint/10 px-4 py-3 text-sm font-semibold text-mint">
                    {vehicleSuccessMessage}
                  </div>
                ) : null}
                {selectedVehicle && adminMessage ? (
                  <div className="neo-subcard rounded-2xl px-4 py-3 text-sm text-white">{adminMessage}</div>
                ) : null}
                {selectedVehicle && loadError ? <div className="rounded-2xl bg-coral/10 px-4 py-3 text-sm text-coral">{loadError}</div> : null}
                {selectedVehicle && actionError ? <div className="rounded-2xl bg-coral/10 px-4 py-3 text-sm text-coral">{actionError}</div> : null}
              </div>
            ) : null}
          </div>
        </aside>
      </div>

      <div className="pointer-events-none fixed bottom-3 right-3 z-[140] hidden max-w-[320px] text-right text-[11px] font-medium leading-snug text-white/90 drop-shadow-[0_1px_6px_rgba(2,8,23,0.9)] md:block">
        Visau Multimedia Sp. z o.o. Wszelkie prawa zastrzeżone.
      </div>
    </main>
  );
}
