Просмотр исходного кода

Use the redesigned confirmation dialog for every prompt (#616)

Every confirmation prompt now draws through the shared confirm dialog: icon chip, tinted hairline, subject rows and a button bar, and a bottom sheet on phones. Undoing an import reads as a delete again, the assign-to-all-work-orders question opens on skip, the classic vehicle delete shows the vehicle icon, and the inspection completion blockers are translated.
Bernt Christian Egeland 1 день назад
Родитель
Сommit
8fd06f9f8f
52 измененных файлов с 1372 добавлено и 1136 удалено
  1. 2 0
      messages/de/inspections.json
  2. 2 0
      messages/en/inspections.json
  3. 2 0
      messages/es/inspections.json
  4. 2 0
      messages/fr/inspections.json
  5. 2 0
      messages/it/inspections.json
  6. 2 0
      messages/lt/inspections.json
  7. 2 0
      messages/nb/inspections.json
  8. 2 0
      messages/nl/inspections.json
  9. 2 0
      messages/pl/inspections.json
  10. 2 0
      messages/pt-BR/inspections.json
  11. 2 0
      messages/pt-PT/inspections.json
  12. 2 0
      messages/ru/inspections.json
  13. 2 0
      messages/tr/inspections.json
  14. 14 1
      src/__tests__/app/settings/webhooks-dropped-connection.test.tsx
  15. 64 0
      src/__tests__/app/settings/workshop-assign-confirm.test.tsx
  16. 172 0
      src/__tests__/app/vehicles/vehicle-detail-delete.test.tsx
  17. 7 1
      src/__tests__/app/vehicles/vehicle-detail-dropped-connection.test.tsx
  18. 7 1
      src/__tests__/app/vehicles/vehicle-detail-new-work-order.test.tsx
  19. 53 1
      src/__tests__/components/confirm-dialog.test.tsx
  20. 24 12
      src/__tests__/features/auth/passkey-settings.test.tsx
  21. 7 1
      src/__tests__/features/condition-map/keyboard-marks.test.tsx
  22. 14 1
      src/__tests__/features/condition-map/mark-change-failure.test.tsx
  23. 7 1
      src/__tests__/features/condition-map/remove-mark.test.tsx
  24. 55 0
      src/__tests__/features/import/import-undo-confirm.test.tsx
  25. 7 1
      src/__tests__/features/inspections/checklist-translate-banner.test.tsx
  26. 7 1
      src/__tests__/features/inspections/item-photo-remove.test.tsx
  27. 7 1
      src/__tests__/features/inspections/quote-requested-marker.test.tsx
  28. 14 1
      src/__tests__/features/inspections/template-list-dropped-connection.test.tsx
  29. 5 1
      src/__tests__/features/leaving/quote-saves-before-leaving.test.tsx
  30. 14 1
      src/__tests__/features/sms/sms-conversation-dropped-connection.test.tsx
  31. 7 1
      src/__tests__/features/telegram/telegram-thread-switch.test.tsx
  32. 40 63
      src/app/(authenticated)/settings/webhooks/webhooks-settings.tsx
  33. 16 50
      src/app/(authenticated)/settings/workshop/workshop-settings.tsx
  34. 17 35
      src/app/(authenticated)/vehicles/[id]/_classic/vehicle-detail-classic.tsx
  35. 14 35
      src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx
  36. 341 216
      src/components/confirm-dialog.tsx
  37. 20 21
      src/components/sent-copy-note.tsx
  38. 14 36
      src/features/condition-map/Components/ConditionMapCard.tsx
  39. 33 48
      src/features/import/Components/ImportHistoryCard.tsx
  40. 19 37
      src/features/inspections/Components/InspectionItemRow.tsx
  41. 87 107
      src/features/inspections/Components/InspectionPageClient.tsx
  42. 15 38
      src/features/inspections/Components/TemplateListClient.tsx
  43. 17 45
      src/features/messaging/Components/UnifiedInbox.tsx
  44. 15 35
      src/features/scheduled-messages/Components/ScheduledMessageList.tsx
  45. 14 30
      src/features/settings/Components/passkey-settings.tsx
  46. 14 40
      src/features/sms/Components/SmsConversation.tsx
  47. 16 42
      src/features/status-reports/Components/StatusReportList.tsx
  48. 79 83
      src/features/subscription/Components/subscription-settings.tsx
  49. 14 38
      src/features/telegram/Components/TelegramConversation.tsx
  50. 14 40
      src/features/telegram/Components/TelegramMessagesClient.tsx
  51. 39 44
      src/features/vehicles/Components/service-edit/NotesSection.tsx
  52. 23 27
      src/features/vehicles/Components/service-page/LeaveUnsavedDialog.tsx

+ 2 - 0
messages/de/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Diese Inspektion abschließen?",
     "completeBody": "Die Prüfpunkte werden mit dem Abschluss gesperrt, und das Ergebnis lautet dann „{result}“.",
     "completeBlocked": "{count} Prüfung(en), die die Checkliste als Pflicht markiert, sind noch offen.",
+    "blockerMissingGrade": "muss bewertet werden",
+    "blockerNeedsPhoto": "braucht ein Foto des Mangels",
     "completeUngraded": "{count} Prüfpunkt(e) wurden nicht bewertet.",
     "completeDangerous": "{count} gefährliche(r) Mangel erfasst. Das Fahrzeug darf nicht am öffentlichen Verkehr teilnehmen.",
     "reopenTitle": "Diese Inspektion wieder öffnen?",

+ 2 - 0
messages/en/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Complete this inspection?",
     "completeBody": "The checks are locked once the inspection is completed, and the result becomes \"{result}\".",
     "completeBlocked": "{count} check(s) the checklist marks as mandatory are outstanding.",
+    "blockerMissingGrade": "must be graded",
+    "blockerNeedsPhoto": "needs a photo of the defect",
     "completeUngraded": "{count} check(s) have not been graded.",
     "completeDangerous": "{count} dangerous defect(s) recorded. The vehicle must not be used on the public road.",
     "reopenTitle": "Reopen this inspection?",

+ 2 - 0
messages/es/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "¿Cerrar esta inspección?",
     "completeBody": "Los puntos quedan bloqueados al cerrar, y el resultado pasa a ser «{result}».",
     "completeBlocked": "{count} comprobación(es) que la lista marca como obligatorias siguen pendientes.",
+    "blockerMissingGrade": "debe calificarse",
+    "blockerNeedsPhoto": "necesita una foto del defecto",
     "completeUngraded": "{count} punto(s) no se han calificado.",
     "completeDangerous": "{count} deficiencia(s) peligrosa(s) registrada(s). El vehículo no debe circular por la vía pública.",
     "reopenTitle": "¿Reabrir esta inspección?",

+ 2 - 0
messages/fr/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Clôturer cette inspection ?",
     "completeBody": "Les points sont verrouillés à la clôture, et le résultat devient « {result} ».",
     "completeBlocked": "{count} contrôle(s) que la liste marque comme obligatoires restent à faire.",
+    "blockerMissingGrade": "doit être évalué",
+    "blockerNeedsPhoto": "nécessite une photo du défaut",
     "completeUngraded": "{count} point(s) n'ont pas été évalués.",
     "completeDangerous": "{count} défaillance(s) critique(s) constatée(s). Le véhicule ne doit pas circuler sur la voie publique.",
     "reopenTitle": "Rouvrir cette inspection ?",

+ 2 - 0
messages/it/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Chiudere questa ispezione?",
     "completeBody": "I punti vengono bloccati alla chiusura e l'esito diventa «{result}».",
     "completeBlocked": "{count} controllo/i che la checklist segna come obbligatori sono ancora da fare.",
+    "blockerMissingGrade": "da valutare",
+    "blockerNeedsPhoto": "serve una foto del difetto",
     "completeUngraded": "{count} punto/i non sono stati valutati.",
     "completeDangerous": "{count} carenza/e pericolosa/e registrata/e. Il veicolo non deve circolare su strada pubblica.",
     "reopenTitle": "Riaprire questa ispezione?",

+ 2 - 0
messages/lt/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Užbaigti šią apžiūrą?",
     "completeBody": "Užbaigus punktai užrakinami, o rezultatas tampa „{result}“.",
     "completeBlocked": "{count} patikrinimas (-ai), kuriuos kontrolinis sąrašas žymi privalomais, dar neatlikti.",
+    "blockerMissingGrade": "turi būti įvertinta",
+    "blockerNeedsPhoto": "reikia defekto nuotraukos",
     "completeUngraded": "{count} punktas (-ai) neįvertinti.",
     "completeDangerous": "Užfiksuota pavojingų trūkumų: {count}. Transporto priemone važiuoti viešaisiais keliais draudžiama.",
     "reopenTitle": "Atverti šią apžiūrą iš naujo?",

+ 2 - 0
messages/nb/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Fullføre denne inspeksjonen?",
     "completeBody": "Punktene låses når inspeksjonen fullføres, og resultatet blir «{result}».",
     "completeBlocked": "{count} kontroll(er) som sjekklisten merker som obligatoriske gjenstår.",
+    "blockerMissingGrade": "må vurderes",
+    "blockerNeedsPhoto": "trenger bilde av mangelen",
     "completeUngraded": "{count} punkt(er) er ikke vurdert.",
     "completeDangerous": "{count} farlig(e) mangel(er) registrert. Kjøretøyet skal ikke brukes på offentlig vei.",
     "reopenTitle": "Gjenåpne denne inspeksjonen?",

+ 2 - 0
messages/nl/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Deze inspectie afronden?",
     "completeBody": "De punten worden bij afronding vergrendeld en de uitkomst wordt “{result}”.",
     "completeBlocked": "{count} controle(s) die de checklist als verplicht markeert, staan nog open.",
+    "blockerMissingGrade": "moet beoordeeld worden",
+    "blockerNeedsPhoto": "foto van het gebrek nodig",
     "completeUngraded": "{count} punt(en) zijn niet beoordeeld.",
     "completeDangerous": "{count} gevaarlijk(e) gebrek(en) vastgelegd. Het voertuig mag niet de openbare weg op.",
     "reopenTitle": "Deze inspectie heropenen?",

+ 2 - 0
messages/pl/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Zakończyć tę inspekcję?",
     "completeBody": "Pozycje zostają zablokowane po zakończeniu, a wynik staje się „{result}”.",
     "completeBlocked": "{count} pozycji, które lista kontrolna oznacza jako obowiązkowe, wciąż czeka.",
+    "blockerMissingGrade": "wymaga oceny",
+    "blockerNeedsPhoto": "wymaga zdjęcia usterki",
     "completeUngraded": "{count} pozycji nie zostało ocenionych.",
     "completeDangerous": "Zapisano {count} usterek stwarzających zagrożenie. Pojazdem nie wolno poruszać się po drogach publicznych.",
     "reopenTitle": "Otworzyć tę inspekcję ponownie?",

+ 2 - 0
messages/pt-BR/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Concluir esta inspeção?",
     "completeBody": "Os itens são travados na conclusão, e o resultado passa a ser “{result}”.",
     "completeBlocked": "{count} item(ns) que o checklist marca como obrigatórios ainda estão pendentes.",
+    "blockerMissingGrade": "precisa ser avaliado",
+    "blockerNeedsPhoto": "precisa de uma foto do defeito",
     "completeUngraded": "{count} item(ns) não foram classificados.",
     "completeDangerous": "{count} deficiência(s) perigosa(s) registrada(s). O veículo não deve circular em via pública.",
     "reopenTitle": "Reabrir esta inspeção?",

+ 2 - 0
messages/pt-PT/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Concluir esta inspeção?",
     "completeBody": "Os itens ficam bloqueados quando a inspeção é concluída, e o resultado passa a ser “{result}”.",
     "completeBlocked": "{count} item(ns) que a lista de verificação marca como obrigatórios continuam pendentes.",
+    "blockerMissingGrade": "tem de ser avaliado",
+    "blockerNeedsPhoto": "precisa de uma fotografia do defeito",
     "completeUngraded": "{count} item(ns) ainda não foram classificados.",
     "completeDangerous": "{count} deficiência(s) perigosa(s) registada(s). O veículo não deve circular na via pública.",
     "reopenTitle": "Reabrir esta inspeção?",

+ 2 - 0
messages/ru/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Завершить этот осмотр?",
     "completeBody": "После завершения пункты блокируются, а итог становится «{result}».",
     "completeBlocked": "Не выполнено пунктов, отмеченных в чек-листе как обязательные: {count}.",
+    "blockerMissingGrade": "нужна оценка",
+    "blockerNeedsPhoto": "нужно фото дефекта",
     "completeUngraded": "{count} пункт(ов) не оценены.",
     "completeDangerous": "Зафиксировано опасных неисправностей: {count}. Эксплуатация на дорогах общего пользования запрещена.",
     "reopenTitle": "Открыть этот осмотр заново?",

+ 2 - 0
messages/tr/inspections.json

@@ -95,6 +95,8 @@
     "completeTitle": "Bu muayene tamamlansın mı?",
     "completeBody": "Tamamlandığında maddeler kilitlenir ve sonuç “{result}” olur.",
     "completeBlocked": "Kontrol listesinin zorunlu olarak işaretlediği {count} kontrol henüz yapılmadı.",
+    "blockerMissingGrade": "değerlendirilmeli",
+    "blockerNeedsPhoto": "kusurun fotoğrafı gerekli",
     "completeUngraded": "{count} madde değerlendirilmedi.",
     "completeDangerous": "{count} tehlikeli kusur kaydedildi. Araç karayolunda kullanılmamalıdır.",
     "reopenTitle": "Bu muayene yeniden açılsın mı?",

+ 14 - 1
src/__tests__/app/settings/webhooks-dropped-connection.test.tsx

@@ -5,7 +5,16 @@
  * boundary and the whole settings page was replaced by the error page.
  */
 import { Component, type ReactNode } from 'react'
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import {
+  act,
+  fireEvent,
+  render as renderBare,
+  screen,
+  waitFor,
+  within,
+} from '@testing-library/react'
 import { toast } from 'sonner'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
@@ -36,6 +45,10 @@ vi.mock('@/features/webhooks/Actions/webhookActions', () => ({
 
 import { WebhooksSettings } from '@/app/(authenticated)/settings/webhooks/webhooks-settings'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 /** Stands in for the app's error page, so losing the page is visible. */
 class ErrorPage extends Component<{ children: ReactNode }, { failed: boolean }> {
   state = { failed: false }

+ 64 - 0
src/__tests__/app/settings/workshop-assign-confirm.test.tsx

@@ -0,0 +1,64 @@
+/**
+ * Picking a default technician offers to put them on every work order that
+ * has nobody. That rewrites many jobs at once, so the question opens on
+ * "No, skip": a stray Enter must not assign anyone.
+ */
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+
+// The picker is a popover Radix measures; jsdom has no ResizeObserver, and
+// nothing here needs measuring.
+// biome-ignore lint/suspicious/noEmptyBlockStatements: a stub that measures nothing
+const noop = () => {}
+vi.stubGlobal(
+  'ResizeObserver',
+  class {
+    observe = noop
+    unobserve = noop
+    disconnect = noop
+  }
+)
+Element.prototype.scrollIntoView = noop
+
+const assignTechToUnassignedWorkOrders = vi.fn()
+
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/settings/Actions/settingsActions', () => ({ setSettings: vi.fn() }))
+vi.mock('@/features/workboard/Actions/technicianActions', () => ({
+  assignTechToUnassignedWorkOrders: (id: string) => assignTechToUnassignedWorkOrders(id),
+  createTechnician: vi.fn(),
+}))
+
+import { WorkshopSettings } from '@/app/(authenticated)/settings/workshop/workshop-settings'
+
+describe('choosing a default technician', () => {
+  beforeEach(() => assignTechToUnassignedWorkOrders.mockReset())
+
+  it('asks before assigning everyone, with focus on skip', async () => {
+    render(<WorkshopSettings settings={{}} technicians={[{ id: 't1', name: 'Petter' }]} />, {
+      wrapper: ConfirmProvider,
+    })
+
+    // The picker shows "Search technician..." but, being a combobox, has no
+    // accessible name of its own.
+    const picker = screen
+      .getAllByRole('combobox')
+      .find((box) => box.textContent?.includes('Search technician...'))
+    if (!picker) throw new Error('technician picker not found')
+    fireEvent.click(picker)
+    fireEvent.click(await screen.findByRole('option', { name: 'Petter' }))
+
+    const dialog = await screen.findByRole('alertdialog', {
+      name: 'Assign to existing work orders?',
+    })
+    await waitFor(() =>
+      expect(within(dialog).getByRole('button', { name: 'No, skip' })).toHaveFocus()
+    )
+
+    fireEvent.click(within(dialog).getByRole('button', { name: 'No, skip' }))
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+    expect(assignTechToUnassignedWorkOrders).not.toHaveBeenCalled()
+  })
+})

+ 172 - 0
src/__tests__/app/vehicles/vehicle-detail-delete.test.tsx

@@ -0,0 +1,172 @@
+/**
+ * Deleting a vehicle from its page: the question is the shared confirmation
+ * dialog, it names the vehicle and its plate, opens on Cancel, and nothing is
+ * deleted until the red button is pressed.
+ */
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { render as renderBare, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+/** The page's query string: which list is showing. */
+const url = vi.hoisted(() => ({ query: '' }))
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }),
+  useSearchParams: () => new URLSearchParams(url.query),
+  usePathname: () => '/vehicles/v1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/vehicles/Actions/dismissMaintenance', () => ({
+  dismissMaintenance: vi.fn(),
+  undismissMaintenance: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({ createServiceRecord: vi.fn() }))
+vi.mock('@/features/vehicles/Actions/findingActions', () => ({ deleteFinding: vi.fn() }))
+vi.mock('@/features/vehicles/Actions/noteActions', () => ({
+  deleteNote: vi.fn(),
+  toggleNotePin: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/reminderActions', () => ({
+  toggleReminder: vi.fn(),
+  deleteReminder: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/unarchiveVehicle', () => ({ unarchiveVehicle: vi.fn() }))
+vi.mock('@/features/vehicles/Actions/deleteVehicle', () => ({ deleteVehicle: vi.fn() }))
+vi.mock('@/features/ai/Actions/aiActions', () => ({
+  aiSummarizeVehicleHistory: vi.fn(),
+  aiGetCommonIssues: vi.fn(),
+  aiClearMessage: vi.fn(),
+}))
+// Screens and dialogs of their own.
+// The edit form hands its Delete button to the page, which asks the question.
+vi.mock('@/features/vehicles/Components/VehicleForm', () => ({
+  VehicleForm: ({ onDelete }: { onDelete?: () => void }) => (
+    <button type="button" onClick={onDelete}>
+      Delete from the edit form
+    </button>
+  ),
+}))
+vi.mock('@/features/vehicles/Components/NoteForm', () => ({ NoteForm: () => null }))
+vi.mock('@/features/vehicles/Components/ReminderForm', () => ({ ReminderForm: () => null }))
+vi.mock('@/features/vehicles/Components/FindingForm', () => ({ FindingForm: () => null }))
+vi.mock('@/features/vehicles/Components/VehicleSafetyPanel', () => ({
+  VehicleSafetyPanel: () => null,
+}))
+vi.mock('@/features/vehicles/Components/ArchiveVehicleDialog', () => ({
+  ArchiveVehicleDialog: () => null,
+}))
+vi.mock('@/features/tire-hotel/Components/VehicleTireSets', () => ({ VehicleTireSets: () => null }))
+vi.mock('@/features/ai/Components/AskAiSheet', () => ({ AskAiSheet: () => null }))
+vi.mock('@/features/inspections/Components/NewInspectionDialog', () => ({
+  NewInspectionDialog: () => null,
+}))
+vi.mock('@/features/quotes/Components/NewQuoteDialog', () => ({ NewQuoteDialog: () => null }))
+vi.mock('@/app/(authenticated)/vehicles/[id]/vehicle-activity-feed', () => ({
+  VehicleActivityFeed: () => null,
+}))
+vi.mock('@/app/(authenticated)/vehicles/[id]/notes-table', () => ({ NotesTable: () => null }))
+vi.mock('@/app/(authenticated)/vehicles/[id]/findings-table', () => ({ FindingsTable: () => null }))
+
+import { VehicleDetailClient } from '@/app/(authenticated)/vehicles/[id]/vehicle-detail-client'
+import { deleteVehicle } from '@/features/vehicles/Actions/deleteVehicle'
+
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
+const VEHICLE = {
+  id: 'v1',
+  make: 'Volvo',
+  model: 'V70',
+  year: 2019,
+  vin: null,
+  licensePlate: 'EL12345',
+  color: null,
+  mileage: 120000,
+  fuelType: null,
+  transmission: null,
+  engineSize: null,
+  engineCode: null,
+  hsn: null,
+  tsn: null,
+  purchaseDate: null,
+  purchasePrice: null,
+  imageUrl: null,
+  isArchived: false,
+  archiveReason: null,
+  customerId: null,
+  customer: null,
+  serviceRecords: [],
+  reminders: [],
+  aiMessages: [],
+  _count: { serviceRecords: 0, notes: 0, reminders: 0, findings: 0 },
+}
+
+const empty = { records: [], total: 0, page: 1, pageSize: 20, totalPages: 0 }
+
+function renderPage(vehicle = VEHICLE) {
+  render(
+    <VehicleDetailClient
+      vehicle={vehicle}
+      paginatedServices={empty}
+      paginatedNotes={empty}
+      paginatedFindings={empty}
+      serviceSearch=""
+      serviceRecordType=""
+      unitSystem="metric"
+      predictionData={null}
+    />
+  )
+}
+
+beforeEach(() => {
+  vi.mocked(deleteVehicle).mockReset()
+  vi.mocked(deleteVehicle).mockResolvedValue({ success: true })
+})
+
+async function askToDelete() {
+  const user = userEvent.setup({ pointerEventsCheck: 0 })
+  renderPage()
+  await user.click(screen.getByRole('button', { name: 'Delete from the edit form' }))
+  const question = await screen.findByRole('alertdialog', { name: 'Delete vehicle?' })
+  return { user, question }
+}
+
+describe('deleting a vehicle from its page', () => {
+  it('asks in the shared confirmation dialog and names the vehicle and its plate', async () => {
+    const { question } = await askToDelete()
+
+    expect(question).toHaveAttribute('data-slot', 'confirm-dialog')
+    expect(question).toHaveAttribute('data-tone', 'destructive')
+    expect(
+      within(question).getByText(
+        'This will permanently delete 2019 Volvo V70 and all associated service records, notes, and reminders. This action cannot be undone.'
+      )
+    ).toBeInTheDocument()
+    const row = within(question).getByRole('listitem')
+    expect(row).toHaveTextContent('2019 Volvo V70')
+    expect(row).toHaveTextContent('EL12345')
+    expect(deleteVehicle).not.toHaveBeenCalled()
+  })
+
+  it('opens on Cancel, so Enter keeps the vehicle', async () => {
+    const { user, question } = await askToDelete()
+
+    expect(within(question).getByRole('button', { name: 'Cancel' })).toHaveFocus()
+    await user.keyboard('{Enter}')
+
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())
+    expect(deleteVehicle).not.toHaveBeenCalled()
+  })
+
+  it('deletes the vehicle once Delete is pressed', async () => {
+    const { user, question } = await askToDelete()
+
+    await user.click(within(question).getByRole('button', { name: 'Delete' }))
+
+    await waitFor(() => expect(deleteVehicle).toHaveBeenCalledWith('v1'))
+    expect(screen.queryByRole('alertdialog')).toBeNull()
+  })
+})

+ 7 - 1
src/__tests__/app/vehicles/vehicle-detail-dropped-connection.test.tsx

@@ -11,7 +11,9 @@
  * made on a dropped connection left the button busy.
  */
 import { Component, type ReactNode } from 'react'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { act, fireEvent, render as renderBare, screen, waitFor } from '@testing-library/react'
 import { toast } from 'sonner'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 import { GlassModal, useGlassModal } from '@/components/glass-modal'
@@ -99,6 +101,10 @@ vi.mock('@/app/(authenticated)/vehicles/[id]/findings-table', () => ({
 
 import { VehicleDetailClient } from '@/app/(authenticated)/vehicles/[id]/vehicle-detail-client'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 /** Stands in for the app's error page, so losing the page is visible. */
 class ErrorPage extends Component<{ children: ReactNode }, { failed: boolean }> {
   state = { failed: false }

+ 7 - 1
src/__tests__/app/vehicles/vehicle-detail-new-work-order.test.tsx

@@ -5,7 +5,9 @@
  * same button adds one of those, so there is one place to add from and never
  * a second button under it. An archived vehicle offers neither.
  */
-import { fireEvent, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { fireEvent, render as renderBare, screen } from '@testing-library/react'
 import { afterEach, describe, expect, it, vi } from 'vitest'
 
 /** The page's query string: which list is showing. */
@@ -63,6 +65,10 @@ vi.mock('@/app/(authenticated)/vehicles/[id]/findings-table', () => ({ FindingsT
 
 import { VehicleDetailClient } from '@/app/(authenticated)/vehicles/[id]/vehicle-detail-client'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const VEHICLE = {
   id: 'v1',
   make: 'Volvo',

+ 53 - 1
src/__tests__/components/confirm-dialog.test.tsx

@@ -2,7 +2,15 @@ import { createEvent, fireEvent, render, screen, waitFor, within } from '@testin
 import userEvent from '@testing-library/user-event'
 import { Building2 } from 'lucide-react'
 import { describe, expect, it, vi } from 'vitest'
-import { type ConfirmOptions, ConfirmProvider, useConfirm } from '@/components/confirm-dialog'
+import {
+  type ConfirmOptions,
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+  ConfirmProvider,
+  useConfirm,
+} from '@/components/confirm-dialog'
 
 /**
  * The shared confirmation dialog, as someone at a keyboard or on a phone
@@ -257,3 +265,47 @@ describe('confirm dialog: phone sheet', () => {
     expect(screen.getByRole('alertdialog')).toBeInTheDocument()
   })
 })
+
+describe('confirm frame: a prompt that is more than a question', () => {
+  function Upgrade({ ready, onDismiss }: { ready: boolean; onDismiss: () => void }) {
+    return (
+      <ConfirmFrame
+        open
+        onDismiss={onDismiss}
+        title="Upgrade to Enterprise?"
+        footer={
+          <>
+            <ConfirmFrameCancel>Cancel</ConfirmFrameCancel>
+            <ConfirmFrameAction disabled={!ready}>Upgrade now</ConfirmFrameAction>
+          </>
+        }
+      >
+        <ConfirmFrameText>
+          <p>{ready ? 'Amount due today: USD 50.00' : 'Calculating cost...'}</p>
+        </ConfirmFrameText>
+      </ConfirmFrame>
+    )
+  }
+
+  it('draws the same dialog, keeps its action asleep until it is ready, and opens on Cancel', () => {
+    const { rerender } = render(<Upgrade ready={false} onDismiss={vi.fn()} />)
+
+    const dialog = screen.getByRole('alertdialog', { name: 'Upgrade to Enterprise?' })
+    expect(dialog).toHaveAttribute('data-slot', 'confirm-dialog')
+    expect(dialog).toHaveAccessibleDescription('Calculating cost...')
+    expect(within(dialog).getByRole('button', { name: 'Cancel' })).toHaveFocus()
+    expect(within(dialog).getByRole('button', { name: 'Upgrade now' })).toBeDisabled()
+
+    rerender(<Upgrade ready onDismiss={vi.fn()} />)
+    expect(within(dialog).getByRole('button', { name: 'Upgrade now' })).toBeEnabled()
+  })
+
+  it('takes Escape as the safe answer', async () => {
+    const onDismiss = vi.fn()
+    const user = userEvent.setup({ pointerEventsCheck: 0 })
+    render(<Upgrade ready onDismiss={onDismiss} />)
+
+    await user.keyboard('{Escape}')
+    expect(onDismiss).toHaveBeenCalled()
+  })
+})

+ 24 - 12
src/__tests__/features/auth/passkey-settings.test.tsx

@@ -1,9 +1,13 @@
 import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, waitFor } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { render as renderBare, screen, waitFor, within } from '@testing-library/react'
 import userEvent from '@testing-library/user-event'
 
 // Mock lucide-react icons
-vi.mock('lucide-react', () => ({
+vi.mock('lucide-react', async (importOriginal) => ({
+  // The confirm dialog draws its own icons; the page's are stubbed below.
+  ...(await importOriginal<typeof import('lucide-react')>()),
   Fingerprint: () => <svg data-testid="icon-fingerprint" />,
   Loader2: () => <svg data-testid="icon-loader" />,
   LogIn: () => <svg data-testid="icon-log-in" />,
@@ -113,6 +117,10 @@ vi.mock('@/lib/auth-client', () => ({
 
 import { PasskeySettings } from '@/features/settings/Components/passkey-settings'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const MOCK_PASSKEY = {
   id: 'pk_1',
   name: 'MacBook Pro',
@@ -391,11 +399,13 @@ describe('PasskeySettings', () => {
       })
 
       // Click the "Delete" button in dialog
-      const deleteButtons = screen.getAllByText('Delete')
-      const confirmButton = deleteButtons.find(
-        (btn) => btn.closest("[data-testid='dialog']") !== null
-      )
-      await userEvent.click(confirmButton!)
+      // The question names the passkey it is about to remove.
+      const question = screen.getByRole('alertdialog')
+      expect(within(question).getByText('MacBook Pro')).toBeInTheDocument()
+      // The Button stub above wraps the real action in a second button; the
+      // inner one is the one that answers.
+      const answers = within(question).getAllByRole('button', { name: 'Delete' })
+      await userEvent.click(answers[answers.length - 1])
 
       await waitFor(() => {
         expect(mockDeletePasskey).toHaveBeenCalledWith({ id: 'pk_1' })
@@ -421,11 +431,13 @@ describe('PasskeySettings', () => {
         ).toBeInTheDocument()
       })
 
-      const deleteButtons = screen.getAllByText('Delete')
-      const confirmButton = deleteButtons.find(
-        (btn) => btn.closest("[data-testid='dialog']") !== null
-      )
-      await userEvent.click(confirmButton!)
+      // The question names the passkey it is about to remove.
+      const question = screen.getByRole('alertdialog')
+      expect(within(question).getByText('MacBook Pro')).toBeInTheDocument()
+      // The Button stub above wraps the real action in a second button; the
+      // inner one is the one that answers.
+      const answers = within(question).getAllByRole('button', { name: 'Delete' })
+      await userEvent.click(answers[answers.length - 1])
 
       await waitFor(() => {
         expect(mockToastError).toHaveBeenCalledWith('Failed to delete passkey')

+ 7 - 1
src/__tests__/features/condition-map/keyboard-marks.test.tsx

@@ -4,7 +4,9 @@
  * nudged with the arrow keys once focused on the drawing. Marks from an
  * earlier visit stay where they are, as they do under a pointer.
  */
-import { act, render, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { act, render as renderBare, screen, waitFor, within } from '@testing-library/react'
 import userEvent from '@testing-library/user-event'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
@@ -46,6 +48,10 @@ import { builtinMarkTypes } from '@/features/condition-map/Lib/markTypes'
 import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
 import { panelSpots } from '@/features/condition-map/Lib/panelSpots'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const TYPES = builtinMarkTypes({ dent: 'Dent', scratch: 'Scratch' })
 
 const mark = (over: Partial<ConditionMarkData>): ConditionMarkData => ({

+ 14 - 1
src/__tests__/features/condition-map/mark-change-failure.test.tsx

@@ -9,7 +9,16 @@
  * fails beside another that went through has the card read back from the
  * server rather than undo the other.
  */
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import {
+  act,
+  fireEvent,
+  render as renderBare,
+  screen,
+  waitFor,
+  within,
+} from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 const updateConditionMark = vi.fn()
@@ -41,6 +50,10 @@ import { ConditionMapCard } from '@/features/condition-map/Components/ConditionM
 import { builtinMarkTypes } from '@/features/condition-map/Lib/markTypes'
 import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const TYPES = builtinMarkTypes({ dent: 'Dent', scratch: 'Scratch' })
 
 const mark = (overrides: Partial<ConditionMarkData>): ConditionMarkData => ({

+ 7 - 1
src/__tests__/features/condition-map/remove-mark.test.tsx

@@ -4,7 +4,9 @@
  * so. A request that never reached the server used to throw inside the card's
  * transition, which replaced the whole page with the error page.
  */
-import { act, fireEvent, render, screen, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { act, fireEvent, render as renderBare, screen, within } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 const removeConditionMark = vi.fn()
@@ -33,6 +35,10 @@ import { ConditionMapCard } from '@/features/condition-map/Components/ConditionM
 import { builtinMarkTypes } from '@/features/condition-map/Lib/markTypes'
 import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const TYPES = builtinMarkTypes({ dent: 'Dent', scratch: 'Scratch' })
 
 const MARKS: ConditionMarkData[] = [

+ 55 - 0
src/__tests__/features/import/import-undo-confirm.test.tsx

@@ -0,0 +1,55 @@
+/**
+ * Undoing an import deletes the customers, vehicles and jobs it created, so
+ * the question reads as a delete: a red button, and focus on Cancel so a
+ * stray Enter does not remove anything.
+ */
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+
+const undoImportBatch = vi.fn()
+
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/import/Actions/importActions', () => ({
+  listImportBatches: async () => ({
+    success: true,
+    data: [
+      {
+        id: 'b1',
+        entity: 'customers',
+        fileName: 'customers-2026.csv',
+        status: 'completed',
+        createdAt: new Date('2026-11-01T10:00:00Z'),
+        created: 3,
+        updated: 0,
+        skipped: 0,
+        failed: 0,
+        attached: { customers: 3, vehicles: 2, serviceRecords: 1 },
+      },
+    ],
+  }),
+  undoImportBatch: (id: string) => undoImportBatch(id),
+}))
+
+import { ImportHistoryCard } from '@/features/import/Components/ImportHistoryCard'
+
+describe('undoing an import', () => {
+  beforeEach(() => undoImportBatch.mockReset())
+
+  it('asks like a delete and opens on Cancel', async () => {
+    render(<ImportHistoryCard />, { wrapper: ConfirmProvider })
+    fireEvent.click(await screen.findByRole('button', { name: 'Undo' }))
+
+    const dialog = await screen.findByRole('alertdialog', { name: 'Undo this import?' })
+    const confirm = within(dialog).getByRole('button', { name: 'Undo import' })
+    expect(confirm).toHaveAttribute('data-variant', 'destructive')
+    await waitFor(() =>
+      expect(within(dialog).getByRole('button', { name: 'Cancel' })).toHaveFocus()
+    )
+
+    fireEvent.keyDown(document.activeElement ?? dialog, { key: 'Escape' })
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+    expect(undoImportBatch).not.toHaveBeenCalled()
+  })
+})

+ 7 - 1
src/__tests__/features/inspections/checklist-translate-banner.test.tsx

@@ -1,5 +1,7 @@
 import { describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { render as renderBare, screen, fireEvent, waitFor } from '@testing-library/react'
 
 const translateChecklists = vi.fn()
 
@@ -22,6 +24,10 @@ vi.mock('@/features/inspections/Actions/packageActions', () => ({
 
 import { TemplateListClient } from '@/features/inspections/Components/TemplateListClient'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const TEMPLATE = {
   id: 't1',
   name: 'Norway — EU-kontroll',

+ 7 - 1
src/__tests__/features/inspections/item-photo-remove.test.tsx

@@ -5,7 +5,9 @@
  * connection it used to stay gone until the page was reloaded, where it was
  * back as if nothing had been pressed.
  */
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { act, fireEvent, render as renderBare, screen } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 const removeInspectionItemMedia = vi.fn()
@@ -28,6 +30,10 @@ vi.mock('@/features/vehicles/Components/service-page/PhotoHandoffButton', () =>
 
 import { InspectionItemRow } from '@/features/inspections/Components/InspectionItemRow'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const ITEM = {
   id: 'tyres',
   name: 'Tyres',

+ 7 - 1
src/__tests__/features/inspections/quote-requested-marker.test.tsx

@@ -3,7 +3,9 @@
  * a technician scrolling the sections sees the request without opening the
  * card above.
  */
-import { render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { render as renderBare, screen } from '@testing-library/react'
 import { describe, expect, it, vi } from 'vitest'
 
 vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
@@ -21,6 +23,10 @@ vi.mock('@/features/vehicles/Components/service-page/PhotoHandoffButton', () =>
 
 import { InspectionItemRow } from '@/features/inspections/Components/InspectionItemRow'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const ITEM = {
   id: 'tyres',
   name: 'Tyres',

+ 14 - 1
src/__tests__/features/inspections/template-list-dropped-connection.test.tsx

@@ -5,7 +5,16 @@
  * boundary and the whole page was replaced by the error page.
  */
 import { Component, type ReactNode } from 'react'
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import {
+  act,
+  fireEvent,
+  render as renderBare,
+  screen,
+  waitFor,
+  within,
+} from '@testing-library/react'
 import { toast } from 'sonner'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
@@ -39,6 +48,10 @@ vi.mock('@/features/inspections/Actions/packageActions', () => ({
 
 import { TemplateListClient } from '@/features/inspections/Components/TemplateListClient'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 /** Stands in for the app's error page, so losing the page is visible. */
 class ErrorPage extends Component<{ children: ReactNode }, { failed: boolean }> {
   state = { failed: false }

+ 5 - 1
src/__tests__/features/leaving/quote-saves-before-leaving.test.tsx

@@ -21,7 +21,11 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: (m: string) => toas
 vi.mock('@/components/glass-modal', () => ({
   useGlassModal: () => ({ open: (...args: unknown[]) => modalOpen(...args) }),
 }))
-vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn(async () => true) }))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  // The leave prompt draws itself with the real frame; only the question is stubbed.
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
 const updateQuote = vi.fn()
 vi.mock('@/features/quotes/Actions/quoteActions', () => ({
   updateQuote: (input: unknown) => updateQuote(input),

+ 14 - 1
src/__tests__/features/sms/sms-conversation-dropped-connection.test.tsx

@@ -7,7 +7,16 @@
  * reloaded, and said nothing.
  */
 import { Component, type ReactNode } from 'react'
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import {
+  act,
+  fireEvent,
+  render as renderBare,
+  screen,
+  waitFor,
+  within,
+} from '@testing-library/react'
 import { toast } from 'sonner'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
@@ -31,6 +40,10 @@ vi.mock('@/features/sms/Components/SmsTemplateMenu', () => ({ SmsTemplateMenu: (
 
 import { SmsConversation } from '@/features/sms/Components/SmsConversation'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 /** Stands in for the app's error page, so losing the page is visible. */
 class ErrorPage extends Component<{ children: ReactNode }, { failed: boolean }> {
   state = { failed: false }

+ 7 - 1
src/__tests__/features/telegram/telegram-thread-switch.test.tsx

@@ -4,7 +4,9 @@
  * new customer's selection, with a composer that sends to the new customer.
  * An answer for an earlier pick that arrives late is dropped as well.
  */
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+import { act, fireEvent, render as renderBare, screen } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 const getTelegramConversation = vi.fn()
@@ -52,6 +54,10 @@ vi.mock('@/features/telegram/Components/TelegramConversation', () => ({
 
 import { TelegramMessagesClient } from '@/features/telegram/Components/TelegramMessagesClient'
 
+// The screen asks its questions through the shared confirm dialog, so every
+// render sits inside its provider, as the app's layout does.
+const render = (ui: ReactElement) => renderBare(ui, { wrapper: ConfirmProvider })
+
 const thread = (customerId: string, customerName: string) => ({
   customerId,
   customerName,

+ 40 - 63
src/app/(authenticated)/settings/webhooks/webhooks-settings.tsx

@@ -4,6 +4,7 @@ import { useEffect, useMemo, useState, useTransition } from 'react'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { toast } from 'sonner'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Card, CardContent } from '@/components/ui/card'
 import { Input } from '@/components/ui/input'
@@ -253,8 +254,7 @@ function WebhookRow({
 }) {
   const t = useTranslations('settings.webhooks')
   const [isPending, startTransition] = useTransition()
-  const [confirmDelete, setConfirmDelete] = useState(false)
-  const [confirmRotate, setConfirmRotate] = useState(false)
+  const confirm = useConfirm()
   const [rotated, setRotated] = useState<string | null>(null)
   const [urlCopied, setUrlCopied] = useState(false)
 
@@ -288,28 +288,45 @@ function WebhookRow({
       }
     })
 
-  const handleDelete = () =>
+  const handleDelete = async () => {
+    const ok = await confirm({
+      title: t('confirmDeleteTitle'),
+      description: t('confirmDeleteDescription', { name: webhook.name }),
+      confirmLabel: t('delete'),
+      cancelLabel: t('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     startTransition(async () => {
       const r = await deleteWebhook(webhook.id).catch(() => null)
       if (r?.success) {
         toast.success(t('deleted'))
-        setConfirmDelete(false)
         onRefresh()
       } else {
         toast.error(r?.error || t('deleteFailed'))
       }
     })
+  }
 
-  const handleRotate = () =>
+  const handleRotate = async () => {
+    const ok = await confirm({
+      title: t('confirmRotateTitle'),
+      description: t('confirmRotateDescription'),
+      confirmLabel: t('rotate'),
+      cancelLabel: t('cancel'),
+      icon: RefreshCw,
+    })
+    if (!ok) return
     startTransition(async () => {
       const r = await rotateWebhookSecret(webhook.id).catch(() => null)
       if (r?.success && r.data) {
         setRotated(r.data.secret)
-        setConfirmRotate(false)
       } else {
         toast.error(r?.error || t('rotateFailed'))
       }
     })
+  }
 
   const status = webhook.autoDisabled
     ? 'auto_disabled'
@@ -448,7 +465,7 @@ function WebhookRow({
                 <Button
                   variant="outline"
                   size="sm"
-                  onClick={() => setConfirmRotate(true)}
+                  onClick={handleRotate}
                   disabled={isPending}
                   title={t('rotateSecret')}
                 >
@@ -457,7 +474,7 @@ function WebhookRow({
                 <Button
                   variant="outline"
                   size="sm"
-                  onClick={() => setConfirmDelete(true)}
+                  onClick={handleDelete}
                   disabled={isPending}
                   className="text-red-600 hover:text-red-700"
                 >
@@ -469,71 +486,31 @@ function WebhookRow({
         </div>
       </CardContent>
 
-      <Dialog open={confirmDelete} onOpenChange={setConfirmDelete}>
-        <DialogContent>
-          <DialogHeader>
-            <DialogTitle>{t('confirmDeleteTitle')}</DialogTitle>
-            <DialogDescription>
-              {t('confirmDeleteDescription', { name: webhook.name })}
-            </DialogDescription>
-          </DialogHeader>
-          <DialogFooter>
-            <Button variant="outline" onClick={() => setConfirmDelete(false)} disabled={isPending}>
-              {t('cancel')}
-            </Button>
-            <Button variant="destructive" onClick={handleDelete} disabled={isPending}>
-              {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {t('delete')}
-            </Button>
-          </DialogFooter>
-        </DialogContent>
-      </Dialog>
-
+      {/* The new secret, shown once after the rotation was confirmed. */}
       <Dialog
-        open={confirmRotate || !!rotated}
+        open={!!rotated}
         onOpenChange={(open) => {
-          if (!open) {
-            setConfirmRotate(false)
-            if (rotated) {
-              setRotated(null)
-              onRefresh()
-            }
+          if (!open && rotated) {
+            setRotated(null)
+            onRefresh()
           }
         }}
       >
         <DialogContent>
           <DialogHeader>
-            <DialogTitle>{rotated ? t('secretRotated') : t('confirmRotateTitle')}</DialogTitle>
-            <DialogDescription>
-              {rotated ? t('secretRotatedDescription') : t('confirmRotateDescription')}
-            </DialogDescription>
+            <DialogTitle>{t('secretRotated')}</DialogTitle>
+            <DialogDescription>{t('secretRotatedDescription')}</DialogDescription>
           </DialogHeader>
           {rotated && <SecretBlock value={rotated} />}
           <DialogFooter>
-            {rotated ? (
-              <Button
-                onClick={() => {
-                  setRotated(null)
-                  onRefresh()
-                }}
-              >
-                {t('done')}
-              </Button>
-            ) : (
-              <>
-                <Button
-                  variant="outline"
-                  onClick={() => setConfirmRotate(false)}
-                  disabled={isPending}
-                >
-                  {t('cancel')}
-                </Button>
-                <Button onClick={handleRotate} disabled={isPending}>
-                  {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-                  {t('rotate')}
-                </Button>
-              </>
-            )}
+            <Button
+              onClick={() => {
+                setRotated(null)
+                onRefresh()
+              }}
+            >
+              {t('done')}
+            </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

+ 16 - 50
src/app/(authenticated)/settings/workshop/workshop-settings.tsx

@@ -8,6 +8,7 @@ import { UnitCombobox } from '@/features/inventory/Components/UnitCombobox'
 import { AppCard } from '@/components/app-card'
 import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Separator } from '@/components/ui/separator'
 import { Switch } from '@/components/ui/switch'
@@ -21,16 +22,6 @@ import {
   CommandList,
   CommandSeparator,
 } from '@/components/ui/command'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { toast } from 'sonner'
 import { setSettings } from '@/features/settings/Actions/settingsActions'
 import { type EngineSizeUnit, engineSizeUnitOf } from '@/lib/engine-size'
@@ -97,9 +88,7 @@ export function WorkshopSettings({
   const [creatingTech, setCreatingTech] = useState(false)
   const [showNewInput, setShowNewInput] = useState(false)
   const [newTechName, setNewTechName] = useState('')
-  const [showAssignDialog, setShowAssignDialog] = useState(false)
-  const [pendingTechId, setPendingTechId] = useState<string | null>(null)
-  const [assigning, setAssigning] = useState(false)
+  const confirm = useConfirm()
   const [defaultLaborRate, setDefaultLaborRate] = useState(
     settings[SETTING_KEYS.DEFAULT_LABOR_RATE] || ''
   )
@@ -153,19 +142,22 @@ export function WorkshopSettings({
   const handleTechSelect = (techId: string) => {
     setDefaultTechnicianId(techId)
     setTechOpen(false)
-    if (techId) {
-      setPendingTechId(techId)
-      setShowAssignDialog(true)
-    }
+    if (techId) handleAssignUnassigned(techId)
   }
 
-  const handleAssignUnassigned = async () => {
-    if (!pendingTechId) return
-    setAssigning(true)
-    const result = await assignTechToUnassignedWorkOrders(pendingTechId)
-    setAssigning(false)
-    setShowAssignDialog(false)
-    setPendingTechId(null)
+  const handleAssignUnassigned = async (techId: string) => {
+    const ok = await confirm({
+      title: t('workshop.assignDialogTitle'),
+      description: t('workshop.assignDialogDescription', {
+        name: technicians.find((tech) => tech.id === techId)?.name || '',
+      }),
+      confirmLabel: t('workshop.assignDialogConfirm'),
+      cancelLabel: t('workshop.assignDialogSkip'),
+      // It rewrites every unassigned work order, so Enter must not do it.
+      defaultFocus: 'cancel',
+    })
+    if (!ok) return
+    const result = await assignTechToUnassignedWorkOrders(techId)
     if (result.success && result.data) {
       toast.success(t('workshop.assignedUnassigned', { count: result.data.updated }))
     } else {
@@ -591,32 +583,6 @@ export function WorkshopSettings({
           </SaveButton>
         </AppCard>
       </ReadOnlyWrapper>
-
-      <AlertDialog
-        open={showAssignDialog}
-        onOpenChange={(open) => {
-          if (!open) setPendingTechId(null)
-          setShowAssignDialog(open)
-        }}
-      >
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('workshop.assignDialogTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {t('workshop.assignDialogDescription', {
-                name: technicians.find((tech) => tech.id === pendingTechId)?.name || '',
-              })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('workshop.assignDialogSkip')}</AlertDialogCancel>
-            <AlertDialogAction onClick={handleAssignUnassigned} disabled={assigning}>
-              {assigning && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {t('workshop.assignDialogConfirm')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 17 - 35
src/app/(authenticated)/vehicles/[id]/_classic/vehicle-detail-classic.tsx

@@ -75,6 +75,7 @@ import {
   Pencil,
   Pin,
   Plus,
+  Ship,
   StickyNote,
   Trash2,
   TrendingUp,
@@ -91,18 +92,9 @@ import {
   DropdownMenuSeparator,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { useTranslations } from 'next-intl'
 import { quoteStatusLabel } from '@/features/quotes/Lib/quoteStatus'
+import { useConfirm } from '@/components/confirm-dialog'
 import { useServiceType } from '@/components/service-type-context'
 import { formatTypeKey } from '@/features/vehicles/Lib/typeKey'
 import { useTypeKeyEnabled } from '@/components/type-key-context'
@@ -336,6 +328,7 @@ export function VehicleDetailClassic({
   const ti = useTranslations('vehicles.inspections')
   const tr = useTranslations('vehicles.reminders')
   const tc = useTranslations('common.buttons')
+  const confirm = useConfirm()
 
   const tq = useTranslations('vehicles.quotes')
   const tQuoteStatus = useTranslations('quotes.statusLabels')
@@ -387,7 +380,6 @@ export function VehicleDetailClassic({
   const [selectedNote, setSelectedNote] = useState<PaginatedNotes['records'][number] | null>(null)
   const [showArchiveDialog, setShowArchiveDialog] = useState(false)
   const [showNewQuoteDialog, setShowNewQuoteDialog] = useState(false)
-  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
   const [showNewInspection, setShowNewInspection] = useState(false)
   const [isDismissPending, startDismissTransition] = useTransition()
   const [aiSummaryLoading, setAiSummaryLoading] = useState(false)
@@ -585,6 +577,18 @@ export function VehicleDetailClassic({
   }
 
   const handleDelete = async () => {
+    const name = `${vehicle.year} ${vehicle.make} ${vehicle.model}`
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription', { name }),
+      subject: [
+        { label: name, detail: vehicle.licensePlate ?? undefined, icon: isMarine ? Ship : Car },
+      ],
+      confirmLabel: tc('delete'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     const result = await deleteVehicle(vehicle.id)
     if (result.success) {
       toast.success(t('vehicleDeleted'))
@@ -661,10 +665,7 @@ export function VehicleDetailClassic({
                   </DropdownMenuItem>
                 )}
                 <DropdownMenuSeparator />
-                <DropdownMenuItem
-                  className="text-destructive"
-                  onClick={() => setShowDeleteDialog(true)}
-                >
+                <DropdownMenuItem className="text-destructive" onClick={handleDelete}>
                   <Trash2 className="mr-2 h-4 w-4" />
                   {t('delete')}
                 </DropdownMenuItem>
@@ -1766,7 +1767,7 @@ export function VehicleDetailClassic({
         // The page's own confirmation does the deleting.
         onDelete={() => {
           setShowEditForm(false)
-          setShowDeleteDialog(true)
+          handleDelete()
         }}
       />
       <NoteForm
@@ -1837,25 +1838,6 @@ export function VehicleDetailClassic({
         vehicleId={vehicle.id}
         vehicleName={`${vehicle.year} ${vehicle.make} ${vehicle.model}`}
       />
-      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {t('deleteDescription', { name: `${vehicle.year} ${vehicle.make} ${vehicle.model}` })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDelete}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
 
       {/* Image lightbox */}
       {showImage && vehicle.imageUrl && (

+ 14 - 35
src/app/(authenticated)/vehicles/[id]/vehicle-detail-client.tsx

@@ -88,17 +88,8 @@ import {
   DropdownMenuSeparator,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { useFormatter, useTranslations } from 'next-intl'
+import { useConfirm } from '@/components/confirm-dialog'
 import { useServiceType } from '@/components/service-type-context'
 import { formatTypeKey } from '@/features/vehicles/Lib/typeKey'
 import { useTypeKeyEnabled } from '@/components/type-key-context'
@@ -428,6 +419,7 @@ export function VehicleDetailClient({
   const ti = useTranslations('vehicles.inspections')
   const tr = useTranslations('vehicles.reminders')
   const tc = useTranslations('common.buttons')
+  const confirm = useConfirm()
 
   const tq = useTranslations('vehicles.quotes')
   const tQuoteStatus = useTranslations('quotes.statusLabels')
@@ -505,7 +497,6 @@ export function VehicleDetailClient({
   const [selectedNote, setSelectedNote] = useState<PaginatedNotes['records'][number] | null>(null)
   const [showArchiveDialog, setShowArchiveDialog] = useState(false)
   const [showNewQuoteDialog, setShowNewQuoteDialog] = useState(false)
-  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
   const [showNewInspection, setShowNewInspection] = useState(false)
   const [isDismissPending, startDismissTransition] = useTransition()
   const [aiSummaryLoading, setAiSummaryLoading] = useState(false)
@@ -878,6 +869,16 @@ export function VehicleDetailClient({
   }
 
   const handleDelete = async () => {
+    const name = `${vehicle.year} ${vehicle.make} ${vehicle.model}`
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription', { name }),
+      subject: [{ label: name, detail: vehicle.licensePlate ?? undefined, icon: VehicleIcon }],
+      confirmLabel: tc('delete'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     const result = await deleteVehicle(vehicle.id)
     if (result.success) {
       toast.success(t('vehicleDeleted'))
@@ -1081,10 +1082,7 @@ export function VehicleDetailClient({
                             </DropdownMenuItem>
                           )}
                           <DropdownMenuSeparator />
-                          <DropdownMenuItem
-                            className="text-destructive"
-                            onClick={() => setShowDeleteDialog(true)}
-                          >
+                          <DropdownMenuItem className="text-destructive" onClick={handleDelete}>
                             <Trash2 className="mr-2 h-4 w-4" />
                             {t('delete')}
                           </DropdownMenuItem>
@@ -2388,7 +2386,7 @@ export function VehicleDetailClient({
         // The page's own confirmation does the deleting.
         onDelete={() => {
           setShowEditForm(false)
-          setShowDeleteDialog(true)
+          handleDelete()
         }}
       />
       <NoteForm
@@ -2486,25 +2484,6 @@ export function VehicleDetailClient({
         vehicleId={vehicle.id}
         vehicleName={`${vehicle.year} ${vehicle.make} ${vehicle.model}`}
       />
-      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {t('deleteDescription', { name: `${vehicle.year} ${vehicle.make} ${vehicle.model}` })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDelete}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
 
       {/* Image lightbox */}
       {showImage && vehicle.imageUrl && (

+ 341 - 216
src/components/confirm-dialog.tsx

@@ -1,12 +1,15 @@
 'use client'
 
 import {
+  type ComponentProps,
   type ComponentType,
   type CSSProperties,
   createContext,
   type PointerEvent as ReactPointerEvent,
+  type ReactNode,
   useCallback,
   useContext,
+  useEffect,
   useId,
   useRef,
   useState,
@@ -95,23 +98,285 @@ function KeyHint({ children }: { children: string }) {
   )
 }
 
+/**
+ * The confirmation layout itself: the icon chip and title, the hairline, a
+ * scrolling body and the button bar; a centred card on larger screens and a
+ * sheet on the bottom edge of a phone. `useConfirm()` draws every plain
+ * question with it. A prompt that needs more than a question can ask (content
+ * that loads while it is open, a third button, a checkbox) renders the frame
+ * itself, so it still looks and behaves like every other prompt.
+ */
+export function ConfirmFrame({
+  open,
+  onDismiss,
+  title,
+  icon,
+  destructive = false,
+  onOpenAutoFocus,
+  footer,
+  children,
+}: {
+  open: boolean
+  /** Escape, a tap outside, or the phone sheet dragged down: the safe answer. */
+  onDismiss: () => void
+  title: string
+  /** The mark in the header. Defaults to a warning when destructive, a question otherwise. */
+  icon?: ConfirmIcon
+  destructive?: boolean
+  /** Without it focus opens on the cancel button. */
+  onOpenAutoFocus?: (event: Event) => void
+  /** The buttons: `ConfirmFrameCancel` and `ConfirmFrameAction`, safest first. */
+  footer: ReactNode
+  /** What a screen reader announces as the description, in reading order. */
+  children: ReactNode
+}) {
+  const [dragY, setDragY] = useState(0)
+  const dragStart = useRef<number | null>(null)
+
+  // A sheet dragged away must not open the next time still pushed down.
+  useEffect(() => {
+    if (open) setDragY(0)
+  }, [open])
+
+  const Icon = icon ?? (destructive ? TriangleAlert : CircleHelp)
+
+  // One colour drives the chip, the glow and the hairline. `--confirm-ink` is
+  // that colour pulled toward the text colour, so a red icon still reads on a
+  // dark card.
+  const tone = {
+    '--confirm-tone': destructive ? 'var(--destructive)' : 'var(--primary)',
+    '--confirm-ink': 'color-mix(in oklab, var(--confirm-tone) 72%, var(--foreground))',
+    transform: dragY > 0 ? `translateY(${dragY}px)` : undefined,
+    transition: dragStart.current === null ? undefined : 'none',
+  } as CSSProperties
+
+  const onGrabDown = (e: ReactPointerEvent<HTMLDivElement>) => {
+    e.currentTarget.setPointerCapture?.(e.pointerId)
+    dragStart.current = e.clientY
+  }
+  const onGrabMove = (e: ReactPointerEvent<HTMLDivElement>) => {
+    if (dragStart.current === null) return
+    setDragY(Math.max(0, e.clientY - dragStart.current))
+  }
+  const onGrabUp = () => {
+    if (dragStart.current === null) return
+    dragStart.current = null
+    if (dragY > DRAG_TO_DISMISS_PX) onDismiss()
+    else setDragY(0)
+  }
+
+  return (
+    <AlertDialog open={open} onOpenChange={(v) => !v && onDismiss()}>
+      <AlertDialogPortal>
+        {/* Tapping outside is the safe answer, the same as Escape. */}
+        <AlertDialogOverlay onClick={onDismiss} />
+        <AlertDialogPrimitive.Content
+          data-slot="confirm-dialog"
+          data-tone={destructive ? 'destructive' : 'neutral'}
+          style={tone}
+          onOpenAutoFocus={onOpenAutoFocus}
+          className={cn(
+            'bg-card text-card-foreground border-card-edge fixed z-50 flex flex-col overflow-hidden border outline-none duration-200',
+            'shadow-[0_1px_2px_rgb(0_0_0/0.06),0_24px_48px_-20px_rgb(0_0_0/0.45)]',
+            'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
+            // Phone: a sheet on the bottom edge, so the buttons sit under the thumb.
+            'max-sm:data-[state=open]:slide-in-from-bottom max-sm:data-[state=closed]:slide-out-to-bottom max-sm:inset-x-0 max-sm:bottom-0 max-sm:max-h-[90dvh] max-sm:rounded-t-[1.375rem] max-sm:border-b-0',
+            // Larger screens: the house card, centred.
+            'sm:data-[state=open]:zoom-in-95 sm:data-[state=closed]:zoom-out-95 sm:top-1/2 sm:left-1/2 sm:max-h-[85vh] sm:w-full sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-xl'
+          )}
+        >
+          {/* The sheen, centred on the chip like the house card's. */}
+          <div
+            aria-hidden="true"
+            className="pointer-events-none absolute inset-0 bg-[radial-gradient(9rem_5.5rem_at_2.4rem_2.2rem,color-mix(in_oklab,var(--confirm-tone)_9%,transparent),transparent_70%)]"
+          />
+          <div
+            aria-hidden="true"
+            data-slot="confirm-grab"
+            onPointerDown={onGrabDown}
+            onPointerMove={onGrabMove}
+            onPointerUp={onGrabUp}
+            onPointerCancel={onGrabUp}
+            className="relative shrink-0 touch-none px-5 pt-2.5 pb-1 sm:hidden"
+          >
+            <div className="bg-muted-foreground/45 mx-auto h-1 w-10 rounded-full" />
+          </div>
+
+          <div className="relative flex shrink-0 items-center gap-3 px-5 pt-3 pb-3.5 sm:pt-4">
+            <div
+              data-slot="confirm-icon"
+              className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-[linear-gradient(to_bottom,color-mix(in_oklab,var(--confirm-tone)_12%,transparent),color-mix(in_oklab,var(--confirm-tone)_4%,transparent))] text-(--confirm-ink) shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--confirm-tone)_22%,transparent),inset_0_1px_0_rgb(255_255_255/0.15)]"
+            >
+              <Icon className="size-[17px]" />
+            </div>
+            <AlertDialogPrimitive.Title className="font-display min-w-0 text-[15px] leading-snug font-semibold tracking-tight text-balance">
+              {title}
+            </AlertDialogPrimitive.Title>
+          </div>
+          {/* The house hairline: the tone under the chip, gone by the far edge. */}
+          <div
+            aria-hidden="true"
+            className="relative h-px shrink-0 bg-[linear-gradient(to_right,color-mix(in_oklab,var(--confirm-tone)_55%,transparent),var(--card-edge)_45%,transparent)]"
+          />
+
+          {/* Everything between the hairline and the buttons is the description
+              a screen reader announces, in reading order. */}
+          <AlertDialogPrimitive.Description asChild>
+            <div className="relative min-h-0 flex-1 overflow-y-auto text-sm">{children}</div>
+          </AlertDialogPrimitive.Description>
+
+          <div className="border-card-edge/60 bg-muted/45 relative flex shrink-0 flex-col-reverse gap-2 border-t px-5 py-3 max-sm:pt-3.5 max-sm:pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:flex-row sm:flex-wrap sm:justify-end">
+            {footer}
+          </div>
+        </AlertDialogPrimitive.Content>
+      </AlertDialogPortal>
+    </AlertDialog>
+  )
+}
+
+/** Body text of a prompt drawn with `ConfirmFrame`: the spacing the shared confirm gives its description. */
+export function ConfirmFrameText({ className, ...props }: ComponentProps<'div'>) {
+  return (
+    <div
+      className={cn('text-muted-foreground grid gap-2.5 px-5 pt-4 pb-5 leading-relaxed', className)}
+      {...props}
+    />
+  )
+}
+
+/** The safe button of a `ConfirmFrame`. Closes the prompt; Escape presses it. */
+export function ConfirmFrameCancel({
+  className,
+  children,
+  ...props
+}: ComponentProps<typeof AlertDialogCancel>) {
+  return (
+    <AlertDialogCancel className={cn('max-sm:h-11 max-sm:text-[15px]', className)} {...props}>
+      <span>{children}</span>
+      <KeyHint>Esc</KeyHint>
+    </AlertDialogCancel>
+  )
+}
+
+/** A button of a `ConfirmFrame` that does something. Closes the prompt when pressed. */
+export function ConfirmFrameAction({
+  className,
+  children,
+  destructive = false,
+  enterHint = false,
+  variant,
+  ...props
+}: ComponentProps<typeof AlertDialogAction> & {
+  destructive?: boolean
+  /** Draw the Enter key on the button. Only for the button focus opens on. */
+  enterHint?: boolean
+}) {
+  return (
+    <AlertDialogAction
+      // The button's own destructive variant, not a class override: two
+      // background utilities on one element are settled by stylesheet
+      // order, which is how a red button ends up amber.
+      variant={variant ?? (destructive ? 'destructive' : 'default')}
+      className={cn('max-sm:h-11 max-sm:text-[15px]', className)}
+      {...props}
+    >
+      <span>{children}</span>
+      {enterHint && <KeyHint>↵</KeyHint>}
+    </AlertDialogAction>
+  )
+}
+
+/** The rows naming what a prompt affects, edge to edge under its text. */
+export function ConfirmSubjectList({
+  rows,
+  more = 0,
+  divided = false,
+}: {
+  rows: ConfirmSubject[]
+  /** How many more things are affected than `rows` shows. */
+  more?: number
+  /** Draw a line above the first row, for rows that follow a paragraph. */
+  divided?: boolean
+}) {
+  const t = useTranslations('common')
+  if (rows.length === 0) return null
+  const hasIcons = rows.some((row) => row.icon)
+  return (
+    <ul
+      data-slot="confirm-subject"
+      className={cn('text-[13px]', divided && 'border-card-edge/45 border-t')}
+    >
+      {rows.map((row, index) => {
+        const RowIcon = row.icon
+        return (
+          <li
+            // Rows are fixed while the prompt is open, and two can share a name.
+            key={`${index}:${row.label}`}
+            className="border-card-edge/45 flex min-w-0 items-center gap-2.5 border-b px-5 py-2"
+          >
+            {RowIcon && <RowIcon className="text-muted-foreground size-[15px] shrink-0" />}
+            <span className="min-w-0 truncate font-medium">{row.label}</span>
+            {row.detail && (
+              <span className="text-muted-foreground ml-auto max-w-[55%] shrink-0 truncate tabular-nums">
+                {row.detail}
+              </span>
+            )}
+          </li>
+        )
+      })}
+      {more > 0 && (
+        <li
+          className={cn(
+            'text-muted-foreground border-card-edge/45 border-b py-2 pr-5',
+            hasIcons ? 'pl-[2.8125rem]' : 'pl-5'
+          )}
+        >
+          {t('confirmDialog.andMore', { count: more })}
+        </li>
+      )}
+    </ul>
+  )
+}
+
+/** The short lines saying what happens next, each behind an icon in the prompt's tone. */
+export function ConfirmConsequenceList({ lines }: { lines: ConfirmConsequence[] }) {
+  if (lines.length === 0) return null
+  return (
+    <ul data-slot="confirm-consequences" className="grid gap-1.5 px-5 pt-3.5 pb-4 text-[13px]">
+      {lines.map((entry) => {
+        const line = typeof entry === 'string' ? { text: entry } : entry
+        const LineIcon = line.icon ?? CircleAlert
+        return (
+          <li
+            key={line.text}
+            className={cn(
+              'flex gap-2.5 leading-snug',
+              line.emphasis ? 'font-medium' : 'text-muted-foreground'
+            )}
+          >
+            <LineIcon className="mt-0.5 size-[15px] shrink-0 text-(--confirm-ink)" />
+            <span>{line.text}</span>
+          </li>
+        )
+      })}
+    </ul>
+  )
+}
+
 export function ConfirmProvider({ children }: { children: React.ReactNode }) {
   const t = useTranslations('common')
   const [open, setOpen] = useState(false)
   const [options, setOptions] = useState<ConfirmOptions>({})
   const [typed, setTyped] = useState('')
-  const [dragY, setDragY] = useState(0)
   const resolveRef = useRef<((value: boolean) => void) | null>(null)
   const cancelRef = useRef<HTMLButtonElement>(null)
   const actionRef = useRef<HTMLButtonElement>(null)
   const inputRef = useRef<HTMLInputElement>(null)
-  const dragStart = useRef<number | null>(null)
   const typeLabelId = useId()
 
   const confirm = useCallback((opts: ConfirmOptions) => {
     setOptions(opts)
     setTyped('')
-    setDragY(0)
     setOpen(true)
     return new Promise<boolean>((resolve) => {
       resolveRef.current = resolve
@@ -133,7 +398,6 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
   // once the name matches.
   const enterConfirms = mustType ? typedMatches : focusTarget === 'confirm'
 
-  const Icon = options.icon ?? (destructive ? TriangleAlert : CircleHelp)
   const consequences: Exclude<ConfirmConsequence, string>[] = [
     ...(options.consequences ?? []).map((c) => (typeof c === 'string' ? { text: c } : c)),
     ...(options.irreversible
@@ -141,226 +405,87 @@ export function ConfirmProvider({ children }: { children: React.ReactNode }) {
       : []),
   ]
   const subject = options.subject ?? []
-  const subjectHasIcons = subject.some((row) => row.icon)
-  const more = options.subjectMore ?? 0
-
-  // One colour drives the chip, the glow and the hairline. `--confirm-ink` is
-  // that colour pulled toward the text colour, so a red icon still reads on a
-  // dark card.
-  const tone = {
-    '--confirm-tone': destructive ? 'var(--destructive)' : 'var(--primary)',
-    '--confirm-ink': 'color-mix(in oklab, var(--confirm-tone) 72%, var(--foreground))',
-    transform: dragY > 0 ? `translateY(${dragY}px)` : undefined,
-    transition: dragStart.current === null ? undefined : 'none',
-  } as CSSProperties
-
-  const onGrabDown = (e: ReactPointerEvent<HTMLDivElement>) => {
-    e.currentTarget.setPointerCapture?.(e.pointerId)
-    dragStart.current = e.clientY
-  }
-  const onGrabMove = (e: ReactPointerEvent<HTMLDivElement>) => {
-    if (dragStart.current === null) return
-    setDragY(Math.max(0, e.clientY - dragStart.current))
-  }
-  const onGrabUp = () => {
-    if (dragStart.current === null) return
-    dragStart.current = null
-    if (dragY > DRAG_TO_DISMISS_PX) settle(false)
-    else setDragY(0)
-  }
 
   return (
     <ConfirmContext value={{ confirm }}>
       {children}
-      <AlertDialog open={open} onOpenChange={(v) => !v && settle(false)}>
-        <AlertDialogPortal>
-          {/* Tapping outside is the safe answer, the same as Escape. */}
-          <AlertDialogOverlay onClick={() => settle(false)} />
-          <AlertDialogPrimitive.Content
-            data-slot="confirm-dialog"
-            data-tone={destructive ? 'destructive' : 'neutral'}
-            style={tone}
-            onOpenAutoFocus={(e) => {
-              e.preventDefault()
-              const target = mustType
-                ? inputRef.current
-                : focusTarget === 'confirm'
-                  ? actionRef.current
-                  : cancelRef.current
-              target?.focus()
-            }}
+      <ConfirmFrame
+        open={open}
+        onDismiss={() => settle(false)}
+        title={options.title || t('confirmDialog.title')}
+        icon={options.icon}
+        destructive={destructive}
+        onOpenAutoFocus={(e) => {
+          e.preventDefault()
+          const target = mustType
+            ? inputRef.current
+            : focusTarget === 'confirm'
+              ? actionRef.current
+              : cancelRef.current
+          target?.focus()
+        }}
+        footer={
+          <>
+            <ConfirmFrameCancel ref={cancelRef}>
+              {options.cancelLabel || t('buttons.cancel')}
+            </ConfirmFrameCancel>
+            <ConfirmFrameAction
+              ref={actionRef}
+              disabled={!typedMatches}
+              onClick={() => settle(true)}
+              destructive={destructive}
+              enterHint={enterConfirms}
+            >
+              {options.confirmLabel || t('buttons.confirm')}
+            </ConfirmFrameAction>
+          </>
+        }
+      >
+        {options.description && (
+          <p className="text-muted-foreground px-5 pt-4 pb-5 leading-relaxed">
+            {options.description}
+          </p>
+        )}
+        <ConfirmSubjectList
+          rows={subject}
+          more={options.subjectMore}
+          divided={Boolean(options.description)}
+        />
+        <ConfirmConsequenceList lines={consequences} />
+        {mustType && (
+          <div
             className={cn(
-              'bg-card text-card-foreground border-card-edge fixed z-50 flex flex-col overflow-hidden border outline-none duration-200',
-              'shadow-[0_1px_2px_rgb(0_0_0/0.06),0_24px_48px_-20px_rgb(0_0_0/0.45)]',
-              'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
-              // Phone: a sheet on the bottom edge, so the buttons sit under the thumb.
-              'max-sm:data-[state=open]:slide-in-from-bottom max-sm:data-[state=closed]:slide-out-to-bottom max-sm:inset-x-0 max-sm:bottom-0 max-sm:max-h-[90dvh] max-sm:rounded-t-[1.375rem] max-sm:border-b-0',
-              // Larger screens: the house card, centred.
-              'sm:data-[state=open]:zoom-in-95 sm:data-[state=closed]:zoom-out-95 sm:top-1/2 sm:left-1/2 sm:max-h-[85vh] sm:w-full sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-xl'
+              'grid gap-1.5 px-5 pb-4 text-[13px]',
+              consequences.length > 0 ? 'pt-1' : 'pt-3.5'
             )}
           >
-            {/* The sheen, centred on the chip like the house card's. */}
-            <div
-              aria-hidden="true"
-              className="pointer-events-none absolute inset-0 bg-[radial-gradient(9rem_5.5rem_at_2.4rem_2.2rem,color-mix(in_oklab,var(--confirm-tone)_9%,transparent),transparent_70%)]"
-            />
-            <div
-              aria-hidden="true"
-              data-slot="confirm-grab"
-              onPointerDown={onGrabDown}
-              onPointerMove={onGrabMove}
-              onPointerUp={onGrabUp}
-              onPointerCancel={onGrabUp}
-              className="relative shrink-0 touch-none px-5 pt-2.5 pb-1 sm:hidden"
-            >
-              <div className="bg-muted-foreground/45 mx-auto h-1 w-10 rounded-full" />
-            </div>
-
-            <div className="relative flex shrink-0 items-center gap-3 px-5 pt-3 pb-3.5 sm:pt-4">
-              <div
-                data-slot="confirm-icon"
-                className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-[linear-gradient(to_bottom,color-mix(in_oklab,var(--confirm-tone)_12%,transparent),color-mix(in_oklab,var(--confirm-tone)_4%,transparent))] text-(--confirm-ink) shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--confirm-tone)_22%,transparent),inset_0_1px_0_rgb(255_255_255/0.15)]"
-              >
-                <Icon className="size-[17px]" />
-              </div>
-              <AlertDialogPrimitive.Title className="font-display min-w-0 text-[15px] leading-snug font-semibold tracking-tight text-balance">
-                {options.title || t('confirmDialog.title')}
-              </AlertDialogPrimitive.Title>
-            </div>
-            {/* The house hairline: the tone under the chip, gone by the far edge. */}
-            <div
-              aria-hidden="true"
-              className="relative h-px shrink-0 bg-[linear-gradient(to_right,color-mix(in_oklab,var(--confirm-tone)_55%,transparent),var(--card-edge)_45%,transparent)]"
+            <label htmlFor={`${typeLabelId}-input`} id={typeLabelId}>
+              {t.rich('confirmDialog.typeToConfirm', {
+                text: mustType,
+                b: (chunks) => <b className="font-semibold">{chunks}</b>,
+              })}
+            </label>
+            <Input
+              ref={inputRef}
+              id={`${typeLabelId}-input`}
+              value={typed}
+              autoComplete="off"
+              autoCapitalize="off"
+              spellCheck={false}
+              onChange={(e) => setTyped(e.target.value)}
+              onKeyDown={(e) => {
+                // An Enter that accepts an input method's composition
+                // finishes the text; it is not an answer.
+                if (e.nativeEvent.isComposing || e.keyCode === 229) return
+                if (e.key === 'Enter' && typedMatches) {
+                  e.preventDefault()
+                  settle(true)
+                }
+              }}
             />
-
-            {/* Everything between the hairline and the buttons is the description
-                a screen reader announces, in reading order. */}
-            <AlertDialogPrimitive.Description asChild>
-              <div className="relative min-h-0 flex-1 overflow-y-auto text-sm">
-                {options.description && (
-                  <p className="text-muted-foreground px-5 pt-4 pb-5 leading-relaxed">
-                    {options.description}
-                  </p>
-                )}
-                {subject.length > 0 && (
-                  <ul
-                    data-slot="confirm-subject"
-                    className={cn(
-                      'text-[13px]',
-                      options.description && 'border-card-edge/45 border-t'
-                    )}
-                  >
-                    {subject.map((row) => {
-                      const RowIcon = row.icon
-                      return (
-                        <li
-                          key={`${row.label}:${row.detail ?? ''}`}
-                          className="border-card-edge/45 flex min-w-0 items-center gap-2.5 border-b px-5 py-2"
-                        >
-                          {RowIcon && (
-                            <RowIcon className="text-muted-foreground size-[15px] shrink-0" />
-                          )}
-                          <span className="min-w-0 truncate font-medium">{row.label}</span>
-                          {row.detail && (
-                            <span className="text-muted-foreground ml-auto max-w-[55%] shrink-0 truncate tabular-nums">
-                              {row.detail}
-                            </span>
-                          )}
-                        </li>
-                      )
-                    })}
-                    {more > 0 && (
-                      <li
-                        className={cn(
-                          'text-muted-foreground border-card-edge/45 border-b py-2 pr-5',
-                          subjectHasIcons ? 'pl-[2.8125rem]' : 'pl-5'
-                        )}
-                      >
-                        {t('confirmDialog.andMore', { count: more })}
-                      </li>
-                    )}
-                  </ul>
-                )}
-                {consequences.length > 0 && (
-                  <ul
-                    data-slot="confirm-consequences"
-                    className="grid gap-1.5 px-5 pt-3.5 pb-4 text-[13px]"
-                  >
-                    {consequences.map((line) => {
-                      const LineIcon = line.icon ?? CircleAlert
-                      return (
-                        <li
-                          key={line.text}
-                          className={cn(
-                            'flex gap-2.5 leading-snug',
-                            line.emphasis ? 'font-medium' : 'text-muted-foreground'
-                          )}
-                        >
-                          <LineIcon className="mt-0.5 size-[15px] shrink-0 text-(--confirm-ink)" />
-                          <span>{line.text}</span>
-                        </li>
-                      )
-                    })}
-                  </ul>
-                )}
-                {mustType && (
-                  <div
-                    className={cn(
-                      'grid gap-1.5 px-5 pb-4 text-[13px]',
-                      consequences.length > 0 ? 'pt-1' : 'pt-3.5'
-                    )}
-                  >
-                    <label htmlFor={`${typeLabelId}-input`} id={typeLabelId}>
-                      {t.rich('confirmDialog.typeToConfirm', {
-                        text: mustType,
-                        b: (chunks) => <b className="font-semibold">{chunks}</b>,
-                      })}
-                    </label>
-                    <Input
-                      ref={inputRef}
-                      id={`${typeLabelId}-input`}
-                      value={typed}
-                      autoComplete="off"
-                      autoCapitalize="off"
-                      spellCheck={false}
-                      onChange={(e) => setTyped(e.target.value)}
-                      onKeyDown={(e) => {
-                        // An Enter that accepts an input method's composition
-                        // finishes the text; it is not an answer.
-                        if (e.nativeEvent.isComposing || e.keyCode === 229) return
-                        if (e.key === 'Enter' && typedMatches) {
-                          e.preventDefault()
-                          settle(true)
-                        }
-                      }}
-                    />
-                  </div>
-                )}
-              </div>
-            </AlertDialogPrimitive.Description>
-
-            <div className="border-card-edge/60 bg-muted/45 relative flex shrink-0 flex-col-reverse gap-2 border-t px-5 py-3 max-sm:pt-3.5 max-sm:pb-[max(1.25rem,env(safe-area-inset-bottom))] sm:flex-row sm:flex-wrap sm:justify-end">
-              <AlertDialogCancel ref={cancelRef} className="max-sm:h-11 max-sm:text-[15px]">
-                <span>{options.cancelLabel || t('buttons.cancel')}</span>
-                <KeyHint>Esc</KeyHint>
-              </AlertDialogCancel>
-              <AlertDialogAction
-                ref={actionRef}
-                disabled={!typedMatches}
-                onClick={() => settle(true)}
-                // The button's own destructive variant, not a class override: two
-                // background utilities on one element are settled by stylesheet
-                // order, which is how a red button ends up amber.
-                variant={destructive ? 'destructive' : 'default'}
-                className="max-sm:h-11 max-sm:text-[15px]"
-              >
-                <span>{options.confirmLabel || t('buttons.confirm')}</span>
-                {enterConfirms && <KeyHint>↵</KeyHint>}
-              </AlertDialogAction>
-            </div>
-          </AlertDialogPrimitive.Content>
-        </AlertDialogPortal>
-      </AlertDialog>
+          </div>
+        )}
+      </ConfirmFrame>
     </ConfirmContext>
   )
 }

+ 20 - 21
src/components/sent-copy-note.tsx

@@ -2,15 +2,11 @@
 
 import { useTranslations } from 'next-intl'
 import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+} from '@/components/confirm-dialog'
 import { useDayFormatter } from '@/features/calendar/Components/useDayFormatter'
 import { cn } from '@/lib/utils'
 
@@ -59,17 +55,20 @@ export function SentCopyConfirm({
 }) {
   const t = useTranslations('common.sentCopy')
   return (
-    <AlertDialog open={open} onOpenChange={(next) => !next && onCancel()}>
-      <AlertDialogContent>
-        <AlertDialogHeader>
-          <AlertDialogTitle>{t('confirmTitle')}</AlertDialogTitle>
-          <AlertDialogDescription>{t('confirmBody')}</AlertDialogDescription>
-        </AlertDialogHeader>
-        <AlertDialogFooter>
-          <AlertDialogCancel onClick={onCancel}>{t('cancel')}</AlertDialogCancel>
-          <AlertDialogAction onClick={onConfirm}>{t('confirm')}</AlertDialogAction>
-        </AlertDialogFooter>
-      </AlertDialogContent>
-    </AlertDialog>
+    <ConfirmFrame
+      open={open}
+      onDismiss={onCancel}
+      title={t('confirmTitle')}
+      footer={
+        <>
+          <ConfirmFrameCancel>{t('cancel')}</ConfirmFrameCancel>
+          <ConfirmFrameAction onClick={onConfirm}>{t('confirm')}</ConfirmFrameAction>
+        </>
+      }
+    >
+      <ConfirmFrameText>
+        <p>{t('confirmBody')}</p>
+      </ConfirmFrameText>
+    </ConfirmFrame>
   )
 }

+ 14 - 36
src/features/condition-map/Components/ConditionMapCard.tsx

@@ -5,17 +5,8 @@ import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { CheckCheck, Eraser, Loader2, Plus } from 'lucide-react'
 import { toast } from 'sonner'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import {
   Dialog,
   DialogContent,
@@ -115,7 +106,7 @@ export function ConditionMapCard({
   const [body, setBody] = useState<BodyType>(bodyTypeFor(vehicle, { serviceType }))
   const [focusView, setFocusView] = useState<View | null>(null)
   const [editingId, setEditingId] = useState<string | null>(null)
-  const [clearingId, setClearingId] = useState<string | null>(null)
+  const confirm = useConfirm()
   /** The Add mark dialog: open, and the panel chosen in it so far. */
   const [adding, setAdding] = useState(false)
   const [addSpot, setAddSpot] = useState<PanelSpot | null>(null)
@@ -333,12 +324,19 @@ export function ConditionMapCard({
     })
   }
 
-  const handleClear = () => {
-    const id = clearingId
-    if (!id) return
-    setClearingId(null)
+  const handleClear = async (id: string) => {
     const before = marks.find((m) => m.id === id)
     if (!before) return
+    const ok = await confirm({
+      title: t('clearRepaired'),
+      description: t('clearBody', {
+        n: numberOf.get(before.id) ?? 0,
+        area: t(`panels.${before.panel}`),
+      }),
+      confirmLabel: t('clearRepaired'),
+      cancelLabel: t('cancel'),
+    })
+    if (!ok) return
     replace({ ...before, resolvedAt: new Date().toISOString() })
     startTransition(async () => {
       const result = await save(
@@ -438,7 +436,6 @@ export function ConditionMapCard({
   }))
 
   const editing = editingId ? (marks.find((m) => m.id === editingId) ?? null) : null
-  const clearing = clearingId ? (marks.find((m) => m.id === clearingId) ?? null) : null
 
   return (
     <div className="space-y-3" data-testid="condition-map">
@@ -571,7 +568,7 @@ export function ConditionMapCard({
                       number={numberOf.get(mark.id) ?? 0}
                       previous
                       onOpen={() => setEditingId(mark.id)}
-                      onClear={readOnly ? undefined : () => setClearingId(mark.id)}
+                      onClear={readOnly ? undefined : () => handleClear(mark.id)}
                     />
                   ))}
               </ul>
@@ -718,25 +715,6 @@ export function ConditionMapCard({
           </form>
         </DialogContent>
       </Dialog>
-
-      <AlertDialog open={clearing !== null} onOpenChange={(open) => !open && setClearingId(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('clearRepaired')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {clearing &&
-                t('clearBody', {
-                  n: numberOf.get(clearing.id) ?? 0,
-                  area: t(`panels.${clearing.panel}`),
-                })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction onClick={handleClear}>{t('clearRepaired')}</AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 33 - 48
src/features/import/Components/ImportHistoryCard.tsx

@@ -3,21 +3,12 @@
 import { useCallback, useEffect, useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { useFormatter, useTranslations } from 'next-intl'
-import { History, Loader2, Undo2 } from 'lucide-react'
+import { FileSpreadsheet, History, Loader2, Undo2 } from 'lucide-react'
 import { toast } from 'sonner'
 import { AppCard } from '@/components/app-card'
 import { Badge } from '@/components/ui/badge'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { listImportBatches, undoImportBatch } from '@/features/import/Actions/importActions'
 
 type Batch = NonNullable<Awaited<ReturnType<typeof listImportBatches>>['data']>[number]
@@ -33,8 +24,9 @@ export function ImportHistoryCard({ refreshKey = 0 }: { refreshKey?: number }) {
   const format = useFormatter()
   const router = useRouter()
   const [batches, setBatches] = useState<Batch[] | null>(null)
-  const [pending, setPending] = useState<Batch | null>(null)
-  const [busy, setBusy] = useState(false)
+  const confirm = useConfirm()
+  // The import being undone; its button waits while the answer is out.
+  const [busyId, setBusyId] = useState<string | null>(null)
 
   const load = useCallback(async () => {
     const res = await listImportBatches()
@@ -46,12 +38,27 @@ export function ImportHistoryCard({ refreshKey = 0 }: { refreshKey?: number }) {
     load()
   }, [load, refreshKey])
 
-  const undo = async () => {
-    if (!pending) return
-    setBusy(true)
-    const res = await undoImportBatch(pending.id)
-    setBusy(false)
-    setPending(null)
+  const undo = async (batch: Batch) => {
+    const ok = await confirm({
+      title: t('confirmTitle'),
+      description: t('confirmDescription', {
+        file: batch.fileName,
+        customers: batch.attached.customers,
+        vehicles: batch.attached.vehicles,
+        services: batch.attached.serviceRecords,
+      }),
+      subject: [{ label: batch.fileName, detail: te(batch.entity), icon: FileSpreadsheet }],
+      confirmLabel: t('confirm'),
+      cancelLabel: t('cancel'),
+      icon: Undo2,
+      // Undoing deletes what the import created, so it reads and focuses
+      // like any other delete.
+      destructive: true,
+    })
+    if (!ok) return
+    setBusyId(batch.id)
+    const res = await undoImportBatch(batch.id)
+    setBusyId(null)
     if (res.success && res.data) {
       toast.success(
         t('undone', {
@@ -118,11 +125,16 @@ export function ImportHistoryCard({ refreshKey = 0 }: { refreshKey?: number }) {
                   variant="outline"
                   size="sm"
                   className="h-8"
-                  onClick={() => setPending(b)}
+                  onClick={() => undo(b)}
+                  disabled={busyId !== null}
                   aria-label={t('undo')}
                   title={t('undo')}
                 >
-                  <Undo2 className="mr-1 h-3.5 w-3.5" />
+                  {busyId === b.id ? (
+                    <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
+                  ) : (
+                    <Undo2 className="mr-1 h-3.5 w-3.5" />
+                  )}
                   {t('undo')}
                 </Button>
               )}
@@ -130,33 +142,6 @@ export function ImportHistoryCard({ refreshKey = 0 }: { refreshKey?: number }) {
           )
         })}
       </div>
-
-      <AlertDialog
-        open={pending !== null}
-        onOpenChange={(open) => !open && !busy && setPending(null)}
-      >
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('confirmTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {pending &&
-                t('confirmDescription', {
-                  file: pending.fileName,
-                  customers: pending.attached.customers,
-                  vehicles: pending.attached.vehicles,
-                  services: pending.attached.serviceRecords,
-                })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={busy}>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction onClick={undo} disabled={busy}>
-              {busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {t('confirm')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </AppCard>
   )
 }

+ 19 - 37
src/features/inspections/Components/InspectionItemRow.tsx

@@ -1,20 +1,11 @@
 'use client'
 
 import { useEffect, useId, useRef, useState, useTransition } from 'react'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { SearchableSelect } from '@/components/ui/searchable-select'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import {
   Ban,
   Camera,
@@ -267,7 +258,7 @@ export function InspectionItemRow({
   }, [serverPhotos]) // eslint-disable-line react-hooks/exhaustive-deps -- follows the server's list only
   const [showNotes, setShowNotes] = useState(!!item.notes)
   const [notesRequired, setNotesRequired] = useState(false)
-  const [showClearDialog, setShowClearDialog] = useState(false)
+  const confirm = useConfirm()
   const [isSaving, startSaving] = useTransition()
   const [isUploading, setIsUploading] = useState(false)
 
@@ -316,12 +307,28 @@ export function InspectionItemRow({
     })
   }
 
+  const clearAfterConfirm = async () => {
+    const ok = await confirm({
+      title: t('clearTitle'),
+      description: t('clearBody', { name: item.name }),
+      confirmLabel: t('clear'),
+      cancelLabel: t('cancel'),
+      destructive: true,
+    })
+    if (!ok) return
+    setCondition('not_inspected')
+    setNotesRequired(false)
+    setShowNotes(false)
+    setNotes('')
+    save({ condition: 'not_inspected', notes: '' })
+  }
+
   const applyCondition = (next: Condition, { focusNotes = true } = {}) => {
     if (isCompleted) return
 
     // Clearing a graded defect throws away its notes, so confirm first.
     if (next === 'not_inspected' && isDefect(condition) && notes.trim()) {
-      setShowClearDialog(true)
+      clearAfterConfirm()
       return
     }
 
@@ -752,31 +759,6 @@ export function InspectionItemRow({
           ))}
         </ul>
       )}
-
-      <AlertDialog open={showClearDialog} onOpenChange={setShowClearDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('clearTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('clearBody', { name: item.name })}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-              onClick={() => {
-                setCondition('not_inspected')
-                setNotesRequired(false)
-                setShowNotes(false)
-                setNotes('')
-                setShowClearDialog(false)
-                save({ condition: 'not_inspected', notes: '' })
-              }}
-            >
-              {t('clear')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </li>
   )
 }

+ 87 - 107
src/features/inspections/Components/InspectionPageClient.tsx

@@ -4,18 +4,17 @@ import { type ComponentProps, type ComponentType, useMemo, useState, useTransiti
 import { useRouter } from 'next/navigation'
 import Link from 'next/link'
 import { useFormatDate } from '@/lib/use-format-date'
+import {
+  ConfirmConsequenceList,
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+  ConfirmSubjectList,
+  useConfirm,
+} from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Badge } from '@/components/ui/badge'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import {
   DropdownMenu,
   DropdownMenuContent,
@@ -39,6 +38,7 @@ import {
   Send,
   Share2,
   Trash2,
+  TriangleAlert,
   Eye,
 } from 'lucide-react'
 import { useTranslations } from 'next-intl'
@@ -79,7 +79,7 @@ import {
   type SeverityScale,
 } from '../Lib/conditions'
 import { useConditionLabels } from '../Lib/useConditionLabels'
-import { describeBlocker, findCompletionBlockers } from '../Lib/completion'
+import { findCompletionBlockers } from '../Lib/completion'
 
 export interface InspectionData {
   id: string
@@ -270,8 +270,7 @@ export function InspectionPageClient({
   const serviceType = useServiceType()
   const [isPending, startTransition] = useTransition()
   const [showCompleteDialog, setShowCompleteDialog] = useState(false)
-  const [showReopenDialog, setShowReopenDialog] = useState(false)
-  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
+  const confirm = useConfirm()
   const [showShareDialog, setShowShareDialog] = useState(false)
   const [showSendDialog, setShowSendDialog] = useState(false)
   const [isCreatingQuote, setIsCreatingQuote] = useState(false)
@@ -454,12 +453,20 @@ export function InspectionPageClient({
     })
   }
 
-  const handleReopen = () => {
+  const handleReopen = async () => {
+    const ok = await confirm({
+      title: t('reopenTitle'),
+      description: t('reopenBody'),
+      consequences: inspection.publicToken ? [t('reopenShared')] : undefined,
+      confirmLabel: t('reopen'),
+      cancelLabel: t('cancel'),
+      icon: RotateCcw,
+    })
+    if (!ok) return
     startTransition(async () => {
       const reopened = await reopenInspection(inspection.id).catch(() => null)
       if (reopened?.success) {
         toast.success(t('reopened'))
-        setShowReopenDialog(false)
         router.refresh()
       } else {
         toast.error(reopened?.error || t('reopenFailed'))
@@ -467,7 +474,16 @@ export function InspectionPageClient({
     })
   }
 
-  const handleDelete = () => {
+  const handleDelete = async () => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteBody'),
+      confirmLabel: t('delete'),
+      cancelLabel: t('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     startTransition(async () => {
       const removed = await deleteInspection(inspection.id).catch(() => null)
       if (removed?.success) {
@@ -545,7 +561,7 @@ export function InspectionPageClient({
                 variant="outline"
                 icon={RotateCcw}
                 label={t('reopen')}
-                onClick={() => setShowReopenDialog(true)}
+                onClick={handleReopen}
               />
             ) : (
               <BarButton
@@ -601,10 +617,7 @@ export function InspectionPageClient({
                   </Link>
                 </DropdownMenuItem>
                 <DropdownMenuSeparator />
-                <DropdownMenuItem
-                  className="text-destructive"
-                  onClick={() => setShowDeleteDialog(true)}
-                >
+                <DropdownMenuItem className="text-destructive" onClick={handleDelete}>
                   <Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
                   {t('delete')}
                 </DropdownMenuItem>
@@ -1082,93 +1095,60 @@ export function InspectionPageClient({
       />
 
       {/* Complete confirmation */}
-      <AlertDialog open={showCompleteDialog} onOpenChange={setShowCompleteDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('completeTitle')}</AlertDialogTitle>
-            <AlertDialogDescription asChild>
-              <div className="space-y-2">
-                {blockers.length > 0 ? (
-                  <>
-                    <p className="text-destructive font-medium">
-                      {t('completeBlocked', { count: blockers.length })}
-                    </p>
-                    <ul className="list-disc space-y-0.5 pl-5">
-                      {blockers.slice(0, 8).map((blocker) => (
-                        <li key={blocker.id}>
-                          {blocker.label} — {describeBlocker(blocker.reason)}
-                        </li>
-                      ))}
-                    </ul>
-                    {blockers.length > 8 && <p>and {blockers.length - 8} more.</p>}
-                  </>
-                ) : null}
-                <p>{t('completeBody', { result: resultLabel(deriveTestResult(gradedItems)) })}</p>
-                {notInspected > 0 && (
-                  <p className="font-medium text-amber-700 dark:text-amber-400">
-                    {t('completeUngraded', { count: notInspected })}
-                  </p>
-                )}
-                {counts.dangerous > 0 && (
-                  <p className="text-destructive font-medium">
-                    {t('completeDangerous', { count: counts.dangerous })}
-                  </p>
-                )}
-              </div>
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction onClick={handleComplete} disabled={isPending || blockers.length > 0}>
-              {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
-              {t('complete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
-
-      {/* Reopen confirmation */}
-      <AlertDialog open={showReopenDialog} onOpenChange={setShowReopenDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('reopenTitle')}</AlertDialogTitle>
-            <AlertDialogDescription asChild>
-              <div className="space-y-2">
-                <p>{t('reopenBody')}</p>
-                {inspection.publicToken && <p>{t('reopenShared')}</p>}
-              </div>
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction onClick={handleReopen} disabled={isPending}>
-              {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
-              {t('reopen')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
-
-      {/* Delete confirmation */}
-      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteBody')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDelete}
-              disabled={isPending}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+      <ConfirmFrame
+        open={showCompleteDialog}
+        onDismiss={() => setShowCompleteDialog(false)}
+        title={t('completeTitle')}
+        icon={CheckCircle2}
+        footer={
+          <>
+            <ConfirmFrameCancel>{t('cancel')}</ConfirmFrameCancel>
+            <ConfirmFrameAction
+              onClick={handleComplete}
+              disabled={isPending || blockers.length > 0}
             >
-              {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
-              {t('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
+              {t('complete')}
+            </ConfirmFrameAction>
+          </>
+        }
+      >
+        <ConfirmFrameText>
+          <p>{t('completeBody', { result: resultLabel(deriveTestResult(gradedItems)) })}</p>
+          {blockers.length > 0 && (
+            <p className="text-destructive font-medium">
+              {t('completeBlocked', { count: blockers.length })}
+            </p>
+          )}
+        </ConfirmFrameText>
+        {/* What stands in the way, named, so the count is not taken on trust. */}
+        <ConfirmSubjectList
+          divided
+          rows={blockers.slice(0, 8).map((blocker) => ({
+            label: blocker.label,
+            detail:
+              blocker.reason === 'missing-grade'
+                ? t('blockerMissingGrade')
+                : t('blockerNeedsPhoto'),
+          }))}
+          more={Math.max(0, blockers.length - 8)}
+        />
+        <ConfirmConsequenceList
+          lines={[
+            ...(notInspected > 0
+              ? [{ text: t('completeUngraded', { count: notInspected }), emphasis: true }]
+              : []),
+            ...(counts.dangerous > 0
+              ? [
+                  {
+                    text: t('completeDangerous', { count: counts.dangerous }),
+                    icon: TriangleAlert,
+                    emphasis: true,
+                  },
+                ]
+              : []),
+          ]}
+        />
+      </ConfirmFrame>
 
       <InspectionShareDialog
         open={showShareDialog}

+ 15 - 38
src/features/inspections/Components/TemplateListClient.tsx

@@ -2,6 +2,7 @@
 
 import { useState, useTransition } from 'react'
 import { useRouter } from 'next/navigation'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Badge } from '@/components/ui/badge'
 import {
@@ -11,16 +12,6 @@ import {
   DropdownMenuSeparator,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import {
   ClipboardCheck,
   Copy,
@@ -239,7 +230,7 @@ export function TemplateListClient({
   const [showImport, setShowImport] = useState(false)
   const [exportTarget, setExportTarget] = useState<{ id: string; name: string } | null>(null)
   const [editingTemplate, setEditingTemplate] = useState<TemplateFormData | undefined>()
-  const [deleteTarget, setDeleteTarget] = useState<Template | null>(null)
+  const confirm = useConfirm()
   const [duplicatingId, setDuplicatingId] = useState<string | null>(null)
   const [isInstalling, startInstalling] = useTransition()
   const [isTranslating, startTranslating] = useTransition()
@@ -287,14 +278,22 @@ export function TemplateListClient({
       }
     })
   }
-  const [isDeleting, startDeleteTransition] = useTransition()
+  const [, startDeleteTransition] = useTransition()
 
-  const handleDelete = (id: string) => {
+  const handleDelete = async (template: Template) => {
+    const ok = await confirm({
+      title: t('deleteTitle', { name: template.name }),
+      description: t('deleteBody'),
+      confirmLabel: t('delete'),
+      cancelLabel: t('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     startDeleteTransition(async () => {
-      const result = await deleteTemplate(id).catch(() => null)
+      const result = await deleteTemplate(template.id).catch(() => null)
       if (result?.success) {
         toast.success(t('deleted'))
-        setDeleteTarget(null)
         router.refresh()
       } else {
         toast.error(result?.error || t('deleteFailed'))
@@ -420,7 +419,7 @@ export function TemplateListClient({
               onEdit={() => handleEdit(t)}
               onDuplicate={() => handleDuplicate(t.id)}
               onExport={() => setExportTarget({ id: t.id, name: t.name })}
-              onDelete={() => setDeleteTarget(t)}
+              onDelete={() => handleDelete(t)}
             />
           ))}
         </div>
@@ -453,28 +452,6 @@ export function TemplateListClient({
         installedNames={templates.map((t) => t.name)}
         installedPackageIds={templates.flatMap((t) => (t.packageId ? [t.packageId] : []))}
       />
-
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>
-              {t('deleteTitle', { name: deleteTarget?.name ?? '' })}
-            </AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteBody')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={() => deleteTarget && handleDelete(deleteTarget.id)}
-              disabled={isDeleting}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />}
-              {t('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 17 - 45
src/features/messaging/Components/UnifiedInbox.tsx

@@ -17,6 +17,7 @@ import {
   Search,
   Trash2,
 } from 'lucide-react'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import {
@@ -26,16 +27,6 @@ import {
   DialogHeader,
   DialogTitle,
 } from '@/components/ui/dialog'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import {
   DropdownMenu,
   DropdownMenuContent,
@@ -146,8 +137,7 @@ export function UnifiedInbox({
   const [smsData, setSmsData] = useState<SmsConversationData | null>(null)
   const [telegramData, setTelegramData] = useState<TelegramConversationData | null>(null)
 
-  const [deleteTarget, setDeleteTarget] = useState<InboxThread | null>(null)
-  const [isDeleting, setIsDeleting] = useState(false)
+  const confirm = useConfirm()
   const [showChannelChoice, setShowChannelChoice] = useState(false)
   const [composeChannel, setComposeChannel] = useState<MessagingChannel | null>(null)
 
@@ -373,10 +363,20 @@ export function UnifiedInbox({
   }, [focusKey])
 
   /** Removes our copy of a conversation; the customer's phone keeps theirs. */
-  const confirmDelete = async () => {
-    const thread = deleteTarget
-    if (!thread) return
-    setIsDeleting(true)
+  const handleDelete = async (thread: InboxThread) => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      // A portal thread has no copy on the customer's phone: it goes for them too.
+      description:
+        thread.channel === 'portal'
+          ? tp('deleteDescription', { name: thread.name })
+          : t('deleteDescription', { name: thread.name }),
+      confirmLabel: t('delete'),
+      cancelLabel: t('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
 
     // A WhatsApp thread can exist under a bare number, and those are the ones
     // most worth clearing away: test sends and wrong numbers. Email threads
@@ -404,9 +404,6 @@ export function UnifiedInbox({
       result = null
     }
 
-    setIsDeleting(false)
-    setDeleteTarget(null)
-
     if (result?.success) {
       if (selected?.key === thread.key) setSelected(null)
       onChanged?.()
@@ -620,7 +617,7 @@ export function UnifiedInbox({
                     <DropdownMenuSeparator />
                     <DropdownMenuItem
                       className="text-destructive"
-                      onClick={() => setDeleteTarget(selected)}
+                      onClick={() => handleDelete(selected)}
                     >
                       <Trash2 className="mr-2 h-4 w-4" />
                       {t('deleteConversation')}
@@ -760,31 +757,6 @@ export function UnifiedInbox({
         </DialogContent>
       </Dialog>
 
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {/* A portal thread has no copy on the customer's phone: it goes for them too. */}
-              {deleteTarget?.channel === 'portal'
-                ? tp('deleteDescription', { name: deleteTarget.name })
-                : t('deleteDescription', { name: deleteTarget?.name ?? '' })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={isDeleting}>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={confirmDelete}
-              disabled={isDeleting}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {t('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
-
       <NewSmsDialog
         open={composeChannel === 'sms'}
         onOpenChange={(open) => !open && setComposeChannel(null)}

+ 15 - 35
src/features/scheduled-messages/Components/ScheduledMessageList.tsx

@@ -16,6 +16,7 @@ import {
   XCircle,
 } from 'lucide-react'
 import { Badge } from '@/components/ui/badge'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import {
   DropdownMenu,
@@ -24,16 +25,6 @@ import {
   DropdownMenuSeparator,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { useFormatDate } from '@/lib/use-format-date'
 import { cn } from '@/lib/utils'
 import {
@@ -81,7 +72,7 @@ export function ScheduledMessageList({
   const [filter, setFilter] = useState<StatusFilter>('upcoming')
   const [editing, setEditing] = useState<ScheduledMessageListItem | undefined>()
   const [showDialog, setShowDialog] = useState(false)
-  const [deleteTarget, setDeleteTarget] = useState<ScheduledMessageListItem | null>(null)
+  const confirm = useConfirm()
   const [busyId, setBusyId] = useState<string | null>(null)
 
   const filtered = useMemo(() => {
@@ -128,10 +119,18 @@ export function ScheduledMessageList({
     setBusyId(null)
   }
 
-  const handleDelete = async () => {
-    if (!deleteTarget) return
-    setBusyId(deleteTarget.id)
-    const result = await deleteScheduledMessage(deleteTarget.id).catch(() => null)
+  const handleDelete = async (message: ScheduledMessageListItem) => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription'),
+      confirmLabel: tc('delete'),
+      cancelLabel: tc('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
+    setBusyId(message.id)
+    const result = await deleteScheduledMessage(message.id).catch(() => null)
     if (result?.success) {
       toast.success(t('deleted'))
       onChanged()
@@ -139,7 +138,6 @@ export function ScheduledMessageList({
       toast.error(result?.error || t('deleteError'))
     }
     setBusyId(null)
-    setDeleteTarget(null)
   }
 
   return (
@@ -274,7 +272,7 @@ export function ScheduledMessageList({
                       )}
                       <DropdownMenuItem
                         className="text-destructive"
-                        onClick={() => setDeleteTarget(message)}
+                        onClick={() => handleDelete(message)}
                       >
                         <Trash2 className="mr-2 h-4 w-4" />
                         {tc('delete')}
@@ -298,24 +296,6 @@ export function ScheduledMessageList({
         message={editing}
         onSaved={onChanged}
       />
-
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteDescription')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDelete}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 14 - 30
src/features/settings/Components/passkey-settings.tsx

@@ -7,13 +7,13 @@ import { toast } from 'sonner'
 import {
   Dialog,
   DialogContent,
-  DialogDescription,
   DialogFooter,
   DialogHeader,
   DialogTitle,
 } from '@/components/ui/dialog'
 import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Separator } from '@/components/ui/separator'
 import { Fingerprint, Loader2, LogIn, Pencil, Plus, Trash2 } from 'lucide-react'
@@ -45,8 +45,7 @@ export function PasskeySettings() {
   const [renamingPasskey, setRenamingPasskey] = useState<Passkey | null>(null)
   const [newName, setNewName] = useState('')
   const [saving, setSaving] = useState(false)
-  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
-  const [passKeyToDelete, setPassKeyToDelete] = useState<Passkey | null>(null)
+  const confirm = useConfirm()
 
   const fetchPasskeys = async () => {
     try {
@@ -124,8 +123,17 @@ export function PasskeySettings() {
     }
   }
 
-  const handleDelete = async () => {
-    if (!passKeyToDelete) return
+  const handleDelete = async (passKeyToDelete: Passkey) => {
+    const ok = await confirm({
+      title: t('account.passkey.confirmDeleteTitle'),
+      description: t('account.passkey.confirmDelete'),
+      subject: [{ label: passKeyToDelete.name || t('account.passkey.unnamed'), icon: Fingerprint }],
+      confirmLabel: t('account.passkey.delete'),
+      cancelLabel: t('account.passkey.cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     setDeletingId(passKeyToDelete.id)
     try {
       await authClient.passkey.deletePasskey({ id: passKeyToDelete.id })
@@ -135,8 +143,6 @@ export function PasskeySettings() {
       toast.error(t('account.passkey.deleteFailed'))
     }
     setDeletingId(null)
-    setDeleteDialogOpen(false)
-    setPassKeyToDelete(null)
   }
 
   const handleRename = async () => {
@@ -214,10 +220,7 @@ export function PasskeySettings() {
                     size="icon"
                     className="h-8 w-8 text-destructive hover:text-destructive"
                     disabled={deletingId === pk.id}
-                    onClick={() => {
-                      setPassKeyToDelete(pk)
-                      setDeleteDialogOpen(true)
-                    }}
+                    onClick={() => handleDelete(pk)}
                     aria-label={t('account.passkey.delete')}
                   >
                     {deletingId === pk.id ? (
@@ -273,25 +276,6 @@ export function PasskeySettings() {
           </DialogFooter>
         </DialogContent>
       </Dialog>
-
-      {/* Delete Confirmation Dialog */}
-      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
-        <DialogContent className="sm:max-w-md">
-          <DialogHeader>
-            <DialogTitle>{t('account.passkey.confirmDeleteTitle')}</DialogTitle>
-            <DialogDescription>{t('account.passkey.confirmDelete')}</DialogDescription>
-          </DialogHeader>
-          <DialogFooter>
-            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
-              {t('account.passkey.cancel')}
-            </Button>
-            <Button variant="destructive" onClick={handleDelete} disabled={deletingId !== null}>
-              {deletingId && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {t('account.passkey.delete')}
-            </Button>
-          </DialogFooter>
-        </DialogContent>
-      </Dialog>
     </>
   )
 }

+ 14 - 40
src/features/sms/Components/SmsConversation.tsx

@@ -2,20 +2,11 @@
 
 import { useState, useTransition, useRef, useEffect, useCallback } from 'react'
 import { useTranslations } from 'next-intl'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Textarea } from '@/components/ui/textarea'
 import { handleGated } from '@/components/upgrade-gate'
 import { SmsTemplateMenu } from './SmsTemplateMenu'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { Loader2, Send, MessageSquare, ChevronUp, Trash2 } from 'lucide-react'
 import { cn } from '@/lib/utils'
 import { sendSmsToCustomer, getConversation, deleteSmsMessage } from '../Actions/smsActions'
@@ -63,8 +54,7 @@ export function SmsConversation({
   const [nextCursor, setNextCursor] = useState<string | null>(initialNextCursor)
   const [newMessage, setNewMessage] = useState('')
   const [mounted, setMounted] = useState(false)
-  const [deleteTarget, setDeleteTarget] = useState<Message | null>(null)
-  const [isDeleting, setIsDeleting] = useState(false)
+  const confirm = useConfirm()
 
   useEffect(() => {
     setMounted(true)
@@ -184,9 +174,16 @@ export function SmsConversation({
     })
   }
 
-  const handleDeleteMessage = async () => {
-    if (!deleteTarget) return
-    setIsDeleting(true)
+  const handleDeleteMessage = async (deleteTarget: Message) => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription'),
+      confirmLabel: tc('delete'),
+      cancelLabel: tc('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     // An action that cannot reach the server throws instead of answering, so
     // it is caught and reported the way a refusal is.
     const result = await deleteSmsMessage(deleteTarget.id).catch(() => null)
@@ -196,8 +193,6 @@ export function SmsConversation({
     } else {
       toast.error(result?.error || t('deleteError'))
     }
-    setIsDeleting(false)
-    setDeleteTarget(null)
   }
 
   const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -257,7 +252,7 @@ export function SmsConversation({
               {isOutbound && (
                 <button
                   type="button"
-                  onClick={() => setDeleteTarget(msg)}
+                  onClick={() => handleDeleteMessage(msg)}
                   className="mr-2 self-center opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
                   title={t('deleteMessage')}
                 >
@@ -284,7 +279,7 @@ export function SmsConversation({
               {!isOutbound && (
                 <button
                   type="button"
-                  onClick={() => setDeleteTarget(msg)}
+                  onClick={() => handleDeleteMessage(msg)}
                   className="ml-2 self-center opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
                   title={t('deleteMessage')}
                 >
@@ -338,27 +333,6 @@ export function SmsConversation({
           </p>
         )}
       </div>
-
-      {/* Delete confirmation dialog */}
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteDescription')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={isDeleting}>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDeleteMessage}
-              disabled={isDeleting}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 16 - 42
src/features/status-reports/Components/StatusReportList.tsx

@@ -16,6 +16,7 @@ import {
   MessageCircle,
 } from 'lucide-react'
 import { Card, CardContent } from '@/components/ui/card'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Badge } from '@/components/ui/badge'
 import {
@@ -35,16 +36,6 @@ import {
 } from '@/components/ui/context-menu'
 import { TableContextMenuHint } from '@/components/table-context-menu-hint'
 import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
 import { toast } from 'sonner'
 import { CreateStatusReportDialog } from './CreateStatusReportDialog'
 import { SendStatusReportDialog } from './SendStatusReportDialog'
@@ -108,8 +99,7 @@ export function StatusReportList({
   const [showCreate, setShowCreate] = useState(false)
   const tableNav = useTableKeyboardNav()
   const [sendReportId, setSendReportId] = useState<string | null>(null)
-  const [deleteReportId, setDeleteReportId] = useState<string | null>(null)
-  const [deleting, setDeleting] = useState(false)
+  const confirm = useConfirm()
   const [detailReport, setDetailReport] = useState<StatusReportSummary | null>(null)
 
   function copyLink(publicToken: string) {
@@ -122,11 +112,18 @@ export function StatusReportList({
     window.open(`/share/status-report/${organizationId}/${publicToken}`, '_blank')
   }
 
-  async function confirmDelete() {
-    if (!deleteReportId) return
-    setDeleting(true)
+  async function handleDelete(reportId: string) {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteConfirm'),
+      confirmLabel: t('delete'),
+      cancelLabel: t('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     try {
-      const result = await deleteStatusReport(deleteReportId)
+      const result = await deleteStatusReport(reportId)
       if (result.success) {
         toast.success(t('deleted'))
         router.refresh()
@@ -135,9 +132,6 @@ export function StatusReportList({
       }
     } catch {
       toast.error(t('deleteFailed'))
-    } finally {
-      setDeleting(false)
-      setDeleteReportId(null)
     }
   }
 
@@ -270,7 +264,7 @@ export function StatusReportList({
                       variant="ghost"
                       size="icon"
                       className="h-9 w-9 text-destructive hover:text-destructive"
-                      onClick={() => setDeleteReportId(report.id)}
+                      onClick={() => handleDelete(report.id)}
                       aria-label={t('delete')}
                     >
                       <Trash2 className="h-4 w-4" />
@@ -385,7 +379,7 @@ export function StatusReportList({
                                 variant="ghost"
                                 size="sm"
                                 className="h-7 px-2 text-destructive hover:text-destructive"
-                                onClick={() => setDeleteReportId(report.id)}
+                                onClick={() => handleDelete(report.id)}
                               >
                                 <Trash2 className="h-3.5 w-3.5" />
                                 <span className="hidden xl:inline ml-1.5">{t('delete')}</span>
@@ -412,7 +406,7 @@ export function StatusReportList({
                         <ContextMenuSeparator />
                         <ContextMenuItem
                           variant="destructive"
-                          onClick={() => setDeleteReportId(report.id)}
+                          onClick={() => handleDelete(report.id)}
                         >
                           <Trash2 className="mr-2 h-4 w-4" />
                           {t('delete')}
@@ -560,26 +554,6 @@ export function StatusReportList({
           telegramEnabled={telegramEnabled}
         />
       )}
-
-      <AlertDialog
-        open={!!deleteReportId}
-        onOpenChange={(open) => {
-          if (!open) setDeleteReportId(null)
-        }}
-      >
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteConfirm')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={deleting}>{t('cancel')}</AlertDialogCancel>
-            <AlertDialogAction variant="destructive" disabled={deleting} onClick={confirmDelete}>
-              {t('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </>
   )
 }

+ 79 - 83
src/features/subscription/Components/subscription-settings.tsx

@@ -5,21 +5,18 @@ import { useEffect, useState } from 'react'
 import { toast } from 'sonner'
 import { useLocale, useTranslations } from 'next-intl'
 import { useRouter } from 'next/navigation'
+import {
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+  ConfirmSubjectList,
+  useConfirm,
+} from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Badge } from '@/components/ui/badge'
 import { Label } from '@/components/ui/label'
 import { AppCard } from '@/components/app-card'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-  AlertDialogTrigger,
-} from '@/components/ui/alert-dialog'
 import {
   Check,
   CheckCircle2,
@@ -91,6 +88,8 @@ export function SubscriptionSettings({
     prorationDate: number
   } | null>(null)
   const [previewLoading, setPreviewLoading] = useState(false)
+  const [upgradeOpen, setUpgradeOpen] = useState(false)
+  const confirm = useConfirm()
 
   const isPaid = plan === 'pro' || plan === 'enterprise'
 
@@ -135,6 +134,7 @@ export function SubscriptionSettings({
   }
 
   const handleUpgradeDialogOpen = async (open: boolean) => {
+    setUpgradeOpen(open)
     if (!open) {
       setUpgradePreview(null)
       return
@@ -157,6 +157,7 @@ export function SubscriptionSettings({
   }
 
   const handleUpgrade = async () => {
+    setUpgradeOpen(false)
     setUpgradeLoading(true)
     try {
       const res = await fetch('/api/protected/subscription/upgrade', {
@@ -181,6 +182,16 @@ export function SubscriptionSettings({
   }
 
   const handleCancel = async () => {
+    const ok = await confirm({
+      title: t('subscription.cancelDialogTitle'),
+      description: t('subscription.cancelDialogDescription', {
+        date: formatDate(currentPeriodEnd),
+      }),
+      confirmLabel: t('subscription.cancelDialogConfirm'),
+      cancelLabel: t('subscription.cancelDialogCancel'),
+      destructive: true,
+    })
+    if (!ok) return
     setCancelLoading(true)
     // An action that cannot reach the server throws instead of answering, so
     // it is caught and reported the way a refusal is.
@@ -669,32 +680,10 @@ export function SubscriptionSettings({
           ) : (
             status === 'active' &&
             !cancelAtPeriodEnd && (
-              <AlertDialog>
-                <AlertDialogTrigger asChild>
-                  <Button variant="destructive">{t('subscription.cancelSubscription')}</Button>
-                </AlertDialogTrigger>
-                <AlertDialogContent>
-                  <AlertDialogHeader>
-                    <AlertDialogTitle>{t('subscription.cancelDialogTitle')}</AlertDialogTitle>
-                    <AlertDialogDescription>
-                      {t('subscription.cancelDialogDescription', {
-                        date: formatDate(currentPeriodEnd),
-                      })}
-                    </AlertDialogDescription>
-                  </AlertDialogHeader>
-                  <AlertDialogFooter>
-                    <AlertDialogCancel>{t('subscription.cancelDialogCancel')}</AlertDialogCancel>
-                    <AlertDialogAction
-                      variant="destructive"
-                      onClick={handleCancel}
-                      disabled={cancelLoading}
-                    >
-                      {cancelLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-                      {t('subscription.cancelDialogConfirm')}
-                    </AlertDialogAction>
-                  </AlertDialogFooter>
-                </AlertDialogContent>
-              </AlertDialog>
+              <Button variant="destructive" onClick={handleCancel} disabled={cancelLoading}>
+                {cancelLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+                {t('subscription.cancelSubscription')}
+              </Button>
             )
           )}
         </AppCard>
@@ -706,56 +695,63 @@ export function SubscriptionSettings({
           title={t('subscription.upgradeTitle')}
           description={t('subscription.upgradeToEnterpriseDescription')}
         >
-          <AlertDialog onOpenChange={handleUpgradeDialogOpen}>
-            <AlertDialogTrigger asChild>
-              <Button variant="outline" size="sm" disabled={upgradeLoading}>
-                {upgradeLoading ? (
-                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
-                ) : (
-                  <Crown className="mr-2 h-4 w-4" />
-                )}
-                {t('subscription.upgradeToEnterprise')}
-              </Button>
-            </AlertDialogTrigger>
-            <AlertDialogContent>
-              <AlertDialogHeader>
-                <AlertDialogTitle>{t('subscription.upgradeDialogTitle')}</AlertDialogTitle>
-                <AlertDialogDescription>
-                  {t('subscription.upgradeDialogDescription')}
-                </AlertDialogDescription>
-              </AlertDialogHeader>
-              {previewLoading && (
-                <div className="flex items-center gap-2 text-sm text-muted-foreground">
-                  <Loader2 className="h-4 w-4 animate-spin" />
-                  {t('subscription.upgradeCalculating')}
-                </div>
-              )}
-              {upgradePreview && (
-                <div className="rounded-md border bg-muted/50 p-3 text-sm">
-                  <p>
-                    {t('subscription.upgradeAmountDue')}:{' '}
-                    <span className="font-semibold">
-                      {formatCurrency(
-                        upgradePreview.amountDue,
-                        upgradePreview.currency.toUpperCase(),
-                        'code'
-                      )}
-                    </span>
-                  </p>
-                </div>
-              )}
-              <AlertDialogFooter>
-                <AlertDialogCancel>{t('subscription.cancelDialogCancel')}</AlertDialogCancel>
-                <AlertDialogAction
+          <Button
+            variant="outline"
+            size="sm"
+            disabled={upgradeLoading}
+            onClick={() => handleUpgradeDialogOpen(true)}
+          >
+            {upgradeLoading ? (
+              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+            ) : (
+              <Crown className="mr-2 h-4 w-4" />
+            )}
+            {t('subscription.upgradeToEnterprise')}
+          </Button>
+          {/* Not a plain question: the amount due is worked out while the prompt
+              is open, and the upgrade waits for it. */}
+          <ConfirmFrame
+            open={upgradeOpen}
+            onDismiss={() => handleUpgradeDialogOpen(false)}
+            title={t('subscription.upgradeDialogTitle')}
+            icon={Crown}
+            footer={
+              <>
+                <ConfirmFrameCancel>{t('subscription.cancelDialogCancel')}</ConfirmFrameCancel>
+                <ConfirmFrameAction
                   onClick={handleUpgrade}
                   disabled={upgradeLoading || previewLoading || !upgradePreview}
                 >
-                  {upgradeLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                   {t('subscription.upgradeConfirm')}
-                </AlertDialogAction>
-              </AlertDialogFooter>
-            </AlertDialogContent>
-          </AlertDialog>
+                </ConfirmFrameAction>
+              </>
+            }
+          >
+            <ConfirmFrameText>
+              <p>{t('subscription.upgradeDialogDescription')}</p>
+              {previewLoading && (
+                <p className="flex items-center gap-2">
+                  <Loader2 className="h-4 w-4 animate-spin" />
+                  {t('subscription.upgradeCalculating')}
+                </p>
+              )}
+            </ConfirmFrameText>
+            {upgradePreview && (
+              <ConfirmSubjectList
+                divided
+                rows={[
+                  {
+                    label: t('subscription.upgradeAmountDue'),
+                    detail: formatCurrency(
+                      upgradePreview.amountDue,
+                      upgradePreview.currency.toUpperCase(),
+                      'code'
+                    ),
+                  },
+                ]}
+              />
+            )}
+          </ConfirmFrame>
         </AppCard>
       )}
     </div>

+ 14 - 38
src/features/telegram/Components/TelegramConversation.tsx

@@ -3,19 +3,10 @@
 import { useState, useTransition, useRef, useEffect, useCallback } from 'react'
 import { useTranslations } from 'next-intl'
 import { setActiveConversation } from '@/features/messaging/activeConversation'
+import { useConfirm } from '@/components/confirm-dialog'
 import { Button } from '@/components/ui/button'
 import { Textarea } from '@/components/ui/textarea'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
-import { Loader2, Send, ChevronUp } from 'lucide-react'
+import { Loader2, Send, ChevronUp, Trash2 } from 'lucide-react'
 import { TelegramConnectCard } from './TelegramQrCode'
 import { cn } from '@/lib/utils'
 import {
@@ -60,8 +51,7 @@ export function TelegramConversation({
   const [nextCursor, setNextCursor] = useState<string | null>(initialNextCursor)
   const [newMessage, setNewMessage] = useState('')
   const [mounted, setMounted] = useState(false)
-  const [deleteTarget, setDeleteTarget] = useState<TelegramMessage | null>(null)
-  const [isDeleting, setIsDeleting] = useState(false)
+  const confirm = useConfirm()
   const [isSending, startSend] = useTransition()
   const [isLoadingMore, startLoadMore] = useTransition()
   const scrollAreaRef = useRef<HTMLDivElement>(null)
@@ -165,9 +155,16 @@ export function TelegramConversation({
     })
   }
 
-  const handleDeleteMessage = async () => {
-    if (!deleteTarget) return
-    setIsDeleting(true)
+  const handleDeleteMessage = async (deleteTarget: TelegramMessage) => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription'),
+      confirmLabel: tc('delete'),
+      cancelLabel: tc('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     // An action that cannot reach the server throws instead of answering, so
     // it is caught and reported the way a refusal is.
     const result = await deleteTelegramMessage(deleteTarget.id).catch(() => null)
@@ -177,8 +174,6 @@ export function TelegramConversation({
     } else {
       toast.error(result?.error || t('deleteError'))
     }
-    setIsDeleting(false)
-    setDeleteTarget(null)
   }
 
   const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -243,7 +238,7 @@ export function TelegramConversation({
             msg={msg}
             mounted={mounted}
             deleteLabel={t('deleteMessage')}
-            onDelete={setDeleteTarget}
+            onDelete={handleDeleteMessage}
           />
         ))}
         <div ref={bottomRef} />
@@ -272,25 +267,6 @@ export function TelegramConversation({
           </Button>
         </div>
       </div>
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>{t('deleteDescription')}</AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={isDeleting}>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDeleteMessage}
-              disabled={isDeleting}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 14 - 40
src/features/telegram/Components/TelegramMessagesClient.tsx

@@ -3,17 +3,8 @@
 import { useState, useEffect, useCallback, useTransition, useRef } from 'react'
 import { useSearchParams, useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
-import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
-import { Loader2 } from 'lucide-react'
+import { Trash2 } from 'lucide-react'
+import { useConfirm } from '@/components/confirm-dialog'
 import { toast } from 'sonner'
 import { getTelegramConversation, deleteTelegramConversation } from '../Actions/telegramActions'
 import { getRecentTelegramThreads } from '../Actions/telegramThreadActions'
@@ -75,8 +66,7 @@ export function TelegramMessagesClient({
   } | null>(null)
   const [loadingConversation, setLoadingConversation] = useState(false)
   const [isLoadingMore, startLoadMore] = useTransition()
-  const [deleteTarget, setDeleteTarget] = useState<TelegramThread | null>(null)
-  const [isDeleting, setIsDeleting] = useState(false)
+  const confirm = useConfirm()
 
   const normalizeMessages = (msgs: TelegramMessage[]) =>
     msgs.map((m) => ({
@@ -164,9 +154,16 @@ export function TelegramMessagesClient({
     }
   }, [threads.length])
 
-  const handleDeleteConversation = async () => {
-    if (!deleteTarget) return
-    setIsDeleting(true)
+  const handleDeleteConversation = async (deleteTarget: TelegramThread) => {
+    const ok = await confirm({
+      title: t('deleteTitle'),
+      description: t('deleteDescription', { name: deleteTarget.customerName }),
+      confirmLabel: tc('delete'),
+      cancelLabel: tc('cancel'),
+      icon: Trash2,
+      destructive: true,
+    })
+    if (!ok) return
     // An action that cannot reach the server throws instead of answering, so
     // it is caught and reported the way a refusal is.
     const result = await deleteTelegramConversation(deleteTarget.customerId).catch(() => null)
@@ -181,8 +178,6 @@ export function TelegramMessagesClient({
     } else {
       toast.error(result?.error || t('deleteError'))
     }
-    setIsDeleting(false)
-    setDeleteTarget(null)
   }
 
   useEffect(() => {
@@ -216,30 +211,9 @@ export function TelegramMessagesClient({
         loadingConversation={loadingConversation}
         threads={threads}
         onBack={handleBack}
-        onDeleteThread={setDeleteTarget}
+        onDeleteThread={handleDeleteConversation}
         t={t}
       />
-      <AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
-        <AlertDialogContent>
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('deleteTitle')}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {t('deleteDescription', { name: deleteTarget?.customerName ?? '' })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel disabled={isDeleting}>{tc('cancel')}</AlertDialogCancel>
-            <AlertDialogAction
-              onClick={handleDeleteConversation}
-              disabled={isDeleting}
-              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
-            >
-              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
-              {tc('delete')}
-            </AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 39 - 44
src/features/vehicles/Components/service-edit/NotesSection.tsx

@@ -5,13 +5,13 @@ import { useTranslations } from 'next-intl'
 import { toast } from 'sonner'
 import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
 import {
-  AlertDialog,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
+  ConfirmConsequenceList,
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+} from '@/components/confirm-dialog'
+import { Checkbox } from '@/components/ui/checkbox'
 import { Button } from '@/components/ui/button'
 import { Eye, FileText, Loader2, Lock, Sparkles } from 'lucide-react'
 import { AppCard } from '@/components/app-card'
@@ -124,47 +124,42 @@ export function NotesSection({
   const internalHasContent = hasContent(internalNotes)
 
   const aiDialog = (
-    <AlertDialog open={showDialog} onOpenChange={setShowDialog}>
-      <AlertDialogContent>
-        <AlertDialogHeader>
-          <AlertDialogTitle className="flex items-center gap-2">
-            <Sparkles className="h-4 w-4" />
-            {t('aiDialogTitle')}
-          </AlertDialogTitle>
-          <AlertDialogDescription>{t('aiDialogDescription')}</AlertDialogDescription>
-        </AlertDialogHeader>
-        {notesHaveContent && (
-          <p className="text-sm text-amber-600 dark:text-amber-400">
-            {t('aiOverwriteDescription')}
-          </p>
-        )}
-        <div className="flex items-center gap-2">
-          <input
-            type="checkbox"
-            id="dont-show-again"
-            checked={dontShowAgain}
-            onChange={(e) => setDontShowAgain(e.target.checked)}
-            className="h-4 w-4 rounded border-gray-300"
-          />
-          <label htmlFor="dont-show-again" className="text-sm text-muted-foreground">
-            {t('aiDontShowAgain')}
-          </label>
-        </div>
-        <AlertDialogFooter>
-          <Button variant="outline" onClick={() => setShowDialog(false)}>
-            {t('aiOverwriteCancel')}
-          </Button>
+    <ConfirmFrame
+      open={showDialog}
+      onDismiss={() => setShowDialog(false)}
+      title={t('aiDialogTitle')}
+      icon={Sparkles}
+      footer={
+        <>
+          <ConfirmFrameCancel>{t('aiOverwriteCancel')}</ConfirmFrameCancel>
           {notesHaveContent && (
-            <Button variant="outline" onClick={() => handleGenerate('append')}>
+            <ConfirmFrameAction variant="outline" onClick={() => handleGenerate('append')}>
               {t('aiOverwriteAppend')}
-            </Button>
+            </ConfirmFrameAction>
           )}
-          <Button onClick={() => handleGenerate('replace')}>
+          <ConfirmFrameAction onClick={() => handleGenerate('replace')}>
             {notesHaveContent ? t('aiOverwriteReplace') : t('aiGenerate')}
-          </Button>
-        </AlertDialogFooter>
-      </AlertDialogContent>
-    </AlertDialog>
+          </ConfirmFrameAction>
+        </>
+      }
+    >
+      <ConfirmFrameText className={notesHaveContent ? 'pb-1' : undefined}>
+        <p>{t('aiDialogDescription')}</p>
+      </ConfirmFrameText>
+      {notesHaveContent && (
+        <ConfirmConsequenceList lines={[{ text: t('aiOverwriteDescription'), emphasis: true }]} />
+      )}
+      <div className="border-card-edge/45 flex items-center gap-2.5 border-t px-5 py-3">
+        <Checkbox
+          id="dont-show-again"
+          checked={dontShowAgain}
+          onCheckedChange={(checked) => setDontShowAgain(checked === true)}
+        />
+        <label htmlFor="dont-show-again" className="text-muted-foreground text-[13px]">
+          {t('aiDontShowAgain')}
+        </label>
+      </div>
+    </ConfirmFrame>
   )
 
   const isLocked = (target: 'public' | 'internal') =>

+ 23 - 27
src/features/vehicles/Components/service-page/LeaveUnsavedDialog.tsx

@@ -2,15 +2,11 @@
 
 import { useTranslations } from 'next-intl'
 import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
+  ConfirmFrame,
+  ConfirmFrameAction,
+  ConfirmFrameCancel,
+  ConfirmFrameText,
+} from '@/components/confirm-dialog'
 
 /**
  * A link was clicked with edits on the page, and the save it waited for was
@@ -32,24 +28,24 @@ export function LeaveUnsavedDialog({
 }) {
   const t = useTranslations('service.leaveUnsaved')
   return (
-    <AlertDialog open={open} onOpenChange={(next) => !next && onStay()}>
-      <AlertDialogContent>
-        <AlertDialogHeader>
-          <AlertDialogTitle>{t('title')}</AlertDialogTitle>
-          <AlertDialogDescription asChild>
-            <div className="space-y-2">
-              <p className="font-medium text-foreground">{reason || t('fallbackReason')}</p>
-              <p>{t('hint')}</p>
-            </div>
-          </AlertDialogDescription>
-        </AlertDialogHeader>
-        <AlertDialogFooter>
-          <AlertDialogCancel>{t('stay')}</AlertDialogCancel>
-          <AlertDialogAction variant="destructive" onClick={onLeave}>
+    <ConfirmFrame
+      open={open}
+      onDismiss={onStay}
+      title={t('title')}
+      destructive
+      footer={
+        <>
+          <ConfirmFrameCancel>{t('stay')}</ConfirmFrameCancel>
+          <ConfirmFrameAction destructive onClick={onLeave}>
             {t('leave')}
-          </AlertDialogAction>
-        </AlertDialogFooter>
-      </AlertDialogContent>
-    </AlertDialog>
+          </ConfirmFrameAction>
+        </>
+      }
+    >
+      <ConfirmFrameText>
+        <p className="text-foreground font-medium">{reason || t('fallbackReason')}</p>
+        <p>{t('hint')}</p>
+      </ConfirmFrameText>
+    </ConfirmFrame>
   )
 }