Skip to content

Colota - Android GPS Location tracker

33.4 KB
Raw Blame
import React from "react"
import { render, fireEvent, waitFor, act } from "@testing-library/react-native"
import { DeviceEventEmitter } from "react-native"

jest.mock("../../hooks/useTheme", () => ({
  useTheme: () => ({
    colors: {
      primary: "#0d9488",
      primaryDark: "#115E59",
      text: "#000",
      textSecondary: "#6b7280",
      textLight: "#9ca3af",
      card: "#fff",
      border: "#e5e7eb",
      background: "#fff",
      backgroundElevated: "#f9fafb",
      success: "#22c55e",
      warning: "#f59e0b",
      info: "#3b82f6",
      error: "#ef4444",
      placeholder: "#9ca3af",
      textOnPrimary: "#fff",
      overlay: "rgba(0,0,0,0.5)"
    }
  })
}))

jest.mock("@react-navigation/native", () => ({
  useFocusEffect: (cb: () => (() => void) | void) => {
    const R = require("react")
    R.useEffect(() => {
      const cleanup = cb()
      return typeof cleanup === "function" ? cleanup : undefined
    }, [cb])
  }
}))

const mockGetAutoExportStatus = jest.fn().mockResolvedValue({
  enabled: false,
  format: "geojson",
  interval: "daily",
  uri: null,
  mode: "all",
  lastExportTimestamp: 0,
  nextExportTimestamp: 0,
  fileCount: 0,
  retentionCount: 10,
  lastFileName: null,
  lastRowCount: 0,
  lastError: null,
  timeOfDay: "00:00",
  weeklyDow: 1,
  monthlyDom: 1,
  filenameTemplate: "colota_export_{date}_{time}",
  deviceModel: "Pixel 7"
})
const mockSaveSetting = jest.fn().mockResolvedValue(undefined)
const mockScheduleAutoExport = jest.fn().mockResolvedValue(true)
const mockCancelAutoExport = jest.fn().mockResolvedValue(true)
const mockRescheduleAutoExport = jest.fn().mockResolvedValue(true)
const mockPickExportDirectory = jest.fn().mockResolvedValue(null)
const mockRunAutoExportNow = jest.fn().mockResolvedValue(true)
const mockGetSetting = jest.fn().mockResolvedValue(null)
const mockGetExportFiles = jest.fn().mockResolvedValue([])
const mockShareExportFile = jest.fn().mockResolvedValue(true)

jest.mock("../../services/NativeLocationService", () => ({
  __esModule: true,
  default: {
    getAutoExportStatus: function () {
      return mockGetAutoExportStatus.apply(null, arguments)
    },
    saveSetting: function () {
      return mockSaveSetting.apply(null, arguments)
    },
    getSetting: function () {
      return mockGetSetting.apply(null, arguments)
    },
    scheduleAutoExport: function () {
      return mockScheduleAutoExport.apply(null, arguments)
    },
    cancelAutoExport: function () {
      return mockCancelAutoExport.apply(null, arguments)
    },
    rescheduleAutoExport: function () {
      return mockRescheduleAutoExport.apply(null, arguments)
    },
    pickExportDirectory: function () {
      return mockPickExportDirectory.apply(null, arguments)
    },
    runAutoExportNow: function () {
      return mockRunAutoExportNow.apply(null, arguments)
    },
    getExportFiles: function () {
      return mockGetExportFiles.apply(null, arguments)
    },
    shareExportFile: function () {
      return mockShareExportFile.apply(null, arguments)
    }
  }
}))

const mockShowAlert = jest.fn()

jest.mock("../../services/modalService", () => ({
  showAlert: function () {
    return mockShowAlert.apply(null, arguments)
  }
}))

jest.mock("../../utils/logger", () => ({
  logger: { error: jest.fn(), warn: jest.fn() }
}))

