import React from 'react'
import { platformAd, type PlatformAdProps } from './PlatformAd'

const LOCAL_STORAGE_KEY = 'platformAdLastShown'

export function usePlatformAd(platformAdProps: PlatformAdProps | undefined) {
  React.useEffect(() => {
    if (!platformAdProps) return

    // Retrieve the last shown time from local storage
    const lastShownStr = localStorage.getItem(LOCAL_STORAGE_KEY)
    let shouldShowAd = true
    if (lastShownStr) {
      const lastShown = new Date(lastShownStr)
      const today = new Date()

      // Check if the ad was already shown today
      if (
        lastShown.getFullYear() === today.getFullYear() &&
        lastShown.getMonth() === today.getMonth() &&
        lastShown.getDate() === today.getDate()
      ) {
        shouldShowAd = false
      }
    }

    if (shouldShowAd) {
      const timeoutId = setTimeout(() => {
        platformAd(platformAdProps)
        // Store the current time in local storage as the ad's shown time
        localStorage.setItem(LOCAL_STORAGE_KEY, new Date().toISOString())
      })

      return () => clearTimeout(timeoutId)
    }
    return
  }, [platformAdProps])
}
