<div id="entry-errors" class="mt-2 text-sm text-red-600"></div>

<form
  class="mt-4 grid grid-cols-1 md:grid-cols-4 gap-2"
  hx-post="{{ url_for(
    'calendars.calendar.day.calendar_entries.add_entry',
    slug=post.slug,
    calendar_slug=calendar.slug,
    day=day,
    month=month,
    year=year,
  ) }}"
  hx-target="#day-entries"
  hx-on::after-request="if (event.detail.successful) this.reset()"
  hx-swap="innerHTML"
>
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  
  {# 1) Entry name #}
  <input
    name="name"
    type="text"
    required
    class="border rounded px-3 py-2"
    placeholder="Entry name"
  />

  {# 2) Slot picker for this weekday (required) #}
  {% if day_slots %}
    <select
      name="slot_id"
      class="border rounded px-3 py-2"
      data-slot-picker
      required
    >
      {% for slot in day_slots %}
        <option
          value="{{ slot.id }}"
          data-start="{{ slot.time_start.strftime('%H:%M') }}"
          data-end="{{ slot.time_end.strftime('%H:%M') if slot.time_end else '' }}"
          data-flexible="{{ '1' if slot | getattr('flexible', False) else '0' }}"
          data-cost="{{ slot.cost if slot.cost is not none else '0' }}"
        >
          {{ slot.name }}
          ({{ slot.time_start.strftime('%H:%M') }}
          {% if slot.time_end %}–{{ slot.time_end.strftime('%H:%M') }}{% else %}–open-ended{% endif %})
          {% if slot | getattr('flexible', False) %}[flexible]{% endif %}
        </option>
      {% endfor %}
    </select>
  {% else %}
    <div class="text-sm text-stone-500">
      No slots defined for this day.
    </div>
  {% endif %}

  {# 3) Time entry + cost display #}
  <div class="md:col-span-2 flex flex-col gap-2">
    {# Time inputs — hidden until a flexible slot is selected #}
    <div data-time-fields class="hidden">
      <div class="mb-2">
        <label class="block text-xs font-medium text-stone-700 mb-1">From</label>
        <input
          name="start_time"
          type="time"
          class="border rounded px-3 py-2 w-full"
          data-entry-start
        />
      </div>
      <div class="mb-2">
        <label class="block text-xs font-medium text-stone-700 mb-1">To</label>
        <input
          name="end_time"
          type="time"
          class="border rounded px-3 py-2 w-full"
          data-entry-end
        />
      </div>
      <p class="text-xs text-stone-500" data-slot-boundary></p>
    </div>

    {# Cost display — shown when a slot is selected #}
    <div data-cost-row class="hidden text-sm font-medium text-stone-700">
      Estimated Cost: <span data-cost-display class="text-green-600">£0.00</span>
    </div>

    {# Summary of fixed times — shown for non-flexible slots #}
    <div data-fixed-summary class="hidden text-sm text-stone-600"></div>
  </div>

  {# Ticket Configuration #}
  <div class="md:col-span-4 border-t pt-3 mt-2">
    <h4 class="text-sm font-semibold text-stone-700 mb-3">Ticket Configuration (Optional)</h4>
    <div class="grid grid-cols-2 gap-3">
      <div>
        <label class="block text-xs font-medium text-stone-700 mb-1">
          Ticket Price (£)
        </label>
        <input
          name="ticket_price"
          type="number"
          step="0.01"
          min="0"
          class="w-full border rounded px-3 py-2 text-sm"
          placeholder="Leave empty for no tickets"
        />
      </div>
      <div>
        <label class="block text-xs font-medium text-stone-700 mb-1">
          Total Tickets
        </label>
        <input
          name="ticket_count"
          type="number"
          min="0"
          class="w-full border rounded px-3 py-2 text-sm"
          placeholder="Leave empty for unlimited"
        />
      </div>
    </div>
  </div>

  <div class="flex justify-end gap-2 pt-2 md:col-span-4">
    <button
      type="button"
      class="{{styles.cancel_button}}"
      hx-get="{{ url_for('calendars.calendar.day.calendar_entries.add_button',
          slug=post.slug,
          calendar_slug=calendar.slug,
          day=day,
          month=month,
          year=year,
      ) }}"
      hx-target="#entry-add-container"
      hx-swap="innerHTML"
    >
      Cancel
    </button>

    <button
      type="submit"
      class="{{styles.action_button}}"
      data-confirm="true"
      data-confirm-title="Add entry?"
      data-confirm-text="Are you sure you want to add this entry?"
      data-confirm-icon="question"
      data-confirm-confirm-text="Yes, add it"
      data-confirm-cancel-text="Cancel"
    >
      <i class="fa fa-save"></i>
      Save entry
    </button>
  </div>
</form>

{# --- Behaviour: lock / unlock times based on slot.flexible --- #}
<script>
  (function () {
    function timeToMinutes(timeStr) {
      if (!timeStr) return 0;
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    }

    function calculateCost(slotCost, slotStart, slotEnd, actualStart, actualEnd, flexible) {
      if (!flexible) {
        // Fixed slot: use full slot cost
        return parseFloat(slotCost);
      }
      
      // Flexible slot: prorate based on time range
      if (!actualStart || !actualEnd) return 0;
      
      const slotStartMin = timeToMinutes(slotStart);
      const slotEndMin = timeToMinutes(slotEnd);
      const actualStartMin = timeToMinutes(actualStart);
      const actualEndMin = timeToMinutes(actualEnd);
      
      const slotDuration = slotEndMin - slotStartMin;
      const actualDuration = actualEndMin - actualStartMin;
      
      if (slotDuration <= 0 || actualDuration <= 0) return 0;
      
      const ratio = actualDuration / slotDuration;
      return parseFloat(slotCost) * ratio;
    }

    function initEntrySlotPicker(root, applyInitial = false) {
      const select = root.querySelector('[data-slot-picker]');
      if (!select) return;

      const timeFields = root.querySelector('[data-time-fields]');
      const startInput = root.querySelector('[data-entry-start]');
      const endInput = root.querySelector('[data-entry-end]');
      const helper = root.querySelector('[data-slot-boundary]');
      const costDisplay = root.querySelector('[data-cost-display]');
      const costRow = root.querySelector('[data-cost-row]');
      const fixedSummary = root.querySelector('[data-fixed-summary]');

      if (!startInput || !endInput) return;

      function updateCost() {
        const opt = select.selectedOptions[0];
        if (!opt || !opt.value) {
          if (costDisplay) costDisplay.textContent = '£0.00';
          return;
        }

        const cost = opt.dataset.cost || '0';
        const s = opt.dataset.start || '';
        const e = opt.dataset.end || '';
        const flexible = opt.dataset.flexible === '1';

        const calculatedCost = calculateCost(
          cost, s, e,
          startInput.value, endInput.value,
          flexible
        );

        if (costDisplay) {
          costDisplay.textContent = '£' + calculatedCost.toFixed(2);
        }
      }

      function applyFromOption(opt) {
        if (!opt || !opt.value) {
          if (timeFields) timeFields.classList.add('hidden');
          if (costRow) costRow.classList.add('hidden');
          if (fixedSummary) fixedSummary.classList.add('hidden');
          return;
        }

        const s = opt.dataset.start || '';
        const e = opt.dataset.end || '';
        const flexible = opt.dataset.flexible === '1';

        if (!flexible) {
          // Fixed slot: hide time inputs, show summary + cost
          if (s) startInput.value = s;
          if (e) endInput.value = e;
          if (timeFields) timeFields.classList.add('hidden');
          if (fixedSummary) {
            fixedSummary.classList.remove('hidden');
            if (e) {
              fixedSummary.textContent = `${s} – ${e}`;
            } else {
              fixedSummary.textContent = `From ${s} (open-ended)`;
            }
          }
          if (costRow) costRow.classList.remove('hidden');
        } else {
          // Flexible slot: show time inputs, hide fixed summary, show cost
          if (timeFields) timeFields.classList.remove('hidden');
          if (fixedSummary) fixedSummary.classList.add('hidden');
          if (costRow) costRow.classList.remove('hidden');
          if (helper) {
            if (e) {
              helper.textContent = `Times must be between ${s} and ${e}.`;
            } else {
              helper.textContent = `Start at or after ${s}.`;
            }
          }
        }

        updateCost();
      }

      // Only apply initial state if explicitly requested (on first load)
      if (applyInitial) {
        applyFromOption(select.selectedOptions[0]);
      }

      // Remove any existing listener to prevent duplicates
      if (select._slotChangeHandler) {
        select.removeEventListener('change', select._slotChangeHandler);
      }

      select._slotChangeHandler = () => {
        applyFromOption(select.selectedOptions[0]);
      };

      select.addEventListener('change', select._slotChangeHandler);

      // Update cost when times change (for flexible slots)
      startInput.addEventListener('input', updateCost);
      endInput.addEventListener('input', updateCost);
    }

    // Initial load - apply initial state
    document.addEventListener('DOMContentLoaded', () => {
      initEntrySlotPicker(document, true);
    });

    // HTMX fragments - apply initial state so visibility is correct
    if (window.htmx) {
      htmx.onLoad((content) => {
        initEntrySlotPicker(content, true);
      });
    }
  })();
</script>