Recording max value each 24hrs

Hi. Trying to create a sensor which records the max value of a sensor just before midnight. The “Spa Daily Total Cost” sensor works.
The only bit not working is the final “Spa Max Daily Total Cost” sensor. It starts life as unknown, then becomes unavailable when it triggers… Any ideas?

template:
  - trigger:
      - platform: time_pattern
        minutes: "/30" 
    sensor:
      - name: "Spa Daily Total Cost"
        unit_of_measurement: "$"
        device_class: monetary
        state: > 
           {{(( (states("sensor.spa_solar_wh_energy_daily") | float * 0.1725) + (states("sensor.spa_dr_wh_energy_daily") | float * 0.3031) + (states("sensor.spa_nr_wh_energy_daily") | float * 0.1814)) | round (2) ) }}           
  
  - trigger:
      - platform: time
        at: "23:59:00"
    sensor:
      - name: "Spa Max Daily Total Cost"
        unit_of_measurement: "$" 
        device_class: monetary        
        state: >
          {% set spacost = states('sensor.spa_daily_total_cost')|float(None) %}
          {% set spamax = states('spa_max_daily_total_cost') | float %}
          {% if  spacost != None and (trigger.id == 'midnight' or spamax == None or spacost > spamax) %} {{ spacost }}
          {% else %} {{ spamax }} {% endif %}