import { useT } from "@agent-native/core/client/i18n";
import { ShareButton } from "@agent-native/core/client/sharing";
import {
  BookingLinkCreateDialog,
  CustomFieldsEditor as SharedCustomFieldsEditor,
  SlugEditor,
} from "@agent-native/scheduling/react/components";
import { VisibilityBadge } from "@agent-native/toolkit/sharing";
import type {
  AvailabilityConfig,
  BookingHost,
  BookingLink,
  ConferencingConfig,
  CustomField,
  DaySchedule,
} from "@shared/api";
import {
  IconBrandGoogle,
  IconBrandZoom,
  IconCalendar,
  IconChevronLeft,
  IconChevronRight,
  IconCircleCheck,
  IconCopy,
  IconExternalLink,
  IconLink,
  IconDotsVertical,
  IconPlus,
  IconTrash,
  IconUsers,
  IconVideo,
  IconVideoOff,
  IconX,
} from "@tabler/icons-react";
import {
  startOfMonth,
  endOfMonth,
  startOfWeek,
  endOfWeek,
  eachDayOfInterval,
  isSameMonth,
  isToday,
  isBefore,
  addDays,
  addMonths,
  subMonths,
  format,
  startOfDay,
  getDay,
} from "date-fns";
import { nanoid } from "nanoid";
import { useEffect, useMemo, useRef, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { toast } from "sonner";

import { CloudUpgrade } from "@/components/CloudUpgrade";
import { useAppHeaderControls } from "@/components/layout/AppLayout";
import { TimezoneCombobox } from "@/components/TimezoneCombobox";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  useAvailability,
  useUpdateAvailability,
} from "@/hooks/use-availability";
import {
  useBookingLinks,
  useCreateBookingLink,
  useDeleteBookingLink,
  useUpdateBookingLink,
  OPTIMISTIC_PREFIX,
} from "@/hooks/use-booking-links";
import { useGoogleAuthStatus } from "@/hooks/use-google-auth";
import { useZoomStatus, useConnectZoom } from "@/hooks/use-zoom-auth";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";

import BookingsList from "./BookingsList";

const DURATION_PRESETS = [15, 30, 45, 60];

