- binary_sensor:
    - name: tesla_charge_now
      state: >
        {% set deadline_raw = states('input_datetime.tesla_charge_deadline') %}
        {% set deadline_ts = as_timestamp(deadline_raw) if deadline_raw not in ['unknown','unavailable',''] else none %}
        {% set now_ts = as_timestamp(now().replace(minute=0, second=0, microsecond=0)) %}

        {% set hours_needed = states('sensor.tesla_charge_hours_needed') | float(0) | round(0, 'ceil') %}

        {% set prices = (state_attr('sensor.energi_data_service','raw_today') or [])
                        + ((state_attr('sensor.energi_data_service','raw_tomorrow') or [])
                           if state_attr('sensor.energi_data_service', 'tomorrow_valid') else []) %}

        {# Filter gyldige slots før deadline #}
        {% set ns = namespace(valid=[], best_block=[], best_price=999999) %}
        {% for p in prices %}
          {% if p.hour %}
            {% set ts = as_timestamp(p.hour) %}
            {% if ts >= now_ts and (not deadline_ts or ts <= deadline_ts) %}
              {% set ns.valid = ns.valid + [p] %}
            {% endif %}
          {% endif %}
        {% endfor %}

        {# Sortér kronologisk #}
        {% set valid = ns.valid | sort(attribute='hour') %}

        {% for i in range(0, (valid | length) - hours_needed + 1) %}
          {% set block = valid[i:i+hours_needed] %}
          {% set total = block | map(attribute='price') | sum %}
          {% if total < ns.best_price %}
            {% set ns.best_price = total %}
            {% set ns.best_block = block %}
          {% endif %}
        {% endfor %}

        {{ ns.best_block | map(attribute='hour') | map('as_timestamp') | select('eq', now_ts) | list | count > 0 }}

- sensor:
    - name: tesla_charge_hours_needed
      unique_id: tesla_charge_hours_needed
      unit_of_measurement: h
      icon: mdi:timer-outline
      state: >
        {% set battery = states('sensor.snowywhite_battery') | replace('%', '') | float(0) %}
        {% set limit = states('number.snowywhite_charge_limit') | float(100) %}
        {% set charger_power = states('sensor.snowywhite_charger_power') | float(0) %}
        {% set effective_power = charger_power if charger_power > 0 else 11 %}
        {% set battery_capacity_kwh = 75 %}
        {% set remaining_pct = [limit - battery, 0] | max %}
        {% set energy_needed = remaining_pct * battery_capacity_kwh / 100 %}
        {{ (energy_needed / effective_power) | round(1) }}

    - name: tesla_charge_plan
      unique_id: tesla_charge_plan
      icon: mdi:calendar-clock
      state: >
        {% set deadline_raw = states('input_datetime.tesla_charge_deadline') %}
        {% set deadline_ts = as_timestamp(deadline_raw) if deadline_raw not in ['unknown','unavailable',''] else none %}
        {% set now_ts = as_timestamp(now().replace(minute=0, second=0, microsecond=0)) %}
        {% set hours_needed = states('sensor.tesla_charge_hours_needed') | float(0) | round(0, 'ceil') %}
        {% set prices = (state_attr('sensor.energi_data_service','raw_today') or [])
                        + ((state_attr('sensor.energi_data_service','raw_tomorrow') or [])
                           if state_attr('sensor.energi_data_service', 'tomorrow_valid') else []) %}
        {% set ns = namespace(valid=[], best_block=[], best_price=999999) %}

        {% for p in prices %}
          {% if p.hour %}
            {% set ts = as_timestamp(p.hour) %}
            {% if ts >= now_ts and (not deadline_ts or ts <= deadline_ts) %}
              {% set ns.valid = ns.valid + [p] %}
            {% endif %}
          {% endif %}
        {% endfor %}

        {% set valid = ns.valid | sort(attribute='hour') %}
        {% for i in range(0, (valid | length) - hours_needed + 1) %}
          {% set block = valid[i:i+hours_needed] %}
          {% set total = block | map(attribute='price') | sum %}
          {% if total < ns.best_price %}
            {% set ns.best_price = total %}
            {% set ns.best_block = block %}
          {% endif %}
        {% endfor %}

        {% if hours_needed <= 0 %}
          Ingen opladning nødvendig
        {% elif ns.best_block | length == 0 %}
          Ingen plan fundet
        {% else %}
          {{ as_timestamp(ns.best_block[0].hour) | timestamp_custom('%H:%M') }}-{{ (as_timestamp(ns.best_block[-1].hour) + 3600) | timestamp_custom('%H:%M') }}
        {% endif %}
