import { useState } from 'react'; import { useNavigate } from 'react-router'; import { trpc } from '../lib/trpc'; import { voice } from '../lib/voice'; import { Card } from '../components/ui/Card'; import { Button } from '../components/ui/Button'; import { Modal } from '../components/ui/Modal'; import { SkeletonCard } from '../components/ui/SkeletonCard'; import { toast } from 'sonner'; import { X, Plus, RotateCw, BellRing, Play, Clock, Check, LogOut } from 'lucide-react'; import { TimelineSection, ManualDialog } from '../components/time/TimelineSection'; import { formatDurationCompact } from '../lib/format-duration'; import { usePresenceSeconds } from '../lib/use-presence-seconds'; /** Aktuelle Stunde in Europe/Berlin (0–23). */ function berlinHourNow(): number { const h = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/Berlin', hour: '2-digit', hour12: false, }).format(new Date()); return parseInt(h, 10); } export function HeuteRoute() { const navigate = useNavigate(); const today = trpc.dayEntry.today.useQuery(); if (today.isPending) return ; if (today.data?.entry) { return ; } return navigate('/dashboard')} />; } function CheckInForm({ onDone }: { onDone: () => void }) { const carryQuery = trpc.dayEntry.pendingCarryOver.useQuery(); const [todos, setTodos] = useState<{ title: string; carried?: boolean }[]>([{ title: '' }]); const [prefilledFromCarry, setPrefilledFromCarry] = useState(false); // Wenn Carryover-ToDos geladen sind und das Formular noch leer ist, vorbefüllen. if ( !prefilledFromCarry && carryQuery.data && carryQuery.data.length > 0 && todos.length === 1 && !todos[0]!.title ) { setPrefilledFromCarry(true); setTodos([...carryQuery.data.map((c) => ({ title: c.title, carried: true })), { title: '' }]); } const utils = trpc.useUtils(); const mutation = trpc.dayEntry.checkIn.useMutation({ onSuccess: async (result) => { const msg = result.carriedOver > 0 ? `Locked in. ${result.carriedOver} offene ToDos vom Vortag übernommen.` : voice.toast.checkedIn; toast(msg); await utils.dayEntry.today.invalidate(); await utils.dayEntry.pendingCarryOver.invalidate(); // Dashboard-Sichten sofort mitziehen (Quote, Anwesenheit, „Heute im Team"). await utils.dayEntry.todayTeam.invalidate(); await utils.dayEntry.todayPresence.invalidate(); await utils.dashboard.overview.invalidate(); onDone(); }, }); function updateAt(i: number, value: string) { setTodos((arr) => arr.map((t, idx) => (idx === i ? { ...t, title: value } : t))); } function addRow() { setTodos((arr) => [...arr, { title: '' }]); } function removeAt(i: number) { setTodos((arr) => arr.filter((_, idx) => idx !== i)); } function handleKey(e: React.KeyboardEvent, i: number) { if (e.key === 'Enter') { e.preventDefault(); if (i === todos.length - 1 && todos[i]?.title.trim()) { addRow(); // Fokus auf neue Zeile in nächstem Tick setTimeout(() => { const inputs = document.querySelectorAll('input[data-todo-input]'); inputs[i + 1]?.focus(); }, 0); } } } function handleSubmit(e: React.FormEvent) { e.preventDefault(); const filtered = todos.filter((t) => t.title.trim().length > 0); if (filtered.length === 0) { toast('Mindestens eine ToDo brauchst du.'); return; } mutation.mutate({ todos: filtered.map((t) => ({ title: t.title.trim() })) }); } return (

Heute

{voice.hint.howIsItGoing}

Was nimmst du dir heute vor?

{carryQuery.data && carryQuery.data.length > 0 && (

{carryQuery.data.length} offene ToDos vom Vortag wurden für dich vorgemerkt. Behalte, ändere oder lösche sie.

)}
    {todos.map((t, i) => (
  • {t.carried && ( )} updateAt(i, e.target.value)} onKeyDown={(e) => handleKey(e, i)} placeholder="ToDo …" maxLength={200} data-todo-input ref={(el) => { if (i === 0 && el && el.value === '') el.focus(); }} className="flex-1 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none" /> {todos.length > 1 && ( )}
  • ))}
); } function TodoRow({ todo, allTodos, }: { todo: { id: string; title: string; status: 'open' | 'done' | 'dropped'; unplanned?: boolean }; allTodos: Array<{ id: string; title: string }>; }) { const utils = trpc.useUtils(); const now = trpc.time.now.useQuery(); const [retroOpen, setRetroOpen] = useState(false); const startMutation = trpc.time.start.useMutation({ onSuccess: async () => { await utils.time.now.invalidate(); await utils.time.listToday.invalidate(); }, }); const stopMutation = trpc.time.stop.useMutation({ onSuccess: async () => { await utils.time.now.invalidate(); await utils.time.listToday.invalidate(); }, }); const activeHere = now.data?.find((a) => a.todoId === todo.id); const isRunningHere = !!activeHere; const dotClass = todo.status === 'done' ? 'h-2 w-2 rounded-full bg-[var(--color-ampel-green-fg)]' : todo.status === 'dropped' ? 'h-2 w-2 rounded-full bg-[var(--color-ink-faint)]' : 'h-2 w-2 rounded-full bg-[var(--color-border-strong)]'; return (
  • {todo.title} {todo.unplanned && ( ungeplant )} {todo.status !== 'done' && todo.status !== 'dropped' && ( )} {todo.status !== 'done' && todo.status !== 'dropped' && !isRunningHere && ( )} {retroOpen && ( setRetroOpen(false)} /> )}
  • ); } function AddTodoInline() { const utils = trpc.useUtils(); const [title, setTitle] = useState(''); const add = trpc.dayEntry.addTodo.useMutation({ onSuccess: async () => { setTitle(''); await utils.dayEntry.today.invalidate(); await utils.dayEntry.todayTeam.invalidate(); await utils.dashboard.overview.invalidate(); }, }); return (
    { e.preventDefault(); const v = title.trim(); if (!v) return; add.mutate({ title: v }); }} > setTitle(e.target.value)} placeholder="Neues ToDo hinzufügen …" maxLength={200} className="flex-1 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none" />
    ); } function CheckInOutBar({ checkedInAt, checkedOutAt, autoCheckedIn, todos, reflected, }: { checkedInAt: string | Date | null; checkedOutAt: string | Date | null; autoCheckedIn: boolean; todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped' }>; reflected: boolean; }) { const utils = trpc.useUtils(); const [confirmOpen, setConfirmOpen] = useState(false); const checkOut = trpc.dayEntry.checkOut.useMutation({ onSuccess: async () => { setConfirmOpen(false); toast('Feierabend — Check-Out gespeichert.'); await utils.dayEntry.today.invalidate(); await utils.dashboard.overview.invalidate(); }, }); const reopen = trpc.dayEntry.reopen.useMutation({ onSuccess: async () => { toast('Willkommen zurück — Arbeit fortgesetzt.'); await utils.dayEntry.today.invalidate(); await utils.dashboard.overview.invalidate(); }, onError: (err) => toast(err.message), }); const hhmm = (d: string | Date | null) => d ? new Intl.DateTimeFormat('de-DE', { timeZone: 'Europe/Berlin', hour: '2-digit', minute: '2-digit', }).format(new Date(d)) : '—'; // Anwesenheit (Lock-in → Feierabend bzw. jetzt) — reine Anzeige, kein Tracking. // Auto-Check-in vom 6-Uhr-Schnitt ist kein echter Lock-in → Fallback-Anker // (erster Zeiteintrag des Tages) aus listToday. const listToday = trpc.time.listToday.useQuery(undefined, { refetchInterval: 30_000 }); const presenceFrom = !autoCheckedIn && checkedInAt ? checkedInAt : (listToday.data?.presenceStartedAt ?? null); const presenceSeconds = usePresenceSeconds(presenceFrom, checkedOutAt); return ( <>
    Arbeitsantritt {hhmm(checkedInAt)} {checkedOutAt ? ( <> · Feierabend {hhmm(checkedOutAt)} {presenceSeconds !== null && ` · ${formatDurationCompact(presenceSeconds)} anwesend`} ) : ( <> {presenceSeconds !== null && ( · anwesend seit{' '} {formatDurationCompact(presenceSeconds)} )} )}
    setConfirmOpen(false)} todos={todos} reflected={reflected} pending={checkOut.isPending} onConfirm={() => checkOut.mutate()} /> ); } /** * Tagesabschluss vor dem Feierabend: kurze Zusammenfassung (erledigt/offen/ * verworfen) und ein Hinweis, falls noch ToDos offen oder die Reflexion fehlt. * Feierabend ist reversibel ("Arbeit fortsetzen") — der Dialog ist daher Info, * keine harte Sperre. */ function FeierabendDialog({ open, onClose, todos, reflected, pending, onConfirm, }: { open: boolean; onClose: () => void; todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped' }>; reflected: boolean; pending: boolean; onConfirm: () => void; }) { const navigate = useNavigate(); const done = todos.filter((t) => t.status === 'done'); const dropped = todos.filter((t) => t.status === 'dropped'); const offen = todos.filter((t) => t.status === 'open'); const reflexionEmpfohlen = !reflected || offen.length > 0; return (

    Kurzer Blick auf den Tag, bevor du abschließt.

    {done.length} erledigt {offen.length} offen {dropped.length > 0 && ( {dropped.length} verworfen )}
    {done.length > 0 && (
      {done.map((t) => (
    • {t.title}
    • ))}
    )} {offen.length > 0 && (
    Noch offen — nicht reflektiert:
      {offen.map((t) => (
    • · {t.title}
    • ))}
    )} {!reflected && (

    Du hast heute noch nicht reflektiert.

    )}
    {reflexionEmpfohlen && ( )}
    ); } function AddUnplannedInline() { const utils = trpc.useUtils(); const [title, setTitle] = useState(''); const add = trpc.dayEntry.addUnplanned.useMutation({ onSuccess: async () => { setTitle(''); toast('Ungeplant erledigt — eingetragen.'); await utils.dayEntry.today.invalidate(); await utils.dayEntry.todayTeam.invalidate(); await utils.dashboard.overview.invalidate(); }, }); return (
    { e.preventDefault(); const v = title.trim(); if (!v) return; add.mutate({ title: v }); }} > setTitle(e.target.value)} placeholder="Ungeplant erledigt? z. B. mItapp-Security-Fix für Yevgen …" maxLength={200} className="flex-1 rounded-[var(--radius-md)] border border-dashed border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none" />
    ); } function EinstempeltView({ todos, entry, }: { todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped'; unplanned?: boolean; }>; entry: { status: 'begun' | 'full' | 'absent'; checkedInAt: string | Date | null; checkedOutAt: string | Date | null; autoCheckedIn: boolean; }; }) { // Reflexion ist „fällig", wenn nach 18:00 Berlin und noch nicht abgeschlossen. const reflectionDue = entry.status !== 'full' && berlinHourNow() >= 18; // CTA bleibt den ganzen Tag sichtbar — der Eintrag ist bis 00:00 (Berlin) änderbar. const ctaLabel = entry.status === 'full' ? 'Reflexion aktualisieren' : voice.cta.reflect; const subtitle = entry.status === 'full' ? 'Tag abgeschlossen. Bis Mitternacht (Berlin) noch änderbar.' : 'Locked in. Heute Abend reflektieren.'; return (

    Heute

    {subtitle}

    {reflectionDue && (
    )}
      {todos.map((t) => ( ))}
    ); }