/**
 * Format an event's date and time range in a user-friendly way.
 *
 * format "long" (default):
 * - same day:  "Freitag 24.07.26, 18:00 - 20:00 Uhr"
 * - multi-day: "Fr. 24.07. 18:00 Uhr - So. 26.07. 14:00 Uhr"
 *
 * format "short" (narrow screens):
 * - same day:  "Freitag, 18:00 - 20:00 Uhr"
 * - multi-day: "Fr 18:00 - So 14:00 Uhr"
 */
export const formatEventDate = (start: Date, end?: Date, format: "long" | "short" = "long"): string => {
  const time = (d: Date) => d.toLocaleTimeString("de-DE", { timeStyle: "short", timeZone: "Europe/Berlin" })
  const calendarDay = (d: Date) => d.toLocaleDateString("de-DE", { timeZone: "Europe/Berlin" })
  const weekday = (d: Date, length: "long" | "short") =>
    d.toLocaleDateString("de-DE", { weekday: length, timeZone: "Europe/Berlin" })
  const isMultiDay = end && calendarDay(start) !== calendarDay(end)

  switch (format) {
    case "short": {
      if (end && isMultiDay) {
        return `${weekday(start, "short")} ${time(start)} - ${weekday(end, "short")} ${time(end)} Uhr`
      }
      const endTime = end ? ` - ${time(end)}` : ""
      return `${weekday(start, "long")}, ${time(start)}${endTime} Uhr`
    }

    case "long": {
      if (end && isMultiDay) {
        // "Fr. 24.07." — assembled manually because Intl puts a comma between weekday and date
        const dayDate = (d: Date) =>
          `${weekday(d, "short")}. ${d.toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", timeZone: "Europe/Berlin" })}`
        return `${dayDate(start)} ${time(start)} Uhr - ${dayDate(end)} ${time(end)} Uhr`
      }
      const endTime = end ? ` - ${time(end)}` : ""
      return `${weekday(start, "long")} ${start.toLocaleDateString("de-DE", { dateStyle: "short", timeZone: "Europe/Berlin" })}, ${time(start)}${endTime} Uhr`
    }
  }
}
