'use client';

import { currentZoneName } from '@/features/settings/ui/accountDefaultsZones';
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react';
import type { CustomSelectOption } from '@/components/crm/CustomSelect';
import { ComposeRichText, htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { ComposerSelect } from '@/components/crm/ComposerSelect';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { DraggablePopup } from '@/components/crm/DraggablePopup';
import { CrmModal, Field, ModalHeader } from '@/components/crm/FormDrawer';
import { MultiCustomSelect } from '@/components/crm/MultiCustomSelect';
import { RecipientChips } from '@/components/crm/RecipientChips';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { useMeetingOptions } from '@/features/meetings/useMeetingOptions';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import type { ActivityLink } from '@/features/activities/api.client';
import { LOGGED_MEETING_TITLE } from '@/features/activities/readable';
import { htmlToText, newIdempotencyKey } from '@/features/inbox/format';
import { logRecordMeeting } from '@/features/objects/record/activityApi';
import {
  connectGoogleCalendar,
  createMeeting,
  getMyCalendar,
  listCalendarEvents,
} from '@/features/meetings/api.client';
import type { CalendarEvent, MyCalendar } from '@/features/meetings/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { isUsable, needsReconnect } from '@/lib/utils/connection';
import { cn } from '@/lib/utils/cn';
import { addDays, dayParts, fromZoned, mondayOf, toZoned, weekdayOf } from '@/lib/utils/timezone';
import { AssociatedRecordsPanel, AssocForPill } from './AssociatedRecordsPanel';
import {
  MAX_NOTE_MEETING_LINKS,
  seedAssociations,
  taskLinksCapped,
  type AssocRecord,
} from './assocTypes';
import { FollowUpTaskControls, followUpDueDate, type FollowUpDueKey } from './FollowUpTaskControls';
import { createTask } from '@/features/tasks/api.client';
import { actionErrorText, timeToHours, useOpenCount } from './shared';
import { snippetTargetFor } from '@/features/snippets/model';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const DOW = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] as const;
const SHORT_MONTH = [
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dec',
];
const H0 = 8;
const H1 = 19;

export type MeetingAttendeeOption = CustomSelectOption;

/** EV22: an attendee option's name: "Ann Lee (ann@x.com)" → "Ann Lee"; an email alone stays. */
export function attendeeName(label: string): string {
  return label.replace(/\s*\([^()]*@[^()]*\)\s*$/, '').trim() || label;
}

/** EV22: the options still on the meeting (`inviteAll`), in their order. */
export function invitedOptions<T extends { value: string }>(
  options: readonly T[],
  dropped: readonly string[],
): T[] {
  return options.filter((o) => !dropped.includes(o.value));
}

/** Design's location types. Video conference is what master calls Google Meet. */
const LOCATION_TYPES = [
  { value: 'Office', label: 'In person' },
  { value: 'Phone', label: 'Phone call' },
  { value: 'Meet', label: 'Video conference' },
  { value: 'Link', label: 'Custom video link' },
];
const VIDEO_LINK_RE = /^https?:\/\/\S+$/i;
/** A meeting lasts at most 7 days (the API's limit), whatever is typed as custom minutes. */
const MAX_CUSTOM_MINUTES = 7 * 24 * 60;
const CUSTOM_DURATION = 'custom';
const MINUTES_PER_SLOT = 15;
const MAX_DURATION_MINUTES = 480;

function durationLabel(minutes: number): string {
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  const hours = h ? `${h} Hour${h > 1 ? 's' : ''}` : '';
  return [hours, m ? `${m} Minutes` : ''].filter(Boolean).join(' ');
}

/** The 15-minute list, plus `current` when it falls between two slots (week grid, user default). */
function slotsWith<T extends { value: string }>(list: T[], current: T): T[] {
  return list.some((o) => o.value === current.value) ? list : [current, ...list];
}
const DURATION_OPTIONS = Array.from({ length: MAX_DURATION_MINUTES / MINUTES_PER_SLOT }, (_, i) => {
  const minutes = (i + 1) * MINUTES_PER_SLOT;
  return { value: String(minutes), label: durationLabel(minutes) };
});
const TIME_OPTIONS = Array.from({ length: 96 }, (_, i) => {
  const value = hoursToTime(i / 4);
  return { value, label: timeLabel(value) };
});
const DESIGN_START_TIME = '10:00';
export { LOGGED_MEETING_TITLE };

function nextSlot(timeZone: string): string {
  const { hours } = toZoned(new Date(), timeZone);
  const next = Math.ceil((hours + 0.01) * 2) / 2;
  if (next >= 23.5) return '09:00';
  const h = Math.floor(next);
  return `${String(h).padStart(2, '0')}:${next % 1 ? '30' : '00'}`;
}

function hoursToTime(hours: number): string {
  const h = Math.floor(hours);
  const m = Math.round((hours - h) * 60);
  return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}

function timeLabel(time: string): string {
  const hours = timeToHours(time) ?? 0;
  const h = Math.floor(hours);
  const m = Math.round((hours - h) * 60);
  return `${h % 12 || 12}:${String(m).padStart(2, '0')} ${h >= 12 ? 'PM' : 'AM'}`;
}

function addMinutesToTime(time: string, minutes: number): string {
  const base = timeToHours(time);
  if (base === null) return time;
  return hoursToTime(Math.min(base + minutes / 60, 23.983));
}