jest.mock("../../utils/exportConverters", () => {
  const R = require("react")
  const { View } = require("react-native")
  const icon = () => R.createElement(View, null)
  return {
    // Real template helpers so the preview assertion exercises the shipped renderer, not a stub.
    ...jest.requireActual("../../utils/exportConverters"),
    EXPORT_FORMAT_KEYS: ["csv", "geojson", "gpx", "kml"],
    EXPORT_FORMATS: {
      csv: { label: "CSV", extension: ".csv", subtitle: "Spreadsheet", description: "desc", icon },
      geojson: { label: "GeoJSON", extension: ".geojson", subtitle: "Geographic", description: "desc", icon },
      gpx: { label: "GPX", extension: ".gpx", subtitle: "GPS Exchange", description: "desc", icon },
      kml: { label: "KML", extension: ".kml", subtitle: "Keyhole", description: "desc", icon }
    }
  }
})

jest.mock("../../components", () => {
  const R = require("react")
  const RN = require("react-native")
  const { EXPORT_FORMATS, EXPORT_FORMAT_KEYS } = require("../../utils/exportConverters")
  return {
    TextField: require("../../testing/componentStubs").TextFieldStub,
    RadioRow: function (props: any) {
      return R.createElement(
        RN.Pressable,
        { testID: props.testID, onPress: props.onPress, accessibilityState: { checked: props.selected } },
        R.createElement(RN.Text, null, props.label),
        props.sub ? R.createElement(RN.Text, null, props.sub) : null
      )
    },
    Toggle: function (props: any) {
      return require("react").createElement(require("react-native").Switch, {
        testID: props.testID,
        value: props.value,
        onValueChange: props.onValueChange,
        disabled: props.disabled,
        accessibilityLabel: props.accessibilityLabel
      })
    },
    Container: (props: any) => R.createElement(RN.View, null, props.children),
    Card: (props: any) => R.createElement(RN.View, null, props.children),
    SectionTitle: (props: any) => R.createElement(RN.Text, null, props.children),
    Divider: () => R.createElement(RN.View, null),
    RadioDot: (props: any) => R.createElement(RN.View, { testID: props.selected ? "radio-selected" : "radio" }),
    ChipGroup: (props: any) =>
      R.createElement(
        RN.View,
        null,
        props.options.map((opt: any) =>
          R.createElement(
            RN.Pressable,
            { key: opt.value, onPress: () => props.onSelect(opt.value), testID: `chip-${opt.value}` },
            R.createElement(RN.Text, null, opt.label)
          )
        )
      ),
    ListItem: ({ label, sub, testID, onPress }: any) =>
      R.createElement(
        RN.Pressable,
        { testID, onPress },
        R.createElement(RN.Text, null, label),
        R.createElement(RN.Text, null, sub)
      ),
    ExportFormatDialog: (props: any) =>
      props.visible
        ? R.createElement(
            RN.View,
            null,
            EXPORT_FORMAT_KEYS.map((key: any) =>
              R.createElement(
                RN.Pressable,
                { key, onPress: () => props.onSelect(key), testID: `format-${key}` },
                R.createElement(RN.Text, null, EXPORT_FORMATS[key].label)
              )
            )
          )
        : null,
    FloatingSaveIndicator: () => null,
    SettingRow: (props: any) =>
      R.createElement(
        RN.View,
        null,
        R.createElement(RN.Text, null, props.label),
        props.hint && R.createElement(RN.Text, null, props.hint),
        props.children
      ),
    Button: (props: any) =>
      R.createElement(
        RN.Pressable,
        { onPress: props.onPress, disabled: props.disabled },
        R.createElement(RN.Text, null, props.title)
      ),
    TimePicker: (props: any) =>
      R.createElement(
        RN.View,
        { testID: "time-picker" },
        R.createElement(RN.Text, null, props.value),
        R.createElement(
          RN.Pressable,
          { testID: "time-picker-bump", onPress: () => props.onChange("06:30") },
          R.createElement(RN.Text, null, "bump")
        )
      ),
    NumericInput: (props: any) =>
      R.createElement(
        RN.View,
        null,
        R.createElement(RN.Text, null, props.label),
        props.hint && R.createElement(RN.Text, null, props.hint),
        R.createElement(RN.TextInput, {
          testID: `numeric-input-${props.label}`,
          value: props.value,
          onChangeText: props.onChange,
          onBlur: props.onBlur
        })
      )
  }
})

