@burdenoff/microfe-healthybowl 2026.714.5 → 2026.714.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/generated/wspace-operations.js +6 -7
  2. package/dist/generated/wspace-operations.js.map +1 -1
  3. package/dist/healthybowl/HealthyBowlRoutes.js +111 -95
  4. package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
  5. package/dist/healthybowl/hooks/useWeatherIntelligence.js +224 -0
  6. package/dist/healthybowl/hooks/useWeatherIntelligence.js.map +1 -0
  7. package/dist/healthybowl/pages/weather/FrostRiskCalendarPage.js +258 -0
  8. package/dist/healthybowl/pages/weather/FrostRiskCalendarPage.js.map +1 -0
  9. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js +255 -0
  10. package/dist/healthybowl/pages/weather/WeatherAlertHistoryPage.js.map +1 -0
  11. package/dist/healthybowl/pages/weather/WeatherAnomalyReportPage.js +387 -0
  12. package/dist/healthybowl/pages/weather/WeatherAnomalyReportPage.js.map +1 -0
  13. package/dist/healthybowl/pages/weather/WeatherHistoryPage.js +313 -114
  14. package/dist/healthybowl/pages/weather/WeatherHistoryPage.js.map +1 -1
  15. package/dist/healthybowl/pages/weather/WeatherOverviewPage.js +554 -213
  16. package/dist/healthybowl/pages/weather/WeatherOverviewPage.js.map +1 -1
  17. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js +457 -0
  18. package/dist/healthybowl/pages/weather/WeatherSettingsPage.js.map +1 -0
  19. package/dist/node_modules/date-fns/addDays.js.map +1 -1
  20. package/dist/node_modules/date-fns/locale/ta/_lib/localize.js.map +1 -1
  21. package/dist/node_modules/date-fns/locale/zh-CN/_lib/match.js +15 -15
  22. package/dist/node_modules/date-fns/locale/zh-CN/_lib/match.js.map +1 -1
  23. package/dist/services/assistantApi.js +34 -234
  24. package/dist/services/assistantApi.js.map +1 -1
  25. package/package.json +2 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useWeatherIntelligence.js","names":[],"sources":["../../../src/healthybowl/hooks/useWeatherIntelligence.ts"],"sourcesContent":["/**\n * Weather-Intelligence data hook — historical weather baselines, anomaly\n * reporting, frost-risk calendar, alert events + alert settings\n * (roadmap #20 / BOFF-2892, Historical Weather & Early Warning).\n *\n * Mirrors the raw-gql pattern used by `useDiseaseWarning` (Suppliers / Nursery /\n * Irrigation): the offline codegen doesn't type these operations yet, so they\n * are hand-written `gql` documents executed directly against the live gateway.\n * Every op carries the workspace `context`.\n * @module healthybowl\n */\nimport { useCallback } from 'react';\nimport { gql } from '@apollo/client';\nimport { useLazyQuery, useMutation, useQuery } from '@apollo/client/react';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/** A single month's actual (synced) weather aggregate for one historical year. */\nexport interface WeatherHistoryMonthPoint {\n /** Calendar year (e.g. 2019). */\n year: number;\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Mean temperature for the month, °C. */\n avgTemp: number;\n /** Total accumulated rainfall for the month, mm. */\n totalRainfall: number;\n /** Mean relative humidity for the month, %. */\n avgHumidity: number;\n}\n\n/** A per-month baseline (multi-year average + observed range) for the farm site. */\nexport interface WeatherHistoryBaselinePoint {\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Baseline mean temperature, °C. */\n avgTemp: number;\n /** Coldest baseline temperature seen for this month, °C. */\n tempMin: number;\n /** Warmest baseline temperature seen for this month, °C. */\n tempMax: number;\n /** Baseline mean rainfall, mm. */\n avgRainfall: number;\n /** Lowest baseline rainfall seen for this month, mm. */\n rainfallMin: number;\n /** Highest baseline rainfall seen for this month, mm. */\n rainfallMax: number;\n}\n\n/** Historical weather series + derived baseline for the farm site. */\nexport interface WeatherHistorySeries {\n /** First year covered by the series. */\n startYear: number;\n /** Last year covered by the series. */\n endYear: number;\n /** Number of years the baseline averages over. */\n baselineYears: number;\n /** Provider of the historical data (e.g. \"open-meteo\"). */\n source: string;\n /** True once at least one sync has populated the series. */\n synced: boolean;\n /** ISO-8601 timestamp of the last successful sync, if any. */\n lastSyncedAt?: string | null;\n /** Per-month, per-year observed points. */\n points: WeatherHistoryMonthPoint[];\n /** Per-month baseline (average + range). */\n baseline: WeatherHistoryBaselinePoint[];\n}\n\n/** One month's current-vs-baseline comparison used in the anomaly report. */\nexport interface WeatherAnomalyMonthPoint {\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label (e.g. \"Jan\"). */\n monthName: string;\n /** Current (this-season) value for the metric. */\n currentValue: number;\n /** Baseline average for the metric. */\n baselineAvg: number;\n /** Baseline minimum for the metric. */\n baselineMin: number;\n /** Baseline maximum for the metric. */\n baselineMax: number;\n}\n\n/** A single narrative callout surfaced in the anomaly report. */\nexport interface WeatherAnomalyCallout {\n id: string;\n /** Short headline (e.g. \"Driest June in 8 years\"). */\n title: string;\n /** Severity band: RED | AMBER | GREY. */\n severity: string;\n /** ISO-8601 date the callout refers to. */\n date: string;\n /** Metric the callout concerns (e.g. \"rainfall\" | \"temp\" | \"frost\"). */\n metric: string;\n}\n\n/** Current-season anomaly report against the multi-year baseline. */\nexport interface WeatherAnomalyReport {\n /** Number of years the baseline averages over. */\n baselineYears: number;\n /** First year of the baseline window. */\n startYear: number;\n /** Last year of the baseline window. */\n endYear: number;\n /** Current month number 1–12. */\n currentMonth: number;\n /** Localised/short current-month label. */\n currentMonthName: string;\n /** Rainfall so far this month, mm. */\n rainfallThisMonthMm: number;\n /** Baseline rainfall for this month, mm. */\n rainfallBaselineMm: number;\n /** Rainfall deviation from baseline, %. */\n rainfallDeviationPct: number;\n /** Temperature delta vs baseline, °C. */\n avgTempDeltaC: number;\n /** Frost days observed so far this season. */\n frostDaysThisSeason: number;\n /** Baseline frost days for the season. */\n frostDaysBaseline: number;\n /** Frost-day delta vs baseline. */\n frostDaysDelta: number;\n /** ISO-8601 first-frost date this season, if any. */\n firstFrostDate?: string | null;\n /** ISO-8601 baseline first-frost date, if any. */\n baselineFirstFrostDate?: string | null;\n /** Days earlier(-)/later(+) than the baseline first frost. */\n firstFrostDeltaDays: number;\n /** Per-month rainfall comparison series. */\n monthlyRainfall: WeatherAnomalyMonthPoint[];\n /** Per-month temperature comparison series. */\n monthlyTemperature: WeatherAnomalyMonthPoint[];\n /** Narrative callouts. */\n callouts: WeatherAnomalyCallout[];\n /** ISO-8601 timestamp the report was generated. */\n generatedAt: string;\n /** Provider of the underlying data. */\n source: string;\n /** True once the underlying history has been synced. */\n synced: boolean;\n}\n\n/** A single day cell in the frost-risk calendar. */\nexport interface FrostRiskDay {\n /** ISO-8601 date (YYYY-MM-DD). */\n date: string;\n /** Day of month 1–31. */\n day: number;\n /** Risk band: FROST_HIGH | FROST_WATCH | HEAT | STORM | DISEASE_WINDOW | CLEAR | UNKNOWN. */\n risk: string;\n /** Short label for the cell. */\n label: string;\n /** Longer detail/tooltip text. */\n detail?: string | null;\n /** Forecast/observed minimum temperature, °C. */\n tempMin?: number | null;\n /** Forecast/observed maximum temperature, °C. */\n tempMax?: number | null;\n /** Data source for the cell (e.g. \"forecast\" | \"historical\"). */\n source?: string | null;\n}\n\n/** A month of frost-risk day cells. */\nexport interface FrostRiskCalendar {\n /** Calendar year. */\n year: number;\n /** Month number 1–12. */\n month: number;\n /** Localised/short month label. */\n monthName: string;\n /** Count of days flagged as frost risk in the month. */\n frostRiskDayCount: number;\n /** ISO-8601 historical average first-frost date, if any. */\n historicalFirstFrost?: string | null;\n /** Day cells for the month. */\n days: FrostRiskDay[];\n}\n\n/** A fired weather alert event (delivered / handled / snoozed). */\nexport interface WeatherAlertEvent {\n id: string;\n /** Id of the rule that produced the event. */\n ruleId: string;\n /** Name of the rule that produced the event. */\n ruleName: string;\n /** Alert category: FROST | STORM | HEAT | DISEASE. */\n alertType: string;\n /** Severity band: RED | AMBER | GREY. */\n severity: string;\n /** Alert headline. */\n title: string;\n /** Advisory message shown to the farmer. */\n advisory?: string | null;\n /** Metric evaluated (e.g. \"temp_min\"). */\n metric: string;\n /** Observed metric value at trigger time. */\n observedValue?: number | null;\n /** Threshold the metric was compared against. */\n threshold?: number | null;\n /** Unit label for the metric/threshold (°C, %, mm, km/h). */\n unit?: string | null;\n /** Delivery channels the alert was sent through. */\n channels: string[];\n /** Lifecycle status: delivered | handled | snoozed. */\n status: string;\n /** ISO-8601 timestamp the alert triggered. */\n triggeredAt: string;\n /** ISO-8601 timestamp the alert was handled, if any. */\n handledAt?: string | null;\n /** ISO-8601 timestamp the alert is snoozed until, if any. */\n snoozedUntil?: string | null;\n}\n\n/** Farm-level weather alerting configuration. */\nexport interface WeatherAlertSettings {\n /** In-app notifications enabled. */\n inAppEnabled: boolean;\n /** SMS notifications enabled. */\n smsEnabled: boolean;\n /** Destination SMS number. */\n smsNumber?: string | null;\n /** Email notifications enabled. */\n emailEnabled: boolean;\n /** Webhook delivery enabled. */\n webhookEnabled: boolean;\n /** Destination webhook URL. */\n webhookUrl?: string | null;\n /** Quiet-hours suppression enabled. */\n quietHoursEnabled: boolean;\n /** Quiet-hours start (HH:mm). */\n quietHoursStart?: string | null;\n /** Quiet-hours end (HH:mm). */\n quietHoursEnd?: string | null;\n /** Escalate critical frost alerts past quiet hours. */\n escalateCriticalFrost: boolean;\n /** Lead time (hours) before an event to alert. */\n alertLeadTimeHours: number;\n /** Baseline window (years) for anomaly comparison. */\n baselineYears: number;\n /** Deviation threshold (%) that constitutes an anomaly. */\n deviationThresholdPct: number;\n /** Weekly digest email enabled. */\n weeklyDigestEmail: boolean;\n /** AI advisory generation enabled. */\n aiAdvisoryEnabled: boolean;\n /** Advisory language code (e.g. \"en\"). */\n advisoryLanguage?: string | null;\n /** Unit system: metric | imperial. */\n units?: string | null;\n /** First year of synced history. */\n historyStartYear?: number | null;\n /** Last year of synced history. */\n historyEndYear?: number | null;\n /** ISO-8601 timestamp of the last history sync. */\n historyLastSyncedAt?: string | null;\n}\n\n/** Editable fields for alert-settings upsert (context is attached from the hook). */\nexport interface UpsertWeatherAlertSettingsInput {\n inAppEnabled?: boolean | null;\n smsEnabled?: boolean | null;\n smsNumber?: string | null;\n emailEnabled?: boolean | null;\n webhookEnabled?: boolean | null;\n webhookUrl?: string | null;\n quietHoursEnabled?: boolean | null;\n quietHoursStart?: string | null;\n quietHoursEnd?: string | null;\n escalateCriticalFrost?: boolean | null;\n alertLeadTimeHours?: number | null;\n baselineYears?: number | null;\n deviationThresholdPct?: number | null;\n weeklyDigestEmail?: boolean | null;\n aiAdvisoryEnabled?: boolean | null;\n advisoryLanguage?: string | null;\n units?: string | null;\n}\n\n/** Optional filter for the alert-events lazy loader. */\nexport interface WeatherAlertEventsFilter {\n /** FROST | STORM | HEAT | DISEASE. */\n alertType?: string | null;\n /** delivered | handled | snoozed. */\n status?: string | null;\n}\n\n/** Options accepted by {@link useWeatherIntelligence}. */\nexport interface UseWeatherIntelligenceOptions {\n /** Number of years of history to load for the eager series query. */\n years?: number;\n}\n\n// ── GraphQL documents ────────────────────────────────────────────────────────\n\nconst WEATHER_HISTORY_SERIES_FIELDS = `\n startYear\n endYear\n baselineYears\n source\n synced\n lastSyncedAt\n points {\n year\n month\n monthName\n avgTemp\n totalRainfall\n avgHumidity\n }\n baseline {\n month\n monthName\n avgTemp\n tempMin\n tempMax\n avgRainfall\n rainfallMin\n rainfallMax\n }\n`;\n\nconst WEATHER_ALERT_EVENT_FIELDS = `\n id\n ruleId\n ruleName\n alertType\n severity\n title\n advisory\n metric\n observedValue\n threshold\n unit\n channels\n status\n triggeredAt\n handledAt\n snoozedUntil\n`;\n\nconst WEATHER_ALERT_SETTINGS_FIELDS = `\n inAppEnabled\n smsEnabled\n smsNumber\n emailEnabled\n webhookEnabled\n webhookUrl\n quietHoursEnabled\n quietHoursStart\n quietHoursEnd\n escalateCriticalFrost\n alertLeadTimeHours\n baselineYears\n deviationThresholdPct\n weeklyDigestEmail\n aiAdvisoryEnabled\n advisoryLanguage\n units\n historyStartYear\n historyEndYear\n historyLastSyncedAt\n`;\n\nconst WEATHER_HISTORY_SERIES_QUERY = gql`\n query GetHealthyBowlWeatherHistorySeries($context: ContextInput!, $years: Int) {\n getHealthyBowlWeatherHistorySeries(context: $context, years: $years) {\n ${WEATHER_HISTORY_SERIES_FIELDS}\n }\n }\n`;\n\nconst WEATHER_ANOMALY_REPORT_QUERY = gql`\n query GetHealthyBowlWeatherAnomalyReport($context: ContextInput!) {\n getHealthyBowlWeatherAnomalyReport(context: $context) {\n baselineYears\n startYear\n endYear\n currentMonth\n currentMonthName\n rainfallThisMonthMm\n rainfallBaselineMm\n rainfallDeviationPct\n avgTempDeltaC\n frostDaysThisSeason\n frostDaysBaseline\n frostDaysDelta\n firstFrostDate\n baselineFirstFrostDate\n firstFrostDeltaDays\n monthlyRainfall {\n month\n monthName\n currentValue\n baselineAvg\n baselineMin\n baselineMax\n }\n monthlyTemperature {\n month\n monthName\n currentValue\n baselineAvg\n baselineMin\n baselineMax\n }\n callouts {\n id\n title\n severity\n date\n metric\n }\n generatedAt\n source\n synced\n }\n }\n`;\n\nconst FROST_RISK_CALENDAR_QUERY = gql`\n query GetHealthyBowlFrostRiskCalendar($context: ContextInput!, $year: Int, $month: Int) {\n getHealthyBowlFrostRiskCalendar(context: $context, year: $year, month: $month) {\n year\n month\n monthName\n frostRiskDayCount\n historicalFirstFrost\n days {\n date\n day\n risk\n label\n detail\n tempMin\n tempMax\n source\n }\n }\n }\n`;\n\nconst WEATHER_ALERT_EVENTS_QUERY = gql`\n query GetHealthyBowlWeatherAlertEvents($context: ContextInput!, $alertType: String, $status: String) {\n getHealthyBowlWeatherAlertEvents(context: $context, alertType: $alertType, status: $status) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst WEATHER_ALERT_SETTINGS_QUERY = gql`\n query GetHealthyBowlWeatherAlertSettings($context: ContextInput!) {\n getHealthyBowlWeatherAlertSettings(context: $context) {\n ${WEATHER_ALERT_SETTINGS_FIELDS}\n }\n }\n`;\n\nconst SYNC_WEATHER_HISTORY = gql`\n mutation SyncHealthyBowlWeatherHistory($context: ContextInput!) {\n syncHealthyBowlWeatherHistory(context: $context) {\n ${WEATHER_HISTORY_SERIES_FIELDS}\n }\n }\n`;\n\nconst MARK_WEATHER_ALERT_HANDLED = gql`\n mutation MarkHealthyBowlWeatherAlertHandled($id: ID!, $context: ContextInput!) {\n markHealthyBowlWeatherAlertHandled(id: $id, context: $context) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst SNOOZE_WEATHER_ALERT = gql`\n mutation SnoozeHealthyBowlWeatherAlert($id: ID!, $until: String!, $context: ContextInput!) {\n snoozeHealthyBowlWeatherAlert(id: $id, until: $until, context: $context) {\n ${WEATHER_ALERT_EVENT_FIELDS}\n }\n }\n`;\n\nconst UPSERT_WEATHER_ALERT_SETTINGS = gql`\n mutation UpsertHealthyBowlWeatherAlertSettings($input: UpsertHealthyBowlWeatherAlertSettingsInput!) {\n upsertHealthyBowlWeatherAlertSettings(input: $input) {\n ${WEATHER_ALERT_SETTINGS_FIELDS}\n }\n }\n`;\n\n// ── Query result shapes ──────────────────────────────────────────────────────\n\ninterface WeatherHistorySeriesQueryData {\n getHealthyBowlWeatherHistorySeries: WeatherHistorySeries;\n}\ninterface WeatherAnomalyReportQueryData {\n getHealthyBowlWeatherAnomalyReport: WeatherAnomalyReport;\n}\ninterface FrostRiskCalendarQueryData {\n getHealthyBowlFrostRiskCalendar: FrostRiskCalendar;\n}\ninterface WeatherAlertEventsQueryData {\n getHealthyBowlWeatherAlertEvents: WeatherAlertEvent[];\n}\ninterface WeatherAlertSettingsQueryData {\n getHealthyBowlWeatherAlertSettings: WeatherAlertSettings;\n}\ninterface SyncWeatherHistoryMutationData {\n syncHealthyBowlWeatherHistory: WeatherHistorySeries;\n}\ninterface MarkHandledMutationData {\n markHealthyBowlWeatherAlertHandled: WeatherAlertEvent;\n}\ninterface SnoozeMutationData {\n snoozeHealthyBowlWeatherAlert: WeatherAlertEvent;\n}\ninterface UpsertSettingsMutationData {\n upsertHealthyBowlWeatherAlertSettings: WeatherAlertSettings;\n}\n\n/**\n * Loads weather-intelligence data for the active workspace: historical series +\n * baseline, the current-season anomaly report, the frost-risk calendar (current\n * month eager, other months via `loadCalendar`), fired alert events (eager list\n * + filtered `loadEvents`), and alert settings — plus the mutations to re-sync\n * history, handle/snooze alerts and save settings. Mutations refetch the\n * relevant query so the caller's view stays in sync.\n */\nexport function useWeatherIntelligence(options: UseWeatherIntelligenceOptions = {}) {\n const { workspaceId } = useHealthyBowl();\n const context = { workspaceId };\n const { years } = options;\n\n // ── History series ──────────────────────────────────────────────────────\n const {\n data: seriesData,\n loading: loadingSeries,\n error: errorSeries,\n refetch: refetchSeries,\n } = useQuery<WeatherHistorySeriesQueryData>(WEATHER_HISTORY_SERIES_QUERY, {\n variables: { context, years },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Anomaly report ──────────────────────────────────────────────────────\n const {\n data: anomalyData,\n loading: loadingAnomaly,\n error: errorAnomaly,\n refetch: refetchAnomaly,\n } = useQuery<WeatherAnomalyReportQueryData>(WEATHER_ANOMALY_REPORT_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Frost-risk calendar — eager current month + lazy month paging ─────────\n const {\n data: calendarData,\n loading: loadingCalendar,\n error: errorCalendar,\n refetch: refetchCalendar,\n } = useQuery<FrostRiskCalendarQueryData>(FROST_RISK_CALENDAR_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n const [runLoadCalendar] = useLazyQuery<FrostRiskCalendarQueryData>(FROST_RISK_CALENDAR_QUERY, {\n fetchPolicy: 'cache-and-network',\n });\n\n // ── Alert events — eager list + lazy filtered loader ──────────────────────\n const {\n data: eventsData,\n loading: loadingEvents,\n error: errorEvents,\n refetch: refetchEvents,\n } = useQuery<WeatherAlertEventsQueryData>(WEATHER_ALERT_EVENTS_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n const [runLoadEvents] = useLazyQuery<WeatherAlertEventsQueryData>(WEATHER_ALERT_EVENTS_QUERY, {\n fetchPolicy: 'cache-and-network',\n });\n\n // ── Settings ────────────────────────────────────────────────────────────\n const {\n data: settingsData,\n loading: loadingSettings,\n error: errorSettings,\n refetch: refetchSettings,\n } = useQuery<WeatherAlertSettingsQueryData>(WEATHER_ALERT_SETTINGS_QUERY, {\n variables: { context },\n skip: !workspaceId,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n });\n\n // ── Mutations ───────────────────────────────────────────────────────────\n const [syncHistoryMutation] = useMutation<SyncWeatherHistoryMutationData>(SYNC_WEATHER_HISTORY);\n const [markHandledMutation] = useMutation<MarkHandledMutationData>(MARK_WEATHER_ALERT_HANDLED);\n const [snoozeMutation] = useMutation<SnoozeMutationData>(SNOOZE_WEATHER_ALERT);\n const [saveSettingsMutation] = useMutation<UpsertSettingsMutationData>(UPSERT_WEATHER_ALERT_SETTINGS);\n\n const loadCalendar = useCallback(\n async (year: number, month: number): Promise<FrostRiskCalendar | null> => {\n const result = await runLoadCalendar({ variables: { context, year, month } });\n return result.data?.getHealthyBowlFrostRiskCalendar ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [runLoadCalendar, workspaceId]\n );\n\n const loadEvents = useCallback(\n async (filter: WeatherAlertEventsFilter = {}): Promise<WeatherAlertEvent[]> => {\n const result = await runLoadEvents({\n variables: { context, alertType: filter.alertType ?? null, status: filter.status ?? null },\n });\n return result.data?.getHealthyBowlWeatherAlertEvents ?? [];\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [runLoadEvents, workspaceId]\n );\n\n const syncHistory = useCallback(\n async (): Promise<WeatherHistorySeries | null> => {\n const result = await syncHistoryMutation({ variables: { context } });\n await refetchSeries();\n await refetchAnomaly();\n return result.data?.syncHealthyBowlWeatherHistory ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [syncHistoryMutation, refetchSeries, refetchAnomaly, workspaceId]\n );\n\n const markHandled = useCallback(\n async (id: string): Promise<WeatherAlertEvent | null> => {\n const result = await markHandledMutation({ variables: { id, context } });\n await refetchEvents();\n return result.data?.markHealthyBowlWeatherAlertHandled ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [markHandledMutation, refetchEvents, workspaceId]\n );\n\n const snooze = useCallback(\n async (id: string, until: string): Promise<WeatherAlertEvent | null> => {\n const result = await snoozeMutation({ variables: { id, until, context } });\n await refetchEvents();\n return result.data?.snoozeHealthyBowlWeatherAlert ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [snoozeMutation, refetchEvents, workspaceId]\n );\n\n const saveSettings = useCallback(\n async (input: UpsertWeatherAlertSettingsInput): Promise<WeatherAlertSettings | null> => {\n const result = await saveSettingsMutation({ variables: { input: { ...input, context } } });\n await refetchSettings();\n return result.data?.upsertHealthyBowlWeatherAlertSettings ?? null;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [saveSettingsMutation, refetchSettings, workspaceId]\n );\n\n return {\n // History series\n series: seriesData?.getHealthyBowlWeatherHistorySeries ?? null,\n loadingSeries,\n errorSeries: errorSeries ?? null,\n refetchSeries,\n // Anomaly report\n anomaly: anomalyData?.getHealthyBowlWeatherAnomalyReport ?? null,\n loadingAnomaly,\n errorAnomaly: errorAnomaly ?? null,\n refetchAnomaly,\n // Frost-risk calendar\n frostCalendar: calendarData?.getHealthyBowlFrostRiskCalendar ?? null,\n loadingCalendar,\n errorCalendar: errorCalendar ?? null,\n refetchCalendar,\n loadCalendar,\n // Alert events\n alertEvents: eventsData?.getHealthyBowlWeatherAlertEvents ?? [],\n loadingEvents,\n errorEvents: errorEvents ?? null,\n refetchEvents,\n loadEvents,\n // Settings\n settings: settingsData?.getHealthyBowlWeatherAlertSettings ?? null,\n loadingSettings,\n errorSettings: errorSettings ?? null,\n refetchSettings,\n // Mutations\n syncHistory,\n markHandled,\n snooze,\n saveSettings,\n };\n}\n"],"mappings":";;;;;AA6SA,IAAM,IAAgC,gUA2BhC,IAA6B,kMAmB7B,IAAgC,uXAuBhC,IAA+B,CAAG;;;QAGhC,EAA8B;;;GAKhC,IAA+B,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDlC,IAA4B,CAAG;;;;;;;;;;;;;;;;;;;;GAsB/B,IAA6B,CAAG;;;QAG9B,EAA2B;;;GAK7B,IAA+B,CAAG;;;QAGhC,EAA8B;;;GAKhC,IAAuB,CAAG;;;QAGxB,EAA8B;;;GAKhC,IAA6B,CAAG;;;QAG9B,EAA2B;;;GAK7B,IAAuB,CAAG;;;QAGxB,EAA2B;;;GAK7B,IAAgC,CAAG;;;QAGjC,EAA8B;;;;AA2CtC,SAAgB,EAAuB,IAAyC,EAAE,EAAE;CAClF,IAAM,EAAE,mBAAgB,GAAgB,EAClC,IAAU,EAAE,gBAAa,EACzB,EAAE,aAAU,GAGZ,EACJ,MAAM,GACN,SAAS,GACT,OAAO,GACP,SAAS,MACP,EAAwC,GAA8B;EACxE,WAAW;GAAE;GAAS;GAAO;EAC7B,MAAM,CAAC;EACP,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAGI,EACJ,MAAM,GACN,SAAS,GACT,OAAO,GACP,SAAS,MACP,EAAwC,GAA8B;EACxE,WAAW,EAAE,YAAS;EACtB,MAAM,CAAC;EACP,aAAa;EACb,6BAA6B;EAC9B,CAAC,EAGI,EACJ,MAAM,GACN,SAAS,GACT,OAAO,GACP,SAAS,MACP,EAAqC,GAA2B;EAClE,WAAW,EAAE,YAAS;EACtB,MAAM,CAAC;EACP,aAAa;EACb,6BAA6B;EAC9B,CAAC,EACI,CAAC,KAAmB,EAAyC,GAA2B,EAC5F,a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AAC;EAAqB;EAAe;EAAY,CAClD,EAEK,IAAS,EACb,OAAO,GAAY,MAAqD;EACtE,IAAM,IAAS,MAAM,EAAe,EAAE,WAAW;GAAE;GAAI;GAAO;GAAS,EAAE,CAAC;AAE1E,SADA,MAAM,GAAe,EACd,EAAO,MAAM,iCAAiC;IAGvD;EAAC;EAAgB;EAAe;EAAY,CAC7C,EAEK,IAAe,EACnB,OAAO,MAAiF;EACtF,IAAM,IAAS,MAAM,EAAqB,EAAE,WAAW,EAAE,OAAO;GAAE,GAAG;GAAO;GAAS,EAAE,EAAE,CAAC;AAE1F,SADA,MAAM,GAAiB,EAChB,EAAO,MAAM,yCAAyC;IAG/D;EAAC;EAAsB;EAAiB;EAAY,CACrD;AAED,QAAO;EAEL,QAAQ,GAAY,sCAAsC;EAC1D;EACA,aAAa,KAAe;EAC5B;EAEA,SAAS,GAAa,sCAAsC;EAC5D;EACA,cAAc,KAAgB;EAC9B;EAEA,eAAe,GAAc,mCAAmC;EAChE;EACA,eAAe,KAAiB;EAChC;EACA;EAEA,aAAa,GAAY,oCAAoC,EAAE;EAC/D;EACA,aAAa,KAAe;EAC5B;EACA;EAEA,UAAU,GAAc,sCAAsC;EAC9D;EACA,eAAe,KAAiB;EAChC;EAEA;EACA;EACA;EACA;EACD"}
