---
import { cn } from '../lib/cn'
import { timeAgo } from '../lib/timeAgo'

import type { Polymorphic } from 'astro/types'

type Props<Tag extends 'div' | 'li' | 'p' | 'span' = 'span'> = Polymorphic<{
  as: Tag
  start: Date
  end?: Date | null
  classNames?: {
    fadedWords?: string
  }
  now?: Date
}>

const { start, end = null, classNames = {}, now = new Date(), as: Tag = 'span', ...htmlProps } = Astro.props

const actualEndedAt = end ?? now
const startedAtFormatted = timeAgo.format(start, 'twitter-minute-now')
const isUpcoming = now < start
const isOngoing = now >= start && (!end || now <= end)
const endedAtFormatted = timeAgo.format(actualEndedAt, 'twitter-minute-now')
const isOneTimeEvent = start === actualEndedAt || startedAtFormatted === endedAtFormatted
---

<Tag {...htmlProps}>
  {
    !end ? (
      isUpcoming ? (
        <>
          Upcoming
          <span class={cn('text-current/50', classNames.fadedWords)}>on</span>
          <time class="whitespace-nowrap">{startedAtFormatted}</time>
        </>
      ) : (
        <>
          Ongoing
          <span class={cn('text-current/50', classNames.fadedWords)}>since</span>
          <time class="whitespace-nowrap">{startedAtFormatted}</time>
        </>
      )
    ) : isOneTimeEvent ? (
      isUpcoming ? (
        <>
          Upcoming
          <span class={cn('text-current/50', classNames.fadedWords)}>on</span>
          <time class="whitespace-nowrap">{startedAtFormatted}</time>
        </>
      ) : (
        <time class="whitespace-nowrap">{startedAtFormatted}</time>
      )
    ) : (
      <>
        {isUpcoming ? (
          <>
            Upcoming
            <span class={cn('text-current/50', classNames.fadedWords)}>from</span>
            <time class="whitespace-nowrap">{startedAtFormatted}</time>
            <span class={cn('text-current/50', classNames.fadedWords)}>to</span>
            <time class="whitespace-nowrap">{endedAtFormatted}</time>
          </>
        ) : isOngoing ? (
          <>
            Ongoing
            <span class={cn('text-current/50', classNames.fadedWords)}>since</span>
            <time class="whitespace-nowrap">{startedAtFormatted}</time>
            <span class={cn('text-current/50', classNames.fadedWords)}>to</span>
            <time class="whitespace-nowrap">{endedAtFormatted}</time>
          </>
        ) : (
          <>
            <span class={cn('text-current/50', classNames.fadedWords)}>From</span>
            <time class="whitespace-nowrap">{startedAtFormatted}</time>
            <span class={cn('text-current/50', classNames.fadedWords)}>to</span>
            <time class="whitespace-nowrap">{endedAtFormatted}</time>
          </>
        )}
      </>
    )
  }
</Tag>
