<h1>Announcements</h1>

<% if (forbidden) { %>
  <div class="alert alert-danger">Your role does not have permission to manage announcements.</div>
<% } else { %>

<% if (error) { %><div class="alert alert-danger"><%= error %></div><% } %>

<div class="card" style="display:flex;justify-content:space-between;align-items:center">
  <p style="margin:0;color:var(--muted);font-size:12px">Live on every tenant page (banner) while active. "Run Trial-Ending Check" sends a real in-app notification to admins of any firm whose trial ends within the notice window.</p>
  <form method="post" action="/ops/messaging/trial-ending-check"><button class="btn" type="submit">Run Trial-Ending Check</button></form>
</div>

<div class="card">
  <table>
    <thead><tr><th>Title</th><th>Severity</th><th>Window</th><th>Status</th><th></th></tr></thead>
    <tbody>
      <% for (const a of announcements) { %>
      <% const now = new Date(), starts = new Date(a.starts_at), ends = new Date(a.ends_at); %>
      <% const state = !a.is_active ? 'canceled' : (now >= starts && now <= ends ? 'active' : (now < starts ? 'scheduled' : 'expired')); %>
      <tr>
        <td><%= a.title %><br><span style="color:var(--muted);font-size:12px"><%= a.message %></span></td>
        <td><span class="badge <%= { info: 'badge-ok', warning: 'badge-warn', critical: 'badge-danger' }[a.severity] %>"><%= a.severity %></span></td>
        <td><%= starts.toLocaleString() %> – <%= ends.toLocaleString() %></td>
        <td><span class="badge <%= { active: 'badge-danger', scheduled: 'badge-warn', canceled: 'badge-ok', expired: 'badge-ok' }[state] %>"><%= state %></span></td>
        <td><% if (state === 'active' || state === 'scheduled') { %><form method="post" action="/ops/announcements/<%= a.id %>/cancel"><button class="link-btn" type="submit">Cancel</button></form><% } %></td>
      </tr>
      <% } %>
      <% if (!announcements.length) { %><tr><td colspan="5" style="color:var(--muted)">No announcements published.</td></tr><% } %>
    </tbody>
  </table>

  <form method="post" action="/ops/announcements" style="max-width:480px;margin-top:16px">
    <label>Title</label>
    <input type="text" name="title" required>
    <label>Message</label>
    <textarea name="message" rows="2" required></textarea>
    <label>Severity</label>
    <select name="severity"><option value="info">Info</option><option value="warning">Warning</option><option value="critical">Critical</option></select>
    <div style="display:flex;gap:12px">
      <div style="flex:1"><label>Starts</label><input type="datetime-local" name="startsAt" required></div>
      <div style="flex:1"><label>Ends</label><input type="datetime-local" name="endsAt" required></div>
    </div>
    <button class="btn" type="submit" style="width:100%;margin-top:16px">Publish Announcement</button>
  </form>
</div>

<% } %>
