<%- include("partials/header", { title: "Submit Entry" , user }) %>

  <h1>Submit Entry</h1>
  <% if (!preset && nextOp && nextOp.start_at) { %>
    <div class="card" style="margin-bottom:16px;">
      <h2 style="margin:0 0 6px 0;">Next Operation Starts In</h2>

      <div style="opacity:.85; margin-bottom:8px;">
        <b>
          <%= nextOp.title %>
        </b> — <%= nextOp.topic %><br>
          Starts: <b>
            <%= fmtMelbourne(nextOp.start_at) %>
          </b>
      </div>

      <div id="nextCountdown" data-start="<%= nextOp.start_at %>" class="countdown">
        Calculating…
      </div>

      <% if (upcomingOps && upcomingOps.length> 1) { %>
        <div style="margin-top:14px; opacity:.9;">
          <b>Upcoming Operations</b>
          <ul id="upcomingList" style="margin:8px 0 0 18px;">
            <% upcomingOps.forEach((op, idx)=> { if (idx === 0) return; %>
              <li style="margin:6px 0;">
                <b>
                  <%= op.title %>
                </b> — <%= op.topic %><br>
                  Starts: <%= fmtMelbourne(op.start_at) %>
                    <span class="small" data-start="<%= op.start_at %>"></span>
              </li>
              <% }) %>
          </ul>
        </div>
        <% } %>
    </div>

    <script>
      (function () {
        function pad(n) { return String(n).padStart(2, "0"); }
        function formatDiff(ms) {
          if (ms <= 0) return " (starting now)";
          const s = Math.floor(ms / 1000);
          const d = Math.floor(s / 86400);
          const h = Math.floor((s % 86400) / 3600);
          const m = Math.floor((s % 3600) / 60);
          const sec = s % 60;
          return " (in " + (d > 0 ? d + "d " : "") + pad(h) + ":" + pad(m) + ":" + pad(sec) + ")";
        }

        // Main countdown (soonest)
        const main = document.getElementById("nextCountdown");
        if (main) {
          const startMs = Date.parse(main.dataset.start);
          function tickMain() {
            const diff = startMs - Date.now();
            if (!Number.isFinite(startMs)) { main.textContent = "Invalid start time"; return; }
            if (diff <= 0) { main.textContent = "Starting now…"; return; }

            const s = Math.floor(diff / 1000);
            const d = Math.floor(s / 86400);
            const h = Math.floor((s % 86400) / 3600);
            const m = Math.floor((s % 3600) / 60);
            const sec = s % 60;

            main.textContent = (d > 0 ? d + "d " : "") + pad(h) + ":" + pad(m) + ":" + pad(sec);
          }
          tickMain();
          setInterval(tickMain, 1000);
        }

        // Inline “(in …)” for the rest
        document.querySelectorAll("#upcomingList .small").forEach(el => {
          const startMs = Date.parse(el.dataset.start);
          function tick() {
            const diff = startMs - Date.now();
            el.textContent = formatDiff(diff);
          }
          tick();
          setInterval(tick, 1000);
        });
      })();
    </script>
    <% } %>

      <% if (error) { %>
        <p class="err">
          <%= error %>
        </p>
        <% if (nextOp && nextOp.start_at) { %>
          <div class="card" style="margin: 12px 0;">
            <h2 style="margin:0 0 6px 0;">Next Operation Starts In</h2>
            <div style="opacity:.85; margin-bottom:8px;">
              <b>
                <%= nextOp.title %>
              </b> — <%= nextOp.topic %><br>
                Starts: <b>
                  <%= fmtMelbourne(nextOp.start_at) %>
                </b>
            </div>

            <div id="nextCountdown" class="countdown" data-start="<%= nextOp.start_at %>">
              Calculating…
            </div>
          </div>

          <script>
            (function () {
              const el = document.getElementById("nextCountdown");
              if (!el) return;

              const startIso = el.getAttribute("data-start");
              const startMs = Date.parse(startIso);
              if (!Number.isFinite(startMs)) { el.textContent = "Invalid start time"; return; }

              function pad(n) { return String(n).padStart(2, "0"); }

              function tick() {
                const now = Date.now();
                let diff = startMs - now;

                if (diff <= 0) {
                  el.textContent = "Starting now…";
                  return;
                }

                const totalSeconds = Math.floor(diff / 1000);
                const days = Math.floor(totalSeconds / 86400);
                const hours = Math.floor((totalSeconds % 86400) / 3600);
                const mins = Math.floor((totalSeconds % 3600) / 60);
                const secs = totalSeconds % 60;

                el.textContent =
                  (days > 0 ? days + "d " : "") +
                  pad(hours) + ":" + pad(mins) + ":" + pad(secs);

                requestAnimationFrame(() => setTimeout(tick, 250));
              }

              tick();
              setInterval(tick, 1000);
            })();
          </script>
          <% } %>

            <% } %>
              <% if (ok) { %>
                <p style="opacity:.9;">✅ Entry submitted.</p>
                <% } %>

                  <div class="grid entry-grid">
                    <!-- LEFT: leaderboard -->
                    <div class="card">
                      <h2>Leaderboard</h2>

                      <% if (preset) { %>
                        <p style="opacity:.85; margin-top:0;">
                          <b>Active:</b>
                          <%= preset.title %><br />
                            <span style="opacity:.75;">
                              <%= preset.topic %>
                            </span>
                        </p>
                        <% } else { %>
                          <p style="opacity:.85; margin-top:0;"><b>No active competition</b></p>
                          <% } %>

                            <p><b>Total entries:</b>
                              <%= totalEntries %>
                            </p>

                            <% if ((leaderboard || []).length) { %>
                              <ol style="margin:0; padding-left:18px;">
                                <% leaderboard.forEach(x=> { %>
                                  <li>
                                    <%= x.eligible ? "🟢" : "🔴" %>
                                      <%= x.name %> — <b>
                                          <%= x.count %>
                                        </b>
                                  </li>
                                  <% }) %>
                              </ol>
                              <% } else { %>
                                <p style="opacity:.7;">No entries yet.</p>
                                <% } %>

                                  <p style="opacity:.7; margin-bottom:0;">Updates when you refresh.
                                  </p>
                    </div>

                    <!-- RIGHT: form -->
                    <div>
                      <% if (preset) { %>
                        <p><b>Submitting for:</b>
                          <%= preset.title %> — <%= preset.topic %>
                        </p>
                        <% } %>

                          <form method="post" action="/entry" class="card">
                            <input type="hidden" name="preset_id" value="<%= preset ? preset.id : '' %>">
                            <label>Officer Name</label>

                            <div class="combo" id="officerCombo">
                              <input type="text" name="officer_name" id="officerInput" class="combo-input"
                                placeholder="Start typing a name..." autocomplete="off" required />
                              <div class="combo-pop" id="officerPop" aria-hidden="true"></div>
                            </div>

                            <small class="hint">Select from the list or type a name manually.</small>

                            <label>Report #</label>
                            <input name="report_number" required />

                            <label>Evidence (Link to Police Record)</label>
                            <input name="evidence" />

                            <label>Suspect</label>
                            <input name="suspect" />

                            <label>Charges (if any given)</label>
                            <textarea name="charges" rows="3"></textarea>

                            <button type="submit" <%=preset ? "" : "disabled" %>>
                              Submit
                            </button>

                            <% if (!preset) { %>
                              <p class="hint" style="margin-top:10px;">No operation is running —
                                submissions are disabled.</p>
                              <% } %>

                          </form>
                    </div>
                  </div>

                  <script>
                    (function () {
                      const officers = <%- JSON.stringify(officers || []) %>;

                      const wrap = document.getElementById("officerCombo");
                      const input = document.getElementById("officerInput");
                      const pop = document.getElementById("officerPop");

                      function escapeHtml(s) {
                        return String(s)
                          .replaceAll("&", "&amp;")
                          .replaceAll("<", "&lt;")
                          .replaceAll(">", "&gt;")
                          .replaceAll('"', "&quot;")
                          .replaceAll("'", "&#039;");
                      }

                      function render(list) {
                        if (!list.length) {
                          pop.innerHTML = `<div class="combo-empty">No matches. You can type manually.</div>`;
                          return;
                        }
                        pop.innerHTML = list.slice(0, 12).map(name => (
                          `<button type="button" class="combo-item" data-value="${escapeHtml(name)}">${escapeHtml(name)}</button>`
                        )).join("");
                      }

                      function openPop() {
                        pop.classList.add("open");
                        pop.setAttribute("aria-hidden", "false");
                      }

                      function closePop() {
                        pop.classList.remove("open");
                        pop.setAttribute("aria-hidden", "true");
                      }

                      function filterNow() {
                        const q = (input.value || "").trim().toLowerCase();
                        const filtered = q
                          ? officers.filter(n => String(n).toLowerCase().includes(q))
                          : officers;
                        render(filtered);
                        openPop();
                      }

                      render(officers);

                      input.addEventListener("focus", filterNow);
                      input.addEventListener("input", filterNow);

                      pop.addEventListener("mousedown", (e) => {
                        const btn = e.target.closest(".combo-item");
                        if (!btn) return;
                        e.preventDefault();
                        input.value = btn.getAttribute("data-value") || btn.textContent;
                        closePop();
                        input.focus();
                      });

                      document.addEventListener("mousedown", (e) => {
                        if (!wrap.contains(e.target)) closePop();
                      });

                      input.addEventListener("keydown", (e) => {
                        if (e.key === "Escape") closePop();
                      });
                    })();
                  </script>

                  <%- include("partials/footer") %>