module SpiritsHelper
  CHALDEAN_ORDER = %w[Saturn Jupiter Mars Sun Venus Mercury Moon].freeze

  def planetary_hour_and_day_match?(datetime, planet)
    planet_for_day(datetime.strftime('%A')) == planet && planetary_hour(datetime) == planet
  end

  def planetary_hour(datetime)
    day_start = datetime.beginning_of_day
    hour_duration = (datetime.end_of_day - day_start) / 12.0
    hour_number = ((datetime - day_start) / hour_duration).floor

    weekday = datetime.strftime('%A')
    start_index = CHALDEAN_ORDER.index(planet_for_day(weekday))
    planet_index = (start_index + hour_number) % 7

    CHALDEAN_ORDER[planet_index]
  end


def time_matches_rank?(datetime, rank)
  latitude = session[:latitude].to_f
  sunrise_time = DateTime.parse(session[:sunrise]) if session[:sunrise]
  sunset_time = DateTime.parse(session[:sunset]) if session[:sunset]
  
  # Adjust twilight duration based on latitude. This is a rough approximation.
  twilight_adjustment = [30 + (latitude.abs / 90) * 30, 60].min.minutes

  dawn_time = sunrise_time - twilight_adjustment if sunrise_time
  twilight_end_time = sunset_time + twilight_adjustment if sunset_time

  case rank.time
  when 'anytime'
    true
  when 'dawn to sunrise'
    return false unless sunrise_time
    datetime.between?(dawn_time, sunrise_time)
  when 'sunrise to noon'
    return false unless sunrise_time
    datetime.between?(sunrise_time, datetime.change(hour: 12))
  when '3pm to sunrise'
    # Here we assume if the datetime is before sunrise, it's from the previous day
    (datetime.hour >= 15) || (datetime <= sunrise_time)
  when 'anytime excluding twilight'
    return false unless twilight_end_time
    !datetime.between?(sunset_time, twilight_end_time)
  when 'anytime in a desolate place'
    true
  when 'on great occasions'
    # Placeholder - you'd have to define what "on great occasions" means in terms of time
    datetime.hour.between?(10, 14)
  else
    false
  end
end  

  def planet_for_day(weekday)
    case weekday
    when 'Sunday'
      'Sun'
    when 'Monday'
      'Moon'
    when 'Tuesday'
      'Mars'
    when 'Wednesday'
      'Mercury'
    when 'Thursday'
      'Jupiter'
    when 'Friday'
      'Venus'
    when 'Saturday'
      'Saturn'
    end
  end
end