<section id="entry-{{ entry.id }}"
     class="{{styles.list_container}}">

  <!-- Error container -->
  <div id="entry-errors-{{ entry.id }}" class="mt-2 text-sm text-red-600"></div>

  <form
    class="space-y-3 mt-4"
    hx-put="{{ url_for(
        'calendars.calendar.day.calendar_entries.calendar_entry.put',
        slug=post.slug,
        calendar_slug=calendar.slug,
        day=day, month=month, year=year,
        entry_id=entry.id
    ) }}"
    hx-target="#entry-{{ entry.id }}"
    hx-swap="outerHTML"
  >

    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

    <!-- Name -->
    <div>
      <label class="block text-sm font-medium text-stone-700 mb-1"
             for="entry-name-{{ entry.id }}">
        Name
      </label>
      <input
        id="entry-name-{{ entry.id }}"
        name="name"
        class="w-full border p-2 rounded"
        placeholder="Name"
        value="{{ entry.name }}"
      >
    </div>

    <!-- Slot picker -->
    <div>
      <label class="block text-sm font-medium text-stone-700 mb-1"
             for="entry-slot-{{ entry.id }}">
        Slot
      </label>
      {% if day_slots %}
        <select
          id="entry-slot-{{ entry.id }}"
          name="slot_id"
          class="w-full border p-2 rounded"
          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.flexible else '0' }}"
              data-cost="{{ slot.cost if slot.cost is not none else '0' }}"
              {% if entry.slot_id == slot.id %}selected{% endif %}
            >
              {{ slot.name }}
              ({{ slot.time_start.strftime('%H:%M') }}
              {% if slot.time_end %}–{{ slot.time_end.strftime('%H:%M') }}{% else %}–open-ended{% endif %})
              {% if slot.flexible %}[flexible]{% endif %}
            </option>
          {% endfor %}
        </select>
      {% else %}
        <div class="text-sm text-stone-500">
          No slots defined for this day.
        </div>
      {% endif %}
    </div>

    <!-- Time inputs — shown only for flexible slots -->
    <div data-time-fields class="hidden space-y-3">
      <div>
        <label class="block text-sm font-medium text-stone-700 mb-1"
               for="entry-start-{{ entry.id }}">
          From
        </label>
        <input
          id="entry-start-{{ entry.id }}"
          name="start_at"
          type="time"
          class="w-full border p-2 rounded"
          value="{{ entry.start_at.strftime('%H:%M') if entry.start_at else '' }}"
          data-entry-start
        >
      </div>

      <div>
        <label class="block text-sm font-medium text-stone-700 mb-1"
               for="entry-end-{{ entry.id }}">
          To
        </label>
        <input
          id="entry-end-{{ entry.id }}"
          name="end_at"
          type="time"
          class="w-full border p-2 rounded"
          value="{{ entry.end_at.strftime('%H:%M') if entry.end_at else '' }}"
          data-entry-end
        >
      </div>

      <p class="text-xs text-stone-500" data-slot-boundary></p>
    </div>

    <!-- Fixed time summary — shown for non-flexible slots -->
    <div data-fixed-summary class="hidden text-sm text-stone-600"></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">£{{ ('%.2f'|format(entry.cost)) if entry.cost is not none else '0.00' }}</span>
    </div>

    <!-- Ticket Configuration -->
    <div class="border-t pt-3 mt-3">
      <h4 class="text-sm font-semibold text-stone-700 mb-3">Ticket Configuration</h4>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-stone-700 mb-1"
                 for="entry-ticket-price-{{ entry.id }}">
            Ticket Price (£)
          </label>
          <input
            id="entry-ticket-price-{{ entry.id }}"
            name="ticket_price"
            type="number"
            step="0.01"
            min="0"
            class="w-full border p-2 rounded"
            placeholder="Leave empty for no tickets"
            value="{{ ('%.2f'|format(entry.ticket_price)) if entry.ticket_price is not none else '' }}"
          >
          <p class="text-xs text-stone-500 mt-1">Leave empty if no tickets needed</p>
        </div>

        <div>
          <label class="block text-sm font-medium text-stone-700 mb-1"
                 for="entry-ticket-count-{{ entry.id }}">
            Total Tickets
          </label>
          <input
            id="entry-ticket-count-{{ entry.id }}"
            name="ticket_count"
            type="number"
            min="0"
            class="w-full border p-2 rounded"
            placeholder="Leave empty for unlimited"
            value="{{ entry.ticket_count if entry.ticket_count is not none else '' }}"
          >
          <p class="text-xs text-stone-500 mt-1">Leave empty for unlimited</p>
        </div>
      </div>
    </div>

    <div class="flex justify-end gap-2 pt-2">
      
      <!-- Cancel button -->
      <button
        type="button"
        class="{{ styles.cancel_button }}"
        hx-get="{{ url_for(
            'calendars.calendar.day.calendar_entries.calendar_entry.get',
            slug=post.slug,
            calendar_slug=calendar.slug,
            day=day, month=month, year=year,
            entry_id=entry.id
        ) }}"
        hx-target="#entry-{{ entry.id }}"
        hx-swap="outerHTML"
      >
        Cancel
      </button>

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

    </div>

  </form>
</section>

{# --- 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) {
      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();
      }

      // Initial state
      applyFromOption(select.selectedOptions[0]);

      select.addEventListener('change', () => {
        applyFromOption(select.selectedOptions[0]);
      });

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

    // Initial load
    document.addEventListener('DOMContentLoaded', () => {
      initEntrySlotPicker(document);
    });

    // HTMX fragments
    if (window.htmx) {
      htmx.onLoad((content) => {
        initEntrySlotPicker(content);
      });
    }
  })();
</script>