"use client" import { createEvent, type EventAttributes } from "ics" import { useIntl } from "react-intl" import { dt } from "@scandic-hotels/common/dt" import { logger } from "@scandic-hotels/common/logger" import { toast } from "@scandic-hotels/design-system/Toast" import useLang from "../../hooks/useLang" import type { RouterOutput } from "@scandic-hotels/trpc/client" type AddToCalendarProps = { checkInDate: NonNullable< RouterOutput["booking"]["get"] >["booking"]["checkInDate"] event: EventAttributes hotelName: NonNullable["hotel"]["name"] renderButton: (onPress: () => Promise) => React.ReactNode } export function AddToCalendar({ checkInDate, event, hotelName, renderButton, }: AddToCalendarProps) { const lang = useLang() const intl = useIntl() async function downloadBooking() { try { const d = dt(checkInDate).locale(lang).format("YYYY-MM-DD") const filename = `${hotelName.toLowerCase().split(" ").join("_")}-${d}.ics` createEvent(event, (error, value) => { if (error) { logger.error("ICS Error:", error) toast.error( intl.formatMessage({ id: "errorMessage.failedToAddToCalendar", defaultMessage: "Failed to add to calendar", }) ) return } const file = new File([value], filename, { type: "text/calendar" }) const url = URL.createObjectURL(file) const anchor = document.createElement("a") anchor.href = url anchor.download = filename document.body.appendChild(anchor) anchor.click() document.body.removeChild(anchor) URL.revokeObjectURL(url) }) } catch (error) { logger.error("Download error:", error) toast.error( intl.formatMessage({ id: "errorMessage.failedToAddToCalendar", defaultMessage: "Failed to add to calendar", }) ) } } return renderButton(downloadBooking) }