function slugify(value: string) {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

const PRODUCTION_DOMAIN = "calendar.agent-native.com";
const PREVIEW_COLLAPSED_STORAGE_KEY = "calendar.bookingLinks.previewCollapsed";
const BRAND_LINK_CLASS = "font-semibold text-[#00B5FF] hover:text-[#33C4FF]";
const BRAND_ICON_LINK_CLASS =
  "text-[#00B5FF] hover:bg-[#00B5FF]/10 hover:text-[#33C4FF]";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const BOOKING_SLOT_STEP_MINUTES = 30;

type DraftLink = {
  id?: string;
  title: string;
  slug: string;
  description: string;
  duration: number;
  durations: number[];
  hosts: BookingHost[];
  customFields: CustomField[];
  conferencing: ConferencingConfig;
  isActive: boolean;
  /** Whether the user has manually edited the slug (vs auto-generated) */
  slugManuallyEdited: boolean;
};

type DayName = keyof AvailabilityConfig["weeklySchedule"];

type BookingPreviewStep = "duration" | "date" | "time" | "info" | "confirmed";

type BookingPreviewFormValue = {
  name: string;
  email: string;
  notes: string;
  fieldResponses: Record<string, string | boolean>;
};

const DAYS: { key: DayName }[] = [
  { key: "monday" },
  { key: "tuesday" },
  { key: "wednesday" },
  { key: "thursday" },
  { key: "friday" },
  { key: "saturday" },
  { key: "sunday" },
];

const DEFAULT_SCHEDULE: DaySchedule = {
  enabled: false,
  slots: [{ start: "09:00", end: "17:00" }],
};

type Tab = "links" | "availability" | "bookings";

function createEmptyDraft(): DraftLink {
  return {
    title: "",
    slug: "",
    description: "",
    duration: 30,
    durations: [30],
    hosts: [],
    customFields: [],
    conferencing: { type: "none" },
    isActive: true,
    slugManuallyEdited: false,
  };
}

function draftFromBookingLink(link: BookingLink): DraftLink {
  const durations =
    link.durations && link.durations.length > 0
      ? link.durations
      : [link.duration];
  const primaryDuration = durations[0] ?? link.duration;

  return {
    id: link.id,
    title: link.title,
    slug: link.slug,
    description: link.description || "",
    duration: primaryDuration,
    durations,
    hosts: link.hosts || [],
    customFields: link.customFields || [],
    conferencing: link.conferencing || { type: "none" },
    isActive: link.isActive,
    // Always lock the slug for saved links — changing a saved URL would
    // break existing shared links. Users can still edit the slug manually.
    slugManuallyEdited: true,
  };
}

function getDraftSignature(draft: DraftLink) {
  return JSON.stringify({
    title: draft.title.trim(),
    slug: slugify(draft.slug),
    description: draft.description.trim(),
    duration: draft.duration,
    durations: draft.durations,
    hosts: draft.hosts,
    customFields: draft.customFields,
    conferencing: draft.conferencing,
    isActive: draft.isActive,
  });
}

function normalizeHostEmail(value: string) {
  const email = value.trim().toLowerCase();
  return EMAIL_RE.test(email) ? email : null;
}

/** Format "09:00" → "9 am", "17:00" → "5 pm" */
function formatTime12(time: string) {
  const [h, m] = time.split(":").map(Number);
  const suffix = h >= 12 ? "pm" : "am";
  const hour = h % 12 || 12;
  return m
    ? `${hour}:${String(m).padStart(2, "0")} ${suffix}`
    : `${hour} ${suffix}`;
}

/** Summarize availability, e.g. "Weekdays, 9 am - 5 pm" */
function formatAvailabilitySummary(
  config: AvailabilityConfig,
  t: ReturnType<typeof useT>,
) {
  const ws = config.weeklySchedule;
  const weekdayKeys: DayName[] = [
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
  ];
  const weekendKeys: DayName[] = ["saturday", "sunday"];
  const allDays: DayName[] = [...weekdayKeys, ...weekendKeys];

  const enabledDays = allDays.filter((d) => ws[d].enabled);
  if (enabledDays.length === 0) return t("bookingLinks.noAvailabilitySet");

  // Determine day label
  const weekdaysOn = weekdayKeys.every((d) => ws[d].enabled);
  const weekendsOn = weekendKeys.every((d) => ws[d].enabled);
  const weekdaysOff = weekdayKeys.every((d) => !ws[d].enabled);
  const weekendsOff = weekendKeys.every((d) => !ws[d].enabled);

  let dayLabel: string;
  if (weekdaysOn && weekendsOn) dayLabel = t("bookingLinks.everyDay");
  else if (weekdaysOn && weekendsOff) dayLabel = t("bookingLinks.weekdays");
  else if (weekdaysOff && weekendsOn) dayLabel = t("bookingLinks.weekends");
  else {
    const shortNames: Record<DayName, string> = {
      monday: t("bookingLinks.days.mondayShort"),
      tuesday: t("bookingLinks.days.tuesdayShort"),
      wednesday: t("bookingLinks.days.wednesdayShort"),
      thursday: t("bookingLinks.days.thursdayShort"),
      friday: t("bookingLinks.days.fridayShort"),
      saturday: t("bookingLinks.days.saturdayShort"),
      sunday: t("bookingLinks.days.sundayShort"),
    };
    dayLabel = enabledDays.map((d) => shortNames[d]).join(", ");
  }

  // Find common time range
  const slot = ws[enabledDays[0]].slots[0];
  if (!slot) return dayLabel;

  return `${dayLabel}, ${formatTime12(slot.start)} - ${formatTime12(slot.end)}`;
}

function BookingLinksListSkeleton() {
  const t = useT();
  return (
    <div
      className="space-y-3"
      aria-label={t("bookingLinks.loadingMeetingTypes")}
    >
      {Array.from({ length: 4 }).map((_, index) => (
        <div
          key={index}
          className="rounded-lg border border-border bg-card px-4 py-4 sm:px-5"
        >
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
            <div className="min-w-0 flex-1 space-y-2">
              <div className="flex items-center gap-2">
                <Skeleton className="h-4 w-32" />
                <Skeleton className="h-4 w-16 rounded-full" />
              </div>
              <Skeleton className="h-3 w-44" />
              <Skeleton className="h-3 w-36" />
            </div>
            <div className="flex shrink-0 items-center gap-2">
              <Skeleton className="h-9 w-28 rounded-full" />
              <Skeleton className="h-9 w-9 rounded-full" />
              <Skeleton className="h-9 w-9 rounded-full" />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

type ProviderStatus = "connected" | "disconnected" | "not-configured";

const CONFERENCING_OPTIONS = [
  {
    type: "none",
    labelKey: "bookingLinks.noConferencing",
    descriptionKey: "bookingLinks.noConferencingDescription",
    Icon: IconVideoOff,
  },
  {
    type: "google_meet",
    labelKey: "bookingLinks.googleMeet",
    descriptionKey: "bookingLinks.googleMeetDescription",
    Icon: IconBrandGoogle,
  },
  {
    type: "zoom",
    labelKey: "bookingLinks.zoom",
    descriptionKey: "bookingLinks.zoomDescription",
    Icon: IconBrandZoom,
  },
  {
    type: "custom",
    labelKey: "bookingLinks.customLink",
    descriptionKey: "bookingLinks.customLinkDescription",
    Icon: IconLink,
  },
] satisfies Array<{
  type: ConferencingConfig["type"];
  labelKey: string;
  descriptionKey: string;
  Icon: typeof IconVideo;
}>;

function BookingConferencingSelect({
  value,
  onChange,
  zoomStatus,
  googleStatus,
  onConnectZoom,
  zoomPending,
}: {
  value: ConferencingConfig;
  onChange: (next: ConferencingConfig) => void;
  zoomStatus: ProviderStatus;
  googleStatus: ProviderStatus;
  onConnectZoom: () => void;
  zoomPending: boolean;
}) {
  const t = useT();
  const selected =
    CONFERENCING_OPTIONS.find((option) => option.type === value.type) ??
    CONFERENCING_OPTIONS[0];
  const SelectedIcon = selected.Icon;
  return (
    <div className="space-y-3">
      <Label className="flex items-center gap-1.5">
        <IconVideo className="h-4 w-4" />
        {t("bookingLinks.conferencing")}
      </Label>
      <Select
        value={value.type}
        onValueChange={(type) =>
          onChange({
            type: type as ConferencingConfig["type"],
            url: type === "custom" ? value.url : undefined,
          })
        }
      >
        <SelectTrigger className="h-11 py-2">
          <div className="flex min-w-0 items-center gap-2 text-left">
            <SelectedIcon className="h-4 w-4 shrink-0" />
            <span className="truncate font-medium">{t(selected.labelKey)}</span>
          </div>
        </SelectTrigger>
        <SelectContent>
          {CONFERENCING_OPTIONS.map((option) => {
            const status =
              option.type === "zoom"
                ? zoomStatus
                : option.type === "google_meet"
                  ? googleStatus
                  : "connected";
            return (
              <SelectItem
                key={option.type}
                value={option.type}
                className="py-2"
              >
                <div className="flex min-w-0 items-start gap-2">
                  <option.Icon className="mt-0.5 h-4 w-4 shrink-0" />
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{t(option.labelKey)}</span>
                      {status === "connected" &&
                        option.type !== "none" &&
                        option.type !== "custom" && (
                          <span className="text-[10px] text-muted-foreground">
                            {t("common.connected")}
                          </span>
                        )}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t(option.descriptionKey)}
                    </p>
                  </div>
                </div>
              </SelectItem>
            );
          })}
        </SelectContent>
      </Select>

      {value.type === "zoom" && zoomStatus !== "connected" && (
        <div className="rounded-lg border border-border/70 bg-muted/25 p-3">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium">
                {t("bookingLinks.connectZoom")}
              </p>
              <p className="text-xs text-muted-foreground">
                {zoomStatus === "not-configured"
                  ? t("bookingLinks.zoomMissingCredentials")
                  : t("bookingLinks.zoomConnectAccount")}
              </p>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={onConnectZoom}
              disabled={zoomPending}
              className="gap-1.5"
            >
              <IconBrandZoom className="h-4 w-4" />
              {zoomPending
                ? t("common.connecting")
                : t("bookingLinks.connectZoom")}
            </Button>
          </div>
        </div>
      )}

      {value.type === "custom" && (
        <div className="space-y-1.5">
          <Label htmlFor="booking-link-meeting-url" className="text-xs">
            {t("bookingLinks.meetingUrl")}
          </Label>
          <Input
            id="booking-link-meeting-url"
            type="url"
            value={value.url ?? ""}
            onChange={(e) =>
              onChange({ type: "custom", url: e.currentTarget.value })
            }
            placeholder="https://meet.example.com/room"
          />
        </div>
      )}
    </div>
  );
}

function BookingHostsEditor({
  hosts,
  onChange,
}: {
  hosts: BookingHost[];
  onChange: (hosts: BookingHost[]) => void;
}) {
  const t = useT();
  const [input, setInput] = useState("");

  function addHosts() {
    const entries = input
      .split(/[\s,;]+/)
      .map((entry) => entry.trim())
      .filter(Boolean);
    if (entries.length === 0) return;

    const existing = new Set(hosts.map((host) => host.email.toLowerCase()));
    const next = [...hosts];
    const invalid: string[] = [];

    for (const entry of entries) {
      const email = normalizeHostEmail(entry);
      if (!email) {
        invalid.push(entry);
        continue;
      }
      if (existing.has(email)) continue;
      existing.add(email);
      next.push({ email });
    }

    if (invalid.length > 0) {
      toast.error(t("bookingLinks.invalidEmail", { email: invalid[0] }));
    }
    if (next.length !== hosts.length) {
      onChange(next);
      setInput("");
    }
  }

  function removeHost(email: string) {
    onChange(hosts.filter((host) => host.email !== email));
  }

  return (
    <div className="space-y-3">
      <div className="space-y-1">
        <Label className="flex items-center gap-1.5">
          <IconUsers className="h-4 w-4" />
          {t("bookingLinks.requiredHosts")}
        </Label>
        <p className="text-xs text-muted-foreground">
          {t("bookingLinks.requiredHostsDescription")}
        </p>
      </div>
      <div className="flex gap-2">
        <Input
          type="email"
          value={input}
          onChange={(event) => setInput(event.currentTarget.value)}
          onKeyDown={(event) => {
            if (event.key === "Enter") {
              event.preventDefault();
              addHosts();
            }
          }}
          placeholder="teammate@example.com"
        />
        <Button
          type="button"
          variant="outline"
          onClick={addHosts}
          disabled={!input.trim()}
          className="shrink-0"
        >
          {t("bookingLinks.add")}
        </Button>
      </div>
      {hosts.length > 0 ? (
        <div className="flex flex-wrap gap-2">
          {hosts.map((host) => (
            <Badge
              key={host.email}
              variant="secondary"
              className="gap-1.5 pr-1"
            >
              {host.displayName || host.email}
              <button
                type="button"
                onClick={() => removeHost(host.email)}
                className="rounded-sm p-0.5 text-muted-foreground hover:bg-background hover:text-foreground"
                aria-label={t("bookingLinks.removeHost", {
                  email: host.email,
                })}
              >
                <IconX className="h-3 w-3" />
              </button>
            </Badge>
          ))}
        </div>
      ) : (
        <p className="text-xs text-muted-foreground">
          {t("bookingLinks.onlyYouRequired")}
        </p>
      )}
    </div>
  );
}

export default function BookingLinksPage({
  selectedId = null,
}: {
  selectedId?: string | null;
}) {
  const t = useT();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const initialTab = (searchParams.get("tab") as Tab) || "links";
  const bookingLinksQuery = useBookingLinks();
  const {
    data: bookingLinks = [],
    isLoading,
    isError: bookingLinksError,
    isFetching: bookingLinksFetching,
    refetch: refetchBookingLinks,
  } = bookingLinksQuery;
  const createBookingLink = useCreateBookingLink();
  const updateBookingLink = useUpdateBookingLink();
  const deleteBookingLink = useDeleteBookingLink();
  const [activeTab, setActiveTab] = useState<Tab>(initialTab);
  const [draft, setDraft] = useState<DraftLink>(() => createEmptyDraft());
  const [savedDraftSignature, setSavedDraftSignature] = useState<string | null>(
    null,
  );
  const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(() => {
    if (typeof window === "undefined") return false;
    return (
      window.localStorage.getItem(PREVIEW_COLLAPSED_STORAGE_KEY) === "true"
    );
  });
  const [customDurationInput, setCustomDurationInput] = useState("");
  const [showCustomDurationInput, setShowCustomDurationInput] = useState(false);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

  // Availability state
  const { data: availability } = useAvailability();
  const updateAvailability = useUpdateAvailability();
  const [schedule, setSchedule] = useState<
    AvailabilityConfig["weeklySchedule"]
  >({
    monday: { ...DEFAULT_SCHEDULE, enabled: true },
    tuesday: { ...DEFAULT_SCHEDULE, enabled: true },
    wednesday: { ...DEFAULT_SCHEDULE, enabled: true },
    thursday: { ...DEFAULT_SCHEDULE, enabled: true },
    friday: { ...DEFAULT_SCHEDULE, enabled: true },
    saturday: { ...DEFAULT_SCHEDULE },
    sunday: { ...DEFAULT_SCHEDULE },
  });
  const [bufferMinutes, setBufferMinutes] = useState(15);
  const [minNoticeHours, setMinNoticeHours] = useState(1);
  const [maxAdvanceDays, setMaxAdvanceDays] = useState(60);
  const [slotDuration, setSlotDuration] = useState(30);
  const [bookingSlug, setBookingSlug] = useState("meeting");
  const [timezone, setTimezone] = useState("America/New_York");
  const [usernameInput, setUsernameInput] = useState("");
  const [showCloudUpgrade, setShowCloudUpgrade] = useState(false);
  const googleStatus = useGoogleAuthStatus();
  const zoomStatus = useZoomStatus();
  const connectZoom = useConnectZoom();

  // Derive a default username from the Google email (e.g. "steve" from "steve@builder.io")
  const suggestedUsername = useMemo(() => {
    const email = googleStatus.data?.accounts?.[0]?.email;
    if (!email) return "";
    const local = email.split("@")[0];
    // Convert "sewell.steve" → "sewell-steve"
    return local.replace(/[^a-z0-9]/gi, "-").toLowerCase();
  }, [googleStatus.data]);

  useEffect(() => {
    if (availability) {
      setSchedule(availability.weeklySchedule);
      setBufferMinutes(availability.bufferMinutes);
      setMinNoticeHours(availability.minNoticeHours);
      setMaxAdvanceDays(availability.maxAdvanceDays);
      setSlotDuration(availability.slotDurationMinutes);
      setBookingSlug(availability.bookingPageSlug);
      setTimezone(availability.timezone);
      setUsernameInput(availability.bookingUsername ?? "");
    }
  }, [availability]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem(
      PREVIEW_COLLAPSED_STORAGE_KEY,
      String(isPreviewCollapsed),
    );
  }, [isPreviewCollapsed]);

  function updateDay(day: DayName, updates: Partial<DaySchedule>) {
    setSchedule((prev) => ({
      ...prev,
      [day]: { ...prev[day], ...updates },
    }));
  }

  function updateDaySlot(day: DayName, field: "start" | "end", value: string) {
    setSchedule((prev) => ({
      ...prev,
      [day]: {
        ...prev[day],
        slots: [{ ...prev[day].slots[0], [field]: value }],
      },
    }));
  }

  function handleSaveAvailability() {
    updateAvailability.mutate(
      {
        timezone,
        weeklySchedule: schedule,
        bufferMinutes,
        minNoticeHours,
        maxAdvanceDays,
        slotDurationMinutes: slotDuration,
        bookingPageSlug: bookingSlug,
        bookingUsername: usernameInput.trim() || undefined,
      },
      {
        onSuccess: () => toast.success(t("bookingLinks.availabilitySaved")),
        onError: (error) =>
          toast.error(
            error instanceof Error
              ? error.message
              : t("bookingLinks.availabilitySaveFailed"),
          ),
      },
    );
  }

  // Navigate back to list if the selected link was deleted
  useEffect(() => {
    if (
      selectedId &&
      !isLoading &&
      !bookingLinks.some((link) => link.id === selectedId)
    ) {
      navigate("/booking-links", { replace: true });
    }
  }, [bookingLinks, selectedId, isLoading, navigate]);

  const selectedLink = useMemo(
    () => bookingLinks.find((link) => link.id === selectedId) ?? null,
    [bookingLinks, selectedId],
  );

  useEffect(() => {
    if (!selectedLink) {
      setDraft(createEmptyDraft());
      setSavedDraftSignature(null);
      return;
    }

    const nextDraft = draftFromBookingLink(selectedLink);
    setDraft(nextDraft);
    setSavedDraftSignature(getDraftSignature(nextDraft));
    setCustomDurationInput("");
    setShowCustomDurationInput(false);
  }, [selectedLink?.id, selectedLink?.updatedAt]);

  const bookingUsername = availability?.bookingUsername;

  function getBookingUrl(slug: string) {
    if (bookingUsername) {
      const host =
        typeof window !== "undefined" &&
        window.location.hostname !== "localhost"
          ? window.location.origin
          : `https://${PRODUCTION_DOMAIN}`;
      return `${host}/book/${bookingUsername}/${slug}`;
    }
    // Fallback for no username set
    if (typeof window === "undefined") return `/book/${slug}`;
    return `${window.location.origin}/book/${slug}`;
  }

  const previewUrl = getBookingUrl(draft.slug);
  const createSlugPrefix = useMemo(() => {
    const host =
      typeof window !== "undefined" && window.location.hostname !== "localhost"
        ? window.location.host
        : PRODUCTION_DOMAIN;
    const username =
      bookingUsername || usernameInput || suggestedUsername || "your-name";
    return `${host}/book/${username}/`;
  }, [bookingUsername, usernameInput, suggestedUsername]);
  const draftSignature = useMemo(() => getDraftSignature(draft), [draft]);
  const hasUnsavedChanges =
    !!selectedLink &&
    savedDraftSignature !== null &&
    draftSignature !== savedDraftSignature;

  function handleCreate() {
    setCreateDialogOpen(true);
  }

  function handleCreateSubmit(input: {
    title: string;
    slug: string;
    length: number;
    description: string;
  }) {
    const title = input.title.trim();
    const slug = slugify(input.slug);
    const duration = input.length;
    if (!title || !slug || !Number.isFinite(duration)) return;
    if (duration < 5) {
      toast.error(t("bookingLinks.durationMinError"));
      return;
    }
    // Pre-generate an optimistic id so we can navigate instantly; the mutation
    // inserts the row into the list cache synchronously via onMutate.
    const optimisticId = `optimistic_${nanoid()}`;
    createBookingLink.mutate(
      {
        title,
        slug,
        duration,
        description: input.description.trim() || undefined,
        isActive: true,
        optimisticId,
      },
      {
        onSuccess: (created) => {
          // Swap URL from optimistic id to the real one without a back-stack entry.
          navigate(`/booking-links/${created.id}`, { replace: true });
          toast.success(t("bookingLinks.bookingLinkCreated"));
        },
        onError: (error) => {
          // Cache was rolled back by the hook's onError. Bring the user back.
          navigate("/booking-links", { replace: true });
          toast.error(
            error instanceof Error
              ? error.message
              : t("bookingLinks.bookingLinkCreateFailed"),
          );
        },
      },
    );
    // Navigate *immediately* — the optimistic row is already in the list cache.
    navigate(`/booking-links/${optimisticId}`);
    setCreateDialogOpen(false);
  }

  async function handleSave() {
    if (!draft.id) return;
    if (!hasUnsavedChanges) return;
    // Optimistic row hasn't resolved to a real ID yet — wait for it
    if (draft.id.startsWith(OPTIMISTIC_PREFIX)) {
      toast.error(t("bookingLinks.stillCreating"));
      return;
    }
    try {
      const updated = await updateBookingLink.mutateAsync({
        id: draft.id,
        title: draft.title.trim(),
        slug: slugify(draft.slug),
        description: draft.description.trim() || undefined,
        duration: draft.durations[0] ?? draft.duration,
        durations: draft.durations.length > 1 ? draft.durations : undefined,
        hosts: draft.hosts.length > 0 ? draft.hosts : undefined,
        customFields:
          draft.customFields.length > 0 ? draft.customFields : undefined,
        conferencing: draft.conferencing,
        isActive: draft.isActive,
      });
      const nextDraft = draftFromBookingLink(updated);
      setDraft(nextDraft);
      setSavedDraftSignature(getDraftSignature(nextDraft));
      toast.success(t("bookingLinks.bookingLinkUpdated"));
    } catch {
      toast.error(t("bookingLinks.bookingLinkUpdateFailed"));
    }
  }

  async function handleDelete() {
    if (!draft.id) return;
    try {
      await deleteBookingLink.mutateAsync(draft.id);
      navigate("/booking-links");
      toast.success(t("bookingLinks.bookingLinkDeleted"));
    } catch {
      toast.error(t("bookingLinks.bookingLinkDeleteFailed"));
    }
  }

  function addCustomDuration() {
    const minutes = Number.parseInt(customDurationInput, 10);
    if (!Number.isFinite(minutes) || minutes < 5 || minutes > 480) {
      toast.error(t("bookingLinks.durationRangeError"));
      return;
    }
    setDraft((prev) => {
      const next = Array.from(new Set([...prev.durations, minutes])).sort(
        (a, b) => a - b,
      );
      return { ...prev, durations: next, duration: next[0] };
    });
    setCustomDurationInput("");
    setShowCustomDurationInput(false);
  }

  async function copyPreviewUrl(slug: string) {
    if (await copyTextToClipboard(getBookingUrl(slug))) {
      toast.success(t("bookingLinks.bookingLinkCopied"));
      return;
    }
    toast.error(t("common.clipboardUnavailable"));
  }

  function bookingPreviewPath(slug: string) {
    return bookingUsername
      ? `/book/${bookingUsername}/${slug}`
      : `/book/${slug}`;
  }

  const handleSaveRef = useRef(handleSave);
  useEffect(() => {
    handleSaveRef.current = handleSave;
  });

  const detailHeaderControls = useMemo(() => {
    if (!selectedId) {
      return {
        left: (
          <h1 className="text-lg font-semibold tracking-tight truncate">
            {t("bookingLinks.title")}
          </h1>
        ),
        right:
          activeTab === "links" ? (
            <Button
              type="button"
              size="sm"
              onClick={handleCreate}
              className="h-8 gap-2"
            >
              <IconPlus className="h-4 w-4" />
              {t("bookingLinks.newBookingLink")}
            </Button>
          ) : null,
      };
    }
    return {
      left: (
        <Link
          to="/booking-links"
          className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
        >
          <IconChevronLeft className="h-4 w-4" />
          {t("bookingLinks.back")}
        </Link>
      ),
      right: selectedLink ? (
        <div className="flex items-center gap-1.5">
          {!selectedLink.id.startsWith(OPTIMISTIC_PREFIX) && (
            <ShareButton
              resourceType="booking-link"
              resourceId={selectedLink.id}
              resourceTitle={draft.title || selectedLink.title}
              variant="compact"
              shareUrl={previewUrl}
              shareUrlLabel={t("bookingLinks.publicBookingLink")}
              shareUrlDescription={t("bookingLinks.shareUrlDescription")}
              shareUrlPlacement="top"
              peopleAccessLabel={t("bookingLinks.peopleAccess")}
              generalAccessLabel={t("bookingLinks.generalAccess")}
              visibilityCopy={{
                private: {
                  description: t("bookingLinks.privateAccessDescription"),
                },
                org: {
                  description: t("bookingLinks.orgAccessDescription"),
                },
                public: {
                  label: t("bookingLinks.publicManagementAccess"),
                  description: t("bookingLinks.publicAccessDescription"),
                },
              }}
            />
          )}
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={() => void copyPreviewUrl(draft.slug)}
                  className={cn("h-8 w-8", BRAND_ICON_LINK_CLASS)}
                  aria-label={t("bookingLinks.copyBookingLink")}
                >
                  <IconCopy className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>{t("bookingLinks.copyLink")}</TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  asChild
                  variant="ghost"
                  size="icon"
                  className={cn("h-8 w-8", BRAND_ICON_LINK_CLASS)}
                  aria-label={t("bookingLinks.openBookingLink")}
                >
                  <a
                    href={bookingPreviewPath(draft.slug)}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <IconExternalLink className="h-4 w-4" />
                  </a>
                </Button>
              </TooltipTrigger>
              <TooltipContent>{t("bookingLinks.openLink")}</TooltipContent>
            </Tooltip>
          </TooltipProvider>
          <Button
            type="button"
            size="sm"
            onClick={() => void handleSaveRef.current()}
            disabled={updateBookingLink.isPending || !hasUnsavedChanges}
            className="h-8 px-3"
          >
            {updateBookingLink.isPending
              ? t("common.saving")
              : hasUnsavedChanges
                ? t("eventDialog.saveChanges")
                : t("bookingLinks.saved")}
          </Button>
        </div>
      ) : null,
    };
  }, [
    selectedId,
    selectedLink,
    draft.title,
    draft.slug,
    previewUrl,
    updateBookingLink.isPending,
    hasUnsavedChanges,
    navigate,
    activeTab,
    t,
  ]);
  useAppHeaderControls(detailHeaderControls);

  const hasLinks = bookingLinks.length > 0;

  // If a link is selected, show the detail/edit view
  if (selectedId) {
    if (bookingLinksError && !isLoading) {
      return (
        <div className="flex min-h-[50vh] flex-col items-center justify-center gap-3 px-6 text-center">
          <p className="text-sm text-destructive">{t("common.loadFailed")}</p>
          <Button
            size="sm"
            variant="outline"
            onClick={() => void refetchBookingLinks()}
            disabled={bookingLinksFetching}
          >
            {t("common.retry")}
          </Button>
        </div>
      );
    }
    return (
      <div className="mx-auto max-w-6xl space-y-6 px-4 py-5 sm:p-6">
        {/* Two-column layout: form left, preview right */}
        <div
          className={cn(
            "grid gap-6",
            isPreviewCollapsed
              ? "lg:grid-cols-[minmax(0,1fr)_auto]"
              : "lg:grid-cols-2",
          )}
        >
          {/* Left — Edit form */}
          <div
            className={cn(
              "space-y-8",
              isPreviewCollapsed && "mx-auto w-full max-w-4xl",
            )}
          >
            {isLoading ? (
              <div className="space-y-5">
                <div className="space-y-2">
                  <Skeleton className="h-4 w-28" />
                  <Skeleton className="h-10 w-full" />
                </div>
                <div className="space-y-2">
                  <Skeleton className="h-4 w-32" />
                  <Skeleton className="h-16 w-full" />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-2">
                    <Skeleton className="h-4 w-20" />
                    <Skeleton className="h-10 w-full" />
                  </div>
                  <div className="space-y-2">
                    <Skeleton className="h-4 w-20" />
                    <Skeleton className="h-10 w-full" />
                  </div>
                </div>
                <div className="space-y-2">
                  <Skeleton className="h-4 w-24" />
                  <Skeleton className="h-10 w-full" />
                </div>
              </div>
            ) : selectedLink ? (
              <>
                {/* Title */}
                <div className="space-y-2">
                  <Label htmlFor="booking-link-title">
                    {t("bookingLinks.meetingName")}
                  </Label>
                  <Input
                    id="booking-link-title"
                    value={draft.title}
                    onChange={(e) => {
                      const title = e.target.value;
                      setDraft((prev) => ({
                        ...prev,
                        title,
                        slug: prev.slugManuallyEdited
                          ? prev.slug
                          : slugify(title),
                      }));
                    }}
                    placeholder={t("bookingLinks.quickChat")}
                  />
                </div>

                {/* Description */}
                <div className="space-y-2">
                  <Label htmlFor="booking-link-description">
                    {t("eventForm.description")}{" "}
                    <span className="text-muted-foreground font-normal">
                      {t("bookingLinks.optional")}
                    </span>
                  </Label>
                  <Textarea
                    id="booking-link-description"
                    rows={2}
                    value={draft.description}
                    onChange={(e) =>
                      setDraft((prev) => ({
                        ...prev,
                        description: e.target.value,
                      }))
                    }
                    placeholder={t("bookingLinks.shownOnBookingPage")}
                  />
                </div>

                {/* Duration options — multi-select */}
                <div className="space-y-3">
                  <Label>{t("bookingLinks.durationOptions")}</Label>
                  <p className="text-xs text-muted-foreground">
                    {t("bookingLinks.durationOptionsDescription")}
                  </p>
                  <div className="flex flex-wrap gap-2">
                    {DURATION_PRESETS.map((minutes) => {
                      const isSelected = draft.durations.includes(minutes);
                      return (
                        <button
                          key={minutes}
                          type="button"
                          onClick={() =>
                            setDraft((prev) => {
                              const next = isSelected
                                ? prev.durations.filter((d) => d !== minutes)
                                : [...prev.durations, minutes].sort(
                                    (a, b) => a - b,
                                  );
                              // Must keep at least one
                              if (next.length === 0) return prev;
                              return {
                                ...prev,
                                durations: next,
                                duration: next[0],
                              };
                            })
                          }
                          className={cn(
                            "rounded-full border px-3 py-1.5 text-sm",
                            isSelected
                              ? "border-primary bg-primary/10 text-primary"
                              : "border-border text-muted-foreground hover:text-foreground hover:bg-accent/60",
                          )}
                        >
                          {minutes} min
                        </button>
                      );
                    })}
                    {draft.durations
                      .filter((minutes) => !DURATION_PRESETS.includes(minutes))
                      .map((minutes) => {
                        const isSelected = draft.durations.includes(minutes);
                        return (
                          <button
                            key={minutes}
                            type="button"
                            onClick={() =>
                              setDraft((prev) => {
                                if (prev.durations.length === 1) return prev;
                                const next = prev.durations.filter(
                                  (d) => d !== minutes,
                                );
                                return {
                                  ...prev,
                                  durations: next,
                                  duration: next[0],
                                };
                              })
                            }
                            className={cn(
                              "rounded-full border px-3 py-1.5 text-sm",
                              isSelected
                                ? "border-primary bg-primary/10 text-primary"
                                : "border-border text-muted-foreground hover:bg-accent/60 hover:text-foreground",
                            )}
                          >
                            {minutes} min
                          </button>
                        );
                      })}
                    <button
                      type="button"
                      onClick={() =>
                        setShowCustomDurationInput((visible) => !visible)
                      }
                      className={cn(
                        "inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-sm",
                        showCustomDurationInput
                          ? "border-primary bg-primary/10 text-primary"
                          : "border-border border-dashed text-muted-foreground hover:bg-accent/60 hover:text-foreground",
                      )}
                    >
                      <IconPlus className="h-3.5 w-3.5" />
                      {t("bookingLinks.custom")}
                    </button>
                  </div>
                  {showCustomDurationInput && (
                    <div className="flex max-w-xs items-center gap-2">
                      <Input
                        type="number"
                        min={5}
                        max={480}
                        step={5}
                        autoFocus
                        value={customDurationInput}
                        onChange={(e) => setCustomDurationInput(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            addCustomDuration();
                          }
                          if (e.key === "Escape") {
                            setShowCustomDurationInput(false);
                          }
                        }}
                        placeholder={t("bookingLinks.minutes")}
                        className="h-9"
                      />
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={addCustomDuration}
                        disabled={!customDurationInput.trim()}
                        className="shrink-0"
                      >
                        {t("bookingLinks.add")}
                      </Button>
                    </div>
                  )}
                  {draft.durations.length > 1 && (
                    <p className="text-xs text-muted-foreground">
                      {t("bookingLinks.bookersChooseBetween", {
                        durations: draft.durations
                          .map((d) =>
                            t("bookingLinks.minutesShort", { count: d }),
                          )
                          .join(", "),
                      })}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <div className="flex items-center justify-between gap-3">
                    <Label>{t("bookingLinks.url")}</Label>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          asChild
                          variant="ghost"
                          size="icon"
                          className={cn("h-8 w-8", BRAND_ICON_LINK_CLASS)}
                          aria-label={t("bookingLinks.openBookingPageNewTab")}
                        >
                          <a
                            href={bookingPreviewPath(draft.slug)}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            <IconExternalLink className="h-4 w-4" />
                          </a>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        {t("bookingLinks.openInNewTab")}
                      </TooltipContent>
                    </Tooltip>
                  </div>
                  {/* Editable URL parts (username / slug) — shared package component */}
                  <SlugEditor
                    hideLabel
                    host={
                      typeof window !== "undefined" &&
                      window.location.hostname !== "localhost"
                        ? window.location.host
                        : PRODUCTION_DOMAIN
                    }
                    pathPrefix="/book"
                    username={
                      bookingUsername ||
                      usernameInput ||
                      suggestedUsername ||
                      ""
                    }
                    slug={draft.slug}
                    onUsernameChange={(val) => {
                      setUsernameInput(val);
                      if (val) {
                        updateAvailability.mutate(
                          {
                            timezone,
                            weeklySchedule: schedule,
                            bufferMinutes,
                            minNoticeHours,
                            maxAdvanceDays,
                            slotDurationMinutes: slotDuration,
                            bookingPageSlug: bookingSlug,
                            bookingUsername: val,
                          },
                          {
                            onError: (error) =>
                              toast.error(
                                error instanceof Error
                                  ? error.message
                                  : t(
                                      "bookingLinks.bookingUsernameUpdateFailed",
                                    ),
                              ),
                          },
                        );
                      }
                    }}
                    onSlugChange={(val) => {
                      setDraft((prev) => ({
                        ...prev,
                        slug: val,
                        slugManuallyEdited: true,
                      }));
                    }}
                  />
                </div>

                {/* Conferencing — Zoom uses real OAuth */}
                <BookingConferencingSelect
                  value={draft.conferencing}
                  onChange={(conferencing) =>
                    setDraft((prev) => ({ ...prev, conferencing }))
                  }
                  zoomStatus={
                    zoomStatus.data?.connected
                      ? "connected"
                      : zoomStatus.data?.configured === false
                        ? "not-configured"
                        : "disconnected"
                  }
                  googleStatus={
                    googleStatus.data?.connected ? "connected" : "disconnected"
                  }
                  onConnectZoom={() =>
                    connectZoom.mutate(undefined, {
                      onError: (error) =>
                        toast.error(
                          error instanceof Error
                            ? error.message
                            : t("bookingLinks.zoomStartFailed"),
                        ),
                    })
                  }
                  zoomPending={connectZoom.isPending}
                />

                <BookingHostsEditor
                  hosts={draft.hosts}
                  onChange={(hosts) => setDraft((prev) => ({ ...prev, hosts }))}
                />

                {/* Custom fields editor — shared package component */}
                <SharedCustomFieldsEditor
                  fields={draft.customFields}
                  onChange={(fields) =>
                    setDraft((prev) => ({ ...prev, customFields: fields }))
                  }
                />

                {/* Lower-risk settings */}
                <div className="space-y-5 border-t border-border pt-5">
                  <div className="flex items-center justify-between gap-4">
                    <div>
                      <p className="text-sm font-medium">
                        {t("bookingLinks.linkVisibility")}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {t("bookingLinks.linkVisibilityDescription")}
                      </p>
                    </div>
                    <Switch
                      checked={draft.isActive}
                      onCheckedChange={(checked) =>
                        setDraft((prev) => ({ ...prev, isActive: checked }))
                      }
                    />
                  </div>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <button
                        type="button"
                        className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-destructive"
                      >
                        <IconTrash className="h-3.5 w-3.5" />
                        {t("eventForm.delete")}
                      </button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>
                          {t("bookingLinks.deleteBookingLink")}
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                          {t("bookingLinks.deleteDescriptionPrefix")}{" "}
                          <span className="font-medium text-foreground">
                            {draft.title}
                          </span>{" "}
                          {t("bookingLinks.deleteDescriptionSuffix")}
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>
                          {t("eventForm.cancel")}
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={handleDelete}>
                          {t("eventForm.delete")}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </>
            ) : null}
          </div>

          {/* Right — Live booking page preview */}
          {selectedLink && (
            <div className="lg:sticky lg:top-8 lg:self-start">
              {isPreviewCollapsed ? (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <button
                        type="button"
                        onClick={() => setIsPreviewCollapsed(false)}
                        className="flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/50 hover:text-foreground"
                        aria-label={t("bookingLinks.openPreview")}
                      >
                        <IconChevronLeft className="h-4 w-4" />
                      </button>
                    </TooltipTrigger>
                    <TooltipContent side="left">
                      {t("bookingLinks.openPreview")}
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              ) : (
                <BookingPreview
                  title={draft.title}
                  description={draft.description}
                  durations={draft.durations}
                  hosts={draft.hosts}
                  customFields={draft.customFields}
                  isActive={draft.isActive}
                  availability={availability ?? undefined}
                  bookingUrl={previewUrl}
                  onCopy={() => void copyPreviewUrl(draft.slug)}
                  openHref={bookingPreviewPath(draft.slug)}
                  onCollapse={() => setIsPreviewCollapsed(true)}
                />
              )}
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto w-full max-w-5xl space-y-6 px-4 py-8">
      <p className="text-sm text-muted-foreground">
        {t("bookingLinks.description")}
      </p>

      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as Tab)}>
        <TabsList>
          <TabsTrigger value="links">
            {t("bookingLinks.meetingTypes")}
          </TabsTrigger>
          <TabsTrigger value="availability">
            {t("bookingLinks.availability")}
          </TabsTrigger>
          <TabsTrigger value="bookings">
            {t("bookingLinks.bookings")}
          </TabsTrigger>
        </TabsList>

        <TabsContent value="links">
          <div className="space-y-6">
            {isLoading ? (
              <BookingLinksListSkeleton />
            ) : bookingLinksError ? (
              <div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-destructive/30 px-6 py-16 text-center">
                <p className="text-sm text-destructive">
                  {t("common.loadFailed")}
                </p>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => void refetchBookingLinks()}
                  disabled={bookingLinksFetching}
                >
                  {t("common.retry")}
                </Button>
              </div>
            ) : !hasLinks ? (
              <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-border py-16 px-6 text-center">
                <div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted mb-4">
                  <IconLink className="h-6 w-6 text-muted-foreground" />
                </div>
                <p className="text-lg font-medium">
                  {t("bookingLinks.noBookingLinks")}
                </p>
                <p className="mt-1 max-w-sm text-sm text-muted-foreground">
                  {t("bookingLinks.noBookingLinksDescription")}
                </p>
                <Button onClick={handleCreate} className="mt-6 gap-2">
                  <IconPlus className="h-4 w-4" />
                  {t("bookingLinks.createFirstLink")}
                </Button>
              </div>
            ) : (
              <div className="space-y-3">
                {bookingLinks.map((link) => {
                  const durations =
                    link.durations && link.durations.length > 0
                      ? link.durations
                      : [link.duration];
                  const durationLabel = durations
                    .map((d) =>
                      d >= 60
                        ? t("bookingLinks.hoursShort", { count: d / 60 })
                        : t("bookingLinks.minutesShort", { count: d }),
                    )
                    .join(", ");
                  const hostCount = (link.hosts?.length ?? 0) + 1;
                  const hostLabel =
                    hostCount > 1
                      ? t("bookingLinks.requiredHostsCount", {
                          count: hostCount,
                        })
                      : t("bookingLinks.oneOnOne");

                  return (
                    <div
                      key={link.id}
                      className={cn(
                        "rounded-lg border text-left hover:bg-accent/40 cursor-pointer",
                        link.isActive
                          ? "border-border bg-card"
                          : "border-transparent bg-muted/60",
                      )}
                    >
                      <div className="flex flex-col gap-3 px-4 py-4 sm:flex-row sm:items-center sm:gap-4 sm:px-5">
                        {/* Info — clickable to edit */}
                        <Link
                          to={`/booking-links/${link.id}`}
                          className="min-w-0 flex-1 text-left"
                        >
                          <div className="flex items-center gap-2">
                            <p
                              className={cn(
                                "text-sm font-semibold truncate",
                                !link.isActive && "text-muted-foreground",
                              )}
                            >
                              {link.title}
                            </p>
                            <VisibilityBadge visibility={link.visibility} />
                          </div>
                          <p className="mt-0.5 text-xs text-muted-foreground truncate">
                            {durationLabel} • {hostLabel}
                          </p>
                          {availability && (
                            <p className="mt-0.5 text-xs text-muted-foreground truncate">
                              {formatAvailabilitySummary(availability, t)} •{" "}
                              {availability.timezone}
                            </p>
                          )}
                        </Link>

                        {/* Actions */}
                        <div className="flex shrink-0 items-center gap-2">
                          {link.isActive && (
                            <>
                              <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  void copyPreviewUrl(link.slug);
                                }}
                                className="rounded-full"
                              >
                                <IconLink className="h-3.5 w-3.5" />
                                {t("bookingLinks.copyLink")}
                              </Button>
                              <Button
                                asChild
                                variant="outline"
                                size="icon"
                                className="h-9 w-9 rounded-full"
                                aria-label={t("bookingLinks.openBookingLink")}
                              >
                                <a
                                  href={bookingPreviewPath(link.slug)}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                >
                                  <IconExternalLink className="h-4 w-4" />
                                </a>
                              </Button>
                            </>
                          )}

                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <button
                                type="button"
                                onClick={(e) => e.stopPropagation()}
                                className="flex h-9 w-9 items-center justify-center rounded-full border border-border text-muted-foreground hover:text-foreground hover:bg-accent/60"
                              >
                                <IconDotsVertical className="h-4 w-4" />
                              </button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem asChild>
                                <Link to={`/booking-links/${link.id}`}>
                                  {t("eventForm.edit")}
                                </Link>
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={() => {
                                  updateBookingLink.mutate(
                                    {
                                      id: link.id,
                                      title: link.title,
                                      slug: link.slug,
                                      duration: durations[0] ?? link.duration,
                                      durations: link.durations,
                                      hosts: link.hosts,
                                      description: link.description,
                                      customFields: link.customFields,
                                      conferencing: link.conferencing,
                                      color: link.color,
                                      isActive: !link.isActive,
                                    },
                                    {
                                      onSuccess: () =>
                                        toast.success(
                                          t(
                                            link.isActive
                                              ? "bookingLinks.linkDisabled"
                                              : "bookingLinks.linkEnabled",
                                            { title: link.title },
                                          ),
                                        ),
                                    },
                                  );
                                }}
                              >
                                {link.isActive
                                  ? t("bookingLinks.disable")
                                  : t("bookingLinks.enable")}
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </TabsContent>

        <TabsContent value="availability">
          <div className="mx-auto max-w-2xl space-y-6">
            {/* Weekly Schedule */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">
                  {t("bookingLinks.weeklySchedule")}
                </CardTitle>
                <CardDescription>
                  {t("bookingLinks.weeklyScheduleDescription")}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2 rounded-lg border border-border bg-muted/20 p-3">
                  <Label htmlFor="booking-links-availability-timezone">
                    {t("eventForm.timezone")}
                  </Label>
                  <TimezoneCombobox
                    id="booking-links-availability-timezone"
                    value={timezone}
                    onChange={setTimezone}
                  />
                  <p className="text-xs text-muted-foreground">
                    {t("bookingLinks.timezoneHelp")}
                  </p>
                </div>
                {DAYS.map(({ key }) => {
                  const day = schedule[key];
                  const slot = day.slots[0] ?? { start: "09:00", end: "17:00" };
                  const label = t(`bookingLinks.days.${key}`);
                  const short = t(`bookingLinks.days.${key}Short`);
                  return (
                    <div
                      key={key}
                      className="flex flex-wrap items-center gap-3 rounded-lg border border-border px-3 py-3 sm:gap-4 sm:px-4"
                    >
                      <div className="flex items-center gap-3 w-28 sm:w-40">
                        <Switch
                          checked={day.enabled}
                          onCheckedChange={(checked) =>
                            updateDay(key, { enabled: checked })
                          }
                        />
                        <span className="text-sm font-medium">
                          <span className="hidden sm:inline">{label}</span>
                          <span className="sm:hidden">{short}</span>
                        </span>
                      </div>

                      {day.enabled ? (
                        <div className="flex items-center gap-2">
                          <Input
                            type="time"
                            value={slot.start}
                            onChange={(e) =>
                              updateDaySlot(key, "start", e.target.value)
                            }
                            className="w-28 sm:w-32"
                          />
                          <span className="text-muted-foreground">
                            {t("bookingLinks.to")}
                          </span>
                          <Input
                            type="time"
                            value={slot.end}
                            onChange={(e) =>
                              updateDaySlot(key, "end", e.target.value)
                            }
                            className="w-28 sm:w-32"
                          />
                        </div>
                      ) : (
                        <span className="text-sm text-muted-foreground">
                          {t("bookingLinks.unavailable")}
                        </span>
                      )}
                    </div>
                  );
                })}
              </CardContent>
            </Card>

            {/* Booking Rules */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">
                  {t("bookingLinks.bookingRules")}
                </CardTitle>
                <CardDescription>
                  {t("bookingLinks.bookingRulesDescription")}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div className="space-y-2">
                    <Label>{t("bookingLinks.bufferBetweenEvents")}</Label>
                    <Input
                      type="number"
                      value={bufferMinutes}
                      onChange={(e) => setBufferMinutes(Number(e.target.value))}
                      min={0}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t("bookingLinks.minimumNotice")}</Label>
                    <Input
                      type="number"
                      value={minNoticeHours}
                      onChange={(e) =>
                        setMinNoticeHours(Number(e.target.value))
                      }
                      min={0}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t("bookingLinks.maxAdvanceBooking")}</Label>
                    <Input
                      type="number"
                      value={maxAdvanceDays}
                      onChange={(e) =>
                        setMaxAdvanceDays(Number(e.target.value))
                      }
                      min={1}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t("bookingLinks.slotDuration")}</Label>
                    <Input
                      type="number"
                      value={slotDuration}
                      onChange={(e) => setSlotDuration(Number(e.target.value))}
                      min={5}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>{t("bookingLinks.bookingUsername")}</Label>
                  <p className="text-xs text-muted-foreground">
                    {t("bookingLinks.bookingUsernameHelp")} {PRODUCTION_DOMAIN}
                    /book/
                    <strong>{usernameInput || "your-name"}</strong>/meeting-slug
                  </p>
                  <Input
                    value={usernameInput}
                    onChange={(e) =>
                      setUsernameInput(
                        e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""),
                      )
                    }
                    placeholder="your-name"
                  />
                </div>
              </CardContent>
            </Card>

            <Button
              onClick={handleSaveAvailability}
              disabled={updateAvailability.isPending}
              className="w-full"
            >
              {updateAvailability.isPending
                ? t("common.saving")
                : t("bookingLinks.saveAvailability")}
            </Button>
          </div>
        </TabsContent>

        <TabsContent value="bookings">
          <BookingsList />
        </TabsContent>
      </Tabs>

      {showCloudUpgrade && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <CloudUpgrade
            title={t("bookingLinks.shareBookingLink")}
            description={t("bookingLinks.cloudUpgradeDescription")}
            onClose={() => setShowCloudUpgrade(false)}
          />
        </div>
      )}
      <BookingLinkCreateDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
        slugPrefix={createSlugPrefix}
        defaultLength={30}
        submitLabel={t("bookingLinks.createLink")}
        onSubmit={handleCreateSubmit}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Inline booking page preview — mirrors BookingPage layout, updates live
// ---------------------------------------------------------------------------

const WEEKDAY_HEADER_KEYS = [
  "sundayShort",
  "mondayShort",
  "tuesdayShort",
  "wednesdayShort",
  "thursdayShort",
  "fridayShort",
  "saturdayShort",
] as const;
const DAY_MAP: Record<number, DayName> = {
  0: "sunday",
  1: "monday",
  2: "tuesday",
  3: "wednesday",
  4: "thursday",
  5: "friday",
  6: "saturday",
};

function BookingPreview({
  title,
  description,
  durations,
  hosts = [],
  customFields = [],
  isActive,
  availability,
  bookingUrl,
  onCopy,
  openHref,
  onCollapse,
}: {
  title: string;
  description: string;
  durations: number[];
  hosts?: BookingHost[];
  customFields?: CustomField[];
  isActive: boolean;
  availability?: AvailabilityConfig;
  bookingUrl?: string;
  onCopy?: () => void;
  openHref?: string;
  onCollapse?: () => void;
}) {
  const t = useT();
  const displayTitle = title.trim() || t("bookingLinks.untitledMeeting");
  const hasDurationChoice = durations.length > 1;
  const primaryDuration = durations[0] ?? 30;

  const today = startOfDay(new Date());
  const maxDate = addDays(today, availability?.maxAdvanceDays ?? 60);

  // Interactive state
  const [viewMonth, setViewMonth] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [selectedDuration, setSelectedDuration] = useState<number | null>(null);
  const [selectedSlot, setSelectedSlot] = useState<string | null>(null);
  const [previewConfirmed, setPreviewConfirmed] = useState(false);
  const [previewForm, setPreviewForm] = useState<BookingPreviewFormValue>({
    name: t("bookingLinks.previewGuest"),
    email: "preview@example.com",
    notes: "",
    fieldResponses: {},
  });

  // Reset selections when durations change
  useEffect(() => {
    setSelectedDuration(null);
    setSelectedSlot(null);
    setPreviewConfirmed(false);
  }, [durations.join(",")]);

  useEffect(() => {
    setPreviewConfirmed(false);
  }, [selectedDate, selectedDuration, selectedSlot]);

  // Calendar data for viewed month
  const monthStart = startOfMonth(viewMonth);
  const monthEnd = endOfMonth(viewMonth);
  const calStart = startOfWeek(monthStart);
  const calEnd = endOfWeek(monthEnd);
  const calDays = eachDayOfInterval({ start: calStart, end: calEnd });

  function isDayDisabled(day: Date) {
    if (isBefore(day, today)) return true;
    if (isBefore(maxDate, day)) return true;
    if (availability) {
      const dayName = DAY_MAP[getDay(day)];
      if (!availability.weeklySchedule[dayName]?.enabled) return true;
    }
    return false;
  }

  // Generate realistic time slots based on availability
  const timeSlots = useMemo(() => {
    if (!selectedDate || !availability) {
      return ["9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM"];
    }
    const dayName = DAY_MAP[getDay(selectedDate)];
    const daySchedule = availability.weeklySchedule[dayName];
    if (!daySchedule?.enabled) return [];
    const slot = daySchedule.slots[0];
    if (!slot) return [];

    const dur = selectedDuration ?? primaryDuration;
    const [startH, startM] = slot.start.split(":").map(Number);
    const [endH, endM] = slot.end.split(":").map(Number);
    const startMin = startH * 60 + startM;
    const endMin = endH * 60 + endM;
    const slots: string[] = [];
    const firstStart =
      Math.ceil(startMin / BOOKING_SLOT_STEP_MINUTES) *
      BOOKING_SLOT_STEP_MINUTES;
    for (
      let m = firstStart;
      m + dur <= endMin;
      m += BOOKING_SLOT_STEP_MINUTES
    ) {
      const h = Math.floor(m / 60);
      const mm = m % 60;
      const ampm = h >= 12 ? "PM" : "AM";
      const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h;
      slots.push(`${h12}:${mm.toString().padStart(2, "0")} ${ampm}`);
    }
    return slots;
  }, [selectedDate, selectedDuration, primaryDuration, availability]);

  // Determine which step to show
  const [forcedStep, setForcedStep] = useState<BookingPreviewStep | null>(null);

  let naturalStep: BookingPreviewStep = "date";
  if (hasDurationChoice && selectedDuration === null) naturalStep = "duration";
  else if (!selectedDate) naturalStep = "date";
  else if (!selectedSlot) naturalStep = "time";
  else naturalStep = "info";

  const step: BookingPreviewStep = previewConfirmed
    ? "confirmed"
    : (forcedStep ?? naturalStep);

  const steps: BookingPreviewStep[] = hasDurationChoice
    ? ["duration", "date", "time", "info"]
    : ["date", "time", "info"];

  const confirmedDuration = selectedDuration ?? primaryDuration;

  function updatePreviewForm(patch: Partial<BookingPreviewFormValue>) {
    setPreviewForm((prev) => ({ ...prev, ...patch }));
  }

  function setPreviewFieldValue(id: string, value: string | boolean) {
    setPreviewForm((prev) => ({
      ...prev,
      fieldResponses: { ...prev.fieldResponses, [id]: value },
    }));
  }

  function handlePreviewSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setPreviewConfirmed(true);
    setForcedStep(null);
  }

  function resetPreviewFlow() {
    setSelectedDuration(null);
    setSelectedDate(null);
    setSelectedSlot(null);
    setPreviewConfirmed(false);
    setForcedStep(null);
  }

  return (
    <div className="rounded-2xl border border-border overflow-hidden bg-card">
      {/* Preview header bar */}
      <div className="border-b border-border/60 bg-muted/30 px-4 py-2 space-y-2">
        <div className="flex items-center justify-between">
          <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
            {t("bookingLinks.preview")}
          </span>
          <div className="flex items-center gap-1">
            {!isActive && (
              <Badge variant="secondary" className="text-[10px]">
                {t("bookingLinks.hidden")}
              </Badge>
            )}
            {onCollapse && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    onClick={onCollapse}
                    className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-accent/60"
                  >
                    <IconChevronRight className="h-3.5 w-3.5" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>
                  {t("bookingLinks.collapsePreview")}
                </TooltipContent>
              </Tooltip>
            )}
            {onCopy && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    onClick={onCopy}
                    className={cn(
                      "flex h-6 w-6 items-center justify-center rounded",
                      BRAND_ICON_LINK_CLASS,
                    )}
                  >
                    <IconCopy className="h-3.5 w-3.5" />
                  </button>
                </TooltipTrigger>
                <TooltipContent>{t("bookingLinks.copyLink")}</TooltipContent>
              </Tooltip>
            )}
            {openHref && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <a
                    href={openHref}
                    target="_blank"
                    rel="noopener noreferrer"
                    className={cn(
                      "flex h-6 w-6 items-center justify-center rounded",
                      BRAND_ICON_LINK_CLASS,
                    )}
                  >
                    <IconExternalLink className="h-3.5 w-3.5" />
                  </a>
                </TooltipTrigger>
                <TooltipContent>
                  {t("bookingLinks.openInteractiveBookingLink")}
                </TooltipContent>
              </Tooltip>
            )}
          </div>
        </div>
        {bookingUrl && (
          <p className="text-[11px] font-mono font-semibold text-[#00B5FF] truncate">
            {bookingUrl.replace(/^https?:\/\//, "")}
          </p>
        )}
      </div>

      {/* Booking page preview */}
      <div className={cn("space-y-5 p-6", !isActive && "opacity-60")}>
        {/* Header */}
        <div className="text-center space-y-2">
          <div className="mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
            <IconCalendar className="h-5 w-5 text-primary" />
          </div>
          <h3 className="text-lg font-semibold leading-tight">
            {displayTitle}
          </h3>
          {description.trim() && (
            <p className="text-xs text-muted-foreground leading-relaxed max-w-xs mx-auto">
              {description}
            </p>
          )}
          {(!hasDurationChoice || hosts.length > 0) && (
            <div className="flex flex-wrap justify-center gap-2">
              {!hasDurationChoice && (
                <span className="inline-flex rounded-full border border-border px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
                  {t("bookingLinks.minuteMeeting", {
                    count: primaryDuration,
                  })}
                </span>
              )}
              {hosts.length > 0 && (
                <span className="inline-flex rounded-full border border-border px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground">
                  {t("bookingLinks.requiredHostsCount", {
                    count: hosts.length + 1,
                  })}
                </span>
              )}
            </div>
          )}
        </div>

        {/* Step indicators */}
        {step !== "confirmed" && (
          <div className="flex items-center justify-center gap-2">
            {steps.map((s, i) => (
              <div key={s} className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => {
                    if (s === step) return;
                    if (s === "duration") {
                      setSelectedDuration(null);
                      setSelectedDate(null);
                      setSelectedSlot(null);
                      setForcedStep(null);
                    } else if (s === "date") {
                      setSelectedDate(null);
                      setSelectedSlot(null);
                      setForcedStep(null);
                    } else if (s === "time") {
                      setSelectedSlot(null);
                      setForcedStep(null);
                    } else {
                      setForcedStep(s);
                    }
                  }}
                  className={cn(
                    "flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-medium cursor-pointer transition-colors",
                    step === s
                      ? "bg-primary text-primary-foreground"
                      : steps.indexOf(step) > i
                        ? "bg-primary/20 text-primary hover:bg-primary/30"
                        : "bg-muted text-muted-foreground hover:bg-muted/80",
                  )}
                  aria-label={t("bookingLinks.goToPreviewStep", {
                    step: i + 1,
                  })}
                >
                  {i + 1}
                </button>
                {i < steps.length - 1 && <div className="h-px w-6 bg-border" />}
              </div>
            ))}
          </div>
        )}

        {/* Duration step */}
        {step === "duration" && (
          <div className="space-y-2">
            <p className="text-xs font-medium text-center text-muted-foreground">
              {t("bookingLinks.chooseDuration")}
            </p>
            <div className="space-y-1.5">
              {durations.map((mins) => (
                <button
                  key={mins}
                  type="button"
                  onClick={() => {
                    setSelectedDuration(mins);
                    setForcedStep(null);
                  }}
                  className="w-full rounded-lg border border-border px-3 py-2 text-left text-xs font-medium text-muted-foreground hover:bg-accent/60 hover:border-primary/30"
                >
                  {t("bookingLinks.minutesLong", { count: mins })}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Date step */}
        {step === "date" && (
          <div className="space-y-2">
            <p className="text-xs font-medium text-center text-muted-foreground">
              {t("bookingLinks.selectDate")}
            </p>
            <div className="rounded-lg border border-border/60 p-3">
              {/* Month navigation */}
              <div className="flex items-center justify-between mb-2">
                <button
                  type="button"
                  onClick={() => setViewMonth((m) => subMonths(m, 1))}
                  className="p-1 rounded hover:bg-accent/60"
                >
                  <IconChevronLeft className="h-3.5 w-3.5 text-muted-foreground" />
                </button>
                <span className="text-xs font-medium">
                  {format(viewMonth, "MMMM yyyy")}
                </span>
                <button
                  type="button"
                  onClick={() => setViewMonth((m) => addMonths(m, 1))}
                  className="p-1 rounded hover:bg-accent/60"
                >
                  <IconChevronRight className="h-3.5 w-3.5 text-muted-foreground" />
                </button>
              </div>

              {/* Weekday headers */}
              <div className="grid grid-cols-7 mb-0.5">
                {WEEKDAY_HEADER_KEYS.map((dayKey) => (
                  <div
                    key={dayKey}
                    className="py-0.5 text-center text-[10px] font-medium text-muted-foreground/60"
                  >
                    {t(`bookingLinks.days.${dayKey}`)}
                  </div>
                ))}
              </div>

              {/* Days grid */}
              <div className="grid grid-cols-7 gap-px">
                {calDays.map((day) => {
                  const inMonth = isSameMonth(day, viewMonth);
                  const disabled = isDayDisabled(day);
                  const isTodayMark = isToday(day);

                  return (
                    <button
                      key={day.toISOString()}
                      type="button"
                      disabled={!inMonth || disabled}
                      onClick={() => {
                        setSelectedDate(day);
                        setSelectedSlot(null);
                        setForcedStep(null);
                      }}
                      className={cn(
                        "flex h-7 items-center justify-center rounded text-[11px]",
                        !inMonth && "opacity-0 pointer-events-none",
                        inMonth && disabled && "text-muted-foreground/30",
                        inMonth &&
                          !disabled &&
                          "text-muted-foreground cursor-pointer hover:bg-accent/60",
                        isTodayMark &&
                          !disabled &&
                          "border border-primary/40 text-foreground font-medium",
                      )}
                    >
                      {format(day, "d")}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {/* Time step */}
        {step === "time" && (
          <div className="space-y-2">
            {selectedDate && (
              <div className="flex items-center justify-between">
                <p className="text-xs font-medium text-muted-foreground">
                  {format(selectedDate, "EEEE, MMM d")}
                </p>
                <button
                  type="button"
                  onClick={() => {
                    setSelectedDate(null);
                    setSelectedSlot(null);
                    setForcedStep(null);
                  }}
                  className={cn(
                    "text-[11px] hover:underline",
                    BRAND_LINK_CLASS,
                  )}
                >
                  {t("bookingLinks.changeDate")}
                </button>
              </div>
            )}
            {!selectedDate && (
              <p className="text-xs font-medium text-center text-muted-foreground">
                {t("bookingLinks.availableTimes")}
              </p>
            )}
            {timeSlots.length > 0 ? (
              <div className="grid grid-cols-3 gap-1.5">
                {timeSlots.map((slot) => (
                  <button
                    key={slot}
                    type="button"
                    onClick={() => {
                      setSelectedSlot(slot);
                      setForcedStep(null);
                    }}
                    className={cn(
                      "rounded-md border px-2 py-1.5 text-center text-[11px] cursor-pointer",
                      selectedSlot === slot
                        ? "border-primary bg-primary/10 text-primary"
                        : "border-border/60 text-muted-foreground hover:bg-accent/60 hover:border-primary/30",
                    )}
                  >
                    {slot}
                  </button>
                ))}
              </div>
            ) : (
              <p className="text-center text-xs text-muted-foreground py-4">
                {t("bookingLinks.noAvailabilityOnDay")}
              </p>
            )}
          </div>
        )}

        {/* Info step */}
        {step === "info" && (
          <form className="space-y-3" onSubmit={handlePreviewSubmit}>
            {selectedDate && selectedSlot ? (
              <div className="flex items-center justify-between">
                <p className="text-xs font-medium text-muted-foreground">
                  {t("bookingLinks.selectedDateTime", {
                    date: format(selectedDate, "EEEE, MMM d"),
                    time: selectedSlot,
                  })}
                </p>
                <button
                  type="button"
                  onClick={() => {
                    setSelectedSlot(null);
                    setForcedStep(null);
                  }}
                  className={cn(
                    "text-[11px] hover:underline",
                    BRAND_LINK_CLASS,
                  )}
                >
                  {t("bookingLinks.changeTime")}
                </button>
              </div>
            ) : (
              <p className="text-xs font-medium text-center text-muted-foreground">
                {t("bookingLinks.bookingDetails")}
              </p>
            )}
            <div className="space-y-2">
              <div className="space-y-1.5">
                <Label htmlFor="preview-booking-name" className="text-[11px]">
                  {t("bookingLinks.name")}
                </Label>
                <Input
                  id="preview-booking-name"
                  value={previewForm.name}
                  onChange={(event) =>
                    updatePreviewForm({ name: event.target.value })
                  }
                  className="h-8 text-xs"
                  required
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="preview-booking-email" className="text-[11px]">
                  {t("bookingLinks.email")}
                </Label>
                <Input
                  id="preview-booking-email"
                  type="email"
                  value={previewForm.email}
                  onChange={(event) =>
                    updatePreviewForm({ email: event.target.value })
                  }
                  className="h-8 text-xs"
                  required
                />
              </div>
              {customFields.map((field) => (
                <PreviewCustomFieldInput
                  key={field.id}
                  field={field}
                  value={previewForm.fieldResponses[field.id]}
                  onChange={(value) => setPreviewFieldValue(field.id, value)}
                />
              ))}
              <div className="space-y-1.5">
                <Label htmlFor="preview-booking-notes" className="text-[11px]">
                  {t("bookingLinks.notesOptional")}
                </Label>
                <Textarea
                  id="preview-booking-notes"
                  value={previewForm.notes}
                  onChange={(event) =>
                    updatePreviewForm({ notes: event.target.value })
                  }
                  className="min-h-16 text-xs"
                  placeholder={t("bookingLinks.notesPlaceholder")}
                />
              </div>
            </div>
            <Button type="submit" className="h-8 w-full text-xs">
              {t("bookingLinks.confirmBooking")}
            </Button>
          </form>
        )}

        {step === "confirmed" && (
          <div className="flex flex-col items-center py-3 text-center">
            <IconCircleCheck className="h-12 w-12 text-emerald-600 dark:text-emerald-400" />
            <div className="mt-3 space-y-1">
              <h4 className="text-base font-semibold">
                {t("bookingLinks.previewConfirmed")}
              </h4>
              <p className="text-xs text-muted-foreground">
                {t("bookingLinks.noBookingCreated")}
              </p>
            </div>
            <div className="mt-4 w-full rounded-lg border border-border bg-muted/20 p-3 text-left text-xs">
              <div>
                <span className="text-muted-foreground">
                  {t("eventForm.event")}
                </span>
                <p className="font-medium text-foreground">{displayTitle}</p>
              </div>
              {selectedDate && (
                <div className="mt-2">
                  <span className="text-muted-foreground">
                    {t("bookingLinks.date")}
                  </span>
                  <p className="font-medium text-foreground">
                    {format(selectedDate, "EEEE, MMMM d, yyyy")}
                  </p>
                </div>
              )}
              {selectedSlot && (
                <div className="mt-2">
                  <span className="text-muted-foreground">
                    {t("bookingLinks.time")}
                  </span>
                  <p className="font-medium text-foreground">
                    {selectedSlot} ·{" "}
                    {t("bookingLinks.minutesLong", {
                      count: confirmedDuration,
                    })}
                  </p>
                </div>
              )}
              <div className="mt-2">
                <span className="text-muted-foreground">
                  {t("bookingLinks.name")}
                </span>
                <p className="font-medium text-foreground">
                  {previewForm.name.trim() || t("bookingLinks.previewGuest")}
                </p>
              </div>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="mt-4 h-8 text-xs"
              onClick={resetPreviewFlow}
            >
              {t("bookingLinks.tryAgain")}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}

function PreviewCustomFieldInput({
  field,
  value,
  onChange,
}: {
  field: CustomField;
  value: string | boolean | undefined;
  onChange: (value: string | boolean) => void;
}) {
  const t = useT();
  const id = `preview-custom-field-${field.id}`;
  const strValue = typeof value === "string" ? value : "";
  const boolValue = typeof value === "boolean" ? value : false;
  const optionalLabel = field.required ? "" : ` ${t("bookingLinks.optional")}`;

  if (field.type === "checkbox") {
    return (
      <div className="flex items-center gap-2 rounded-md border border-border/60 px-3 py-2">
        <Checkbox
          id={id}
          checked={boolValue}
          onCheckedChange={(checked) => onChange(checked === true)}
        />
        <Label htmlFor={id} className="text-[11px] font-normal">
          {field.label}
          {optionalLabel}
        </Label>
      </div>
    );
  }

  if (field.type === "select" && field.options?.length) {
    return (
      <div className="space-y-1.5">
        <Label htmlFor={id} className="text-[11px]">
          {field.label}
          {optionalLabel}
        </Label>
        <Select value={strValue} onValueChange={onChange}>
          <SelectTrigger id={id} className="h-8 text-xs">
            <span
              className={cn("truncate", !strValue && "text-muted-foreground")}
            >
              {strValue ||
                field.placeholder ||
                t("bookingLinks.selectPlaceholder")}
            </span>
          </SelectTrigger>
          <SelectContent>
            {field.options.map((option) => (
              <SelectItem key={option} value={option}>
                {option}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  }

  if (field.type === "textarea") {
    return (
      <div className="space-y-1.5">
        <Label htmlFor={id} className="text-[11px]">
          {field.label}
          {optionalLabel}
        </Label>
        <Textarea
          id={id}
          value={strValue}
          onChange={(event) => onChange(event.target.value)}
          placeholder={field.placeholder}
          className="min-h-16 text-xs"
        />
      </div>
    );
  }

  return (
    <div className="space-y-1.5">
      <Label htmlFor={id} className="text-[11px]">
        {field.label}
        {optionalLabel}
      </Label>
      <Input
        id={id}
        type={
          field.type === "url"
            ? "url"
            : field.type === "tel"
              ? "tel"
              : field.type === "email"
                ? "email"
                : "text"
        }
        value={strValue}
        onChange={(event) => onChange(event.target.value)}
        placeholder={field.placeholder}
        className="h-8 text-xs"
      />
    </div>
  );
}
