"use client";

import { createPortal } from "react-dom";
import { useEffect, useMemo, useRef, useState } from "react";
import type { RefObject } from "react";
import { useQueryClient, useMutation, useQuery } from "@tanstack/react-query";
import clsx from "clsx";
import { CalendarDays, Check, ChevronLeft, ChevronRight, Clock3, MapPin, MoreHorizontal, Pencil, Plus, RefreshCw, Repeat2, Share2, Trash2, X } from "lucide-react";
import { api } from "@/lib/api";
import { createTranslator } from "@/lib/i18n";
import type { AppLocale } from "@/lib/i18n";
import { DEFAULT_TIME_ZONE } from "@/lib/time-zone";
import type { CalendarAttendee, CalendarEvent, CalendarSource, CalendarStatus, Contact, NativeZimbraShareEntry } from "@/lib/types";
import { ShareRecipientAutocomplete } from "./share-recipient-autocomplete";

const calendarColorOptions = [
  { value: 1, label: "Blue", hex: "#60a5fa" },
  { value: 2, label: "Cyan", hex: "#22d3ee" },
  { value: 3, label: "Green", hex: "#4ade80" },
  { value: 4, label: "Purple", hex: "#a78bfa" },
  { value: 5, label: "Red", hex: "#fb7185" },
  { value: 6, label: "Yellow", hex: "#facc15" },
  { value: 7, label: "Pink", hex: "#f472b6" },
  { value: 8, label: "Gray", hex: "#94a3b8" },
  { value: 9, label: "Orange", hex: "#fb923c" },
] as const;

export type CalendarNotice = {
  tone: "success" | "error" | "info";
  message: string;
};

export type CalendarTabProps = {
  serviceLabel: string;
  status?: CalendarStatus;
  statusLoading: boolean;
  calendars: CalendarSource[];
  allowColorEdit?: boolean;
  allowCalendarCreation?: boolean;
  allowShareManagement?: boolean;
  showDisconnect?: boolean;
  showRecurringOptions?: boolean;
  selectedCalendarId: string;
  timeZone: string;
  locale: AppLocale;
  onSelectCalendar: (value: string) => void;
  events: CalendarEvent[];
  loading: boolean;
  loadingCalendars: boolean;
  connectPending: boolean;
  resyncPending: boolean;
  disconnectPending: boolean;
  notice: CalendarNotice | null;
  onDismissNotice: () => void;
  onConnect: () => void;
  onResync: () => void;
  onDisconnect: () => void;
  contacts: Contact[];
  focusEventId?: string | null;
  onFocusEventHandled?: () => void;
  t: ReturnType<typeof createTranslator>;
};

