"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useTranslations } from "next-intl"; import { ArrowLeftRight, LoaderCircle } from "lucide-react"; import type { SyncOpResult } from "@/lib/sync/envelope"; import { isSuccess, newClientId, submitOp } from "@/lib/field/client-ops"; import { currentPosition } from "@/lib/field/image"; import { otherSessionOf, type OtherSession } from "@/lib/field/time-rules"; import { btnPrimary, btnSecondary } from "./ui"; type StartKind = "travel" | "work" | "resume"; async function startPayload(workOrderId: string, mode: "travel" | "work", switchFromOther: boolean) { const pos = await currentPosition(3000); return { workOrderId, mode, clientId: newClientId(), at: new Date().toISOString(), offline: typeof navigator !== "undefined" ? !navigator.onLine : false, deviceInfo: typeof navigator !== "undefined" ? navigator.userAgent.slice(0, 200) : undefined, ...(switchFromOther ? { switchFromOther: true } : {}), ...(pos ?? {}), }; } /** Sends session.start / session.resume (optionally with the auto switch flag). */ export async function submitStart(workOrderId: string, kind: StartKind, switchFromOther = false): Promise { if (kind === "resume") { return submitOp({ opType: "session.resume", payload: { workOrderId, at: new Date().toISOString(), ...(switchFromOther ? { switchFromOther: true } : {}) } }); } return submitOp({ opType: "session.start", payload: await startPayload(workOrderId, kind, switchFromOther) }); } /** * L12 auto switch: start/resume work; when another order is still on the clock the server answers * `other_session_running` and the bottom sheet asks „A-00041 läuft noch. Pausieren und A-00042 starten?". */ export function useSessionStart(workOrderId: string, number: string, onDone?: (result: SyncOpResult) => void) { const router = useRouter(); const [busy, setBusy] = useState(null); const [pending, setPending] = useState<{ kind: StartKind; other: OtherSession } | null>(null); const [result, setResult] = useState(null); async function start(kind: StartKind, switchFromOther = false) { setBusy(kind); const r = await submitStart(workOrderId, kind, switchFromOther); setBusy(null); const other = otherSessionOf(r); if (other && !switchFromOther) { setPending({ kind, other }); return r; } setPending(null); setResult(r); onDone?.(r); if (isSuccess(r)) router.refresh(); return r; } const sheet = pending ? ( start(pending.kind, true)} onCancel={() => setPending(null)} /> ) : null; return { start, busy, result, sheet }; } export function SwitchSessionSheet({ from, to, busy, onConfirm, onCancel }: { from: string; to: string; busy: boolean; onConfirm: () => void; onCancel: () => void }) { const t = useTranslations("field.switch"); return (
e.stopPropagation()} >

{t("title")}

{from ? t("text", { from, to }) : t("textUnknown", { to })}

); }