function clockLabel(hours: number): string {
  const h = Math.floor(hours);
  const m = Math.round((hours - h) * 60);
  const ampm = h >= 12 ? 'PM' : 'AM';
  const h12 = h % 12 || 12;
  return m ? `${h12}:${String(m).padStart(2, '0')} ${ampm}` : `${h12} ${ampm}`;
}

function weekRangeLabel(monday: string): string {
  const fri = addDays(monday, 4);
  const a = dayParts(monday);
  const b = dayParts(fri);
  if (a.month === b.month) {
    return `${SHORT_MONTH[a.month]} ${a.date} – ${b.date}, ${a.year}`;
  }
  return `${SHORT_MONTH[a.month]} ${a.date} – ${SHORT_MONTH[b.month]} ${b.date}, ${b.year}`;
}

/** Compact Mon–Fri availability grid for the maximized schedule popup. */
function MeetingWeekPreview({
  timeZone,
  selectedDay,
  selectedStart,
  selectedEnd,
  onPickSlot,
}: {
  timeZone: string;
  selectedDay: string;
  selectedStart: string;
  selectedEnd: string;
  onPickSlot: (day: string, start: string, end: string) => void;
}) {
  const toast = useToast();
  const today = toZoned(new Date(), timeZone).day;
  const [weekOffset, setWeekOffset] = useState(0);
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [loading, setLoading] = useState(false);
  const [hideWeekends] = useState(true);
  const requestId = useRef(0);

  const monday = addDays(mondayOf(selectedDay || today), weekOffset * 7);

  const load = useCallback(
    async (fromDay: string) => {
      const id = ++requestId.current;
      setLoading(true);
      try {
        const res = await listCalendarEvents(
          fromZoned(fromDay, 0, timeZone),
          fromZoned(addDays(fromDay, 7), 0, timeZone),
        );
        if (id === requestId.current) setEvents(res.data);
      } catch (err) {
        if (id === requestId.current) toast(errorText(err), 'danger');
      } finally {
        if (id === requestId.current) setLoading(false);
      }
    },
    [timeZone, toast],
  );

  useEffect(() => {
    setWeekOffset(0);
  }, [selectedDay]);

  useEffect(() => {
    void load(monday);
  }, [monday, load]);

  const items = useMemo(() => {
    return events
      .filter((e) => !e.allDay && e.status !== 'cancelled')
      .map((e) => {
        const s = toZoned(new Date(e.startsAt), timeZone);
        const en = toZoned(new Date(e.endsAt), timeZone);
        return {
          id: e.id,
          title: e.title || 'Busy',
          startDay: s.day,
          startHours: s.hours,
          endHours: en.day !== s.day ? H1 : en.hours,
        };
      })
      .filter((i) => weekdayOf(i.startDay) < 5);
  }, [events, timeZone]);

  const startH = timeToHours(selectedStart) ?? 0;
  const endH = timeToHours(selectedEnd) ?? startH + 0.5;
  const durationMin = Math.max(Math.round((endH - startH) * 60), 15);

  const onColumnClick = (dayIndex: number, e: React.MouseEvent<HTMLDivElement>) => {
    const col = e.currentTarget;
    const rect = col.getBoundingClientRect();
    const y = e.clientY - rect.top;
    const hours = H0 + (y / rect.height) * (H1 - H0);
    const snapped = Math.round(hours * 2) / 2;
    const clamped = Math.min(Math.max(snapped, H0), H1 - 0.25);
    const day = addDays(monday, dayIndex);
    const start = hoursToTime(clamped);
    onPickSlot(day, start, addMinutesToTime(start, durationMin));
  };

  return (
    <div className="meeting-week">
      <div className="meeting-week__toolbar">
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          onClick={() => setWeekOffset(0)}
        >
          Today
        </button>
        <button
          type="button"
          className="icon-btn"
          aria-label="Previous week"
          onClick={() => setWeekOffset((w) => w - 1)}
        >
          <CrmIcon name="chevron-left" className="iconSize-16" />
        </button>
        <span className="meeting-week__range">{weekRangeLabel(monday)}</span>
        <button
          type="button"
          className="icon-btn"
          aria-label="Next week"
          onClick={() => setWeekOffset((w) => w + 1)}
        >
          <CrmIcon name="chevron-right" className="iconSize-16" />
        </button>
        <span className="meeting-week__tz" title={currentZoneName(timeZone)}>
          {hideWeekends ? 'Hide weekends' : ''} · {currentZoneName(timeZone)}
        </span>
      </div>

      <div className="meeting-week__days">
        <span />
        {DOW.map((dow, i) => {
          const day = addDays(monday, i);
          return (
            <div key={dow} className={cn('meeting-week__day', day === today && 'is-today')}>
              <span className="meeting-week__dow">{dow}</span>
              <span className="meeting-week__date">{dayParts(day).date}</span>
            </div>
          );
        })}
      </div>

      <div className="meeting-week__grid">
        <div className="meeting-week__times" aria-hidden>
          {Array.from({ length: H1 - H0 }, (_, i) => (
            <div key={i} className="meeting-week__time">
              {clockLabel(H0 + i)}
            </div>
          ))}
        </div>
        {DOW.map((dow, dayIndex) => {
          const day = addDays(monday, dayIndex);
          return (
            <div
              key={dow}
              className="meeting-week__col"
              onClick={(e) => onColumnClick(dayIndex, e)}
            >
              {items
                .filter((i) => i.startDay === day)
                .map((item) => {
                  const s = Math.max(item.startHours, H0);
                  const en = Math.min(item.endHours, H1);
                  return (
                    <div
                      key={item.id}
                      className="meeting-week__event"
                      style={{
                        top: `calc((100% / ${H1 - H0}) * ${s - H0})`,
                        height: `calc((100% / ${H1 - H0}) * ${Math.max(en - s, 0.25)})`,
                      }}
                      title={item.title}
                    >
                      <strong>{item.title}</strong>
                    </div>
                  );
                })}
              {selectedDay === day ? (
                <div
                  className="meeting-week__draft"
                  style={{
                    top: `calc((100% / ${H1 - H0}) * ${Math.max(startH, H0) - H0})`,
                    height: `calc((100% / ${H1 - H0}) * ${Math.max(Math.min(endH, H1) - Math.max(startH, H0), 0.25)})`,
                  }}
                >
                  New
                </div>
              ) : null}
            </div>
          );
        })}
        {loading ? <p className="meeting-week__empty">Loading…</p> : null}
      </div>
    </div>
  );
}