export function CalendarWorkspaceTab({
  serviceLabel,
  status,
  statusLoading,
  calendars,
  allowColorEdit = false,
  allowCalendarCreation = false,
  allowShareManagement = false,
  showDisconnect = true,
  showRecurringOptions = false,
  selectedCalendarId,
  timeZone,
  locale,
  onSelectCalendar,
  events,
  loading,
  loadingCalendars,
  connectPending,
  resyncPending,
  disconnectPending,
  notice,
  onDismissNotice,
  onConnect,
  onResync,
  onDisconnect,
  contacts,
  focusEventId = null,
  onFocusEventHandled,
  t,
}: CalendarTabProps) {
  const queryClient = useQueryClient();
  const actionMenuRef = useRef<HTMLDivElement | null>(null);
  const actionMenuTriggerRef = useRef<HTMLButtonElement | null>(null);
  const calendarListRef = useRef<HTMLDivElement | null>(null);
  const shareDialogRef = useRef<HTMLDivElement | null>(null);
  const [view, setView] = useState<"month" | "week" | "day">("month");
  const [focusDate, setFocusDate] = useState(() => isoDate(todayStart()));
  const [composerOpen, setComposerOpen] = useState(false);
  const [newCalendarName, setNewCalendarName] = useState("");
  const [actionMenuCalendarId, setActionMenuCalendarId] = useState("");
  const [actionMenuFocusIndex, setActionMenuFocusIndex] = useState(0);
  const [renameCalendarId, setRenameCalendarId] = useState("");
  const [renameCalendarName, setRenameCalendarName] = useState("");
  const [colorCalendarId, setColorCalendarId] = useState("");
  const [shareCalendarId, setShareCalendarId] = useState("");
  const [shareEmail, setShareEmail] = useState("");
  const [sharePermissions, setSharePermissions] = useState("r");
  const [editingEvent, setEditingEvent] = useState<CalendarEvent | null>(null);
  const [activeEvent, setActiveEvent] = useState<CalendarEvent | null>(null);
  const [composerNotice, setComposerNotice] = useState<CalendarNotice | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<CalendarEvent | null>(null);
  const selectedCalendarLabel =
    selectedCalendarId === "__all__"
      ? t("calendar.allCalendars")
      : selectedCalendarId === "primary"
        ? calendars.find((item) => item.primary)?.summary || t("calendar.primaryCalendar")
        : calendars.find((item) => item.id === selectedCalendarId)?.summary ||
        calendars.find((item) => item.primary)?.summary ||
        t("calendar.primaryCalendar");
  const calendarColorById = useMemo(
    () => new Map(calendars.map((calendar) => [calendar.id, calendar.background_color || "#cbd5e1"] as const)),
    [calendars]
  );

  const normalizedEvents = useMemo(
    () =>
      events
        .map((event) => ({
          ...event,
          startDate: calendarEventStart(event),
          endDate: calendarEventEnd(event),
        }))
        .filter((event) => !Number.isNaN(event.startDate.getTime()))
        .sort((a, b) => a.startDate.getTime() - b.startDate.getTime()),
    [events]
  );
  const focus = parseIsoDate(focusDate);
  const currentMonthStart = startOfMonth(focus);
  const monthGridStart = startOfWeek(currentMonthStart);
  const monthDays = Array.from({ length: 42 }, (_, index) => addDays(monthGridStart, index));
  const weekDays = Array.from({ length: 7 }, (_, index) => addDays(startOfWeek(focus), index));
  const selectedDayEvents = normalizedEvents.filter((event) => occursOnDay(event, focus));
  const upcomingEvents = normalizedEvents
    .filter((event) => event.endDate.getTime() >= Date.now())
    .slice()
    .sort((left, right) => left.startDate.getTime() - right.startDate.getTime())
    .slice(0, 8);
  const screenReaderAnnouncement = useMemo(() => {
    const messages = [
      `Selected calendar: ${selectedCalendarLabel}. ${events.length} events loaded.`,
      notice?.message || "",
      composerNotice?.message || "",
    ].filter(Boolean);
    return messages.join(" ");
  }, [selectedCalendarLabel, events.length, notice?.message, composerNotice?.message]);

  async function openEventEditor(event: CalendarEvent) {
    if (!canWriteCalendarEvent(event, calendars)) return;
    setComposerNotice(null);
    try {
      const response = await loadCalendarEvent.mutateAsync({
        eventId: event.id,
        calendarId: event.calendar_id || selectedCalendarId || "primary",
      });
      setEditingEvent({
        ...response.event,
        description: normalizeCalendarPlainText(response.event.description || event.description || ""),
        reminder_minutes:
          response.event.reminder_minutes > 0
            ? response.event.reminder_minutes
            : event.reminder_minutes > 0
              ? event.reminder_minutes
              : response.event.reminder_minutes,
      });
    } catch {
      setEditingEvent({ ...event, description: normalizeCalendarPlainText(event.description || "") });
    }
    setActiveEvent(null);
    setComposerOpen(true);
  }

  async function openEventDetails(event: CalendarEvent) {
    setActiveEvent({ ...event, description: normalizeCalendarPlainText(event.description || "") });
    try {
      const response = await loadCalendarEvent.mutateAsync({
        eventId: event.id,
        calendarId: event.calendar_id || selectedCalendarId || "primary",
      });
      setActiveEvent((current) =>
        current?.id === event.id
          ? {
              ...event,
              ...response.event,
              description: normalizeCalendarPlainText(response.event.description || event.description || ""),
              description_html: response.event.description_html || event.description_html || "",
            }
          : current
      );
    } catch {
      // Keep the summary event visible when the provider cannot load its detail.
    }
  }

  useEffect(() => {
    if (normalizedEvents.length || focusDate !== isoDate(todayStart())) return;
    setFocusDate(isoDate(todayStart()));
  }, [normalizedEvents, focusDate]);

  useEffect(() => {
    if (!focusEventId) return;
    const matched = normalizedEvents.find((event) => event.id === focusEventId || event.ical_uid === focusEventId);
    if (!matched) return;
    setActiveEvent(matched);
    setFocusDate(isoDate(matched.startDate));
    onFocusEventHandled?.();
  }, [focusEventId, normalizedEvents, onFocusEventHandled]);

  useEffect(() => {
    if (!allowShareManagement) {
      setShareCalendarId("");
      setShareEmail("");
      setSharePermissions("r");
    }
  }, [allowShareManagement]);

  useEffect(() => {
    if (!actionMenuCalendarId) return;
    const menu = actionMenuRef.current;
    const trigger = actionMenuTriggerRef.current;
    const items = getFocusableElements(menu);
    items[0]?.focus();

    const closeMenu = (event?: MouseEvent) => {
      if (!event) {
        setActionMenuCalendarId("");
        return;
      }
      const target = event.target;
      if (target instanceof Node && menu?.contains(target)) return;
      setActionMenuCalendarId("");
    };
    const handleKeyDown = (event: KeyboardEvent) => {
      const currentItems = getFocusableElements(actionMenuRef.current);
      if (!currentItems.length) {
        if (event.key === "Escape") setActionMenuCalendarId("");
        return;
      }
      const activeIndex = currentItems.findIndex((item) => item === document.activeElement);
      if (event.key === "Escape") {
        event.preventDefault();
        setActionMenuCalendarId("");
        return;
      }
      if (event.key === "ArrowDown") {
        event.preventDefault();
        const nextIndex = (activeIndex + 1 + currentItems.length) % currentItems.length;
        setActionMenuFocusIndex(nextIndex);
        currentItems[nextIndex]?.focus();
        return;
      }
      if (event.key === "ArrowUp") {
        event.preventDefault();
        const nextIndex = (activeIndex - 1 + currentItems.length) % currentItems.length;
        setActionMenuFocusIndex(nextIndex);
        currentItems[nextIndex]?.focus();
        return;
      }
      if (event.key === "Home") {
        event.preventDefault();
        setActionMenuFocusIndex(0);
        currentItems[0]?.focus();
        return;
      }
      if (event.key === "End") {
        event.preventDefault();
        setActionMenuFocusIndex(currentItems.length - 1);
        currentItems[currentItems.length - 1]?.focus();
      }
    };
    window.addEventListener("click", closeMenu);
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("click", closeMenu);
      window.removeEventListener("keydown", handleKeyDown);
      trigger?.focus();
    };
  }, [actionMenuCalendarId]);

  function resetCalendarActionPanels() {
    setActionMenuCalendarId("");
    setActionMenuFocusIndex(0);
    setRenameCalendarId("");
    setRenameCalendarName("");
    setColorCalendarId("");
    setShareCalendarId("");
  }

  useFocusTrap(!!shareCalendarId, shareDialogRef, () => setShareCalendarId(""));

  function moveRange(direction: -1 | 1) {
    if (view === "day") setFocusDate(isoDate(addDays(focus, direction)));
    if (view === "week") setFocusDate(isoDate(addDays(focus, direction * 7)));
    if (view === "month") setFocusDate(isoDate(addMonths(focus, direction)));
  }

  function moveCalendarCardFocus(currentId: string, direction: "next" | "previous" | "first" | "last") {
    const cards = getCalendarCardButtons(calendarListRef.current);
    if (!cards.length) return;
    const currentIndex = cards.findIndex((button) => button.dataset.calendarId === currentId);
    if (direction === "first") {
      cards[0]?.focus();
      return;
    }
    if (direction === "last") {
      cards[cards.length - 1]?.focus();
      return;
    }
    if (currentIndex === -1) {
      cards[0]?.focus();
      return;
    }
    const nextIndex =
      direction === "next"
        ? (currentIndex + 1) % cards.length
        : (currentIndex - 1 + cards.length) % cards.length;
    cards[nextIndex]?.focus();
  }

  const headerLabel =
    view === "day"
      ? new Intl.DateTimeFormat(calendarDisplayLocale(locale), { dateStyle: "full" }).format(focus)
      : view === "week"
        ? `${new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "short", day: "numeric" }).format(weekDays[0])} - ${new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "short", day: "numeric", year: "numeric" }).format(weekDays[6])}`
        : new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "long", year: "numeric" }).format(focus);
  const mobileWeekHeaderEndOptions: Intl.DateTimeFormatOptions = sameMonth(weekDays[0], weekDays[6]) ? { day: "numeric" } : { month: "short", day: "numeric" };
  const mobileWeekHeaderLabel = `${new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "short", day: "numeric" }).format(weekDays[0])}–${new Intl.DateTimeFormat(calendarDisplayLocale(locale), mobileWeekHeaderEndOptions).format(weekDays[6])}`;
  const mobileWeekHeaderYear = new Intl.DateTimeFormat(calendarDisplayLocale(locale), { year: "numeric" }).format(weekDays[6]);

  const createCalendarEvent = useMutation({
    mutationFn: api.createCalendarEvent,
    onSuccess: async () => {
      setComposerOpen(false);
      setComposerNotice({ tone: "success", message: `Event created in ${serviceLabel}.` });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.createFailed") });
    }
  });
  const calendarShares = useQuery({
    queryKey: ["native-zimbra-calendar-shares", shareCalendarId],
    queryFn: () => api.nativeZimbraCalendarShares(shareCalendarId),
    enabled: allowShareManagement && Boolean(shareCalendarId),
    staleTime: 30_000,
    refetchOnWindowFocus: false,
  });
  const visibleCalendarShares = useMemo(
    () => (calendarShares.data?.shares ?? []).filter(hasShareRecipient),
    [calendarShares.data?.shares]
  );
  const shareNativeCalendar = useMutation({
    mutationFn: ({ resource_id, email, permissions }: { resource_id: string; email: string; permissions: string }) =>
      api.nativeZimbraShareCalendar({ resource_id, email, permissions }),
    onSuccess: async (_data, variables) => {
      setShareEmail("");
      setSharePermissions("r");
      setComposerNotice({ tone: "success", message: t("calendar.sharingUpdated") });
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares"] });
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares", variables.resource_id] });
      setShareCalendarId("");
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableUpdateSharing") });
    },
  });
  const revokeNativeCalendarShare = useMutation({
    mutationFn: ({ resource_id, email }: { resource_id: string; email: string }) =>
      api.nativeZimbraRevokeCalendarShare({ resource_id, email }),
    onSuccess: async (_data, variables) => {
      setComposerNotice({ tone: "success", message: t("calendar.sharingUpdated") });
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares"] });
      await queryClient.invalidateQueries({ queryKey: ["native-zimbra-calendar-shares", variables.resource_id] });
      setShareCalendarId("");
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableUpdateSharing") });
    },
  });
  const updateCalendarEvent = useMutation({
    mutationFn: ({ eventId, payload }: { eventId: string; payload: Parameters<typeof api.updateCalendarEvent>[1] }) =>
      api.updateCalendarEvent(eventId, payload),
    onSuccess: async () => {
      setEditingEvent(null);
      setComposerOpen(false);
      setComposerNotice({ tone: "success", message: t("calendar.updatedIn", { service: serviceLabel }) });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.updateFailed") });
    }
  });
  const deleteCalendarEvent = useMutation({
    mutationFn: ({ eventId, calendarId, scope }: { eventId: string; calendarId: string; scope?: "this" | "series" }) => api.deleteCalendarEvent(eventId, calendarId, scope ?? "series"),
    onSuccess: async () => {
      const removedName = deleteConfirm?.summary || t("calendar.event");
      setDeleteConfirm(null);
      setComposerNotice({ tone: "success", message: t("calendar.deletedFrom", { event: removedName, service: serviceLabel }) });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.deleteFailed") });
    }
  });
  const loadCalendarEvent = useMutation({
    mutationFn: ({ eventId, calendarId }: { eventId: string; calendarId: string }) => api.getCalendarEvent(eventId, calendarId, timeZone),
  });
  const updateCalendarColor = useMutation({
    mutationFn: ({ calendarId, color, rgb }: { calendarId: string; color: number; rgb: string }) =>
      api.updateCalendarColor(calendarId, { calendarId, color, rgb }),
    onSuccess: async (response) => {
      setComposerNotice({ tone: "success", message: t("calendar.colorUpdated") });
      queryClient.setQueryData(["calendar-sources"], response);
      await queryClient.invalidateQueries({ queryKey: ["calendar-sources"] });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableUpdateColor") });
    }
  });
  const createCalendar = useMutation({
    mutationFn: api.createCalendar,
    onSuccess: async () => {
      const createdName = newCalendarName.trim();
      setNewCalendarName("");
      setComposerNotice({ tone: "success", message: createdName ? t("calendar.createdWithName", { name: createdName }) : t("calendar.created") });
      await queryClient.invalidateQueries({ queryKey: ["calendar-sources"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableCreateCalendar") });
    }
  });
  const renameCalendar = useMutation({
    mutationFn: ({ calendarId, name }: { calendarId: string; name: string }) => api.renameCalendar(calendarId, name),
    onSuccess: async () => {
      const nextName = renameCalendarName.trim();
      setRenameCalendarId("");
      setRenameCalendarName("");
      setComposerNotice({ tone: "success", message: nextName ? t("calendar.renamedTo", { name: nextName }) : t("calendar.renamed") });
      await queryClient.invalidateQueries({ queryKey: ["calendar-sources"] });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableRenameCalendar") });
    }
  });
  const deleteCalendar = useMutation({
    mutationFn: (calendarId: string) => api.deleteCalendar(calendarId),
    onSuccess: async () => {
      setComposerNotice({ tone: "success", message: t("calendar.deleted") });
      await queryClient.invalidateQueries({ queryKey: ["calendar-sources"] });
      await queryClient.invalidateQueries({ queryKey: ["calendar"] });
      if (selectedCalendarId !== "__all__") {
        onSelectCalendar("__all__");
      }
    },
    onError: (error) => {
      setComposerNotice({ tone: "error", message: error instanceof Error ? error.message : t("calendar.unableDeleteCalendar") });
    }
  });

  const activeComposerCalendarId = resolveComposerCalendarId(selectedCalendarId, calendars, editingEvent);
  const activeComposerCalendarLabel =
    editingEvent?.calendar_summary ||
    calendars.find((item) => item.id === activeComposerCalendarId)?.summary ||
    selectedCalendarLabel;
  const activeComposerCalendarWritable = canWriteCalendarSource(calendars.find((item) => item.id === activeComposerCalendarId));

  return (
    <section className="grid h-full min-h-0 overflow-hidden p-2 lg:p-3">
      <div className="sr-only" aria-live="polite" aria-atomic="true">{screenReaderAnnouncement}</div>
      <div className="control-surface flex min-h-0 flex-col overflow-hidden rounded-xl p-3 sm:p-3">
        <div className="mb-3 flex flex-wrap items-center justify-between gap-3 xl:mb-4">
          <div className="hidden xl:block">
            <p className="text-xs font-black uppercase text-[var(--accent)]">{serviceLabel}</p>
            <h2 className="text-xl font-black">{t("calendar.workspace")}</h2>
            {(status?.connected || status?.mode === "public") ? (
              <p className="mt-2 text-xs font-semibold text-slate-400">
                {t("calendar.eventsLoaded", { count: events.length, calendar: selectedCalendarLabel.toLowerCase() })}
              </p>
            ) : null}
          </div>
          {status?.configured && (status.connected || status.mode === "public") ? (
            <div className="flex w-full flex-wrap items-center gap-2 sm:w-auto sm:gap-3">
              <button type="button" onClick={() => setComposerOpen(true)} disabled={!status.writable || !activeComposerCalendarWritable || disconnectPending} className="theme-button h-11 w-full justify-center px-4 text-sm transition hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-60 sm:h-10 sm:w-auto">
                <Plus size={16} />
                {t("calendar.newEvent")}
              </button>
              <label className="flex h-11 min-w-0 flex-1 items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-600 sm:h-10 sm:min-w-[220px]">
                <span className="shrink-0 text-slate-400">{t("calendar.calendar")}</span>
                <select value={selectedCalendarId} onChange={(event) => onSelectCalendar(event.target.value)} className="min-w-0 flex-1 bg-transparent outline-none" disabled={loadingCalendars || !calendars.length}>
                  {!calendars.length ? <option value={selectedCalendarId}>{selectedCalendarLabel}</option> : null}
                  <option value="__all__">{t("calendar.allCalendars")}</option>
                  {calendars.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.summary}{item.primary ? ` (${t("calendar.primary")})` : ""}
                    </option>
                  ))}
                </select>
              </label>
              <button type="button" onClick={onResync} disabled={resyncPending} className="icon-button h-10 w-10" aria-label={t("calendar.refresh")} title={t("calendar.refresh")}>
                <RefreshCw size={16} className={clsx(resyncPending && "animate-spin")} />
              </button>
              {showDisconnect && status.connected ? (
                <button onClick={onDisconnect} disabled={disconnectPending} className="theme-button-soft h-11 px-3 text-slate-700 disabled:opacity-50 sm:h-10 sm:px-4">
                  {t("calendar.disconnect")}
                </button>
              ) : null}
            </div>
          ) : null}
        </div>

        {notice ? (
          <div className={clsx("mb-4 flex shrink-0 items-start justify-between gap-3 rounded-lg border px-4 py-3 text-sm font-semibold", notice.tone === "success" ? "border-[color-mix(in_srgb,var(--accent)_20%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)] text-[var(--accent)]" : "border-rose-200 bg-rose-50 text-rose-700")}>
            <span className="min-w-0 break-words">{notice.message}</span>
            <button type="button" onClick={onDismissNotice} className="shrink-0 text-current/70 transition hover:text-current">
              <X size={16} />
            </button>
          </div>
        ) : null}

        {composerNotice ? (
          <div className={clsx("mb-4 flex shrink-0 items-start justify-between gap-3 rounded-lg border px-4 py-3 text-sm font-semibold", composerNotice.tone === "success" ? "border-[color-mix(in_srgb,var(--accent)_20%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)] text-[var(--accent)]" : "border-rose-200 bg-rose-50 text-rose-700")}>
            <span className="min-w-0 break-words">{composerNotice.message}</span>
            <button type="button" onClick={() => setComposerNotice(null)} className="shrink-0 text-current/70 transition hover:text-current">
              <X size={16} />
            </button>
          </div>
        ) : null}

        {statusLoading ? <div className="rounded-xl border border-slate-200 bg-slate-50 p-4"><h3 className="text-lg font-black text-slate-900">{t("calendar.loading", { service: serviceLabel })}</h3></div> : null}
        {!statusLoading && !status?.configured ? (
          <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 p-4">
            <h3 className="text-lg font-black text-slate-900">{t("calendar.notConfigured", { service: serviceLabel })}</h3>
          </div>
        ) : null}

        {!statusLoading && status?.oauth_configured && !status.connected ? (
          <div className="rounded-xl border border-[color-mix(in_srgb,var(--accent)_16%,white)] bg-[linear-gradient(135deg,rgba(236,253,245,0.95)_0%,rgba(240,249,255,0.95)_100%)] p-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <h3 className="text-lg font-black text-slate-900">{t("calendar.connectTitle", { service: serviceLabel })}</h3>
              </div>
              <button onClick={onConnect} disabled={connectPending} className="theme-button h-11 px-5 transition hover:-translate-y-0.5 disabled:opacity-50">
                {connectPending ? t("calendar.connecting") : t("calendar.connect", { service: serviceLabel })}
              </button>
            </div>
          </div>
        ) : null}

        {status?.connected && !status.writable ? <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800">{t("calendar.readOnly")}</div> : null}
        {status?.mode === "public" ? <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-semibold text-amber-800">{t("calendar.publicMode")}</div> : null}
        {selectedCalendarId === "__all__" ? <div className="mb-4 hidden rounded-lg border border-[color-mix(in_srgb,var(--accent)_18%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)] px-4 py-3 text-sm font-semibold text-[var(--accent)] xl:block">{t("calendar.viewingAll")}</div> : null}
        {selectedCalendarId === "primary" ? <div className="mb-4 hidden rounded-lg border border-[color-mix(in_srgb,var(--accent)_18%,white)] bg-[color-mix(in_srgb,var(--accent)_8%,white)] px-4 py-3 text-sm font-semibold text-[var(--accent)] xl:block">{t("calendar.viewingPrimary")}</div> : null}

        {(status?.connected || status?.mode === "public") ? (
          <div className="grid min-h-0 min-w-0 flex-1 gap-3 overflow-hidden xl:grid-cols-[minmax(0,1fr)_360px]">
            <div className="min-h-0 min-w-0 overflow-auto rounded-xl border border-slate-200 bg-white pb-[calc(5.5rem+env(safe-area-inset-bottom))] xl:pb-0">
              <div className="grid gap-2.5 border-b border-slate-200 px-3 py-3 sm:flex sm:flex-wrap sm:items-center sm:justify-between sm:px-3">
                <div className="flex min-w-0 items-center gap-2">
                  <button type="button" onClick={() => moveRange(-1)} className="icon-button h-10 w-10" aria-label={t("calendar.previousRange")}><ChevronLeft size={18} /></button>
                  <button type="button" onClick={() => setFocusDate(isoDate(todayStart()))} className="theme-button-soft h-10 px-3 text-sm">{t("calendar.today")}</button>
                  <button type="button" onClick={() => moveRange(1)} className="icon-button h-10 w-10" aria-label={t("calendar.nextRange")}><ChevronRight size={18} /></button>
                  <div className="ml-1 min-w-0 sm:ml-2">
                    <p className={clsx("text-xs font-black uppercase tracking-[0.12em] text-slate-400", view === "week" && "hidden sm:block")}>{selectedCalendarLabel}</p>
                    <h3 className="text-base font-black text-slate-900 sm:text-lg">
                      {view === "week" ? (
                        <>
                          <span className="block sm:hidden">{mobileWeekHeaderLabel}</span>
                          <span className="block text-xs font-bold text-slate-400 sm:hidden">{mobileWeekHeaderYear}</span>
                          <span className="hidden truncate sm:block">{headerLabel}</span>
                        </>
                      ) : (
                        <span className="block truncate">{headerLabel}</span>
                      )}
                    </h3>
                  </div>
                </div>
                <div className="grid grid-cols-3 items-center gap-1 rounded-lg border border-slate-200 bg-slate-50 p-1 sm:flex sm:gap-2">
                  {(["month", "week", "day"] as const).map((option) => (
                    <button key={option} type="button" onClick={() => setView(option)} className={clsx("h-10 rounded-md px-3 text-sm font-black capitalize transition sm:h-9 sm:px-4", view === option ? "bg-[var(--accent)] text-white shadow-[0_14px_24px_-18px_color-mix(in_srgb,var(--accent)_80%,transparent)]" : "text-slate-500 hover:bg-white hover:text-slate-900")}>
                      {option === "month" ? t("calendar.month") : option === "week" ? t("calendar.week") : t("calendar.day")}
                    </button>
                  ))}
                </div>
              </div>

              {view === "month" ? (
                <>
                  <div className="sm:hidden">
                    <div className="grid grid-cols-7 gap-1 border-b border-slate-100 bg-slate-50 p-2">
                      {monthDays.map((day) => {
                        const dayEvents = normalizedEvents.filter((event) => occursOnDay(event, day));
                        const isFocus = sameDay(day, focus);
                        const isToday = sameDay(day, todayStart());
                        const inMonth = sameMonth(day, focus);
                        return (
                          <button
                            key={isoDate(day)}
                            type="button"
                            onClick={() => setFocusDate(isoDate(day))}
                            className={clsx(
                              "grid min-h-12 place-items-center rounded-lg border px-1 py-1 text-center transition",
                              inMonth ? "border-slate-200 bg-white text-slate-800" : "border-transparent bg-transparent text-slate-400",
                              isToday && "border-emerald-200 bg-emerald-50 text-emerald-800",
                              isFocus && "ring-2 ring-[var(--accent)] ring-offset-1"
                            )}
                            aria-label={`${new Intl.DateTimeFormat(calendarDisplayLocale(locale), { dateStyle: "full" }).format(day)}. ${dayEvents.length ? t("calendar.moreEvents", { count: dayEvents.length }) : t("calendar.noEvents")}`}
                          >
                            <span className="text-sm font-black">{day.getDate()}</span>
                            <span className={clsx("mt-0.5 h-1.5 w-1.5 rounded-full", dayEvents.length ? "bg-[var(--accent)]" : "bg-transparent")} />
                          </button>
                        );
                      })}
                    </div>
                    <div className="p-3">
                      <div className="mb-3 rounded-lg border border-slate-200 bg-slate-50 px-4 py-3">
                        <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.selectedDay")}</p>
                        <h3 className="mt-1 text-lg font-black text-slate-900">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { dateStyle: "full" }).format(focus)}</h3>
                      </div>
                      <div className="grid gap-2">
                        {selectedDayEvents.length ? selectedDayEvents.map((event) => (
                          <button key={event.id} type="button" onClick={() => void openEventDetails(event)} className="rounded-lg border px-3 py-3 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                            <div className="flex min-w-0 items-center justify-between gap-2">
                              <p className="min-w-0 flex-1 break-words text-sm font-black leading-5 text-slate-900">{event.summary}</p>
                              <CalendarEventResponseBadge event={event} t={t} />
                            </div>
                            <p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p>
                            <p className="mt-1 break-words text-[11px] font-semibold leading-4 text-slate-500">{event.calendar_summary || selectedCalendarLabel}</p>
                          </button>
                        )) : <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("calendar.noEventsOnDay")}</p>}
                      </div>
                      <div className="mt-4 rounded-lg border border-slate-200 bg-slate-50 p-3">
                        <div className="mb-2 flex items-center gap-2 text-xs font-black uppercase tracking-[0.12em] text-slate-400">
                          <Clock3 size={14} className="text-[var(--accent)]" />
                          {t("calendar.upcoming")}
                        </div>
                        <div className="grid gap-2">
                          {upcomingEvents.slice(0, 2).map((event) => (
                            <button key={`mobile-month-upcoming-${event.id}`} type="button" onClick={() => void openEventDetails(event)} className="rounded-lg border bg-white px-3 py-2 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                              <div className="flex min-w-0 items-center justify-between gap-2">
                                <p className="min-w-0 flex-1 truncate text-sm font-bold text-slate-800">{event.summary}</p>
                                <CalendarEventResponseBadge event={event} t={t} />
                              </div>
                              <p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p>
                            </button>
                          ))}
                          {!upcomingEvents.length && !loading ? <p className="rounded-lg bg-white px-3 py-2 text-sm font-semibold text-slate-500">{t("calendar.noUpcomingEvents")}</p> : null}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="hidden sm:grid sm:grid-cols-7">
                    {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((label) => (
                      <div key={label} className="border-b border-slate-100 px-3 py-2 text-xs font-black uppercase tracking-[0.12em] text-slate-400">{label}</div>
                    ))}
                    {monthDays.map((day) => {
                      const dayEvents = normalizedEvents.filter((event) => occursOnDay(event, day));
                      const isFocus = sameDay(day, focus);
                      const isToday = sameDay(day, todayStart());
                      const inMonth = sameMonth(day, focus);
                      return (
                        <button key={isoDate(day)} type="button" onClick={() => { setFocusDate(isoDate(day)); setView("day"); }} className={clsx("min-h-[92px] border-b border-r border-slate-100 px-3 py-3 text-left transition xl:min-h-[94px] 2xl:min-h-[104px]", inMonth ? "bg-white hover:bg-slate-50" : "bg-slate-50/80 text-slate-400 hover:bg-slate-100/80", isFocus && "ring-2 ring-emerald-200 ring-inset")}>
                          <div className="mb-2 flex items-center justify-between">
                            <span className={clsx("grid h-8 w-8 place-items-center rounded-full text-sm font-black", isToday ? "bg-emerald-100 text-emerald-800" : "text-slate-700")}>{day.getDate()}</span>
                            {dayEvents.length ? <span className="rounded-full bg-[color-mix(in_srgb,var(--accent)_10%,white)] px-2 py-0.5 text-[11px] font-black text-[var(--accent)]">{dayEvents.length}</span> : null}
                          </div>
                          <div className="block space-y-1">
                            {dayEvents.slice(0, 3).map((event) => (
                              <div key={`${day.toISOString()}-${event.id}`} className="flex min-w-0 items-start gap-1 rounded-md px-2 py-1 text-[11px] font-semibold leading-4 text-slate-800" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                                {isRecurringEvent(event) ? <Repeat2 size={11} className="shrink-0 text-sky-700" aria-label={t("calendar.recurringEvent")} /> : null}
                                <span className="min-w-0 whitespace-normal break-words">{calendarEventBadge(event, timeZone, locale, t)} {event.summary}</span>
                              </div>
                            ))}
                            {dayEvents.length > 3 ? <div className="text-[11px] font-bold text-slate-400">{t("calendar.moreEvents", { count: dayEvents.length - 3 })}</div> : null}
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </>
              ) : null}

              {view === "week" ? (
                <>
                  <div className="grid gap-2 p-3 md:hidden">
                    {weekDays.map((day) => {
                      const dayEvents = normalizedEvents.filter((event) => occursOnDay(event, day));
                      const isToday = sameDay(day, todayStart());
                      const isFocus = sameDay(day, focus);
                      if (!dayEvents.length) {
                        return (
                          <button key={isoDate(day)} type="button" onClick={() => { setFocusDate(isoDate(day)); setView("day"); }} className={clsx("flex min-h-12 w-full items-center justify-between gap-3 rounded-xl border px-3 py-2 text-left transition hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2", isFocus ? "border-[color-mix(in_srgb,var(--accent)_28%,white)] bg-[color-mix(in_srgb,var(--accent)_6%,white)]" : "border-slate-200 bg-white")}>
                            <div className="min-w-0 flex items-baseline gap-2">
                              <span className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { weekday: "short" }).format(day)}</span>
                              <span className={clsx("text-sm font-black", isToday ? "text-emerald-700" : "text-slate-900")}>{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "short", day: "numeric" }).format(day)}</span>
                            </div>
                            <span className="shrink-0 text-xs font-semibold text-slate-400">{t("calendar.noEvents")}</span>
                          </button>
                        );
                      }
                      return (
                        <article key={isoDate(day)} className={clsx("rounded-xl border px-3 py-3", isFocus ? "border-[color-mix(in_srgb,var(--accent)_28%,white)] bg-[color-mix(in_srgb,var(--accent)_6%,white)]" : "border-slate-200 bg-white")}>
                          <button type="button" onClick={() => { setFocusDate(isoDate(day)); setView("day"); }} className="mb-2 flex w-full items-center justify-between gap-3 rounded-lg text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2">
                            <div className="min-w-0">
                              <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { weekday: "long" }).format(day)}</p>
                              <p className={clsx("mt-1 text-base font-black", isToday ? "text-emerald-700" : "text-slate-900")}>{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { month: "short", day: "numeric" }).format(day)}</p>
                            </div>
                            <span className="rounded-full bg-[color-mix(in_srgb,var(--accent)_10%,white)] px-2 py-0.5 text-[11px] font-black text-[var(--accent)]">{dayEvents.length}</span>
                          </button>
                          <div className="grid gap-2">
                            {dayEvents.map((event) => (
                              <button key={event.id} type="button" onClick={() => void openEventDetails(event)} className="rounded-lg border px-3 py-2 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                                <div className="flex min-w-0 items-center justify-between gap-2">
                                  <p className="min-w-0 flex-1 break-words text-sm font-bold leading-5 text-slate-800">{event.summary}</p>
                                  <CalendarEventResponseBadge event={event} t={t} />
                                </div>
                                <p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p>
                                <p className="mt-1 break-words text-[11px] font-semibold leading-4 text-slate-500">{event.calendar_summary || selectedCalendarLabel}</p>
                              </button>
                            ))}
                          </div>
                        </article>
                      );
                    })}
                  </div>
                  <div className="hidden divide-slate-100 md:grid md:grid-cols-7 md:divide-x">
                    {weekDays.map((day) => {
                      const dayEvents = normalizedEvents.filter((event) => occursOnDay(event, day));
                      const isToday = sameDay(day, todayStart());
                      const isFocus = sameDay(day, focus);
                      return (
                        <button key={isoDate(day)} type="button" onClick={() => { setFocusDate(isoDate(day)); setView("day"); }} className={clsx("min-h-[340px] px-3 py-3 text-left transition hover:bg-slate-50", isFocus ? "bg-emerald-50/40" : "bg-white")}>
                          <div className="mb-3 flex items-center justify-between">
                            <div>
                              <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { weekday: "short" }).format(day)}</p>
                              <p className={clsx("mt-1 text-lg font-black", isToday ? "text-emerald-700" : "text-slate-900")}>{day.getDate()}</p>
                            </div>
                            {dayEvents.length ? <span className="rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-black text-emerald-700">{dayEvents.length}</span> : null}
                          </div>
                          <div className="grid gap-2">
                            {dayEvents.length ? dayEvents.map((event) => (
                              <button key={event.id} type="button" onClick={() => void openEventDetails(event)} className="rounded-lg border px-3 py-2 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                                <div className="flex min-w-0 items-center justify-between gap-2">
                                  <p className="truncate text-sm font-bold text-slate-800">{event.summary}</p>
                                  <CalendarEventResponseBadge event={event} t={t} />
                                </div>
                                <p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p>
                                <p className="mt-1 truncate text-[11px] font-semibold text-slate-500">{event.calendar_summary || selectedCalendarLabel}</p>
                              </button>
                            )) : <p className="text-sm font-medium text-slate-400">{t("calendar.noEvents")}</p>}
                          </div>
                        </button>
                      );
                    })}
                  </div>
                </>
              ) : null}

              {view === "day" ? (
                <div className="p-3">
                  <div className="mb-3 rounded-lg border border-slate-200 bg-slate-50 px-4 py-3">
                    <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.selectedDay")}</p>
                    <h3 className="mt-1 text-xl font-black text-slate-900">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { dateStyle: "full" }).format(focus)}</h3>
                  </div>
                  <div className="grid gap-3">
                    {selectedDayEvents.length ? selectedDayEvents.map((event) => (
                      <article key={event.id} className="rounded-xl border p-3 transition hover:border-[var(--accent)] sm:p-3.5" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                        <div className="flex flex-wrap items-start justify-between gap-3">
                          <div className="min-w-0">
                            <div className="flex min-w-0 items-center gap-2">
                              <strong className="block truncate text-base font-black text-slate-900">{event.summary}</strong>
                              <CalendarEventResponseBadge event={event} t={t} />
                            </div>
                            <div className="mt-2 inline-flex items-center gap-1.5 rounded-full border border-black/5 px-2 py-0.5 text-[11px] font-semibold text-slate-700" style={{ backgroundColor: "color-mix(in srgb, white 72%, transparent)" }}>
                              <span className="h-2 w-2 rounded-full border border-black/5" style={{ backgroundColor: calendarColorById.get(event.calendar_id || "") || "#cbd5e1" }} />
                              <span className="truncate">{event.calendar_summary || selectedCalendarLabel}</span>
                            </div>
                            <div className="mt-2 flex flex-wrap items-center gap-3 text-sm font-semibold text-slate-500">
                              <span className="inline-flex items-center gap-1.5"><Clock3 size={15} /> {formatCalendarRange(event, timeZone, locale, t)}</span>
                              {event.location ? <span className="inline-flex items-center gap-1.5"><MapPin size={15} /> {event.location}</span> : null}
                            </div>
                          </div>
                          <div className="grid w-full grid-cols-3 gap-2 sm:flex sm:w-auto sm:flex-wrap sm:items-center">
                            <button type="button" onClick={() => void openEventDetails(event)} className="theme-button-soft h-10 px-3 text-sm">
                              {t("calendar.details")}
                            </button>
                            <button type="button" onClick={() => void openEventEditor(event)} disabled={!canWriteCalendarEvent(event, calendars)} className="theme-button-soft h-10 px-3 text-sm disabled:cursor-not-allowed disabled:opacity-50">
                              {t("common.edit")}
                            </button>
                            <button type="button" onClick={() => setDeleteConfirm(event)} disabled={!canWriteCalendarEvent(event, calendars)} className="theme-button-soft h-10 border-red-200 px-3 text-sm text-red-600 hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50">{t("common.delete")}</button>
                          </div>
                        </div>
                        {event.description ? <p className="mt-4 whitespace-pre-wrap text-sm leading-6 text-slate-600">{event.description}</p> : null}
                      </article>
                    )) : <p className="rounded-lg bg-slate-50 p-5 text-sm font-semibold text-slate-500">{t("calendar.noEventsOnDay")}</p>}
                  </div>
                </div>
              ) : null}
            </div>

            <aside className="hidden min-h-0 min-w-0 gap-4 overflow-auto pr-1 xl:grid">
              <div className="rounded-xl border border-slate-200 bg-white p-3">
                <div className="mb-4 flex items-center gap-2">
                  <CalendarDays size={18} className="text-[var(--accent)]" />
                  <div>
                    <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.calendar")}</p>
                    <h3 className="text-lg font-black text-slate-900">{t("calendar.sources")}</h3>
                  </div>
                </div>
                {allowCalendarCreation ? (
                  <form
                    className="mb-4 grid gap-2"
                    onSubmit={(event) => {
                      event.preventDefault();
                      const name = newCalendarName.trim();
                      if (!name) return;
                      void createCalendar.mutateAsync(name);
                    }}
                  >
                    <input
                      value={newCalendarName}
                      onChange={(event) => setNewCalendarName(event.target.value)}
                      className="field h-10 min-w-0 flex-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                      placeholder={t("calendar.newCalendar")}
                    />
                    <button type="submit" className="theme-button h-10 w-full justify-center px-4 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" disabled={!newCalendarName.trim() || createCalendar.isPending}>
                      <Plus size={16} />
                      {createCalendar.isPending ? t("calendar.creating") : t("calendar.newCalendar")}
                    </button>
                  </form>
                ) : null}
                <div ref={calendarListRef} className="grid gap-3">
                  {calendars.map((calendar) => {
                    const mountedShare = isMountedCalendarSource(calendar);
                    const calendarWritable = canWriteCalendarSource(calendar);
                    return (
                    <div
                      key={calendar.id}
                      data-primary-calendar={calendar.primary ? "true" : "false"}
                      className={clsx(
                        "min-w-0 rounded-xl border px-3 py-3 transition",
                        actionMenuCalendarId === calendar.id ||
                        renameCalendarId === calendar.id ||
                        colorCalendarId === calendar.id ||
                        shareCalendarId === calendar.id ||
                        isCalendarOptionSelected(calendar, selectedCalendarId)
                          ? "border-[color-mix(in_srgb,var(--accent)_22%,white)] bg-[color-mix(in_srgb,var(--accent)_6%,white)]"
                          : "border-slate-200 bg-slate-50"
                      )}
                    >
                      <div className="flex min-w-0 items-start justify-between gap-3">
                        <button
                          type="button"
                          data-calendar-id={calendar.id}
                          onClick={() => { resetCalendarActionPanels(); onSelectCalendar(calendar.id); }}
                          onKeyDown={(event) => {
                            if (event.key === "ArrowDown") {
                              event.preventDefault();
                              moveCalendarCardFocus(calendar.id, "next");
                              return;
                            }
                            if (event.key === "ArrowUp") {
                              event.preventDefault();
                              moveCalendarCardFocus(calendar.id, "previous");
                              return;
                            }
                            if (event.key === "Home") {
                              event.preventDefault();
                              moveCalendarCardFocus(calendar.id, "first");
                              return;
                            }
                            if (event.key === "End") {
                              event.preventDefault();
                              moveCalendarCardFocus(calendar.id, "last");
                            }
                          }}
                          className="min-w-0 flex-1 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                        >
                          <div className="flex min-w-0 flex-wrap items-center gap-2">
                            <span className="h-3 w-3 rounded-full border border-black/5" style={{ backgroundColor: calendar.background_color }} />
                            {mountedShare ? <SharedCalendarIcon label={t("sharing.sharedWithMe")} /> : null}
                            <p className="min-w-0 flex-1 break-words text-sm font-black leading-5 text-slate-900">{calendar.summary}</p>
                            {calendar.primary ? <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-black uppercase tracking-[0.08em] text-slate-500">{t("calendar.primary")}</span> : null}
                          </div>
                          <p className="mt-1 text-xs font-semibold text-slate-500">{calendarAccessRoleLabel(calendar, t)}</p>
                        </button>
                        {allowCalendarCreation || allowColorEdit || allowShareManagement || !calendar.primary ? (
                          <div className="relative shrink-0" onClick={(event) => event.stopPropagation()}>
                            <button
                              type="button"
                              onClick={(event) => {
                                actionMenuTriggerRef.current = event.currentTarget;
                                setRenameCalendarId("");
                                setColorCalendarId("");
                                setShareCalendarId("");
                                setActionMenuFocusIndex(0);
                                setActionMenuCalendarId((current) => (current === calendar.id ? "" : calendar.id));
                              }}
                              className="theme-button-soft h-8 w-9 shrink-0 justify-center px-0 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                              disabled={renameCalendar.isPending || deleteCalendar.isPending || updateCalendarColor.isPending || shareNativeCalendar.isPending || revokeNativeCalendarShare.isPending}
                              aria-label={t("calendar.calendarActionsFor", { name: calendar.summary })}
                              aria-haspopup="menu"
                              aria-expanded={actionMenuCalendarId === calendar.id}
                              title={t("calendar.calendarActions")}
                            >
                              <MoreHorizontal size={15} />
                            </button>
                            {actionMenuCalendarId === calendar.id ? (
                              <div ref={actionMenuRef} role="menu" aria-label={t("calendar.calendarActionsFor", { name: calendar.summary })} className="absolute right-0 top-10 z-20 min-w-[220px] rounded-xl border border-slate-200 bg-white p-1.5 shadow-xl">
                                <div className="px-3 py-2 text-[11px] font-black uppercase tracking-[0.08em] text-slate-400">{t("calendar.manage")}</div>
                                {!calendar.primary ? (
                                  <button
                                    type="button"
                                    onClick={() => {
                                      resetCalendarActionPanels();
                                      setRenameCalendarId(calendar.id);
                                      setRenameCalendarName(calendar.summary);
                                    }}
                                    onFocus={() => setActionMenuFocusIndex(0)}
                                    role="menuitem"
                                    tabIndex={actionMenuFocusIndex === 0 ? 0 : -1}
                                    className="flex h-9 w-full items-center gap-2 rounded-md px-3 text-sm font-semibold text-slate-700 transition hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-inset"
                                  >
                                    <Pencil size={14} />
                                    {t("calendar.rename")}
                                  </button>
                                ) : null}
                                {allowColorEdit ? (
                                  <button
                                    type="button"
                                    onClick={() => {
                                      resetCalendarActionPanels();
                                      setColorCalendarId((current) => (current === calendar.id ? "" : calendar.id));
                                    }}
                                    onFocus={() => setActionMenuFocusIndex(calendar.primary ? 0 : 1)}
                                    role="menuitem"
                                    tabIndex={actionMenuFocusIndex === (calendar.primary ? 0 : 1) ? 0 : -1}
                                    className="flex h-9 w-full items-center gap-2 rounded-md px-3 text-sm font-semibold text-slate-700 transition hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-inset"
                                  >
                                    <span className="h-3 w-3 rounded-full border border-black/5" style={{ backgroundColor: calendar.background_color }} />
                                    {t("calendar.changeColor")}
                                  </button>
                                ) : null}
                                {allowShareManagement && calendarWritable ? (
                                  <>
                                    <div className="my-1 border-t border-slate-100" />
                                    <div className="px-3 py-2 text-[11px] font-black uppercase tracking-[0.08em] text-slate-400">{t("calendar.access")}</div>
                                    <button
                                      type="button"
                                      onClick={() => {
                                        setActionMenuCalendarId("");
                                        setShareCalendarId(calendar.id);
                                      }}
                                      onFocus={() => setActionMenuFocusIndex((calendar.primary ? 0 : 1) + (allowColorEdit ? 1 : 0))}
                                      role="menuitem"
                                      tabIndex={actionMenuFocusIndex === ((calendar.primary ? 0 : 1) + (allowColorEdit ? 1 : 0)) ? 0 : -1}
                                      className="flex h-9 w-full items-center gap-2 rounded-md px-3 text-sm font-semibold text-slate-700 transition hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-inset"
                                    >
                                      <Share2 size={14} />
                                      {t("calendar.shareCalendar")}
                                    </button>
                                  </>
                                ) : null}
                                {!calendar.primary ? (
                                  <>
                                    <div className="my-1 border-t border-slate-100" />
                                    <div className="px-3 py-2 text-[11px] font-black uppercase tracking-[0.08em] text-slate-400">{t("calendar.danger")}</div>
                                    <button
                                      type="button"
                                      onClick={() => {
                                        resetCalendarActionPanels();
                                        if (!window.confirm(t("calendar.deleteCalendarConfirm", { name: calendar.summary }))) return;
                                        void deleteCalendar.mutateAsync(calendar.id);
                                      }}
                                      onFocus={() => setActionMenuFocusIndex((calendar.primary ? 0 : 1) + (allowColorEdit ? 1 : 0) + 1)}
                                      role="menuitem"
                                      tabIndex={actionMenuFocusIndex === ((calendar.primary ? 0 : 1) + (allowColorEdit ? 1 : 0) + 1) ? 0 : -1}
                                      className="flex h-9 w-full items-center gap-2 rounded-md px-3 text-sm font-semibold text-red-600 transition hover:bg-red-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-300 focus-visible:ring-inset"
                                    >
                                      <Trash2 size={14} />
                                      {t("common.delete")}
                                    </button>
                                  </>
                                ) : null}
                              </div>
                            ) : null}
                          </div>
                        ) : null}
                      </div>
                      {!calendar.primary && allowCalendarCreation && renameCalendarId === calendar.id ? (
                        <form
                          className="mt-3 flex flex-wrap gap-2"
                          onSubmit={(event) => {
                            event.preventDefault();
                            const nextName = renameCalendarName.trim();
                            if (!nextName || nextName === calendar.summary) {
                              setRenameCalendarId("");
                              setRenameCalendarName("");
                              return;
                            }
                            void renameCalendar.mutateAsync({ calendarId: calendar.id, name: nextName });
                          }}
                        >
                          <input
                            value={renameCalendarName}
                            onChange={(event) => setRenameCalendarName(event.target.value)}
                            className="field h-10 min-w-0 flex-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                            placeholder={t("calendar.calendarName")}
                            autoFocus
                          />
                          <button type="submit" className="theme-button h-10 px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" disabled={!renameCalendarName.trim() || renameCalendar.isPending}>
                            {t("common.save")}
                          </button>
                          <button
                            type="button"
                            className="theme-button-soft h-10 px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                            onClick={() => {
                              setRenameCalendarId("");
                              setRenameCalendarName("");
                            }}
                            disabled={renameCalendar.isPending}
                          >
                            Cancel
                          </button>
                        </form>
                      ) : null}
                      {allowColorEdit && colorCalendarId === calendar.id ? (
                        <div className="mt-3 flex flex-wrap gap-1.5">
                          {calendarColorOptions.map((option) => {
                            const selected = calendarColorMatches(calendar, option.value, option.hex);
                            return (
                              <button
                                key={`${calendar.id}:${option.value}`}
                                type="button"
                                onClick={() => void updateCalendarColor.mutateAsync({ calendarId: calendar.id, color: option.value, rgb: option.hex })}
                                disabled={updateCalendarColor.isPending}
                                className={clsx(
                                  "grid h-7 w-7 place-items-center rounded-full border transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2",
                                  updateCalendarColor.isPending ? "cursor-not-allowed border-slate-100 opacity-50" : selected ? "border-slate-900 scale-105" : "border-slate-200 hover:border-slate-400"
                                )}
                                style={{ backgroundColor: option.hex }}
                                aria-label={`Set ${calendar.summary} color to ${option.label}`}
                                title={option.label}
                              >
                                {selected ? <span className="text-xs font-black text-slate-950">✓</span> : null}
                              </button>
                            );
                          })}
                        </div>
                      ) : null}
                      {calendar.primary ? <p className="mt-2 text-[11px] font-semibold text-slate-400">{t("calendar.primaryCalendarLocked")}</p> : null}
                    </div>
                    );
                  })}
                  {!calendars.length && !loadingCalendars ? <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("calendar.noCalendars")}</p> : null}
                </div>
              </div>
              <div className="rounded-xl border border-slate-200 bg-white p-3">
                <div className="mb-4 flex items-center gap-2"><CalendarDays size={18} className="text-[var(--accent)]" /><div><p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.agenda")}</p><h3 className="text-lg font-black text-slate-900">{t("calendar.upcoming")}</h3></div></div>
                <div className="grid gap-3">
                  {upcomingEvents.map((event) => (
                    <button key={event.id} type="button" onClick={() => void openEventDetails(event)} className="min-w-0 rounded-xl border px-3 py-3 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}>
                      <div className="flex min-w-0 items-center justify-between gap-2">
                        <p className="min-w-0 flex-1 break-words text-sm font-black leading-5 text-slate-900">{event.summary}</p>
                        <CalendarEventResponseBadge event={event} t={t} />
                      </div>
                      <p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p>
                      <p className="mt-1 break-words text-[11px] font-semibold leading-4 text-slate-500">{event.calendar_summary || selectedCalendarLabel}</p>
                      {isRecurringEvent(event) || event.reminder_minutes > 0 ? (
                        <p className="mt-1 text-[11px] font-semibold text-slate-400">
                          {t("calendar.recurringEvent")}
                          {isRecurringEvent(event) && event.reminder_minutes > 0 ? " • " : ""}
                          {event.reminder_minutes > 0 ? t("calendar.reminderBefore", { time: describeReminderMinutes(event.reminder_minutes) }) : ""}
                        </p>
                      ) : null}
                    </button>
                  ))}
                  {!upcomingEvents.length && !loading ? <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("calendar.noUpcomingEvents")}</p> : null}
                </div>
              </div>
              <div className="rounded-xl border border-slate-200 bg-white p-3">
                <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.selectedDay")}</p>
                <h3 className="mt-1 text-lg font-black text-slate-900">{new Intl.DateTimeFormat(calendarDisplayLocale(locale), { dateStyle: "medium" }).format(focus)}</h3>
                <div className="mt-4 grid gap-3">
                  {selectedDayEvents.slice(0, 5).map((event) => <button key={event.id} type="button" onClick={() => void openEventDetails(event)} className="min-w-0 rounded-lg border px-3 py-3 text-left transition hover:border-[var(--accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" style={calendarEventSurfaceStyle(event, calendarColorById)}><div className="flex min-w-0 items-center justify-between gap-2"><p className="min-w-0 flex-1 break-words text-sm font-bold leading-5 text-slate-900">{event.summary}</p><CalendarEventResponseBadge event={event} t={t} /></div><p className="mt-1 text-xs font-semibold text-slate-500">{formatCalendarRange(event, timeZone, locale, t)}</p><p className="mt-1 break-words text-[11px] font-semibold leading-4 text-slate-500">{event.calendar_summary || selectedCalendarLabel}</p>{isRecurringEvent(event) || event.reminder_minutes > 0 ? <p className="mt-1 text-[11px] font-semibold text-slate-400">{isRecurringEvent(event) ? t("calendar.recurringEvent") : ""}{isRecurringEvent(event) && event.reminder_minutes > 0 ? " • " : ""}{event.reminder_minutes > 0 ? t("calendar.reminderBefore", { time: describeReminderMinutes(event.reminder_minutes) }) : ""}</p> : null}</button>)}
                  {!selectedDayEvents.length ? <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("calendar.nothingScheduled")}</p> : null}
                </div>
              </div>
            </aside>
          </div>
        ) : null}
      </div>
      {allowShareManagement && shareCalendarId ? (
        <div className="fixed inset-0 z-40 grid place-items-center bg-slate-950/35 p-4">
          <div ref={shareDialogRef} role="dialog" aria-modal="true" aria-label={t("calendar.shareCalendar")} className="w-full max-w-xl rounded-2xl border border-slate-200 bg-white p-4 shadow-2xl">
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.calendarAccess")}</p>
                <h3 className="mt-1 text-lg font-black text-slate-900">{t("calendar.shareCalendar")}</h3>
              </div>
              <button type="button" onClick={() => setShareCalendarId("")} className="theme-button-soft h-9 px-3 text-sm">
                <X size={14} />
              </button>
            </div>
            <form
              className="mt-4 grid gap-3"
              onSubmit={(event) => {
                event.preventDefault();
                const email = shareEmail.trim();
                if (!email) return;
                void shareNativeCalendar.mutateAsync({ resource_id: shareCalendarId, email, permissions: sharePermissions.trim() || "r" });
              }}
            >
              <ShareRecipientAutocomplete
                value={shareEmail}
                onChange={setShareEmail}
                contacts={contacts}
                label={t("dialog.emailAddress")}
                autoFocus
                disabled={shareNativeCalendar.isPending}
              />
              <div className="flex flex-wrap gap-2">
                <select value={sharePermissions} onChange={(event) => setSharePermissions(event.target.value)} className="field h-11 min-w-[160px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2">
                  <option value="r">{t("dialog.viewer")}</option>
                  <option value="rwidx">{t("dialog.manager")}</option>
                </select>
                <span className={clsx("inline-flex h-11 items-center rounded-full px-3 text-xs font-black uppercase tracking-[0.08em]", calendarSharePermissionBadgeClass(sharePermissions))}>
                  {describeCalendarSharePermissions(sharePermissions || "r")}
                </span>
                <button type="submit" className="theme-button h-11 px-4 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" disabled={!shareEmail.trim() || shareNativeCalendar.isPending}>
                  <Share2 size={14} />
                  {shareNativeCalendar.isPending ? t("common.sharing") : t("common.share")}
                </button>
              </div>
            </form>
            <div className="mt-4 grid gap-2">
              <div className="flex items-center justify-between gap-3">
                <p className="text-sm font-black text-slate-900">{t("dialog.currentShares")}</p>
                <span className="text-xs font-semibold text-slate-400">{visibleCalendarShares.length}</span>
              </div>
              {calendarShares.isLoading ? <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("dialog.loadingShares")}</p> : null}
              {!calendarShares.isLoading && !visibleCalendarShares.length ? <p className="rounded-lg bg-slate-50 p-4 text-sm font-semibold text-slate-500">{t("calendar.noCurrentShares")}</p> : null}
              {visibleCalendarShares.map((share: NativeZimbraShareEntry) => (
                <div key={`${share.email}:${share.permissions}`} className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-3">
                  <div className="min-w-0">
                    <p className="truncate text-sm font-bold text-slate-900">{share.display_name || share.email || t("dialog.sharedAccess")}</p>
                    <div className="mt-1 flex flex-wrap items-center gap-2">
                      <span className={clsx("inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-black uppercase tracking-[0.08em]", nativeShareStateBadgeClass(share.status || "pending"))}>
                        {nativeShareStatusLabel(share.status || "pending", t)}
                      </span>
                      <span className={clsx("inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-black uppercase tracking-[0.08em]", calendarSharePermissionBadgeClass(share.permissions || "r"))}>
                        {describeCalendarSharePermissions(share.permissions || "r")}
                      </span>
                      <span className="text-xs font-semibold text-slate-500">{share.email || t("calendar.unknownRecipient")}</span>
                    </div>
                  </div>
                  <button
                    type="button"
                    className="theme-button-soft h-9 px-3 text-sm text-red-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-300 focus-visible:ring-offset-2"
                    disabled={revokeNativeCalendarShare.isPending || !share.email}
                    onClick={() => void revokeNativeCalendarShare.mutateAsync({ resource_id: shareCalendarId, email: share.email })}
                  >
                    <Trash2 size={14} />
                    {t("common.revoke")}
                  </button>
                </div>
              ))}
                </div>
          </div>
        </div>
      ) : null}
      {composerOpen ? (
          <CalendarEventDialog
            t={t}
            mode={editingEvent ? "edit" : "create"}
          calendarLabel={activeComposerCalendarLabel}
          defaultDate={focus}
          initialEvent={editingEvent}
          contacts={contacts}
          showRecurringOptions={showRecurringOptions}
          busy={createCalendarEvent.isPending || updateCalendarEvent.isPending}
          onClose={() => {
            setComposerOpen(false);
            setEditingEvent(null);
          }}
          onSave={async (draft) => {
            const payload = buildCalendarEventPayload(draft, activeComposerCalendarId, timeZone);
            if (editingEvent) {
              await updateCalendarEvent.mutateAsync({
                eventId: editingEvent.id,
                payload,
              });
              return;
            }
            await createCalendarEvent.mutateAsync(payload);
          }}
        />
      ) : null}
      {deleteConfirm ? (
        <ConfirmDialog
          title={t("calendar.deleteEvent")}
          message={
            isRecurringEvent(deleteConfirm)
              ? t("calendar.deleteRecurringMessage", { title: deleteConfirm.summary })
              : t("calendar.deleteSingleMessage", { title: deleteConfirm.summary, calendar: deleteConfirm.calendar_summary || selectedCalendarLabel })
          }
          confirmLabel={isRecurringEvent(deleteConfirm) ? t("calendar.allRecurringEvents") : t("calendar.deleteEvent")}
          secondaryConfirmLabel={isRecurringEvent(deleteConfirm) ? t("calendar.thisEventOnly") : undefined}
          t={t}
          tone="danger"
          busy={deleteCalendarEvent.isPending}
          onClose={() => setDeleteConfirm(null)}
          onSecondaryConfirm={isRecurringEvent(deleteConfirm) ? async () => {
            await deleteCalendarEvent.mutateAsync({
              eventId: deleteConfirm.id,
              calendarId: deleteConfirm.calendar_id || activeComposerCalendarId,
              scope: "this",
            });
          } : undefined}
          onConfirm={async () => {
            await deleteCalendarEvent.mutateAsync({
              eventId: deleteConfirm.id,
              calendarId: deleteConfirm.calendar_id || activeComposerCalendarId,
              scope: "series",
            });
          }}
        />
      ) : null}
      {activeEvent ? (
        <EventDetailsDialog
          t={t}
          event={activeEvent}
          calendarLabel={activeEvent.calendar_summary || selectedCalendarLabel}
          calendarColor={calendarColorById.get(activeEvent.calendar_id || "") || "#cbd5e1"}
          timeZone={timeZone}
          locale={locale}
          writable={canWriteCalendarEvent(activeEvent, calendars)}
          onClose={() => setActiveEvent(null)}
          onEdit={() => void openEventEditor(activeEvent)}
          onDelete={() => {
            if (!canWriteCalendarEvent(activeEvent, calendars)) return;
            setDeleteConfirm(activeEvent);
            setActiveEvent(null);
          }}
        />
      ) : null}
    </section>
  );
}

