import { i as __toESM } from "../_runtime.mjs";
import { g as useNavigate, h as Link } from "../_libs/@tanstack/react-router+[...].mjs";
import { c as createServerFn } from "./createServerFn-CIHAFgYl.mjs";
import { b as require_react, y as require_jsx_runtime } from "../_libs/@radix-ui/react-accordion+[...].mjs";
import { n as useServerFn, t as createSsrRpc } from "./createSsrRpc-CQD-iuId.mjs";
import { t as requireSupabaseAuth } from "./auth-middleware-tiFBA43n.mjs";
import { t as supabase } from "./client-DL1N1MJt.mjs";
import { t as cva } from "../_libs/class-variance-authority+clsx.mjs";
import { a as cn, o as formatDuration, s as formatPrice, t as Button } from "./button-BJ7sUxAL.mjs";
import { n as Label, t as Input } from "./label-BJlqMHkc.mjs";
import { n as CardContent, t as Card } from "./card-BuMrzT75.mjs";
import { a as objectType, i as numberType, n as enumType, o as stringType, t as booleanType } from "../_libs/zod.mjs";
import { i as useQuery, o as useQueryClient, t as useMutation } from "../_libs/tanstack__react-query.mjs";
import { n as toast } from "../_libs/sonner.mjs";
import { c as LogOut, l as LoaderCircle } from "../_libs/lucide-react.mjs";
import { i as Trigger, n as List, r as Root2, t as Content } from "../_libs/radix-ui__react-tabs.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/admin-DlN7wokE.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
var Tabs = Root2;
var TabsList = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(List, {
	ref,
	className: cn("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground", className),
	...props
}));
TabsList.displayName = List.displayName;
var TabsTrigger = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Trigger, {
	ref,
	className: cn("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background cursor-pointer transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow", className),
	...props
}));
TabsTrigger.displayName = Trigger.displayName;
var TabsContent = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Content, {
	ref,
	className: cn("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", className),
	...props
}));
TabsContent.displayName = Content.displayName;
var badgeVariants = cva("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", {
	variants: { variant: {
		default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
		secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
		destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
		outline: "text-foreground"
	} },
	defaultVariants: { variant: "default" }
});
function Badge({ className, variant, ...props }) {
	return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
		className: cn(badgeVariants({ variant }), className),
		...props
	});
}
/** If no admin exists yet, grant admin role to the current signed-in user. */
var bootstrapAdminIfNone = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).handler(createSsrRpc("4ace4570f991c075b5a867d81119d2f45921163af898eb5e7e5fc80a3d7b8e98"));
var isCurrentUserAdmin = createServerFn({ method: "GET" }).middleware([requireSupabaseAuth]).handler(createSsrRpc("a45e00ad593665a6a088648f7fc61e2ccc9c10c96e673c43a1b3b060a647427c"));
var updateServiceInput = objectType({
	id: stringType().uuid(),
	price: numberType().nullable(),
	duration_minutes: numberType().int().nullable(),
	active: booleanType().optional()
});
var updateService = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => updateServiceInput.parse(d)).handler(createSsrRpc("f794c7dd65be4ac125cb831bfc785502112fd4fdd11439dba579bf1be06cedee"));
var setStatusInput = objectType({
	id: stringType().uuid(),
	status: enumType([
		"scheduled",
		"completed",
		"cancelled",
		"no_show"
	])
});
var setAppointmentStatus = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => setStatusInput.parse(d)).handler(createSsrRpc("48c24c547c97a5aad30561af9b7aef26828854e5b44aca5eff77d783954ec677"));
var addBlockInput = objectType({
	providerId: stringType().uuid(),
	startTime: stringType(),
	endTime: stringType(),
	reason: stringType().max(200).optional().nullable()
});
var addBlockedTime = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => addBlockInput.parse(d)).handler(createSsrRpc("c4cd22d504e1738dc016662e8e21329284c5ff9140ec42dfac61b3fb498cb7bb"));
var TIME_RE = /^\d{2}:\d{2}$/;
var addAvailabilityInput = objectType({
	providerId: stringType().uuid(),
	date: stringType().regex(/^\d{4}-\d{2}-\d{2}$/),
	startTime: stringType().regex(TIME_RE),
	endTime: stringType().regex(TIME_RE)
});
var addAvailability = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => addAvailabilityInput.parse(d)).handler(createSsrRpc("02666ce88815bf1e5d6434665392e5d9b3e21037eff361349270bc822222f26f"));
var deleteAvailabilityInput = objectType({ id: stringType().uuid() });
var deleteAvailability = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => deleteAvailabilityInput.parse(d)).handler(createSsrRpc("e224b0438c173aac6a36788a6aeaf80642baad92223f33cd8e2671499e6a8b68"));
var settingInput = objectType({
	key: stringType().min(1),
	value: stringType()
});
var upsertSetting = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => settingInput.parse(d)).handler(createSsrRpc("9ec7f3a618f0bbb27900e9a7a04c06a55fad47bdfb9b546adea1038e8572761f"));
var manualApptInput = objectType({
	providerId: stringType().uuid(),
	serviceId: stringType().uuid(),
	startTime: stringType(),
	clientName: stringType().min(1).max(100),
	clientPhone: stringType().min(1).max(30),
	note: stringType().max(500).optional().nullable()
});
var adminCreateAppointment = createServerFn({ method: "POST" }).middleware([requireSupabaseAuth]).inputValidator((d) => manualApptInput.parse(d)).handler(createSsrRpc("7d21fc5777ec7133c2f3f295ae307a75db3300be962f7ff1689c178f7f77a9ba"));
function AdminPage() {
	const nav = useNavigate();
	const qc = useQueryClient();
	const bootstrap = useServerFn(bootstrapAdminIfNone);
	const checkAdmin = useServerFn(isCurrentUserAdmin);
	const adminQ = useQuery({
		queryKey: ["is-admin"],
		queryFn: () => checkAdmin()
	});
	(0, import_react.useEffect)(() => {
		if (adminQ.data && !adminQ.data.isAdmin) bootstrap().then((r) => {
			if (r.granted) {
				toast.success("Dobili ste admin ulogu");
				qc.invalidateQueries({ queryKey: ["is-admin"] });
			}
		}).catch(() => {});
	}, [
		adminQ.data,
		bootstrap,
		qc
	]);
	async function logout() {
		await supabase.auth.signOut();
		nav({ to: "/auth" });
	}
	if (adminQ.isLoading) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FullscreenLoader, {});
	if (!adminQ.data?.isAdmin) return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "mx-auto max-w-md p-10 text-center",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", {
				className: "text-2xl",
				children: "Nemate admin pristup"
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
				className: "mt-3 text-muted-foreground",
				children: "Ako ste prvi korisnik, sačekajte trenutak – uloga se automatski dodeljuje."
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				onClick: () => adminQ.refetch(),
				className: "mt-4",
				children: "Osveži"
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				variant: "ghost",
				onClick: logout,
				className: "mt-2",
				children: "Odjavi se"
			})
		]
	});
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "min-h-screen bg-background",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("header", {
			className: "border-b border-border/60 bg-background",
			children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "mx-auto flex max-w-7xl items-center gap-4 px-4 py-4",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, {
					to: "/",
					className: "font-display text-xl",
					children: "Švonja Beauty · Admin"
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "ml-auto flex items-center gap-2",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
						variant: "ghost",
						size: "sm",
						asChild: true,
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Link, {
							to: "/",
							children: "Sajt"
						})
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
						variant: "ghost",
						size: "sm",
						onClick: logout,
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogOut, { className: "mr-1 h-4 w-4" }), " Odjava"]
					})]
				})]
			})
		}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("main", {
			className: "mx-auto max-w-7xl px-4 py-8",
			children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Tabs, {
				defaultValue: "slots",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TabsList, {
						className: "mb-6 flex-wrap",
						children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "slots",
								children: "Slobodni termini"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "appointments",
								children: "Zakazano"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "services",
								children: "Usluge i cene"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "blocks",
								children: "Blokade"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "sms",
								children: "SMS logovi"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsTrigger, {
								value: "settings",
								children: "Podešavanja"
							})
						]
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "slots",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AvailabilityTab, {})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "appointments",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AppointmentsTab, {})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "services",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ServicesTab, {})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "blocks",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(BlocksTab, {})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "sms",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SmsTab, {})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
						value: "settings",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SettingsTab, {})
					})
				]
			})
		})]
	});
}
function FullscreenLoader() {
	return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
		className: "flex min-h-screen items-center justify-center",
		children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LoaderCircle, { className: "h-6 w-6 animate-spin text-primary" })
	});
}
function AppointmentsTab() {
	const qc = useQueryClient();
	const [providerFilter, setProviderFilter] = (0, import_react.useState)("all");
	const setStatus = useServerFn(setAppointmentStatus);
	const createManual = useServerFn(adminCreateAppointment);
	const provs = useQuery({
		queryKey: ["providers"],
		queryFn: async () => (await supabase.from("providers").select("*").order("sort_order")).data ?? []
	});
	const appts = useQuery({
		queryKey: ["appointments", providerFilter],
		queryFn: async () => {
			let q = supabase.from("appointments").select("*, services(name), providers(name)").order("start_time", { ascending: true });
			if (providerFilter !== "all") q = q.eq("provider_id", providerFilter);
			const { data, error } = await q;
			if (error) throw error;
			return data ?? [];
		}
	});
	const svcQ = useQuery({
		queryKey: ["all-services"],
		queryFn: async () => (await supabase.from("services").select("id, name, provider_id, category").order("sort_order")).data ?? []
	});
	const statusMut = useMutation({
		mutationFn: (v) => setStatus({ data: v }),
		onSuccess: () => {
			qc.invalidateQueries({ queryKey: ["appointments"] });
			toast.success("Ažurirano");
		},
		onError: (e) => toast.error(e.message)
	});
	const now = Date.now();
	const upcoming = (appts.data ?? []).filter((a) => new Date(a.start_time).getTime() >= now - 24 * 36e5);
	const past = (appts.data ?? []).filter((a) => new Date(a.start_time).getTime() < now - 24 * 36e5);
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "space-y-6",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "flex flex-wrap items-end gap-3",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: "Filter: osoba" }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("select", {
					className: "mt-1 h-9 rounded-md border border-input bg-background px-3 text-sm",
					value: providerFilter,
					onChange: (e) => setProviderFilter(e.target.value),
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
						value: "all",
						children: "Sve"
					}), (provs.data ?? []).map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
						value: p.id,
						children: p.name
					}, p.id))]
				})] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ManualBook, {
					onCreate: async (v) => {
						try {
							await createManual({ data: v });
							qc.invalidateQueries({ queryKey: ["appointments"] });
							toast.success("Termin dodat");
						} catch (e) {
							toast.error(e.message);
						}
					},
					services: svcQ.data ?? [],
					providers: provs.data ?? []
				})]
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h2", {
				className: "text-xl mb-3",
				children: [
					"Predstojeći termini (",
					upcoming.length,
					")"
				]
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ApptList, {
				items: upcoming,
				onStatus: (id, s) => statusMut.mutate({
					id,
					status: s
				})
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h2", {
				className: "text-xl mb-3 text-muted-foreground",
				children: "Prošli termini"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ApptList, {
				items: past.slice(0, 30),
				onStatus: (id, s) => statusMut.mutate({
					id,
					status: s
				})
			})] })
		]
	});
}
function ApptList({ items, onStatus }) {
	if (items.length === 0) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
		className: "text-sm text-muted-foreground",
		children: "Nema termina."
	});
	return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
		className: "space-y-2",
		children: items.map((a) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
			className: "grid gap-3 p-4 md:grid-cols-[1fr_auto_auto]",
			children: [
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "min-w-0",
					children: [
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "flex flex-wrap items-center gap-2",
							children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
									className: "font-medium",
									children: a.client_name
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", {
									href: `tel:${a.client_phone}`,
									className: "text-sm text-primary",
									children: a.client_phone
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(StatusBadge, { status: a.status })
							]
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "mt-1 text-sm text-muted-foreground truncate",
							children: [
								a.services?.name,
								" · ",
								a.providers?.name
							]
						}),
						a.note && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "mt-1 text-xs text-muted-foreground",
							children: ["📝 ", a.note]
						})
					]
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "text-sm md:text-right",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: new Date(a.start_time).toLocaleDateString("sr-Latn-RS") }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "text-muted-foreground",
						children: [
							new Date(a.start_time).toLocaleTimeString("sr-Latn-RS", {
								hour: "2-digit",
								minute: "2-digit"
							}),
							" –",
							" ",
							new Date(a.end_time).toLocaleTimeString("sr-Latn-RS", {
								hour: "2-digit",
								minute: "2-digit"
							})
						]
					})]
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "flex flex-wrap gap-1",
					children: [a.status !== "completed" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
						size: "sm",
						variant: "outline",
						onClick: () => onStatus(a.id, "completed"),
						children: "Završi"
					}), a.status !== "cancelled" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
						size: "sm",
						variant: "ghost",
						onClick: () => onStatus(a.id, "cancelled"),
						children: "Otkaži"
					})]
				})
			]
		}) }, a.id))
	});
}
function StatusBadge({ status }) {
	return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, {
		className: {
			scheduled: "bg-primary/10 text-primary",
			completed: "bg-emerald-100 text-emerald-700",
			cancelled: "bg-muted text-muted-foreground",
			no_show: "bg-destructive/10 text-destructive"
		}[status] ?? "",
		children: {
			scheduled: "Zakazano",
			completed: "Završeno",
			cancelled: "Otkazano",
			no_show: "Nije došla"
		}[status] ?? status
	});
}
function ManualBook({ onCreate, services, providers }) {
	const [providerId, setProviderId] = (0, import_react.useState)("");
	const [serviceId, setServiceId] = (0, import_react.useState)("");
	const [dt, setDt] = (0, import_react.useState)("");
	const [name, setName] = (0, import_react.useState)("");
	const [phone, setPhone] = (0, import_react.useState)("");
	const filteredServices = services.filter((s) => !providerId || s.provider_id === providerId);
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "flex flex-wrap items-end gap-2 rounded-xl border border-dashed border-border p-3",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
				className: "text-xs",
				children: "Osoba"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("select", {
				className: "mt-1 h-9 rounded-md border bg-background px-2 text-sm",
				value: providerId,
				onChange: (e) => setProviderId(e.target.value),
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: "",
					children: "—"
				}), providers.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: p.id,
					children: p.name
				}, p.id))]
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
				className: "text-xs",
				children: "Usluga"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("select", {
				className: "mt-1 h-9 rounded-md border bg-background px-2 text-sm",
				value: serviceId,
				onChange: (e) => setServiceId(e.target.value),
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: "",
					children: "—"
				}), filteredServices.map((s) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: s.id,
					children: s.name
				}, s.id))]
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
				className: "text-xs",
				children: "Datum i vreme"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				type: "datetime-local",
				className: "h-9",
				value: dt,
				onChange: (e) => setDt(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
				className: "text-xs",
				children: "Ime klijenta"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				className: "h-9",
				value: name,
				onChange: (e) => setName(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
				className: "text-xs",
				children: "Telefon"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				className: "h-9",
				value: phone,
				onChange: (e) => setPhone(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				size: "sm",
				disabled: !providerId || !serviceId || !dt || !name || !phone,
				onClick: () => {
					onCreate({
						providerId,
						serviceId,
						startTime: new Date(dt).toISOString(),
						clientName: name,
						clientPhone: phone
					});
					setDt("");
					setName("");
					setPhone("");
				},
				children: "Dodaj termin"
			})
		]
	});
}
function ServicesTab() {
	const qc = useQueryClient();
	const update = useServerFn(updateService);
	const svc = useQuery({
		queryKey: ["services-admin"],
		queryFn: async () => (await supabase.from("services").select("*, providers(name)").order("sort_order")).data ?? []
	});
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "space-y-2",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
			className: "mb-4 text-sm text-muted-foreground",
			children: "Cene se unose kao konačne, sa uračunatim porezom. Trajanje je u minutima i određuje koliko se termin zauzima u kalendaru."
		}), (svc.data ?? []).map((s) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
			className: "grid gap-3 p-4 md:grid-cols-[1fr_auto_auto_auto]",
			children: [
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
					className: "font-medium",
					children: s.name
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "text-xs text-muted-foreground",
					children: [
						s.category,
						" · ",
						s.providers?.name
					]
				})] }),
				/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PriceInput, {
					value: s.price != null ? Number(s.price) : null,
					onSave: (v) => update({ data: {
						id: s.id,
						price: v,
						duration_minutes: s.duration_minutes
					} }).then(() => {
						toast.success("Sačuvano");
						qc.invalidateQueries({ queryKey: ["services-admin"] });
					}).catch((e) => toast.error(e.message)),
					placeholder: "Cena (RSD)"
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PriceInput, {
					value: s.duration_minutes,
					onSave: (v) => update({ data: {
						id: s.id,
						price: s.price != null ? Number(s.price) : null,
						duration_minutes: v
					} }).then(() => {
						toast.success("Sačuvano");
						qc.invalidateQueries({ queryKey: ["services-admin"] });
					}).catch((e) => toast.error(e.message)),
					placeholder: "Trajanje (min)"
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "text-xs text-muted-foreground",
					children: [
						formatPrice(s.price != null ? Number(s.price) : null),
						" · ",
						formatDuration(s.duration_minutes)
					]
				})
			]
		}) }, s.id))]
	});
}
function PriceInput({ value, onSave, placeholder }) {
	const [v, setV] = (0, import_react.useState)(value != null ? String(value) : "");
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "flex gap-2",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
			className: "h-9 w-32",
			value: v,
			onChange: (e) => setV(e.target.value),
			placeholder
		}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
			size: "sm",
			variant: "outline",
			onClick: () => onSave(v === "" ? null : Number(v)),
			children: "Sačuvaj"
		})]
	});
}
var DAYS_AHEAD = 14;
function toIsoDate(d) {
	return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
/** 07:00 – 21:00 in 15-min steps. */
var TIME_OPTIONS = Array.from({ length: 57 }, (_, i) => {
	const mins = 420 + i * 15;
	return `${String(Math.floor(mins / 60)).padStart(2, "0")}:${String(mins % 60).padStart(2, "0")}`;
});
function AvailabilityTab() {
	const qc = useQueryClient();
	const add = useServerFn(addAvailability);
	const del = useServerFn(deleteAvailability);
	const provs = useQuery({
		queryKey: ["providers"],
		queryFn: async () => (await supabase.from("providers").select("*").order("sort_order")).data ?? []
	});
	const [providerId, setProviderId] = (0, import_react.useState)("");
	const activeProviderId = providerId || provs.data?.[0]?.id || "";
	const days = (0, import_react.useMemo)(() => {
		const today = /* @__PURE__ */ new Date();
		return Array.from({ length: DAYS_AHEAD }, (_, i) => {
			const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
			return {
				iso: toIsoDate(d),
				label: d.toLocaleDateString("sr-Latn-RS", {
					weekday: "long",
					day: "numeric",
					month: "numeric"
				})
			};
		});
	}, []);
	const avail = useQuery({
		queryKey: ["availability", activeProviderId],
		enabled: !!activeProviderId,
		queryFn: async () => {
			const { data, error } = await supabase.from("availability").select("*").eq("provider_id", activeProviderId).gte("date", days[0].iso).lte("date", days[days.length - 1].iso).order("date").order("start_time");
			if (error) throw error;
			return data ?? [];
		}
	});
	const addMut = useMutation({
		mutationFn: (v) => add({ data: {
			providerId: activeProviderId,
			...v
		} }),
		onSuccess: () => {
			qc.invalidateQueries({ queryKey: ["availability"] });
			toast.success("Termini dodati");
		},
		onError: (e) => toast.error(e.message)
	});
	const delMut = useMutation({
		mutationFn: (id) => del({ data: { id } }),
		onSuccess: () => qc.invalidateQueries({ queryKey: ["availability"] }),
		onError: (e) => toast.error(e.message)
	});
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "space-y-6",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
				className: "text-sm text-muted-foreground",
				children: "Unesite kada primate klijente za svaki dan — sajt nudi samo ove termine, u koracima od 15 minuta. Za dvokratno radno vreme dodajte dva intervala u istom danu (npr. 09:00–13:00 i 16:00–20:00)."
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", {
				className: "rounded-xl border border-amber-300/60 bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "Važno:" }),
					" termin se nudi klijentu samo ako usluga ",
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)("em", { children: "cela staje" }),
					" u uneti interval. Uslugama bez unetog trajanja računa se 30 minuta — unesite prava trajanja u tabu „Usluge i cene\"."
				]
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: "flex flex-wrap gap-2",
				children: (provs.data ?? []).map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					variant: activeProviderId === p.id ? "default" : "outline",
					size: "sm",
					onClick: () => setProviderId(p.id),
					children: [
						p.name,
						" · ",
						p.role
					]
				}, p.id))
			}),
			avail.isLoading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FullscreenLoader, {}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: "grid gap-3",
				children: days.map((day) => {
					const ranges = (avail.data ?? []).filter((a) => a.date === day.iso);
					return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
						className: "flex flex-wrap items-center gap-3 p-4",
						children: [
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
								className: "w-40 text-sm font-medium capitalize",
								children: day.label
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
								className: "flex flex-wrap items-center gap-2",
								children: [ranges.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
									className: "text-xs text-muted-foreground",
									children: "Nema unetih termina"
								}), ranges.map((r) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
									variant: "outline",
									className: "gap-1 py-1 pl-3 pr-1 text-sm font-normal",
									children: [
										r.start_time.slice(0, 5),
										" – ",
										r.end_time.slice(0, 5),
										/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
											"aria-label": "Obriši interval",
											className: "ml-1 rounded px-1.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive",
											onClick: () => delMut.mutate(r.id),
											children: "×"
										})
									]
								}, r.id))]
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)(AddRange, {
								className: "ml-auto",
								disabled: addMut.isPending,
								onAdd: (startTime, endTime) => addMut.mutate({
									date: day.iso,
									startTime,
									endTime
								})
							})
						]
					}) }, day.iso);
				})
			})
		]
	});
}
function AddRange({ onAdd, disabled, className }) {
	const [start, setStart] = (0, import_react.useState)("09:00");
	const [end, setEnd] = (0, import_react.useState)("13:00");
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: `flex items-center gap-1.5 ${className ?? ""}`,
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
				className: "h-8 rounded-md border bg-background px-2 text-sm",
				value: start,
				onChange: (e) => setStart(e.target.value),
				children: TIME_OPTIONS.map((t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: t,
					children: t
				}, t))
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
				className: "text-sm text-muted-foreground",
				children: "–"
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("select", {
				className: "h-8 rounded-md border bg-background px-2 text-sm",
				value: end,
				onChange: (e) => setEnd(e.target.value),
				children: TIME_OPTIONS.map((t) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
					value: t,
					children: t
				}, t))
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				size: "sm",
				variant: "outline",
				disabled: disabled || end <= start,
				onClick: () => onAdd(start, end),
				children: "Dodaj"
			})
		]
	});
}
function BlocksTab() {
	const qc = useQueryClient();
	const add = useServerFn(addBlockedTime);
	const provs = useQuery({
		queryKey: ["providers"],
		queryFn: async () => (await supabase.from("providers").select("*").order("sort_order")).data ?? []
	});
	const blocks = useQuery({
		queryKey: ["blocks"],
		queryFn: async () => (await supabase.from("blocked_times").select("*, providers(name)").order("start_time", { ascending: false })).data ?? []
	});
	const [providerId, setProviderId] = (0, import_react.useState)("");
	const [start, setStart] = (0, import_react.useState)("");
	const [end, setEnd] = (0, import_react.useState)("");
	const [reason, setReason] = (0, import_react.useState)("");
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "space-y-6",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
			className: "p-4",
			children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h3", {
				className: "text-lg mb-3",
				children: "Dodaj blokadu / pauzu"
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "flex flex-wrap items-end gap-2",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
						className: "text-xs",
						children: "Osoba"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("select", {
						className: "mt-1 h-9 rounded-md border bg-background px-2 text-sm",
						value: providerId,
						onChange: (e) => setProviderId(e.target.value),
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
							value: "",
							children: "—"
						}), (provs.data ?? []).map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", {
							value: p.id,
							children: p.name
						}, p.id))]
					})] }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
						className: "text-xs",
						children: "Od"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
						type: "datetime-local",
						className: "h-9",
						value: start,
						onChange: (e) => setStart(e.target.value)
					})] }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
						className: "text-xs",
						children: "Do"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
						type: "datetime-local",
						className: "h-9",
						value: end,
						onChange: (e) => setEnd(e.target.value)
					})] }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, {
						className: "text-xs",
						children: "Razlog"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
						className: "h-9",
						value: reason,
						onChange: (e) => setReason(e.target.value),
						placeholder: "npr. Godišnji"
					})] }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
						size: "sm",
						disabled: !providerId || !start || !end,
						onClick: async () => {
							try {
								await add({ data: {
									providerId,
									startTime: new Date(start).toISOString(),
									endTime: new Date(end).toISOString(),
									reason: reason || null
								} });
								setStart("");
								setEnd("");
								setReason("");
								qc.invalidateQueries({ queryKey: ["blocks"] });
								toast.success("Blokada dodata");
							} catch (e) {
								toast.error(e.message);
							}
						},
						children: "Dodaj"
					})
				]
			})]
		}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
			className: "space-y-2",
			children: (blocks.data ?? []).map((b) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
				className: "flex flex-wrap items-center justify-between gap-3 p-4 text-sm",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "font-medium",
						children: b.providers?.name
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "text-muted-foreground",
						children: [
							new Date(b.start_time).toLocaleString("sr-Latn-RS"),
							" – ",
							new Date(b.end_time).toLocaleString("sr-Latn-RS")
						]
					}),
					b.reason && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-xs text-muted-foreground",
						children: b.reason
					})
				] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
					size: "sm",
					variant: "ghost",
					onClick: async () => {
						await supabase.from("blocked_times").delete().eq("id", b.id);
						qc.invalidateQueries({ queryKey: ["blocks"] });
					},
					children: "Obriši"
				})]
			}) }, b.id))
		})]
	});
}
function SmsTab() {
	const q = useQuery({
		queryKey: ["sms"],
		queryFn: async () => (await supabase.from("sms_logs").select("*").order("created_at", { ascending: false }).limit(100)).data ?? []
	});
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "space-y-2",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
			className: "text-sm text-muted-foreground",
			children: "SMS integracija nije još povezana. Poruke se pripremaju i biće poslate čim izaberete provajdera."
		}), (q.data ?? []).map((r) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
			className: "p-4 text-sm",
			children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "flex flex-wrap items-center gap-2",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, {
						variant: "outline",
						children: r.type
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Badge, { children: r.status }),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
						className: "text-muted-foreground",
						children: ["→ ", r.recipient]
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
						className: "ml-auto text-xs text-muted-foreground",
						children: new Date(r.created_at).toLocaleString("sr-Latn-RS")
					})
				]
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: "mt-2 whitespace-pre-wrap",
				children: r.body
			})]
		}) }, r.id))]
	});
}
function SettingsTab() {
	const qc = useQueryClient();
	const upsert = useServerFn(upsertSetting);
	const s = useQuery({
		queryKey: ["settings-admin"],
		queryFn: async () => {
			const { data } = await supabase.from("site_settings").select("*");
			const m = {};
			for (const r of data ?? []) m[r.key] = r.value ?? "";
			return m;
		}
	});
	const [phone, setPhone] = (0, import_react.useState)("");
	const [ig, setIg] = (0, import_react.useState)("");
	const [addr, setAddr] = (0, import_react.useState)("");
	(0, import_react.useEffect)(() => {
		if (s.data) {
			setPhone(s.data.salon_phone ?? "");
			setIg(s.data.salon_instagram ?? "");
			setAddr(s.data.salon_address ?? "");
		}
	}, [s.data]);
	async function save() {
		await Promise.all([
			upsert({ data: {
				key: "salon_phone",
				value: phone
			} }),
			upsert({ data: {
				key: "salon_instagram",
				value: ig
			} }),
			upsert({ data: {
				key: "salon_address",
				value: addr
			} })
		]);
		qc.invalidateQueries({ queryKey: ["settings-admin"] });
		qc.invalidateQueries({ queryKey: ["site-settings"] });
		toast.success("Sačuvano");
	}
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "max-w-lg space-y-4",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: "Telefon salona" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				value: phone,
				onChange: (e) => setPhone(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: "Instagram (bez @)" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				value: ig,
				onChange: (e) => setIg(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Label, { children: "Adresa" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
				value: addr,
				onChange: (e) => setAddr(e.target.value)
			})] }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				onClick: save,
				children: "Sačuvaj"
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "mt-8 rounded-2xl border border-dashed p-4 text-sm text-muted-foreground",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
					className: "font-medium text-foreground",
					children: "SMS / WhatsApp integracija"
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
					className: "mt-1",
					children: "Kada izaberete provajdera (Twilio / Vonage / Infobip), dodaćemo API ključeve u Cloud Secrets i pravi SMS će početi da se šalje – bez izmene ostatka aplikacije."
				})]
			})
		]
	});
}
//#endregion
export { AdminPage as component };
