All files / src/components/organizer/SpeakerDrawer ContentSubmissionSubView.tsx

64.51% Statements 80/124
59.81% Branches 64/107
58.82% Functions 10/17
66.66% Lines 80/120

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584                                                                                                                            1x   1x             257x 257x   257x 257x 257x 257x   257x         257x   257x   257x   3x   2x 2x 2x 2x       2x 2x                     257x                                           257x 5x 5x 5x               5x 5x 1x 1x                       5x 5x 5x 5x 5x   5x 5x       5x                   5x 5x 5x     5x     5x           5x     257x 2x 2x 2x 2x 2x             257x             257x   257x 3x         3x     3x   3x     3x   3x                         3x 3x     257x 3x         3x   3x 3x 3x                 3x                           3x               3x     257x                                         257x         257x           257x                             257x 257x         257x 257x 257x   257x                                                                                                                                                                                                                                                                                                                                     81x                       162x                                                                                                                
/**
 * On-behalf content submission form (Story 11.D.4 — AC8;
 * Epic 11 bug fix 2026-05-19 stripped the bio + portrait overrides).
 *
 * Hosts inside the drawer's `drawerView === 'content-submission'` sub-view, or as the
 * `embedded` body of the Content TAB. The form collects:
 *   - Speaker (user-autocomplete, required) — picked to resolve `speaker_pool.username`.
 *   - Presentation title + abstract (required).
 *   - Optional presentation upload — DEFERRED: the speaker-portal materials upload uses
 *     a magic-link `?token=` path that isn't accessible from the organizer surface; per
 *     AC8 step 3 fallback this field is omitted until a dedicated organizer materials
 *     endpoint is added. The `SubmitContentRequest.presentationUploadId` field is wired
 *     and ready to accept the upload ID when that endpoint lands.
 *
 * Bio + portrait are NOT edited here — they are user-level attributes and are
 * managed via the user-edit modal (the "Edit speaker profile" button below the
 * autocomplete opens `UserCreateEditModal`). Carrying them on the per-event
 * content-submission form duplicates that surface with no added value.
 *
 * The request body NO LONGER includes `username` — the 11.C.2 backend reads the
 * resolved username from `speaker_pool` (set at provisioning time by Story 11.D.1's
 * promote flow). Sending `username` to the strict backend returns 400.
 */