function calendarFormatterOptions(timeZone: string | undefined, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormatOptions {
  return timeZone ? { ...options, timeZone } : options;
}

function calendarColorMatches(calendar: CalendarSource, color: number, rgb: string) {
  const currentRgb = (calendar.rgb || calendar.background_color || "").trim().toLowerCase();
  const nextRgb = rgb.trim().toLowerCase();
  if (currentRgb && nextRgb) return currentRgb === nextRgb;
  return (calendar.color ?? 0) === color;
}

function isMountedCalendarSource(calendar: CalendarSource) {
  return Boolean((calendar.share_owner_email || calendar.share_owner_id || calendar.remote_id || "").trim()) || calendar.access_role === "reader";
}

function calendarAccessRoleLabel(calendar: CalendarSource, t: ReturnType<typeof createTranslator>) {
  if (isMountedCalendarSource(calendar)) {
    return describeCalendarSharePermissions(calendar.permissions || calendar.access_role || "r") === "manager" ? t("dialog.manager") : t("dialog.viewer");
  }
  return calendar.access_role === "owner" || !calendar.access_role ? "owner" : calendar.access_role;
}

function canWriteCalendarSource(calendar: CalendarSource | null | undefined) {
  if (!calendar) return true;
  if (!isMountedCalendarSource(calendar)) return true;
  const permissions = (calendar.permissions || "").trim().toLowerCase();
  if (permissions) {
    if (["r", "read", "reader", "view", "viewer"].includes(permissions)) return false;
    if (["owner", "manager", "admin"].includes(permissions)) return true;
    return ["w", "i", "d", "a"].some((right) => permissions.includes(right));
  }
  return ["owner", "manager", "admin"].includes((calendar.access_role || "").trim().toLowerCase());
}

function canWriteCalendarEvent(event: CalendarEvent, calendars: CalendarSource[]) {
  const source = calendars.find((calendar) => calendar.id === event.calendar_id);
  return canWriteCalendarSource(source);
}

function SharedCalendarIcon({ label }: { label: string }) {
  return (
    <span className="relative grid h-5 w-5 shrink-0 place-items-center text-[var(--accent)]" aria-label={label}>
      <CalendarDays size={16} />
      <span className="absolute -bottom-0.5 -right-0.5 grid h-3 w-3 place-items-center rounded-full bg-white text-[var(--accent)] shadow-sm">
        <Share2 size={8} />
      </span>
    </span>
  );
}

function describeCalendarSharePermissions(value: string) {
  return isCalendarManagerPermission(value) ? "manager" : "viewer";
}

function calendarSharePermissionBadgeClass(value: string) {
  if (isCalendarManagerPermission(value)) return "bg-[color-mix(in_srgb,var(--accent)_10%,white)] text-[var(--accent)]";
  return "bg-slate-100 text-slate-500";
}

function isCalendarManagerPermission(value: string) {
  const normalized = (value || "").trim().toLowerCase();
  return (
    normalized === "manager" ||
    normalized === "rwidx" ||
    normalized === "rwid" ||
    normalized === "rwd" ||
    normalized === "rw" ||
    normalized.includes("w") ||
    normalized.includes("d") ||
    normalized.includes("i") ||
    normalized.includes("x")
  );
}

function nativeShareStatusLabel(value: string, t: ReturnType<typeof createTranslator>) {
  const normalized = (value || "").trim().toLowerCase();
  if (normalized === "accepted") return t("calendar.accepted");
  if (normalized === "active") return t("sharing.active");
  if (normalized === "declined") return t("calendar.declined");
  if (normalized === "revoked") return "Revoked";
  return "Pending";
}

function nativeShareStateBadgeClass(value: string) {
  const normalized = (value || "").trim().toLowerCase();
  if (normalized === "accepted" || normalized === "active") return "border border-emerald-200 bg-emerald-50 text-emerald-800";
  if (normalized === "revoked" || normalized === "declined") return "border border-rose-200 bg-rose-50 text-rose-800";
  return "border border-amber-200 bg-amber-50 text-amber-800";
}

function hasShareRecipient(share: { email?: string }) {
  return Boolean((share.email || "").trim());
}

function isCalendarOptionSelected(calendar: CalendarSource, selectedCalendarId: string) {
  if (selectedCalendarId === "__all__") return true;
  if (selectedCalendarId === "primary") return !!calendar.primary;
  return selectedCalendarId === calendar.id;
}

function getFocusableElements(container: HTMLElement | null) {
  if (!container) return [];
  return Array.from(
    container.querySelectorAll<HTMLElement>(
      'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
    )
  ).filter((element) => !element.hasAttribute("disabled") && element.tabIndex !== -1);
}

function useFocusTrap(active: boolean, ref: RefObject<HTMLElement | null>, onClose: () => void) {
  const onCloseRef = useRef(onClose);
  onCloseRef.current = onClose;

  useEffect(() => {
    if (!active) return;
    const container = ref.current;
    if (!container) return;
    const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    const focusable = getFocusableElements(container);
    const initialFocus = focusable.find((element) => element.matches("input, textarea, select, [contenteditable='true'], [role='textbox']")) ?? focusable[0];
    initialFocus?.focus();

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onCloseRef.current();
        return;
      }
      if (event.key !== "Tab") return;
      const items = getFocusableElements(container);
      if (!items.length) {
        event.preventDefault();
        return;
      }
      const first = items[0];
      const last = items[items.length - 1];
      const activeElement = document.activeElement;
      if (event.shiftKey) {
        if (activeElement === first || !container.contains(activeElement)) {
          event.preventDefault();
          last.focus();
        }
        return;
      }
      if (activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      previous?.focus();
    };
  }, [active, ref]);
}

