<% layout('layouts/main') %>
<% const staffBase = typeof staffBaseUrl !== 'undefined' ? staffBaseUrl : '/agenda'; %>
<% const agendaBase = typeof agendaBaseUrl !== 'undefined' ? agendaBaseUrl : staffBase; %>
<% const agendaDetailBase = typeof agendaDetailBaseUrl !== 'undefined' ? agendaDetailBaseUrl : `${staffBase}/interventions`; %>
<% const adminAgenda = Boolean(typeof isAdminAgenda !== 'undefined' && isAdminAgenda); %>
<div class="app-shell">
  <%- partial(adminAgenda ? 'partials/admin-nav' : 'partials/staff-nav') %>
  <section class="content">
    <div class="page-head">
      <div><p class="eyebrow"><%= adminAgenda ? 'Administration terrain' : 'Équipe' %></p><h1><%= adminAgenda ? 'Agenda terrain' : 'Mon agenda' %></h1></div>
    </div>
    <section class="panel guided-dashboard staff-guided-dashboard">
      <div class="compact-heading">
        <p class="eyebrow"><%= adminAgenda ? 'Vue équipe' : 'Mode terrain' %></p>
        <h2><%= adminAgenda ? 'Pilotage du planning terrain' : 'Votre journée en trois gestes' %></h2>
        <p><%= adminAgenda ? 'Filtrez par employé, ouvrez les interventions et gardez une vue claire du mois sans quitter l’administration.' : 'Ouvrez l’intervention, contactez le client si besoin, puis ajoutez votre rapport à la fin du travail.' %></p>
      </div>
      <div class="guided-action-grid">
        <a href="<%= agendaBase %>"><strong>1. Voir le planning du jour</strong><span>Les interventions du jour sont affichées en premier.</span></a>
        <a href="<%= adminAgenda ? adminBaseUrl + '/suite#pointage' : staffBase + '/heures' %>"><strong>2. Suivre les heures</strong><span>Les saisies terrain restent centralisées pour validation.</span></a>
        <a href="<%= adminAgenda ? adminBaseUrl + '/rh#demandes-rh' : staffBase + '/absences' %>"><strong>3. Absences et certificats</strong><span>Vacances, maladie ou autre demande transmise à l’entreprise.</span></a>
      </div>
    </section>
    <form class="panel search-panel form-grid two" method="get">
      <% if (currentUser && (currentUser.role === 'admin' || currentUser.is_responsible)) { %>
        <label>Agenda<select name="staff_id">
          <option value="0" <%= Number(selectedStaffId || 0) === 0 ? 'selected' : '' %>>Toute l’équipe</option>
          <% staff.forEach(member => { %><option value="<%= member.id %>" <%= Number(selectedStaffId || 0) === member.id ? 'selected' : '' %>><%= member.first_name %> <%= member.last_name %></option><% }) %>
        </select></label>
      <% } %>
      <label>Mois<input type="month" name="month" value="<%= month %>"></label>
      <label>Statut<select name="status">
        <option value="">Tous</option>
        <% ['planifiee','confirmee','en_cours','terminee','annulee','reportee'].forEach(s => { %><option value="<%= s %>" <%= filters.status===s?'selected':'' %>><%= ui.label(s) %></option><% }) %>
      </select></label>
      <button>Afficher</button>
    </form>

    <% function interventionCard(i) { %>
      <article class="list-card">
        <div class="list-card-head">
          <div><strong><%= i.service_type %></strong><span><%= i.first_name %> <%= i.last_name %></span></div>
          <span class="badge"><%= ui.label(i.status) %></span>
        </div>
        <div class="detail-grid compact">
          <div class="detail-item"><span>Date</span><strong><%= ui.date(i.starts_at, true) %></strong></div>
          <div class="detail-item"><span>Adresse</span><strong><%= i.address || [i.profile_address, i.postal_code, i.city].filter(Boolean).join(', ') || 'Non renseignée' %></strong></div>
          <div class="detail-item"><span>Tarif</span><strong><%= ui.money(i.hourly_rate) %> / h</strong></div>
          <% if (i.status === 'terminee') { %><div class="detail-item"><span>Réalisé</span><strong><%= Math.floor((i.actual_duration_minutes || 0) / 60) %>h<%= String((i.actual_duration_minutes || 0) % 60).padStart(2, '0') %></strong></div><% } %>
        </div>
        <div class="actions inline-actions">
          <a class="button" href="<%= agendaDetailBase %>/<%= i.id %>">Ouvrir</a>
          <% if (i.phone) { %><a class="button secondary" href="tel:<%= ui.phoneHref(i.phone) %>">Appeler</a><a class="button secondary" target="_blank" rel="noopener" href="<%= ui.whatsappHref(i.phone, `Bonjour, je vous contacte au sujet de votre intervention ${currentCompany ? currentCompany.name : 'SaaS DEMO'}.`) %>">WhatsApp</a><% } %>
        </div>
      </article>
    <% } %>

    <section class="today-panel">
      <div class="section-heading compact-heading">
        <p class="eyebrow">Aujourd’hui</p>
        <h2>Planning du jour</h2>
        <p>Les interventions à réaliser aujourd’hui, accessibles en un clic.</p>
      </div>
      <div class="today-list">
        <% todayItems.forEach(i => { %>
          <article class="today-card">
            <div class="today-time"><strong><%= i.starts_at ? new Date(i.starts_at).toLocaleTimeString('fr-CH', { hour: '2-digit', minute: '2-digit' }) : '--:--' %></strong><span><%= ui.label(i.status) %></span></div>
            <div class="today-main">
              <strong><%= i.first_name %> <%= i.last_name %></strong>
              <span><%= i.service_type %></span>
              <small><%= i.address || [i.profile_address, i.postal_code, i.city].filter(Boolean).join(', ') || 'Adresse non renseignée' %></small>
            </div>
            <div class="today-actions">
              <a class="button small" href="<%= agendaDetailBase %>/<%= i.id %>">Ouvrir</a>
              <% if (i.phone) { %><a class="button secondary small" href="tel:<%= ui.phoneHref(i.phone) %>">Appeler</a><% } %>
            </div>
          </article>
        <% }) %>
        <% if (!todayItems.length) { %>
          <div class="empty-state compact-empty"><strong>Aucune intervention aujourd’hui</strong><span>Le planning complet reste disponible dans l’agenda mensuel.</span></div>
        <% } %>
      </div>
    </section>

    <section class="calendar-panel">
      <div class="section-heading compact-heading">
        <h2>Planning du mois</h2>
        <p>Ouvrez une intervention directement depuis le calendrier.</p>
      </div>
      <div class="calendar-scroll">
        <div class="calendar-grid calendar-weekdays">
          <% ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'].forEach(day => { %><span><%= day %></span><% }) %>
        </div>
        <div class="calendar-grid">
          <% calendarDays.forEach(day => { %>
            <div class="calendar-day <%= day.inMonth ? '' : 'muted-day' %> <%= day.isToday ? 'today' : '' %>">
              <div class="calendar-date"><span><%= day.day %></span></div>
              <div class="calendar-events">
                <% day.items.forEach(i => { %>
                  <a class="calendar-event status-<%= i.status %>" href="<%= agendaDetailBase %>/<%= i.id %>">
                    <span><%= i.start_time %></span>
                    <strong><%= i.first_name %> <%= i.last_name %></strong>
                    <small><%= i.service_type %></small>
                    <% if (currentUser && (currentUser.role === 'admin' || currentUser.is_responsible) && Number(selectedStaffId || 0) === 0 && (i.team_names || i.assigned_first_name)) { %><em><%= i.team_names || i.assigned_first_name %></em><% } %>
                  </a>
                <% }) %>
              </div>
            </div>
          <% }) %>
        </div>
      </div>
      <% if (!interventions.length) { %><p class="panel">Aucune intervention à venir pour ce mois.</p><% } %>
    </section>

    <section class="mobile-agenda">
      <div class="section-heading compact-heading">
        <h2>Agenda mobile</h2>
        <p>Vue par jour, optimisée pour le terrain.</p>
      </div>
      <% const daysWithItems = calendarDays.filter(day => day.inMonth && day.items.length); %>
      <% daysWithItems.forEach(day => { %>
        <article class="mobile-day">
          <header><span><%= day.day %></span><strong><%= new Date(day.key + 'T00:00:00').toLocaleDateString('fr-CH', { weekday: 'long', day: 'numeric', month: 'long' }) %></strong></header>
          <div>
            <% day.items.forEach(i => { %>
              <a class="mobile-event status-<%= i.status %>" href="<%= agendaDetailBase %>/<%= i.id %>">
                <span><%= i.start_time %></span>
                <strong><%= i.first_name %> <%= i.last_name %></strong>
                <small><%= i.service_type %></small>
                <% if (i.team_names) { %><em><%= i.team_names %></em><% } %>
              </a>
            <% }) %>
          </div>
        </article>
      <% }) %>
      <% if (!daysWithItems.length) { %><p class="panel">Aucune intervention à venir pour ce mois.</p><% } %>
    </section>

    <div class="panel">
      <h2>Résumé mensuel</h2>
      <p class="muted">Total effectué et total dû du 1 au dernier jour du mois sélectionné.</p>
      <div class="mobile-list compact-list">
        <% summary.forEach(row => { %>
          <article class="line-card">
            <strong><%= row.first_name %> <%= row.last_name %></strong>
            <span><%= Math.floor(row.minutes / 60) %>h<%= String(row.minutes % 60).padStart(2, '0') %> effectuées</span>
            <b><%= ui.money(row.amount) %></b>
          </article>
        <% }) %>
        <% if (!summary.length) { %><p class="muted">Aucune heure terminée pour ce mois.</p><% } %>
      </div>
    </div>

    <details class="ops-drawer completed-drawer" <%= filters.status === 'terminee' || completedPagination.page > 1 ? 'open' : '' %>>
      <summary><span>Interventions terminées</span><small><%= completedPagination.total %> terminée(s), 3 par page</small></summary>
      <div class="mobile-list completed-list">
        <% completed.forEach(i => { %>
          <% interventionCard(i) %>
        <% }) %>
        <% if (!completed.length) { %><p class="muted">Aucune intervention terminée sur ce mois.</p><% } %>
      </div>
      <% if (completedPagination.pages > 1) { %>
        <nav class="pagination" aria-label="Pagination interventions terminées">
          <% for (let page = 1; page <= completedPagination.pages; page += 1) { %>
            <a class="<%= page === completedPagination.page ? 'active' : '' %>" href="<%= agendaBase %>?staff_id=<%= selectedStaffId || 0 %>&month=<%= month %>&status=<%= filters.status || '' %>&completed_page=<%= page %>"><%= page %></a>
          <% } %>
        </nav>
      <% } %>
    </details>
  </section>
</div>