jest.mock("lucide-react-native", () => {
  const R = require("react")
  const RN = require("react-native")
  const stub = (name: any) => () => R.createElement(RN.Text, null, name)
  return {
    FolderOpen: stub("FolderOpen"),
    CircleCheckBig: stub("CircleCheckBig"),
    Share2: stub("Share2"),
    TriangleAlert: stub("TriangleAlert")
  }
})

import { AutoExportScreen } from "../AutoExportScreen"

describe("AutoExportScreen", () => {
  const mockProps = { navigation: { navigate: jest.fn() } } as any

  beforeEach(() => {
    jest.clearAllMocks()
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: null,
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 1,
      monthlyDom: 1,
      filenameTemplate: "colota_export_{date}_{time}",
      deviceModel: "Pixel 7"
    })
    mockGetExportFiles.mockResolvedValue([])
  })

  it("renders subtitle", async () => {
    // The "Auto-Export" page title lives in the navigation header, not the screen body
    // (removed to avoid duplicating the nav-bar title), so we only assert on the subtitle.
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Automatically export your location data on a schedule")).toBeTruthy()
    })
  })

  it("names the stored format on the row, and offers the rest in the shared dialog", async () => {
    const { getByText, getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => expect(getByTestId("auto-export-format")).toBeTruthy())
    expect(getByText("GeoJSON")).toBeTruthy()

    fireEvent.press(getByTestId("auto-export-format"))

    expect(getByTestId("format-csv")).toBeTruthy()
    expect(getByTestId("format-gpx")).toBeTruthy()
    expect(getByTestId("format-kml")).toBeTruthy()
  })

  it("renders all interval options including monthly", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Daily")).toBeTruthy()
      expect(getByText("Weekly")).toBeTruthy()
      expect(getByText("Monthly")).toBeTruthy()
    })
  })

  it("renders export mode options", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("All data")).toBeTruthy()
      expect(getByText("Since last export")).toBeTruthy()
    })
  })

  it("shows 'Never' when no export has occurred", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Never")).toBeTruthy()
    })
  })

  it("shows last export date when available", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "csv",
      interval: "weekly",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000,
      nextExportTimestamp: 1700604800,
      fileCount: 5
    })

    const { queryByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(queryByText("Never")).toBeNull()
    })
  })

  it("shows alert when enabling without directory", async () => {
    const { getByRole } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByRole("switch")).toBeTruthy()
    })

    fireEvent(getByRole("switch"), "valueChange", true)

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith("No Directory", "Please select an export directory first.", "info")
    })
  })

  it("enables auto-export when directory is set", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    const { getByRole } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByRole("switch")).toBeTruthy()
    })

    fireEvent(getByRole("switch"), "valueChange", true)

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportEnabled", "true")
      expect(mockScheduleAutoExport).toHaveBeenCalled()
    })
  })

  it("disabling auto-export cancels the schedule", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 86400,
      fileCount: 0
    })

    const { getByRole } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByRole("switch")).toBeTruthy()
    })

    fireEvent(getByRole("switch"), "valueChange", false)

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportEnabled", "false")
      expect(mockCancelAutoExport).toHaveBeenCalled()
    })
  })

  it("selecting directory picker calls native module", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Select directory")).toBeTruthy()
    })

    fireEvent.press(getByText("Select directory"))

    await waitFor(() => {
      expect(mockPickExportDirectory).toHaveBeenCalled()
    })
  })

  it("changing format saves the setting", async () => {
    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => expect(getByTestId("auto-export-format")).toBeTruthy())
    fireEvent.press(getByTestId("auto-export-format"))

    fireEvent.press(getByTestId("format-csv"))

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportFormat", "csv")
    })
  })

  it("changing interval saves the setting", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 86400,
      fileCount: 0
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Weekly")).toBeTruthy()
    })

    fireEvent.press(getByText("Weekly"))

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportInterval", "weekly")
    })
  })

  it("shows next export when enabled with last export", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000,
      nextExportTimestamp: 1700086400,
      fileCount: 3
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Next export")).toBeTruthy()
      expect(getByText("Export files")).toBeTruthy()
      expect(getByText("3")).toBeTruthy()
    })
  })

  it("hides next export when disabled", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000,
      nextExportTimestamp: 0,
      fileCount: 3
    })

    const { queryByText, getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(queryByText("Next export")).toBeNull()
      expect(getByText("Export files")).toBeTruthy()
    })
  })

  it("changing mode saves the setting", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Since last export")).toBeTruthy()
    })

    fireEvent.press(getByText("Since last export"))

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMode", "incremental")
    })
  })

  it("changing retention saves the setting on blur", async () => {
    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByTestId("numeric-input-Files to keep")).toBeTruthy()
    })

    const input = getByTestId("numeric-input-Files to keep")
    fireEvent.changeText(input, "25")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "25")
    })
  })

  it("retention 0 saves as unlimited", async () => {
    const { getByTestId, getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("0 keeps every file. Counts the Colota exports in the chosen folder.")).toBeTruthy()
    })

    const input = getByTestId("numeric-input-Files to keep")
    fireEvent.changeText(input, "0")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "0")
    })
  })

  it("saves a valid filename template on blur", async () => {
    const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
    })

    const input = getByDisplayValue("colota_export_{date}_{time}")
    fireEvent.changeText(input, "{device}_colota_export-{date}_{time}")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportFilenameTemplate", "{device}_colota_export-{date}_{time}")
    })
  })

  it("rejects a filename template without the marker and reverts the field", async () => {
    const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
    })

    const input = getByDisplayValue("colota_export_{date}_{time}")
    fireEvent.changeText(input, "backup_{date}_{time}")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith("Invalid Template", expect.any(String), "warning")
    })
    expect(mockSaveSetting).not.toHaveBeenCalledWith("autoExportFilenameTemplate", "backup_{date}_{time}")
    expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
  })

  it("rejects a filename template missing the time token", async () => {
    const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
    })

    const input = getByDisplayValue("colota_export_{date}_{time}")
    fireEvent.changeText(input, "colota_export_{date}")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith("Invalid Template", expect.any(String), "warning")
    })
    expect(mockSaveSetting).not.toHaveBeenCalledWith("autoExportFilenameTemplate", "colota_export_{date}")
  })

  it("previews the filename the exporter will actually write", async () => {
    // Pins the JS mirror to the native renderer; drift would otherwise be invisible.
    jest.useFakeTimers().setSystemTime(new Date(2026, 4, 20, 8, 15, 0))
    try {
      const { getByText } = render(<AutoExportScreen {...mockProps} />)

      await waitFor(() => {
        expect(getByText("Preview: colota_export_2026-05-20_0815.geojson")).toBeTruthy()
      })
    } finally {
      jest.useRealTimers()
    }
  })

  it("retention hint reflects per-device scope when the template has a device token", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: null,
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 1,
      monthlyDom: 1,
      filenameTemplate: "{device}_colota_export-{date}_{time}",
      deviceModel: "Pixel 7"
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("0 keeps every file. Counts only this device's exports in the chosen folder.")).toBeTruthy()
    })
  })

  it("shows Export Now button when directory is set", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Export now")).toBeTruthy()
    })
  })

  it("hides Export Now button when no directory is set", async () => {
    const { queryByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(queryByText("Export now")).toBeNull()
    })
  })

  it("Export Now triggers runAutoExportNow", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: false,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Export now")).toBeTruthy()
    })

    fireEvent.press(getByText("Export now"))

    await waitFor(() => {
      expect(mockRunAutoExportNow).toHaveBeenCalled()
    })
  })

  it("shows the export as running when the screen opens mid-run", async () => {
    // The line is component state, so returning to the screen while the worker is still going
    // would have shown nothing; the status map carries the worker's own flag for that.
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      running: true,
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByTestId("export-running")).toBeTruthy()
    })
  })

  it("says so when a manual export found nothing new", async () => {
    // The worker reports a zero-row run with no filename, which read as "Exported 0 locations to
    // null" before.
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      uri: "content://some-uri",
      mode: "incremental",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    render(<AutoExportScreen {...mockProps} />)
    await waitFor(() => expect(mockGetAutoExportStatus).toHaveBeenCalled())

    act(() => {
      DeviceEventEmitter.emit("onAutoExportComplete", { success: true, fileName: null, rowCount: 0, error: null })
    })

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith("Export Complete", "No new locations to export.", "success")
    })
  })

  it("keeps saying the export is running until the worker reports back", async () => {
    // runAutoExportNow only enqueues, so the button's own spinner lasts about a frame while a
    // real export runs for minutes. Nothing on the screen said the work was still going.
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0
    })

    const { getByText, getByTestId, queryByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Export now")).toBeTruthy()
    })
    expect(queryByTestId("export-running")).toBeNull()

    fireEvent.press(getByText("Export now"))
    await waitFor(() => {
      expect(getByTestId("export-running")).toBeTruthy()
    })

    act(() => {
      DeviceEventEmitter.emit("onAutoExportComplete", {
        success: true,
        fileName: "colota-2026-09-06.geojson",
        rowCount: 12,
        error: null
      })
    })

    await waitFor(() => {
      expect(queryByTestId("export-running")).toBeNull()
    })
  })

  it("shows permission lost alert when flag is set", async () => {
    mockGetSetting.mockResolvedValue("true")

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Automatically export your location data on a schedule")).toBeTruthy()
    })

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith(
        "Export Directory Access Lost",
        "The app lost access to the export directory. Please re-select it to resume auto-exports.",
        "warning"
      )
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportPermissionLost", "false")
    })
  })

  it("shows last file name and row count in status", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000,
      nextExportTimestamp: 1700086400,
      fileCount: 3,
      retentionCount: 10,
      lastFileName: "colota_export_2026-03-10_1200.geojson",
      lastRowCount: 42,
      lastError: null
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Last file")).toBeTruthy()
      expect(getByText("colota_export_2026-03-10_1200.geojson")).toBeTruthy()
      expect(getByText("Locations exported")).toBeTruthy()
      expect(getByText("42")).toBeTruthy()
    })
  })

  it("shows error message when lastError is set", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000,
      nextExportTimestamp: 1700086400,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: "IO error: disk full"
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("IO error: disk full")).toBeTruthy()
    })
  })

  it("renders export history with file list", async () => {
    mockGetExportFiles.mockResolvedValue([
      { name: "colota_export_2026-03-10.geojson", size: 1024, lastModified: 1700000000, uri: "content://file1" },
      { name: "colota_export_2026-03-09.geojson", size: 2048, lastModified: 1699913600, uri: "content://file2" }
    ])

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Export history")).toBeTruthy()
      expect(getByText("colota_export_2026-03-10.geojson")).toBeTruthy()
      expect(getByText("colota_export_2026-03-09.geojson")).toBeTruthy()
    })
  })

  it("does not show export history when no files", async () => {
    mockGetExportFiles.mockResolvedValue([])

    const { queryByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(queryByText("Export history")).toBeNull()
    })
  })

  it("handles onAutoExportComplete event for success", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Automatically export your location data on a schedule")).toBeTruthy()
    })

    await act(async () => {
      DeviceEventEmitter.emit("onAutoExportComplete", {
        success: true,
        fileName: "colota_export_2026-03-10.csv",
        rowCount: 100,
        error: null
      })
    })

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith(
        "Export Complete",
        "Exported 100 locations to colota_export_2026-03-10.csv",
        "success"
      )
    })
  })

  it("renders time picker with configured timeOfDay", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "07:45",
      weeklyDow: 1,
      monthlyDom: 1
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("07:45")).toBeTruthy()
    })
  })

  it("changing time of day saves the setting", async () => {
    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByTestId("time-picker")).toBeTruthy()
    })

    fireEvent.press(getByTestId("time-picker-bump"))

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportTimeOfDay", "06:30")
    })
  })

  it("renders weekday chips when interval is weekly", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "weekly",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 3,
      monthlyDom: 1
    })

    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Mon")).toBeTruthy()
      expect(getByText("Sun")).toBeTruthy()
    })

    fireEvent.press(getByText("Fri"))

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportWeeklyDow", "5")
    })
  })

  it("renders day-of-month input when interval is monthly", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "monthly",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 1,
      monthlyDom: 7
    })

    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByTestId("numeric-input-Day of month")).toBeTruthy()
    })

    const input = getByTestId("numeric-input-Day of month")
    fireEvent.changeText(input, "15")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMonthlyDom", "15")
    })
  })

  it("clamps day-of-month to 31", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "monthly",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 0,
      nextExportTimestamp: 0,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 1,
      monthlyDom: 1
    })

    const { getByTestId } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByTestId("numeric-input-Day of month")).toBeTruthy()
    })

    const input = getByTestId("numeric-input-Day of month")
    fireEvent.changeText(input, "99")
    fireEvent(input, "blur")

    await waitFor(() => {
      expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMonthlyDom", "31")
    })
  })

  it("formats Last Export with 24h clock", async () => {
    mockGetAutoExportStatus.mockResolvedValue({
      enabled: true,
      format: "geojson",
      interval: "daily",
      uri: "content://some-uri",
      mode: "all",
      lastExportTimestamp: 1700000000, // 2023-11-14 22:13:20 UTC
      nextExportTimestamp: 1700086400,
      fileCount: 0,
      retentionCount: 10,
      lastFileName: null,
      lastRowCount: 0,
      lastError: null,
      timeOfDay: "00:00",
      weeklyDow: 1,
      monthlyDom: 1
    })

    const { queryAllByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      // Format: "YYYY-MM-DD HH:MM" - assert no AM/PM and digits look right.
      const ampmMatches = queryAllByText(/\b(AM|PM)\b/)
      expect(ampmMatches.length).toBe(0)
    })
  })

  it("handles onAutoExportComplete event for failure", async () => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)

    await waitFor(() => {
      expect(getByText("Automatically export your location data on a schedule")).toBeTruthy()
    })

    await act(async () => {
      DeviceEventEmitter.emit("onAutoExportComplete", {
        success: false,
        fileName: null,
        rowCount: 0,
        error: "Directory permission lost"
      })
    })

    await waitFor(() => {
      expect(mockShowAlert).toHaveBeenCalledWith("Export Failed", "Directory permission lost", "error")
    })
  })

  const renderAndEmit = async (event: Record<string, unknown>) => {
    const { getByText } = render(<AutoExportScreen {...mockProps} />)
    await waitFor(() => expect(getByText("Automatically export your location data on a schedule")).toBeTruthy())
    await act(async () => {
      DeviceEventEmitter.emit("onAutoExportComplete", event)
    })
  }

  it("words a one-row export in the singular", async () => {
    await renderAndEmit({ success: true, fileName: "colota_export_2026-03-10.csv", rowCount: 1, error: null })

    await waitFor(() =>
      expect(mockShowAlert).toHaveBeenCalledWith(
        "Export Complete",
        "Exported 1 location to colota_export_2026-03-10.csv",
        "success"
      )
    )
  })

  it("still says something when a failed export carries no reason", async () => {
    await renderAndEmit({ success: false, fileName: null, rowCount: 0, error: null })

    await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Export Failed", "Unknown error", "error"))
  })
})