function calendarDisplayLocale(locale: AppLocale) {
  return `${locale}-u-ca-gregory`;
}

function formatCalendarRange(event: CalendarEvent, fallbackTimeZone: string, locale: AppLocale, t: ReturnType<typeof createTranslator>) {
  const timeZone = event.time_zone || fallbackTimeZone || DEFAULT_TIME_ZONE;
  const displayLocale = calendarDisplayLocale(locale);
  if (event.all_day) {
    const date = parseCalendarDateTime(event.start);
    if (Number.isNaN(date.getTime())) return event.start || t("calendar.allDay");
    return `${new Intl.DateTimeFormat(displayLocale, { dateStyle: "full" }).format(date)} • ${t("calendar.allDay")}`;
  }
  const start = event.start ? parseCalendarDateTime(event.start) : null;
  const end = event.end ? parseCalendarDateTime(event.end) : null;
  if (!start || Number.isNaN(start.getTime())) return event.start || "";
  const sameDay = !!end && !Number.isNaN(end.getTime()) && calendarDateKey(start, timeZone) === calendarDateKey(end, timeZone);
  const startText = new Intl.DateTimeFormat(displayLocale, calendarFormatterOptions(timeZone, { dateStyle: "medium", timeStyle: "short" })).format(start);
  if (!end || Number.isNaN(end.getTime())) return startText;
  const endText = sameDay
    ? new Intl.DateTimeFormat(displayLocale, calendarFormatterOptions(timeZone, { timeStyle: "short" })).format(end)
    : new Intl.DateTimeFormat(displayLocale, calendarFormatterOptions(timeZone, { dateStyle: "medium", timeStyle: "short" })).format(end);
  return `${startText} - ${endText}`;
}