/**
 * Schedule a meeting in Google Calendar (POST /meetings). Checks calendar connection first;
 * maximize shows the week's synced events beside the form.
 */
export function ScheduleMeetingDrawer({
  open,
  onClose,
  link,
  recordName = '',
  defaultAttendeeEmail,
  attendeeOptions,
  initialAssociations,
  timeZone: timeZoneProp,
  defaultMinutes: defaultMinutesProp,
  /** When false (custom-object record pages), open as log-only and never gate on Calendar. */
  defaultAddToCalendar = true,
  onScheduled,
  composer,
  snippetContactId,
  inviteAll = false,
}: {
  open: boolean;
  onClose: () => void;
  /** The record the meeting is for. Without one (the Meetings page) the picker starts empty. */
  link?: ActivityLink;
  recordName?: string;
  defaultAttendeeEmail?: string | null;
  attendeeOptions?: MeetingAttendeeOption[];
  /** Extra records to pre-check (e.g. contact's companies). */
  initialAssociations?: AssocRecord[];
  /** Default: the user's own zone. */
  timeZone?: string;
  /** Default: the user's meeting length. */
  defaultMinutes?: number;
  defaultAddToCalendar?: boolean;
  /** Gets the new meeting's id when one was saved. */
  onScheduled: (meetingId?: string) => void;
  /** Contacts: the design's floating window. */
  composer?: RefObject<ComposerWindowHandle | null>;
  /** Who stands for the record when a snippet is filled (a company's or deal's contact). */
  snippetContactId?: string;
  /**
   * EV22: the composer's Attendees are every one of `attendeeOptions` (a record's contacts with an
   * email), each removable, as the design's (activity-composer.js:1429, the linked contacts, all
   * selected). Event record pages. Off: the record itself (contact and company pages).
   */
  inviteAll?: boolean;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const prefs = useUserPrefs();
  const timeZone = timeZoneProp ?? prefs.timeZone;
  const defaultMinutes = defaultMinutesProp ?? prefs.meetingMinutes;
  const [calendar, setCalendar] = useState<MyCalendar | null>(null);
  const [meetingKey, setMeetingKey] = useState(newIdempotencyKey);
  const [connecting, setConnecting] = useState(false);
  const [busy, setBusy] = useState(false);
  const [selectedAttendees, setSelectedAttendees] = useState<string[]>([]);
  const [title, setTitle] = useState('');
  const [date, setDate] = useState('');
  const [startTime, setStartTime] = useState('');
  /** The meeting's length, any number of minutes (it may run past midnight). */
  const [minutes, setMinutes] = useState(defaultMinutes);
  const [customLength, setCustomLength] = useState(false);
  const [where, setWhere] = useState('Meet');
  /** Design's free-text Location; empty sends the location type, as master does. */
  const [place, setPlace] = useState('');
  const [guests, setGuests] = useState<string[]>([]);
  const [contactInvited, setContactInvited] = useState(true);
  /** EV22 (`inviteAll`): the attendees taken off this meeting, by email. */
  const [dropped, setDropped] = useState<string[]>([]);
  /** Settings > Meetings: the outcomes, types and reminder every meeting form shows. */
  const options = useMeetingOptions(open);
  const [meetingType, setMeetingType] = useState('');
  const [outcome, setOutcome] = useState('');
  /** M-02: Log meeting's follow-up task, as Log call's (LogCallDrawer `FollowUpTaskControls`). */
  const [followUp, setFollowUp] = useState(false);
  const [followDue, setFollowDue] = useState<FollowUpDueKey>('biz3');
  const [customDueDate, setCustomDueDate] = useState('');
  const [taskType, setTaskType] = useState('todo');
  /** The meeting was logged, and only its follow-up task is left (a retry doesn't log it twice). */
  const logged = useRef(false);
  const savedId = useRef<string | undefined>(undefined);
  const [guestBoxBad, setGuestBoxBad] = useState(false);
  const [description, setDescription] = useState('');
  const [addToCalendar, setAddToCalendar] = useState(defaultAddToCalendar);
  // The design's new meeting starts unnamed; Log meeting has no name field there, so keep ours.
  const defaultTitle =
    (composer && defaultAddToCalendar) || !recordName ? '' : `Meeting with ${recordName}`;
  const primary: AssocRecord | null = useMemo(
    () => (link ? { type: link.type, id: link.id, displayName: recordName } : null),
    [link, recordName],
  );
  const popupId = link?.type ?? 'meeting';
  const seedAssoc = useMemo(
    () => seedAssociations(primary, initialAssociations).slice(0, MAX_NOTE_MEETING_LINKS),
    [primary, initialAssociations],
  );
  const [assoc, setAssoc] = useState<AssocRecord[]>(seedAssoc);
  const [assocOpen, setAssocOpen] = useState(false);
  /** M-22: "Select at least one record…" shows only after a save attempt. */
  const [triedSave, setTriedSave] = useState(false);
  const forPillRef = useRef<HTMLButtonElement>(null);

  const pickerOptions = useMemo(() => {
    const fromProps = (attendeeOptions ?? []).map(({ value, label }) => ({
      value: value.trim().toLowerCase(),
      label,
    }));
    const fallback = defaultAttendeeEmail?.trim().toLowerCase();
    if (
      fallback &&
      EMAIL_RE.test(fallback) &&
      !fromProps.some((o) => o.value === fallback) &&
      !attendeeOptions?.length
    ) {
      fromProps.push({ value: fallback, label: fallback });
    }
    const seen = new Set<string>();
    return fromProps.filter((o) => {
      if (!o.value || seen.has(o.value)) return false;
      seen.add(o.value);
      return true;
    });
  }, [attendeeOptions, defaultAttendeeEmail]);

  const openCount = useOpenCount(open, () => {
    setMeetingKey(newIdempotencyKey());
    setTitle(defaultTitle);
    const today = toZoned(new Date(), timeZone).day;
    // A new meeting starts tomorrow at 10:00 as designed; a logged one has already happened.
    const planned = Boolean(composer) && defaultAddToCalendar;
    const day = planned ? addDays(today, 1) : today;
    const start = planned ? DESIGN_START_TIME : nextSlot(timeZone);
    setDate(day);
    setStartTime(start);
    setMinutes(defaultMinutes);
    setCustomLength(false);
    setWhere('Meet');
    setPlace('');
    setGuests([]);
    setContactInvited(true);
    setDropped([]);
    setGuestBoxBad(false);
    setDescription('');
    setAddToCalendar(defaultAddToCalendar);
    setAssoc(seedAssoc);
    setAssocOpen(false);
    setTriedSave(false);
    setMeetingType('');
    setOutcome('');
    setFollowUp(false);
    setFollowDue('biz3');
    setCustomDueDate('');
    setTaskType('todo');
    logged.current = false;
    savedId.current = undefined;
  });

  // A new meeting starts as "Scheduled" when Settings has that outcome.
  useEffect(() => {
    if (!open || !options.loaded || !addToCalendar) return;
    if (options.outcomes.includes('Scheduled')) setOutcome((cur) => cur || 'Scheduled');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, openCount, options.loaded]);

  useEffect(() => {
    if (!open) return;
    const preferred = defaultAttendeeEmail?.trim().toLowerCase();
    const first =
      pickerOptions.find((o) => o.value === preferred)?.value ?? pickerOptions[0]?.value;
    setSelectedAttendees(first ? [first] : []);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, openCount]);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    getMyCalendar().then(
      (c) => {
        if (alive) setCalendar(c);
      },
      (err) => {
        if (alive) toast(errorText(err), 'danger');
      },
    );
    return () => {
      alive = false;
    };
  }, [open, toast]);

  // Schedule-first pages (contacts/companies/deals) still require Calendar up front.
  // Log-only pages (custom records) never gate — user can tick Calendar later if connected.
  const blocked = defaultAddToCalendar && calendar !== null && !isUsable(calendar);
  const reconnect = needsReconnect(calendar);
  const calendarReady = calendar !== null && isUsable(calendar);
  const hostLabel = calendar?.emailAddress
    ? `${me.user.name} <${calendar.emailAddress}>`
    : me.user.name;

  const onConnect = async () => {
    setConnecting(true);
    try {
      const { authUrl } = await connectGoogleCalendar();
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
      setConnecting(false);
    }
  };

  // The legacy form's End time: a time on the start day, after the start.
  const endTime = addMinutesToTime(startTime, minutes);
  const onEndChange = (next: string) => {
    const s = timeToHours(startTime);
    const e = timeToHours(next);
    if (s !== null && e !== null && e > s) setMinutes(Math.round((e - s) * 60));
  };

  // Read live: the record's email can be fixed in the card behind the window.
  const preferredAttendee = defaultAttendeeEmail?.trim().toLowerCase();
  const contactAttendee =
    pickerOptions.find((o) => o.value === preferredAttendee)?.value ?? pickerOptions[0]?.value;

  // M-02: Log meeting is HubSpot's (attendees, outcome, type, start, duration, body, records,
  // follow-up task); Title, Location, Other guests and Activity assigned to are Schedule's only.
  const logMode = !addToCalendar;
  // M-22: a missing record is reported on save, so it doesn't disable the button.
  const canSchedule =
    !!date &&
    timeToHours(startTime) !== null &&
    Number.isInteger(minutes) &&
    minutes > 0 &&
    minutes <= MAX_CUSTOM_MINUTES &&
    (logMode
      ? // HubSpot's Log meeting stays off until the body has text.
        !htmlIsEmpty(description)
      : !guestBoxBad &&
        title.trim().length > 0 &&
        (where !== 'Link' || VIDEO_LINK_RE.test(place.trim())) &&
        calendarReady);

  const submit = async () => {
    if (!canSchedule || busy) return;
    if (!assoc.length) {
      setTriedSave(true);
      return;
    }
    if (addToCalendar && !calendarReady) {
      toast(
        'Connect Google Calendar to schedule, or untick Add to Google Calendar to log only',
        'danger',
      );
      return;
    }
    const startH = timeToHours(startTime);
    if (startH === null) return;
    // Other guests are Schedule's only.
    const extraGuests = logMode ? [] : guests;
    const invited = composer
      ? inviteAll
        ? [...invitedOptions(pickerOptions, dropped).map((o) => o.value), ...extraGuests]
        : [...(contactInvited && contactAttendee ? [contactAttendee] : []), ...extraGuests]
      : selectedAttendees;
    const attendees = invited.map((s) => s.trim().toLowerCase()).filter(Boolean);
    const bad = attendees.find((a) => !EMAIL_RE.test(a));
    if (bad) {
      toast(`Not an email address: ${bad}`, 'danger');
      return;
    }
    const start = fromZoned(date, startH, timeZone);
    const end = new Date(start.getTime() + minutes * 60_000);
    const links = assoc.map((a) => ({ type: a.type, id: a.id })).slice(0, MAX_NOTE_MEETING_LINKS);
    // Google Calendar gets the description as plain text; a logged meeting keeps it as its
    // rich-text notes (QA #648), which the API sanitizes.
    const descriptionText = htmlToText(description).slice(0, 8000) || undefined;
    const notesHtml = htmlIsEmpty(description) ? undefined : description;
    // A custom video link is the meeting's link and its place; the others name the kind of place.
    const videoLink = where === 'Link' ? place.trim() : undefined;
    const locationText =
      videoLink ||
      place.trim() ||
      (where === 'Phone' ? 'Phone call' : where === 'Office' ? 'In person' : undefined);
    setBusy(true);
    try {
      if (!addToCalendar) {
        // Log only — no Google event / invites (POST /meetings/log).
        if (!logged.current) {
          const loggedMeeting = await logRecordMeeting({
            title: LOGGED_MEETING_TITLE,
            start: start.toISOString(),
            end: end.toISOString(),
            notes: notesHtml,
            links,
            timezone: timeZone,
            attendees: [...new Set(attendees)],
            ...(outcome ? { outcome } : {}),
            ...(meetingType ? { meetingType } : {}),
          });
          savedId.current = loggedMeeting.id;
          logged.current = true;
        }
        if (followUp) {
          // M-02: the follow-up task, as Log call (LogCallDrawer.tsx:156-175).
          try {
            const taskSafe = taskLinksCapped(assoc);
            if (!taskSafe.length) {
              throw new Error('Follow-up needs a contact, company, or deal association');
            }
            await createTask({
              title: `Follow up with ${recordName}`,
              taskType,
              dueDate: followUpDueDate(followDue, timeZone, customDueDate),
              links: taskSafe,
            });
          } catch (taskErr) {
            toast(`Meeting logged, follow-up task failed: ${actionErrorText(taskErr)}`, 'danger', {
              durationMs: 8000,
            });
            onScheduled(savedId.current);
            onClose();
            return;
          }
          toast(`Meeting logged with follow-up task`);
        } else {
          toast(recordName ? `Meeting logged with ${recordName}` : 'Meeting logged');
        }
      } else {
        const meeting = await createMeeting({
          title: title.trim(),
          start: start.toISOString(),
          end: end.toISOString(),
          timezone: timeZone,
          attendees: [...new Set(attendees)],
          description: descriptionText,
          location: locationText,
          addMeet: where === 'Meet',
          links,
          idempotencyKey: meetingKey,
          ...(videoLink ? { meetingUrl: videoLink } : {}),
          ...(outcome ? { outcome } : {}),
          ...(meetingType ? { meetingType } : {}),
        });
        toast(recordName ? `Meeting scheduled with ${recordName}` : 'Meeting scheduled');
        if (meeting.googleStatus === 'failed' && meeting.googleError) {
          toast(`Google Calendar: ${meeting.googleError}`, 'danger', { durationMs: null });
        }
        savedId.current = meeting.id;
      }
      onScheduled(savedId.current);
      onClose();
    } catch (err) {
      if (
        addToCalendar &&
        isApiError(err) &&
        (err.isConflict || err.code === 'MAILBOX_NEEDS_REAUTH')
      ) {
        const fresh = await getMyCalendar().catch(() => null);
        setCalendar(
          fresh && !isUsable(fresh)
            ? fresh
            : {
                connected: false,
                emailAddress: null,
                status: null,
                lastSyncedAt: null,
                lastError: null,
              },
        );
        return;
      }
      toast(actionErrorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  if (blocked) {
    return (
      <CrmModal id={`${popupId}MeetingConnect`} open={open} onClose={onClose}>
        <ModalHeader id={`${popupId}MeetingConnect`} title="Schedule meeting" onClose={onClose} />
        <div className="modal__body">
          <h3 className="crm-mb-2" style={{ fontSize: 16, fontWeight: 600 }}>
            {reconnect ? 'Reconnect Google Calendar' : 'Connect Google Calendar'}
          </h3>
          <p className="crm-text-muted crm-mb-4">
            {reconnect
              ? `Your Google Calendar connection (${calendar?.emailAddress ?? 'Google'}) stopped working. Reconnect it to schedule meetings from the CRM.`
              : 'Meetings are created in your Google Calendar with a Google Meet link, and the invitation is sent from there. Connect your calendar first.'}
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            onClick={onConnect}
            disabled={connecting}
            aria-busy={connecting}
          >
            {reconnect ? 'Reconnect Google Calendar' : 'Connect Google Calendar'}
          </button>
        </div>
      </CrmModal>
    );
  }

  const durationMinutes = minutes;
  const startOption = { value: startTime, label: startTime ? timeLabel(startTime) : '' };
  const durationOption = {
    value: String(durationMinutes),
    label: durationMinutes > 0 ? durationLabel(durationMinutes) : '',
  };

  // M-02: HubSpot's Log meeting says "Meeting type"; Schedule keeps its label until its form is seen.
  const typeLabel = logMode ? 'Meeting type' : 'Call and meeting type';
  const followUpRow = logMode ? (
    // M-02: "Create a To-do task to follow up" (activity-composer.js:1399, `followRow`).
    <FollowUpTaskControls
      enabled={followUp}
      onEnabledChange={setFollowUp}
      taskType={taskType}
      onTaskTypeChange={setTaskType}
      dueKey={followDue}
      onDueKeyChange={setFollowDue}
      customDate={customDueDate}
      onCustomDateChange={setCustomDueDate}
      timeZone={timeZone}
      composer={Boolean(composer)}
    />
  ) : null;
  const bodyPlaceholder = logMode ? 'Start typing to log a meeting...' : undefined;

  const composerOutcomeType = (
    <>
      {options.outcomes.length ? (
        <div className="acx-field">
          <span className="acx-field__label">Meeting outcome</span>
          <ComposerSelect
            look="box"
            label="Meeting outcome"
            placeholder="Select meeting outcome"
            value={outcome}
            options={options.outcomes.map((o) => ({ value: o, label: o }))}
            onChange={setOutcome}
          />
        </div>
      ) : null}
      {options.types.length ? (
        <div className="acx-field">
          <span className="acx-field__label">{typeLabel}</span>
          <ComposerSelect
            look="box"
            search
            label={typeLabel}
            placeholder={`Select ${typeLabel.toLowerCase()}`}
            value={meetingType}
            options={options.types.map((o) => ({ value: o, label: o }))}
            onChange={setMeetingType}
          />
        </div>
      ) : null}
    </>
  );

  const composerForm = (
    <div className="meeting-popup__form" key={openCount}>
      {logMode ? null : (
        <div className="acx-pad">
          <input
            className="acx-input acx-input--title"
            placeholder="Meeting name"
            aria-label="Meeting name"
            autoComplete="off"
            maxLength={500}
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
      )}
      <div className="acx-fields acx-fields--grid">
        <div className="acx-field acx-field--wide">
          <span className="acx-field__label">Attendees</span>
          {inviteAll ? (
            <div className="acx-attendee" style={{ flexWrap: 'wrap' }}>
              {pickerOptions.length ? (
                pickerOptions.map((o) => {
                  const name = attendeeName(o.label);
                  return dropped.includes(o.value) ? (
                    <button
                      key={o.value}
                      type="button"
                      className="acx-assoc-link is-placeholder"
                      onClick={() => setDropped((cur) => cur.filter((v) => v !== o.value))}
                    >
                      Add {name}
                    </button>
                  ) : (
                    <span key={o.value} className="acx-attendee" title={o.value}>
                      <strong>{name}</strong>
                      <button
                        type="button"
                        aria-label={`Remove ${name}`}
                        onClick={() => setDropped((cur) => [...cur, o.value])}
                      >
                        <CrmIcon name="x" className="iconSize-14" />
                      </button>
                    </span>
                  );
                })
              ) : (
                <span className="acx-assoc-link is-placeholder">No contacts with an email</span>
              )}
            </div>
          ) : (
            <div className="acx-attendee">
              {contactAttendee && contactInvited ? (
                <>
                  <strong>{recordName}</strong>
                  <button
                    type="button"
                    aria-label={`Remove ${recordName}`}
                    onClick={() => setContactInvited(false)}
                  >
                    <CrmIcon name="x" className="iconSize-14" />
                  </button>
                </>
              ) : contactAttendee ? (
                <button
                  type="button"
                  className="acx-assoc-link is-placeholder"
                  onClick={() => setContactInvited(true)}
                >
                  Add {recordName}
                </button>
              ) : (
                <span className="acx-assoc-link is-placeholder">No email on this record</span>
              )}
            </div>
          )}
        </div>
        {logMode ? (
          composerOutcomeType
        ) : (
          <div className="acx-field acx-field--wide">
            <span className="acx-field__label">Other guests</span>
            <RecipientChips
              value={guests}
              onChange={setGuests}
              label="Add guest"
              onInvalidChange={setGuestBoxBad}
            />
          </div>
        )}
        <div className="acx-field">
          <span className="acx-field__label">Date</span>
          <input
            className="acx-input"
            type="date"
            aria-label="Meeting date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
          />
        </div>
        <div className="acx-field">
          <span className="acx-field__label">Start time</span>
          <ComposerSelect
            look="box"
            search
            label="Start time"
            value={startTime}
            options={slotsWith(TIME_OPTIONS, startOption)}
            onChange={(next) => {
              // Moves the meeting, keeping its length.
              setStartTime(next);
            }}
          />
        </div>
        <div className="acx-field">
          <span className="acx-field__label">Duration</span>
          <ComposerSelect
            look="box"
            search
            label="Duration"
            value={customLength ? CUSTOM_DURATION : String(durationMinutes)}
            options={[
              ...slotsWith(DURATION_OPTIONS, durationOption),
              { value: CUSTOM_DURATION, label: 'Custom…' },
            ]}
            onChange={(next) => {
              setCustomLength(next === CUSTOM_DURATION);
              if (next !== CUSTOM_DURATION) setMinutes(Number(next));
            }}
          />
        </div>
        {customLength ? (
          <div className="acx-field">
            <span className="acx-field__label">Custom duration (minutes)</span>
            <input
              className="acx-input"
              type="number"
              min={1}
              max={MAX_CUSTOM_MINUTES}
              step={1}
              aria-label="Custom duration in minutes"
              value={minutes || ''}
              onChange={(e) => setMinutes(Math.trunc(Number(e.target.value)))}
            />
          </div>
        ) : null}
        {logMode ? null : (
          <>
            {composerOutcomeType}
            <div className="acx-field">
              <span className="acx-field__label">Location type</span>
              <ComposerSelect
                look="box"
                label="Location type"
                value={where}
                options={LOCATION_TYPES}
                onChange={setWhere}
              />
            </div>
            <div className="acx-field">
              <span className="acx-field__label">
                {where === 'Link' ? 'Video link' : 'Location'}
              </span>
              <input
                className="acx-input"
                placeholder={where === 'Link' ? 'https://…' : 'Add location or video link'}
                aria-label={where === 'Link' ? 'Video link' : 'Location'}
                aria-invalid={
                  where === 'Link' && !!place.trim() && !VIDEO_LINK_RE.test(place.trim())
                }
                autoComplete="off"
                maxLength={500}
                value={place}
                onChange={(e) => setPlace(e.target.value)}
              />
            </div>
            <div className="acx-field">
              <span className="acx-field__label">Reminder</span>
              <span className="acx-static">
                {options.reminders.length
                  ? options.reminders.join(', ')
                  : options.loaded
                    ? 'No reminder'
                    : ''}
              </span>
            </div>
            <div className="acx-field">
              <span className="acx-field__label">Activity assigned to</span>
              {/* A scheduled meeting lives in its organizer's calendar. */}
              <span className="acx-static">{me.user.name}</span>
            </div>
          </>
        )}
      </div>
      <ComposeRichText
        openKey={openCount}
        value={description}
        onChange={setDescription}
        label="Description"
        placeholder={bodyPlaceholder ?? 'Add a description...'}
        minHeight={102}
        plannedTools
        snippetTarget={snippetTargetFor(link, snippetContactId)}
      />
      <AssociatedRecordsPanel
        className="acx-row"
        value={assoc}
        onChange={setAssoc}
        locked={primary}
        maxSelected={MAX_NOTE_MEETING_LINKS}
        open={assocOpen}
        onOpenChange={setAssocOpen}
      />
      {followUpRow}
    </div>
  );

  const popupAttendees = (
    <Field label="Attendees" htmlFor="meetAttendees">
      <MultiCustomSelect
        id="meetAttendees"
        name="attendees"
        placeholder="Select or type an email"
        value={selectedAttendees}
        options={pickerOptions}
        onChange={setSelectedAttendees}
        selectedText="attendees"
        menuMinWidth={320}
        allowCustomEmail
      />
    </Field>
  );

  const popupOutcomeType = (
    <>
      {options.outcomes.length ? (
        <Field label="Meeting outcome" htmlFor="meetOutcome">
          <select
            className="input"
            id="meetOutcome"
            value={outcome}
            onChange={(e) => setOutcome(e.target.value)}
          >
            <option value="">Select meeting outcome</option>
            {options.outcomes.map((o) => (
              <option key={o} value={o}>
                {o}
              </option>
            ))}
          </select>
        </Field>
      ) : null}
      {options.types.length ? (
        <Field label={typeLabel} htmlFor="meetType">
          <select
            className="input"
            id="meetType"
            value={meetingType}
            onChange={(e) => setMeetingType(e.target.value)}
          >
            <option value="">{`Select ${typeLabel.toLowerCase()}`}</option>
            {options.types.map((o) => (
              <option key={o} value={o}>
                {o}
              </option>
            ))}
          </select>
        </Field>
      ) : null}
    </>
  );

  const form = composer ? (
    composerForm
  ) : (
    <div className="meeting-popup__form" key={openCount}>
      <AssocForPill
        ref={forPillRef}
        label={
          assoc.length > 1
            ? `${recordName || 'Records'} and ${assoc.length - 1} record${assoc.length === 2 ? '' : 's'}`
            : recordName || 'Select records'
        }
        expanded={assocOpen}
        onClick={() => setAssocOpen((o) => !o)}
      />
      {triedSave && assoc.length === 0 ? (
        // M-22: said once a save was tried, not as the window opens.
        <div className="field is-invalid">
          <span className="field__error" role="status">
            Select at least one record to save this meeting with.
          </span>
        </div>
      ) : null}

      {logMode ? (
        popupAttendees
      ) : (
        <>
          <Field label="Host" htmlFor="meetHost">
            <input className="input" id="meetHost" value={hostLabel} readOnly disabled />
          </Field>

          <Field label="Title" htmlFor="meetTitle">
            <input
              className="input"
              id="meetTitle"
              maxLength={500}
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Meeting title"
              required
            />
          </Field>

          <Field label="Timezone" htmlFor="meetTz">
            <input
              className="input"
              id="meetTz"
              value={currentZoneName(timeZone)}
              readOnly
              disabled
            />
          </Field>
        </>
      )}

      {logMode ? popupOutcomeType : null}

      <div className="meeting-popup__time-row">
        <Field label="Start date" htmlFor="meetDate">
          <input
            className="input"
            id="meetDate"
            type="date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            required
          />
        </Field>
        <Field label="Start time" htmlFor="meetStart">
          <input
            className="input"
            id="meetStart"
            type="time"
            step={300}
            value={startTime}
            onChange={(e) => setStartTime(e.target.value)}
            required
          />
        </Field>
        {logMode ? (
          <Field label="Duration" htmlFor="meetDuration">
            <select
              className="input"
              id="meetDuration"
              value={String(durationMinutes)}
              onChange={(e) => setMinutes(Number(e.target.value))}
            >
              {slotsWith(DURATION_OPTIONS, durationOption).map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </Field>
        ) : (
          <Field label="End time" htmlFor="meetEnd">
            <input
              className="input"
              id="meetEnd"
              type="time"
              step={300}
              value={endTime}
              onChange={(e) => onEndChange(e.target.value)}
              required
            />
          </Field>
        )}
      </div>

      {logMode ? null : (
        <>
          <Field label="Location" htmlFor="meetWhere">
            <select
              className="input"
              id="meetWhere"
              value={where}
              onChange={(e) => setWhere(e.target.value)}
            >
              <option value="Meet">Google Meet</option>
              <option value="Phone">Phone call</option>
              <option value="Office">In person</option>
              <option value="Link">Custom video link</option>
            </select>
          </Field>
          {where === 'Link' ? (
            <Field label="Video link" htmlFor="meetLink">
              <input
                className="input"
                id="meetLink"
                value={place}
                onChange={(e) => setPlace(e.target.value)}
                placeholder="https://…"
              />
            </Field>
          ) : null}
          {popupOutcomeType}
          {popupAttendees}
        </>
      )}

      <ComposeRichText
        openKey={openCount}
        value={description}
        onChange={setDescription}
        label="Description"
        placeholder={bodyPlaceholder ?? 'Agenda, links, anything attendees should know'}
        minHeight={120}
        snippetTarget={snippetTargetFor(link, snippetContactId)}
      />

      <AssociatedRecordsPanel
        value={assoc}
        onChange={setAssoc}
        locked={primary}
        maxSelected={MAX_NOTE_MEETING_LINKS}
        open={assocOpen}
        onOpenChange={setAssocOpen}
        extraAnchorRef={forPillRef}
      />

      {followUpRow}
    </div>
  );

  return (
    <DraggablePopup
      composer={composer}
      id={`${popupId}MeetingModal`}
      open={open}
      onClose={onClose}
      confirmClose={title.trim() !== defaultTitle || !htmlIsEmpty(description) || guests.length > 0}
      // M-24: the window says the mode it is in.
      title={logMode ? 'Log Meeting' : 'Schedule'}
      size="lg"
      className="activity-popup--meeting"
      footer={
        <>
          <button
            type="button"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            disabled={!canSchedule || busy}
            aria-busy={busy}
            onClick={() => void submit()}
          >
            {addToCalendar ? (composer ? 'Schedule' : 'Schedule meeting') : 'Log meeting'}
          </button>
          {composer ? null : (
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          )}
          <label
            className={composer ? 'acx-track' : 'activity-popup__followup'}
            style={composer ? undefined : { margin: 0, marginLeft: 'auto' }}
          >
            <input
              type="checkbox"
              checked={addToCalendar}
              onChange={(e) => {
                setAddToCalendar(e.target.checked);
                // Unticking removes the guest box, and what was in it.
                setGuestBoxBad(false);
              }}
            />
            <span>{composer ? 'Send calendar invite to attendees' : 'Add to Google Calendar'}</span>
          </label>
          {addToCalendar && !calendarReady && calendar !== null && !defaultAddToCalendar ? (
            <button
              type="button"
              className="btn-crm btn-crm--ghost"
              onClick={() => void onConnect()}
              disabled={connecting}
            >
              Connect Calendar
            </button>
          ) : null}
        </>
      }
    >
      {({ maximized }) => (
        <div className={cn('meeting-popup__layout', maximized && 'is-maximized')}>
          {form}
          {maximized ? (
            <MeetingWeekPreview
              timeZone={timeZone}
              selectedDay={date}
              selectedStart={startTime}
              selectedEnd={endTime}
              onPickSlot={(day, start) => {
                setDate(day);
                setStartTime(start);
              }}
            />
          ) : null}
        </div>
      )}
    </DraggablePopup>
  );
}
