{% extends "base.html" %}

{% block content %}
{# --- UI wording polish (SAFE): keep backend variables, only change what we DISPLAY --- #}
{% set ui_headline_map = {
  "Stable": "All clear.",
  "Attention needed": "A quick look is recommended.",
  "Review suggested": "A small review may help."
} %}

{% set ui_subline_map = {
  "Stable": "No meaningful changes were detected in the latest reports.",
  "Attention needed": "A notable change appeared recently. It may be worth reviewing.",
  "Review suggested": "A few patterns stood out. Nothing urgent, but worth checking when convenient."
} %}

{% set ui_headline = ui_headline_map.get(status_label, status_label) %}
{% set ui_subline = ui_subline_map.get(status_label, status_reason) %}

{# Sources detected: keep it dead simple to avoid editor “red errors” #}
{% set sources_expected = 2 %}
{% set sources_found = 0 %}
{% if scan_meta and scan_meta.daily_dir %}{% set sources_found = sources_found + 1 %}{% endif %}
{% if scan_meta and scan_meta.weekly_dir %}{% set sources_found = sources_found + 1 %}{% endif %}

{# Latest IDs (avoid list indexing to keep editor calm) #}
{% set ns = namespace(latest_day="", latest_week="") %}
{% if available_days %}
  {% for d in available_days %}
    {% if loop.first %}{% set ns.latest_day = d %}{% endif %}
  {% endfor %}
{% endif %}
{% if available_weeks %}
  {% for w in available_weeks %}
    {% if loop.first %}{% set ns.latest_week = w %}{% endif %}
  {% endfor %}
{% endif %}

<style>
  :root{
    --bg:#f6f7f9;
    --card:#ffffff;
    --border:#e6e8ee;
    --text:#101828;
    --muted:#667085;
    --shadow: 0 1px 2px rgba(0,0,0,.05);
    --shadow-soft: 0 20px 60px rgba(16,24,40,.08);
    --radius: 16px;
    --accent:#2e7dd7;
  }

  .overview-wrap{
    color:var(--text);
    font-family: system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
    font-size:15px;
    line-height:1.65;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
  }

  .overview-shell{
    width: min(1180px, 100%);
    margin: 0;
    display:block;
    border-radius: 22px;
    overflow:hidden;
    box-shadow: var(--shadow-soft);
    border:1px solid var(--border);
    background: var(--card);
  }

  .overview-main{
    padding: 22px 24px 26px;
    background: linear-gradient(180deg, #ffffff, #fbfcfe);
  }

  .topline{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap: 12px;
    flex-wrap:wrap;
    margin-bottom: 16px;
  }

  .headline{
    margin:0;
    font-size: 34px;
    line-height: 1.12;
    letter-spacing: -0.03em;
    font-weight: 900;
  }

  .lead{
    margin: 10px 0 0 0;
    color: var(--muted);
    max-width: 70ch;
    font-size: 15px;
    line-height: 1.55;
  }

  .tag{
    font-size:12px;
    color:#475467;
    border:1px solid rgba(16,24,40,.10);
    background:#fff;
    padding:6px 10px;
    border-radius:999px;
    white-space:nowrap;
  }

  .tag-stack{
    display:flex;
    flex-direction:column;
    gap:8px;
    align-items:flex-end;
  }
  @media (max-width: 980px){
    .tag-stack{ align-items:flex-start; }
  }

  .grid{
    display:grid;
    grid-template-columns: minmax(360px, 1fr) minmax(360px, 1fr);
    align-items:start;
    gap: 14px;
    margin-top: 10px;
  }
  @media (max-width: 980px){
    .grid{ grid-template-columns: 1fr; }
  }

  .stack{
    display:flex;
    flex-direction:column;
    gap:14px;
  }

  .card{
    background:var(--card);
    border:1px solid rgba(16,24,40,.08);
    border-radius: var(--radius);
    padding:16px 16px 14px;
    box-shadow: var(--shadow);
  }

  .card-title{
    font-size: 12px;
    font-weight: 800;
    margin:0 0 12px;
    color:#475467;
    letter-spacing:0.08em;
    text-transform:uppercase;
  }

  .status-row{
    display:flex;
    flex-direction:column;
    gap:8px;
  }

  .status-label{
    display:inline-flex;
    align-items:center;
    gap:8px;
    font-size:16px;
    font-weight:850;
    letter-spacing:-0.01em;
    color:#111827;
  }

  .status-reason{
    font-size:13px;
    color:var(--muted);
    line-height:1.55;
  }

  .narrative{
    padding:18px 18px 16px;
  }

  .row{
    display:flex;
    align-items:center;
    justify-content:flex-start;
    gap:10px;
    flex-wrap:wrap;
    margin: 2px 0 12px;
  }

  .row .hint{
    color:var(--muted);
    font-size:12px;
  }

  select{
    appearance:none;
    -webkit-appearance:none;
    -moz-appearance:none;
    font-size:13px;
    padding:8px 34px 8px 10px;
    border:1px solid rgba(16,24,40,.12);
    border-radius:12px;
    background: #fff;
    color: var(--text);
    cursor:pointer;
    outline:none;
  }

  .select-wrap{
    position:relative;
    display:inline-block;
  }
  .select-wrap:after{
    content:"▾";
    position:absolute;
    right:12px;
    top:50%;
    transform:translateY(-52%);
    font-size:12px;
    color:var(--muted);
    pointer-events:none;
  }

  ul{ margin: 8px 0 0 0; padding:0; list-style:none; }
  li{
    margin: 10px 0;
    padding-left: 14px;
    position: relative;
    line-height:1.65;
  }
  li:before{
    content:"";
    width:5px;
    height:5px;
    border-radius:999px;
    background:#cbd5e1;
    position:absolute;
    left:0;
    top: 0.72em;
  }

  .actions li:before{ background:#d0d5dd; }

  .quiet-note{
    margin-top: 14px;
    color: var(--muted);
    font-size: 12px;
    line-height:1.5;
    max-width: 80ch;
  }

  .empty{
    margin-top: 8px;
    font-size: 13px;
    color: var(--muted);
    line-height: 1.55;
  }

  .empty strong{
    color:#475467;
    font-weight:700;
  }

  .empty-state{
    margin-top: 10px;
    padding: 18px 18px 16px;
    border: 1px solid rgba(16,24,40,.08);
    border-radius: var(--radius);
    background: linear-gradient(180deg, #ffffff, #fbfcfe);
    box-shadow: var(--shadow);
  }

  .empty-state h3{
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 850;
    letter-spacing: -0.01em;
    color: #111827;
  }

  .empty-state p{
    margin: 0;
    font-size: 13px;
    color: var(--muted);
    line-height: 1.55;
    max-width: 78ch;
  }

  /* ---- Snapshot card (intentional + calm) ---- */
  .snap-row{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .snap-desc{
    font-size:13px;
    color: var(--muted);
    line-height:1.5;
    max-width: 62ch;
    margin: 0;
  }

  .snap-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:10px 14px;
    border-radius: 12px;
    border:1px solid rgba(16,24,40,.10);
    background: var(--accent);
    color:#fff;
    font-weight:850;
    font-size:13px;
    cursor:pointer;
    min-width: 170px;
  }
  .snap-btn[disabled]{ opacity:.6; cursor:not-allowed; }

  .snap-status{
    margin-top: 10px;
    font-size:12px;
    color:#475467;
    background:#f2f4f7;
    border:1px solid rgba(16,24,40,.06);
    padding:8px 10px;
    border-radius: 12px;
    display:none;
  }

  .snap-meta{
    margin-top: 4px;
    color:#667085;
  }

  .snap-link{
    margin-left: 8px;
    font-weight: 850;
    text-decoration: none;
    color: #2e7dd7;
  }
  .snap-link:hover{ text-decoration: underline; }
</style>

<div class="overview-wrap">
  <div class="overview-shell">
    <main class="overview-main">

      <div class="topline">
        <div>
          <h1 class="headline">{{ ui_headline }}</h1>
          <p class="lead">
            {{ ui_subline
               | replace("warning-level", "notable")
               | replace("Warning-level", "Notable") }}
          </p>
        </div>

        <div class="tag-stack">
          <div class="tag">Read-only • Local</div>
          <div class="tag">Sources detected: {{ sources_found }}/{{ sources_expected }}</div>
          <div class="tag">
            Last snapshot:
            {% if scan_meta and scan_meta.last_snapshot_label %}
              {{ scan_meta.last_snapshot_label }}
            {% else %}
              Not found
            {% endif %}
          </div>
        </div>
      </div>

      {% if has_reports %}

      <div class="grid">

        <!-- LEFT: Snapshot + Status + Actions -->
        <div class="stack">

          <div class="card">
            <div class="card-title">Snapshot</div>

            <div class="snap-row">
              <p class="snap-desc">
                Generates a new snapshot from local reports and saves it to Scan History.
                No system changes. No background monitoring.
              </p>

              <button class="snap-btn" id="snapshotBtn" type="button">
                Generate snapshot
              </button>
            </div>

            <div class="snap-status"
                 id="snapshotStatusBox"
                 data-latest-day="{{ ns.latest_day }}"
                 data-latest-week="{{ ns.latest_week }}">
              <div>
                <span id="snapshotStatusText"></span>
                <a id="snapshotViewLink" class="snap-link" href="#" style="display:none;">View latest snapshot</a>
              </div>
              <div class="snap-meta" id="snapshotSavedMeta" style="display:none;"></div>
            </div>

            <div class="quiet-note">
              Snapshots create calm summaries. If nothing meaningful happened, the result may be quiet — that’s valid.
            </div>
          </div>

          <div class="card">
            <div class="card-title">System Status</div>
            <div class="status-row">
              <div class="status-label">{{ ui_headline }}</div>
              <div class="status-reason">
                {{ status_reason
                   | replace("warning-level", "notable")
                   | replace("Warning-level", "Notable") }}
              </div>
            </div>
          </div>

          {% set actions_kept = namespace(lines=[]) %}
          {% if suggested_actions %}
            {% for a in suggested_actions %}
              {% set s = (a|string).strip() %}
              {% if s and s|lower != "none" and s|lower != "- none" %}
                {% set _ = actions_kept.lines.append(a) %}
              {% endif %}
            {% endfor %}
          {% endif %}

          {% if actions_kept.lines|length > 0 %}
          <div class="card">
            <div class="card-title">Suggested Actions</div>
            <ul class="actions">
              {% for action in actions_kept.lines %}
              <li>{{ action }}</li>
              {% endfor %}
            </ul>
          </div>
          {% else %}
          <div class="card">
            <div class="card-title">Suggested Actions</div>
            <div class="empty"><strong>No action is needed right now.</strong> If something earns attention, it will appear here.</div>
          </div>
          {% endif %}

        </div>

        <!-- RIGHT: Narratives -->
        <div class="stack">

          <div class="card narrative">
            <div class="card-title">Today’s Story</div>

            {% if available_days %}
            <div class="row">
              <div class="hint">Viewing</div>
              <div class="select-wrap">
                <select id="daySelect">
                  {% for d in available_days %}
                  <option value="{{ d }}" {% if d == selected_day %}selected{% endif %}>{{ d }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            {% endif %}

            {% set kept = namespace(lines=[]) %}
            {% for line in todays_story %}
              {% set s = (line|string).strip() %}
              {% if s and s|lower != "none" and s|lower != "- none" %}
                {% set softened = s
                  | replace("(warning)", "")
                  | replace(" (warning)", "")
                  | replace("includes warning", "includes a notable change")
                  | replace("Includes warning", "Includes a notable change")
                  | replace("No urgent issues", "No significant issues")
                  | replace("no urgent issues", "no significant issues")
                  | replace("may need review", "may be worth a look")
                  | replace("May need review", "May be worth a look")
                %}
                {% set _ = kept.lines.append(softened) %}
              {% endif %}
            {% endfor %}

            {% if kept.lines|length == 0 %}
              <div class="empty"><strong>Nothing meaningful stood out today.</strong> That’s a normal outcome.</div>
            {% else %}
              <ul>
                {% for line in kept.lines %}
                <li>{{ line }}</li>
                {% endfor %}
              </ul>
            {% endif %}
          </div>

          <div class="card narrative">
            <div class="card-title">This Week’s Story</div>

            {% if available_weeks %}
            <div class="row">
              <div class="hint">Viewing</div>
              <div class="select-wrap">
                <select id="weekSelect">
                  {% for w in available_weeks %}
                  <option value="{{ w }}" {% if w == selected_week %}selected{% endif %}>{{ w }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            {% endif %}

            {% set wkept = namespace(lines=[]) %}
            {% for line in weeks_story %}
              {% set s = (line|string).strip() %}
              {% if s and s|lower != "none" and s|lower != "- none" %}
                {% set softened = s
                  | replace("(warning)", "")
                  | replace(" (warning)", "")
                  | replace("includes warning", "includes a notable change")
                  | replace("Includes warning", "Includes a notable change")
                  | replace("No urgent issues", "No significant issues")
                  | replace("no urgent issues", "no significant issues")
                  | replace("may need review", "may be worth a look")
                  | replace("May need review", "May be worth a look")
                %}
                {% set _ = wkept.lines.append(softened) %}
              {% endif %}
            {% endfor %}

            {% if wkept.lines|length == 0 %}
              <div class="empty"><strong>No notable patterns were detected this week.</strong> System behavior appeared steady.</div>
            {% else %}
              <ul>
                {% for line in wkept.lines %}
                <li>{{ line }}</li>
                {% endfor %}
              </ul>
            {% endif %}
          </div>

          <div class="quiet-note">Silence is valid. Actions appear only when earned.</div>

        </div>
      </div>

      {% else %}

      <div class="empty-state">
        <h3>No snapshots yet</h3>
        <p>NarrativeOps hasn’t found any system snapshots yet. Run a snapshot to generate calm daily and weekly summaries. Once a snapshot exists, this page will fill in automatically.</p>
      </div>

      {% endif %}

    </main>
  </div>
</div>

<script>
(function () {
  const day = document.getElementById("daySelect");
  const week = document.getElementById("weekSelect");

  function reload(d, w) {
    const p = new URLSearchParams(window.location.search);
    if (d) p.set("day", d);
    if (w) p.set("week", w);
    window.location.search = p.toString();
  }

  if (day) day.addEventListener("change", () => reload(day.value, week ? week.value : null));
  if (week) week.addEventListener("change", () => reload(day ? day.value : null, week.value));
})();
</script>

<script>
(function () {
  const btn = document.getElementById("snapshotBtn");
  const box = document.getElementById("snapshotStatusBox");
  const text = document.getElementById("snapshotStatusText");
  const link = document.getElementById("snapshotViewLink");
  const meta = document.getElementById("snapshotSavedMeta");

  function getLatestDay(){ return box ? (box.getAttribute("data-latest-day") || "") : ""; }
  function getLatestWeek(){ return box ? (box.getAttribute("data-latest-week") || "") : ""; }

  function setViewLink() {
    if (!link) return;

    const latestDay = getLatestDay();
    const latestWeek = getLatestWeek();

    if (latestDay) {
      link.href = "/?day=" + encodeURIComponent(latestDay);
      link.style.display = "inline";
      return;
    }
    if (latestWeek) {
      link.href = "/?week=" + encodeURIComponent(latestWeek);
      link.style.display = "inline";
      return;
    }
    link.style.display = "none";
  }

  function setSavedMeta() {
    if (!meta) return;

    const latestDay = getLatestDay();
    const latestWeek = getLatestWeek();

    const parts = [];
    if (latestDay) parts.push("Daily (" + latestDay + ")");
    if (latestWeek) parts.push("Weekly (" + latestWeek + ")");

    if (parts.length === 0) {
      meta.style.display = "none";
      meta.textContent = "";
      return;
    }

    meta.style.display = "block";
    meta.textContent = "Saved: " + parts.join(" + ");
  }

  let polling = false;

  function show(msg) {
    if (!box || !text) return;
    box.style.display = "block";
    text.textContent = msg || "";
    if (link) link.style.display = "none";
    if (meta) { meta.style.display = "none"; meta.textContent = ""; }
  }

  function showSuccess(msg) {
    if (!box || !text) return;
    box.style.display = "block";
    text.textContent = msg || "Snapshot saved.";
    setViewLink();
    setSavedMeta();
  }

  async function pollStatus() {
    if (polling) return;
    polling = true;

    try {
      while (true) {
        const res = await fetch("/snapshot/status", { cache: "no-store" });
        if (!res.ok) break;

        const s = await res.json();
        const status = (s && s.status) ? s.status : "idle";
        const message = (s && s.message) ? s.message : "";

        if (status === "idle") {
          if (box) box.style.display = "none";
          break;
        }

        if (status === "running") {
          if (btn) btn.disabled = true;
          show(message || "Generating snapshot…");
          await new Promise(r => setTimeout(r, 900));
          continue;
        }

        if (btn) btn.disabled = false;

        if (status === "success") {
          showSuccess(message || "Snapshot saved.");
        } else if (status === "error") {
          show(message || "Snapshot failed.");
        }
        break;
      }
    } catch (e) {
      // fail quietly
    } finally {
      polling = false;
    }
  }

  async function runSnapshot() {
    if (!btn || btn.disabled) return;

    btn.disabled = true;
    show("Generating snapshot…");

    try {
      await fetch("/snapshot/run", { method: "POST" });
    } catch (e) {
      show("Could not start snapshot.");
      btn.disabled = false;
      return;
    }

    pollStatus();
  }

  if (btn) btn.addEventListener("click", runSnapshot);

  // On load: make link usable immediately if latest IDs exist
  setViewLink();
  pollStatus();
})();
</script>
{% endblock %}