function CalendarEventResponseBadge({ event, t }: { event: CalendarEvent; t: ReturnType<typeof createTranslator> }) {
  const status = (event.attendee_status || "").trim().toUpperCase();
  const recurring = isRecurringEvent(event);
  const showResponse = !(event.is_organizer || !status || status === "NE" || status === "NEEDS-ACTION");
  if (!recurring && !showResponse) return null;
  const accepted = status === "AC" || status === "ACCEPTED";
  const tentative = status === "TE" || status === "TENTATIVE";
  const label = accepted ? t("calendar.accepted") : tentative ? t("calendar.tentative") : t("calendar.declined");
  return (
    <span className="inline-flex shrink-0 items-center gap-1">
      {recurring ? (
        <span
          className="inline-flex shrink-0 items-center gap-1 rounded-full border border-sky-200 bg-sky-50 px-1.5 py-0.5 text-[10px] font-black text-sky-700"
          title={t("calendar.recurringEvent")}
          aria-label={t("calendar.recurringEvent")}
        >
          <Repeat2 size={11} />
          <span className="hidden sm:inline">{t("calendar.recurringEvent")}</span>
        </span>
      ) : null}
      {showResponse ? (
        <span
          className={clsx(
            "inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-black",
            accepted ? "border-emerald-200 bg-emerald-50 text-emerald-700" : tentative ? "border-amber-200 bg-amber-50 text-amber-700" : "border-red-200 bg-red-50 text-red-700"
          )}
          title={label}
          aria-label={label}
        >
          {accepted ? <Check size={11} /> : tentative ? <Clock3 size={11} /> : <X size={11} />}
          <span className="hidden sm:inline">{label}</span>
        </span>
      ) : null}
    </span>
  );
}

function isRecurringEvent(event: CalendarEvent) {
  return Boolean(event.recurring) || (event.repeat_pattern || "none").trim().toLowerCase() !== "none";
}

function describeEventRecurrence(event: CalendarEvent) {
  if (!isRecurringEvent(event)) return "";
  if ((event.repeat_pattern || "none").trim().toLowerCase() === "none") return "Recurring event";
  return `Repeats ${describeRepeatPattern(event.repeat_pattern, event.repeat_interval)} ${describeRepeatEndMode(event.repeat_end_mode, event.repeat_until, event.repeat_occurrences)}`;
}

function calendarEventStart(event: CalendarEvent) {
  const value = event.start || event.end;
  const date = parseCalendarDateTime(value);
  return Number.isNaN(date.getTime()) ? new Date(NaN) : date;
}

function calendarEventEnd(event: CalendarEvent) {
  const value = event.end || event.start;
  const date = parseCalendarDateTime(value);
  return Number.isNaN(date.getTime()) ? calendarEventStart(event) : date;
}

function calendarEventBadge(event: CalendarEvent, fallbackTimeZone: string, locale: AppLocale, t: ReturnType<typeof createTranslator>) {
  const timeZone = event.time_zone || fallbackTimeZone || DEFAULT_TIME_ZONE;
  return event.all_day ? t("calendar.allDay") : new Intl.DateTimeFormat(calendarDisplayLocale(locale), calendarFormatterOptions(timeZone, { hour: "2-digit", minute: "2-digit" })).format(calendarEventStart(event));
}