import React, { useEffect, useRef, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  Divider,
  IconButton,
  Paper,
  TextField,
  Typography,
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { speakerContentService } from '@/services/speakerContentService';
import { sessionApiClient } from '@/services/api/sessionApiClient';
import { speakerPoolKeys } from '@/hooks/useSpeakerPool';
import { getUserByUsername, searchUsers, updateUserRoles } from '@/services/api/userManagementApi';
import { UserAutocomplete } from '@/components/shared/UserAutocomplete';
import { UserAvatar } from '@/components/shared/UserAvatar';
import UserCreateEditModal from '@/components/organizer/UserManagement/UserCreateEditModal';
import type { SpeakerPoolEntry } from '@/types/speakerPool.types';
import type { SubmitContentRequest } from '@/services/speakerContentService';
import type { UserSearchResponse, User, Role } from '@/types/user.types';
 
interface ContentSubmissionSubViewProps {
  speaker: SpeakerPoolEntry;
  eventCode: string;
  onBack: () => void;
  onClose: () => void;
  /**
   * When true the sub-view renders without its takeover chrome (back-arrow header bar +
   * onClose-on-success). Used by the drawer's Content TAB so the tab body looks like a
   * regular panel. Epic 11 bug fix 2026-05-18.
   */
  embedded?: boolean;
}
 
const MAX_ABSTRACT_LENGTH = 1000;
 
export const ContentSubmissionSubView: React.FC<ContentSubmissionSubViewProps> = ({
  speaker,
  eventCode,
  onBack,
  onClose,
  embedded = false,
}) => {
  const { t } = useTranslation(['organizer', 'common']);
  const queryClient = useQueryClient();
 
  const [selectedUser, setSelectedUser] = useState<UserSearchResponse | null>(null);
  const [presentationTitle, setPresentationTitle] = useState('');
  const [presentationAbstract, setPresentationAbstract] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});
 
  const [userModalOpen, setUserModalOpen] = useState(false);
  // `editingUser` holds the FULL `User` (UserResponse) shape — UserSearchResponse
  // omits `bio` / `isActive` / other user-level fields, and passing it to the modal
  // surfaces an empty bio even when the backend has one. Resolved on demand in
  // `handleEditSpeaker` (fetches the full projection via getUserByUsername).
  const [editingUser, setEditingUser] = useState<User | null>(null);
 
  const lastPrefilledSpeakerIdRef = useRef<string | null>(null);
 
  const submitContentMutation = useMutation({
    mutationFn: (request: SubmitContentRequest) =>
      speakerContentService.submitContent(eventCode, speaker.id, request),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['speakerStatusSummary', eventCode] });
      queryClient.invalidateQueries({ queryKey: speakerPoolKeys.list(eventCode) });
      queryClient.invalidateQueries({ queryKey: ['event', eventCode] });
      resetForm();
      // Takeover mode auto-closes the drawer on success; embedded mode leaves the
      // drawer open so the organizer sees the updated state in the now-CONTENT_SUBMITTED
      // panel (Epic 11 bug fix 2026-05-18 — Content as a tab).
      Eif (!embedded) {
        onClose();
      }
    },
  });
 
  // 2026-05-20 (Q#8) — READY-state draft save. Writes directly to sessions.title /
  // sessions.description (the canonical source per plan §2.9) without transitioning the
  // workflow state and without inserting a session_content_history row. The speaker can
  // still later accept normally; their accepted-state Save will be the first real
  // session_content_history audit row. PATCH /events/{code}/sessions/{slug} is the same
  // endpoint the organizer's session-edit modal uses.
  const saveDraftMutation = useMutation({
    mutationFn: async ({ title, description }: { title: string; description: string }) => {
      if (!speaker.sessionSlug) {
        throw new Error(
          'Session is not yet provisioned for this speaker — re-run promote-to-READY first.'
        );
      }
      return sessionApiClient.updateSession(eventCode, speaker.sessionSlug, {
        title,
        description,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: speakerPoolKeys.list(eventCode) });
      queryClient.invalidateQueries({ queryKey: ['event', eventCode] });
      // Embedded mode: keep drawer open so the organizer sees the saved values reflected.
      if (!embedded) {
        onClose();
      }
    },
  });
 
  useEffect(() => {
    const prefillSpeaker = async () => {
      Eif (speaker && lastPrefilledSpeakerIdRef.current !== speaker.id) {
        try {
          // Epic 11 bug fix 2026-05-19 — once promoted, the pool entry carries
          // `username` (the linked User's meaningful ID). Direct lookup via
          // `getUserByUsername` is the only reliable resolver: `/users/search`
          // matches name/email substrings and does NOT match by username, so
          // `searchUsers("nissim.buchs.3")` returns `[]` even though the user
          // exists. Falls back to the legacy name-based search for unpromoted
          // speakers (where `speaker.username == null`).
          let resolved: UserSearchResponse | null = null;
          if (speaker.username) {
            const user = await getUserByUsername(speaker.username);
            Iif (user) {
              resolved = {
                id: user.id,
                email: user.email,
                firstName: user.firstName,
                lastName: user.lastName,
                roles: user.roles,
                profilePictureUrl: user.profilePictureUrl,
                companyId: user.companyId,
              };
            }
          }
          Eif (!resolved) {
            let users = await searchUsers(speaker.speakerName, 20);
            Eif (users.length === 0 && speaker.speakerName.includes(' ')) {
              const firstName = speaker.speakerName.split(' ')[0];
              users = await searchUsers(firstName, 20);
            }
            const candidates = users.filter((u) => u.roles?.includes('SPEAKER'));
            Iif (candidates.length > 0) {
              resolved = candidates[0];
            }
          }
          Iif (resolved) {
            setSelectedUser(resolved);
          }
          // 2026-05-20 (Q#9) — prefill both title and abstract from the canonical
          // sessions.title / sessions.description (mirrored as submittedTitle /
          // submittedAbstract on the pool response per plan §2.9). The old code only
          // read the now-dropped initialPresentationTitle column, so the abstract was
          // never prefilled and the title was empty in any state past READY. The
          // initialPresentationTitle fallback is kept for any legacy rows where
          // submittedTitle is still null.
          const prefilledTitle = speaker.submittedTitle || speaker.initialPresentationTitle || '';
          const prefilledAbstract = speaker.submittedAbstract || '';
          Iif (prefilledTitle) {
            setPresentationTitle(prefilledTitle);
          }
          Iif (prefilledAbstract) {
            setPresentationAbstract(prefilledAbstract);
          }
          lastPrefilledSpeakerIdRef.current = speaker.id;
        } catch (error) {
          console.error('Failed to prefill speaker:', error);
        }
      }
    };
    prefillSpeaker();
  }, [speaker]);
 
  const resetForm = () => {
    setSelectedUser(null);
    setPresentationTitle('');
    setPresentationAbstract('');
    setErrors({});
    lastPrefilledSpeakerIdRef.current = null;
  };
 
  // 2026-05-20 (Q#8) — in READY the workflow doesn't yet allow CONTENT_SUBMITTED, so the
  // form runs in "draft" mode: title + abstract are OPTIONAL, save writes directly to
  // sessions.title / sessions.description (no state transition, no audit row). In
  // ACCEPTED+ the form is a real submission; both title and abstract become required.
  const isReadyStateDraftOnly = speaker.status === 'READY';
 
  // Phase D.5 (BATbern75 follow-up, 2026-05-21) — once a session is provisioned (status
  // ≥ READY per Story 11.E.8) the speaker identity is owned by session_users; this tab
  // only handles content (title, abstract, materials). The user-picker is suppressed
  // and a static identity label takes its place, with an inline hint pointing the
  // organizer to the Sessions tab for any speaker reassignment.
  const isSessionAssigned = !!speaker.sessionId;
 
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    // Phase D.5: speaker identity is fixed once a session is assigned (session_users
    // owns it). Skip the username-required check in that case; the prefill effect has
    // already resolved selectedUser from speaker.username, and the picker is not
    // editable.
    Iif (!selectedUser && !isSessionAssigned) {
      newErrors.username = t('organizer:speakerContent.errors.usernameRequired');
    }
    if (!isReadyStateDraftOnly) {
      // Real submission: title + abstract required.
      Iif (!presentationTitle.trim()) {
        newErrors.presentationTitle = t('organizer:speakerContent.errors.titleRequired');
      }
      Iif (!presentationAbstract.trim()) {
        newErrors.presentationAbstract = t('organizer:speakerContent.errors.abstractRequired');
      } else if (IpresentationAbstract.length > MAX_ABSTRACT_LENGTH) {
        newErrors.presentationAbstract = t('organizer:speakerContent.errors.abstractTooLong', {
          max: MAX_ABSTRACT_LENGTH,
        });
      }
    } else E{
      // Draft mode: only the abstract-length cap is enforced when an abstract is given.
      if (presentationAbstract.length > MAX_ABSTRACT_LENGTH) {
        newErrors.presentationAbstract = t('organizer:speakerContent.errors.abstractTooLong', {
          max: MAX_ABSTRACT_LENGTH,
        });
      }
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
 
  const handleSubmit = async () => {
    Iif (!validateForm()) return;
    // Phase D.5: post-session, selectedUser may be null if the prefill failed but the
    // server-side identity is already established via session_users. We still want
    // submission to work. The SPEAKER-role grant below is a no-op anyway (the user
    // received the role at the READY transition).
    Iif (!selectedUser && !isSessionAssigned) return;
 
    Eif (selectedUser) {
      const existingRoles = (selectedUser.roles ?? []) as Role[];
      Iif (!existingRoles.includes('SPEAKER')) {
        try {
          await updateUserRoles(selectedUser.id, [...existingRoles, 'SPEAKER']);
        } catch (error) {
          console.error('Failed to grant SPEAKER role:', error);
        }
      }
    }
 
    Iif (isReadyStateDraftOnly) {
      // 2026-05-20 (Q#8) — draft path: PATCH sessions.title / .description directly.
      // No workflow transition, no session_content_history row.
      saveDraftMutation.mutate({
        title: presentationTitle.trim(),
        description: presentationAbstract.trim(),
      });
      return;
    }
 
    // Story 11.D.4 AC8 — request body shape matches the 11.C.2 backend DTO.
    // CRITICAL: NO `username` field (the strict backend rejects unknown properties).
    // Epic 11 bug fix 2026-05-19 — bio + profilePictureUrl removed; those are
    // user-level fields edited via the user-edit modal, not per-event submissions.
    const requestBody: SubmitContentRequest = {
      presentationTitle: presentationTitle.trim(),
      presentationAbstract: presentationAbstract.trim(),
    };
    // presentationUploadId is wired and ready for a future organizer-side materials
    // upload endpoint (per AC8 step 3 fallback — speaker-portal materials flow uses a
    // magic-link `?token=` that isn't reachable from the organizer drawer today).
 
    submitContentMutation.mutate(requestBody);
  };
 
  const handleEditSpeaker = async () => {
    if (!selectedUser) return;
    // Epic 11 bug fix 2026-05-19 — `selectedUser` is the narrow UserSearchResponse
    // returned by the autocomplete, which omits `bio` / `isActive` and other
    // user-level fields. Passing that to UserCreateEditModal renders an empty bio
    // even when the backend has one set (e.g. opening the same modal from the
    // user-list page shows the bio filled). Fetch the full `UserResponse` here so
    // every field round-trips correctly. Modal opens optimistically with the
    // narrow projection so the UI is responsive while the fetch resolves.
    setEditingUser(selectedUser as unknown as User);
    setUserModalOpen(true);
    try {
      const fullUser = await getUserByUsername(selectedUser.id);
      if (fullUser) {
        setEditingUser(fullUser);
      }
    } catch (error) {
      console.error('Failed to fetch full user for edit:', error);
    }
  };
 
  const handleCreateSpeaker = () => {
    setEditingUser(null);
    setUserModalOpen(true);
  };
 
  const handleUserModalClose = () => {
    setUserModalOpen(false);
    setEditingUser(null);
    queryClient.invalidateQueries({ queryKey: ['users', 'search'] });
  };
 
  const handleUserModalSuccess = (createdOrUpdatedUser?: User) => {
    if (createdOrUpdatedUser) {
      setSelectedUser({
        id: createdOrUpdatedUser.id,
        email: createdOrUpdatedUser.email,
        firstName: createdOrUpdatedUser.firstName,
        lastName: createdOrUpdatedUser.lastName,
        roles: createdOrUpdatedUser.roles,
        profilePictureUrl: createdOrUpdatedUser.profilePictureUrl,
        companyId: createdOrUpdatedUser.companyId,
      });
    }
    handleUserModalClose();
  };
 
  const remainingAbstractChars = MAX_ABSTRACT_LENGTH - presentationAbstract.length;
  const isAbstractTooLong = remainingAbstractChars < 0;
 
  // 2026-05-20 (Q#8) — `isReadyStateDraftOnly` is hoisted to the validate/submit closures
  // above (re-declaring it here would shadow). Used below to swap the submit button label
  // + banner + busy spinner between the draft and real-submit mutations.
  const isSavingDraft = saveDraftMutation.isPending;
  const isSubmitting = submitContentMutation.isPending;
  const isBusy = isSavingDraft || isSubmitting;
 
  return (
    <>
      {!embedded && (
        <>
          <Box sx={{ p: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
            <IconButton
              onClick={onBack}
              size="small"
              aria-label={t('organizer:speakers.drawer.back')}
            >
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="h6">{t('organizer:speakerContent.submitContent')}</Typography>
          </Box>
          <Divider />
        </>
      )}
 
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        <Typography variant="subtitle2" gutterBottom>
          {t('organizer:speakerContent.presentationDetails')}
        </Typography>
 
        {isReadyStateDraftOnly && (
          <Alert severity="info" sx={{ mb: 2 }} data-testid="content-tab-ready-banner">
            {t(
              'organizer:speakerContent.readyStateDraftBanner',
              'Speaker has not accepted yet. Saving here writes the title and abstract as a draft on the session — no submission is recorded, and the speaker can still update it after accepting.'
            )}
          </Alert>
        )}
 
        {submitContentMutation.isError && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {submitContentMutation.error instanceof Error
              ? submitContentMutation.error.message
              : t('organizer:speakerContent.errors.submitFailed')}
          </Alert>
        )}
 
        {saveDraftMutation.isError && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {saveDraftMutation.error instanceof Error
              ? saveDraftMutation.error.message
              : t('organizer:speakerContent.errors.saveDraftFailed', 'Could not save the draft.')}
          </Alert>
        )}
 
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
          {/* Speaker selection (or, post-session, static identity readout) */}
          <Box>
            <Typography variant="subtitle2" gutterBottom>
              {t('organizer:speakerContent.speakerInformation')}
            </Typography>
            <Paper variant="outlined" sx={{ p: 2 }}>
              {isSessionAssigned ? (
                // Phase D.5: post-session, speaker identity is owned by session_users
                // (mutated only via the Sessions tab). Render a read-only label
                // sourced from the prefilled selectedUser (resolved from
                // speaker.username, which Phase A's overlay now keeps live). The
                // user-picker / Create-new buttons are hidden so the Content tab
                // cannot double-write the identity.
                <Box data-testid="content-tab-speaker-readonly">
                  {selectedUser ? (
                    <Box sx={{ mb: 2 }}>
                      <UserAvatar
                        firstName={selectedUser.firstName}
                        lastName={selectedUser.lastName}
                        company={selectedUser.companyId}
                        profilePictureUrl={selectedUser.profilePictureUrl}
                        size={40}
                        showCompany={true}
                      />
                      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                        {selectedUser.email}
                      </Typography>
                    </Box>
                  ) : (
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                      {speaker.speakerName ?? '—'}
                    </Typography>
                  )}
                  <Alert severity="info" sx={{ mb: 2 }}>
                    {t(
                      'organizer:speakerContent.speakerLockedHint',
                      'The speaker is fixed for this session. Use the Sessions tab to reassign.'
                    )}
                  </Alert>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={handleEditSpeaker}
                    disabled={!selectedUser || submitContentMutation.isPending}
                    fullWidth
                  >
                    {t('organizer:speakerContent.editSpeakerProfile')}
                  </Button>
                </Box>
              ) : (
                <>
                  <UserAutocomplete
                    value={selectedUser}
                    onChange={setSelectedUser}
                    error={errors.username}
                    label={t('organizer:speakerContent.form.username')}
                    role="SPEAKER"
                    disabled={submitContentMutation.isPending}
                    data-testid="speaker-search-field"
                  />
 
                  {selectedUser && (
                    <Box sx={{ mt: 2, p: 2, bgcolor: 'action.hover', borderRadius: 1 }}>
                      <Box sx={{ mb: 2 }}>
                        <UserAvatar
                          firstName={selectedUser.firstName}
                          lastName={selectedUser.lastName}
                          company={selectedUser.companyId}
                          profilePictureUrl={selectedUser.profilePictureUrl}
                          size={40}
                          showCompany={true}
                        />
                      </Box>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        {selectedUser.email}
                      </Typography>
                      {selectedUser.roles && selectedUser.roles.length > 0 && (
                        <Typography variant="caption" color="text.secondary">
                          Role: {selectedUser.roles.join(', ')}
                        </Typography>
                      )}
                      <Box sx={{ mt: 2 }}>
                        <Button
                          variant="outlined"
                          size="small"
                          onClick={handleEditSpeaker}
                          disabled={submitContentMutation.isPending}
                          fullWidth
                        >
                          {t('organizer:speakerContent.editSpeakerProfile')}
                        </Button>
                      </Box>
                    </Box>
                  )}
 
                  <Box sx={{ mt: 2 }}>
                    <Button
                      variant="outlined"
                      size="small"
                      onClick={handleCreateSpeaker}
                      disabled={submitContentMutation.isPending}
                      fullWidth
                    >
                      {t('organizer:speakerContent.createNewSpeaker')}
                    </Button>
                  </Box>
                </>
              )}
            </Paper>
          </Box>
 
          <TextField
            label={t('organizer:speakerContent.form.presentationTitle')}
            value={presentationTitle}
            onChange={(e) => setPresentationTitle(e.target.value)}
            error={!!errors.presentationTitle}
            helperText={errors.presentationTitle}
            required={!isReadyStateDraftOnly}
            fullWidth
            disabled={isBusy}
            inputProps={{ 'data-testid': 'presentation-title-field' }}
          />
 
          <TextField
            label={t('organizer:speakerContent.form.presentationAbstract')}
            value={presentationAbstract}
            onChange={(e) => setPresentationAbstract(e.target.value)}
            error={!!errors.presentationAbstract || isAbstractTooLong}
            helperText={
              errors.presentationAbstract ||
              `${remainingAbstractChars} / ${MAX_ABSTRACT_LENGTH} ${t('organizer:speakerContent.form.charactersRemaining')}`
            }
            required={!isReadyStateDraftOnly}
            multiline
            rows={6}
            fullWidth
            disabled={isBusy}
            inputProps={{ 'data-testid': 'presentation-abstract-field' }}
          />
        </Box>
      </Box>
 
      {/* Actions */}
      <Box
        sx={{
          p: 2,
          display: 'flex',
          justifyContent: 'flex-end',
          gap: 2,
          borderTop: 1,
          borderColor: 'divider',
        }}
      >
        <Button variant="outlined" onClick={onBack} disabled={isBusy}>
          {t('common:actions.cancel')}
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          // 2026-05-20 (Q#8) — `isReadyStateDraftOnly` no longer disables Save; in READY
          // we route through `saveDraftMutation` instead of `submitContentMutation`.
          disabled={isBusy || isAbstractTooLong}
          startIcon={isBusy ? <CircularProgress size={20} /> : null}
          data-testid="submit-speaker-content-button"
        >
          {isBusy
            ? t('organizer:speakerContent.submitting')
            : isReadyStateDraftOnly
              ? t('organizer:speakerContent.saveDraft', 'Save draft')
              : t('organizer:speakerContent.submitContent')}
        </Button>
      </Box>
 
      <UserCreateEditModal
        open={userModalOpen}
        onClose={handleUserModalClose}
        onSuccess={handleUserModalSuccess}
        user={editingUser}
      />
    </>
  );
};