@@ -0,0 +1,258 @@
1
+ import { PageLayout as e } from "../../components/PageLayout.js";
2
+ import { EmptyState as t } from "../../components/EmptyState.js";
3
+ import { ErrorState as n } from "../../components/ErrorState.js";
4
+ import { PageLoader as r } from "../../components/PageLoader.js";
5
+ import { useToast as i } from "../../hooks/useToast.js";
6
+ import "../../components/index.js";
7
+ import { useWeatherIntelligence as a } from "../../hooks/useWeatherIntelligence.js";
8
+ import { useEffect as o, useMemo as s, useState as c } from "react";
9
+ import { useI18n as l } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
10
+ import { CalendarDays as u, ChevronLeft as d, ChevronRight as f, Snowflake as p } from "lucide-react";
11
+ import { useNavigate as m } from "react-router-dom";
12
+ import { Fragment as h, jsx as g, jsxs as _ } from "react/jsx-runtime";
13
+ import { Button as v } from "@burdenoff/fe-libs/ui";
14
+ //#region src/healthybowl/pages/weather/FrostRiskCalendarPage.tsx
15
+ var y = [
16
+ "Sun",
17
+ "Mon",
18
+ "Tue",
19
+ "Wed",
20
+ "Thu",
21
+ "Fri",
22
+ "Sat"
23
+ ], b = {
24
+ FROST_HIGH: {
25
+ key: "frostHigh",
26
+ label: "Frost - High risk",
27
+ swatch: "bg-red-600",
28
+ block: "bg-red-600 text-white",
29
+ tint: "bg-red-500/10"
30
+ },
31
+ FROST_WATCH: {
32
+ key: "frostWatch",
33
+ label: "Frost - Watch",
34
+ swatch: "bg-amber-500",
35
+ block: "bg-amber-500 text-white",
36
+ tint: "bg-amber-500/10"
37
+ },
38
+ HEAT: {
39
+ key: "heat",
40
+ label: "Heat",
41
+ swatch: "bg-orange-500",
42
+ block: "bg-orange-500 text-white",
43
+ tint: "bg-orange-500/10"
44
+ },
45
+ STORM: {
46
+ key: "storm",
47
+ label: "Storm",
48
+ swatch: "bg-slate-500",
49
+ block: "bg-slate-500 text-white",
50
+ tint: "bg-slate-500/10"
51
+ },
52
+ DISEASE_WINDOW: {
53
+ key: "diseaseWindow",
54
+ label: "Disease-favourable window (DEWS)",
55
+ swatch: "bg-violet-600",
56
+ block: "bg-violet-600 text-white",
57
+ tint: "bg-violet-500/10"
58
+ },
59
+ CLEAR: {
60
+ key: "clear",
61
+ label: "Clear",
62
+ swatch: "bg-emerald-500",
63
+ block: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
64
+ tint: "",
65
+ soft: !0
66
+ },
67
+ UNKNOWN: {
68
+ key: "unknown",
69
+ label: "Unknown",
70
+ swatch: "bg-bg-sunken",
71
+ block: "bg-bg-sunken text-text-secondary",
72
+ tint: "",
73
+ soft: !0
74
+ }
75
+ }, x = [
76
+ "FROST_HIGH",
77
+ "FROST_WATCH",
78
+ "HEAT",
79
+ "DISEASE_WINDOW",
80
+ "STORM",
81
+ "CLEAR",
82
+ "UNKNOWN"
83
+ ], S = (e) => b[e] ?? b.UNKNOWN, C = (e, t, n) => {
84
+ let r = t - 1 + n;
85
+ return {
86
+ year: e + Math.floor(r / 12),
87
+ month: (r % 12 + 12) % 12 + 1
88
+ };
89
+ }, w = (e) => {
90
+ let t = new Date(e);
91
+ return Number.isNaN(t.getTime()) ? e : t.toLocaleDateString("en-US", {
92
+ day: "numeric",
93
+ month: "short"
94
+ });
95
+ }, T = () => {
96
+ let { t: T } = l(), E = m(), { toast: D } = i(), { frostCalendar: O, loadingCalendar: k, errorCalendar: A, refetchCalendar: j, loadCalendar: M } = a(), [N, P] = c(null), [F, I] = c(!1);
97
+ o(() => {
98
+ O && P(O);
99
+ }, [O]);
100
+ let L = N ?? O, R = async (e, t) => {
101
+ I(!0);
102
+ try {
103
+ let n = await M(e, t);
104
+ n ? P(n) : D({
105
+ title: T("healthybowl.weather.calendar.toast.noData.title", "No calendar data"),
106
+ description: T("healthybowl.weather.calendar.toast.noData.description", "No frost-risk data is available for that month yet."),
107
+ variant: "info"
108
+ });
109
+ } catch {
110
+ D({
111
+ title: T("healthybowl.weather.calendar.toast.error.title", "Could not load month"),
112
+ description: T("healthybowl.weather.calendar.toast.error.description", "Something went wrong loading that month. Please try again."),
113
+ variant: "error"
114
+ });
115
+ } finally {
116
+ I(!1);
117
+ }
118
+ }, { weeks: z } = s(() => {
119
+ if (!L) return { weeks: [] };
120
+ let e = /* @__PURE__ */ new Map();
121
+ for (let t of L.days) e.set(t.day, t);
122
+ let t = new Date(L.year, L.month, 0).getDate(), n = new Date(L.year, L.month - 1, 1).getDay(), r = [];
123
+ for (let e = 0; e < n; e += 1) r.push(null);
124
+ for (let n = 1; n <= t; n += 1) r.push(e.get(n) ?? null);
125
+ for (; r.length % 7 != 0;) r.push(null);
126
+ let i = [];
127
+ for (let e = 0; e < r.length; e += 7) i.push(r.slice(e, e + 7));
128
+ return { weeks: i };
129
+ }, [L]), B = L ? C(L.year, L.month, -1) : null, V = L ? C(L.year, L.month, 1) : null, H = /* @__PURE__ */ _("div", {
130
+ className: "flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-surface p-1",
131
+ children: [
132
+ /* @__PURE__ */ g(v, {
133
+ variant: "ghost",
134
+ size: "sm",
135
+ disabled: !B || F,
136
+ onClick: () => B && R(B.year, B.month),
137
+ "aria-label": T("healthybowl.weather.calendar.nav.prev", "Previous month"),
138
+ children: /* @__PURE__ */ g(d, { className: "h-4 w-4" })
139
+ }),
140
+ /* @__PURE__ */ g("span", {
141
+ className: "min-w-[9rem] text-center text-sm font-medium text-text-primary",
142
+ children: L ? `${L.monthName} ${L.year}` : "—"
143
+ }),
144
+ /* @__PURE__ */ g(v, {
145
+ variant: "ghost",
146
+ size: "sm",
147
+ disabled: !V || F,
148
+ onClick: () => V && R(V.year, V.month),
149
+ "aria-label": T("healthybowl.weather.calendar.nav.next", "Next month"),
150
+ children: /* @__PURE__ */ g(f, { className: "h-4 w-4" })
151
+ })
152
+ ]
153
+ });
154
+ return /* @__PURE__ */ _(e, {
155
+ title: T("healthybowl.weather.calendar.title", "Frost-Risk Calendar"),
156
+ description: T("healthybowl.weather.calendar.description", "A month-by-month view of frost, heat, storm and disease-risk days for your farm site."),
157
+ purpose: "A daily risk calendar for your farm site so you can see, at a glance, which nights carry frost danger, which days bring heat or storm stress, and when conditions favour disease — and plan protective action (covers, irrigation, spraying) before the risk arrives.",
158
+ actions: H,
159
+ children: [k && !L ? /* @__PURE__ */ g(r, {}) : A && !L ? /* @__PURE__ */ g(n, { onRetry: j }) : L ? /* @__PURE__ */ _("div", {
160
+ className: "grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_18rem]",
161
+ children: [/* @__PURE__ */ _("div", {
162
+ className: "relative rounded-lg border border-border-subtle bg-bg-surface p-3 sm:p-4",
163
+ children: [
164
+ F && /* @__PURE__ */ g("div", {
165
+ className: "absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-bg-surface/60",
166
+ children: /* @__PURE__ */ g(r, {})
167
+ }),
168
+ /* @__PURE__ */ g("div", {
169
+ className: "grid grid-cols-7 border-b border-border-subtle pb-2",
170
+ children: y.map((e) => /* @__PURE__ */ g("div", {
171
+ className: "px-1 text-center text-xs font-semibold text-text-secondary",
172
+ children: T(`healthybowl.weather.calendar.weekday.${e.toLowerCase()}`, e)
173
+ }, e))
174
+ }),
175
+ /* @__PURE__ */ g("div", {
176
+ className: "grid grid-cols-7",
177
+ children: z.map((e, t) => e.map((e, n) => {
178
+ let r = e ? S(e.risk) : null;
179
+ return /* @__PURE__ */ g("div", {
180
+ className: `min-h-[6.5rem] border-b border-r border-border-subtle p-1.5 last:border-r-0 ${r ? r.tint : ""} ${e ? "" : "bg-bg-sunken/30"}`,
181
+ title: e?.detail ?? void 0,
182
+ children: e && /* @__PURE__ */ _(h, { children: [/* @__PURE__ */ g("div", {
183
+ className: "mb-1 text-xs font-semibold text-text-primary",
184
+ children: e.day
185
+ }), r?.soft ? /* @__PURE__ */ _("span", {
186
+ className: `inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${r.block}`,
187
+ children: [/* @__PURE__ */ g("span", { className: `h-1.5 w-1.5 rounded-full ${r.swatch}` }), e.label]
188
+ }) : r && /* @__PURE__ */ _("div", {
189
+ className: `rounded-md px-1.5 py-1 text-center leading-tight ${r.block}`,
190
+ children: [/* @__PURE__ */ g("div", {
191
+ className: "text-[10px] font-semibold uppercase tracking-wide",
192
+ children: e.label
193
+ }), e.tempMin != null && /* @__PURE__ */ _("div", {
194
+ className: "text-[11px] font-bold",
195
+ children: [e.tempMin, "°C"]
196
+ })]
197
+ })] })
198
+ }, `${t}-${n}`);
199
+ }))
200
+ })
201
+ ]
202
+ }), /* @__PURE__ */ _("div", {
203
+ className: "space-y-4",
204
+ children: [/* @__PURE__ */ _("div", {
205
+ className: "rounded-lg border border-border-subtle bg-bg-surface p-4",
206
+ children: [/* @__PURE__ */ g("h3", {
207
+ className: "mb-3 text-sm font-semibold text-text-primary",
208
+ children: T("healthybowl.weather.calendar.legend.title", "Legend")
209
+ }), /* @__PURE__ */ g("ul", {
210
+ className: "space-y-2.5",
211
+ children: x.map((e) => {
212
+ let t = b[e];
213
+ return /* @__PURE__ */ _("li", {
214
+ className: "flex items-center gap-2.5",
215
+ children: [/* @__PURE__ */ g("span", { className: `h-3 w-3 shrink-0 rounded-full ${t.swatch}` }), /* @__PURE__ */ g("span", {
216
+ className: "text-sm text-text-secondary",
217
+ children: T(`healthybowl.weather.calendar.legend.${t.key}`, t.label)
218
+ })]
219
+ }, e);
220
+ })
221
+ })]
222
+ }), /* @__PURE__ */ _("div", {
223
+ className: "rounded-lg border border-border-subtle bg-bg-surface p-4",
224
+ children: [/* @__PURE__ */ _("div", {
225
+ className: "flex items-start gap-3",
226
+ children: [/* @__PURE__ */ g("div", {
227
+ className: "rounded-md bg-bg-sunken p-2",
228
+ children: /* @__PURE__ */ g(p, { className: "h-5 w-5 text-info" })
229
+ }), /* @__PURE__ */ _("div", { children: [/* @__PURE__ */ g("p", {
230
+ className: "text-2xl font-bold text-text-primary",
231
+ children: L.frostRiskDayCount
232
+ }), /* @__PURE__ */ g("p", {
233
+ className: "text-sm text-text-secondary",
234
+ children: L.frostRiskDayCount === 1 ? T("healthybowl.weather.calendar.summary.frostDaysSingular", "frost-risk day this month") : T("healthybowl.weather.calendar.summary.frostDaysPlural", "frost-risk days this month")
235
+ })] })]
236
+ }), /* @__PURE__ */ g("p", {
237
+ className: "mt-3 border-t border-border-subtle pt-3 text-xs text-text-secondary",
238
+ children: L.historicalFirstFrost ? T("healthybowl.weather.calendar.summary.historicalFirstFrost", "Historical avg first-frost: {{date}}", { date: w(L.historicalFirstFrost) }) : T("healthybowl.weather.calendar.summary.noHistoricalFrost", "No historical first-frost on record for this site.")
239
+ })]
240
+ })]
241
+ })]
242
+ }) : /* @__PURE__ */ g(t, {
243
+ icon: /* @__PURE__ */ g(u, { className: "h-8 w-8" }),
244
+ title: T("healthybowl.weather.calendar.empty.title", "No calendar data"),
245
+ description: T("healthybowl.weather.calendar.empty.description", "Frost-risk data will appear here once your weather history has been synced.")
246
+ }), /* @__PURE__ */ g("div", { children: /* @__PURE__ */ _(v, {
247
+ variant: "ghost",
248
+ size: "sm",
249
+ onClick: () => E(".."),
250
+ className: "gap-1 text-text-secondary hover:text-text-primary",
251
+ children: ["← ", T("healthybowl.weather.calendar.backToDashboard", "Back to Weather Dashboard")]
252
+ }) })]
253
+ });
254
+ };
255
+ //#endregion
256
+ export { T as FrostRiskCalendarPage };
257
+
258
+ //# sourceMappingURL=FrostRiskCalendarPage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FrostRiskCalendarPage.js","names":[],"sources":["../../../../src/healthybowl/pages/weather/FrostRiskCalendarPage.tsx"],"sourcesContent":["/**\n * Frost-Risk Calendar — month-view grid of daily weather-risk bands (frost,\n * heat, storm, disease-favourable window) for the active farm site, driven by\n * `useWeatherIntelligence().loadCalendar(year, month)` (roadmap #20 / BOFF-2892).\n *\n * The current month loads eagerly (`frostCalendar`); prev/next navigation pages\n * other months through the lazy `loadCalendar`. Every value — the risk band per\n * day, the frost-risk day count and the historical first-frost date — comes from\n * the GraphQL hook; there are no mocked cells.\n * @module healthybowl\n */\nimport { useEffect, useMemo, useState, type FC } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport { CalendarDays, ChevronLeft, ChevronRight, Snowflake } from 'lucide-react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { Button } from '@burdenoff/fe-libs/ui';\nimport { PageLayout, ErrorState, PageLoader, EmptyState } from '../../components';\nimport { useToast } from '../../hooks/useToast';\nimport { useWeatherIntelligence, type FrostRiskCalendar, type FrostRiskDay } from '../../hooks/useWeatherIntelligence';\n\n/** Weekday column headers (Sun-first, matching the grid layout). */\nconst WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;\n\n/** Presentation metadata for each risk band (data-viz palette is the accepted exception). */\ninterface RiskMeta {\n /** i18n key suffix for the human label. */\n key: string;\n /** English fallback label. */\n label: string;\n /** Legend swatch colour. */\n swatch: string;\n /** Solid pill/block colour for flagged days. */\n block: string;\n /** Subtle cell background tint. */\n tint: string;\n /** True when the band renders as a soft \"all clear\" pill rather than a solid block. */\n soft?: boolean;\n}\n\nconst RISK_META: Record<string, RiskMeta> = {\n FROST_HIGH: {\n key: 'frostHigh',\n label: 'Frost - High risk',\n swatch: 'bg-red-600',\n block: 'bg-red-600 text-white',\n tint: 'bg-red-500/10',\n },\n FROST_WATCH: {\n key: 'frostWatch',\n label: 'Frost - Watch',\n swatch: 'bg-amber-500',\n block: 'bg-amber-500 text-white',\n tint: 'bg-amber-500/10',\n },\n HEAT: {\n key: 'heat',\n label: 'Heat',\n swatch: 'bg-orange-500',\n block: 'bg-orange-500 text-white',\n tint: 'bg-orange-500/10',\n },\n STORM: {\n key: 'storm',\n label: 'Storm',\n swatch: 'bg-slate-500',\n block: 'bg-slate-500 text-white',\n tint: 'bg-slate-500/10',\n },\n DISEASE_WINDOW: {\n key: 'diseaseWindow',\n label: 'Disease-favourable window (DEWS)',\n swatch: 'bg-violet-600',\n block: 'bg-violet-600 text-white',\n tint: 'bg-violet-500/10',\n },\n CLEAR: {\n key: 'clear',\n label: 'Clear',\n swatch: 'bg-emerald-500',\n block: 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300',\n tint: '',\n soft: true,\n },\n UNKNOWN: {\n key: 'unknown',\n label: 'Unknown',\n swatch: 'bg-bg-sunken',\n block: 'bg-bg-sunken text-text-secondary',\n tint: '',\n soft: true,\n },\n};\n\n/** Legend order (all bands, matching the mock). */\nconst LEGEND_ORDER = ['FROST_HIGH', 'FROST_WATCH', 'HEAT', 'DISEASE_WINDOW', 'STORM', 'CLEAR', 'UNKNOWN'] as const;\n\nconst metaFor = (risk: string): RiskMeta => RISK_META[risk] ?? RISK_META.UNKNOWN;\n\n/** Compute the {year, month} one step before/after the given month (1-indexed). */\nconst stepMonth = (year: number, month: number, delta: number): { year: number; month: number } => {\n const zero = month - 1 + delta;\n const y = year + Math.floor(zero / 12);\n const m = ((zero % 12) + 12) % 12;\n return { year: y, month: m + 1 };\n};\n\nconst formatFirstFrost = (iso: string): string => {\n const d = new Date(iso);\n return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });\n};\n\nexport const FrostRiskCalendarPage: FC = () => {\n const { t } = useI18n();\n const navigate = useNavigate();\n const { toast } = useToast();\n const { frostCalendar, loadingCalendar, errorCalendar, refetchCalendar, loadCalendar } = useWeatherIntelligence();\n\n // Locally-tracked displayed month: seeded by the eager current-month query,\n // then advanced through the lazy loader on prev/next navigation.\n const [calendar, setCalendar] = useState<FrostRiskCalendar | null>(null);\n const [navLoading, setNavLoading] = useState(false);\n\n useEffect(() => {\n if (frostCalendar) setCalendar(frostCalendar);\n }, [frostCalendar]);\n\n const active = calendar ?? frostCalendar;\n\n const goToMonth = async (year: number, month: number) => {\n setNavLoading(true);\n try {\n const next = await loadCalendar(year, month);\n if (next) setCalendar(next);\n else\n toast({\n title: t('healthybowl.weather.calendar.toast.noData.title', 'No calendar data'),\n description: t(\n 'healthybowl.weather.calendar.toast.noData.description',\n 'No frost-risk data is available for that month yet.'\n ),\n variant: 'info',\n });\n } catch {\n toast({\n title: t('healthybowl.weather.calendar.toast.error.title', 'Could not load month'),\n description: t(\n 'healthybowl.weather.calendar.toast.error.description',\n 'Something went wrong loading that month. Please try again.'\n ),\n variant: 'error',\n });\n } finally {\n setNavLoading(false);\n }\n };\n\n // Map day-of-month → cell, and lay out the month into weeks (leading blanks\n // for the first weekday). Derived purely from the loaded calendar.\n const { weeks } = useMemo(() => {\n if (!active) return { weeks: [] as (FrostRiskDay | null)[][] };\n const byDay = new Map<number, FrostRiskDay>();\n for (const d of active.days) byDay.set(d.day, d);\n const daysInMonth = new Date(active.year, active.month, 0).getDate();\n const firstWeekday = new Date(active.year, active.month - 1, 1).getDay(); // 0=Sun\n const cells: (FrostRiskDay | null)[] = [];\n for (let i = 0; i < firstWeekday; i += 1) cells.push(null);\n for (let day = 1; day <= daysInMonth; day += 1) cells.push(byDay.get(day) ?? null);\n while (cells.length % 7 !== 0) cells.push(null);\n const rows: (FrostRiskDay | null)[][] = [];\n for (let i = 0; i < cells.length; i += 7) rows.push(cells.slice(i, i + 7));\n return { weeks: rows };\n }, [active]);\n\n const prev = active ? stepMonth(active.year, active.month, -1) : null;\n const next = active ? stepMonth(active.year, active.month, 1) : null;\n\n const monthNav = (\n <div className=\"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-surface p-1\">\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!prev || navLoading}\n onClick={() => prev && goToMonth(prev.year, prev.month)}\n aria-label={t('healthybowl.weather.calendar.nav.prev', 'Previous month')}\n >\n <ChevronLeft className=\"h-4 w-4\" />\n </Button>\n <span className=\"min-w-[9rem] text-center text-sm font-medium text-text-primary\">\n {active ? `${active.monthName} ${active.year}` : '—'}\n </span>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={!next || navLoading}\n onClick={() => next && goToMonth(next.year, next.month)}\n aria-label={t('healthybowl.weather.calendar.nav.next', 'Next month')}\n >\n <ChevronRight className=\"h-4 w-4\" />\n </Button>\n </div>\n );\n\n return (\n <PageLayout\n title={t('healthybowl.weather.calendar.title', 'Frost-Risk Calendar')}\n description={t(\n 'healthybowl.weather.calendar.description',\n 'A month-by-month view of frost, heat, storm and disease-risk days for your farm site.'\n )}\n purpose=\"A daily risk calendar for your farm site so you can see, at a glance, which nights carry frost danger, which days bring heat or storm stress, and when conditions favour disease — and plan protective action (covers, irrigation, spraying) before the risk arrives.\"\n actions={monthNav}\n >\n {loadingCalendar && !active ? (\n <PageLoader />\n ) : errorCalendar && !active ? (\n <ErrorState onRetry={refetchCalendar} />\n ) : !active ? (\n <EmptyState\n icon={<CalendarDays className=\"h-8 w-8\" />}\n title={t('healthybowl.weather.calendar.empty.title', 'No calendar data')}\n description={t(\n 'healthybowl.weather.calendar.empty.description',\n 'Frost-risk data will appear here once your weather history has been synced.'\n )}\n />\n ) : (\n <div className=\"grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_18rem]\">\n {/* Calendar grid */}\n <div className=\"relative rounded-lg border border-border-subtle bg-bg-surface p-3 sm:p-4\">\n {navLoading && (\n <div className=\"absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-bg-surface/60\">\n <PageLoader />\n </div>\n )}\n {/* Weekday header */}\n <div className=\"grid grid-cols-7 border-b border-border-subtle pb-2\">\n {WEEKDAYS.map((wd) => (\n <div key={wd} className=\"px-1 text-center text-xs font-semibold text-text-secondary\">\n {t(`healthybowl.weather.calendar.weekday.${wd.toLowerCase()}`, wd)}\n </div>\n ))}\n </div>\n {/* Weeks */}\n <div className=\"grid grid-cols-7\">\n {weeks.map((week, wi) =>\n week.map((cell, ci) => {\n const meta = cell ? metaFor(cell.risk) : null;\n return (\n <div\n key={`${wi}-${ci}`}\n className={`min-h-[6.5rem] border-b border-r border-border-subtle p-1.5 last:border-r-0 ${\n meta ? meta.tint : ''\n } ${!cell ? 'bg-bg-sunken/30' : ''}`}\n title={cell?.detail ?? undefined}\n >\n {cell && (\n <>\n <div className=\"mb-1 text-xs font-semibold text-text-primary\">{cell.day}</div>\n {meta?.soft ? (\n <span\n className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${meta.block}`}\n >\n <span className={`h-1.5 w-1.5 rounded-full ${meta.swatch}`} />\n {cell.label}\n </span>\n ) : (\n meta && (\n <div className={`rounded-md px-1.5 py-1 text-center leading-tight ${meta.block}`}>\n <div className=\"text-[10px] font-semibold uppercase tracking-wide\">{cell.label}</div>\n {cell.tempMin != null && <div className=\"text-[11px] font-bold\">{cell.tempMin}°C</div>}\n </div>\n )\n )}\n </>\n )}\n </div>\n );\n })\n )}\n </div>\n </div>\n\n {/* Legend + summary rail */}\n <div className=\"space-y-4\">\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-4\">\n <h3 className=\"mb-3 text-sm font-semibold text-text-primary\">\n {t('healthybowl.weather.calendar.legend.title', 'Legend')}\n </h3>\n <ul className=\"space-y-2.5\">\n {LEGEND_ORDER.map((risk) => {\n const meta = RISK_META[risk];\n return (\n <li key={risk} className=\"flex items-center gap-2.5\">\n <span className={`h-3 w-3 shrink-0 rounded-full ${meta.swatch}`} />\n <span className=\"text-sm text-text-secondary\">\n {t(`healthybowl.weather.calendar.legend.${meta.key}`, meta.label)}\n </span>\n </li>\n );\n })}\n </ul>\n </div>\n\n <div className=\"rounded-lg border border-border-subtle bg-bg-surface p-4\">\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-md bg-bg-sunken p-2\">\n <Snowflake className=\"h-5 w-5 text-info\" />\n </div>\n <div>\n <p className=\"text-2xl font-bold text-text-primary\">{active.frostRiskDayCount}</p>\n <p className=\"text-sm text-text-secondary\">\n {active.frostRiskDayCount === 1\n ? t('healthybowl.weather.calendar.summary.frostDaysSingular', 'frost-risk day this month')\n : t('healthybowl.weather.calendar.summary.frostDaysPlural', 'frost-risk days this month')}\n </p>\n </div>\n </div>\n <p className=\"mt-3 border-t border-border-subtle pt-3 text-xs text-text-secondary\">\n {active.historicalFirstFrost\n ? t(\n 'healthybowl.weather.calendar.summary.historicalFirstFrost',\n 'Historical avg first-frost: {{date}}',\n { date: formatFirstFrost(active.historicalFirstFrost) }\n )\n : t(\n 'healthybowl.weather.calendar.summary.noHistoricalFrost',\n 'No historical first-frost on record for this site.'\n )}\n </p>\n </div>\n </div>\n </div>\n )}\n\n {/* Back nav */}\n <div>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => navigate('..')}\n className=\"gap-1 text-text-secondary hover:text-text-primary\"\n >\n &larr; {t('healthybowl.weather.calendar.backToDashboard', 'Back to Weather Dashboard')}\n </Button>\n </div>\n </PageLayout>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;A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;QAEN,kBAAC,OAAD;KAAK,WAAU;eAAf,CACE,kBAAC,OAAD;MAAK,WAAU;gBAAf,CACE,kBAAC,OAAD;OAAK,WAAU;iBACb,kBAAC,GAAD,EAAW,WAAU,qBAAsB,CAAA;OACvC,CAAA,EACN,kBAAC,OAAD,EAAA,UAAA,CACE,kBAAC,KAAD;OAAG,WAAU;iBAAwC,EAAO;OAAsB,CAAA,EAClF,kBAAC,KAAD;OAAG,WAAU;iBACV,EAAO,sBAAsB,IAC1B,EAAE,0DAA0D,4BAA4B,GACxF,EAAE,wDAAwD,6BAA6B;OACzF,CAAA,CACA,EAAA,CAAA,CACF;SACN,kBAAC,KAAD;MAAG,WAAU;gBACV,EAAO,uBACJ,EACE,6DACA,wCACA,EAAE,MAAM,EAAiB,EAAO,qBAAqB,EAAE,CACxD,GACD,EACE,0DACA,qDACD;MACH,CAAA,CACA;OACF;MACF;OAlHN,kBAAC,GAAD;GACE,MAAM,kBAAC,GAAD,EAAc,WAAU,WAAY,CAAA;GAC1C,OAAO,EAAE,4CAA4C,mBAAmB;GACxE,aAAa,EACX,kDACA,8EACD;GACD,CAAA,EA+GJ,kBAAC,OAAD,EAAA,UACE,kBAAC,GAAD;GACE,SAAQ;GACR,MAAK;GACL,eAAe,EAAS,KAAK;GAC7B,WAAU;aAJZ,CAKC,MACS,EAAE,gDAAgD,4BAA4B,CAC/E;MACL,CAAA,CACK"}
@@ -0,0 +1,255 @@
1
+ import { getRelativeTime as e } from "../../utils/helpers.js";
2
+ import { PageLayout as t } from "../../components/PageLayout.js";
3
+ import { StatusBadge as n } from "../../components/StatusBadge.js";
4
+ import { EmptyState as r } from "../../components/EmptyState.js";
5
+ import { ErrorState as i } from "../../components/ErrorState.js";
6
+ import { ToastContainer as a } from "../../components/Toast.js";
7
+ import { PageLoader as o } from "../../components/PageLoader.js";
8
+ import { useToast as s } from "../../hooks/useToast.js";
9
+ import "../../components/index.js";
10
+ import { useWeatherIntelligence as c } from "../../hooks/useWeatherIntelligence.js";
11
+ import { useCallback as l, useState as u } from "react";
12
+ import { useI18n as d } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
13
+ import { AlertTriangle as f, BellRing as p, Bug as m, Check as h, Clock as g, Cloud as _, CloudRain as v, Send as y, Snowflake as b, Sun as x } from "lucide-react";
14
+ import { jsx as S, jsxs as C } from "react/jsx-runtime";
15
+ import { Button as w } from "@burdenoff/fe-libs/ui";
16
+ //#region src/healthybowl/pages/weather/WeatherAlertHistoryPage.tsx
17
+ var T = [
18
+ "ALL",
19
+ "FROST",
20
+ "STORM",
21
+ "HEAT"
22
+ ], E = (e) => {
23
+ switch (e) {
24
+ case "RED": return "bg-red-600 text-white";
25
+ case "AMBER": return "bg-amber-500 text-white";
26
+ default: return "bg-slate-500 text-white";
27
+ }
28
+ }, D = (e, t) => {
29
+ switch (e) {
30
+ case "FROST": return /* @__PURE__ */ S(b, { className: t });
31
+ case "STORM": return /* @__PURE__ */ S(v, { className: t });
32
+ case "HEAT": return /* @__PURE__ */ S(x, { className: t });
33
+ case "DISEASE": return /* @__PURE__ */ S(m, { className: t });
34
+ default: return /* @__PURE__ */ S(_, { className: t });
35
+ }
36
+ }, O = (e) => {
37
+ let t = e.toLowerCase();
38
+ return t === "in_app" || t === "inapp" || t === "in-app" ? "In-app" : t === "sms" ? "SMS" : t === "email" ? "Email" : t === "webhook" ? "Webhook" : t === "push" ? "Push" : e.charAt(0).toUpperCase() + e.slice(1);
39
+ }, k = () => {
40
+ let { t: m } = d(), { toasts: _, toast: v, dismiss: b } = s(), { alertEvents: x, loadingEvents: k, errorEvents: A, refetchEvents: j, loadEvents: M, markHandled: N, snooze: P } = c(), [F, I] = u("ALL"), [L, R] = u(null), [z, B] = u(!1), [V, H] = u(null), U = F === "ALL" ? x : L ?? [], W = l(async (e) => {
41
+ if (I(e), e === "ALL") {
42
+ R(null);
43
+ return;
44
+ }
45
+ B(!0);
46
+ try {
47
+ R(await M({ alertType: e }));
48
+ } catch (e) {
49
+ v({
50
+ title: m("healthybowl.weather.alertHistory.toast.loadError.title", "Could not load alerts"),
51
+ description: e instanceof Error ? e.message : void 0,
52
+ variant: "error"
53
+ }), R([]);
54
+ } finally {
55
+ B(!1);
56
+ }
57
+ }, [
58
+ M,
59
+ m,
60
+ v
61
+ ]), G = l(async () => {
62
+ F !== "ALL" && R(await M({ alertType: F }));
63
+ }, [F, M]), K = l(async (e) => {
64
+ H(e.id);
65
+ try {
66
+ await N(e.id), await G(), v({
67
+ title: m("healthybowl.weather.alertHistory.toast.handled.title", "Alert marked as handled"),
68
+ variant: "success"
69
+ });
70
+ } catch (e) {
71
+ v({
72
+ title: m("healthybowl.weather.alertHistory.toast.error.title", "Could not update alert"),
73
+ description: e instanceof Error ? e.message : void 0,
74
+ variant: "error"
75
+ });
76
+ } finally {
77
+ H(null);
78
+ }
79
+ }, [
80
+ N,
81
+ G,
82
+ m,
83
+ v
84
+ ]), q = l(async (e) => {
85
+ let t = new Date(Date.now() + 1440 * 60 * 1e3).toISOString();
86
+ H(e.id);
87
+ try {
88
+ await P(e.id, t), await G(), v({
89
+ title: m("healthybowl.weather.alertHistory.toast.snoozed.title", "Alert snoozed for 1 day"),
90
+ variant: "success"
91
+ });
92
+ } catch (e) {
93
+ v({
94
+ title: m("healthybowl.weather.alertHistory.toast.error.title", "Could not update alert"),
95
+ description: e instanceof Error ? e.message : void 0,
96
+ variant: "error"
97
+ });
98
+ } finally {
99
+ H(null);
100
+ }
101
+ }, [
102
+ P,
103
+ G,
104
+ m,
105
+ v
106
+ ]), J = (e) => {
107
+ switch (e) {
108
+ case "handled": return /* @__PURE__ */ S(n, {
109
+ label: m("healthybowl.weather.alertHistory.status.handled", "Handled ✓"),
110
+ variant: "success"
111
+ });
112
+ case "snoozed": return /* @__PURE__ */ S(n, {
113
+ label: m("healthybowl.weather.alertHistory.status.snoozed", "Snoozed"),
114
+ variant: "warning"
115
+ });
116
+ default: return /* @__PURE__ */ S(n, {
117
+ label: m("healthybowl.weather.alertHistory.status.delivered", "Delivered"),
118
+ variant: "muted"
119
+ });
120
+ }
121
+ }, Y = (e) => {
122
+ switch (e) {
123
+ case "ALL": return m("healthybowl.weather.alertHistory.filter.all", "All");
124
+ case "FROST": return m("healthybowl.weather.alertHistory.filter.frost", "Frost");
125
+ case "STORM": return m("healthybowl.weather.alertHistory.filter.storm", "Storm");
126
+ case "HEAT": return m("healthybowl.weather.alertHistory.filter.heat", "Heat");
127
+ default: return e;
128
+ }
129
+ }, X = k && x.length === 0, Z = A && x.length === 0;
130
+ return /* @__PURE__ */ C(t, {
131
+ title: m("healthybowl.weather.alertHistory.title", "Alert History"),
132
+ description: m("healthybowl.weather.alertHistory.description", "Weather early-warnings triggered for this farm"),
133
+ purpose: "Every weather early-warning that has fired for your farm — frost, storm, heat and disease alerts — in one timeline. See what was sent, through which channels and when, then mark an alert as handled or snooze it for a day once you've acted.",
134
+ children: [X ? /* @__PURE__ */ S(o, {}) : Z ? /* @__PURE__ */ S(i, { onRetry: () => void j() }) : /* @__PURE__ */ C("div", {
135
+ className: "space-y-6",
136
+ children: [
137
+ /* @__PURE__ */ S("div", {
138
+ className: "flex flex-wrap items-center gap-1 border-b border-border-subtle",
139
+ children: T.map((e) => /* @__PURE__ */ S("button", {
140
+ type: "button",
141
+ onClick: () => void W(e),
142
+ className: `border-b-2 px-3 pb-2 text-sm font-medium transition-colors ${F === e ? "border-primary text-primary" : "border-transparent text-text-secondary hover:text-text-primary"}`,
143
+ children: Y(e)
144
+ }, e))
145
+ }),
146
+ z ? /* @__PURE__ */ S(o, {}) : U.length === 0 ? /* @__PURE__ */ S(r, {
147
+ icon: /* @__PURE__ */ S(p, { className: "h-6 w-6 text-text-secondary" }),
148
+ title: m("healthybowl.weather.alertHistory.empty.title", "No weather alerts yet"),
149
+ description: m("healthybowl.weather.alertHistory.empty.description", "Alerts appear here the moment one of your early-warning rules crosses its threshold — frost tonight, a storm tomorrow or a heat spike. Nothing has fired for this filter yet.")
150
+ }) : /* @__PURE__ */ C("ol", {
151
+ className: "relative space-y-4 sm:pl-6",
152
+ children: [/* @__PURE__ */ S("span", {
153
+ "aria-hidden": !0,
154
+ className: "absolute left-2 top-2 bottom-2 hidden w-px bg-border-subtle sm:block"
155
+ }), U.map((t) => {
156
+ let n = V === t.id, r = t.status === "handled";
157
+ return /* @__PURE__ */ C("li", {
158
+ className: "relative",
159
+ children: [/* @__PURE__ */ S("span", {
160
+ "aria-hidden": !0,
161
+ className: "absolute -left-[1.375rem] top-6 hidden h-2.5 w-2.5 rounded-full border-2 border-bg-canvas bg-border-subtle sm:block"
162
+ }), /* @__PURE__ */ C("div", {
163
+ className: "flex overflow-hidden rounded-xl border border-border-subtle bg-bg-surface",
164
+ children: [/* @__PURE__ */ C("div", {
165
+ className: `flex w-20 shrink-0 flex-col items-center justify-center gap-1 py-4 ${E(t.severity)}`,
166
+ children: [D(t.alertType, "h-6 w-6"), /* @__PURE__ */ S("span", {
167
+ className: "text-xs font-semibold tracking-wide",
168
+ children: t.severity
169
+ })]
170
+ }), /* @__PURE__ */ C("div", {
171
+ className: "min-w-0 flex-1 p-4",
172
+ children: [
173
+ /* @__PURE__ */ C("div", {
174
+ className: "flex flex-wrap items-start justify-between gap-2",
175
+ children: [/* @__PURE__ */ C("h3", {
176
+ className: "flex items-center gap-1.5 text-sm font-semibold text-text-primary",
177
+ children: [/* @__PURE__ */ S("span", {
178
+ className: "text-text-secondary",
179
+ children: D(t.alertType, "h-4 w-4")
180
+ }), t.title]
181
+ }), J(t.status)]
182
+ }),
183
+ t.advisory && /* @__PURE__ */ S("p", {
184
+ className: "mt-1 text-sm text-text-secondary",
185
+ children: t.advisory
186
+ }),
187
+ t.observedValue != null && t.threshold != null && /* @__PURE__ */ C("p", {
188
+ className: "mt-1 flex items-center gap-1 text-xs text-text-secondary",
189
+ children: [/* @__PURE__ */ S(f, { className: "h-3.5 w-3.5 text-warning" }), m("healthybowl.weather.alertHistory.metric", "{{metric}} {{observed}}{{unit}} · threshold {{threshold}}{{unit}}", {
190
+ metric: t.metric,
191
+ observed: t.observedValue,
192
+ threshold: t.threshold,
193
+ unit: t.unit ?? ""
194
+ })]
195
+ }),
196
+ /* @__PURE__ */ C("p", {
197
+ className: "mt-2 flex flex-wrap items-center gap-1 text-xs text-text-secondary",
198
+ children: [
199
+ /* @__PURE__ */ S(y, { className: "h-3.5 w-3.5" }),
200
+ t.channels.length > 0 ? m("healthybowl.weather.alertHistory.sentVia", "Sent via {{channels}} · {{when}}", {
201
+ channels: t.channels.map(O).join(" + "),
202
+ when: e(t.triggeredAt)
203
+ }) : m("healthybowl.weather.alertHistory.triggered", "Triggered {{when}}", { when: e(t.triggeredAt) }),
204
+ t.status === "snoozed" && t.snoozedUntil && /* @__PURE__ */ C("span", {
205
+ className: "inline-flex items-center gap-1 text-warning",
206
+ children: [
207
+ "· ",
208
+ /* @__PURE__ */ S(g, { className: "h-3.5 w-3.5" }),
209
+ m("healthybowl.weather.alertHistory.snoozedUntil", "snoozed until {{when}}", { when: e(t.snoozedUntil) })
210
+ ]
211
+ })
212
+ ]
213
+ }),
214
+ t.ruleName && /* @__PURE__ */ S("p", {
215
+ className: "mt-1 text-[11px] text-text-secondary",
216
+ children: m("healthybowl.weather.alertHistory.rule", "Rule: {{name}}", { name: t.ruleName })
217
+ }),
218
+ /* @__PURE__ */ C("div", {
219
+ className: "mt-3 flex flex-wrap items-center gap-2",
220
+ children: [!r && /* @__PURE__ */ C(w, {
221
+ variant: "outline",
222
+ size: "sm",
223
+ onClick: () => void K(t),
224
+ disabled: n,
225
+ children: [/* @__PURE__ */ S(h, { className: "h-3.5 w-3.5" }), m("healthybowl.weather.alertHistory.actions.markHandled", "Mark as handled")]
226
+ }), /* @__PURE__ */ C(w, {
227
+ variant: "ghost",
228
+ size: "sm",
229
+ onClick: () => void q(t),
230
+ disabled: n,
231
+ className: "text-text-secondary hover:text-text-primary",
232
+ children: [/* @__PURE__ */ S(g, { className: "h-3.5 w-3.5" }), m("healthybowl.weather.alertHistory.actions.snooze", "Snooze 1 day")]
233
+ })]
234
+ })
235
+ ]
236
+ })]
237
+ })]
238
+ }, t.id);
239
+ })]
240
+ }),
241
+ k && x.length > 0 && F === "ALL" && /* @__PURE__ */ S("p", {
242
+ className: "text-center text-[11px] text-text-secondary",
243
+ children: m("healthybowl.weather.alertHistory.refreshing", "Refreshing…")
244
+ })
245
+ ]
246
+ }), /* @__PURE__ */ S(a, {
247
+ toasts: _,
248
+ onDismiss: b
249
+ })]
250
+ });
251
+ };
252
+ //#endregion
253
+ export { k as WeatherAlertHistoryPage };
254
+
255
+ //# sourceMappingURL=WeatherAlertHistoryPage.js.map