function calendarEventSurfaceStyle(event: CalendarEvent, calendarColorById: Map<string, string>) {
  const color = calendarColorById.get(event.calendar_id || "") || "#e2e8f0";
  return {
    backgroundColor: `color-mix(in srgb, ${color} 16%, white)`,
    borderColor: `color-mix(in srgb, ${color} 32%, white)`,
  };
}

function todayStart() { return startOfDay(new Date()); }
function startOfDay(date: Date) { return new Date(date.getFullYear(), date.getMonth(), date.getDate()); }
function startOfWeek(date: Date) { const copy = startOfDay(date); copy.setDate(copy.getDate() - copy.getDay()); return copy; }
function startOfMonth(date: Date) { return new Date(date.getFullYear(), date.getMonth(), 1); }
function addDays(date: Date, amount: number) { const copy = startOfDay(date); copy.setDate(copy.getDate() + amount); return copy; }
function addMonths(date: Date, amount: number) { return new Date(date.getFullYear(), date.getMonth() + amount, 1); }
function parseIsoDate(value: string) { const date = new Date(`${value}T00:00:00`); return Number.isNaN(date.getTime()) ? todayStart() : date; }
function parseCalendarDateTime(value: string) {
  const text = (value || "").trim();
  if (!text) return new Date(NaN);
  const compact = /^(\d{4})(\d{2})(\d{2})T?(\d{2})(\d{2})(\d{2})Z?$/.exec(text);
  if (compact) {
    const date = new Date(Date.UTC(Number(compact[1]), Number(compact[2]) - 1, Number(compact[3]), Number(compact[4]), Number(compact[5]), Number(compact[6])));
    return Number.isNaN(date.getTime()) ? new Date(NaN) : date;
  }
  if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
    return new Date(`${text}T00:00:00`);
  }
  const date = new Date(text);
  return Number.isNaN(date.getTime()) ? new Date(NaN) : date;
}
function isoDate(date: Date) { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; }
function sameDay(a: Date, b: Date) { return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); }
function sameMonth(a: Date, b: Date) { return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth(); }
function occursOnDay(event: { startDate: Date; endDate: Date; all_day?: boolean }, day: Date) {
  const start = startOfDay(event.startDate);
  const rawEnd = startOfDay(event.endDate);
  const inclusiveEnd = event.all_day && rawEnd.getTime() > start.getTime() ? addDays(rawEnd, -1) : rawEnd;
  const end = inclusiveEnd.getTime() < start.getTime() ? start : inclusiveEnd;
  return start.getTime() <= day.getTime() && day.getTime() <= end.getTime();
}
function calendarDateKey(date: Date, timeZone: string) {
  return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
}

function normalizeCalendarPlainText(value: string) {
  const text = (value || "").replace(/\\r\\n|\\n|\\r/g, "\n").replace(/\\,/g, ",").replace(/\\;/g, ";").replace(/\\\\/g, "\\");
  if (looksLikeHtml(text) && typeof document !== "undefined") {
    const template = document.createElement("template");
    template.innerHTML = text;
    return (template.content.textContent || "").replace(/\u00a0/g, " ").trim();
  }
  return text.trim();
}

function safeCalendarDescriptionHtml(value: string) {
  const text = (value || "").replace(/\\r\\n|\\n|\\r/g, "\n").trim();
  if (!text || !looksLikeHtml(text) || typeof document === "undefined") return "";
  const template = document.createElement("template");
  template.innerHTML = text;
  const allowedTags = new Set(["A", "B", "BR", "DIV", "EM", "I", "IMG", "LI", "OL", "P", "SPAN", "STRONG", "TABLE", "TBODY", "TD", "TH", "THEAD", "TR", "UL"]);
  const allowedAttrs = new Set(["href", "src", "alt", "title", "colspan", "rowspan"]);
  template.content.querySelectorAll("*").forEach((node) => {
    if (!allowedTags.has(node.tagName)) {
      node.replaceWith(...Array.from(node.childNodes));
      return;
    }
    Array.from(node.attributes).forEach((attr) => {
      const name = attr.name.toLowerCase();
      if (name.startsWith("on") || name === "style" || !allowedAttrs.has(name)) {
        node.removeAttribute(attr.name);
        return;
      }
      if ((name === "href" || name === "src") && !isSafeCalendarUrl(attr.value, name === "src")) {
        node.removeAttribute(attr.name);
      }
    });
    if (node.tagName === "A") {
      node.setAttribute("target", "_blank");
      node.setAttribute("rel", "noreferrer");
    }
    if (node.tagName === "IMG" && !node.getAttribute("alt")) {
      node.setAttribute("alt", "");
    }
  });
  return template.innerHTML.trim();
}

function looksLikeHtml(value: string) {
  return /<\/?[a-z][\s\S]*>/i.test(value || "");
}

function isSafeCalendarUrl(value: string, allowDataImage: boolean) {
  const text = (value || "").trim();
  if (!text) return false;
  if (allowDataImage && /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(text)) return true;
  if (/^(https?:|mailto:)/i.test(text)) return true;
  if (text.startsWith("/")) return true;
  return false;
}

type CalendarEventDraft = {
  summary: string;
  allDay: boolean;
  startDate: string;
  endDate: string;
  startTime: string;
  endTime: string;
  location: string;
  description: string;
  attendees: string;
  repeatPattern: "none" | "daily" | "weekly" | "monthly" | "yearly";
  repeatInterval: string;
  repeatEndMode: "never" | "on_date" | "after_occurrences";
  repeatUntil: string;
  repeatOccurrences: string;
  reminderMinutes: string;
};

