<% layout('layouts/main') %>
<% const staffBase = typeof staffBaseUrl !== 'undefined' ? staffBaseUrl : '/agenda'; %>
<% const month = time.month || new Date().toISOString().slice(0, 7); %>
<% const statusLabels = { draft: 'Brouillon', submitted: 'En validation', approved: 'Validé', exported: 'Exporté' }; %>
<% const entryDate = (entry) => entry.work_date || (entry.starts_at ? String(entry.starts_at).slice(0, 10) : String(entry.created_at || '').slice(0, 10)); %>
<% const totalHours = (minutes) => (Number(minutes || 0) / 60).toFixed(2); %>
<% const hoursLabel = (minutes) => Number(minutes || 0) > 0 ? ui.duration(minutes || 0) : '0h00'; %>
<% const timeOnly = (value) => {
  if (!value) return '';
  const raw = value instanceof Date ? value.toTimeString().slice(0, 5) : String(value);
  const match = raw.match(/(\d{2}):(\d{2})/);
  return match ? `${match[1]}:${match[2]}` : '';
}; %>
<% const segmentSummary = (start, end, minutes) => {
  const range = [timeOnly(start), timeOnly(end)].filter(Boolean).join(' - ');
  return { range, duration: hoursLabel(minutes) };
}; %>
<div class="app-shell">
  <%- partial('partials/staff-nav') %>
  <section class="content staff-hours-page">
    <div class="page-head">
      <div>
        <p class="eyebrow">Portail employé</p>
        <h1>Mes heures</h1>
        <p class="muted">Saisie simple des heures du matin, de l’après-midi et des frais éventuels. Les heures validées restent centralisées pour l’administration.</p>
      </div>
      <a class="button secondary" href="<%= staffBase %>">Agenda</a>
    </div>

    <section class="stat-grid compact-stat-grid staff-hours-kpis">
      <article class="stat"><strong><%= ui.duration(time.totals.minutes || 0) %></strong><span>Saisi ce mois</span></article>
      <article class="stat"><strong><%= ui.duration(time.totals.approvedMinutes || 0) %></strong><span>Validé admin</span></article>
      <article class="stat"><strong><%= time.totals.pending || 0 %></strong><span>En attente RH</span></article>
      <article class="stat"><strong><%= ui.money(time.totals.expenses || 0) %></strong><span>Frais déclarés</span></article>
    </section>

    <form class="panel search-panel form-grid two" method="get">
      <label>Mois<input type="month" name="month" value="<%= month %>"></label>
      <button>Afficher</button>
    </form>

    <section class="panel staff-hours-entry-panel">
      <div class="compact-heading">
        <p class="eyebrow">Nouvelle saisie</p>
        <h2>Ajouter mes heures</h2>
        <p>Le total est calculé automatiquement, même si seule une demi-journée est renseignée.</p>
      </div>
      <form method="post" action="<%= staffBase %>/heures" class="staff-hours-form" data-hours-form>
        <input type="hidden" name="_csrf" value="<%= csrfToken %>">
        <input type="hidden" name="month" value="<%= month %>">
        <input type="hidden" name="source_type" value="manual">
        <div class="form-grid two">
          <label>Date<input type="date" name="work_date" value="<%= new Date().toISOString().slice(0, 10) %>" required></label>
          <label>Frais CHF<input type="number" step="0.01" name="expense_amount" value="0"></label>
        </div>
        <div class="form-grid four staff-hours-simple-grid">
          <label>Début matin<input type="time" name="morning_start_time" data-hours-start></label>
          <label>Fin matin<input type="time" name="morning_end_time" data-hours-end></label>
          <label>Début après-midi<input type="time" name="afternoon_start_time" data-hours-start></label>
          <label>Fin après-midi<input type="time" name="afternoon_end_time" data-hours-end></label>
        </div>
        <div class="staff-hours-total-row">
          <span>Total calculé</span>
          <strong data-hours-total>0h00</strong>
        </div>
        <div class="actions">
          <button name="action" value="submit">Envoyer pour validation</button>
        </div>
      </form>
    </section>

    <section class="panel">
      <div class="compact-heading">
        <p class="eyebrow">Historique</p>
        <h2>Feuille d’heures du mois</h2>
      </div>
      <div class="table-wrap staff-hours-table">
        <table>
          <thead><tr><th>Date</th><th>Matin</th><th>Après-midi</th><th>Total</th><th>Frais</th><th>Statut</th></tr></thead>
          <tbody>
            <% time.entries.forEach((entry) => { %>
              <% const morningSegment = segmentSummary(entry.morning_starts_at, entry.morning_ends_at, entry.morning_minutes); %>
              <% const afternoonSegment = segmentSummary(entry.afternoon_starts_at, entry.afternoon_ends_at, entry.afternoon_minutes); %>
              <tr>
                <td><strong><%= ui.date(entryDate(entry)) %></strong></td>
                <td>
                  <strong><%= morningSegment.range || morningSegment.duration %></strong>
                  <% if (morningSegment.range) { %><br><span class="muted"><%= morningSegment.duration %></span><% } %>
                </td>
                <td>
                  <strong><%= afternoonSegment.range || afternoonSegment.duration %></strong>
                  <% if (afternoonSegment.range) { %><br><span class="muted"><%= afternoonSegment.duration %></span><% } %>
                </td>
                <td><strong><%= ui.duration(entry.resolved_minutes || 0) %></strong><br><span class="muted"><%= totalHours(entry.resolved_minutes) %> h</span></td>
                <td><%= ui.money(entry.expense_amount || 0) %></td>
                <td><span class="badge status-<%= entry.status %>"><%= statusLabels[entry.status] || ui.label(entry.status) %></span></td>
              </tr>
            <% }) %>
            <% if (!time.entries.length) { %>
              <tr><td colspan="6">Aucune heure saisie sur ce mois. Ajoutez vos heures depuis le formulaire ci-dessus.</td></tr>
            <% } %>
          </tbody>
        </table>
      </div>
    </section>
  </section>
</div>
<script>
  (() => {
    const form = document.querySelector('[data-hours-form]');
    if (!form) return;
    const target = form.querySelector('[data-hours-total]');
    const segments = [
      ['morning_start_time', 'morning_end_time'],
      ['afternoon_start_time', 'afternoon_end_time']
    ];
    const timeToMinutes = (value) => {
      const match = String(value || '').match(/^(\d{2}):(\d{2})$/);
      if (!match) return null;
      return Number(match[1]) * 60 + Number(match[2]);
    };
    const segmentMinutes = (startName, endName) => {
      const start = timeToMinutes(form.elements[startName]?.value);
      const end = timeToMinutes(form.elements[endName]?.value);
      if (start === null || end === null) return 0;
      return end > start ? end - start : 0;
    };
    const render = () => {
      const minutes = segments.reduce((sum, segment) => sum + segmentMinutes(segment[0], segment[1]), 0);
      const hours = Math.floor(minutes / 60);
      const rest = String(minutes % 60).padStart(2, '0');
      target.textContent = `${hours}h${rest}`;
    };
    form.querySelectorAll('input[type="time"]').forEach((field) => field.addEventListener('input', render));
    render();
  })();
</script>
