"use client"; import { api } from "@/lib/api"; import type { TenantWithRole } from "@/lib/types"; import { ChevronsUpDown } from "lucide-react"; import { useEffect, useRef, useState } from "react"; export function TenantSwitcher() { const [tenants, setTenants] = useState([]); const [current, setCurrent] = useState(null); const [open, setOpen] = useState(false); const ref = useRef(null); useEffect(() => { api .get("/tenants") .then((data) => { if (!Array.isArray(data)) return; setTenants(data); const savedId = localStorage.getItem("kanzlai_tenant_id"); const match = data.find((t) => t.id === savedId) || data[0]; if (match) { setCurrent(match); localStorage.setItem("kanzlai_tenant_id", match.id); } }) .catch(() => { // Not authenticated or no tenants }); }, []); useEffect(() => { function handleClick(e: MouseEvent) { if (ref.current && !ref.current.contains(e.target as Node)) { setOpen(false); } } document.addEventListener("mousedown", handleClick); return () => document.removeEventListener("mousedown", handleClick); }, []); function switchTenant(tenant: TenantWithRole) { setCurrent(tenant); localStorage.setItem("kanzlai_tenant_id", tenant.id); setOpen(false); window.location.reload(); } if (!current) return null; return (
{open && (
{tenants.map((tenant) => ( ))} {tenants.length <= 1 && (

Einzige Kanzlei

)}
)}
); }