function CalendarEventDialog({
  t,
  mode,
  calendarLabel,
  defaultDate,
  initialEvent,
  contacts,
  showRecurringOptions,
  busy,
  onClose,
  onSave
}: {
  t: ReturnType<typeof createTranslator>;
  mode: "create" | "edit";
  calendarLabel: string;
  defaultDate: Date;
  initialEvent: CalendarEvent | null;
  contacts: Contact[];
  showRecurringOptions: boolean;
  busy: boolean;
  onClose: () => void;
  onSave: (draft: CalendarEventDraft) => void | Promise<void>;
}) {
  const dialogRef = useRef<HTMLFormElement | null>(null);
  const [draft, setDraft] = useState<CalendarEventDraft>(() =>
    initialEvent ? draftFromCalendarEvent(initialEvent, defaultDate) : defaultCalendarEventDraft(defaultDate)
  );
  const [submitError, setSubmitError] = useState("");
  const disabled = !draft.summary.trim() || !draft.startDate || !draft.endDate || (!draft.allDay && (!draft.startTime || !draft.endTime)) || busy;

  useFocusTrap(true, dialogRef, onClose);

  useEffect(() => {
    setSubmitError("");
    setDraft(initialEvent ? draftFromCalendarEvent(initialEvent, defaultDate) : defaultCalendarEventDraft(defaultDate));
  }, [defaultDate.getTime(), initialEvent?.id]);

  const attendeeToken = currentAttendeeToken(draft.attendees);
  const attendeeAddresses = parseAttendeeList(draft.attendees);
  const attendeeSuggestions = useMemo(
    () =>
      attendeeToken
        ? contacts
            .filter((contact) => {
              const email = contact.email.trim();
              if (!email) return false;
              return email.toLowerCase().includes(attendeeToken) && !attendeeAddresses.some((item) => item.toLowerCase() === email.toLowerCase());
            })
            .slice(0, 6)
        : [],
    [attendeeAddresses, attendeeToken, contacts]
  );

  function applyAttendeeSuggestion(email: string) {
    const clean = email.trim().replace(/,$/, "");
    if (!clean) return;
    const current = parseAttendeeList(draft.attendees);
    if (current.some((item) => item.toLowerCase() === clean.toLowerCase())) return;
    const pending = currentAttendeeToken(draft.attendees);
    const next = pending ? current.slice(0, -1).concat(clean).join(", ") + ", " : current.concat(clean).join(", ") + ", ";
    setSubmitError("");
    setDraft((state) => ({ ...state, attendees: next }));
  }

  const dialogTitle = mode === "edit" ? t("calendar.editEvent") : t("calendar.newEvent");

  return (
    <div className="fixed inset-0 z-[10000] grid place-items-end bg-slate-950/35 p-0 backdrop-blur-sm sm:place-items-center sm:p-4">
      <form
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-label={dialogTitle}
        className="grid h-[100dvh] w-full max-w-none grid-rows-[auto_minmax(0,1fr)] overflow-hidden rounded-none border border-slate-200 bg-white shadow-soft sm:h-auto sm:max-h-[92vh] sm:max-w-2xl sm:rounded-xl"
        onClick={(event) => event.stopPropagation()}
        onSubmit={async (event) => {
          event.preventDefault();
          if (disabled) return;
          const attendeeValidation = validateCalendarAttendees(draft.attendees, t);
          if (attendeeValidation.error) {
            setSubmitError(attendeeValidation.error);
            return;
          }
          if (draft.allDay) {
            if (parseIsoDate(draft.endDate).getTime() < parseIsoDate(draft.startDate).getTime()) {
              setSubmitError(t("calendar.endDateError"));
              return;
            }
          } else if (calendarDraftDateTimeValue(draft.endDate, draft.endTime) <= calendarDraftDateTimeValue(draft.startDate, draft.startTime)) {
            setSubmitError(t("calendar.endTimeError"));
            return;
          }
          if (draft.repeatPattern !== "none") {
            if (draft.repeatEndMode === "on_date" && !draft.repeatUntil.trim()) {
              setSubmitError(t("calendar.repeatEndRequired"));
              return;
            }
            if (draft.repeatEndMode === "after_occurrences") {
              const occurrences = Number.parseInt(draft.repeatOccurrences, 10);
              if (!Number.isFinite(occurrences) || occurrences < 1) {
                setSubmitError(t("calendar.repeatOccurrencesError"));
                return;
              }
            }
          }
          setSubmitError("");
          await onSave({ ...draft, attendees: attendeeValidation.attendees.join(", ") });
        }}
      >
        <div className="flex items-center justify-between border-b border-slate-200 px-4 py-3 sm:border-b-0 sm:px-5 sm:pb-0 sm:pt-5">
          <div>
            <p className="text-xs font-black uppercase text-slate-500">{t("calendar.calendar")}</p>
            <h3 className="text-lg font-black">{dialogTitle}</h3>
            <p className="mt-1 text-sm font-medium text-slate-500">{calendarLabel}</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" aria-label={t("calendar.closeEventDialog")}>
            <X size={17} />
          </button>
        </div>
        <div className="grid gap-4 overflow-auto px-4 py-4 sm:px-5 sm:pb-5">
          <div className="grid gap-2">
            <label className="text-sm font-bold text-slate-600">{t("calendar.title")}</label>
            <input value={draft.summary} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, summary: event.target.value })); }} className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" placeholder={t("calendar.meetingTitle")} autoFocus />
          </div>
          <label className="inline-flex items-center gap-3 text-sm font-bold text-slate-600">
            <input type="checkbox" checked={draft.allDay} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, allDay: event.target.checked })); }} className="h-4 w-4 rounded border-slate-300 text-emerald-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" />
            {t("calendar.allDay")}
          </label>
              <div className={clsx("grid gap-4", draft.allDay ? "md:grid-cols-2" : "md:grid-cols-4")}>
                <div className="grid gap-2">
                  <label className="text-sm font-bold text-slate-600">{t("calendar.startDate")}</label>
                  <input type="date" value={draft.startDate} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, startDate: event.target.value })); }} className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" />
                </div>
                {!draft.allDay ? (
                  <div className="grid gap-2">
                    <label className="text-sm font-bold text-slate-600">{t("calendar.startTime")}</label>
                    <TimePickerField
                      value={draft.startTime}
                      t={t}
                      onChange={(value) => {
                        setSubmitError("");
                        setDraft((current) => ({ ...current, startTime: value }));
                      }}
                    />
                  </div>
                ) : null}
                <div className="grid gap-2">
                  <label className="text-sm font-bold text-slate-600">{t("calendar.endDate")}</label>
                  <input type="date" value={draft.endDate} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, endDate: event.target.value })); }} className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" />
                </div>
                {!draft.allDay ? (
                  <div className="grid gap-2">
                    <label className="text-sm font-bold text-slate-600">{t("calendar.endTime")}</label>
                    <TimePickerField
                      value={draft.endTime}
                      t={t}
                      onChange={(value) => {
                        setSubmitError("");
                        setDraft((current) => ({ ...current, endTime: value }));
                      }}
                    />
                  </div>
                ) : null}
              </div>
          <div className="grid gap-2">
            <label className="text-sm font-bold text-slate-600">{t("calendar.location")}</label>
            <input value={draft.location} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, location: event.target.value })); }} className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" placeholder={t("calendar.locationPlaceholder")} />
          </div>
          <div className="grid gap-2">
            <label className="text-sm font-bold text-slate-600">{t("calendar.description")}</label>
            <textarea value={draft.description} onChange={(event) => { setSubmitError(""); setDraft((current) => ({ ...current, description: event.target.value })); }} className="field min-h-32 w-full p-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" placeholder={t("calendar.descriptionPlaceholder")} />
          </div>
          {showRecurringOptions ? (
            <div className="grid gap-4 rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div className="grid gap-2">
                <label className="text-sm font-bold text-slate-600">{t("calendar.repeat")}</label>
                <select
                  value={draft.repeatPattern}
                  onChange={(event) => {
                    setSubmitError("");
                    const nextPattern = event.target.value as CalendarEventDraft["repeatPattern"];
                    setDraft((current) => ({
                      ...current,
                      repeatPattern: nextPattern,
                    }));
                  }}
                  className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                >
                  <option value="none">{t("calendar.doesNotRepeat")}</option>
                  <option value="daily">{t("calendar.daily")}</option>
                  <option value="weekly">{t("calendar.weekly")}</option>
                  <option value="monthly">{t("calendar.monthly")}</option>
                  <option value="yearly">{t("calendar.yearly")}</option>
                </select>
              </div>
              {draft.repeatPattern !== "none" ? (
                <>
                  <div className="grid gap-2">
                    <label className="text-sm font-bold text-slate-600">{t("calendar.repeatInterval")}</label>
                    <input
                      type="number"
                      min={1}
                      max={99}
                      value={draft.repeatInterval}
                      onChange={(event) => {
                        setSubmitError("");
                        setDraft((current) => ({ ...current, repeatInterval: event.target.value }));
                      }}
                      className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                    />
                  </div>
                  <div className="grid gap-2">
                    <label className="text-sm font-bold text-slate-600">{t("calendar.ends")}</label>
                    <select
                      value={draft.repeatEndMode}
                      onChange={(event) => {
                        setSubmitError("");
                        const nextMode = event.target.value as CalendarEventDraft["repeatEndMode"];
                        setDraft((current) => ({ ...current, repeatEndMode: nextMode }));
                      }}
                      className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                    >
                      <option value="never">{t("calendar.never")}</option>
                      <option value="on_date">{t("calendar.onDate")}</option>
                      <option value="after_occurrences">{t("calendar.afterOccurrences")}</option>
                    </select>
                  </div>
                  {draft.repeatEndMode === "on_date" ? (
                    <div className="grid gap-2">
                      <label className="text-sm font-bold text-slate-600">{t("calendar.repeatEndDate")}</label>
                      <input
                        type="date"
                        value={draft.repeatUntil}
                        onChange={(event) => {
                          setSubmitError("");
                          setDraft((current) => ({ ...current, repeatUntil: event.target.value }));
                        }}
                        className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                      />
                    </div>
                  ) : null}
                  {draft.repeatEndMode === "after_occurrences" ? (
                    <div className="grid gap-2">
                      <label className="text-sm font-bold text-slate-600">{t("calendar.occurrences")}</label>
                      <input
                        type="number"
                        min={1}
                        max={999}
                        value={draft.repeatOccurrences}
                        onChange={(event) => {
                          setSubmitError("");
                          setDraft((current) => ({ ...current, repeatOccurrences: event.target.value }));
                        }}
                        className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                      />
                    </div>
                  ) : null}
                  <p className="text-xs font-semibold text-slate-500">
                    {describeRepeatPattern(draft.repeatPattern, Number.parseInt(draft.repeatInterval, 10))}{" "}
                    {describeRepeatEndMode(draft.repeatEndMode, draft.repeatUntil, Number.parseInt(draft.repeatOccurrences, 10))}
                  </p>
                </>
              ) : null}
              <div className="grid gap-2">
                <label className="text-sm font-bold text-slate-600">{t("calendar.reminder")}</label>
                <select
                  value={draft.reminderMinutes}
                  onChange={(event) => {
                    setSubmitError("");
                    setDraft((current) => ({ ...current, reminderMinutes: event.target.value }));
                  }}
                  className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                >
                  <option value="0">{t("calendar.reminderNone")}</option>
                  <option value="5">{t("calendar.minutesBefore", { minutes: 5 })}</option>
                  <option value="10">{t("calendar.minutesBefore", { minutes: 10 })}</option>
                  <option value="15">{t("calendar.minutesBefore", { minutes: 15 })}</option>
                  <option value="30">{t("calendar.minutesBefore", { minutes: 30 })}</option>
                  <option value="60">{t("calendar.hourBefore")}</option>
                  <option value="1440">{t("calendar.dayBefore")}</option>
                </select>
              </div>
            </div>
          ) : null}
          <div className="grid gap-2">
            <label className="text-sm font-bold text-slate-600">{t("calendar.attendees")}</label>
            <div className="relative">
              <input
                value={draft.attendees}
                onChange={(event) => {
                  setSubmitError("");
                  setDraft((current) => ({ ...current, attendees: event.target.value }));
                }}
                onKeyDown={(event) => {
                  if (!attendeeSuggestions.length) return;
                  if (event.key === "Enter" || event.key === "Tab" || event.key === ",") {
                    event.preventDefault();
                    applyAttendeeSuggestion(attendeeSuggestions[0].email);
                    return;
                  }
                }}
                className="field h-11 w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
                placeholder="name@example.com, name2@example.com"
                autoComplete="off"
              />
              {attendeeSuggestions.length ? (
                <div className="absolute left-0 right-0 top-full z-20 mt-1 overflow-hidden rounded-xl border border-slate-200 bg-white shadow-soft">
                  {attendeeSuggestions.map((contact) => (
                    <button
                      key={`${contact.id || contact.email}`}
                      type="button"
                      onMouseDown={(event) => event.preventDefault()}
                      onClick={() => applyAttendeeSuggestion(contact.email)}
                      className="flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm transition hover:bg-slate-50"
                    >
                      <span className="min-w-0">
                        <strong className="block truncate text-slate-800">{contact.email}</strong>
                      </span>
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
            <p className="text-xs font-medium text-slate-500">{t("calendar.attendeesHelp")}</p>
          </div>
          {submitError ? <p className="text-sm font-bold text-red-600">{submitError}</p> : null}
          <div className="grid grid-cols-2 gap-2 sm:flex sm:justify-end">
            <button type="button" onClick={onClose} className="h-11 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2 sm:h-10">{t("common.cancel")}</button>
            <button type="submit" disabled={disabled} className="theme-button h-11 px-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2 disabled:opacity-50 sm:h-10">{busy ? t("common.saving") : mode === "edit" ? t("calendar.saveChanges") : t("calendar.createEvent")}</button>
          </div>
        </div>
      </form>
    </div>
  );
}

function ConfirmDialog({
  title,
  message,
  confirmLabel,
  secondaryConfirmLabel,
  t,
  tone = "default",
  busy,
  onClose,
  onConfirm,
  onSecondaryConfirm,
}: {
  title: string;
  message: string;
  confirmLabel: string;
  secondaryConfirmLabel?: string;
  t: ReturnType<typeof createTranslator>;
  tone?: "default" | "danger";
  busy: boolean;
  onClose: () => void;
  onConfirm: () => void | Promise<void>;
  onSecondaryConfirm?: () => void | Promise<void>;
}) {
  const dialogRef = useRef<HTMLDivElement | null>(null);

  useFocusTrap(true, dialogRef, onClose);

  return (
    <div className="fixed inset-0 z-[10001] grid place-items-center bg-slate-950/35 p-4 backdrop-blur-sm">
      <div ref={dialogRef} role="dialog" aria-modal="true" aria-label={title} className="w-full max-w-md rounded-xl border border-slate-200 bg-white p-5 shadow-soft">
        <h3 className="text-lg font-black text-slate-900">{title}</h3>
        <p className="mt-2 text-sm leading-6 text-slate-600">{message}</p>
        <div className="mt-5 flex flex-wrap justify-end gap-2">
          <button type="button" onClick={onClose} className="theme-button-soft h-10 px-4 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" disabled={busy}>{t("common.cancel")}</button>
          {secondaryConfirmLabel && onSecondaryConfirm ? (
            <button type="button" onClick={() => void onSecondaryConfirm()} className="theme-button-soft h-10 border-red-200 px-4 text-sm font-bold text-red-600 hover:bg-red-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-300 focus-visible:ring-offset-2" disabled={busy}>
              {busy ? t("common.working") : secondaryConfirmLabel}
            </button>
          ) : null}
          <button type="button" onClick={() => void onConfirm()} className={clsx("h-10 rounded-lg px-4 text-sm font-bold text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2", tone === "danger" ? "bg-red-600 hover:bg-red-500 focus-visible:ring-red-300" : "bg-[var(--accent)] hover:brightness-105 focus-visible:ring-[var(--accent)]")} disabled={busy}>
            {busy ? t("common.working") : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

function EventDetailsDialog({
  t,
  event,
  calendarLabel,
  calendarColor,
  timeZone,
  locale,
  writable,
  onClose,
  onEdit,
  onDelete,
}: {
  t: ReturnType<typeof createTranslator>;
  event: CalendarEvent;
  calendarLabel: string;
  calendarColor: string;
  timeZone: string;
  locale: AppLocale;
  writable: boolean;
  onClose: () => void;
  onEdit: () => void | Promise<void>;
  onDelete: () => void;
}) {
  const dialogRef = useRef<HTMLDivElement | null>(null);
  useFocusTrap(true, dialogRef, onClose);
  const attendeeDetails: CalendarAttendee[] = event.attendee_details?.length
    ? event.attendee_details
    : event.attendees.map((email) => ({ email, name: "", status: "NE", role: "", rsvp: false }));
  const statusLabel = (status: string) => {
    const normalized = status.toUpperCase();
    if (normalized === "AC" || normalized === "ACCEPTED") return t("calendar.accepted");
    if (normalized === "TE" || normalized === "TENTATIVE") return t("calendar.tentative");
    if (normalized === "DE" || normalized === "DECLINED") return t("calendar.declined");
    if (normalized === "DG" || normalized === "DELEGATED") return t("calendar.delegated");
    return t("calendar.needAction");
  };
  const statusClass = (status: string) => {
    const normalized = status.toUpperCase();
    if (normalized === "AC" || normalized === "ACCEPTED") return "border-emerald-200 bg-emerald-50 text-emerald-700";
    if (normalized === "TE" || normalized === "TENTATIVE") return "border-amber-200 bg-amber-50 text-amber-700";
    if (normalized === "DE" || normalized === "DECLINED") return "border-red-200 bg-red-50 text-red-700";
    return "border-slate-200 bg-slate-50 text-slate-600";
  };
  const descriptionHtml = safeCalendarDescriptionHtml(event.description_html || "");
  const descriptionText = normalizeCalendarPlainText(event.description || "");

  return (
    <div className="fixed inset-0 z-[10000] grid place-items-end bg-slate-950/35 p-0 backdrop-blur-sm sm:place-items-center sm:p-4">
      <div ref={dialogRef} role="dialog" aria-modal="true" aria-label={t("calendar.eventDetails")} className="grid h-[100dvh] w-full max-w-none grid-rows-[auto_minmax(0,1fr)] overflow-hidden rounded-none border border-slate-200 bg-white shadow-soft sm:h-auto sm:max-h-[92vh] sm:w-[min(960px,calc(100vw-2rem))] sm:rounded-xl">
        <div className="flex items-center justify-between border-b border-slate-200 px-4 py-3 sm:border-b-0 sm:px-5 sm:pb-0 sm:pt-5">
          <div className="min-w-0">
            <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-500">{t("calendar.event")}</p>
            <h3 className="max-w-[72ch] break-words text-lg font-black leading-6 text-slate-900">{event.summary}</h3>
            <p className="mt-1 truncate text-sm font-medium text-slate-500">{calendarLabel}</p>
          </div>
          <button type="button" onClick={onClose} className="icon-button h-10 w-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2" aria-label={t("calendar.eventDetails")}>
            <X size={17} />
          </button>
        </div>
        <div className="grid gap-4 overflow-auto px-4 py-4 sm:px-5 sm:pb-5">
          <div className="rounded-xl border px-4 py-4" style={{ backgroundColor: `color-mix(in srgb, ${calendarColor} 16%, white)`, borderColor: `color-mix(in srgb, ${calendarColor} 32%, white)` }}>
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div className="min-w-0">
                <p className="text-sm font-bold text-slate-900">{formatCalendarRange(event, timeZone, locale, t)}</p>
                {event.location ? <p className="mt-1 text-sm font-semibold text-slate-600">{event.location}</p> : null}
              </div>
              <div className="inline-flex items-center gap-1.5 rounded-full border border-black/5 px-2 py-0.5 text-[11px] font-semibold text-slate-700" style={{ backgroundColor: "color-mix(in srgb, white 72%, transparent)" }}>
                <span className="h-2 w-2 rounded-full border border-black/5" style={{ backgroundColor: calendarColor }} />
                <span className="truncate">{calendarLabel}</span>
              </div>
            </div>
            {isRecurringEvent(event) || event.reminder_minutes > 0 ? (
              <p className="mt-3 text-sm font-semibold text-slate-500">
                {t("calendar.recurringEvent")}
                {isRecurringEvent(event) && event.reminder_minutes > 0 ? " • " : ""}
                {event.reminder_minutes > 0 ? t("calendar.reminderBefore", { time: describeReminderMinutes(event.reminder_minutes) }) : ""}
              </p>
            ) : null}
          </div>
          {descriptionHtml || descriptionText ? (
            <div className="overflow-hidden rounded-xl border border-slate-200 bg-slate-50 px-4 py-4">
              <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.description")}</p>
              {descriptionHtml ? (
                <div
                  className="mt-2 max-w-none break-words text-sm leading-6 text-slate-700 [overflow-wrap:anywhere] [&_*]:max-w-full [&_a]:font-semibold [&_a]:text-[var(--accent)] [&_img]:my-3 [&_img]:h-auto [&_img]:max-h-[520px] [&_img]:max-w-full [&_img]:rounded-lg [&_img]:border [&_img]:border-slate-200 [&_table]:block [&_table]:max-w-full [&_table]:overflow-auto"
                  dangerouslySetInnerHTML={{ __html: descriptionHtml }}
                />
              ) : (
                <div className="mt-2 whitespace-pre-wrap break-words text-sm leading-6 text-slate-700 [overflow-wrap:anywhere]">{descriptionText}</div>
              )}
            </div>
          ) : null}
          {event.organizer || event.attendee_status || attendeeDetails.length ? (
            <div className="rounded-xl border border-slate-200 bg-white px-4 py-4">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <p className="text-xs font-black uppercase tracking-[0.12em] text-slate-400">{t("calendar.attendees")}</p>
                {!event.is_organizer && event.attendee_status ? (
                  <span className={clsx("rounded-full border px-2.5 py-1 text-xs font-bold", statusClass(event.attendee_status))}>
                    {t("calendar.yourResponse", { status: statusLabel(event.attendee_status) })}
                  </span>
                ) : null}
              </div>
              {event.organizer ? <p className="mt-2 text-sm text-slate-600">{t("calendar.organizer")} <span className="font-semibold text-slate-800">{event.organizer}</span></p> : null}
              <div className="mt-3 divide-y divide-slate-100">
                {attendeeDetails.map((attendee) => (
                  <div key={attendee.email} className="flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0">
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-slate-800">{attendee.name || attendee.email}</p>
                      {attendee.name ? <p className="truncate text-xs text-slate-500">{attendee.email}</p> : null}
                    </div>
                    <span className={clsx("shrink-0 rounded-full border px-2.5 py-1 text-xs font-bold", statusClass(attendee.status))}>
                      {statusLabel(attendee.status)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ) : null}
          <div className="grid gap-3 sm:flex sm:justify-end sm:gap-2">
            <button type="button" onClick={onClose} className="hidden h-10 rounded-lg border border-slate-200 bg-white px-4 font-bold text-slate-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2 sm:inline-flex sm:items-center sm:justify-center">
              {t("common.close")}
            </button>
            {writable ? (
              <>
                <button type="button" onClick={() => void onEdit()} className="theme-button h-11 w-full justify-center px-4 font-bold sm:h-10 sm:w-auto">
                  {t("common.edit")}
                </button>
                <button type="button" onClick={onDelete} className="theme-button-soft h-11 w-full justify-center border-red-200 px-4 font-bold text-red-600 hover:bg-red-50 sm:h-10 sm:w-auto">
                  {t("common.delete")}
                </button>
              </>
            ) : null}
          </div>
        </div>
      </div>
    </div>
  );
}

function getCalendarCardButtons(container: HTMLElement | null) {
  if (!container) return [];
  return Array.from(container.querySelectorAll<HTMLButtonElement>("button[data-calendar-id]"));
}

function calendarDraftDateTimeValue(date: string, time: string) {
  return new Date(`${date}T${time}:00`).getTime();
}

function validateCalendarAttendees(value: string, t: ReturnType<typeof createTranslator>) {
  const attendees = value
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
  const valid: string[] = [];
  const seen = new Set<string>();
  const invalid: string[] = [];
  for (const attendee of attendees) {
    const normalized = attendee.toLowerCase();
    if (seen.has(normalized)) continue;
    if (!isValidEmailAddress(attendee)) {
      invalid.push(attendee);
      continue;
    }
    seen.add(normalized);
    valid.push(attendee);
  }
  if (invalid.length) {
    return {
      attendees: valid,
      error: invalid.length === 1 ? t("calendar.invalidAttendee", { email: invalid[0] }) : t("calendar.invalidAttendees", { emails: invalid.join(", ") }),
    };
  }
  return { attendees: valid, error: "" };
}

function parseAttendeeList(value: string) {
  return value
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
}

function currentAttendeeToken(value: string) {
  return value.split(",").pop()?.trim().toLowerCase() || "";
}

function TimePickerField({ value, onChange, t }: { value: string; onChange: (value: string) => void; t: ReturnType<typeof createTranslator> }) {
  const triggerRef = useRef<HTMLButtonElement | null>(null);
  const panelRef = useRef<HTMLDivElement | null>(null);
  const [open, setOpen] = useState(false);
  const [hoverHour, setHoverHour] = useState(() => parseTimeHour(value));
  const [position, setPosition] = useState({ top: 0, left: 0, width: 0 });

  useEffect(() => {
    if (!open) return;
    setHoverHour(parseTimeHour(value));
  }, [open, value]);

  useEffect(() => {
    if (!open) return;

    const updatePosition = () => {
      const rect = triggerRef.current?.getBoundingClientRect();
      if (!rect) return;
      const margin = 12;
      const width = Math.min(320, Math.max(280, window.innerWidth - margin * 2));
      const estimatedHeight = 336;
      const maxLeft = Math.max(margin, window.innerWidth - width - margin);
      const left = Math.min(maxLeft, Math.max(margin, rect.left));
      const openAbove = rect.bottom + estimatedHeight + margin > window.innerHeight && rect.top - estimatedHeight - margin > margin;
      const top = openAbove ? Math.max(margin, rect.top - estimatedHeight - 8) : rect.bottom + 8;
      setPosition({ top, left, width });
    };

    const onPointerDown = (event: MouseEvent) => {
      const target = event.target as Node | null;
      if (!target) return;
      if (triggerRef.current?.contains(target)) return;
      if (panelRef.current?.contains(target)) return;
      setOpen(false);
    };
    const onEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };

    updatePosition();
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onEscape);
    window.addEventListener("resize", updatePosition);
    window.addEventListener("scroll", updatePosition, true);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onEscape);
      window.removeEventListener("resize", updatePosition);
      window.removeEventListener("scroll", updatePosition, true);
    };
  }, [open]);

  const parsedHour = parseTimeHour(value);
  const parsedMinute = parseTimeMinute(value);
  const selectedHour = Number.isFinite(hoverHour) ? hoverHour : parsedHour;
  const displayValue = formatTimeValue(parsedHour, parsedMinute);
  const quarterOptions = [15, 30, 45];

  return (
    <>
      <button
        ref={triggerRef}
        type="button"
        onClick={() => setOpen((current) => !current)}
        onKeyDown={(event) => {
          if (event.key === "ArrowDown" || event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            setOpen(true);
          }
        }}
        className="field flex h-11 w-full items-center justify-between gap-3 px-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)] focus-visible:ring-offset-2"
        aria-haspopup="dialog"
        aria-expanded={open}
      >
        <span className="font-semibold text-slate-900">{displayValue}</span>
        <Clock3 size={15} className="shrink-0 text-slate-400" />
      </button>
      {open && typeof document !== "undefined"
        ? createPortal(
            <div
              ref={panelRef}
              className="fixed z-[10050] overflow-hidden rounded-xl border border-slate-200 bg-white shadow-soft"
              style={{ top: position.top, left: position.left, width: position.width }}
              role="dialog"
              aria-label={t("calendar.chooseTime")}
            >
              <div className="grid grid-cols-[1fr_1.15fr]">
                <div className="max-h-72 overflow-auto border-r border-slate-200 py-2">
                  {Array.from({ length: 24 }, (_, hour) => {
                    const hourValue = formatTimeValue(hour, 0);
                    const active = hour === selectedHour;
                    return (
                      <button
                        key={hour}
                        type="button"
                        onMouseEnter={() => setHoverHour(hour)}
                        onFocus={() => setHoverHour(hour)}
                        onClick={() => {
                          onChange(hourValue);
                          setOpen(false);
                        }}
                        className={clsx(
                          "flex w-full items-center justify-between px-3 py-2 text-left text-sm font-semibold transition",
                          active ? "bg-[color-mix(in_srgb,var(--accent)_10%,white)] text-slate-950" : "text-slate-600 hover:bg-slate-50 hover:text-slate-950"
                        )}
                      >
                        <span>{String(hour).padStart(2, "0")}</span>
                        <span className="text-[11px] font-bold text-slate-400">:00</span>
                      </button>
                    );
                  })}
                </div>
                <div className="max-h-72 overflow-auto py-2">
                  <div className="px-3 pb-2 text-[11px] font-black uppercase tracking-[0.14em] text-slate-400">
                    {String(selectedHour).padStart(2, "0")}:00
                  </div>
                  {quarterOptions.map((minute) => {
                    const nextValue = formatTimeValue(selectedHour, minute);
                    const active = selectedHour === parsedHour && minute === parsedMinute;
                    return (
                      <button
                        key={minute}
                        type="button"
                        onClick={() => {
                          onChange(nextValue);
                          setOpen(false);
                        }}
                        className={clsx(
                          "flex w-full items-center justify-between px-3 py-2 text-left text-sm font-semibold transition",
                          active ? "bg-[color-mix(in_srgb,var(--accent)_10%,white)] text-slate-950" : "text-slate-600 hover:bg-slate-50 hover:text-slate-950"
                        )}
                      >
                        <span>{nextValue}</span>
                        <span className="text-[11px] font-bold text-slate-400">{minute}m</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>,
            document.body
          )
        : null}
    </>
  );
}

function parseTimeHour(value: string) {
  const match = /^(\d{2}):(\d{2})$/.exec((value || "").trim());
  if (!match) return 9;
  const hour = Number.parseInt(match[1], 10);
  return Number.isFinite(hour) && hour >= 0 && hour <= 23 ? hour : 9;
}

function parseTimeMinute(value: string) {
  const match = /^(\d{2}):(\d{2})$/.exec((value || "").trim());
  if (!match) return 0;
  const minute = Number.parseInt(match[2], 10);
  return Number.isFinite(minute) && minute >= 0 && minute <= 59 ? minute : 0;
}

function formatTimeValue(hour: number, minute: number) {
  return `${String(Math.max(0, Math.min(23, hour))).padStart(2, "0")}:${String(Math.max(0, Math.min(59, minute))).padStart(2, "0")}`;
}

function isValidEmailAddress(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

function defaultCalendarEventDraft(date: Date): CalendarEventDraft {
  const base = startOfDay(date);
  const now = new Date();
  const roundedStart = roundUpToHalfHour(now);
  const startHour = new Date(base.getFullYear(), base.getMonth(), base.getDate(), roundedStart.getHours(), roundedStart.getMinutes(), 0);
  const endHour = new Date(startHour.getTime() + 30 * 60 * 1000);
  return {
    summary: "",
    allDay: false,
    startDate: isoDate(base),
    endDate: isoDate(base),
    startTime: timeInputValue(startHour),
    endTime: timeInputValue(endHour),
    location: "",
    description: "",
    attendees: "",
    repeatPattern: "none",
    repeatInterval: "1",
    repeatEndMode: "never",
    repeatUntil: "",
    repeatOccurrences: "1",
    reminderMinutes: "0",
  };
}

function draftFromCalendarEvent(event: CalendarEvent, fallbackDate: Date): CalendarEventDraft {
  const attendees = Array.isArray(event.attendees) ? event.attendees.filter(Boolean).join(", ") : "";
  if (event.all_day) {
    const start = event.start ? parseIsoDate(event.start) : fallbackDate;
    const rawEnd = event.end ? parseIsoDate(event.end) : start;
    const inclusiveEnd = addDays(rawEnd, -1);
    return {
      summary: event.summary,
      allDay: true,
      startDate: isoDate(start),
      endDate: isoDate(inclusiveEnd.getTime() >= start.getTime() ? inclusiveEnd : start),
      startTime: "09:00",
      endTime: "10:00",
      location: event.location || "",
      description: normalizeCalendarPlainText(event.description || ""),
      attendees,
      repeatPattern: event.repeat_pattern || "none",
      repeatInterval: String(Math.max(1, event.repeat_interval || 1)),
      repeatEndMode: event.repeat_end_mode || "never",
      repeatUntil: event.repeat_until || "",
      repeatOccurrences: String(Math.max(1, event.repeat_occurrences || 1)),
      reminderMinutes: String(Math.max(0, event.reminder_minutes || 0)),
    };
  }
  const zone = event.time_zone || DEFAULT_TIME_ZONE;
  const start = calendarEventStart(event);
  const end = calendarEventEnd(event);
  return {
    summary: event.summary,
    allDay: false,
    startDate: Number.isNaN(start.getTime()) ? isoDate(fallbackDate) : eventDatePart(start, zone),
    endDate: Number.isNaN(end.getTime()) ? isoDate(fallbackDate) : eventDatePart(end, zone),
    startTime: Number.isNaN(start.getTime()) ? "09:00" : eventTimePart(start, zone),
    endTime: Number.isNaN(end.getTime()) ? "10:00" : eventTimePart(end, zone),
    location: event.location || "",
    description: normalizeCalendarPlainText(event.description || ""),
    attendees,
    repeatPattern: event.repeat_pattern || "none",
    repeatInterval: String(Math.max(1, event.repeat_interval || 1)),
    repeatEndMode: event.repeat_end_mode || "never",
    repeatUntil: event.repeat_until || "",
    repeatOccurrences: String(Math.max(1, event.repeat_occurrences || 1)),
    reminderMinutes: String(Math.max(0, event.reminder_minutes || 0)),
  };
}

function eventDatePart(date: Date, timeZone: string) {
  return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(date);
}

function eventTimePart(date: Date, timeZone: string) {
  return new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit", hour12: false }).format(date);
}

function roundUpToHalfHour(date: Date) {
  const copy = new Date(date);
  copy.setSeconds(0, 0);
  const minutes = copy.getMinutes();
  const remainder = minutes % 30;
  if (remainder === 0) return copy;
  copy.setMinutes(minutes + (30 - remainder));
  return copy;
}

function timeInputValue(date: Date) {
  return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}

function timeZoneOffsetSuffix(date: string, time: string, timeZone: string) {
  try {
    const instant = new Date(`${date}T${time}:00Z`);
    const formatter = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset", hour: "2-digit", minute: "2-digit", hour12: false });
    const part = formatter.formatToParts(instant).find((item) => item.type === "timeZoneName")?.value || "GMT+00:00";
    return part.replace("GMT", "");
  } catch {
    return "";
  }
}

function combineCalendarDateTime(date: string, time: string, timeZone: string) {
  return `${date}T${time}:00${timeZoneOffsetSuffix(date, time, timeZone)}`;
}

function resolveComposerCalendarId(selectedCalendarId: string, calendars: CalendarSource[], editingEvent: CalendarEvent | null) {
  if (editingEvent?.calendar_id) return editingEvent.calendar_id;
  if (selectedCalendarId && selectedCalendarId !== "__all__") return selectedCalendarId;
  const primary = calendars.find((item) => item.primary)?.id;
  return primary || "primary";
}

function buildCalendarEventPayload(draft: CalendarEventDraft, calendarId: string, timeZone: string) {
  const attendees = parseAttendeeList(draft.attendees);
  const repeatInterval = Number.parseInt(draft.repeatInterval, 10);
  const repeatOccurrences = Number.parseInt(draft.repeatOccurrences, 10);
  const reminderMinutes = Number.parseInt(draft.reminderMinutes, 10);
  const allDay = draft.allDay;
  const start = allDay ? draft.startDate : combineCalendarDateTime(draft.startDate, draft.startTime, timeZone);
  const end = allDay
    ? isoDate(addDays(parseIsoDate(draft.endDate), 1))
    : combineCalendarDateTime(draft.endDate, draft.endTime, timeZone);
  return {
    calendar_id: calendarId || "primary",
    summary: draft.summary.trim(),
    start,
    end,
    time_zone: timeZone || DEFAULT_TIME_ZONE,
    all_day: allDay,
    location: draft.location.trim(),
    description: draft.description.trim(),
    attendees,
    repeat_pattern: draft.repeatPattern,
    repeat_interval: Number.isFinite(repeatInterval) && repeatInterval > 0 ? repeatInterval : 1,
    repeat_end_mode: draft.repeatPattern === "none" ? "never" : draft.repeatEndMode,
    repeat_until: draft.repeatPattern === "none" ? "" : draft.repeatUntil,
    repeat_occurrences: Number.isFinite(repeatOccurrences) && repeatOccurrences > 0 ? repeatOccurrences : 1,
    reminder_minutes: Number.isFinite(reminderMinutes) && reminderMinutes > 0 ? reminderMinutes : 0,
  };
}

function describeRepeatPattern(pattern: CalendarEventDraft["repeatPattern"], interval: number) {
  const step = Math.max(1, Number.isFinite(interval) ? interval : 1);
  const prefix = step === 1 ? "every" : `every ${step}`;
  switch (pattern) {
    case "daily":
      return `${prefix} ${step === 1 ? "day" : "days"}`;
    case "weekly":
      return `${prefix} ${step === 1 ? "week" : "weeks"}`;
    case "monthly":
      return `${prefix} ${step === 1 ? "month" : "months"}`;
    case "yearly":
      return `${prefix} ${step === 1 ? "year" : "years"}`;
    default:
      return "does not repeat";
  }
}

function describeRepeatEndMode(mode: CalendarEventDraft["repeatEndMode"], until: string, occurrences: number) {
  switch (mode) {
    case "on_date":
      return until ? `until ${until}` : "until a date";
    case "after_occurrences":
      return `after ${Math.max(1, Number.isFinite(occurrences) ? occurrences : 1)} occurrences`;
    default:
      return "never ends";
  }
}

function describeReminderMinutes(minutes: number) {
  const value = Math.max(0, minutes);
  if (!value) return "no reminder";
  if (value % 1440 === 0) return value === 1440 ? "1 day" : `${value / 1440} days`;
  if (value % 60 === 0) return value === 60 ? "1 hour" : `${value / 60} hours`;
  return `${value} minutes`;
}
