Your favorite shift management application!
chore: refactor app (#3)
panteL1feae507c151
diff --git a/app/api/calendars/[id]/route.ts b/app/api/calendars/[id]/route.tsindex 68662d6..6022a95 100644--- a/app/api/calendars/[id]/route.ts+++ b/app/api/calendars/[id]/route.ts@@ -105,8 +105,19 @@ export async function DELETE() {try {const { id } = await params;- const { searchParams } = new URL(request.url);- const password = searchParams.get("password");++ // Read password from request body+ let password: string | null = null;+ const contentType = request.headers.get("content-type");++ if (contentType?.includes("application/json")) {+ try {+ const body = await request.json();+ password = body.password || null;+ } catch (e) {+ // If body parsing fails, continue with null password+ }+ }// Fetch calendar to check passwordconst [calendar] = await dbdiff --git a/app/api/notes/[id]/route.ts b/app/api/notes/[id]/route.tsindex f6c383b..ad33402 100644--- a/app/api/notes/[id]/route.ts+++ b/app/api/notes/[id]/route.ts@@ -1,8 +1,9 @@import { NextResponse } from "next/server";import { db } from "@/lib/db";-import { calendarNotes } from "@/lib/db/schema";+import { calendarNotes, calendars } from "@/lib/db/schema";import { eq } from "drizzle-orm";import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";+import { verifyPassword } from "@/lib/password-utils";// GET single calendar noteexport async function GET(@@ -41,12 +42,48 @@ export async function PUT(try {const { id } = await params;const body = await request.json();- const { note } = body;+ const { note, password } = body;if (!note) {return NextResponse.json({ error: "Note is required" }, { status: 400 });}+ // Fetch existing note to get calendar ID+ const [existingNote] = await db+ .select()+ .from(calendarNotes)+ .where(eq(calendarNotes.id, id));++ if (!existingNote) {+ return NextResponse.json(+ { error: "Calendar note not found" },+ { status: 404 }+ );+ }++ // Fetch calendar to check password+ const [calendar] = await db+ .select()+ .from(calendars)+ .where(eq(calendars.id, existingNote.calendarId));++ if (!calendar) {+ return NextResponse.json(+ { error: "Calendar not found" },+ { status: 404 }+ );+ }++ // Verify password if calendar is protected+ if (calendar.passwordHash) {+ if (!password || !verifyPassword(password, calendar.passwordHash)) {+ return NextResponse.json(+ { error: "Invalid password" },+ { status: 401 }+ );+ }+ }+const [updated] = await db.update(calendarNotes).set({@@ -89,6 +126,55 @@ export async function DELETE(try {const { id } = await params;+ // Read password from request body+ let password: string | null = null;+ const contentType = request.headers.get("content-type");++ if (contentType?.includes("application/json")) {+ try {+ const body = await request.json();+ password = body.password || null;+ } catch (e) {+ // If body parsing fails, continue with null password+ }+ }++ // Fetch existing note to get calendar ID+ const [existingNote] = await db+ .select()+ .from(calendarNotes)+ .where(eq(calendarNotes.id, id));++ if (!existingNote) {+ return NextResponse.json(+ { error: "Calendar note not found" },+ { status: 404 }+ );+ }++ // Fetch calendar to check password+ const [calendar] = await db+ .select()+ .from(calendars)+ .where(eq(calendars.id, existingNote.calendarId));++ if (!calendar) {+ return NextResponse.json(+ { error: "Calendar not found" },+ { status: 404 }+ );+ }++ // Verify password if calendar is protected+ if (calendar.passwordHash) {+ if (!password || !verifyPassword(password, calendar.passwordHash)) {+ return NextResponse.json(+ { error: "Invalid password" },+ { status: 401 }+ );+ }+ }+const result = await db.delete(calendarNotes).where(eq(calendarNotes.id, id))diff --git a/app/api/notes/route.ts b/app/api/notes/route.tsindex 035718a..cfa920d 100644--- a/app/api/notes/route.ts+++ b/app/api/notes/route.ts@@ -1,8 +1,9 @@import { NextResponse } from "next/server";import { db } from "@/lib/db";-import { calendarNotes } from "@/lib/db/schema";+import { calendarNotes, calendars } from "@/lib/db/schema";import { eq, and, gte, lte } from "drizzle-orm";import { eventEmitter, CalendarChangeEvent } from "@/lib/event-emitter";+import { verifyPassword } from "@/lib/password-utils";// GET calendar notes for a calendar (with optional date filter)export async function GET(request: Request) {@@ -56,7 +57,7 @@ export async function GET(request: Request) {export async function POST(request: Request) {try {const body = await request.json();- const { calendarId, date, note } = body;+ const { calendarId, date, note, password } = body;if (!calendarId || !date || !note) {return NextResponse.json(@@ -65,6 +66,29 @@ export async function POST(request: Request) {);}+ // Fetch calendar to check password+ const [calendar] = await db+ .select()+ .from(calendars)+ .where(eq(calendars.id, calendarId));++ if (!calendar) {+ return NextResponse.json(+ { error: "Calendar not found" },+ { status: 404 }+ );+ }++ // Verify password if calendar is protected+ if (calendar.passwordHash) {+ if (!password || !verifyPassword(password, calendar.passwordHash)) {+ return NextResponse.json(+ { error: "Invalid password" },+ { status: 401 }+ );+ }+ }+const [calendarNote] = await db.insert(calendarNotes).values({diff --git a/app/api/presets/[id]/route.ts b/app/api/presets/[id]/route.tsindex d4048e2..00a0688 100644--- a/app/api/presets/[id]/route.ts+++ b/app/api/presets/[id]/route.ts@@ -111,8 +111,19 @@ export async function DELETE() {try {const { id } = await params;- const { searchParams } = new URL(request.url);- const password = searchParams.get("password");++ // Read password from request body+ let password: string | null = null;+ const contentType = request.headers.get("content-type");++ if (contentType?.includes("application/json")) {+ try {+ const body = await request.json();+ password = body.password || null;+ } catch (e) {+ // If body parsing fails, continue with null password+ }+ }// Fetch preset to get calendar IDconst [preset] = await dbdiff --git a/app/api/shifts/[id]/route.ts b/app/api/shifts/[id]/route.tsindex c70ca3c..09ec4cb 100644--- a/app/api/shifts/[id]/route.ts+++ b/app/api/shifts/[id]/route.ts@@ -144,8 +144,19 @@ export async function DELETE() {try {const { id } = await params;- const { searchParams } = new URL(request.url);- const password = searchParams.get("password");++ // Read password from request body+ let password: string | null = null;+ const contentType = request.headers.get("content-type");++ if (contentType?.includes("application/json")) {+ try {+ const body = await request.json();+ password = body.password || null;+ } catch (e) {+ // If body parsing fails, continue with null password+ }+ }// Fetch shift to get calendar IDconst [shift] = await db.select().from(shifts).where(eq(shifts.id, id));diff --git a/app/page.tsx b/app/page.tsxindex 3768636..a15bc79 100644--- a/app/page.tsx+++ b/app/page.tsx@@ -1,34 +1,24 @@"use client";-import { useState, useEffect, Suspense, useRef } from "react";+import { useState, useEffect, Suspense } from "react";import { useRouter, useSearchParams } from "next/navigation";import { useTranslations, useLocale } from "next-intl";-import { ShiftWithCalendar, CalendarWithCount } from "@/lib/types";-import { CalendarSelector } from "@/components/calendar-selector";import { CalendarDialog } from "@/components/calendar-dialog";import { ShiftDialog, ShiftFormData } from "@/components/shift-dialog";-import { ShiftCard } from "@/components/shift-card";-import { PresetSelector } from "@/components/preset-selector";import { PasswordDialog } from "@/components/password-dialog";import { ManagePasswordDialog } from "@/components/manage-password-dialog";import { DeleteCalendarDialog } from "@/components/delete-calendar-dialog";import { LanguageSwitcher } from "@/components/language-switcher";import { ShiftStats } from "@/components/shift-stats";import { NoteDialog } from "@/components/note-dialog";+import { AppHeader } from "@/components/app-header";+import { CalendarGrid } from "@/components/calendar-grid";+import { ShiftsList } from "@/components/shifts-list";import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,-} from "@/components/ui/dialog";import {Plus,ChevronLeft,ChevronRight,- ChevronUp,- ChevronDown,Calendar as CalendarIcon,StickyNote,} from "lucide-react";@@ -40,15 +30,19 @@ import {isSameDay,addMonths,subMonths,- isToday,startOfWeek,endOfWeek,} from "date-fns";import { de, enUS } from "date-fns/locale";-import { ShiftPreset, CalendarNote } from "@/lib/db/schema";+import { CalendarNote, ShiftPreset } from "@/lib/db/schema";import { formatDateToLocal } from "@/lib/date-utils";import { toast } from "sonner";-import { motion, AnimatePresence } from "motion/react";+import { motion } from "motion/react";+import { useCalendars } from "@/hooks/useCalendars";+import { useShifts } from "@/hooks/useShifts";+import { usePresets } from "@/hooks/usePresets";+import { useNotes } from "@/hooks/useNotes";+import { useSSEConnection } from "@/hooks/useSSEConnection";function HomeContent() {const router = useRouter();@@ -56,12 +50,38 @@ function HomeContent() {const t = useTranslations();const locale = useLocale();const dateLocale = locale === "de" ? de : enUS;- const [calendars, setCalendars] = useState<CalendarWithCount[]>([]);- const [selectedCalendar, setSelectedCalendar] = useState<- string | undefined- >();- const [shifts, setShifts] = useState<ShiftWithCalendar[]>([]);- const [presets, setPresets] = useState<ShiftPreset[]>([]);++ // Custom hooks for data management+ const {+ calendars,+ selectedCalendar,+ setSelectedCalendar,+ loading,+ createCalendar: createCalendarHook,+ deleteCalendar: deleteCalendarHook,+ refetchCalendars,+ } = useCalendars(searchParams.get("id"));++ const {+ shifts,+ setShifts,+ createShift: createShiftHook,+ updateShift: updateShiftHook,+ deleteShift: deleteShiftHook,+ refetchShifts,+ } = useShifts(selectedCalendar);++ const { presets, refetchPresets } = usePresets(selectedCalendar);++ const {+ notes,+ createNote: createNoteHook,+ updateNote: updateNoteHook,+ deleteNote: deleteNoteHook,+ refetchNotes,+ } = useNotes(selectedCalendar);++ // Local stateconst [selectedPresetId, setSelectedPresetId] = useState<string | undefined>();@@ -81,23 +101,29 @@ function HomeContent() {string | undefined>();const [selectedNote, setSelectedNote] = useState<CalendarNote | undefined>();- const [notes, setNotes] = useState<CalendarNote[]>([]);const [pendingAction, setPendingAction] = useState<{type: "delete" | "edit";shiftId?: string;formData?: ShiftFormData;presetAction?: () => Promise<void>;+ noteAction?: () => Promise<void>;} | null>(null);- const [loading, setLoading] = useState(true);const [statsRefreshTrigger, setStatsRefreshTrigger] = useState(0);const [isTogglingShift, setIsTogglingShift] = useState(false);- const [showShiftsSection, setShowShiftsSection] = useState(false);- const eventSourceRef = useRef<EventSource | null>(null);const [isConnected, setIsConnected] = useState(true);- const lastSyncTimeRef = useRef<number>(Date.now());- const disconnectTimeRef = useRef<number | null>(null);const [version, setVersion] = useState<string | null>(null);+ // SSE Connection for real-time updates+ useSSEConnection({+ calendarId: selectedCalendar,+ onShiftUpdate: refetchShifts,+ onPresetUpdate: refetchPresets,+ onNoteUpdate: refetchNotes,+ onStatsRefresh: () => setStatsRefreshTrigger((prev) => prev + 1),+ isConnected,+ setIsConnected,+ });+// Fetch version informationconst fetchVersion = async () => {try {@@ -109,74 +135,10 @@ function HomeContent() {}};- // Fetch calendars on mount and setup cleanupuseEffect(() => {- fetchCalendars();fetchVersion();-- return () => {- if (eventSourceRef.current) {- eventSourceRef.current.close();- }- };}, []);- // Handle page visibility changes (tab switching, app backgrounding)- useEffect(() => {- const handleVisibilityChange = () => {- if (document.visibilityState === "visible" && selectedCalendar) {- const now = Date.now();- const timeSinceLastSync = now - lastSyncTimeRef.current;-- // If more than 30 seconds passed or we were disconnected, resync- if (timeSinceLastSync > 30000 || disconnectTimeRef.current) {- console.log("Tab became visible, resyncing data...");- toast.info(t("sync.refreshing"), { duration: Infinity });- fetchShifts();- fetchPresets();- fetchNotes();- setStatsRefreshTrigger((prev) => prev + 1);- lastSyncTimeRef.current = now;- disconnectTimeRef.current = null;- // Dismiss the refreshing toast after data is loaded- setTimeout(() => toast.dismiss(), 1000);- }- }- };-- const handleOnline = () => {- console.log("Network connection restored");- toast.dismiss(); // Dismiss all persistent error toasts- toast.success(t("sync.reconnected"));- setIsConnected(true);- if (selectedCalendar) {- fetchShifts();- fetchPresets();- fetchNotes();- setStatsRefreshTrigger((prev) => prev + 1);- lastSyncTimeRef.current = Date.now();- disconnectTimeRef.current = null;- }- };-- const handleOffline = () => {- console.log("Network connection lost");- toast.error(t("sync.offline"), { duration: Infinity });- setIsConnected(false);- disconnectTimeRef.current = Date.now();- };-- document.addEventListener("visibilitychange", handleVisibilityChange);- window.addEventListener("online", handleOnline);- window.addEventListener("offline", handleOffline);-- return () => {- document.removeEventListener("visibilitychange", handleVisibilityChange);- window.removeEventListener("online", handleOnline);- window.removeEventListener("offline", handleOffline);- };- }, [selectedCalendar, t]);-// Update URL when selected calendar changesuseEffect(() => {if (selectedCalendar) {@@ -184,344 +146,18 @@ function HomeContent() {}}, [selectedCalendar, router]);- // Fetch shifts and presets when calendar changes and setup SSE- useEffect(() => {- if (selectedCalendar) {- fetchShifts();- fetchPresets();- fetchNotes();-- // Close existing SSE connection if any- if (eventSourceRef.current) {- eventSourceRef.current.close();- }-- // Setup Server-Sent Events for real-time updates- const eventSource = new EventSource(- `/api/events/stream?calendarId=${selectedCalendar}`- );-- eventSource.onopen = () => {- setIsConnected(true);- toast.dismiss(); // Dismiss any persistent error/info toasts-- // If we were disconnected for more than 10 seconds, resync all data- if (disconnectTimeRef.current) {- const disconnectDuration = Date.now() - disconnectTimeRef.current;- if (disconnectDuration > 10000) {- console.log("Reconnected after long disconnect, resyncing...");- toast.info(t("sync.resyncing"), { duration: Infinity });- fetchShifts();- fetchPresets();- fetchNotes();- setStatsRefreshTrigger((prev) => prev + 1);- }- disconnectTimeRef.current = null;- }- lastSyncTimeRef.current = Date.now();- };-- eventSource.onmessage = (event) => {- try {- const data = JSON.parse(event.data);-- // Handle connection message- if (data.type === "connected") {- console.log("SSE connected for calendar:", data.calendarId);- return;- }-- // Handle calendar change events- if (data.type === "shift") {- fetchShifts();- setStatsRefreshTrigger((prev) => prev + 1);- } else if (data.type === "preset") {- fetchPresets();- } else if (data.type === "note") {- fetchNotes();- }-- lastSyncTimeRef.current = Date.now();- } catch (error) {- console.error("Error parsing SSE message:", error);- }- };-- eventSource.onerror = (error) => {- console.error("SSE connection error:", error);- setIsConnected(false);- disconnectTimeRef.current = Date.now();- eventSource.close();-- // Show error message if offline for more than 5 seconds- const errorTimeout = setTimeout(() => {- if (!navigator.onLine) {- toast.error(t("sync.disconnected"), { duration: Infinity });- }- }, 5000);-- // Attempt to reconnect after 3 seconds- setTimeout(() => {- clearTimeout(errorTimeout);- if (selectedCalendar && navigator.onLine) {- console.log("Attempting to reconnect and resync...");- fetchShifts();- fetchPresets();- fetchNotes();- }- }, 3000);- };-- eventSourceRef.current = eventSource;-- return () => {- eventSource.close();- };- } else {- setShifts([]);- setPresets([]);- setNotes([]);- if (eventSourceRef.current) {- eventSourceRef.current.close();- }- }- }, [selectedCalendar]);-- const fetchCalendars = async () => {- try {- const response = await fetch("/api/calendars");- const data = await response.json();- setCalendars(data);-- // Check if there's a calendar ID in the URL- const urlCalendarId = searchParams.get("id");-- if (- urlCalendarId &&- data.some((cal: CalendarWithCount) => cal.id === urlCalendarId)- ) {- // Use the calendar from URL if it exists- setSelectedCalendar(urlCalendarId);- } else if (data.length > 0 && !selectedCalendar) {- // Otherwise, select the first calendar- setSelectedCalendar(data[0].id);- }- } catch (error) {- console.error("Failed to fetch calendars:", error);- } finally {- setLoading(false);- }- };-- const fetchPresets = async () => {- if (!selectedCalendar) return;-- try {- const response = await fetch(- `/api/presets?calendarId=${selectedCalendar}`- );- const data = await response.json();- setPresets(data);- } catch (error) {- console.error("Failed to fetch presets:", error);- }- };-- const fetchShifts = async () => {- if (!selectedCalendar) return;-- try {- const response = await fetch(- `/api/shifts?calendarId=${selectedCalendar}`- );- const data = await response.json();- setShifts(data);- } catch (error) {- console.error("Failed to fetch shifts:", error);- }- };-- const fetchNotes = async () => {- if (!selectedCalendar) return;-- try {- const response = await fetch(`/api/notes?calendarId=${selectedCalendar}`);- const data = await response.json();- setNotes(data);- } catch (error) {- console.error("Failed to fetch notes:", error);- }- };-- const createCalendar = async (- name: string,- color: string,- password?: string- ) => {- try {- const response = await fetch("/api/calendars", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name, color, password }),- });- const newCalendar = await response.json();- setCalendars([...calendars, newCalendar]);- setSelectedCalendar(newCalendar.id);- toast.success(t("calendar.created"));- } catch (error) {- console.error("Failed to create calendar:", error);- toast.error(t("calendar.createError"));- }- };-const initiateDeleteCalendar = (id: string) => {setCalendarToDelete(id);setShowDeleteCalendarDialog(true);};- const deleteCalendar = async (password?: string) => {+ const handleDeleteCalendar = async (password?: string) => {if (!calendarToDelete) return;- try {- const url = password- ? `/api/calendars/${calendarToDelete}?password=${encodeURIComponent(- password- )}`- : `/api/calendars/${calendarToDelete}`;-- const response = await fetch(url, { method: "DELETE" });-- if (response.status === 401) {- toast.error(t("password.errorIncorrect"));- return;- }-- if (response.ok) {- const remainingCalendars = calendars.filter(- (c) => c.id !== calendarToDelete- );- setCalendars(remainingCalendars);- localStorage.removeItem(`calendar_password_${calendarToDelete}`);-- // If deleting the selected calendar, select the first remaining one or undefined- if (selectedCalendar === calendarToDelete) {- setSelectedCalendar(- remainingCalendars.length > 0 ? remainingCalendars[0].id : undefined- );- }-- setShowDeleteCalendarDialog(false);- setCalendarToDelete(undefined);- toast.success(t("calendar.deleted"));- }- } catch (error) {- console.error("Failed to delete calendar:", error);- toast.error(t("calendar.deleteError"));- }- };-- const createShift = async (formData: ShiftFormData) => {- if (!selectedCalendar) return;-- // Optimistic update: add shift immediately with temporary ID- const tempId = `temp-${Date.now()}`;- const optimisticShift: ShiftWithCalendar = {- id: tempId,- date: new Date(formData.date),- startTime: formData.startTime,- endTime: formData.endTime,- title: formData.title,- color: formData.color || "#000000",- notes: formData.notes || null,- isAllDay: formData.isAllDay || false,- calendarId: selectedCalendar,- createdAt: new Date(),- updatedAt: new Date(),- };-- setShifts([...shifts, optimisticShift]);- setStatsRefreshTrigger((prev) => prev + 1);-- try {- const response = await fetch("/api/shifts", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- ...formData,- calendarId: selectedCalendar,- }),- });- const newShift = await response.json();- // Replace optimistic shift with real one- setShifts((shifts) =>- shifts.map((s) => (s.id === tempId ? newShift : s))- );- toast.success(t("shift.created"));- } catch (error) {- console.error("Failed to create shift:", error);- // Rollback optimistic update on error- setShifts((shifts) => shifts.filter((s) => s.id !== tempId));- setStatsRefreshTrigger((prev) => prev + 1);- toast.error(t("shift.createError"));- }- };-- const updateShift = async (id: string, formData: ShiftFormData) => {- try {- // Get stored password from localStorage- const password = selectedCalendar- ? localStorage.getItem(`calendar_password_${selectedCalendar}`)- : null;-- const response = await fetch(`/api/shifts/${id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...formData, password }),- });-- if (response.status === 401) {- // Password required or invalid- setPendingAction({ type: "edit", shiftId: id, formData });- setShowPasswordDialog(true);- return;- }-- const updatedShift = await response.json();- setShifts(shifts.map((s) => (s.id === id ? updatedShift : s)));- setStatsRefreshTrigger((prev) => prev + 1);- toast.success(t("shift.updated"));- } catch (error) {- console.error("Failed to update shift:", error);- toast.error(t("shift.updateError"));- }- };-- const deleteShift = async (id: string) => {- try {- // Get stored password from localStorage- const password = selectedCalendar- ? localStorage.getItem(`calendar_password_${selectedCalendar}`)- : null;-- const url = password- ? `/api/shifts/${id}?password=${encodeURIComponent(password)}`- : `/api/shifts/${id}`;-- const response = await fetch(url, { method: "DELETE" });-- if (response.status === 401) {- // Password required or invalid- setPendingAction({ type: "delete", shiftId: id });- setShowPasswordDialog(true);- return;- }-- setShifts(shifts.filter((s) => s.id !== id));- setStatsRefreshTrigger((prev) => prev + 1);- toast.success(t("shift.deleted"));- } catch (error) {- console.error("Failed to delete shift:", error);- toast.error(t("shift.deleteError"));+ const success = await deleteCalendarHook(calendarToDelete, password);+ if (success) {+ setShowDeleteCalendarDialog(false);+ setCalendarToDelete(undefined);}};@@ -530,15 +166,16 @@ function HomeContent() {try {if (pendingAction.type === "delete" && pendingAction.shiftId) {- const response = await fetch(- `/api/shifts/${pendingAction.shiftId}?password=${encodeURIComponent(- password- )}`,- { method: "DELETE" }- );+ const response = await fetch(`/api/shifts/${pendingAction.shiftId}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });if (response.ok) {setShifts(shifts.filter((s) => s.id !== pendingAction.shiftId));- setStatsRefreshTrigger((prev) => prev + 1); // Refresh stats+ setStatsRefreshTrigger((prev) => prev + 1);}} else if (pendingAction.type === "edit" &&@@ -560,8 +197,10 @@ function HomeContent() {setStatsRefreshTrigger((prev) => prev + 1);}} else if (pendingAction.presetAction) {- // Execute the pending preset actionawait pendingAction.presetAction();+ } else if (pendingAction.noteAction) {+ await pendingAction.noteAction();+ setShowNoteDialog(false);}} catch (error) {console.error("Failed to execute pending action:", error);@@ -575,66 +214,71 @@ function HomeContent() {setShowPasswordDialog(true);};- const createNote = async (noteText: string, date: Date) => {- if (!selectedCalendar) return;-- try {- const response = await fetch("/api/notes", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId: selectedCalendar,- date: formatDateToLocal(date),- note: noteText,- }),- });- const newNote = await response.json();- setNotes([...notes, newNote]);- toast.success(t("note.created"));- } catch (error) {- console.error("Failed to create note:", error);- toast.error(t("note.createError"));- }- };-- const updateNote = async (noteId: string, noteText: string) => {- try {- const response = await fetch(`/api/notes/${noteId}`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ note: noteText }),+ const handleNoteSubmit = async (noteText: string) => {+ const handlePasswordRequired = () => {+ setPendingAction({+ type: "edit",+ noteAction: async () => {+ if (selectedNote) {+ await updateNoteHook(+ selectedNote.id,+ noteText,+ handlePasswordRequired+ );+ } else if (selectedDate) {+ await createNoteHook(+ noteText,+ selectedDate,+ handlePasswordRequired+ );+ }+ },});- const updatedNote = await response.json();- setNotes(notes.map((n) => (n.id === noteId ? updatedNote : n)));- toast.success(t("note.updated"));- } catch (error) {- console.error("Failed to update note:", error);- toast.error(t("note.updateError"));- }- };-- const deleteNote = async (noteId: string) => {- try {- await fetch(`/api/notes/${noteId}`, { method: "DELETE" });- setNotes(notes.filter((n) => n.id !== noteId));- toast.success(t("note.deleted"));- } catch (error) {- console.error("Failed to delete note:", error);- toast.error(t("note.deleteError"));- }- };+ setShowPasswordDialog(true);+ };- const handleNoteSubmit = (noteText: string) => {if (selectedNote) {- updateNote(selectedNote.id, noteText);+ const success = await updateNoteHook(+ selectedNote.id,+ noteText,+ handlePasswordRequired+ );+ if (success) {+ setShowNoteDialog(false);+ }} else if (selectedDate) {- createNote(noteText, selectedDate);+ const success = await createNoteHook(+ noteText,+ selectedDate,+ handlePasswordRequired+ );+ if (success) {+ setShowNoteDialog(false);+ }}};- const handleNoteDelete = () => {- if (selectedNote) {- deleteNote(selectedNote.id);+ const handleNoteDelete = async () => {+ if (!selectedNote) return;++ const handlePasswordRequired = () => {+ setPendingAction({+ type: "delete",+ noteAction: async () => {+ if (selectedNote) {+ await deleteNoteHook(selectedNote.id, handlePasswordRequired);+ }+ },+ });+ setShowPasswordDialog(true);+ };++ const success = await deleteNoteHook(+ selectedNote.id,+ handlePasswordRequired+ );+ if (success) {+ setShowNoteDialog(false);}};@@ -675,7 +319,28 @@ function HomeContent() {};const handleShiftSubmit = (formData: ShiftFormData) => {- createShift(formData);+ createShiftHook(formData);+ setStatsRefreshTrigger((prev) => prev + 1);+ };++ const handleUpdateShift = async (id: string, formData: ShiftFormData) => {+ const success = await updateShiftHook(id, formData, () => {+ setPendingAction({ type: "edit", shiftId: id, formData });+ setShowPasswordDialog(true);+ });+ if (success) {+ setStatsRefreshTrigger((prev) => prev + 1);+ }+ };++ const handleDeleteShift = async (id: string) => {+ const success = await deleteShiftHook(id, () => {+ setPendingAction({ type: "delete", shiftId: id });+ setShowPasswordDialog(true);+ });+ if (success) {+ setStatsRefreshTrigger((prev) => prev + 1);+ }};const handleManualShiftCreation = async () => {@@ -686,7 +351,6 @@ function HomeContent() {`calendar_password_${selectedCalendar}`);- // Verify password if calendar is protectedconst response = await fetch(`/api/calendars/${selectedCalendar}/verify-password`,{@@ -699,7 +363,6 @@ function HomeContent() {const data = await response.json();if (data.protected && !data.valid) {- // Password required or invalidlocalStorage.removeItem(`calendar_password_${selectedCalendar}`);setPendingAction({type: "edit",@@ -709,7 +372,6 @@ function HomeContent() {return;}- // Password valid or not required, open shift dialogsetSelectedDate(new Date());setShowShiftDialog(true);} catch (error) {@@ -719,113 +381,94 @@ function HomeContent() {};const handleAddShift = async (date: Date) => {- // Prevent multiple simultaneous toggles (debouncing)- if (isTogglingShift) return;-- // Only proceed if a preset is selected- if (!selectedPresetId) return;+ if (isTogglingShift || !selectedPresetId) return;const preset = presets.find((p) => p.id === selectedPresetId);if (!preset) return;- // Check password before adding/deleting shift- const checkAndToggle = async () => {- setIsTogglingShift(true);-- try {- const password = selectedCalendar- ? localStorage.getItem(`calendar_password_${selectedCalendar}`)- : null;+ setIsTogglingShift(true);- // Verify password if calendar is protected- if (selectedCalendar) {- const response = await fetch(- `/api/calendars/${selectedCalendar}/verify-password`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password }),- }- );-- const data = await response.json();+ try {+ const password = selectedCalendar+ ? localStorage.getItem(`calendar_password_${selectedCalendar}`)+ : null;- if (data.protected && !data.valid) {- // Password required or invalid- localStorage.removeItem(`calendar_password_${selectedCalendar}`);- setPendingAction({- type: "edit",- presetAction: () => handleAddShift(date),- });- setShowPasswordDialog(true);- setIsTogglingShift(false);- return;+ if (selectedCalendar) {+ const response = await fetch(+ `/api/calendars/${selectedCalendar}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),}- }-- // Password valid or not required, proceed with toggle- // Check if a shift with the same preset already exists on this date- const existingShift = shifts.find(- (shift) =>- shift.date &&- isSameDay(new Date(shift.date), date) &&- shift.title === preset.title &&- shift.startTime === preset.startTime &&- shift.endTime === preset.endTime);- if (existingShift) {- // Toggle: remove the existing shift- // Optimistic delete- setShifts(shifts.filter((s) => s.id !== existingShift.id));- setStatsRefreshTrigger((prev) => prev + 1);+ const data = await response.json();++ if (data.protected && !data.valid) {+ localStorage.removeItem(`calendar_password_${selectedCalendar}`);+ setPendingAction({+ type: "edit",+ presetAction: () => handleAddShift(date),+ });+ setShowPasswordDialog(true);+ setIsTogglingShift(false);+ return;+ }+ }- try {- const password = selectedCalendar- ? localStorage.getItem(`calendar_password_${selectedCalendar}`)- : null;- const url = password- ? `/api/shifts/${existingShift.id}?password=${encodeURIComponent(- password- )}`- : `/api/shifts/${existingShift.id}`;- const response = await fetch(url, { method: "DELETE" });+ const existingShift = shifts.find(+ (shift) =>+ shift.date &&+ isSameDay(new Date(shift.date), date) &&+ shift.title === preset.title &&+ shift.startTime === preset.startTime &&+ shift.endTime === preset.endTime+ );- if (!response.ok) {- // Rollback on error- setShifts(shifts);- setStatsRefreshTrigger((prev) => prev + 1);- toast.error(t("shift.deleteError"));- } else {- toast.success(t("shift.deleted"));- }- } catch (error) {- console.error("Failed to delete shift:", error);- // Rollback on error+ if (existingShift) {+ setShifts(shifts.filter((s) => s.id !== existingShift.id));+ setStatsRefreshTrigger((prev) => prev + 1);++ try {+ const response = await fetch(`/api/shifts/${existingShift.id}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });++ if (!response.ok) {setShifts(shifts);setStatsRefreshTrigger((prev) => prev + 1);toast.error(t("shift.deleteError"));+ } else {+ toast.success(t("shift.deleted"));}- } else {- // Toggle: add the shift- const shiftData: ShiftFormData = {- date: formatDateToLocal(date),- startTime: preset.startTime,- endTime: preset.endTime,- title: preset.title,- color: preset.color,- notes: preset.notes || "",- presetId: preset.id,- isAllDay: preset.isAllDay || false,- };- await createShift(shiftData);+ } catch (error) {+ console.error("Failed to delete shift:", error);+ setShifts(shifts);+ setStatsRefreshTrigger((prev) => prev + 1);+ toast.error(t("shift.deleteError"));}- } finally {- setIsTogglingShift(false);+ } else {+ const shiftData: ShiftFormData = {+ date: formatDateToLocal(date),+ startTime: preset.startTime,+ endTime: preset.endTime,+ title: preset.title,+ color: preset.color,+ notes: preset.notes || "",+ presetId: preset.id,+ isAllDay: preset.isAllDay || false,+ };+ await createShiftHook(shiftData);+ setStatsRefreshTrigger((prev) => prev + 1);}- };-- await checkAndToggle();+ } finally {+ setIsTogglingShift(false);+ }};// Calendar grid calculations@@ -838,12 +481,6 @@ function HomeContent() {end: calendarEnd,});- const getShiftsForDate = (date: Date) => {- return shifts.filter(- (shift) => shift.date && isSameDay(new Date(shift.date), date)- );- };-if (loading) {return (<div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-background to-muted/20">@@ -853,14 +490,8 @@ function HomeContent() {animate={{ opacity: 1, scale: 1 }}><motion.div- animate={{- rotate: 360,- }}- transition={{- duration: 2,- repeat: Infinity,- ease: "linear",- }}+ animate={{ rotate: 360 }}+ transition={{ duration: 2, repeat: Infinity, ease: "linear" }}><CalendarIcon className="h-12 w-12 sm:h-16 sm:w-16 mx-auto text-primary" /></motion.div>@@ -917,7 +548,7 @@ function HomeContent() {<CalendarDialogopen={showCalendarDialog}onOpenChange={setShowCalendarDialog}- onSubmit={createCalendar}+ onSubmit={createCalendarHook}/></div>);@@ -925,201 +556,27 @@ function HomeContent() {return (<div className="min-h-screen flex flex-col">- {/* Header - Desktop: Horizontal, Mobile: Compact with Dialog */}- <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">- <div className="container max-w-4xl mx-auto p-3 sm:p-4">- <div className="space-y-3 sm:space-y-4">- {/* Desktop: Logo + Calendar Selector in one line */}- <div className="hidden sm:flex items-center justify-between gap-4">- {/* Logo Section */}- <motion.div- className="flex items-center gap-3"- initial={{ opacity: 0, x: -20 }}- animate={{ opacity: 1, x: 0 }}- transition={{ duration: 0.3 }}- >- <div className="relative shrink-0">- <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-xl shadow-primary/30 ring-2 ring-primary/20">- <CalendarIcon className="h-6 w-6 text-primary-foreground" />- </div>- {/* Connection Status Indicator */}- <div- className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${- isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"- }`}- title={- isConnected- ? t("sync.reconnected")- : t("sync.disconnected")- }- ></div>- </div>- <div>- <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text">- {t("app.title")}- </h1>- <p className="text-xs text-muted-foreground font-medium">- {t("app.subtitle", { default: "Organize your shifts" })}- </p>- </div>- </motion.div>-- {/* Calendar Selector - Desktop */}- <motion.div- className="flex items-center gap-3 min-w-0 flex-1 max-w-md bg-muted/30 rounded-xl p-2 border border-border/50"- initial={{ opacity: 0, x: 20 }}- animate={{ opacity: 1, x: 0 }}- transition={{ duration: 0.3, delay: 0.1 }}- >- <div- className="w-1 h-8 bg-gradient-to-b rounded-full transition-colors duration-300"- style={{- backgroundImage: selectedCalendar- ? `linear-gradient(to bottom, ${- calendars.find((c) => c.id === selectedCalendar)- ?.color || "hsl(var(--primary))"- }, ${- calendars.find((c) => c.id === selectedCalendar)- ?.color || "hsl(var(--primary))"- }80)`- : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",- }}- ></div>- <div className="flex-1 min-w-0">- <CalendarSelector- calendars={calendars}- selectedId={selectedCalendar}- onSelect={setSelectedCalendar}- onCreateNew={() => setShowCalendarDialog(true)}- onManagePassword={() => setShowManagePasswordDialog(true)}- onDelete={initiateDeleteCalendar}- />- </div>- </motion.div>- </div>-- {/* Mobile: Logo Icon + Calendar Card + Add Button */}- <div className="sm:hidden flex items-center gap-2">- {/* Logo Icon Only */}- <div className="relative shrink-0">- <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-lg shadow-primary/30 ring-2 ring-primary/20">- <CalendarIcon className="h-5 w-5 text-primary-foreground" />- </div>- <div className="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 rounded-full border-2 border-background"></div>- </div>-- {/* Calendar Selection Card */}- <button- onClick={() => setShowMobileCalendarDialog(true)}- className="flex-1 bg-muted/30 backdrop-blur-sm border border-border/50 rounded-xl p-3 flex items-center justify-between gap-2 hover:bg-accent/50 transition-all active:scale-[0.98] shadow-sm"- >- <div className="flex items-center gap-2.5 min-w-0 flex-1">- <div- className="w-1 h-9 bg-gradient-to-b rounded-full transition-colors duration-300"- style={{- backgroundImage: selectedCalendar- ? `linear-gradient(to bottom, ${- calendars.find((c) => c.id === selectedCalendar)- ?.color || "hsl(var(--primary))"- }, ${- calendars.find((c) => c.id === selectedCalendar)- ?.color || "hsl(var(--primary))"- }80)`- : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",- }}- ></div>- <div className="min-w-0 flex-1 text-left">- <p className="text-[10px] text-muted-foreground font-medium">- {t("calendar.select", {- default: "Your BetterShift Calendar",- })}- </p>- <p className="text-sm font-semibold truncate">- {calendars.find((c) => c.id === selectedCalendar)?.name ||- t("calendar.title")}- </p>- </div>- </div>- <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center">- <CalendarIcon className="h-4 w-4 text-primary" />- </div>- </button>-- {/* Mobile Add Shift Button */}- {selectedCalendar && (- <motion.div- initial={{ scale: 0, opacity: 0 }}- animate={{ scale: 1, opacity: 1 }}- transition={{ delay: 0.2, type: "spring", stiffness: 200 }}- >- <Button- size="icon"- onClick={handleManualShiftCreation}- className="h-10 w-10 rounded-xl shadow-lg shadow-primary/30 shrink-0"- >- <Plus className="h-5 w-5" />- </Button>- </motion.div>- )}- </div>-- {/* Preset Selector - Aligned properly */}- <div className="px-0.5 sm:px-0">- <PresetSelector- presets={presets}- selectedPresetId={selectedPresetId}- onSelectPreset={setSelectedPresetId}- onPresetsChange={fetchPresets}- onShiftsChange={fetchShifts}- calendarId={selectedCalendar || ""}- onPasswordRequired={handlePresetPasswordRequired}- />- </div>- </div>- </div>- </div>-- {/* Mobile Calendar Dialog */}- <Dialog- open={showMobileCalendarDialog}- onOpenChange={setShowMobileCalendarDialog}- >- <DialogContent className="sm:max-w-md p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">- <DialogTitle className="flex items-center gap-2.5 text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("calendar.select", { default: "Your BetterShift Calendar" })}- </DialogTitle>- <DialogDescription className="text-sm text-muted-foreground">- {t("calendar.selectDescription", {- default: "Choose a calendar to manage your shifts",- })}- </DialogDescription>- </DialogHeader>- <div className="p-6">- <CalendarSelector- calendars={calendars}- selectedId={selectedCalendar}- onSelect={(id) => {- setSelectedCalendar(id);- setShowMobileCalendarDialog(false);- }}- onCreateNew={() => {- setShowMobileCalendarDialog(false);- setShowCalendarDialog(true);- }}- onManagePassword={() => {- setShowMobileCalendarDialog(false);- setShowManagePasswordDialog(true);- }}- onDelete={initiateDeleteCalendar}- />- </div>- </DialogContent>- </Dialog>+ <AppHeader+ calendars={calendars}+ selectedCalendar={selectedCalendar}+ presets={presets}+ selectedPresetId={selectedPresetId}+ isConnected={isConnected}+ showMobileCalendarDialog={showMobileCalendarDialog}+ onSelectCalendar={setSelectedCalendar}+ onSelectPreset={setSelectedPresetId}+ onCreateCalendar={() => setShowCalendarDialog(true)}+ onManagePassword={() => setShowManagePasswordDialog(true)}+ onDeleteCalendar={initiateDeleteCalendar}+ onPresetsChange={refetchPresets}+ onShiftsChange={refetchShifts}+ onPasswordRequired={handlePresetPasswordRequired}+ onManualShiftCreation={handleManualShiftCreation}+ onMobileCalendarDialogChange={setShowMobileCalendarDialog}+ />- {/* Month Navigation */}<div className="container max-w-4xl mx-auto px-1 py-3 sm:p-4 flex-1">+ {/* Month Navigation */}<motion.divclassName="flex items-center justify-between mb-4 sm:mb-5 px-2 sm:px-0"initial={{ opacity: 0, y: -10 }}@@ -1154,139 +611,18 @@ function HomeContent() {</motion.div>{/* Calendar Grid */}- <div className="grid grid-cols-7 gap-0 sm:gap-1.5 mb-6">- {[- t("calendar_grid.monday"),- t("calendar_grid.tuesday"),- t("calendar_grid.wednesday"),- t("calendar_grid.thursday"),- t("calendar_grid.friday"),- t("calendar_grid.saturday"),- t("calendar_grid.sunday"),- ].map((day) => (- <div- key={day}- className="text-center text-[11px] sm:text-xs font-semibold text-muted-foreground p-1 sm:p-2"- >- {day}- </div>- ))}- {calendarDays.map((day, idx) => {- const dayShifts = getShiftsForDate(day);- const dayNote = notes.find(- (note) => note.date && isSameDay(new Date(note.date), day)- );- const isCurrentMonth = day.getMonth() === currentDate.getMonth();- const isTodayDate = isToday(day);-- // Long press handling for mobile- let pressTimer: NodeJS.Timeout | null = null;- const handleTouchStart = (e: React.TouchEvent) => {- pressTimer = setTimeout(() => handleLongPress(day), 500);- };- const handleTouchEnd = () => {- if (pressTimer) clearTimeout(pressTimer);- };-- return (- <motion.button- key={idx}- onClick={() => handleAddShift(day)}- onContextMenu={(e) => handleDayRightClick(e, day)}- onTouchStart={handleTouchStart}- onTouchEnd={handleTouchEnd}- onTouchMove={handleTouchEnd}- disabled={false}- whileTap={{ scale: 0.95 }}- style={{- WebkitUserSelect: "none",- userSelect: "none",- WebkitTouchCallout: "none",- }}- className={`- min-h-25 sm:min-h-28 px-1 py-1.5 sm:p-2.5 rounded-md sm:rounded-lg text-sm transition-all relative flex flex-col border sm:border-2- ${- isCurrentMonth- ? "text-foreground"- : "text-muted-foreground/50"- }- ${- isTodayDate- ? "border-primary shadow-lg shadow-primary/20 bg-primary/5 ring-2 ring-primary/20"- : "border-border/30 sm:border-border/50"- }- ${- isCurrentMonth- ? "hover:bg-accent cursor-pointer active:bg-accent/80 hover:border-border"- : selectedPresetId- ? "cursor-not-allowed"- : "cursor-pointer"- }- ${!isCurrentMonth ? "opacity-40" : ""}- `}- >- <div- className={`text-sm sm:text-sm font-semibold mb-1 flex items-center justify-between ${- isTodayDate ? "text-primary" : ""- }`}- >- <span>{day.getDate()}</span>- {dayNote && (- <motion.div- className="group/note relative"- onClick={(e) => handleNoteIconClick(e, day)}- title={dayNote.note}- whileHover={{ scale: 1.1 }}- whileTap={{ scale: 0.9 }}- >- <StickyNote className="h-3.5 w-3.5 text-orange-500 cursor-pointer hover:text-orange-600 transition-colors" />- {/* Tooltip for desktop */}- <div className="hidden sm:block absolute z-50 bottom-full right-0 mb-1 invisible group-hover/note:visible opacity-0 group-hover/note:opacity-100 transition-opacity duration-200">- <div className="bg-popover text-popover-foreground text-xs rounded-md shadow-lg border p-2 max-w-[200px] whitespace-normal break-words">- {dayNote.note}- <div className="absolute top-full right-2 -mt-1 border-4 border-transparent border-t-popover"></div>- </div>- </div>- </motion.div>- )}- </div>- <div className="flex-1 space-y-0.5 sm:space-y-1 overflow-hidden">- {dayShifts.slice(0, 2).map((shift) => (- <div- key={shift.id}- className="text-[10px] sm:text-xs px-0.5 py-0.5 sm:px-1.5 sm:py-1 rounded"- style={{- backgroundColor: shift.color- ? `${shift.color}20`- : "#3b82f620",- borderLeft: `2px solid ${shift.color || "#3b82f6"}`,- }}- title={`${shift.title} ${- shift.isAllDay- ? `(${t("shift.allDay")})`- : `(${shift.startTime} - ${shift.endTime})`- }`}- >- <div className="font-semibold line-clamp-2 leading-[1.1] sm:leading-tight">- {shift.title}- </div>- <div className="text-[9px] sm:text-[10px] opacity-70 leading-tight">- {shift.isAllDay- ? t("shift.allDay")- : shift.startTime.substring(0, 5)}- </div>- </div>- ))}- {dayShifts.length > 2 && (- <div className="text-[10px] sm:text-xs text-muted-foreground font-medium text-center pt-0.5">- +{dayShifts.length - 2}- </div>- )}- </div>- </motion.button>- );- })}- </div>+ <CalendarGrid+ calendarDays={calendarDays}+ currentDate={currentDate}+ shifts={shifts}+ notes={notes}+ selectedPresetId={selectedPresetId}+ isTogglingShift={isTogglingShift}+ onDayClick={handleAddShift}+ onDayRightClick={handleDayRightClick}+ onNoteIconClick={handleNoteIconClick}+ onLongPress={handleLongPress}+ />{/* Note Hint */}<motion.div@@ -1301,14 +637,12 @@ function HomeContent() {<StickyNote className="h-4 w-4 text-orange-500" /></div><div className="flex-1">- {/* Mobile hint */}<p className="text-xs sm:hidden text-foreground/80 leading-relaxed">{t("note.hintMobile", {default:"Long press on a day to open notes. The note icon shows existing notes.",})}</p>- {/* Desktop hint */}<p className="hidden sm:block text-sm text-foreground/80 leading-relaxed">{t("note.hintDesktop", {default:@@ -1322,176 +656,17 @@ function HomeContent() {{/* Shifts List */}<div className="space-y-3 sm:space-y-4 px-2 sm:px-0">- {/* Shift Statistics */}<ShiftStatscalendarId={selectedCalendar}currentDate={currentDate}refreshTrigger={statsRefreshTrigger}/>- <div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">- <button- onClick={() => setShowShiftsSection(!showShiftsSection)}- className="w-full px-3 sm:px-4 py-3 sm:py-3.5 flex items-center justify-between hover:bg-primary/5 transition-all"- >- <div className="flex items-center gap-2.5">- <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/20">- <CalendarIcon className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />- </div>- <h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- {t("shift.title")}- </h3>- </div>- <div className="flex items-center gap-3">- {!showShiftsSection &&- (() => {- const shiftsInMonth = shifts.filter((shift) => {- if (!shift.date) return false;- const shiftDate = new Date(shift.date);- return (- shiftDate.getMonth() === currentDate.getMonth() &&- shiftDate.getFullYear() === currentDate.getFullYear()- );- }).length;- return (- shiftsInMonth > 0 && (- <div className="px-3 py-1.5 bg-primary/10 rounded-full">- <span className="font-semibold text-primary text-xs sm:text-sm">- {shiftsInMonth}- </span>- </div>- )- );- })()}- {showShiftsSection ? (- <ChevronUp className="h-4 w-4 text-muted-foreground" />- ) : (- <ChevronDown className="h-4 w-4 text-muted-foreground" />- )}- </div>- </button>-- {showShiftsSection && (- <div className="border-t border-border/30 bg-muted/20 p-3 sm:p-4">- {shifts.filter((shift) => {- if (!shift.date) return false;- const shiftDate = new Date(shift.date);- return (- shiftDate.getMonth() === currentDate.getMonth() &&- shiftDate.getFullYear() === currentDate.getFullYear()- );- }).length === 0 ? (- <motion.div- className="border-2 border-dashed border-border/50 rounded-xl p-10 sm:p-14 text-center space-y-4 sm:space-y-5"- initial={{ opacity: 0, scale: 0.95 }}- animate={{ opacity: 1, scale: 1 }}- transition={{ duration: 0.3 }}- >- <motion.div- className="flex justify-center"- initial={{ scale: 0 }}- animate={{ scale: 1 }}- transition={{- delay: 0.1,- type: "spring",- stiffness: 200,- }}- >- <div className="h-16 w-16 sm:h-20 sm:w-20 rounded-full bg-gradient-to-br from-primary/20 to-primary/10 flex items-center justify-center shadow-lg">- <CalendarIcon className="h-8 w-8 sm:h-10 sm:w-10 text-primary/70" />- </div>- </motion.div>- <div className="space-y-2 sm:space-y-2.5">- <h4 className="font-bold text-lg sm:text-xl text-foreground/90">- {t("shift.noShiftsInMonth", {- default: "No shifts this month",- })}- </h4>- <p className="text-sm sm:text-base text-muted-foreground max-w-md mx-auto leading-relaxed">- {t("shift.noShiftsInMonthDescription", {- default:- "Add shifts by clicking on days in the calendar above.",- })}- </p>- </div>- </motion.div>- ) : (- <AnimatePresence mode="popLayout">- <motion.div- className="space-y-3 sm:space-y-4"- initial={{ opacity: 0 }}- animate={{ opacity: 1 }}- transition={{ staggerChildren: 0.05 }}- >- {Object.entries(- shifts- .filter((shift) => {- if (!shift.date) return false;- const shiftDate = new Date(shift.date);- return (- shiftDate.getMonth() === currentDate.getMonth() &&- shiftDate.getFullYear() ===- currentDate.getFullYear()- );- })- .sort(- (a, b) =>- (a.date ? new Date(a.date).getTime() : 0) -- (b.date ? new Date(b.date).getTime() : 0)- )- .reduce((acc, shift) => {- const dateKey = shift.date- ? format(new Date(shift.date), "yyyy-MM-dd")- : "unknown";- if (!acc[dateKey]) acc[dateKey] = [];- acc[dateKey].push(shift);- return acc;- }, {} as Record<string, ShiftWithCalendar[]>)- ).map(([dateKey, dayShifts], index) => (- <motion.div- key={dateKey}- className="border border-border/50 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-all bg-gradient-to-b from-card via-card to-muted/20"- initial={{ opacity: 0, y: 20 }}- animate={{ opacity: 1, y: 0 }}- transition={{ delay: index * 0.05 }}- layout- >- <div className="bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-4 sm:px-5 py-2.5 sm:py-3 border-b border-border/30">- <div className="flex items-center justify-between">- <div className="font-bold text-sm sm:text-base flex items-center gap-2">- <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {dayShifts[0].date &&- format(- new Date(dayShifts[0].date),- "EEEE, MMMM d, yyyy",- { locale: dateLocale }- )}- </div>- <div className="text-xs sm:text-sm px-2.5 py-1 bg-primary/15 text-primary rounded-full font-semibold shadow-sm">- {dayShifts.length}{" "}- {dayShifts.length === 1- ? t("shift.shift_one")- : t("shift.shifts")}- </div>- </div>- </div>- <div className="p-3 sm:p-4 grid gap-2 sm:gap-3 sm:grid-cols-2">- {dayShifts.map((shift) => (- <ShiftCard- key={shift.id}- shift={shift}- onDelete={deleteShift}- />- ))}- </div>- </motion.div>- ))}- </motion.div>- </AnimatePresence>- )}- </div>- )}- </div>+ <ShiftsList+ shifts={shifts}+ currentDate={currentDate}+ onDeleteShift={handleDeleteShift}+ /></div></div>@@ -1517,14 +692,14 @@ function HomeContent() {<CalendarDialogopen={showCalendarDialog}onOpenChange={setShowCalendarDialog}- onSubmit={createCalendar}+ onSubmit={createCalendarHook}/><ShiftDialogopen={showShiftDialog}onOpenChange={setShowShiftDialog}onSubmit={handleShiftSubmit}selectedDate={selectedDate}- onPresetsChange={fetchPresets}+ onPresetsChange={refetchPresets}calendarId={selectedCalendar}/>{selectedCalendar && (@@ -1549,9 +724,7 @@ function HomeContent() {hasPassword={!!calendars.find((c) => c.id === selectedCalendar)?.passwordHash}- onSuccess={() => {- fetchCalendars();- }}+ onSuccess={refetchCalendars}/>)}<NoteDialog@@ -1572,7 +745,7 @@ function HomeContent() {hasPassword={!!calendars.find((c) => c.id === calendarToDelete)?.passwordHash}- onConfirm={deleteCalendar}+ onConfirm={handleDeleteCalendar}/>)}diff --git a/components/app-header.tsx b/components/app-header.tsxnew file mode 100644index 0000000..fc37090--- /dev/null+++ b/components/app-header.tsx@@ -0,0 +1,261 @@+import { motion } from "motion/react";+import { useTranslations } from "next-intl";+import { CalendarWithCount } from "@/lib/types";+import { CalendarSelector } from "@/components/calendar-selector";+import { PresetSelector } from "@/components/preset-selector";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Calendar as CalendarIcon, Plus } from "lucide-react";+import { ShiftPreset } from "@/lib/db/schema";++interface AppHeaderProps {+ calendars: CalendarWithCount[];+ selectedCalendar: string | undefined;+ presets: ShiftPreset[];+ selectedPresetId: string | undefined;+ isConnected: boolean;+ showMobileCalendarDialog: boolean;+ onSelectCalendar: (id: string) => void;+ onSelectPreset: (id: string | undefined) => void;+ onCreateCalendar: () => void;+ onManagePassword: () => void;+ onDeleteCalendar: (id: string) => void;+ onPresetsChange: () => void;+ onShiftsChange: () => void;+ onPasswordRequired: (action: () => Promise<void>) => void;+ onManualShiftCreation: () => void;+ onMobileCalendarDialogChange: (open: boolean) => void;+}++export function AppHeader({+ calendars,+ selectedCalendar,+ presets,+ selectedPresetId,+ isConnected,+ showMobileCalendarDialog,+ onSelectCalendar,+ onSelectPreset,+ onCreateCalendar,+ onManagePassword,+ onDeleteCalendar,+ onPresetsChange,+ onShiftsChange,+ onPasswordRequired,+ onManualShiftCreation,+ onMobileCalendarDialogChange,+}: AppHeaderProps) {+ const t = useTranslations();++ return (+ <>+ <div className="sticky top-0 z-10 bg-background/80 backdrop-blur-xl border-b border-border/50 shadow-sm">+ <div className="container max-w-4xl mx-auto p-3 sm:p-4">+ <div className="space-y-3 sm:space-y-4">+ {/* Desktop: Logo + Calendar Selector in one line */}+ <div className="hidden sm:flex items-center justify-between gap-4">+ {/* Logo Section */}+ <motion.div+ className="flex items-center gap-3"+ initial={{ opacity: 0, x: -20 }}+ animate={{ opacity: 1, x: 0 }}+ transition={{ duration: 0.3 }}+ >+ <div className="relative shrink-0">+ <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-xl shadow-primary/30 ring-2 ring-primary/20">+ <CalendarIcon className="h-6 w-6 text-primary-foreground" />+ </div>+ {/* Connection Status Indicator */}+ <div+ className={`absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-full border-2 border-background transition-colors ${+ isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"+ }`}+ title={+ isConnected+ ? t("sync.reconnected")+ : t("sync.disconnected")+ }+ ></div>+ </div>+ <div>+ <h1 className="text-xl font-bold bg-gradient-to-r from-foreground via-foreground to-foreground/70 bg-clip-text">+ {t("app.title")}+ </h1>+ <p className="text-xs text-muted-foreground font-medium">+ {t("app.subtitle", { default: "Organize your shifts" })}+ </p>+ </div>+ </motion.div>++ {/* Calendar Selector - Desktop */}+ <motion.div+ className="flex items-center gap-3 min-w-0 flex-1 max-w-md bg-muted/30 rounded-xl p-2 border border-border/50"+ initial={{ opacity: 0, x: 20 }}+ animate={{ opacity: 1, x: 0 }}+ transition={{ duration: 0.3, delay: 0.1 }}+ >+ <div+ className="w-1 h-8 bg-gradient-to-b rounded-full transition-colors duration-300"+ style={{+ backgroundImage: selectedCalendar+ ? `linear-gradient(to bottom, ${+ calendars.find((c) => c.id === selectedCalendar)+ ?.color || "hsl(var(--primary))"+ }, ${+ calendars.find((c) => c.id === selectedCalendar)+ ?.color || "hsl(var(--primary))"+ }80)`+ : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",+ }}+ ></div>+ <div className="flex-1 min-w-0">+ <CalendarSelector+ calendars={calendars}+ selectedId={selectedCalendar}+ onSelect={onSelectCalendar}+ onCreateNew={onCreateCalendar}+ onManagePassword={onManagePassword}+ onDelete={onDeleteCalendar}+ />+ </div>+ </motion.div>+ </div>++ {/* Mobile: Logo Icon + Calendar Card + Add Button */}+ <div className="sm:hidden flex items-center gap-2">+ {/* Logo Icon Only */}+ <div className="relative shrink-0">+ <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary via-primary/90 to-primary/70 flex items-center justify-center shadow-lg shadow-primary/30 ring-2 ring-primary/20">+ <CalendarIcon className="h-5 w-5 text-primary-foreground" />+ </div>+ {/* Connection Status Indicator */}+ <div+ className={`absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background transition-colors ${+ isConnected ? "bg-green-500 animate-pulse" : "bg-red-500"+ }`}+ title={+ isConnected ? t("sync.reconnected") : t("sync.disconnected")+ }+ ></div>+ </div>++ {/* Calendar Selection Card */}+ <button+ onClick={() => onMobileCalendarDialogChange(true)}+ className="flex-1 bg-muted/30 backdrop-blur-sm border border-border/50 rounded-xl p-3 flex items-center justify-between gap-2 hover:bg-accent/50 transition-all active:scale-[0.98] shadow-sm"+ >+ <div className="flex items-center gap-2.5 min-w-0 flex-1">+ <div+ className="w-1 h-9 bg-gradient-to-b rounded-full transition-colors duration-300"+ style={{+ backgroundImage: selectedCalendar+ ? `linear-gradient(to bottom, ${+ calendars.find((c) => c.id === selectedCalendar)+ ?.color || "hsl(var(--primary))"+ }, ${+ calendars.find((c) => c.id === selectedCalendar)+ ?.color || "hsl(var(--primary))"+ }80)`+ : "linear-gradient(to bottom, hsl(var(--primary)), hsl(var(--primary) / 0.5))",+ }}+ ></div>+ <div className="min-w-0 flex-1 text-left">+ <p className="text-[10px] text-muted-foreground font-medium">+ {t("calendar.select", {+ default: "Your BetterShift Calendar",+ })}+ </p>+ <p className="text-sm font-semibold truncate">+ {calendars.find((c) => c.id === selectedCalendar)?.name ||+ t("calendar.title")}+ </p>+ </div>+ </div>+ <div className="shrink-0 w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center">+ <CalendarIcon className="h-4 w-4 text-primary" />+ </div>+ </button>++ {/* Mobile Add Shift Button */}+ {selectedCalendar && (+ <motion.div+ initial={{ scale: 0, opacity: 0 }}+ animate={{ scale: 1, opacity: 1 }}+ transition={{ delay: 0.2, type: "spring", stiffness: 200 }}+ >+ <Button+ size="icon"+ onClick={onManualShiftCreation}+ className="h-10 w-10 rounded-xl shadow-lg shadow-primary/30 shrink-0"+ >+ <Plus className="h-5 w-5" />+ </Button>+ </motion.div>+ )}+ </div>++ {/* Preset Selector */}+ {selectedCalendar && (+ <div className="px-0.5 sm:px-0">+ <PresetSelector+ presets={presets}+ selectedPresetId={selectedPresetId}+ onSelectPreset={onSelectPreset}+ onPresetsChange={onPresetsChange}+ onShiftsChange={onShiftsChange}+ calendarId={selectedCalendar}+ onPasswordRequired={onPasswordRequired}+ />+ </div>+ )}+ </div>+ </div>+ </div>++ {/* Mobile Calendar Dialog */}+ <Dialog+ open={showMobileCalendarDialog}+ onOpenChange={onMobileCalendarDialogChange}+ >+ <DialogContent className="sm:max-w-md p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">+ <DialogTitle className="flex items-center gap-2.5 text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">+ <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("calendar.select", { default: "Your BetterShift Calendar" })}+ </DialogTitle>+ <DialogDescription className="text-sm text-muted-foreground">+ {t("calendar.selectDescription", {+ default: "Choose a calendar to manage your shifts",+ })}+ </DialogDescription>+ </DialogHeader>+ <div className="p-6">+ <CalendarSelector+ calendars={calendars}+ selectedId={selectedCalendar}+ onSelect={(id) => {+ onSelectCalendar(id);+ onMobileCalendarDialogChange(false);+ }}+ onCreateNew={() => {+ onMobileCalendarDialogChange(false);+ onCreateCalendar();+ }}+ onManagePassword={() => {+ onMobileCalendarDialogChange(false);+ onManagePassword();+ }}+ onDelete={onDeleteCalendar}+ />+ </div>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/components/calendar-grid.tsx b/components/calendar-grid.tsxnew file mode 100644index 0000000..0800e4f--- /dev/null+++ b/components/calendar-grid.tsx@@ -0,0 +1,210 @@+import { motion } from "motion/react";+import { StickyNote } from "lucide-react";+import { ShiftWithCalendar } from "@/lib/types";+import { CalendarNote } from "@/lib/db/schema";+import { isToday } from "date-fns";+import { useTranslations } from "next-intl";+import { useRef, useEffect } from "react";++interface CalendarGridProps {+ calendarDays: Date[];+ currentDate: Date;+ shifts: ShiftWithCalendar[];+ notes: CalendarNote[];+ selectedPresetId: string | undefined;+ isTogglingShift: boolean;+ onDayClick: (date: Date) => void;+ onDayRightClick: (e: React.MouseEvent, date: Date) => void;+ onNoteIconClick: (e: React.MouseEvent, date: Date) => void;+ onLongPress: (date: Date) => void;+}++export function CalendarGrid({+ calendarDays,+ currentDate,+ shifts,+ notes,+ selectedPresetId,+ isTogglingShift,+ onDayClick,+ onDayRightClick,+ onNoteIconClick,+ onLongPress,+}: CalendarGridProps) {+ const t = useTranslations();+ const pressTimerRef = useRef<Record<string, NodeJS.Timeout>>({});++ // Cleanup all timers on unmount+ useEffect(() => {+ return () => {+ Object.values(pressTimerRef.current).forEach((timer) => {+ if (timer) clearTimeout(timer);+ });+ pressTimerRef.current = {};+ };+ }, []);++ const getShiftsForDate = (date: Date) => {+ return shifts.filter(+ (shift) => shift.date && isSameDay(new Date(shift.date), date)+ );+ };++ const isSameDay = (date1: Date, date2: Date) => {+ return (+ date1.getFullYear() === date2.getFullYear() &&+ date1.getMonth() === date2.getMonth() &&+ date1.getDate() === date2.getDate()+ );+ };++ return (+ <div className="grid grid-cols-7 gap-0 sm:gap-1.5 mb-6">+ {[+ t("calendar_grid.monday"),+ t("calendar_grid.tuesday"),+ t("calendar_grid.wednesday"),+ t("calendar_grid.thursday"),+ t("calendar_grid.friday"),+ t("calendar_grid.saturday"),+ t("calendar_grid.sunday"),+ ].map((day) => (+ <div+ key={day}+ className="text-center text-[11px] sm:text-xs font-semibold text-muted-foreground p-1 sm:p-2"+ >+ {day}+ </div>+ ))}+ {calendarDays.map((day, idx) => {+ const dayShifts = getShiftsForDate(day);+ const dayNote = notes.find(+ (note) => note.date && isSameDay(new Date(note.date), day)+ );+ const isCurrentMonth = day.getMonth() === currentDate.getMonth();+ const isTodayDate = isToday(day);++ const dayKey = `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`;++ const handleTouchStart = (e: React.TouchEvent) => {+ pressTimerRef.current[dayKey] = setTimeout(+ () => onLongPress(day),+ 500+ );+ };+ const handleTouchEnd = () => {+ if (pressTimerRef.current[dayKey]) {+ clearTimeout(pressTimerRef.current[dayKey]);+ delete pressTimerRef.current[dayKey];+ }+ };++ return (+ <motion.button+ key={idx}+ onClick={() => onDayClick(day)}+ onContextMenu={(e) => {+ e.preventDefault();+ onDayRightClick(e, day);+ }}+ onTouchStart={handleTouchStart}+ onTouchEnd={handleTouchEnd}+ onTouchMove={handleTouchEnd}+ disabled={false}+ whileTap={{ scale: 0.95 }}+ style={{+ WebkitUserSelect: "none",+ userSelect: "none",+ WebkitTouchCallout: "none",+ }}+ className={`+ min-h-25 sm:min-h-28 px-1 py-1.5 sm:p-2.5 rounded-md sm:rounded-lg text-sm transition-all relative flex flex-col border sm:border-2+ ${isCurrentMonth ? "text-foreground" : "text-muted-foreground/50"}+ ${+ isTodayDate+ ? "border-primary shadow-lg shadow-primary/20 bg-primary/5 ring-2 ring-primary/20"+ : "border-border/30 sm:border-border/50"+ }+ ${+ isCurrentMonth+ ? "hover:bg-accent cursor-pointer active:bg-accent/80 hover:border-border"+ : selectedPresetId+ ? "cursor-not-allowed"+ : "cursor-pointer"+ }+ ${!isCurrentMonth ? "opacity-40" : ""}+ `}+ >+ <div+ className={`text-sm sm:text-sm font-semibold mb-1 flex items-center justify-between ${+ isTodayDate ? "text-primary" : ""+ }`}+ >+ <span>{day.getDate()}</span>+ {dayNote && (+ <motion.div+ className="group/note relative"+ onClick={(e) => onNoteIconClick(e, day)}+ title={dayNote.note}+ whileHover={{ scale: 1.1 }}+ whileTap={{ scale: 0.9 }}+ >+ <StickyNote className="h-3.5 w-3.5 text-orange-500 cursor-pointer hover:text-orange-600 transition-colors" />+ <div className="hidden sm:block absolute z-50 bottom-full right-0 mb-1 invisible group-hover/note:visible opacity-0 group-hover/note:opacity-100 transition-opacity duration-200">+ <div className="bg-popover text-popover-foreground text-xs rounded-md shadow-lg border p-2 max-w-[200px] whitespace-normal break-words">+ {dayNote.note}+ <div className="absolute top-full right-2 -mt-1 border-4 border-transparent border-t-popover"></div>+ </div>+ </div>+ </motion.div>+ )}+ </div>+ <div className="flex-1 space-y-0.5 sm:space-y-1 overflow-hidden">+ {dayShifts.slice(0, 2).map((shift) => (+ <div+ key={shift.id}+ className="text-[10px] sm:text-xs px-0.5 py-0.5 sm:px-1.5 sm:py-1 rounded"+ style={{+ backgroundColor: shift.color+ ? `${shift.color}20`+ : "#3b82f620",+ borderLeft: `2px solid ${shift.color || "#3b82f6"}`,+ }}+ title={`${shift.title} ${+ shift.isAllDay+ ? `(${t("shift.allDay")})`+ : `(${shift.startTime} - ${shift.endTime})`+ }`}+ >+ <div className="font-semibold line-clamp-2 leading-[1.1] sm:leading-tight">+ {shift.title}+ </div>+ <div className="text-[9px] sm:text-[10px] opacity-70 leading-tight">+ {shift.isAllDay ? (+ t("shift.allDay")+ ) : (+ <>+ <span className="sm:hidden">+ {shift.startTime.substring(0, 5)}+ </span>+ <span className="hidden sm:inline">+ {shift.startTime.substring(0, 5)} -{" "}+ {shift.endTime.substring(0, 5)}+ </span>+ </>+ )}+ </div>+ </div>+ ))}+ {dayShifts.length > 2 && (+ <div className="text-[10px] sm:text-xs text-muted-foreground font-medium text-center pt-0.5">+ +{dayShifts.length - 2}+ </div>+ )}+ </div>+ </motion.button>+ );+ })}+ </div>+ );+}diff --git a/components/preset-edit-dialog.tsx b/components/preset-edit-dialog.tsxnew file mode 100644index 0000000..91b0428--- /dev/null+++ b/components/preset-edit-dialog.tsx@@ -0,0 +1,252 @@+import { useState, useEffect } from "react";+import { useTranslations } from "next-intl";+import { motion } from "motion/react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Checkbox } from "@/components/ui/checkbox";+import { ColorPicker } from "@/components/ui/color-picker";+import { ShiftPreset } from "@/lib/db/schema";++const PRESET_COLORS = [+ { name: "Blue", value: "#3b82f6" },+ { name: "Red", value: "#ef4444" },+ { name: "Green", value: "#10b981" },+ { name: "Amber", value: "#f59e0b" },+ { name: "Violet", value: "#8b5cf6" },+ { name: "Pink", value: "#ec4899" },+ { name: "Cyan", value: "#06b6d4" },+ { name: "Orange", value: "#f97316" },+];++interface PresetFormData {+ title: string;+ startTime: string;+ endTime: string;+ color: string;+ notes: string;+ isSecondary: boolean;+ isAllDay: boolean;+}++interface PresetEditDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ preset: ShiftPreset | null;+ isCreating: boolean;+ onSave: (data: PresetFormData) => void;+}++export function PresetEditDialog({+ open,+ onOpenChange,+ preset,+ isCreating,+ onSave,+}: PresetEditDialogProps) {+ const t = useTranslations();+ const [formData, setFormData] = useState<PresetFormData>({+ title: "",+ startTime: "09:00",+ endTime: "17:00",+ color: PRESET_COLORS[0].value,+ notes: "",+ isSecondary: false,+ isAllDay: false,+ });++ useEffect(() => {+ if (open && preset && !isCreating) {+ setFormData({+ title: preset.title,+ startTime: preset.startTime,+ endTime: preset.endTime,+ color: preset.color,+ notes: preset.notes || "",+ isSecondary: preset.isSecondary || false,+ isAllDay: preset.isAllDay || false,+ });+ } else if (open && isCreating) {+ setFormData({+ title: "",+ startTime: "09:00",+ endTime: "17:00",+ color: PRESET_COLORS[0].value,+ notes: "",+ isSecondary: false,+ isAllDay: false,+ });+ }+ }, [open, preset, isCreating]);++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ onSave(formData);+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[90vh] overflow-y-auto overflow-x-hidden w-[95vw] max-w-[520px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">+ <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">+ {isCreating ? t("preset.createNew") : t("preset.edit")}+ </DialogTitle>+ <DialogDescription className="text-sm text-muted-foreground">+ {isCreating+ ? t("preset.createDescription", {+ default: "Create a new preset for quick shift creation",+ })+ : t("preset.editDescription", {+ default: "Update preset details",+ })}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-5 p-6">+ <div className="space-y-2.5">+ <Label+ htmlFor="preset-title"+ className="text-sm font-medium flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.titleLabel")}+ </Label>+ <Input+ id="preset-title"+ placeholder={t("preset.namePlaceholder")}+ value={formData.title}+ onChange={(e) =>+ setFormData({ ...formData, title: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ required+ />+ </div>++ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">+ <Checkbox+ id="preset-allday"+ checked={formData.isAllDay}+ onCheckedChange={(checked) =>+ setFormData({ ...formData, isAllDay: !!checked })+ }+ />+ <Label+ htmlFor="preset-allday"+ className="text-sm font-medium cursor-pointer"+ >+ {t("shift.allDayShift")}+ </Label>+ </div>++ {!formData.isAllDay && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: "auto" }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.2 }}+ className="grid grid-cols-2 gap-3"+ >+ <div className="space-y-2">+ <Label htmlFor="preset-start" className="text-sm font-medium">+ {t("shift.startTime")}+ </Label>+ <Input+ id="preset-start"+ type="time"+ value={formData.startTime}+ onChange={(e) =>+ setFormData({ ...formData, startTime: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="preset-end" className="text-sm font-medium">+ {t("shift.endTime")}+ </Label>+ <Input+ id="preset-end"+ type="time"+ value={formData.endTime}+ onChange={(e) =>+ setFormData({ ...formData, endTime: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ />+ </div>+ </motion.div>+ )}++ <ColorPicker+ color={formData.color}+ onChange={(color) => setFormData({ ...formData, color })}+ label={t("shift.color")}+ presetColors={PRESET_COLORS}+ />++ <div className="space-y-2.5">+ <Label+ htmlFor="preset-notes"+ className="text-sm font-medium flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.notesOptional")}+ </Label>+ <Input+ id="preset-notes"+ placeholder={t("shift.notesPlaceholder")}+ value={formData.notes}+ onChange={(e) =>+ setFormData({ ...formData, notes: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ />+ </div>++ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">+ <Checkbox+ id="preset-secondary"+ checked={formData.isSecondary}+ onCheckedChange={(checked) =>+ setFormData({ ...formData, isSecondary: !!checked })+ }+ />+ <Label+ htmlFor="preset-secondary"+ className="text-sm font-medium cursor-pointer"+ >+ {t("preset.markAsSecondary")}+ </Label>+ </div>++ <div className="flex gap-2.5 pt-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ className="flex-1 h-11 border-border/50 hover:bg-muted/50"+ >+ {t("common.cancel")}+ </Button>+ <Button+ type="submit"+ disabled={!formData.title.trim()}+ className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"+ >+ {isCreating ? t("common.create") : t("common.save")}+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}++export type { PresetFormData };diff --git a/components/preset-list.tsx b/components/preset-list.tsxnew file mode 100644index 0000000..eb5a269--- /dev/null+++ b/components/preset-list.tsx@@ -0,0 +1,217 @@+import { motion } from "motion/react";+import { useTranslations } from "next-intl";+import { Button } from "@/components/ui/button";+import { Check, Plus, Settings, ChevronDown, ChevronUp } from "lucide-react";+import { ShiftPreset } from "@/lib/db/schema";++interface PresetListProps {+ presets: ShiftPreset[];+ selectedPresetId?: string;+ onSelectPreset: (presetId: string | undefined) => void;+ onCreateNew: () => void;+ onManageClick: () => void;+}++export function PresetList({+ presets,+ selectedPresetId,+ onSelectPreset,+ onCreateNew,+ onManageClick,+}: PresetListProps) {+ const t = useTranslations();+ const [showSecondary, setShowSecondary] = React.useState(false);++ const primaryPresets = presets.filter((p) => !p.isSecondary);+ const secondaryPresets = presets.filter((p) => p.isSecondary);++ if (presets.length === 0) {+ return (+ <div className="border-2 border-dashed rounded-lg p-4 sm:p-6 text-center space-y-2 sm:space-y-3">+ <div className="flex items-center justify-center gap-2 text-muted-foreground">+ <Plus className="h-4 sm:h-5 w-4 sm:w-5" />+ <p className="text-xs sm:text-sm font-medium">+ {t("preset.noPresets")}+ </p>+ </div>+ <p className="text-[10px] sm:text-xs text-muted-foreground max-w-md mx-auto">+ {t("preset.createFirstDescription")}+ </p>+ <Button onClick={onCreateNew} size="sm" className="gap-2">+ <Plus className="h-4 w-4" />+ <span className="text-xs sm:text-sm">+ {t("preset.createYourFirst")}+ </span>+ </Button>+ </div>+ );+ }++ return (+ <div className="space-y-3">+ {/* Primary Presets */}+ <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">+ {primaryPresets.map((preset) => (+ <PresetButton+ key={preset.id}+ preset={preset}+ isSelected={selectedPresetId === preset.id}+ onSelect={() =>+ onSelectPreset(+ selectedPresetId === preset.id ? undefined : preset.id+ )+ }+ />+ ))}+ <Button+ variant="outline"+ size="sm"+ onClick={onCreateNew}+ className="gap-1 text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"+ >+ <Plus className="h-3 sm:h-4 w-3 sm:w-4" />+ <span className="hidden xs:inline sm:inline">+ {t("preset.create")}+ </span>+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={onManageClick}+ className="h-8 sm:h-9 w-8 sm:w-9 p-0"+ >+ <Settings className="h-3 sm:h-4 w-3 sm:w-4" />+ </Button>+ </div>++ {/* Secondary Presets - Collapsible */}+ {secondaryPresets.length > 0 && (+ <div className="space-y-1.5">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setShowSecondary(!showSecondary)}+ className="gap-1 text-xs text-muted-foreground h-6 px-2"+ >+ {showSecondary ? (+ <ChevronUp className="h-3 w-3" />+ ) : (+ <ChevronDown className="h-3 w-3" />+ )}+ <span>+ {t("preset.secondaryPresets")} ({secondaryPresets.length})+ </span>+ </Button>+ {showSecondary && (+ <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">+ {secondaryPresets.map((preset) => (+ <PresetButton+ key={preset.id}+ preset={preset}+ isSelected={selectedPresetId === preset.id}+ onSelect={() =>+ onSelectPreset(+ selectedPresetId === preset.id ? undefined : preset.id+ )+ }+ compact+ />+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ );+}++interface PresetButtonProps {+ preset: ShiftPreset;+ isSelected: boolean;+ onSelect: () => void;+ compact?: boolean;+}++function PresetButton({+ preset,+ isSelected,+ onSelect,+ compact,+}: PresetButtonProps) {+ const t = useTranslations();++ if (compact) {+ return (+ <Button+ variant={isSelected ? "default" : "outline"}+ size="sm"+ onClick={onSelect}+ className="relative text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"+ style={{+ backgroundColor: isSelected ? preset.color : undefined,+ borderColor: preset.color,+ }}+ >+ {isSelected && <Check className="mr-1 h-3 w-3" />}+ <span className="font-medium truncate max-w-[80px] sm:max-w-none">+ {preset.title}+ </span>+ <span className="ml-1 text-[10px] sm:text-xs opacity-70">+ {preset.isAllDay ? (+ <span>{t("shift.allDay")}</span>+ ) : (+ <>+ <span className="sm:hidden">{preset.startTime}</span>+ <span className="hidden sm:inline">+ {preset.startTime} - {preset.endTime}+ </span>+ </>+ )}+ </span>+ </Button>+ );+ }++ return (+ <motion.div+ whileTap={{ scale: 0.95 }}+ initial={{ opacity: 0, scale: 0.9 }}+ animate={{ opacity: 1, scale: 1 }}+ >+ <Button+ variant={isSelected ? "default" : "outline"}+ size="sm"+ onClick={onSelect}+ className="relative text-[11px] sm:text-sm px-2 sm:px-4 h-8 sm:h-10 rounded-full font-semibold transition-all"+ style={{+ backgroundColor: isSelected ? preset.color : undefined,+ borderColor: preset.color,+ borderWidth: "2px",+ }}+ >+ {isSelected && (+ <Check className="mr-1 sm:mr-1.5 h-3 sm:h-3.5 w-3 sm:w-3.5" />+ )}+ <span className="truncate max-w-[80px] sm:max-w-none">+ {preset.title}+ </span>+ <span className="ml-1 sm:ml-1.5 text-[9px] sm:text-xs opacity-80">+ {preset.isAllDay ? (+ <span>{t("shift.allDay")}</span>+ ) : (+ <>+ <span className="sm:hidden">+ {preset.startTime.substring(0, 5)}+ </span>+ <span className="hidden sm:inline">+ {preset.startTime} - {preset.endTime}+ </span>+ </>+ )}+ </span>+ </Button>+ </motion.div>+ );+}++import React from "react";diff --git a/components/preset-manage-dialog.tsx b/components/preset-manage-dialog.tsxnew file mode 100644index 0000000..11a7b4e--- /dev/null+++ b/components/preset-manage-dialog.tsx@@ -0,0 +1,102 @@+import { useTranslations } from "next-intl";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Plus, Trash2 } from "lucide-react";+import { ShiftPreset } from "@/lib/db/schema";++interface PresetManageDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ presets: ShiftPreset[];+ onCreateNew: () => void;+ onEdit: (preset: ShiftPreset) => void;+ onDelete: (presetId: string) => void;+}++export function PresetManageDialog({+ open,+ onOpenChange,+ presets,+ onCreateNew,+ onEdit,+ onDelete,+}: PresetManageDialogProps) {+ const t = useTranslations();++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[520px] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">+ <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">+ <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">+ {t("preset.manage")}+ </DialogTitle>+ <DialogDescription className="text-sm text-muted-foreground">+ {t("preset.manageDescription", {+ default: "Edit or delete your shift presets",+ })}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-3 overflow-y-auto flex-1 p-6">+ <Button+ onClick={onCreateNew}+ className="w-full h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"+ variant="default"+ >+ <Plus className="mr-2 h-4 w-4" />+ {t("preset.createNew")}+ </Button>+ {presets.map((preset) => (+ <div+ key={preset.id}+ className="flex items-center justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"+ style={{ borderLeftColor: preset.color, borderLeftWidth: 4 }}+ >+ <div className="flex-1">+ <div className="font-semibold flex items-center gap-2">+ <div+ className="w-1 h-4 rounded-full"+ style={{ backgroundColor: preset.color }}+ ></div>+ {preset.title}+ </div>+ <div className="text-sm text-muted-foreground mt-1">+ {preset.isAllDay ? (+ <span>{t("shift.allDay")}</span>+ ) : (+ <>+ {preset.startTime} - {preset.endTime}+ </>+ )}+ </div>+ </div>+ <div className="flex gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => onEdit(preset)}+ className="h-9"+ >+ {t("common.edit")}+ </Button>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onDelete(preset.id)}+ className="h-9 w-9 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/preset-select.tsx b/components/preset-select.tsxnew file mode 100644index 0000000..2def59f--- /dev/null+++ b/components/preset-select.tsx@@ -0,0 +1,52 @@+import { useTranslations } from "next-intl";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { ShiftPreset } from "@/lib/db/schema";++interface PresetSelectProps {+ presets: ShiftPreset[];+ onPresetSelect: (preset: ShiftPreset) => void;+}++export function PresetSelect({ presets, onPresetSelect }: PresetSelectProps) {+ const t = useTranslations();++ if (presets.length === 0) {+ return null;+ }++ return (+ <div className="space-y-2.5 p-4 bg-primary/5 border border-primary/20 rounded-xl">+ <Label className="text-sm font-medium flex items-center gap-2">+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.selectPreset")}+ </Label>+ <Select+ onValueChange={(value) => {+ const preset = presets.find((p) => p.id === value);+ if (preset) onPresetSelect(preset);+ }}+ >+ <SelectTrigger className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80">+ <SelectValue placeholder={t("shift.none")} />+ </SelectTrigger>+ <SelectContent>+ {presets.map((preset) => (+ <SelectItem key={preset.id} value={preset.id}>+ {preset.title}{" "}+ {preset.isAllDay+ ? `(${t("shift.allDay")})`+ : `(${preset.startTime} - ${preset.endTime})`}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}diff --git a/components/preset-selector.tsx b/components/preset-selector.tsxindex db8ca09..8ce3b0e 100644--- a/components/preset-selector.tsx+++ b/components/preset-selector.tsx@@ -2,23 +2,15 @@import { useTranslations } from "next-intl";import { ShiftPreset } from "@/lib/db/schema";-import { Button } from "@/components/ui/button";-import { Check, Settings, Plus, ChevronDown, ChevronUp } from "lucide-react";import { useState } from "react";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogDescription,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { Trash2 } from "lucide-react";-import { Checkbox } from "@/components/ui/checkbox";-import { ColorPicker } from "@/components/ui/color-picker";-import { motion } from "motion/react";import { toast } from "sonner";+import { PresetList } from "@/components/preset-list";+import {+ PresetEditDialog,+ PresetFormData,+} from "@/components/preset-edit-dialog";+import { PresetManageDialog } from "@/components/preset-manage-dialog";+import { usePasswordProtection } from "@/hooks/usePasswordProtection";interface PresetSelectorProps {presets: ShiftPreset[];@@ -30,17 +22,6 @@ interface PresetSelectorProps {onPasswordRequired: (action: () => Promise<void>) => void;}-const PRESET_COLORS = [- { name: "Blue", value: "#3b82f6" },- { name: "Red", value: "#ef4444" },- { name: "Green", value: "#10b981" },- { name: "Amber", value: "#f59e0b" },- { name: "Violet", value: "#8b5cf6" },- { name: "Pink", value: "#ec4899" },- { name: "Cyan", value: "#06b6d4" },- { name: "Orange", value: "#f97316" },-];-export function PresetSelector({presets,selectedPresetId,@@ -52,113 +33,37 @@ export function PresetSelector({}: PresetSelectorProps) {const t = useTranslations();const [showManageDialog, setShowManageDialog] = useState(false);+ const [showEditDialog, setShowEditDialog] = useState(false);const [editingPreset, setEditingPreset] = useState<ShiftPreset | null>(null);const [isCreatingNew, setIsCreatingNew] = useState(false);- const [formData, setFormData] = useState({- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- });- const [showSecondary, setShowSecondary] = useState(false);- const resetForm = () => {- setFormData({- title: "",- startTime: "09:00",- endTime: "17:00",- color: PRESET_COLORS[0].value,- notes: "",- isSecondary: false,- isAllDay: false,- });- };+ const { withPasswordCheck, getPassword } = usePasswordProtection({+ calendarId,+ onPasswordRequired,+ });const handleCreateNew = async () => {- // Check password before opening dialog- const password = localStorage.getItem(`calendar_password_${calendarId}`);-- const checkAndCreate = async () => {- const pwd = localStorage.getItem(`calendar_password_${calendarId}`);- // Verify password by trying to fetch presets with it- const response = await fetch(- `/api/calendars/${calendarId}/verify-password`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password: pwd }),- }- );-- const data = await response.json();-- if (data.protected && !data.valid) {- // Password required or invalid- localStorage.removeItem(`calendar_password_${calendarId}`);- await onPasswordRequired(checkAndCreate);- return;- }-- // Password valid or not required, open dialog- resetForm();+ await withPasswordCheck(async () => {setIsCreatingNew(true);setEditingPreset(null);- };-- await checkAndCreate();+ setShowEditDialog(true);+ });};const handleEditPreset = async (preset: ShiftPreset) => {- // Check password before opening dialog- const checkAndEdit = async () => {- const password = localStorage.getItem(`calendar_password_${calendarId}`);- // Verify password- const response = await fetch(- `/api/calendars/${calendarId}/verify-password`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password }),- }- );-- const data = await response.json();-- if (data.protected && !data.valid) {- // Password required or invalid- localStorage.removeItem(`calendar_password_${calendarId}`);- await onPasswordRequired(checkAndEdit);- return;- }-- // Password valid or not required, open dialog+ await withPasswordCheck(async () => {setIsCreatingNew(false);setEditingPreset(preset);- setFormData({- title: preset.title,- startTime: preset.startTime,- endTime: preset.endTime,- color: preset.color,- notes: preset.notes || "",- isSecondary: preset.isSecondary || false,- isAllDay: preset.isAllDay || false,- });- };-- await checkAndEdit();+ setShowEditDialog(true);+ });};- const handleSave = async () => {+ const handleSavePreset = async (formData: PresetFormData) => {try {- // Get stored password from localStorage (already verified)- const password = localStorage.getItem(`calendar_password_${calendarId}`);+ const password = getPassword();if (isCreatingNew) {- // Create new preset- await fetch("/api/presets", {+ const response = await fetch("/api/presets", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -167,23 +72,44 @@ export function PresetSelector({password,}),});++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to create preset: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("preset.saveError"));+ return;+ }+toast.success(t("preset.created"));} else if (editingPreset) {- // Update existing preset- await fetch(`/api/presets/${editingPreset.id}`, {+ const response = await fetch(`/api/presets/${editingPreset.id}`, {method: "PATCH",headers: { "Content-Type": "application/json" },body: JSON.stringify({ ...formData, password }),});++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to update preset: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("preset.saveError"));+ return;+ }+toast.success(t("preset.updated"));- // Refresh shifts as they may have been updatedif (onShiftsChange) onShiftsChange();}+onPresetsChange();+ setShowEditDialog(false);setEditingPreset(null);setIsCreatingNew(false);- resetForm();} catch (error) {console.error("Failed to save preset:", error);toast.error(t("preset.saveError"));@@ -191,458 +117,76 @@ export function PresetSelector({};const handleDeletePreset = async (id: string) => {- // Check password first- const checkAndDelete = async () => {- const password = localStorage.getItem(`calendar_password_${calendarId}`);- // Verify password- const verifyResponse = await fetch(- `/api/calendars/${calendarId}/verify-password`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ password }),- }- );-- const data = await verifyResponse.json();-- if (data.protected && !data.valid) {- // Password required or invalid- localStorage.removeItem(`calendar_password_${calendarId}`);- await onPasswordRequired(() => handleDeletePreset(id));- return;- }-- // Password valid, confirm deletion+ await withPasswordCheck(async () => {if (!confirm(t("preset.deleteConfirm"))) return;try {- const url = password- ? `/api/presets/${id}?password=${encodeURIComponent(password)}`- : `/api/presets/${id}`;+ const password = getPassword();- await fetch(url, { method: "DELETE" });+ const response = await fetch(`/api/presets/${id}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to delete preset: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("preset.deleteError"));+ return;+ }if (selectedPresetId === id) {onSelectPreset(undefined);}+onPresetsChange();- // Refresh shifts as they may have been deletedif (onShiftsChange) onShiftsChange();toast.success(t("preset.deleted"));} catch (error) {console.error("Failed to delete preset:", error);toast.error(t("preset.deleteError"));}- };-- await checkAndDelete();+ });};return (- <div>- {presets.length === 0 ? (- <div className="border-2 border-dashed rounded-lg p-4 sm:p-6 text-center space-y-2 sm:space-y-3">- <div className="flex items-center justify-center gap-2 text-muted-foreground">- <Plus className="h-4 sm:h-5 w-4 sm:w-5" />- <p className="text-xs sm:text-sm font-medium">- {t("preset.noPresets")}- </p>- </div>- <p className="text-[10px] sm:text-xs text-muted-foreground max-w-md mx-auto">- {t("preset.createFirstDescription")}- </p>- <Button onClick={handleCreateNew} size="sm" className="gap-2">- <Plus className="h-4 w-4" />- <span className="text-xs sm:text-sm">- {t("preset.createYourFirst")}- </span>- </Button>- </div>- ) : (- <div className="space-y-3">- {/* Primary Presets */}- <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">- {presets- .filter((p) => !p.isSecondary)- .map((preset) => (- <motion.div- key={preset.id}- whileTap={{ scale: 0.95 }}- initial={{ opacity: 0, scale: 0.9 }}- animate={{ opacity: 1, scale: 1 }}- >- <Button- variant={- selectedPresetId === preset.id ? "default" : "outline"- }- size="sm"- onClick={() =>- onSelectPreset(- selectedPresetId === preset.id ? undefined : preset.id- )- }- className="relative text-[11px] sm:text-sm px-2 sm:px-4 h-8 sm:h-10 rounded-full font-semibold transition-all"- style={{- backgroundColor:- selectedPresetId === preset.id- ? preset.color- : undefined,- borderColor: preset.color,- borderWidth: "2px",- }}- >- {selectedPresetId === preset.id && (- <Check className="mr-1 sm:mr-1.5 h-3 sm:h-3.5 w-3 sm:w-3.5" />- )}- <span className="truncate max-w-[80px] sm:max-w-none">- {preset.title}- </span>- <span className="ml-1 sm:ml-1.5 text-[9px] sm:text-xs opacity-80">- {preset.isAllDay ? (- <span>{t("shift.allDay")}</span>- ) : (- <>- <span className="sm:hidden">- {preset.startTime.substring(0, 5)}- </span>- <span className="hidden sm:inline">- {preset.startTime} - {preset.endTime}- </span>- </>- )}- </span>- </Button>- </motion.div>- ))}- <Button- variant="outline"- size="sm"- onClick={handleCreateNew}- className="gap-1 text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"- >- <Plus className="h-3 sm:h-4 w-3 sm:w-4" />- <span className="hidden xs:inline sm:inline">- {t("preset.create")}- </span>- </Button>- <Button- variant="ghost"- size="sm"- onClick={() => setShowManageDialog(true)}- className="h-8 sm:h-9 w-8 sm:w-9 p-0"- >- <Settings className="h-3 sm:h-4 w-3 sm:w-4" />- </Button>- </div>-- {/* Secondary Presets - Collapsible */}- {presets.some((p) => p.isSecondary) && (- <div className="space-y-1.5">- <Button- variant="ghost"- size="sm"- onClick={() => setShowSecondary(!showSecondary)}- className="gap-1 text-xs text-muted-foreground h-6 px-2"- >- {showSecondary ? (- <ChevronUp className="h-3 w-3" />- ) : (- <ChevronDown className="h-3 w-3" />- )}- <span>- {t("preset.secondaryPresets")} (- {presets.filter((p) => p.isSecondary).length})- </span>- </Button>- {showSecondary && (- <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">- {presets- .filter((p) => p.isSecondary)- .map((preset) => (- <Button- key={preset.id}- variant={- selectedPresetId === preset.id ? "default" : "outline"- }- size="sm"- onClick={() =>- onSelectPreset(- selectedPresetId === preset.id- ? undefined- : preset.id- )- }- className="relative text-xs sm:text-sm px-2 sm:px-3 h-8 sm:h-9"- style={{- backgroundColor:- selectedPresetId === preset.id- ? preset.color- : undefined,- borderColor: preset.color,- }}- >- {selectedPresetId === preset.id && (- <Check className="mr-1 h-3 w-3" />- )}- <span className="font-medium truncate max-w-[80px] sm:max-w-none">- {preset.title}- </span>- <span className="ml-1 text-[10px] sm:text-xs opacity-70">- {preset.isAllDay ? (- <span>{t("shift.allDay")}</span>- ) : (- <>- <span className="sm:hidden">- {preset.startTime}- </span>- <span className="hidden sm:inline">- {preset.startTime} - {preset.endTime}- </span>- </>- )}- </span>- </Button>- ))}- </div>- )}- </div>- )}- </div>- )}-- {/* Manage Presets Dialog */}- <Dialog open={showManageDialog} onOpenChange={setShowManageDialog}>- <DialogContent className="sm:max-w-[520px] max-h-[85vh] flex flex-col p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">- <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- {t("preset.manage")}- </DialogTitle>- <DialogDescription className="text-sm text-muted-foreground">- {t("preset.manageDescription", {- default: "Edit or delete your shift presets",- })}- </DialogDescription>- </DialogHeader>- <div className="space-y-3 overflow-y-auto flex-1 p-6">- <Button- onClick={handleCreateNew}- className="w-full h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25"- variant="default"- >- <Plus className="mr-2 h-4 w-4" />- {t("preset.createNew")}- </Button>- {presets.map((preset) => (- <div- key={preset.id}- className="flex items-center justify-between p-4 rounded-xl border border-border/50 bg-muted/20 hover:bg-muted/30 transition-all"- style={{ borderLeftColor: preset.color, borderLeftWidth: 4 }}- >- <div className="flex-1">- <div className="font-semibold flex items-center gap-2">- <div- className="w-1 h-4 rounded-full"- style={{ backgroundColor: preset.color }}- ></div>- {preset.title}- </div>- <div className="text-sm text-muted-foreground mt-1">- {preset.isAllDay ? (- <span>{t("shift.allDay")}</span>- ) : (- <>- {preset.startTime} - {preset.endTime}- </>- )}- </div>- </div>- <div className="flex gap-2">- <Button- variant="outline"- size="sm"- onClick={() => handleEditPreset(preset)}- className="h-9"- >- {t("common.edit")}- </Button>- <Button- variant="ghost"- size="sm"- onClick={() => handleDeletePreset(preset.id)}- className="h-9 w-9 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"- >- <Trash2 className="h-4 w-4" />- </Button>- </div>- </div>- ))}- </div>- </DialogContent>- </Dialog>-- {/* Edit/Create Preset Dialog */}- <Dialog- open={!!editingPreset || isCreatingNew}- onOpenChange={(open) => {- if (!open) {- setEditingPreset(null);- setIsCreatingNew(false);- resetForm();- }+ <>+ <PresetList+ presets={presets}+ selectedPresetId={selectedPresetId}+ onSelectPreset={onSelectPreset}+ onCreateNew={handleCreateNew}+ onManageClick={() => setShowManageDialog(true)}+ />++ <PresetManageDialog+ open={showManageDialog}+ onOpenChange={setShowManageDialog}+ presets={presets}+ onCreateNew={() => {+ setShowManageDialog(false);+ handleCreateNew();+ }}+ onEdit={(preset) => {+ setShowManageDialog(false);+ handleEditPreset(preset);}}- >- <DialogContent className="max-h-[90vh] overflow-y-auto overflow-x-hidden w-[95vw] max-w-[520px] p-0 gap-0 border border-border/50 bg-gradient-to-b from-background via-background to-muted/30 backdrop-blur-xl shadow-2xl">- <DialogHeader className="border-b border-border/50 bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6 pb-5 space-y-1.5">- <DialogTitle className="text-xl font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">- {isCreatingNew ? t("preset.createNew") : t("preset.edit")}- </DialogTitle>- <DialogDescription className="text-sm text-muted-foreground">- {isCreatingNew- ? t("preset.createDescription", {- default: "Create a new preset for quick shift creation",- })- : t("preset.editDescription", {- default: "Update preset details",- })}- </DialogDescription>- </DialogHeader>- <div className="space-y-5 p-6">- <div className="space-y-2.5">- <Label- htmlFor="preset-title"- className="text-sm font-medium flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.titleLabel")}- </Label>- <Input- id="preset-title"- placeholder={t("preset.namePlaceholder")}- value={formData.title}- onChange={(e) =>- setFormData({ ...formData, title: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">- <Checkbox- id="preset-allday"- checked={formData.isAllDay}- onCheckedChange={(checked) =>- setFormData({ ...formData, isAllDay: !!checked })- }- />- <Label- htmlFor="preset-allday"- className="text-sm font-medium cursor-pointer"- >- {t("shift.allDayShift")}- </Label>- </div>- {!formData.isAllDay && (- <motion.div- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: "auto" }}- exit={{ opacity: 0, height: 0 }}- transition={{ duration: 0.2 }}- className="grid grid-cols-2 gap-3"- >- <div className="space-y-2">- <Label htmlFor="preset-start" className="text-sm font-medium">- {t("shift.startTime")}- </Label>- <Input- id="preset-start"- type="time"- value={formData.startTime}- onChange={(e) =>- setFormData({ ...formData, startTime: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- <div className="space-y-2">- <Label htmlFor="preset-end" className="text-sm font-medium">- {t("shift.endTime")}- </Label>- <Input- id="preset-end"- type="time"- value={formData.endTime}- onChange={(e) =>- setFormData({ ...formData, endTime: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- </motion.div>- )}- <ColorPicker- color={formData.color}- onChange={(color) => setFormData({ ...formData, color })}- label={t("shift.color")}- presetColors={PRESET_COLORS}- />- <div className="space-y-2.5">- <Label- htmlFor="preset-notes"- className="text-sm font-medium flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.notesOptional")}- </Label>- <Input- id="preset-notes"- placeholder={t("shift.notesPlaceholder")}- value={formData.notes}- onChange={(e) =>- setFormData({ ...formData, notes: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">- <Checkbox- id="preset-secondary"- checked={formData.isSecondary}- onCheckedChange={(checked) =>- setFormData({ ...formData, isSecondary: !!checked })- }- />- <Label- htmlFor="preset-secondary"- className="text-sm font-medium cursor-pointer"- >- {t("preset.markAsSecondary")}- </Label>- </div>- <div className="flex gap-2.5 pt-2">- <Button- type="button"- variant="outline"- onClick={() => {- setEditingPreset(null);- setIsCreatingNew(false);- resetForm();- }}- className="flex-1 h-11 border-border/50 hover:bg-muted/50"- >- {t("common.cancel")}- </Button>- <Button- type="button"- onClick={handleSave}- disabled={!formData.title.trim()}- className="flex-1 h-11 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg shadow-primary/25 disabled:opacity-50 disabled:shadow-none"- >- {isCreatingNew ? t("common.create") : t("common.save")}- </Button>- </div>- </div>- </DialogContent>- </Dialog>- </div>+ onDelete={handleDeletePreset}+ />++ <PresetEditDialog+ open={showEditDialog}+ onOpenChange={setShowEditDialog}+ preset={editingPreset}+ isCreating={isCreatingNew}+ onSave={handleSavePreset}+ />+ </>);}diff --git a/components/shift-dialog.tsx b/components/shift-dialog.tsxindex 51f4c4d..ca1b8d4 100644--- a/components/shift-dialog.tsx+++ b/components/shift-dialog.tsx@@ -1,8 +1,6 @@"use client";-import { useState, useEffect } from "react";import { useTranslations } from "next-intl";-import { motion } from "motion/react";import {Dialog,DialogContent,@@ -11,32 +9,10 @@ import {DialogDescription,} from "@/components/ui/dialog";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { Textarea } from "@/components/ui/textarea";-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from "@/components/ui/select";import { ShiftWithCalendar } from "@/lib/types";-import { ShiftPreset } from "@/lib/db/schema";-import { formatDateToLocal } from "@/lib/date-utils";-import { Checkbox } from "@/components/ui/checkbox";-import { ColorPicker } from "@/components/ui/color-picker";--const PRESET_COLORS = [- { name: "Blue", value: "#3b82f6" },- { name: "Red", value: "#ef4444" },- { name: "Green", value: "#10b981" },- { name: "Amber", value: "#f59e0b" },- { name: "Violet", value: "#8b5cf6" },- { name: "Pink", value: "#ec4899" },- { name: "Cyan", value: "#06b6d4" },- { name: "Orange", value: "#f97316" },-];+import { ShiftFormFields } from "@/components/shift-form-fields";+import { PresetSelect } from "@/components/preset-select";+import { useShiftForm } from "@/hooks/useShiftForm";interface ShiftDialogProps {open: boolean;@@ -69,135 +45,50 @@ export function ShiftDialog({calendarId,}: ShiftDialogProps) {const t = useTranslations();- const [formData, setFormData] = useState<ShiftFormData>({- date:- shift?.date && shift.date instanceof Date- ? formatDateToLocal(shift.date)- : selectedDate- ? formatDateToLocal(selectedDate)- : formatDateToLocal(new Date()),- startTime: shift?.startTime || "09:00",- endTime: shift?.endTime || "17:00",- title: shift?.title || "",- notes: shift?.notes || "",- color: shift?.color || "#3b82f6",- isAllDay: false,- });-- const [presets, setPresets] = useState<ShiftPreset[]>([]);- const [saveAsPreset, setSaveAsPreset] = useState(false); // Auto-save disabled by default- const [presetName, setPresetName] = useState("");- // Fetch presets on mount- useEffect(() => {- fetchPresets();- }, []);-- // Update form data when selectedDate or shift changes- useEffect(() => {- if (open) {- setFormData({- date:- shift?.date && shift.date instanceof Date- ? formatDateToLocal(shift.date)- : selectedDate- ? formatDateToLocal(selectedDate)- : formatDateToLocal(new Date()),- startTime: shift?.startTime || "09:00",- endTime: shift?.endTime || "17:00",- title: shift?.title || "",- notes: shift?.notes || "",- color: shift?.color || "#3b82f6",- isAllDay: shift?.isAllDay || false,- });- setSaveAsPreset(false); // Disabled by default- setPresetName("");- }- }, [open, selectedDate, shift]);+ const {+ formData,+ setFormData,+ presets,+ saveAsPreset,+ setSaveAsPreset,+ presetName,+ setPresetName,+ applyPreset,+ saveAsPresetHandler,+ resetForm,+ refetchPresets,+ } = useShiftForm({ open, shift, selectedDate, calendarId });++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!formData.title.trim()) return;- const fetchPresets = async () => {- try {- const response = await fetch("/api/presets");- const data = await response.json();- setPresets(data);- } catch (error) {- console.error("Failed to fetch presets:", error);- }- };+ // If all-day, set default times for backend+ const submitData = {+ ...formData,+ startTime: formData.isAllDay ? "00:00" : formData.startTime,+ endTime: formData.isAllDay ? "23:59" : formData.endTime,+ };- const handleSaveAsPreset = async (shiftData: ShiftFormData) => {- if (!presetName.trim() || !calendarId) return;+ onSubmit(submitData);- try {- const response = await fetch("/api/presets", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- calendarId,- title: presetName,- startTime: shiftData.startTime,- endTime: shiftData.endTime,- color: shiftData.color,- notes: shiftData.notes,- isAllDay: shiftData.isAllDay,- }),- });- await response.json();- await fetchPresets();- // Notify parent to refresh presets- if (onPresetsChange) {+ // Save as preset if enabled and it's a new shift+ if (!shift && saveAsPreset && presetName.trim()) {+ const success = await saveAsPresetHandler(submitData);+ if (success && onPresetsChange) {onPresetsChange();}- } catch (error) {- console.error("Failed to save preset:", error);}- };- const applyPreset = (preset: ShiftPreset) => {- setFormData({- ...formData,- startTime: preset.startTime,- endTime: preset.endTime,- title: preset.title,- notes: preset.notes || "",- color: preset.color,- isAllDay: preset.isAllDay || false,- });+ if (!shift) {+ resetForm();+ }+ onOpenChange(false);};- const handleSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (formData.title.trim()) {- // If all-day, set default times for backend- const submitData = {- ...formData,- startTime: formData.isAllDay ? "00:00" : formData.startTime,- endTime: formData.isAllDay ? "23:59" : formData.endTime,- };-- onSubmit(submitData);-- // Save as preset if enabled and it's a new shift- if (!shift && saveAsPreset && presetName.trim()) {- handleSaveAsPreset(submitData);- }-- if (!shift) {- setFormData({- date: selectedDate- ? formatDateToLocal(selectedDate)- : formatDateToLocal(new Date()),- startTime: "09:00",- endTime: "17:00",- title: "",- notes: "",- color: "#3b82f6",- isAllDay: false,- });- setPresetName("");- }- onOpenChange(false);- }+ const handlePresetSelect = async (preset: Parameters<typeof applyPreset>[0]) => {+ applyPreset(preset);};return (@@ -220,191 +111,17 @@ export function ShiftDialog({<form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0"><div className="p-6 space-y-5 overflow-y-auto flex-1">{/* Preset Selection */}- {!shift && presets.length > 0 && (- <div className="space-y-2.5 p-4 bg-primary/5 border border-primary/20 rounded-xl">- <Label className="text-sm font-medium flex items-center gap-2">- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.selectPreset")}- </Label>- <Select- onValueChange={(value) => {- const preset = presets.find((p) => p.id === value);- if (preset) applyPreset(preset);- }}- >- <SelectTrigger className="h-11 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80">- <SelectValue placeholder={t("shift.none")} />- </SelectTrigger>- <SelectContent>- {presets.map((preset) => (- <SelectItem key={preset.id} value={preset.id}>- {preset.title} ({preset.startTime} - {preset.endTime})- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- )}-- <div className="space-y-2.5">- <Label- htmlFor="date"- className="text-sm font-medium flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.date")}- </Label>- <Input- id="date"- type="date"- value={formData.date}- onChange={(e) =>- setFormData({ ...formData, date: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"- />- </div>-- <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">- <Checkbox- id="allDay"- checked={formData.isAllDay}- onCheckedChange={(checked) =>- setFormData({ ...formData, isAllDay: !!checked })- }- />- <Label- htmlFor="allDay"- className="text-sm font-medium cursor-pointer"- >- {t("shift.allDayShift")}- </Label>- </div>-- {!formData.isAllDay && (- <motion.div- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: "auto" }}- exit={{ opacity: 0, height: 0 }}- transition={{ duration: 0.2 }}- className="grid grid-cols-2 gap-3"- >- <div className="space-y-2">- <Label htmlFor="startTime" className="text-sm font-medium">- {t("shift.startTime")}- </Label>- <Input- id="startTime"- type="time"- value={formData.startTime}- onChange={(e) =>- setFormData({ ...formData, startTime: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- <div className="space-y-2">- <Label htmlFor="endTime" className="text-sm font-medium">- {t("shift.endTime")}- </Label>- <Input- id="endTime"- type="time"- value={formData.endTime}- onChange={(e) =>- setFormData({ ...formData, endTime: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"- />- </div>- </motion.div>- )}- <div className="space-y-2.5">- <Label- htmlFor="title"- className="text-sm font-medium flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.titleLabel")}- </Label>- <Input- id="title"- placeholder={t("shift.titlePlaceholder")}- value={formData.title}- onChange={(e) =>- setFormData({ ...formData, title: e.target.value })- }- className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"- autoFocus- />- </div>- <div className="space-y-2.5">- <Label- htmlFor="notes"- className="text-sm font-medium flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("shift.notesOptional")}- </Label>- <Textarea- id="notes"- placeholder={t("shift.notesPlaceholder")}- value={formData.notes}- onChange={(e) =>- setFormData({ ...formData, notes: e.target.value })- }- rows={3}- className="border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 resize-none"- />- </div>- <ColorPicker- color={formData.color || "#3b82f6"}- onChange={(color) => setFormData({ ...formData, color })}- label={t("shift.color")}- presetColors={PRESET_COLORS}+ {!shift && <PresetSelect presets={presets} onPresetSelect={handlePresetSelect} />}++ <ShiftFormFields+ formData={formData}+ onFormDataChange={setFormData}+ saveAsPreset={saveAsPreset}+ onSaveAsPresetChange={setSaveAsPreset}+ presetName={presetName}+ onPresetNameChange={setPresetName}+ isEditing={!!shift}/>-- {/* Auto-Save as Preset */}- {!shift && (- <div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">- <div className="flex items-center space-x-2">- <Checkbox- id="savePreset"- checked={saveAsPreset}- onCheckedChange={(checked) =>- setSaveAsPreset(checked as boolean)- }- />- <Label- htmlFor="savePreset"- className="text-sm font-medium cursor-pointer flex items-center gap-2"- >- <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>- {t("preset.saveAsPreset")}- </Label>- </div>- {saveAsPreset && (- <motion.div- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: "auto" }}- exit={{ opacity: 0, height: 0 }}- transition={{ duration: 0.2 }}- className="space-y-2 pt-1"- >- <Label htmlFor="presetName" className="text-sm">- {t("preset.presetName")}- </Label>- <Input- id="presetName"- placeholder={t("preset.presetNamePlaceholder")}- value={presetName}- onChange={(e) => setPresetName(e.target.value)}- className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"- />- </motion.div>- )}- </div>- )}</div><div className="border-t border-border/50 bg-muted/20 p-4 flex gap-2.5 flex-shrink-0">diff --git a/components/shift-form-fields.tsx b/components/shift-form-fields.tsxnew file mode 100644index 0000000..3b291fe--- /dev/null+++ b/components/shift-form-fields.tsx@@ -0,0 +1,205 @@+import { motion } from "motion/react";+import { useTranslations } from "next-intl";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Textarea } from "@/components/ui/textarea";+import { Checkbox } from "@/components/ui/checkbox";+import { ColorPicker } from "@/components/ui/color-picker";+import { ShiftFormData } from "@/components/shift-dialog";++const PRESET_COLORS = [+ { name: "Blue", value: "#3b82f6" },+ { name: "Red", value: "#ef4444" },+ { name: "Green", value: "#10b981" },+ { name: "Amber", value: "#f59e0b" },+ { name: "Violet", value: "#8b5cf6" },+ { name: "Pink", value: "#ec4899" },+ { name: "Cyan", value: "#06b6d4" },+ { name: "Orange", value: "#f97316" },+];++interface ShiftFormFieldsProps {+ formData: ShiftFormData;+ onFormDataChange: (data: ShiftFormData) => void;+ saveAsPreset: boolean;+ onSaveAsPresetChange: (value: boolean) => void;+ presetName: string;+ onPresetNameChange: (value: string) => void;+ isEditing: boolean;+}++export function ShiftFormFields({+ formData,+ onFormDataChange,+ saveAsPreset,+ onSaveAsPresetChange,+ presetName,+ onPresetNameChange,+ isEditing,+}: ShiftFormFieldsProps) {+ const t = useTranslations();++ return (+ <div className="space-y-5">+ <div className="space-y-2.5">+ <Label+ htmlFor="date"+ className="text-sm font-medium flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.date")}+ </Label>+ <Input+ id="date"+ type="date"+ value={formData.date}+ onChange={(e) =>+ onFormDataChange({ ...formData, date: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"+ />+ </div>++ <div className="flex items-center space-x-2 p-3 bg-muted/30 rounded-lg border border-border/30">+ <Checkbox+ id="allDay"+ checked={formData.isAllDay}+ onCheckedChange={(checked) =>+ onFormDataChange({ ...formData, isAllDay: !!checked })+ }+ />+ <Label htmlFor="allDay" className="text-sm font-medium cursor-pointer">+ {t("shift.allDayShift")}+ </Label>+ </div>++ {!formData.isAllDay && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: "auto" }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.2 }}+ className="grid grid-cols-2 gap-3"+ >+ <div className="space-y-2">+ <Label htmlFor="startTime" className="text-sm font-medium">+ {t("shift.startTime")}+ </Label>+ <Input+ id="startTime"+ type="time"+ value={formData.startTime}+ onChange={(e) =>+ onFormDataChange({ ...formData, startTime: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="endTime" className="text-sm font-medium">+ {t("shift.endTime")}+ </Label>+ <Input+ id="endTime"+ type="time"+ value={formData.endTime}+ onChange={(e) =>+ onFormDataChange({ ...formData, endTime: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50"+ />+ </div>+ </motion.div>+ )}++ <div className="space-y-2.5">+ <Label+ htmlFor="title"+ className="text-sm font-medium flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.titleLabel")}+ </Label>+ <Input+ id="title"+ placeholder={t("shift.titlePlaceholder")}+ value={formData.title}+ onChange={(e) =>+ onFormDataChange({ ...formData, title: e.target.value })+ }+ className="h-11 border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 backdrop-blur-sm"+ autoFocus+ />+ </div>++ <div className="space-y-2.5">+ <Label+ htmlFor="notes"+ className="text-sm font-medium flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("shift.notesOptional")}+ </Label>+ <Textarea+ id="notes"+ placeholder={t("shift.notesPlaceholder")}+ value={formData.notes}+ onChange={(e) =>+ onFormDataChange({ ...formData, notes: e.target.value })+ }+ rows={3}+ className="border-border/50 focus:border-primary/50 focus:ring-primary/20 bg-background/50 resize-none"+ />+ </div>++ <ColorPicker+ color={formData.color || "#3b82f6"}+ onChange={(color) => onFormDataChange({ ...formData, color })}+ label={t("shift.color")}+ presetColors={PRESET_COLORS}+ />++ {/* Auto-Save as Preset */}+ {!isEditing && (+ <div className="space-y-3 p-4 bg-primary/5 border border-primary/20 rounded-xl">+ <div className="flex items-center space-x-2">+ <Checkbox+ id="savePreset"+ checked={saveAsPreset}+ onCheckedChange={(checked) =>+ onSaveAsPresetChange(checked as boolean)+ }+ />+ <Label+ htmlFor="savePreset"+ className="text-sm font-medium cursor-pointer flex items-center gap-2"+ >+ <div className="w-1 h-4 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {t("preset.saveAsPreset")}+ </Label>+ </div>+ {saveAsPreset && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: "auto" }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.2 }}+ className="space-y-2 pt-1"+ >+ <Label htmlFor="presetName" className="text-sm">+ {t("preset.presetName")}+ </Label>+ <Input+ id="presetName"+ placeholder={t("preset.presetNamePlaceholder")}+ value={presetName}+ onChange={(e) => onPresetNameChange(e.target.value)}+ className="h-10 border-primary/30 focus:border-primary/50 focus:ring-primary/20 bg-background/80"+ />+ </motion.div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/components/shifts-list.tsx b/components/shifts-list.tsxnew file mode 100644index 0000000..f4ca399--- /dev/null+++ b/components/shifts-list.tsx@@ -0,0 +1,173 @@+import { useState } from "react";+import { motion, AnimatePresence } from "motion/react";+import { format } from "date-fns";+import { useTranslations, useLocale } from "next-intl";+import { de, enUS } from "date-fns/locale";+import { ShiftWithCalendar } from "@/lib/types";+import { ShiftCard } from "@/components/shift-card";+import { ChevronUp, ChevronDown, Calendar as CalendarIcon } from "lucide-react";++interface ShiftsListProps {+ shifts: ShiftWithCalendar[];+ currentDate: Date;+ onDeleteShift: (id: string) => void;+}++export function ShiftsList({+ shifts,+ currentDate,+ onDeleteShift,+}: ShiftsListProps) {+ const t = useTranslations();+ const locale = useLocale();+ const dateLocale = locale === "de" ? de : enUS;+ const [showShiftsSection, setShowShiftsSection] = useState(false);++ const shiftsInMonth = shifts.filter((shift) => {+ if (!shift.date) return false;+ const shiftDate = new Date(shift.date);+ return (+ shiftDate.getMonth() === currentDate.getMonth() &&+ shiftDate.getFullYear() === currentDate.getFullYear()+ );+ });++ const groupedShifts = shiftsInMonth+ .sort(+ (a, b) =>+ (a.date ? new Date(a.date).getTime() : 0) -+ (b.date ? new Date(b.date).getTime() : 0)+ )+ .reduce((acc, shift) => {+ const dateKey = shift.date+ ? format(new Date(shift.date), "yyyy-MM-dd")+ : "unknown";+ if (!acc[dateKey]) acc[dateKey] = [];+ acc[dateKey].push(shift);+ return acc;+ }, {} as Record<string, ShiftWithCalendar[]>);++ return (+ <div className="border border-border/50 rounded-xl bg-gradient-to-b from-card/80 via-card/60 to-card/40 backdrop-blur-sm overflow-hidden shadow-lg">+ <button+ onClick={() => setShowShiftsSection(!showShiftsSection)}+ className="w-full px-3 sm:px-4 py-3 sm:py-3.5 flex items-center justify-between hover:bg-primary/5 transition-all"+ >+ <div className="flex items-center gap-2.5">+ <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/20">+ <CalendarIcon className="h-4 w-4 sm:h-5 sm:w-5 text-primary-foreground" />+ </div>+ <h3 className="text-sm sm:text-base font-semibold bg-gradient-to-r from-foreground to-foreground/70 bg-clip-text">+ {t("shift.title")}+ </h3>+ </div>+ <div className="flex items-center gap-3">+ {!showShiftsSection && shiftsInMonth.length > 0 && (+ <div className="px-3 py-1.5 bg-primary/10 rounded-full">+ <span className="font-semibold text-primary text-xs sm:text-sm">+ {shiftsInMonth.length}+ </span>+ </div>+ )}+ {showShiftsSection ? (+ <ChevronUp className="h-4 w-4 text-muted-foreground" />+ ) : (+ <ChevronDown className="h-4 w-4 text-muted-foreground" />+ )}+ </div>+ </button>++ {showShiftsSection && (+ <div className="border-t border-border/30 bg-muted/20 p-3 sm:p-4">+ {shiftsInMonth.length === 0 ? (+ <motion.div+ className="border-2 border-dashed border-border/50 rounded-xl p-10 sm:p-14 text-center space-y-4 sm:space-y-5"+ initial={{ opacity: 0, scale: 0.95 }}+ animate={{ opacity: 1, scale: 1 }}+ transition={{ duration: 0.3 }}+ >+ <motion.div+ className="flex justify-center"+ initial={{ scale: 0 }}+ animate={{ scale: 1 }}+ transition={{+ delay: 0.1,+ type: "spring",+ stiffness: 200,+ }}+ >+ <div className="h-16 w-16 sm:h-20 sm:w-20 rounded-full bg-gradient-to-br from-primary/20 to-primary/10 flex items-center justify-center shadow-lg">+ <CalendarIcon className="h-8 w-8 sm:h-10 sm:w-10 text-primary/70" />+ </div>+ </motion.div>+ <div className="space-y-2 sm:space-y-2.5">+ <h4 className="font-bold text-lg sm:text-xl text-foreground/90">+ {t("shift.noShiftsInMonth", {+ default: "No shifts this month",+ })}+ </h4>+ <p className="text-sm sm:text-base text-muted-foreground max-w-md mx-auto leading-relaxed">+ {t("shift.noShiftsInMonthDescription", {+ default:+ "Add shifts by clicking on days in the calendar above.",+ })}+ </p>+ </div>+ </motion.div>+ ) : (+ <AnimatePresence mode="popLayout">+ <motion.div+ className="space-y-3 sm:space-y-4"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ staggerChildren: 0.05 }}+ >+ {Object.entries(groupedShifts).map(+ ([dateKey, dayShifts], index) => (+ <motion.div+ key={dateKey}+ className="border border-border/50 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-all bg-gradient-to-b from-card via-card to-muted/20"+ initial={{ opacity: 0, y: 20 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ delay: index * 0.05 }}+ layout+ >+ <div className="bg-gradient-to-r from-primary/10 via-primary/5 to-transparent px-4 sm:px-5 py-2.5 sm:py-3 border-b border-border/30">+ <div className="flex items-center justify-between">+ <div className="font-bold text-sm sm:text-base flex items-center gap-2">+ <div className="w-1 h-5 bg-gradient-to-b from-primary to-primary/50 rounded-full"></div>+ {dayShifts[0].date &&+ format(+ new Date(dayShifts[0].date),+ "EEEE, MMMM d, yyyy",+ { locale: dateLocale }+ )}+ </div>+ <div className="text-xs sm:text-sm px-2.5 py-1 bg-primary/15 text-primary rounded-full font-semibold shadow-sm">+ {dayShifts.length}{" "}+ {dayShifts.length === 1+ ? t("shift.shift_one")+ : t("shift.shifts")}+ </div>+ </div>+ </div>+ <div className="p-3 sm:p-4 grid gap-2 sm:gap-3 sm:grid-cols-2">+ {dayShifts.map((shift) => (+ <ShiftCard+ key={shift.id}+ shift={shift}+ onDelete={onDeleteShift}+ />+ ))}+ </div>+ </motion.div>+ )+ )}+ </motion.div>+ </AnimatePresence>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/hooks/useCalendars.ts b/hooks/useCalendars.tsnew file mode 100644index 0000000..1d18854--- /dev/null+++ b/hooks/useCalendars.ts@@ -0,0 +1,129 @@+import { useState, useEffect } from "react";+import { CalendarWithCount } from "@/lib/types";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++export function useCalendars(initialCalendarId?: string | null) {+ const t = useTranslations();+ const [calendars, setCalendars] = useState<CalendarWithCount[]>([]);+ const [selectedCalendar, setSelectedCalendar] = useState<+ string | undefined+ >();+ const [loading, setLoading] = useState(true);++ const fetchCalendars = async () => {+ try {+ const response = await fetch("/api/calendars");+ const data = await response.json();+ setCalendars(data);++ if (+ initialCalendarId &&+ data.some((cal: CalendarWithCount) => cal.id === initialCalendarId)+ ) {+ setSelectedCalendar(initialCalendarId);+ } else if (data.length > 0 && !selectedCalendar) {+ setSelectedCalendar(data[0].id);+ }+ } catch (error) {+ console.error("Failed to fetch calendars:", error);+ } finally {+ setLoading(false);+ }+ };++ const createCalendar = async (+ name: string,+ color: string,+ password?: string+ ) => {+ try {+ const response = await fetch("/api/calendars", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name, color, password }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to create calendar: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("calendar.createError"));+ return;+ }++ const newCalendar = await response.json();+ setCalendars((prev) => [...prev, newCalendar]);+ setSelectedCalendar(newCalendar.id);+ toast.success(t("calendar.created"));+ } catch (error) {+ console.error("Failed to create calendar:", error);+ toast.error(t("calendar.createError"));+ }+ };++ const deleteCalendar = async (calendarId: string, password?: string) => {+ try {+ const response = await fetch(`/api/calendars/${calendarId}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });++ if (response.status === 401) {+ toast.error(t("password.errorIncorrect"));+ return false;+ }++ if (response.ok) {+ setCalendars((prev) => {+ const remainingCalendars = prev.filter((c) => c.id !== calendarId);++ if (selectedCalendar === calendarId) {+ setSelectedCalendar(+ remainingCalendars.length > 0+ ? remainingCalendars[0].id+ : undefined+ );+ }++ return remainingCalendars;+ });+ localStorage.removeItem(`calendar_password_${calendarId}`);++ toast.success(t("calendar.deleted"));+ return true;+ } else {+ const errorText = await response.text();+ console.error(+ `Failed to delete calendar: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("calendar.deleteError"));+ return false;+ }+ } catch (error) {+ console.error("Failed to delete calendar:", error);+ toast.error(t("calendar.deleteError"));+ }+ return false;+ };++ useEffect(() => {+ fetchCalendars();+ }, []);++ return {+ calendars,+ selectedCalendar,+ setSelectedCalendar,+ loading,+ createCalendar,+ deleteCalendar,+ refetchCalendars: fetchCalendars,+ };+}diff --git a/hooks/useNotes.ts b/hooks/useNotes.tsnew file mode 100644index 0000000..9f6f2a9--- /dev/null+++ b/hooks/useNotes.ts@@ -0,0 +1,175 @@+import { useState, useEffect } from "react";+import { CalendarNote } from "@/lib/db/schema";+import { formatDateToLocal } from "@/lib/date-utils";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++export function useNotes(calendarId: string | undefined) {+ const t = useTranslations();+ const [notes, setNotes] = useState<CalendarNote[]>([]);++ const fetchNotes = async () => {+ if (!calendarId) return;++ try {+ const response = await fetch(`/api/notes?calendarId=${calendarId}`);+ if (!response.ok) {+ throw new Error(+ `Failed to fetch notes: ${response.status} ${response.statusText}`+ );+ }+ const data = await response.json();+ setNotes(data);+ } catch (error) {+ console.error("Failed to fetch notes:", error);+ setNotes([]);+ }+ };++ const createNote = async (+ noteText: string,+ date: Date,+ onPasswordRequired?: () => void+ ) => {+ if (!calendarId) return false;++ try {+ const password = localStorage.getItem(`calendar_password_${calendarId}`);++ const response = await fetch("/api/notes", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ calendarId: calendarId,+ date: formatDateToLocal(date),+ note: noteText,+ password,+ }),+ });++ if (response.status === 401) {+ onPasswordRequired?.();+ return false;+ }++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to create note: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("note.createError"));+ return false;+ }++ const newNote = await response.json();+ setNotes((prev) => [...prev, newNote]);+ toast.success(t("note.created"));+ return true;+ } catch (error) {+ console.error("Failed to create note:", error);+ toast.error(t("note.createError"));+ return false;+ }+ };++ const updateNote = async (+ noteId: string,+ noteText: string,+ onPasswordRequired?: () => void+ ) => {+ try {+ const password = calendarId+ ? localStorage.getItem(`calendar_password_${calendarId}`)+ : null;++ const response = await fetch(`/api/notes/${noteId}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ note: noteText, password }),+ });++ if (response.status === 401) {+ onPasswordRequired?.();+ return false;+ }++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to update note: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("note.updateError"));+ return false;+ }++ const updatedNote = await response.json();+ setNotes((prev) => prev.map((n) => (n.id === noteId ? updatedNote : n)));+ toast.success(t("note.updated"));+ return true;+ } catch (error) {+ console.error("Failed to update note:", error);+ toast.error(t("note.updateError"));+ return false;+ }+ };++ const deleteNote = async (+ noteId: string,+ onPasswordRequired?: () => void+ ) => {+ try {+ const password = calendarId+ ? localStorage.getItem(`calendar_password_${calendarId}`)+ : null;++ const response = await fetch(`/api/notes/${noteId}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });++ if (response.status === 401) {+ onPasswordRequired?.();+ return false;+ }++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to delete note: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("note.deleteError"));+ return false;+ }++ setNotes((prev) => prev.filter((n) => n.id !== noteId));+ toast.success(t("note.deleted"));+ return true;+ } catch (error) {+ console.error("Failed to delete note:", error);+ toast.error(t("note.deleteError"));+ return false;+ }+ };++ useEffect(() => {+ if (calendarId) {+ fetchNotes();+ } else {+ setNotes([]);+ }+ }, [calendarId]);++ return {+ notes,+ createNote,+ updateNote,+ deleteNote,+ refetchNotes: fetchNotes,+ };+}diff --git a/hooks/usePasswordProtection.ts b/hooks/usePasswordProtection.tsnew file mode 100644index 0000000..e039d03--- /dev/null+++ b/hooks/usePasswordProtection.ts@@ -0,0 +1,64 @@+import { useCallback } from "react";++interface UsePasswordProtectionOptions {+ calendarId: string;+ onPasswordRequired: (action: () => Promise<void>) => void;+}++export function usePasswordProtection({+ calendarId,+ onPasswordRequired,+}: UsePasswordProtectionOptions) {+ const verifyPassword = useCallback(async (): Promise<boolean> => {+ const password = localStorage.getItem(`calendar_password_${calendarId}`);++ try {+ const response = await fetch(+ `/api/calendars/${calendarId}/verify-password`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ password }),+ }+ );++ const data = await response.json();++ if (data.protected && !data.valid) {+ localStorage.removeItem(`calendar_password_${calendarId}`);+ return false;+ }++ return true;+ } catch (error) {+ console.error("Failed to verify password:", error);+ return false;+ }+ }, [calendarId]);++ const withPasswordCheck = useCallback(+ async <T>(action: () => Promise<T>): Promise<T | null> => {+ const isValid = await verifyPassword();++ if (!isValid) {+ await onPasswordRequired(async () => {+ await action();+ });+ return null;+ }++ return await action();+ },+ [verifyPassword, onPasswordRequired]+ );++ const getPassword = useCallback(() => {+ return localStorage.getItem(`calendar_password_${calendarId}`);+ }, [calendarId]);++ return {+ verifyPassword,+ withPasswordCheck,+ getPassword,+ };+}diff --git a/hooks/usePresets.ts b/hooks/usePresets.tsnew file mode 100644index 0000000..7d27e9a--- /dev/null+++ b/hooks/usePresets.ts@@ -0,0 +1,37 @@+import { useState, useEffect } from "react";+import { ShiftPreset } from "@/lib/db/schema";++export function usePresets(calendarId: string | undefined) {+ const [presets, setPresets] = useState<ShiftPreset[]>([]);++ const fetchPresets = async () => {+ if (!calendarId) return;++ try {+ const response = await fetch(`/api/presets?calendarId=${calendarId}`);+ if (!response.ok) {+ throw new Error(+ `Failed to fetch presets: ${response.status} ${response.statusText}`+ );+ }+ const data = await response.json();+ setPresets(data);+ } catch (error) {+ console.error("Failed to fetch presets:", error);+ setPresets([]);+ }+ };++ useEffect(() => {+ if (calendarId) {+ fetchPresets();+ } else {+ setPresets([]);+ }+ }, [calendarId]);++ return {+ presets,+ refetchPresets: fetchPresets,+ };+}diff --git a/hooks/useSSEConnection.ts b/hooks/useSSEConnection.tsnew file mode 100644index 0000000..fffdc60--- /dev/null+++ b/hooks/useSSEConnection.ts@@ -0,0 +1,232 @@+import { useEffect, useRef } from "react";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++interface SSEConnectionOptions {+ calendarId: string | undefined;+ onShiftUpdate: () => void;+ onPresetUpdate: () => void;+ onNoteUpdate: () => void;+ onStatsRefresh: () => void;+ isConnected: boolean;+ setIsConnected: (connected: boolean) => void;+}++export function useSSEConnection({+ calendarId,+ onShiftUpdate,+ onPresetUpdate,+ onNoteUpdate,+ onStatsRefresh,+ isConnected,+ setIsConnected,+}: SSEConnectionOptions) {+ const t = useTranslations();+ const eventSourceRef = useRef<EventSource | null>(null);+ const lastSyncTimeRef = useRef<number>(Date.now());+ const disconnectTimeRef = useRef<number | null>(null);+ const errorTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const resyncTimeoutRef = useRef<NodeJS.Timeout | null>(null);++ // Refs to avoid stale closures in SSE handlers+ const shiftUpdateRef = useRef(onShiftUpdate);+ const presetUpdateRef = useRef(onPresetUpdate);+ const noteUpdateRef = useRef(onNoteUpdate);+ const statsRefreshRef = useRef(onStatsRefresh);+ const setIsConnectedRef = useRef(setIsConnected);+ const tRef = useRef(t);++ // Update refs when callbacks or translations change+ useEffect(() => {+ shiftUpdateRef.current = onShiftUpdate;+ presetUpdateRef.current = onPresetUpdate;+ noteUpdateRef.current = onNoteUpdate;+ statsRefreshRef.current = onStatsRefresh;+ setIsConnectedRef.current = setIsConnected;+ tRef.current = t;+ }, [+ onShiftUpdate,+ onPresetUpdate,+ onNoteUpdate,+ onStatsRefresh,+ setIsConnected,+ t,+ ]);++ // Handle page visibility changes+ useEffect(() => {+ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible" && calendarId) {+ const now = Date.now();+ const timeSinceLastSync = now - lastSyncTimeRef.current;++ if (timeSinceLastSync > 30000 || disconnectTimeRef.current) {+ console.log("Tab became visible, resyncing data...");+ toast.info(tRef.current("sync.refreshing"), { duration: Infinity });+ shiftUpdateRef.current();+ presetUpdateRef.current();+ noteUpdateRef.current();+ statsRefreshRef.current();+ lastSyncTimeRef.current = now;+ disconnectTimeRef.current = null;+ setTimeout(() => toast.dismiss(), 1000);+ }+ }+ };++ const handleOnline = () => {+ console.log("Network connection restored");+ toast.dismiss();+ toast.success(tRef.current("sync.reconnected"));+ setIsConnectedRef.current(true);+ if (calendarId) {+ shiftUpdateRef.current();+ presetUpdateRef.current();+ noteUpdateRef.current();+ statsRefreshRef.current();+ lastSyncTimeRef.current = Date.now();+ disconnectTimeRef.current = null;+ }+ };++ const handleOffline = () => {+ console.log("Network connection lost");+ toast.error(tRef.current("sync.offline"), { duration: Infinity });+ setIsConnectedRef.current(false);+ disconnectTimeRef.current = Date.now();+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("online", handleOnline);+ window.addEventListener("offline", handleOffline);++ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ window.removeEventListener("online", handleOnline);+ window.removeEventListener("offline", handleOffline);+ };+ }, [calendarId]);++ // Setup SSE connection+ useEffect(() => {+ if (!calendarId) {+ if (eventSourceRef.current) {+ eventSourceRef.current.close();+ }+ return;+ }++ if (eventSourceRef.current) {+ eventSourceRef.current.close();+ }++ const eventSource = new EventSource(+ `/api/events/stream?calendarId=${calendarId}`+ );++ eventSource.onopen = () => {+ setIsConnectedRef.current(true);+ toast.dismiss();++ if (disconnectTimeRef.current) {+ const disconnectDuration = Date.now() - disconnectTimeRef.current;+ if (disconnectDuration > 10000) {+ console.log("Reconnected after long disconnect, resyncing...");+ toast.info(tRef.current("sync.resyncing"), { duration: Infinity });+ shiftUpdateRef.current();+ presetUpdateRef.current();+ noteUpdateRef.current();+ statsRefreshRef.current();+ }+ disconnectTimeRef.current = null;+ }+ lastSyncTimeRef.current = Date.now();+ };++ eventSource.onmessage = (event) => {+ try {+ const data = JSON.parse(event.data);++ if (data.type === "connected") {+ console.log("SSE connected for calendar:", data.calendarId);+ return;+ }++ if (data.type === "shift") {+ shiftUpdateRef.current();+ statsRefreshRef.current();+ } else if (data.type === "preset") {+ presetUpdateRef.current();+ } else if (data.type === "note") {+ noteUpdateRef.current();+ }++ lastSyncTimeRef.current = Date.now();+ } catch (error) {+ console.error("Error parsing SSE message:", error);+ }+ };++ eventSource.onerror = (error) => {+ console.error("SSE connection error:", error);+ setIsConnectedRef.current(false);+ disconnectTimeRef.current = Date.now();++ // Clear any existing timeouts+ if (errorTimeoutRef.current) {+ clearTimeout(errorTimeoutRef.current);+ errorTimeoutRef.current = null;+ }+ if (resyncTimeoutRef.current) {+ clearTimeout(resyncTimeoutRef.current);+ resyncTimeoutRef.current = null;+ }++ // Show error toast after delay if offline+ errorTimeoutRef.current = setTimeout(() => {+ if (!navigator.onLine) {+ toast.error(tRef.current("sync.disconnected"), {+ duration: Infinity,+ });+ }+ errorTimeoutRef.current = null;+ }, 5000);++ // Attempt resync after delay (EventSource will auto-reconnect)+ resyncTimeoutRef.current = setTimeout(() => {+ if (errorTimeoutRef.current) {+ clearTimeout(errorTimeoutRef.current);+ errorTimeoutRef.current = null;+ }+ if (calendarId && navigator.onLine) {+ console.log("Attempting to resync data...");+ shiftUpdateRef.current();+ presetUpdateRef.current();+ noteUpdateRef.current();+ }+ resyncTimeoutRef.current = null;+ }, 3000);+ };++ eventSourceRef.current = eventSource;++ return () => {+ // Clear all timeouts on cleanup+ if (errorTimeoutRef.current) {+ clearTimeout(errorTimeoutRef.current);+ errorTimeoutRef.current = null;+ }+ if (resyncTimeoutRef.current) {+ clearTimeout(resyncTimeoutRef.current);+ resyncTimeoutRef.current = null;+ }+ // Close EventSource on unmount or calendarId change+ eventSource.close();+ };+ }, [calendarId]);++ return {+ lastSyncTimeRef,+ disconnectTimeRef,+ };+}diff --git a/hooks/useShiftForm.ts b/hooks/useShiftForm.tsnew file mode 100644index 0000000..08cc004--- /dev/null+++ b/hooks/useShiftForm.ts@@ -0,0 +1,139 @@+import { useState, useEffect } from "react";+import { ShiftFormData } from "@/components/shift-dialog";+import { ShiftPreset } from "@/lib/db/schema";+import { ShiftWithCalendar } from "@/lib/types";+import { formatDateToLocal } from "@/lib/date-utils";+import { usePresets } from "@/hooks/usePresets";++interface UseShiftFormOptions {+ open: boolean;+ shift?: ShiftWithCalendar;+ selectedDate?: Date;+ calendarId?: string;+}++export function useShiftForm({+ open,+ shift,+ selectedDate,+ calendarId,+}: UseShiftFormOptions) {+ const [formData, setFormData] = useState<ShiftFormData>({+ date:+ shift?.date && shift.date instanceof Date+ ? formatDateToLocal(shift.date)+ : selectedDate+ ? formatDateToLocal(selectedDate)+ : formatDateToLocal(new Date()),+ startTime: shift?.startTime || "09:00",+ endTime: shift?.endTime || "17:00",+ title: shift?.title || "",+ notes: shift?.notes || "",+ color: shift?.color || "#3b82f6",+ isAllDay: false,+ });++ const { presets, refetchPresets } = usePresets(calendarId);+ const [saveAsPreset, setSaveAsPreset] = useState(false);+ const [presetName, setPresetName] = useState("");++ const saveAsPresetHandler = async (shiftData: ShiftFormData) => {+ if (!presetName.trim() || !calendarId) return false;++ try {+ const response = await fetch("/api/presets", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ calendarId,+ title: presetName,+ startTime: shiftData.startTime,+ endTime: shiftData.endTime,+ color: shiftData.color,+ notes: shiftData.notes,+ isAllDay: shiftData.isAllDay,+ }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to save preset: ${response.status} ${response.statusText}`,+ errorText+ );+ return false;+ }++ await response.json();+ await refetchPresets();+ return true;+ } catch (error) {+ console.error("Failed to save preset:", error);+ return false;+ }+ };++ const applyPreset = (preset: ShiftPreset) => {+ setFormData({+ ...formData,+ startTime: preset.startTime,+ endTime: preset.endTime,+ title: preset.title,+ notes: preset.notes || "",+ color: preset.color,+ isAllDay: preset.isAllDay || false,+ });+ };++ const resetForm = () => {+ setFormData({+ date: selectedDate+ ? formatDateToLocal(selectedDate)+ : formatDateToLocal(new Date()),+ startTime: "09:00",+ endTime: "17:00",+ title: "",+ notes: "",+ color: "#3b82f6",+ isAllDay: false,+ });+ setPresetName("");+ setSaveAsPreset(false);+ };++ // Update form data when dialog opens or shift/date changes+ useEffect(() => {+ if (open) {+ setFormData({+ date:+ shift?.date && shift.date instanceof Date+ ? formatDateToLocal(shift.date)+ : selectedDate+ ? formatDateToLocal(selectedDate)+ : formatDateToLocal(new Date()),+ startTime: shift?.startTime || "09:00",+ endTime: shift?.endTime || "17:00",+ title: shift?.title || "",+ notes: shift?.notes || "",+ color: shift?.color || "#3b82f6",+ isAllDay: shift?.isAllDay || false,+ });+ setSaveAsPreset(false);+ setPresetName("");+ }+ }, [open, selectedDate, shift]);++ return {+ formData,+ setFormData,+ presets,+ saveAsPreset,+ setSaveAsPreset,+ presetName,+ setPresetName,+ applyPreset,+ saveAsPresetHandler,+ resetForm,+ refetchPresets,+ };+}diff --git a/hooks/useShifts.ts b/hooks/useShifts.tsnew file mode 100644index 0000000..4fe6d3f--- /dev/null+++ b/hooks/useShifts.ts@@ -0,0 +1,173 @@+import { useState, useEffect } from "react";+import { ShiftWithCalendar } from "@/lib/types";+import { ShiftFormData } from "@/components/shift-dialog";+import { toast } from "sonner";+import { useTranslations } from "next-intl";++export function useShifts(calendarId: string | undefined) {+ const t = useTranslations();+ const [shifts, setShifts] = useState<ShiftWithCalendar[]>([]);++ const fetchShifts = async () => {+ if (!calendarId) return;++ try {+ const response = await fetch(`/api/shifts?calendarId=${calendarId}`);+ const data = await response.json();+ setShifts(data);+ } catch (error) {+ console.error("Failed to fetch shifts:", error);+ }+ };++ const createShift = async (formData: ShiftFormData) => {+ if (!calendarId) return;++ const tempId = `temp-${Date.now()}`;+ const optimisticShift: ShiftWithCalendar = {+ id: tempId,+ date: new Date(formData.date),+ startTime: formData.startTime,+ endTime: formData.endTime,+ title: formData.title,+ color: formData.color || "#000000",+ notes: formData.notes || null,+ isAllDay: formData.isAllDay || false,+ calendarId: calendarId,+ createdAt: new Date(),+ updatedAt: new Date(),+ };++ setShifts((prev) => [...prev, optimisticShift]);++ try {+ const response = await fetch("/api/shifts", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ ...formData,+ calendarId: calendarId,+ }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to create shift: ${response.status} ${response.statusText}`,+ errorText+ );+ setShifts((shifts) => shifts.filter((s) => s.id !== tempId));+ toast.error(t("shift.createError"));+ return;+ }++ const newShift = await response.json();+ setShifts((shifts) =>+ shifts.map((s) => (s.id === tempId ? newShift : s))+ );+ toast.success(t("shift.created"));+ } catch (error) {+ console.error("Failed to create shift:", error);+ setShifts((shifts) => shifts.filter((s) => s.id !== tempId));+ toast.error(t("shift.createError"));+ }+ };++ const updateShift = async (+ id: string,+ formData: ShiftFormData,+ onPasswordRequired?: () => void+ ) => {+ try {+ const password = calendarId+ ? localStorage.getItem(`calendar_password_${calendarId}`)+ : null;++ const response = await fetch(`/api/shifts/${id}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...formData, password }),+ });++ if (response.status === 401) {+ onPasswordRequired?.();+ return false;+ }++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to update shift: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("shift.updateError"));+ return false;+ }++ const updatedShift = await response.json();+ setShifts((prev) => prev.map((s) => (s.id === id ? updatedShift : s)));+ toast.success(t("shift.updated"));+ return true;+ } catch (error) {+ console.error("Failed to update shift:", error);+ toast.error(t("shift.updateError"));+ return false;+ }+ };++ const deleteShift = async (id: string, onPasswordRequired?: () => void) => {+ try {+ const password = calendarId+ ? localStorage.getItem(`calendar_password_${calendarId}`)+ : null;++ const response = await fetch(`/api/shifts/${id}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ password }),+ });++ if (response.status === 401) {+ onPasswordRequired?.();+ return false;+ }++ if (!response.ok) {+ const errorText = await response.text();+ console.error(+ `Failed to delete shift: ${response.status} ${response.statusText}`,+ errorText+ );+ toast.error(t("shift.deleteError"));+ return false;+ }++ setShifts((prev) => prev.filter((s) => s.id !== id));+ toast.success(t("shift.deleted"));+ return true;+ } catch (error) {+ console.error("Failed to delete shift:", error);+ toast.error(t("shift.deleteError"));+ return false;+ }+ };++ useEffect(() => {+ if (calendarId) {+ fetchShifts();+ } else {+ setShifts([]);+ }+ }, [calendarId]);++ return {+ shifts,+ setShifts,+ createShift,+ updateShift,+ deleteShift,+ refetchShifts: fetchShifts,+ };+}