/* War Monitor — Extracted Styles */
/* 2026-03-25 Performance Optimization */


/* === Skeleton Loading === */
.skeleton-box {
  background: linear-gradient(90deg, #0d1f0d 25%, #1a3a1a 50%, #0d1f0d 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.5s infinite;
  border-radius: 4px;
  min-height: 20px;
}
@keyframes skeleton-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
.skeleton-card {
  background: linear-gradient(90deg, #0d1f0d 25%, #1a3a1a 50%, #0d1f0d 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.5s infinite;
  border-radius: 8px;
  border: 1px solid rgba(0,255,65,0.1);
  padding: 1.5rem;
  min-height: 120px;
}
.skeleton-text {
  background: linear-gradient(90deg, #0d1f0d 25%, #1a3a1a 50%, #0d1f0d 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.5s infinite;
  border-radius: 3px;
  height: 14px;
  margin-bottom: 8px;
}
.skeleton-text.wide { width: 85%; }
.skeleton-text.medium { width: 60%; }
.skeleton-text.short { width: 40%; }
[data-lazy-section] { min-height: 200px; }



  /* Font already loaded via preload — @import removed to eliminate render-blocking */

  :root {
    --dark: #0d0d0d;
    --card: #161616;
    --border: #2a2a2a;
    --red: #e74c3c;
    --red-dim: rgba(231,76,60,0.15);
    --gold: #f39c12;
    --gold-dim: rgba(243,156,18,0.12);
    --green: #27ae60;
    --green-dim: rgba(39,174,96,0.12);
    --blue: #3498db;
    --blue-dim: rgba(52,152,219,0.12);
    --text: #e8e8e8;
    --text-muted: #888;
    --navy: #0B1F3A;
  }

  * { margin: 0; padding: 0; box-sizing: border-box; }

  body {
    font-family: 'Cairo', sans-serif;
    background: var(--dark);
    color: var(--text);
    min-height: 100vh;
    direction: rtl;
    font-variant-numeric: lining-nums;
    -webkit-font-feature-settings: "lnum" 1;
    font-feature-settings: "lnum" 1;
  }
  /* Force Latin (Western Arabic) digits everywhere */
  * { unicode-bidi: plaintext; }
  .ind-value, .ukv, .stat-num, [id*="kpi"], [id*="ind-"] {
    font-variant-numeric: lining-nums tabular-nums;
    direction: ltr;
    unicode-bidi: embed;
    text-align: center;
  }

  /* TOP BAR */
  .topbar {
    background: #0a0a0a;
    border-bottom: 2px solid var(--red);
    padding: 0;
    position: sticky;
    top: 0;
    z-index: 100;
  }

  /* Basira brand strip */
  .mizan-strip {
    background: linear-gradient(135deg, #0B1F3A 0%, #0d2545 100%);
    border-bottom: 1px solid rgba(184,136,42,0.3);
    padding: 5px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .ms-brand {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .ms-logo {
    font-size: 16px;
    font-weight: 900;
    color: #B8882A;
    letter-spacing: 0.5px;
  }
  .ms-sep {
    width: 1px; height: 16px;
    background: rgba(184,136,42,0.3);
  }
  .ms-tagline {
    font-size: 10px;
    color: rgba(255,255,255,0.45);
  }
  .ms-powered {
    font-size: 9px;
    color: rgba(184,136,42,0.6);
    direction: ltr;
  }

  .topbar-inner {
    background: #0a0a0a;
    padding: 8px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .tb-left { display: flex; align-items: center; gap: 12px; }
  .tb-logo { font-size: 16px; font-weight: 900; color: var(--red); }
  .tb-badge {
    background: var(--red);
    color: #fff;
    font-size: 9px;
    font-weight: 800;
    padding: 3px 8px;
    border-radius: 4px;
    letter-spacing: 1px;
    animation: blink 1.5s infinite;
  }

  @keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.5} }
  @keyframes livePulse { 0%,100%{box-shadow:0 0 0 0 rgba(39,174,96,0.4)} 50%{box-shadow:0 0 0 6px rgba(39,174,96,0)} }

  .tb-clock { font-size: 13px; color: var(--text-muted); direction: ltr; font-variant-numeric: tabular-nums; }
  .tb-refresh { background: var(--border); border: none; color: var(--text-muted); padding: 5px 12px; border-radius: 6px; cursor: pointer; font-family: 'Cairo', sans-serif; font-size: 12px; }
  .tb-refresh:hover { background: var(--red); color: #fff; }

  /* Visitors badge */
  .visitors-badge {
    display: flex; align-items: center; gap: 6px;
    background: rgba(39,174,96,0.12);
    border: 1px solid rgba(39,174,96,0.3);
    border-radius: 20px;
    padding: 3px 10px;
    font-size: 11px;
    color: var(--green);
    direction: ltr;
    cursor: pointer;
    transition: all 0.2s;
  }
  .visitors-badge:hover { background: rgba(39,174,96,0.2); }
  .visitors-dot {
    width: 6px; height: 6px;
    background: var(--green);
    border-radius: 50%;
    animation: pulse-green 1.5s infinite;
  }
  @keyframes pulse-green {
    0%,100% { opacity:1; transform:scale(1); }
    50% { opacity:0.5; transform:scale(1.4); }
  }
  .visitors-count { font-weight: 800; font-size: 13px; }

  /* Live refresh bar */
  .refresh-bar-wrap {
    position: fixed;
    top: 4px; left: 0; right: 0;
    height: 3px;
    z-index: 9996;
    background: rgba(231,76,60,0.1);
  }
  .refresh-bar {
    height: 100%;
    background: linear-gradient(90deg, var(--red), #f39c12);
    width: 100%;
    transform-origin: left;
    transition: transform 0.5s linear;
  }
  /* ══ SKELETON SCREENS — Pre-embedded (no FOUC) ════════════════════════ */
  .skel-pulse { animation: skelPulse 1.2s ease-in-out infinite; color: rgba(255,255,255,0.18); font-size: 8px; letter-spacing: 2px; }
  .skel-bar { display:block; background:#2a2a2a; border-radius:4px; animation: skelPulse 1.2s ease-in-out infinite; }
  @keyframes skelPulse { 0%,100%{opacity:0.3} 50%{opacity:0.85} }
  .content-fade-in { animation: fadeIn 0.4s ease-out; }
  @keyframes fadeIn { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:translateY(0)} }

  /* ══ DB FETCH PROGRESS BAR — visible before JS finishes loading ════════ */
  #db-fetch-progress {
    position: fixed;
    top: 0; left: 0; right: 0;
    height: 4px;
    z-index: 9999;
    background: rgba(231,76,60,0.08);
    display: block;
  }
  #db-fetch-progress-fill {
    height: 100%;
    width: 0%;
    background: linear-gradient(90deg, #e74c3c, #f39c12, #27ae60);
    transition: width 0.3s ease;
    border-radius: 0 2px 2px 0;
  }
  #db-fetch-progress.indeterminate #db-fetch-progress-fill {
    width: 100% !important;
    background: linear-gradient(90deg,#e74c3c,#f39c12,#27ae60,#e74c3c);
    background-size: 300%;
    animation: loadingBar 2s linear infinite;
  }
  #db-fetch-label {
    position: fixed;
    top: 6px; left: 50%;
    transform: translateX(-50%);
    font-family: 'Cairo', sans-serif;
    font-size: 10px;
    color: rgba(255,255,255,0.45);
    background: rgba(0,0,0,0.7);
    padding: 2px 10px;
    border-radius: 8px;
    z-index: 9998;
    pointer-events: none;
    white-space: nowrap;
    display: none;
  }
  @keyframes loadingBar { 0%{background-position:300% 0} 100%{background-position:-100% 0} }

  /* ══ LOADING OVERLAY (animated gradient — kept for backward compat) ════ */
  .loading-overlay { position:fixed;top:0;left:0;right:0;height:3px;background:linear-gradient(90deg,#e74c3c,#f39c12,#27ae60,#e74c3c);background-size:300%;animation:loadingBar 2s linear infinite;z-index:9997; }

  /* Last-updated pill */
  .last-updated-pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    background: rgba(255,255,255,0.04);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 2px 10px;
    font-size: 10px;
    color: var(--text-muted);
    direction: ltr;
  }
  .lu-dot { width: 5px; height: 5px; border-radius: 50%; background: var(--green); }
  /* Flash on data refresh */
  @keyframes data-flash {
    0% { background: rgba(231,76,60,0.08); }
    100% { background: transparent; }
  }
  .data-flash { animation: data-flash 0.6s ease-out; }


  /* MAIN */
  .main { padding: 16px 20px; max-width: 1400px; margin: 0 auto; }

  /* INDICATORS ROW */
  .indicators {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
    margin-bottom: 16px;
  }

  .indicator {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 12px 14px;
    position: relative;
    overflow: hidden;
  }

  .indicator::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 3px;
  }

  .indicator.red::before { background: var(--red); }
  .indicator.gold::before { background: var(--gold); }
  .indicator.green::before { background: var(--green); }
  .indicator.blue::before { background: var(--blue); }

  .ind-label { font-size: 10px; color: var(--text-muted); margin-bottom: 4px; }
  .ind-value { font-size: 20px; font-weight: 900; }
  .ind-value.red { color: var(--red); }
  .ind-value.gold { color: var(--gold); }
  .ind-value.green { color: var(--green); }
  .ind-value.blue { color: var(--blue); }
  .ind-sub { font-size: 10px; color: var(--text-muted); margin-top: 3px; }
  .ind-change { font-size: 11px; margin-top: 4px; }
  .ind-change.up { color: #e74c3c; }
  .ind-change.down { color: #27ae60; }

  /* GRID */
  .grid-2 { display: grid; grid-template-columns: 2fr 1fr; gap: 14px; margin-bottom: 14px; }
  .grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; margin-bottom: 14px; }

  /* CARD */
  .card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 10px;
    overflow: hidden;
  }

  .card-header {
    padding: 10px 14px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: rgba(255,255,255,0.02);
  }

  .card-title { font-size: 12px; font-weight: 700; color: var(--text); }
  .card-count { font-size: 10px; color: var(--text-muted); background: var(--border); padding: 2px 8px; border-radius: 10px; }
  .card-body { padding: 12px 14px; }

  /* TIMELINE */
  .timeline { position: relative; }

  .tl-item {
    display: flex;
    gap: 12px;
    margin-bottom: 10px;
    position: relative;
  }

  .tl-dot {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    flex-shrink: 0;
    margin-top: 2px;
  }

  .tl-dot.strike      { background: rgba(231,76,60,0.2);   border: 1.5px solid var(--red);   color: var(--red); }
  .tl-dot.airstrike   { background: rgba(231,76,60,0.2);   border: 1.5px solid var(--red);   color: var(--red); }
  .tl-dot.retaliation { background: rgba(231,76,60,0.3);   border: 1.5px solid #c0392b;      color: #c0392b; }
  .tl-dot.missile     { background: rgba(192,57,43,0.2);   border: 1.5px solid #c0392b;      color: #c0392b; }
  .tl-dot.missile_attack { background: rgba(192,57,43,0.2); border: 1.5px solid #c0392b;     color: #c0392b; }
  .tl-dot.missile_drone_attack { background: rgba(192,57,43,0.2); border:1.5px solid #c0392b;color:#c0392b; }
  .tl-dot.missile_strike { background: rgba(192,57,43,0.2); border:1.5px solid #c0392b;      color:#c0392b; }
  .tl-dot.drone_attack{ background: rgba(192,57,43,0.15);  border: 1.5px solid #e67e22;      color: #e67e22; }
  .tl-dot.drone       { background: rgba(192,57,43,0.15);  border: 1.5px solid #e67e22;      color: #e67e22; }
  .tl-dot.attack      { background: rgba(231,76,60,0.15);  border: 1.5px solid var(--red);   color: var(--red); }
  .tl-dot.explosion   { background: rgba(243,156,18,0.25); border: 1.5px solid #e67e22;      color: #e67e22; }
  .tl-dot.diplomatic  { background: rgba(52,152,219,0.2);  border: 1.5px solid var(--blue);  color: var(--blue); }
  .tl-dot.political   { background: rgba(52,152,219,0.15); border: 1.5px solid var(--blue);  color: var(--blue); }
  .tl-dot.assessment  { background: rgba(52,152,219,0.1);  border: 1.5px solid #5dade2;      color: #5dade2; }
  .tl-dot.interception{ background: rgba(39,174,96,0.2);   border: 1.5px solid var(--green); color: var(--green); }
  .tl-dot.alert       { background: rgba(231,76,60,0.15);  border: 1.5px solid #e74c3c;      color: #e74c3c; }
  .tl-dot.uncertainty { background: rgba(243,156,18,0.2);  border: 1.5px solid var(--gold);  color: var(--gold); }
  .tl-dot.threat      { background: rgba(231,76,60,0.15);  border: 1.5px solid #e74c3c;      color: #e74c3c; }
  .tl-dot.military    { background: rgba(142,68,173,0.15); border: 1.5px solid #9b59b6;      color: #9b59b6; }
  .tl-dot.military_action { background:rgba(142,68,173,0.15); border:1.5px solid #9b59b6;   color:#9b59b6; }
  .tl-dot.assassination { background: rgba(142,68,173,0.2); border: 1.5px solid #8e44ad;    color: #8e44ad; }
  .tl-dot.leadership  { background: rgba(142,68,173,0.2);  border: 1.5px solid #8e44ad;     color: #8e44ad; }
  .tl-dot.maritime    { background: rgba(52,152,219,0.15); border: 1.5px solid #2980b9;      color: #2980b9; }
  .tl-dot.naval       { background: rgba(52,152,219,0.15); border: 1.5px solid #2980b9;      color: #2980b9; }
  .tl-dot.blockade    { background: rgba(52,152,219,0.2);  border: 1.5px solid #1a6fa0;      color: #1a6fa0; }
  .tl-dot.evacuation  { background: rgba(243,156,18,0.15); border: 1.5px solid var(--gold);  color: var(--gold); }
  .tl-dot.civilian_impact { background: rgba(231,76,60,0.1); border:1.5px solid #e67e22;    color:#e67e22; }
  .tl-dot.civilian_casualty{ background:rgba(231,76,60,0.1); border:1.5px solid #e67e22;    color:#e67e22; }
  .tl-dot.casualty    { background: rgba(231,76,60,0.1);   border: 1.5px solid #e67e22;      color: #e67e22; }
  .tl-dot.civilian    { background: rgba(231,76,60,0.1);   border: 1.5px solid #e67e22;      color: #e67e22; }
  .tl-dot.aviation    { background: rgba(52,152,219,0.1);  border: 1.5px solid #5dade2;      color: #5dade2; }
  .tl-dot.economic    { background: rgba(243,156,18,0.1);  border: 1.5px solid var(--gold);  color: var(--gold); }
  .tl-dot.impact      { background: rgba(231,76,60,0.1);   border: 1.5px solid #e74c3c;      color: #e74c3c; }
  .tl-dot.other       { background: rgba(136,136,136,0.15);border: 1.5px solid #888;         color: #888; }

  /* ══ MISSILE TRACKER ════════════════════════════════════════════════════ */
  .mtrack-grid {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 10px;
    padding: 12px 14px 14px;
  }
  @media(max-width:1100px){ .mtrack-grid { grid-template-columns: repeat(3,1fr); } }
  @media(max-width:600px){  .mtrack-grid { grid-template-columns: repeat(2,1fr); } }
  .mtrack-country {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.07);
    border-radius: 10px;
    padding: 12px 11px;
    transition: .2s;
    position: relative;
    overflow: hidden;
  }
  .mtrack-country::after {
    content:''; position:absolute; bottom:0; left:0; right:0; height:2px;
  }
  .mtrack-country.mtrack-uae::after   { background: linear-gradient(90deg,#e74c3c,#27ae60,#000); }
  .mtrack-country.mtrack-sa::after    { background: #27ae60; }
  .mtrack-country.mtrack-kw::after    { background: linear-gradient(90deg,#27ae60,#fff,#e74c3c); }
  .mtrack-country.mtrack-qa::after    { background: #8b1a2f; }
  .mtrack-country.mtrack-bh::after    { background: #ce1126; }
  .mtrack-country.mtrack-om::after    { background: #db161e; }
  .mtrack-country.mtrack-il::after    { background: linear-gradient(90deg,#fff,#3498db,#fff); }
  .mtrack-country.mtrack-jo::after    { background: linear-gradient(90deg,#000,#fff,#27ae60); }
  .mtrack-country:hover { border-color: rgba(231,76,60,0.4); transform: translateY(-2px); }
  .mtrack-flag { font-size: 20px; margin-bottom: 5px; }
  .mtrack-name { font-size: 12px; font-weight: 800; color: #e8e8e8; margin-bottom: 8px; }
  .mtrack-row  { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
  .mtrack-lbl  { font-size: 9px; color: #888; }
  .mtrack-val  { font-size: 13px; font-weight: 900; }
  .mtrack-sub  { font-size: 9px; color: #888; margin-top: 6px; line-height: 1.5; }
  .mtrack-rate-bar { height: 4px; background: rgba(255,255,255,0.07); border-radius: 2px; margin-top: 8px; overflow:hidden; }
  .mtrack-rate-fill { height: 100%; border-radius: 2px; background: #27ae60; transition: width 1s; }
  .mtrack-verified { display:inline-flex;align-items:center;gap:3px;font-size:8px;font-weight:700;padding:1px 7px;border-radius:8px;margin-top:6px; }
  .mv-yes { background:rgba(39,174,96,.15);color:#27ae60;border:1px solid rgba(39,174,96,.3); }
  .mv-no  { background:rgba(243,156,18,.12);color:#f39c12;border:1px solid rgba(243,156,18,.3); }
  .mtrack-divider { height:1px; background:rgba(255,255,255,0.05); margin:5px 0; }

  /* ══ STATS SECTION ══════════════════════════════════════════════════════ */
  .stats-section {
    display: grid;
    grid-template-columns: 1.6fr 1fr 1fr;
    gap: 12px;
    margin-bottom: 14px;
  }

  /* Daily Reports Download Section */
  .reports-bar {
    background: linear-gradient(135deg, #0B1F3A 0%, #0d2545 100%);
    border: 1px solid rgba(184,136,42,0.3);
    border-radius: 8px;
    padding: 12px 16px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    gap: 14px;
    flex-wrap: wrap;
  }
  .reports-bar-title {
    font-size: 13px;
    font-weight: 700;
    color: #B8882A;
    white-space: nowrap;
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .reports-bar-divider {
    width: 1px; height: 28px;
    background: rgba(184,136,42,0.25);
    flex-shrink: 0;
  }
  .reports-bar-group {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
    flex: 1;
  }
  .report-label {
    font-size: 11px;
    color: rgba(255,255,255,0.5);
    white-space: nowrap;
  }
  .report-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 5px 12px;
    border-radius: 5px;
    font-size: 11px;
    font-weight: 600;
    font-family: 'Cairo', sans-serif;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.2s;
    border: none;
  }
  .report-btn.html-btn {
    background: rgba(52,152,219,0.15);
    color: #3498db;
    border: 1px solid rgba(52,152,219,0.3);
  }
  .report-btn.html-btn:hover { background: rgba(52,152,219,0.25); }
  .report-btn.pdf-btn {
    background: rgba(231,76,60,0.15);
    color: #e74c3c;
    border: 1px solid rgba(231,76,60,0.3);
  }
  .report-btn.pdf-btn:hover { background: rgba(231,76,60,0.25); }
  .report-btn.disabled {
    opacity: 0.35;
    cursor: not-allowed;
    pointer-events: none;
  }
  .report-session-tag {
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 3px;
    font-weight: 700;
    white-space: nowrap;
  }
  .tag-morning { background: rgba(243,156,18,0.15); color: #f39c12; }
  .tag-evening { background: rgba(52,152,219,0.15); color: #3498db; }
  @media (max-width: 768px) {
    .reports-bar { flex-direction: column; align-items: flex-start; }
    .reports-bar-divider { width: 100%; height: 1px; }
  }

  /* Reports lock state */
  .reports-locked {
    display: flex; align-items: center; gap: 10px; flex-wrap: wrap; flex: 1;
  }
  .reports-lock-icon {
    font-size: 16px; opacity: 0.6;
  }
  .reports-lock-text {
    font-size: 11px; color: rgba(255,255,255,0.4);
  }
  .reports-pw-form {
    display: flex; align-items: center; gap: 6px;
  }
  .reports-pw-input {
    background: rgba(255,255,255,0.07);
    border: 1px solid rgba(184,136,42,0.3);
    border-radius: 6px;
    padding: 5px 10px;
    font-family: 'Cairo', sans-serif;
    font-size: 14px; letter-spacing: 4px;
    color: #fff; width: 90px; text-align: center;
    outline: none; transition: border-color .2s;
  }
  .reports-pw-input:focus { border-color: #B8882A; }
  .reports-pw-input.error { border-color: #e74c3c; animation: rshake .3s; }
  .reports-pw-btn {
    padding: 5px 12px;
    background: rgba(184,136,42,0.15);
    border: 1px solid rgba(184,136,42,0.35);
    border-radius: 6px;
    font-family: 'Cairo', sans-serif;
    font-size: 11px; font-weight: 700; color: #B8882A;
    cursor: pointer; transition: background .2s;
  }
  .reports-pw-btn:hover { background: rgba(184,136,42,0.28); }
  .reports-pw-err {
    font-size: 10px; color: #e74c3c;
    display: none;
  }
  @keyframes rshake {
    0%,100%{transform:translateX(0)} 25%,75%{transform:translateX(-4px)} 50%{transform:translateX(4px)}
  }

  /* Country target bars */
  .country-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 5px 0;
    border-bottom: 1px solid rgba(255,255,255,0.04);
  }
  .country-row:last-child { border-bottom: none; }
  .cr-flag  { font-size: 16px; flex-shrink: 0; width: 22px; text-align: center; }
  .cr-name  { font-size: 11px; color: var(--text); min-width: 80px; flex-shrink: 0; }
  .cr-bar-wrap { flex: 1; height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; }
  .cr-bar   { height: 100%; border-radius: 3px; transition: width 1s ease; }
  .cr-count { font-size: 10px; color: var(--text-muted); min-width: 28px; text-align: left; direction: ltr; font-variant-numeric: tabular-nums; }

  /* Attack type donut-like list */
  .attack-type-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 5px 0;
    border-bottom: 1px solid rgba(255,255,255,0.04);
  }
  .attack-type-row:last-child { border-bottom: none; }
  .at-icon     { font-size: 14px; width: 22px; text-align: center; flex-shrink:0; }
  .at-label    { font-size: 11px; color: var(--text); min-width: 100px; }
  .at-bar-wrap { flex: 1; height: 4px; background: rgba(255,255,255,0.07); border-radius: 2px; margin: 0 6px; overflow:hidden; }
  .at-bar      { height: 100%; border-radius: 2px; transition: width 0.5s ease; }
  .at-count    { font-size: 11px; font-weight: 700; min-width: 28px; text-align: left; direction: ltr; }
  .at-pct      { font-size: 9px; color: var(--text-muted); min-width: 32px; text-align: left; direction: ltr; }

  /* Actor rows */
  .actor-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 5px 0;
    border-bottom: 1px solid rgba(255,255,255,0.04);
  }
  .actor-row:last-child { border-bottom: none; }
  .act-flag  { font-size: 14px; width: 22px; text-align: center; }
  .act-name  { font-size: 11px; color: var(--text); flex: 1; }
  .act-bar-wrap { width: 60px; height: 5px; background: var(--border); border-radius: 3px; overflow: hidden; }
  .act-bar   { height: 100%; border-radius: 3px; }
  .act-count { font-size: 10px; font-weight: 700; color: var(--text-muted); min-width: 28px; text-align: left; direction: ltr; }

  /* Date divider in timeline */
  .tl-date-divider {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 11px;
    font-weight: 800;
    color: var(--text);
    padding: 10px 14px;
    margin: 14px 0 5px;
    background: linear-gradient(135deg, rgba(231,76,60,0.08) 0%, rgba(255,255,255,0.02) 100%);
    border: 1px solid rgba(231,76,60,0.2);
    border-radius: 10px;
    letter-spacing: 0.5px;
    gap: 8px;
  }
  .tl-date-divider .tl-date-label { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
  .tl-date-divider .tl-date-count {
    font-size: 9px;
    background: rgba(231,76,60,0.15);
    border: 1px solid rgba(231,76,60,0.3);
    color: var(--red);
    padding: 2px 8px;
    border-radius: 10px;
    font-weight: 700;
  }

  /* Severity background tinting */
  .tl-item.sev-critical { background: rgba(231,76,60,0.06); border-radius: 6px; }
  .tl-item.sev-high     { background: rgba(230,126,34,0.05); border-radius: 6px; }
  .tl-item.sev-medium   { background: rgba(243,156,18,0.04); border-radius: 6px; }
  .tl-item.sev-low      { background: rgba(149,165,166,0.03); border-radius: 6px; }

  /* Enhanced type badges */
  .tl-type-badge.type-military  { background: rgba(231,76,60,0.15); color: #e74c3c; border: 1px solid rgba(231,76,60,0.3); }
  .tl-type-badge.type-oil       { background: rgba(243,156,18,0.15); color: #f39c12; border: 1px solid rgba(243,156,18,0.3); }
  .tl-type-badge.type-diplo     { background: rgba(52,152,219,0.15); color: #3498db; border: 1px solid rgba(52,152,219,0.3); }
  .tl-type-badge.type-intel     { background: rgba(155,89,182,0.15); color: #9b59b6; border: 1px solid rgba(155,89,182,0.3); }
  .tl-type-badge.type-economic  { background: rgba(39,174,96,0.15); color: #27ae60; border: 1px solid rgba(39,174,96,0.3); }

  /* Escalation gauge */
  .escalation-gauge {
    position: relative;
    height: 6px;
    background: linear-gradient(to left, #e74c3c, #f39c12, #27ae60);
    border-radius: 3px;
    margin: 6px 0 2px;
    overflow: visible;
  }
  .escalation-needle {
    position: absolute;
    top: -4px;
    width: 14px; height: 14px;
    border-radius: 50%;
    background: #fff;
    border: 3px solid var(--red);
    transform: translateX(50%);
    transition: right 0.8s ease;
    box-shadow: 0 0 6px rgba(231,76,60,0.5);
  }

  /* Casualties source note */
  .cas-source { font-size: 9px; color: var(--text-muted); margin-top: 4px; line-height: 1.4; }
  .cas-updated { font-size: 9px; color: rgba(39,174,96,0.7); }

  .tl-body { flex: 1; }
  /* Timeline item enhancements */
  .tl-item         { border-right: 3px solid transparent; }
  .tl-meta-row     { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; margin-bottom: 3px; }
  .tl-time         { font-size: 10px; color: var(--text-muted); direction: ltr; }
  .tl-type-badge   { font-size: 9px; padding: 1px 5px; border-radius: 10px; background: rgba(255,255,255,0.07); color: var(--text-muted); }
  .tl-new          { font-size: 8px; padding: 1px 5px; border-radius: 10px; background: rgba(231,76,60,0.2); color: #e74c3c; font-weight: 700; animation: pulse 1.5s infinite; }
  .tl-lang-en      { font-size: 8px; padding: 1px 4px; border-radius: 3px; background: rgba(52,152,219,0.15); color: #3498db; font-weight: 700; }
  .tl-title        { font-size: 12px; font-weight: 700; color: var(--text); margin-bottom: 3px; }
  .tl-footer-row   { display: flex; align-items: center; justify-content: space-between; gap: 6px; margin-top: 4px; flex-wrap: wrap; }
  .tl-source       { font-size: 9px; text-decoration: none; padding: 1px 5px; border-radius: 3px; background: rgba(255,255,255,0.05); transition: background 0.2s; }
  .tl-source:hover { background: rgba(255,255,255,0.12); }
  .tl-desc { font-size: 11px; color: #aaa; line-height: 1.7; }
  .tl-casualties { font-size: 10px; color: var(--red); margin-top: 3px; }
  .tl-verified { font-size: 9px; padding: 1px 5px; border-radius: 3px; margin-top: 3px; display: inline-block; }
  .tl-verified.yes { background: rgba(39,174,96,0.15); color: var(--green); }
  .tl-verified.no { background: rgba(243,156,18,0.15); color: var(--gold); }

  /* STATUS TABLE */
  .status-table { width: 100%; border-collapse: collapse; font-size: 12px; }
  .status-table tr { border-bottom: 1px solid var(--border); }
  .status-table tr:last-child { border-bottom: none; }
  .status-table td { padding: 8px 6px; }
  .status-table td:first-child { color: var(--text); font-weight: 600; }
  .status-table td:last-child { text-align: left; direction: ltr; }

  .status-pill {
    display: inline-block;
    font-size: 10px;
    font-weight: 700;
    padding: 2px 8px;
    border-radius: 10px;
  }
  .s-closed { background: rgba(231,76,60,0.2); color: var(--red); }
  .s-restricted { background: rgba(243,156,18,0.2); color: var(--gold); }
  .s-open { background: rgba(39,174,96,0.2); color: var(--green); }
  .s-threatened { background: rgba(231,76,60,0.15); color: #e67e22; }

  /* OIL CHART */
  .oil-chart { display: flex; align-items: flex-end; gap: 8px; height: 80px; padding: 8px 0; }
  .oil-bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 4px; height: 100%; justify-content: flex-end; }
  .oil-bar { width: 100%; border-radius: 3px 3px 0 0; background: linear-gradient(to top, var(--red), #c0392b); transition: height 0.5s; }
  .oil-label { font-size: 9px; color: var(--text-muted); }
  .oil-val { font-size: 10px; font-weight: 700; color: var(--red); }

  /* STATEMENTS */
  .stmt-item {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-right: 3px solid var(--blue);
    border-radius: 6px;
    padding: 8px 10px;
    margin-bottom: 7px;
  }
  .stmt-item.iran { border-right-color: var(--red); }
  .stmt-item.gcc { border-right-color: var(--gold); }
  .stmt-item.houthi { border-right-color: #8e44ad; }
  .stmt-item.intl { border-right-color: #95a5a6; }

  .stmt-actor { font-size: 10px; font-weight: 700; color: var(--text); }
  .stmt-time { font-size: 9px; color: var(--text-muted); direction: ltr; white-space: nowrap; }
  .stmt-header { display: flex; justify-content: space-between; align-items: center; gap: 6px; }
  .stmt-text { font-size: 11px; color: #aaa; line-height: 1.6; margin-top: 4px; }

  /* SOURCES */
  .sources-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
  .src-item {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 7px 9px;
    cursor: pointer;
    text-decoration: none;
    display: block;
    transition: border-color 0.2s;
  }
  .src-item:hover { border-color: var(--red); }
  .src-name { font-size: 11px; font-weight: 600; color: var(--text); }
  .src-type { font-size: 9px; color: var(--text-muted); margin-top: 2px; }
  .src-priority { font-size: 9px; padding: 1px 5px; border-radius: 3px; display: inline-block; margin-top: 2px; }
  .sp-1 { background: rgba(231,76,60,0.15); color: var(--red); }
  .sp-2 { background: rgba(243,156,18,0.1); color: var(--gold); }

  /* SCENARIOS */
  .scenario {
    background: rgba(255,255,255,0.02);
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 9px 11px;
    margin-bottom: 7px;
  }
  .sc-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
  .sc-title { font-size: 12px; font-weight: 700; color: var(--text); }
  .sc-prob { font-size: 10px; font-weight: 700; padding: 2px 7px; border-radius: 10px; }
  .sc-high { background: rgba(231,76,60,0.2); color: var(--red); }
  .sc-med { background: rgba(243,156,18,0.2); color: var(--gold); }
  .sc-low { background: rgba(39,174,96,0.2); color: var(--green); }
  .sc-desc { font-size: 11px; color: #999; line-height: 1.6; }

  /* SEARCH */
  .search-box {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 8px 12px;
    width: 100%;
    color: var(--text);
    font-family: 'Cairo', sans-serif;
    font-size: 13px;
    margin-bottom: 10px;
    outline: none;
  }
  .search-box:focus { border-color: var(--red); }

  /* FILTER TABS */
  .filter-tabs { display: flex; gap: 6px; margin-bottom: 10px; flex-wrap: wrap; }
  /* Source filter tabs — smaller, distinct style */
  #source-filter-tabs { overflow-x: auto; flex-wrap: nowrap; padding-bottom: 2px; scrollbar-width: none; }
  #source-filter-tabs::-webkit-scrollbar { display: none; }
  .stab { font-size: 10px !important; padding: 3px 8px !important; opacity: 0.75; background: rgba(255,255,255,0.04) !important; border-color: rgba(255,255,255,0.08) !important; white-space: nowrap; }
  .stab.active { opacity: 1; background: rgba(212,175,55,0.15) !important; border-color: var(--gold) !important; color: var(--gold) !important; }
  .ftab {
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 10px;
    font-weight: 600;
    cursor: pointer;
    border: 1px solid var(--border);
    background: transparent;
    color: var(--text-muted);
    font-family: 'Cairo', sans-serif;
    transition: all 0.2s;
  }
  .ftab.active, .ftab:hover { border-color: var(--red); background: var(--red-dim); color: var(--red); }

  /* MONITORS */
  .monitor-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 7px 0;
    border-bottom: 1px solid var(--border);
    font-size: 12px;
  }
  .monitor-item:last-child { border-bottom: none; }
  .mi-name { color: var(--text); }
  .mi-info { font-size: 10px; color: var(--text-muted); margin-top: 1px; }
  .mi-status { font-size: 10px; padding: 2px 8px; border-radius: 10px; }
  .mi-active { background: rgba(39,174,96,0.15); color: var(--green); }
  .mi-warning { background: rgba(243,156,18,0.15); color: var(--gold); }

  .divider { border: none; border-top: 1px solid var(--border); margin: 12px 0; }

  .last-update { font-size: 10px; color: var(--text-muted); text-align: center; margin-top: 16px; padding-bottom: 20px; }

  /* ======= MOBILE / iPHONE ======= */
  @media (max-width: 768px) {
    .mizan-strip { padding: 4px 12px; }
    .ms-logo { font-size: 13px; }
    .ms-tagline { font-size: 9px; }
    .ms-powered { font-size: 8px; }
    .topbar-inner { padding: 7px 12px; }
    .tb-logo { font-size: 13px; }
    .tb-badge { font-size: 8px; }
    .tb-clock { font-size: 11px; }
    .tb-refresh { padding: 4px 8px; font-size: 11px; }

    .main { padding: 10px 12px; }

    .stats-section { grid-template-columns: 1fr; }
    .indicators {
      grid-template-columns: repeat(4, 1fr) !important;
      gap: 8px;
    }
    .ind-value { font-size: 18px; }
    .ind-label { font-size: 9px; }
    .cas-source { display: none; } /* hide source on mobile to save space */

    .grid-2 { grid-template-columns: 1fr; }
    .grid-3 { grid-template-columns: 1fr; }

    .card-header { padding: 8px 12px; flex-wrap: wrap; gap: 4px; }
    .card-body { padding: 10px 12px; }

    .filter-tabs { gap: 4px; }
    .ftab { font-size: 9px; padding: 3px 8px; }

    .tl-item { gap: 8px; margin-bottom: 12px; }
    .tl-dot { width: 24px; height: 24px; font-size: 10px; }
    .tl-title { font-size: 12px; }
    .tl-desc { font-size: 11px; }

    .status-table td { padding: 7px 4px; font-size: 12px; }
    .status-pill { font-size: 10px; padding: 2px 7px; }

    .oil-chart { height: 70px; gap: 5px; }
    .oil-val { font-size: 9px; }
    .oil-label { font-size: 8px; }

    .stmt-item { padding: 7px 9px; }
    .stmt-actor { font-size: 11px; }
    .stmt-text { font-size: 10px; }

    .scenario { padding: 8px 10px; }
    .sc-title { font-size: 11px; }
    .sc-desc { font-size: 10px; }

    .sources-grid { grid-template-columns: 1fr; }
    .src-name { font-size: 12px; }

    .monitor-item { flex-wrap: wrap; gap: 4px; }
    .mi-name { font-size: 11px; }
    .mi-info { font-size: 9px; }
  }

  /* ── MOBILE ≤768px ──────────────────────────────────────── */
  @media (max-width: 768px) {

    /* Brand strip: compact */
    .mizan-strip { padding: 4px 10px; }
    .ms-tagline  { display: none; }
    .ms-powered  { display: none; }
    .ms-logo     { font-size: 14px; }

    /* Top bar inner */
    .topbar-inner { padding: 6px 10px; flex-wrap: wrap; gap: 6px; }
    .tb-left      { gap: 7px; }
    .tb-logo      { font-size: 13px; }
    .tb-clock     { font-size: 10px; }
    .tb-refresh   { display: none; }
    .last-updated-pill { display: none; }
    .visitors-badge { font-size: 10px; padding: 3px 8px; }
    .minister-link { font-size: 10px !important; padding: 4px 10px !important; }

    /* Indicators */
    .indicators {
      grid-template-columns: repeat(3, 1fr) !important;
      gap: 6px;
    }
    .indicator   { padding: 8px 8px; }
    .ind-label   { font-size: 8px; line-height: 1.3; }
    .ind-value   { font-size: 17px; }
    .ind-sub     { font-size: 8px; }
    .cas-source  { display: none; }
    .escalation-gauge { margin-top: 4px; }
    #ind-events-sub   { display: none; }

    /* Stats section */
    .stats-section { grid-template-columns: 1fr !important; }

    /* Filter tabs: horizontal scroll (most important fix!) */
    .filter-tabs {
      overflow-x: auto !important;
      flex-wrap: nowrap !important;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
      padding-bottom: 2px;
      margin-right: -10px;
    }
    .filter-tabs::-webkit-scrollbar { display: none; }
    .ftab { font-size: 10px; padding: 4px 10px; white-space: nowrap; flex-shrink: 0; }

    /* Main grids: single column */
    .grid-2 { grid-template-columns: 1fr !important; }

    /* Cards */
    .card-header { flex-wrap: wrap; gap: 4px; }
    .card-body   { padding: 10px; }
    .card-title  { font-size: 11px; }
    .card-count  { font-size: 10px; }

    /* Timeline */
    .tl-time  { font-size: 9px; }
    .tl-title { font-size: 12px; }
    .tl-desc  { font-size: 11px; }
    .tl-dot   { font-size: 12px; width: 26px; height: 26px; }

    /* Search */
    #timeline-search { font-size: 12px; padding: 6px 10px; }

    /* Oil chart flat display */
    #oil-chart { height: 80px; }

    /* Sources: 2 cols */
    .sources-grid { grid-template-columns: repeat(2, 1fr); }

    /* Main padding */
    .main { padding: 8px; }
  }

  /* ── SMALL ≤480px ─────────────────────────────────────── */
  @media (max-width: 480px) {
    .indicators { grid-template-columns: repeat(2, 1fr) !important; }
    .ind-value   { font-size: 20px; }
    .ind-label   { font-size: 9px; }
    .minister-label { display: none; } /* icon only */
    .minister-link  { padding: 4px 8px !important; }
  }

  /* ── NAV WRAP — scrollable nav bar on mobile ─────────── */
  .tb-nav-wrap {
    display: flex;
    align-items: center;
    gap: 6px;
    flex-wrap: nowrap;
  }
  @media (max-width: 768px) {
    /* visitors badge: compact */
    .visitors-badge {
      flex-direction: row !important;
      align-items: center !important;
      padding: 3px 8px !important;
      height: auto !important;
      gap: 4px !important;
    }
    #total-visits-display { display: none; }
    /* topbar-inner stacks to 2 rows */
    .topbar-inner {
      flex-direction: column !important;
      align-items: flex-start !important;
      gap: 6px !important;
      padding: 7px 10px !important;
    }
    /* second tb-left takes full width */
    .tb-left:last-child {
      width: 100%;
    }
    /* nav wrap becomes full-width scrollable strip */
    .tb-nav-wrap {
      width: 100%;
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
      padding-bottom: 2px;
    }
    .tb-nav-wrap::-webkit-scrollbar { display: none; }
    .tb-nav-wrap a {
      font-size: 11px !important;
      padding: 5px 10px !important;
      flex-shrink: 0;
    }
  }
  @media (max-width: 480px) {
    .tb-nav-wrap a {
      font-size: 10px !important;
      padding: 4px 8px !important;
    }
  }

  /* ── HAMBURGER & MOBILE NAV ─────────────────────────── */
  .ham-btn-idx {
    display: none;
    background: rgba(212,175,55,.12);
    border: 1px solid rgba(212,175,55,.35);
    color: var(--gold);
    font-size: 1.25rem;
    width: 36px; height: 36px;
    border-radius: 8px;
    cursor: pointer;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }
  .mobile-nav-idx {
    display: none;
    position: fixed;
    inset: 0;
    z-index: 10000;
    background: rgba(4,9,20,.97);
    flex-direction: column;
  }
  .mobile-nav-idx.open { display: flex !important; }
  .mnav-hdr {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 20px; border-bottom: 1px solid #1e2d42;
  }
  .mnav-hdr-brand { font-size: 1rem; font-weight: 900; color: var(--gold); }
  .mnav-hdr-close { background: none; border: none; color: #7a8394; font-size: 1.5rem; cursor: pointer; }
  .mnav-scroll { flex: 1; overflow-y: auto; padding: 16px 20px; }
  .mnav-sec { margin-bottom: 22px; }
  .mnav-sec-title {
    font-size: 10px; font-weight: 800; letter-spacing: 2px; color: #7a8394;
    text-transform: uppercase; margin-bottom: 10px;
    padding-bottom: 6px; border-bottom: 1px solid #1e2d42;
  }
  .mnav-items { display: flex; flex-direction: column; gap: 6px; }
  .mnav-item {
    display: flex; align-items: center; gap: 10px;
    padding: 11px 14px; border-radius: 10px;
    text-decoration: none; font-size: .92rem; font-weight: 700;
    border: 1px solid #1e2d42; color: #e8edf5; transition: .15s;
  }
  .mnav-item:hover, .mnav-item:active {
    border-color: rgba(212,175,55,.35);
    background: rgba(212,175,55,.06);
    color: #D4AF37;
  }
  .mnav-item.current {
    border-color: #e74c3c;
    background: rgba(231,76,60,.08);
    color: #e74c3c;
  }
  .mnav-item .mnav-lock {
    font-size: 9px; background: rgba(212,175,55,.12);
    color: var(--gold); border: 1px solid rgba(212,175,55,.25);
    padding: 2px 6px; border-radius: 8px; margin-right: auto;
  }
  @media (max-width: 900px) {
    .tb-nav-wrap { display: none !important; }
    .ham-btn-idx { display: flex !important; }
  }
  /* always show timeline btn regardless of nav-wrap */
  .timeline-topbar-btn { display: flex !important; }

/* ══ UAE SHIELD HERO ══════════════════════════════════════════════════════ */
.uae-hero{background:linear-gradient(135deg,rgba(0,100,0,0.18) 0%,rgba(0,60,0,0.12) 50%,rgba(0,82,165,0.1) 100%);border:1.5px solid rgba(0,150,0,0.4);border-radius:12px;padding:14px 18px;margin-bottom:14px;position:relative;overflow:hidden;}
.uae-hero::before{content:'';position:absolute;inset:0;background:url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23006400' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");pointer-events:none;}
.uae-hero-top{display:flex;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap;}
.uae-hero-flag{font-size:2.2rem;line-height:1;}
.uae-hero-title{flex:1;}
.uae-hero-title h2{font-size:1rem;font-weight:800;color:#fff;margin-bottom:2px;}
.uae-hero-title p{font-size:0.72rem;color:#aaa;}
.uae-status-badge{display:flex;align-items:center;gap:6px;padding:5px 12px;border-radius:20px;font-size:0.75rem;font-weight:700;}
.uae-status-badge.green{background:rgba(39,174,96,0.18);border:1px solid rgba(39,174,96,0.5);color:#27ae60;}
.uae-status-badge.yellow{background:rgba(243,156,18,0.18);border:1px solid rgba(243,156,18,0.5);color:#f39c12;}
.uae-status-badge.red{background:rgba(231,76,60,0.18);border:1px solid rgba(231,76,60,0.5);color:#e74c3c;}
.uae-status-dot{width:8px;height:8px;border-radius:50%;animation:pulse-dot 1.5s infinite;}
.uae-status-dot.green{background:#27ae60;}
.uae-status-dot.yellow{background:#f39c12;}
.uae-status-dot.red{background:#e74c3c;}
@keyframes pulse-dot{0%,100%{opacity:1;}50%{opacity:0.4;}}
.uae-kpi-row{display:grid;grid-template-columns:repeat(5,1fr);gap:8px;margin-bottom:10px;}
@media(max-width:640px){.uae-kpi-row{grid-template-columns:repeat(2,1fr);}}
.uae-kpi{background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:8px 10px;text-align:center;}
.uae-kpi .ukv{font-size:1.4rem;font-weight:800;line-height:1.1;}
.uae-kpi .ukl{font-size:0.65rem;color:#aaa;margin-top:3px;line-height:1.3;}
.uae-mbz-quote{background:rgba(212,175,55,0.08);border-right:3px solid #D4AF37;border-radius:0 6px 6px 0;padding:8px 12px;font-size:0.73rem;color:#ccc;font-style:italic;margin-top:10px;}
.uae-mbz-quote span{color:#D4AF37;font-weight:700;font-style:normal;}
.uae-today-strip{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;}
.uae-today-item{background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);border-radius:6px;padding:5px 10px;font-size:0.71rem;color:#ddd;display:flex;align-items:center;gap:5px;}
/* ══ MOBILE BOTTOM TAB BAR ═════════════════════════════════════════════════ */
.mobile-bottom-tabs{display:none;}
@media(max-width:768px){
  .mobile-bottom-tabs{display:flex;position:fixed;bottom:0;left:0;right:0;background:#0d0d0d;border-top:1px solid #2a2a2a;z-index:9999;padding:6px 0 8px;padding-bottom:max(8px,env(safe-area-inset-bottom));}
  .mbt-item{flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#888;font-size:0.6rem;font-weight:600;padding:2px 0;transition:color 0.2s;}
  .mbt-item.active,.mbt-item:hover{color:#D4AF37;}
  .mbt-icon{font-size:1.3rem;line-height:1;}
  /* Push page content up on mobile so tabs don't overlap */
  .main{padding-bottom:72px;}
}


/* ══ VIEW TOGGLE SWITCH — GCC Multi-Country ═══════════════════════════════ */
.view-toggle-bar{display:flex;align-items:center;justify-content:center;gap:4px;margin:0 0 12px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.1);border-radius:30px;padding:5px 8px;width:fit-content;margin-left:auto;margin-right:auto;flex-wrap:wrap;}
.vt-btn{display:flex;align-items:center;gap:5px;padding:6px 14px;border-radius:24px;border:none;background:transparent;color:#888;font-family:'Cairo',sans-serif;font-size:0.78rem;font-weight:700;cursor:pointer;transition:all 0.25s;white-space:nowrap;}
.vt-btn:hover{color:#ccc;background:rgba(255,255,255,0.06);}
/* UAE — main (green/gold) */
.vt-btn.active.v-uae{background:linear-gradient(135deg,#004d00,#006400);color:#D4AF37;box-shadow:0 2px 8px rgba(0,100,0,0.4);}
/* Saudi */
.vt-btn.active.v-saudi{background:linear-gradient(135deg,#1a4a1a,#2d7a2d);color:#4caf50;box-shadow:0 2px 8px rgba(45,122,45,0.4);}
/* Bahrain */
.vt-btn.active.v-bahrain{background:linear-gradient(135deg,#4a0a0a,#8b1a1a);color:#ff6b6b;box-shadow:0 2px 8px rgba(139,26,26,0.4);}
/* Qatar */
.vt-btn.active.v-qatar{background:linear-gradient(135deg,#3a0a2a,#6b1a4a);color:#e07bb8;box-shadow:0 2px 8px rgba(107,26,74,0.4);}
/* Kuwait */
.vt-btn.active.v-kuwait{background:linear-gradient(135deg,#2a2a00,#4a4a00);color:#d4d400;box-shadow:0 2px 8px rgba(74,74,0,0.4);}
/* Oman */
.vt-btn.active.v-oman{background:linear-gradient(135deg,#1a0a0a,#3a1a1a);color:#c0392b;box-shadow:0 2px 8px rgba(192,57,43,0.4);}
/* Regional */
.vt-btn.active.v-regional{background:linear-gradient(135deg,#0f3460,#1a5276);color:#3498db;box-shadow:0 2px 8px rgba(52,152,219,0.3);}
.vt-divider{width:1px;height:20px;background:rgba(255,255,255,0.1);flex-shrink:0;}
/* UAE local view: hide regional cards */
body.uae-local-view .regional-only{display:none!important;}
/* Regional view: hide UAE hero */
body.regional-view .uae-local-only{display:none!important;}
/* Regional view: hide individual country cards, indicators strip, and other sections — show only regional hero */
body.regional-view .indicators{display:none!important;}
/* Timeline view — show only timeline section, hide everything else */
body.timeline-view .indicators{display:none!important;}
body.timeline-view #stats-section-wrapper{display:none!important;}
body.timeline-view #offensive-ops-wrapper{display:none!important;}
body.timeline-view #offensive-ops-card{display:none!important;}
body.timeline-view .gcc-hero{display:none!important;}
body.timeline-view #regional-hero-section{display:none!important;}
body.timeline-view #uae-hero-section{display:none!important;}
body.timeline-view #main-grid-3{display:none!important;}
body.timeline-view #today-updates-card{display:none!important;}
body.timeline-view #request-access-cta{display:none!important;}
body.timeline-view #live-view-banner{display:none!important;}
body.timeline-view .card:has(#airspace-table){display:none!important;}
body.timeline-view .card:has(#scenarios-container){display:none!important;}
body.timeline-view .card:has(#attack-types-container){display:none!important;}
body.timeline-view .card:has(#actors-container){display:none!important;}
body.regional-view #stats-section-wrapper{display:none!important;}
body.regional-view #missile-drone-tracker{display:none!important;}
body.regional-view #tg-subscribe-banner{display:none!important;}
body.regional-view a.hide-in-uae{display:none!important;}
body.timeline-view #missile-drone-tracker{display:none!important;}
body.timeline-view #tg-subscribe-banner{display:none!important;}
/* Force show timeline card in timeline-view (overrides hide-in-uae) */
body.timeline-view #timeline-card{display:block!important;}
body.timeline-view #main-grid-2{display:block!important;}
body.regional-view #offensive-ops-wrapper{display:none!important;}
body.regional-view #offensive-ops-card{display:none!important;}
body.regional-view .gcc-hero{display:none!important;}
body.regional-view #main-grid-3{display:none!important;}
body.regional-view #today-updates-card{display:none!important;}
body.regional-view #request-access-cta{display:none!important;}
body.regional-view #live-view-banner{display:none!important;}
body.regional-view .card:has(#airspace-table){display:none!important;}
body.regional-view .card:has(#scenarios-container){display:none!important;}
/* GCC country views — same as regional but with country hero visible */
body.gcc-view .uae-local-only{display:none!important;}
/* ── Iran view: show ONLY the hero card, hide all regular page content ── */
body.iran-view .uae-local-only{display:none!important;}
body.iran-view .indicators{display:none!important;}
body.iran-view #map-open-banner{display:none!important;}
body.iran-view #tg-subscribe-banner{display:none!important;}
body.iran-view .hide-in-uae{display:none!important;}
body.iran-view #stats-section-wrapper{display:none!important;}
body.iran-view #offensive-ops-wrapper{display:none!important;}
body.iran-view #offensive-ops-card{display:none!important;}
body.iran-view .card:has(#airspace-table){display:none!important;}
body.iran-view .card:has(#scenarios-container){display:none!important;}
body.iran-view .card:has(#oil-chart){display:none!important;}
body.iran-view .grid-2{display:none!important;}
body.iran-view .grid-3{display:none!important;}
body.iran-view #today-updates-card{display:none!important;}
body.iran-view #timeline-container{display:none!important;}
body.iran-view .card:has(#timeline-container){display:none!important;}
body.iran-view .gcc-hero{display:block;}
/* ── US view: same — show only hero card ── */
body.us-view .uae-local-only{display:none!important;}
body.us-view .indicators{display:none!important;}
body.us-view #map-open-banner{display:none!important;}
body.us-view #tg-subscribe-banner{display:none!important;}
body.us-view .hide-in-uae{display:none!important;}
body.us-view #stats-section-wrapper{display:none!important;}
body.us-view #offensive-ops-wrapper{display:none!important;}
body.us-view #offensive-ops-card{display:none!important;}
body.us-view .card:has(#airspace-table){display:none!important;}
body.us-view .card:has(#scenarios-container){display:none!important;}
body.us-view .card:has(#oil-chart){display:none!important;}
body.us-view .grid-2{display:none!important;}
body.us-view .grid-3{display:none!important;}
body.us-view #today-updates-card{display:none!important;}
body.us-view #timeline-container{display:none!important;}
body.us-view .card:has(#timeline-container){display:none!important;}
body.us-view .gcc-hero{display:block;}

/* ── GCC view: hide all regional/global content, show only GCC hero ── */
body.gcc-view .indicators{display:none!important;}
body.gcc-view #map-open-banner{display:none!important;}
body.gcc-view #tg-subscribe-banner{display:none!important;}
body.gcc-view .hide-in-uae{display:none!important;}
body.gcc-view #stats-section-wrapper{display:none!important;}
body.gcc-view #offensive-ops-wrapper{display:none!important;}
body.gcc-view #offensive-ops-card{display:none!important;}
body.gcc-view .card:has(#airspace-table){display:none!important;}
body.gcc-view .card:has(#scenarios-container){display:none!important;}
/* Timeline section + search bar stay visible — filtered to country events */
/* gcc-hero is the ONLY stats section shown in gcc view */
body:not(.uae-local-view):not(.gcc-view) .uae-local-only{display:none!important;}

/* ══ GCC COUNTRY HERO CARD ════════════════════════════════════════════════ */
.gcc-hero{border-radius:12px;padding:14px 18px;margin-bottom:14px;position:relative;overflow:hidden;display:none;}
body.gcc-view .gcc-hero{display:block;}
.gcc-hero-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:8px;margin-top:12px;}
.gcc-stat{background:rgba(0,0,0,0.25);border-radius:8px;padding:8px 10px;text-align:center;}
.gcc-stat-val{font-size:1.5rem;font-weight:900;line-height:1;}
.gcc-stat-lbl{font-size:0.65rem;color:#aaa;margin-top:3px;}
.gcc-intercept-bar{height:5px;border-radius:3px;background:rgba(255,255,255,0.1);margin-top:10px;overflow:hidden;}
.gcc-intercept-fill{height:100%;border-radius:3px;transition:width 0.8s ease;}


/* ══ UAE LOCAL VIEW — HIDE ELEMENTS ══════════════════════════════════════ */
body.uae-local-view .hide-in-uae { display:none!important; }

/* ══ SAFETY STATUS CARD ══════════════════════════════════════════════════ */
.safety-card{border-radius:10px;padding:12px 16px;margin-bottom:10px;display:flex;align-items:center;gap:14px;transition:all 0.4s;}
.safety-card.safe{background:linear-gradient(135deg,rgba(39,174,96,0.15),rgba(39,174,96,0.06));border:1.5px solid rgba(39,174,96,0.5);}
.safety-card.warning{background:linear-gradient(135deg,rgba(243,156,18,0.15),rgba(243,156,18,0.06));border:1.5px solid rgba(243,156,18,0.5);}
.safety-card.danger{background:linear-gradient(135deg,rgba(231,76,60,0.2),rgba(231,76,60,0.08));border:1.5px solid rgba(231,76,60,0.6);}
.safety-icon{font-size:2rem;flex-shrink:0;}
.safety-text h3{font-size:1rem;font-weight:800;margin-bottom:2px;}
.safety-card.safe .safety-text h3{color:#27ae60;}
.safety-card.warning .safety-text h3{color:#f39c12;}
.safety-card.danger .safety-text h3{color:#e74c3c;}
.safety-text p{font-size:0.72rem;color:#aaa;}
.safety-meta{margin-right:auto;text-align:left;font-size:0.7rem;color:#888;}

/* ══ UAE DAILY LIFE STRIP ═════════════════════════════════════════════════ */
.daily-life-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:10px;}
@media(max-width:640px){.daily-life-grid{grid-template-columns:repeat(2,1fr);}}
.dl-card{background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.09);border-radius:8px;padding:9px 10px;text-align:center;}
.dl-icon{font-size:1.3rem;margin-bottom:3px;}
.dl-val{font-size:0.85rem;font-weight:700;color:#fff;}
.dl-lbl{font-size:0.63rem;color:#888;margin-top:1px;}
.dl-status{display:inline-block;font-size:0.6rem;padding:1px 6px;border-radius:8px;font-weight:700;margin-top:3px;}
.dl-status.open{background:rgba(39,174,96,0.2);color:#27ae60;border:1px solid rgba(39,174,96,0.4);}
.dl-status.limited{background:rgba(243,156,18,0.2);color:#f39c12;border:1px solid rgba(243,156,18,0.4);}
.dl-status.closed{background:rgba(231,76,60,0.2);color:#e74c3c;border:1px solid rgba(231,76,60,0.4);}

/* ══ LAST OFFICIAL STATEMENT ═════════════════════════════════════════════ */
.uae-stmt-card{background:rgba(212,175,55,0.06);border:1px solid rgba(212,175,55,0.25);border-radius:8px;padding:10px 14px;margin-bottom:10px;}
.uae-stmt-card .stmt-who{font-size:0.7rem;color:#D4AF37;font-weight:700;margin-bottom:4px;display:flex;align-items:center;gap:6px;}
.uae-stmt-card .stmt-text{font-size:0.82rem;color:#ddd;font-style:italic;line-height:1.6;}
.uae-stmt-card .stmt-time{font-size:0.65rem;color:#888;margin-top:4px;}

/* ══ EMERGENCY GUIDANCE ══════════════════════════════════════════════════ */
.emergency-guide{background:rgba(231,76,60,0.06);border:1px solid rgba(231,76,60,0.2);border-radius:8px;padding:10px 14px;margin-bottom:10px;}
.emergency-guide h4{font-size:0.8rem;font-weight:800;color:#e74c3c;margin-bottom:8px;}
.eg-item{display:flex;align-items:flex-start;gap:8px;margin-bottom:6px;font-size:0.75rem;color:#ccc;}
.eg-num{background:#e74c3c;color:#fff;border-radius:50%;width:18px;height:18px;display:flex;align-items:center;justify-content:center;font-size:0.6rem;font-weight:800;flex-shrink:0;margin-top:1px;}
@media(max-width:640px){
  .view-toggle-bar{border-radius:16px;gap:3px;padding:4px;}
  .vt-btn{padding:5px 10px;font-size:0.7rem;gap:3px;}
  .vt-divider{display:none;}
  .gcc-hero-grid{grid-template-columns:repeat(3,1fr);}
}


 (no FOUC, no dynamic injection)
// No need to inject skel-style anymore — it's in the static CSS above.

// ══ DB Fetch Progress Indicator ══════════════════════════════════════════════
// Uses pre-embedded #db-fetch-progress bar (visible before JS finishes loading)
const _progBar    = document.getElementById('db-fetch-progress');
const _progFill   = document.getElementById('db-fetch-progress-fill');
const _progLabel  = document.getElementById('db-fetch-label');

function showDbProgress(pct, label) {
  if (!_progBar) return;
  if (typeof pct === 'number') {
    _progBar.classList.remove('indeterminate');
    _progFill.style.width = pct + '%';
  } else {
    _progBar.classList.add('indeterminate');
  }
  if (_progLabel) {
    _progLabel.style.display = label ? 'block' : 'none';
    if (label) _progLabel.textContent = label;
  }
  _progBar.style.display = 'block';
}

function hideDbProgress() {
  if (_progBar) {
    _progFill.style.width = '100%';
    _progBar.classList.remove('indeterminate');
    setTimeout(() => {
      if (_progBar) _progBar.style.display = 'none';
      if (_progLabel) _progLabel.style.display = 'none';
    }, 350);
  }
}

// Loading bar element (backward compat — still used by live refresh)
let _loadingBar = null;
function showLoadingBar() {
  if (!_loadingBar) {
    _loadingBar = document.createElement('div');
    _loadingBar.className = 'loading-overlay';
    document.body.appendChild(_loadingBar);
  }
  _loadingBar.style.display = 'block';
}
function hideLoadingBar() {
  if (_loadingBar) _loadingBar.style.display = 'none';
}

async function loadData() {
  // Save scroll position before re-render to prevent jumping to top
  var _scrollY = window.scrollY || window.pageYOffset || 0;
  var _restoreScroll = _scrollY > 80; // only restore if user has scrolled down

  // ⚡ v7: على التحميل الأول، حاول عرض الكاش فوراً (IndexedDB أولاً للسرعة)
  if (!window.warDB) {
    const localDB = await getLocalDBAsync(); // IndexedDB أسرع من localStorage للـ 2.8MB
    if (localDB) {
      console.log('⚡ بصيرة: عرض الكاش الفوري أثناء التحديث');
      window.warDB = localDB;
      try {
        renderStatsSection(localDB.events);
        renderMissileTracker(localDB.stats);
        renderUAEHero(localDB);
        renderUAELocalView(localDB);
      } catch(e) { /* ignore partial render errors */ }
    } else {
      showSkeletons();
      showDbProgress(null, '⏳ جارٍ تحميل البيانات…');
      showLoadingBar();
    }
  }

  try {
    showDbProgress(15, '📡 جارٍ الاتصال بالخادم…');
    const db = await smartFetchDB();
    showDbProgress(95, '✅ تم التحميل — جارٍ العرض…');
    hideLoadingBar();
    hideDbProgress();
    window.warDB = db; // expose for GCC hero
    // ⚡ v7: بيانات جديدة → بطّل كاش الفرز (يُعاد الحساب بعد الـ render)
    _sortedEventsCache = null; _sortedFilterKey = ''; _dateCountsCache = null;
    renderStatsSection(db.events);
    renderMissileTracker(db.stats);
    renderUAEHero(db);
    renderUAELocalView(db);
    if (typeof initViewToggle !== "undefined") initViewToggle();
    // Restore scroll position after render
    if (_restoreScroll) {
      requestAnimationFrame(function() { window.scrollTo(0, _scrollY); });
    }
    initReportsGate();
    renderTimeline(db.events, currentFilter, currentSearch, timelinePage);
    renderStatements(db.statements);
    const stmtCountEl = document.getElementById('statements-count');
    if (stmtCountEl) stmtCountEl.textContent = (db.statements?.length || 0) + ' بيان';
    const verifiedCount = db.events.filter(e=>e.verified).length;
    document.getElementById('ind-events').textContent = db.events.length;
    const indSubEl = document.getElementById('ind-events-sub');
    if(indSubEl) indSubEl.textContent = `${verifiedCount} موثّق · ${db.events.length - verifiedCount} غير مؤكد`;
    document.getElementById('events-count').textContent = db.events.length + ' حدث';
    document.getElementById('last-update').textContent = 'آخر تحديث: ' + new Date(db.meta.lastUpdated).toLocaleString('ar-AE-u-ca-gregory-nu-latn', { timeZone: 'Asia/Dubai' });

    // ── Data Freshness Bar ───────────────────────────────────────────────────
    (function() {
      const metaUp = db.meta?.lastUpdated ? new Date(db.meta.lastUpdated) : null;
      const freshnessMetaEl = document.getElementById('freshness-meta-updated');
      const freshnessExactEl = document.getElementById('freshness-exact-time');
      if (freshnessMetaEl && metaUp) {
        const diff = Date.now() - metaUp.getTime();
        const mins = Math.floor(diff / 60000);
        const hrs  = Math.floor(mins / 60);
        if (hrs > 0) freshnessMetaEl.textContent = `منذ ${hrs} ساعة ${mins % 60 > 0 ? 'و' + (mins % 60) + ' دقيقة' : ''}`;
        else if (mins > 0) freshnessMetaEl.textContent = `منذ ${mins} دقيقة`;
        else freshnessMetaEl.textContent = 'الآن';
        // Color code by freshness
        freshnessMetaEl.style.color = hrs >= 6 ? '#e74c3c' : hrs >= 2 ? '#f39c12' : '#27ae60';
      }
      if (freshnessExactEl && metaUp) {
        freshnessExactEl.textContent = metaUp.toLocaleString('ar-AE-u-ca-gregory-nu-latn', { timeZone: 'Asia/Dubai', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
      }
      // "آخر خبر مُنشور" = latest event publication datetime
      const allEvt = db.events || [];
      const countEl = document.getElementById('freshness-event-count');
      if (countEl) countEl.textContent = allEvt.length.toLocaleString('en-US') + ' حدث';
      if (allEvt.length) {
        const latest = allEvt.reduce((a, b) => (a.datetime > b.datetime ? a : b));
        const evEl   = document.getElementById('freshness-last-event');
        if (evEl) {
          const evDiff = Date.now() - new Date(latest.datetime).getTime();
          const evMins = Math.floor(evDiff / 60000);
          const evHrs  = Math.floor(evMins / 60);
          if (evHrs > 0) evEl.textContent = `منذ ${evHrs} ساعة`;
          else if (evMins > 0) evEl.textContent = `منذ ${evMins} دقيقة`;
          else evEl.textContent = 'الآن';
          // Publication date being old is normal — cron freshness is more important
          evEl.style.color = evHrs >= 24 ? '#e74c3c' : evHrs >= 6 ? '#f39c12' : '#27ae60';
        }
      }
    })();
    allEvents = db.events;
    buildSourceTabs(allEvents);   // populate source filter tabs

    // ── Missiles & Drones Count ───────────────────────────────────────────
    (function() {
      const mEl  = document.getElementById('ind-missiles');
      const mSub = document.getElementById('ind-missiles-sub');
      const dEl  = document.getElementById('ind-drones');
      const dSub = document.getElementById('ind-drones-sub');

      // ── Use verified db.stats if available ───────────────────────────
      if (db.stats?.missiles && db.stats?.drones) {
        const ms = db.stats.missiles;
        const ds = db.stats.drones;
        // Show TOTAL count (GCC + Israel + all targets)
        const msTotal = ms.total;
        const dsTotal = ds.total;
        if (mEl)  mEl.textContent  = msTotal.toLocaleString('en-US');
        if (mSub) {
          const gcc     = ms.gccTotal  || 0;
          const israel  = ms.israel?.total || 0;
          mSub.textContent = `الخليج ${gcc.toLocaleString('en-US')} · إسرائيل ${israel.toLocaleString('en-US')} · ${ms.interceptRate}% اعتراض`;
          // Per-country breakdown on hover
          const byC = ms.byCountry || {};
          mSub.title = Object.entries(byC).map(([c,v]) => `${c}: ${v.total}`).join(' | ');
        }
        if (dEl)  dEl.textContent  = dsTotal.toLocaleString('en-US');
        if (dSub) {
          const gcc    = ds.gccTotal  || 0;
          const israel = ds.israel?.total || 0;
          dSub.textContent = `الخليج ${gcc.toLocaleString('en-US')} · إسرائيل ${israel.toLocaleString('en-US')} · ${ds.interceptRate}% اعتراض`;
          const byC = ds.byCountry || {};
          dSub.title = Object.entries(byC).map(([c,v]) => `${c}: ${v.total}`).join(' | ');
        }
        return;
      }

      // ── Fallback: count from events ───────────────────────────────────
      const missileTypes = ['missile','missile_attack','missile_strike','missile_drone_attack','retaliation'];
      const droneTypes   = ['drone','drone_attack'];
      let totalMissiles  = 0, totalDrones = 0, missileEvents = 0, droneEvents = 0;

      for (const e of db.events) {
        const etype = (e.type || '').toLowerCase();
        const desc  = ((e.description || '') + ' ' + (e.title || '')).toLowerCase();
        if (missileTypes.includes(etype)) {
          missileEvents++;
          const nums = [
            ...(desc.match(/(\d+)\s*(?:صاروخ|صواريخ)/g) || []),
            ...(desc.match(/(\d+)\s*(?:missile|ballistic|cruise|rocket)/gi) || []),
          ].map(m => parseInt(m.match(/\d+/)[0])).filter(n => n > 0 && n < 5000);
          totalMissiles += nums.length ? Math.max(...nums) : 1;
        }
        if (droneTypes.includes(etype)) {
          droneEvents++;
          const nums = [
            ...(desc.match(/(\d+)\s*(?:درون|مسيّرات|طائرات مسيّرة)/g) || []),
            ...(desc.match(/(\d+)\s*(?:drone|uav|unmanned)/gi) || []),
          ].map(m => parseInt(m.match(/\d+/)[0])).filter(n => n > 0 && n < 5000);
          totalDrones += nums.length ? Math.max(...nums) : 1;
        }
      }

      if (mEl)  mEl.textContent  = totalMissiles.toLocaleString('en-US');
      if (mSub) mSub.textContent = `في ${missileEvents} حدث · تقدير`;
      if (dEl)  dEl.textContent  = totalDrones > 0 ? totalDrones.toLocaleString('en-US') : droneEvents;
      if (dSub) dSub.textContent = `في ${droneEvents} حدث · تقدير`;
    
})();

    // ── Casualties ────────────────────────────────────────────────────────
    let iranKilled=0, iranInjured=0, gulfKilled=0, gulfInjured=0, israelKilled=0, israelInjured=0;

    if (db.casualties) {
      iranKilled    = db.casualties.iran?.killed    || 0;
      iranInjured   = db.casualties.iran?.injured   || 0;
      gulfKilled    = db.casualties.gulf?.killed    || 0;
      gulfInjured   = db.casualties.gulf?.injured   || 0;
      israelKilled  = db.casualties.israel?.killed  || 0;
      israelInjured = db.casualties.israel?.injured || 0;

      // Show source + timestamp for each
      function casSource(obj) {
        if (!obj) return '';
        const src = obj.source || '';
        const ts  = obj.lastUpdated ? new Date(obj.lastUpdated).toLocaleString('ar-AE-u-ca-gregory-nu-latn',{timeZone:'Asia/Dubai',hour:'2-digit',minute:'2-digit',day:'numeric',month:'short'}) : '';
        return (src ? src.split('—')[0].trim() : '') + (ts ? ` · ${ts}` : '');
      }
      const srcEl = (id, obj) => { const el=document.getElementById(id); if(el) el.textContent = casSource(obj); };
      srcEl('ind-iran-source',   db.casualties.iran);
      srcEl('ind-gulf-source',   db.casualties.gulf);
      srcEl('ind-israel-source', db.casualties.israel);
      if (db.casualties?.us) srcEl('ind-us-source', db.casualties.us);
    } else {
      // Fallback: aggregate from events
      const gulfTargets = ['UAE','Abu Dhabi','Dubai','Bahrain','Qatar','Kuwait','Saudi','الإمارات','البحرين','قطر'];
      for (const e of db.events) {
        const c = e.casualties || {};
        const targets = JSON.stringify(e.targetLocations || e.target || '');
        const isGulf  = gulfTargets.some(t => targets.includes(t));
        if (isGulf) { gulfKilled += c.killed||0; gulfInjured += c.injured||0; }
        else        { iranKilled += c.killed||0; iranInjured += c.injured||0; }
      }
    }

    // Iran
    const elK = document.getElementById('ind-killed');
    const elI = document.getElementById('ind-injured');
    if (elK) elK.textContent = iranKilled.toLocaleString('en-US');
    if (elI) elI.textContent = (iranInjured||0).toLocaleString('en-US') + ' جريح';

    // Gulf
    const elGK   = document.getElementById('ind-gulf-killed');
    const elGSub = document.getElementById('ind-gulf-sub');
    if (elGK)   elGK.textContent   = gulfKilled  || '—';
    if (elGSub) elGSub.textContent = gulfInjured ? gulfInjured + ' جريح' : 'لا إصابات مؤكدة';

    // Israel
    const elIK   = document.getElementById('ind-israel-killed');
    const elISub = document.getElementById('ind-israel-sub');
    if (elIK)   elIK.textContent   = israelKilled  || '—';
    if (elISub) elISub.textContent = israelInjured ? israelInjured + ' جريح' : 'لا إصابات مؤكدة';

    // USA
    const usData    = db.casualties?.us || {};
    const usKilled  = usData.killed  || 0;
    const usInjured = usData.injured || 0;
    const elUK   = document.getElementById('ind-us-killed');
    const elUSub = document.getElementById('ind-us-sub');
    const elUSrc = document.getElementById('ind-us-source');
    if (elUK)   elUK.textContent   = usKilled  || '—';
    if (elUSub) elUSub.textContent = usInjured ? usInjured + ' جريح خطير' : 'لا إصابات مؤكدة';
    if (elUSrc) elUSrc.textContent = usData.source ? '📡 ' + usData.source : '—';

    // ── Escalation gauge (0–100) ──────────────────────────────────────────
    // Factors: total events, verified events, hormuz status, airspace closures
    const totalEvents = db.events.length;
    const verifiedCnt = db.events.filter(e=>e.verified).length;
    const closedAirspace = Object.values(db.indicators?.airspace||{}).filter(a=>a.status==='closed').length;
    const hormuzStatus = db.indicators?.hormuz?.status || 'open';
    let escalation = Math.min(100, Math.round(
      (totalEvents * 0.1) +        // more events = higher
      (verifiedCnt * 0.05) +       // verified events count more
      (closedAirspace * 5) +       // each closed airspace +5
      (hormuzStatus === 'closed' ? 25 : hormuzStatus === 'restricted' ? 15 : hormuzStatus === 'warning' ? 10 : 0) +
      (iranKilled > 1000 ? 20 : iranKilled > 100 ? 10 : 5)
    ));
    const needle = document.getElementById('escalation-needle');
    const label  = document.getElementById('escalation-label');
    if (needle) needle.style.right = (100 - escalation) + '%';
    const escLabels = [[80,'🔴 خطر شديد'],[60,'🟠 تصعيد عالٍ'],[40,'🟡 متوسط'],[20,'🟢 محدود'],[0,'🔵 منخفض']];
    const escLabel = escLabels.find(([th])=>escalation>=th)?.[1] || '🔵 منخفض';
    if (label) { label.textContent = escLabel; label.style.fontWeight='700'; }

    // Hormuz status
    const hormuz = db.indicators?.hormuz;
    if (hormuz) {
      const el    = document.getElementById('ind-hormuz');
      const elSub = document.getElementById('ind-hormuz-sub');
      const statusMap = {
        open:       { text: 'مفتوح ✅',   color: 'var(--green)' },
        restricted: { text: 'مقيّد ⚠️',   color: '#e67e22' },
        warning:    { text: 'تحذير 🚨',   color: 'var(--red)' },
        closed:     { text: 'مغلق 🚫',    color: 'var(--red)' },
      };
      const st = statusMap[hormuz.status] || { text: hormuz.status, color: 'var(--text-muted)' };
      if (el)    { el.textContent = st.text; el.style.color = st.color; }
      if (elSub) elSub.textContent = hormuz.note || '';
    }

    // Update offensive ops from DB
    if (db.stats?.offensiveOps) renderOffensiveOps(db.stats.offensiveOps);

    // Update scenarios from DB
    if (db.scenarios) renderScenarios(db.scenarios);

    // Update sources from DB
    if (db.sources) renderSources(db.sources);

    // Update airspace from DB
    if (db.indicators?.airspace) renderAirspace(db.indicators.airspace);

    // Today's updates card
    renderTodayUpdates(db);

    // Update oil price from DB
    const oilPrices = db.indicators?.oilPrice || [];
    if (oilPrices.length >= 1) {
      const latest = oilPrices[oilPrices.length - 1];
      const prev   = oilPrices.length >= 2 ? oilPrices[oilPrices.length - 2] : null;
      const price  = latest.brent;
      const el     = document.getElementById('ind-oil');
      const chEl   = document.getElementById('ind-oil-change');
      if (el) el.textContent = '$' + price.toFixed(1);
      if (chEl && prev) {
        const diff = (price - prev.brent).toFixed(2);
        const pct  = ((price - prev.brent) / prev.brent * 100).toFixed(1);
        const up   = diff >= 0;
        chEl.textContent = (up ? '▲ +' : '▼ ') + diff + ' (' + (up ? '+' : '') + pct + '%)';
        chEl.className = 'ind-change ' + (up ? 'up' : 'down');
      }
      // Color indicator border based on threshold
      const indEl = el?.closest('.indicator');
      if (indEl) {
        indEl.style.borderColor = price >= 150 ? '#e74c3c' : price >= 120 ? '#f39c12' : '#2a2a2a';
      }
      renderOilChart(oilPrices);
      renderOilSparkline(oilPrices);
      // Update oil card header: % change from first entry to latest
      const oilHeaderEl = document.getElementById('oil-header-change');
      if (oilHeaderEl && oilPrices.length >= 2) {
        const first = oilPrices[0].brent;
        const now   = oilPrices[oilPrices.length - 1].brent;
        const pctTot = ((now - first) / first * 100).toFixed(1);
        const upTot  = now >= first;
        oilHeaderEl.textContent = (upTot ? '▲ +' : '▼ ') + Math.abs(pctTot) + '% منذ الأزمة';
        oilHeaderEl.style.color = upTot ? 'var(--red)' : 'var(--green)';
      }
    }
  } catch(e) {
    console.error(e);
    // ⚡ v8: إخفاء مؤشرات التحميل عند الخطأ
    hideLoadingBar();
    hideDbProgress();
    const tc = document.getElementById('timeline-container');
    if (tc && !window.warDB) {
      // فقط إذا لم تُعرض بيانات قط — لا نكسر بيانات موجودة
      tc.innerHTML = `
        <div style="text-align:center;padding:40px 20px;background:rgba(231,76,60,0.08);border:1px solid rgba(231,76,60,0.25);border-radius:12px;margin:16px 0;">
          <div style="font-size:2rem;margin-bottom:12px;">📡</div>
          <div style="color:#e74c3c;font-size:1rem;font-weight:700;margin-bottom:8px;">تعذّر تحميل البيانات</div>
          <div style="color:#888;font-size:0.8rem;margin-bottom:16px;">تأكد من اتصالك بالإنترنت ثم أعد المحاولة</div>
          <button onclick="loadDataLive()" style="background:#e74c3c;color:#fff;border:none;padding:8px 24px;border-radius:20px;font-family:Cairo,sans-serif;font-size:0.85rem;cursor:pointer;font-weight:700;">🔄 إعادة المحاولة</button>
        </div>`;
    }
  }
}

// ─── TODAY'S UPDATES ─────────────────────────────────────────────────────────

function renderTodayUpdates(db) {
  const listEl  = document.getElementById('today-events-list');
  const badgeEl = document.getElementById('today-badge');
  const countEl = document.getElementById('today-count');
  if (!listEl) return;

  const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Dubai' }); // YYYY-MM-DD
  const dayLabel = new Date().toLocaleDateString('ar-AE-u-ca-gregory-nu-latn', { timeZone: 'Asia/Dubai', weekday: 'long', day: 'numeric', month: 'long' });
  const now24h  = Date.now() - 24 * 60 * 60 * 1000;

  const events = (db.events || []).filter(ev => {
    if (!ev.datetime) return false;
    if (ev.datetime.startsWith(today)) return true;
    const t = new Date(ev.datetime).getTime();
    return !isNaN(t) && t >= now24h;
  });

  events.sort((a, b) => (b.datetime || '').localeCompare(a.datetime || ''));
  const shown = events.slice(0, 8);

  if (badgeEl) badgeEl.textContent = 'اليوم ' + dayLabel;
  if (countEl) countEl.textContent = events.length + ' حدث';

  const sevMap = {
    critical:  { color: '#e74c3c', bg: 'rgba(231,76,60,0.15)',  label: 'حرج' },
    high:      { color: '#e67e22', bg: 'rgba(230,126,34,0.15)', label: 'عالي' },
    medium:    { color: '#f1c40f', bg: 'rgba(241,196,15,0.15)', label: 'متوسط' },
    low:       { color: '#27ae60', bg: 'rgba(39,174,96,0.15)',  label: 'منخفض' },
  };

  if (shown.length === 0) {
    listEl.innerHTML = '<div style="text-align:center;padding:20px;color:#555;font-size:0.82rem;">لا أحداث مسجّلة لليوم بعد</div>';
    return;
  }

  const rows = shown.map(ev => {
    const sev  = sevMap[ev.severity] || sevMap.medium;
    const time = ev.datetime ? ev.datetime.slice(11, 16) : '';
    const title = ev.title_ar || ev.title || ev.description || '—';
    return `<div style="display:flex;gap:10px;align-items:flex-start;padding:8px 10px;background:rgba(255,255,255,0.03);border-radius:8px;border-right:3px solid ${sev.color};">
      <span style="font-size:10px;color:#888;white-space:nowrap;margin-top:2px;">${time}</span>
      <span style="flex:1;font-size:0.78rem;color:#e0e0e0;line-height:1.5;">${title}</span>
      <span style="font-size:9px;padding:1px 5px;border-radius:3px;background:${sev.bg};color:${sev.color};">${sev.label}</span>
    </div>`;
  }).join('');

  listEl.innerHTML = `<div style="display:flex;flex-direction:column;gap:6px;">${rows}</div>`;
}

// ─── OIL SPARKLINE ───────────────────────────────────────────────────────────

function renderOilSparkline(oilArr) {
  if (!oilArr || oilArr.length < 2) return;
  const el = document.getElementById('oil-sparkline');
  if (!el) return;
  const vals = oilArr.slice(-8).map(o => parseFloat(o.brent) || 0);
  const min = Math.min(...vals) - 2;
  const max = Math.max(...vals) + 2;
  const w = 80, h = 24;
  const pts = vals.map((v, i) => {
    const x = (i / (vals.length - 1)) * w;
    const y = h - ((v - min) / (max - min)) * h;
    return `${x},${y}`;
  }).join(' ');
  const trend = vals[vals.length - 1] > vals[0] ? '#e74c3c' : '#27ae60';
  el.innerHTML = `<svg width="${w}" height="${h}" style="vertical-align:middle;margin-right:6px;"><polyline points="${pts}" fill="none" stroke="${trend}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
}

// ─── STATS SECTION RENDERERS ─────────────────────────────────────────────────

// Map raw location strings → canonical country
const COUNTRY_MAP = {
  // Iran
  'إيران': 'إيران', 'Iran': 'إيران',
  'إيران (طهران، أصفهان، قم، كرج، كرمانشاه)': 'إيران',
  'طهران': 'إيران', 'أصفهان': 'إيران', 'قم': 'إيران',
  'تهران': 'إيران', 'ناتانز': 'إيران', 'فردو': 'إيران',
  'إيران — المنشآت النووية': 'إيران',
  // Israel
  'إسرائيل': 'إسرائيل', 'Israel': 'إسرائيل',
  'تل أبيب': 'إسرائيل', 'حيفا': 'إسرائيل',
  // UAE
  'الإمارات': 'الإمارات', 'UAE': 'الإمارات',
  'الإمارات — دبي': 'الإمارات', 'دبي': 'الإمارات',
  'أبوظبي': 'الإمارات', 'Abu Dhabi': 'الإمارات',
  'الإمارات — قاعدة الظفرة': 'الإمارات',
  'مطار دبي الدولي — الإمارات': 'الإمارات',
  // Bahrain
  'البحرين': 'البحرين', 'Bahrain': 'البحرين',
  'قاعدة الأسطول الخامس الأمريكي — البحرين': 'البحرين',
  'البحرين — مقر الأسطول الخامس الأمريكي': 'البحرين',
  'مقر الأسطول الخامس الأمريكي — البحرين': 'البحرين',
  'Bahrain — Juffair Naval Base': 'البحرين',
  'البحرين — قاعدة الأسطول الخامس': 'البحرين',
  // Qatar
  'قطر': 'قطر', 'Qatar': 'قطر',
  'قطر — قاعدة العديد الجوية': 'قطر',
  'قاعدة العديد': 'قطر',
  // Kuwait
  'الكويت': 'الكويت', 'Kuwait': 'الكويت',
  'الكويت — Camp Arifjan وقاعدة علي السالم': 'الكويت',
  'مطار الكويت الدولي — الصالة 1': 'الكويت',
  // Saudi Arabia
  'السعودية': 'السعودية', 'Saudi Arabia': 'السعودية', 'KSA': 'السعودية',
  'الرياض والمنطقة الشرقية — المملكة العربية السعودية': 'السعودية',
  'أرامكو': 'السعودية',
  // Jordan
  'الأردن': 'الأردن', 'Jordan': 'الأردن',
  // Iraq
  'العراق': 'العراق', 'Iraq': 'العراق',
  'العراق — القنصلية الأمريكية في أربيل': 'العراق',
  // Cyprus / UK bases
  'قبرص': 'قبرص', 'Cyprus': 'قبرص',
  // Red Sea / Maritime
  'البحر الأحمر': 'البحر الأحمر',
  'الملاحة في البحر الأحمر': 'البحر الأحمر',
  'البحر الأحمر — الملاحة الدولية': 'البحر الأحمر',
  'مضيق هرمز': 'البحر الأحمر',
  'مضيق هرمز / الملاحة الدولية': 'البحر الأحمر',
  'الخليج العربي': 'الخليج العربي',
  // US forces (general)
  'القواعد الأمريكية': 'قواعد أمريكية',
  'القواعد العسكرية الأمريكية': 'قواعد أمريكية',
};

const COUNTRY_META = {
  'إيران':          { flag: '🇮🇷', color: '#e74c3c' },
  'إسرائيل':        { flag: '🇮🇱', color: '#3498db' },
  'الإمارات':       { flag: '🇦🇪', color: '#27ae60' },
  'البحرين':        { flag: '🇧🇭', color: '#e67e22' },
  'قطر':            { flag: '🇶🇦', color: '#9b59b6' },
  'الكويت':         { flag: '🇰🇼', color: '#f39c12' },
  'السعودية':       { flag: '🇸🇦', color: '#1abc9c' },
  'الأردن':         { flag: '🇯🇴', color: '#e67e22' },
  'العراق':         { flag: '🇮🇶', color: '#c0392b' },
  'قبرص':           { flag: '🇨🇾', color: '#7f8c8d' },
  'البحر الأحمر':   { flag: '🌊', color: '#2980b9' },
  'مضيق هرمز':      { flag: '⚓', color: '#2980b9' },
  'الخليج العربي':  { flag: '🌊', color: '#2980b9' },
  'قواعد أمريكية':  { flag: '🇺🇸', color: '#7f8c8d' },
};

const ACTOR_META = {
  'إيران':                   { flag: '🇮🇷', color: '#e74c3c' },
  'الولايات المتحدة وإسرائيل': { flag: '🇺🇸🇮🇱', color: '#3498db' },
  'إسرائيل':                  { flag: '🇮🇱', color: '#2980b9' },
  'الحوثيون':                 { flag: '🇾🇪', color: '#8e44ad' },
  'الولايات المتحدة':          { flag: '🇺🇸', color: '#1abc9c' },
};

const ATTACK_TYPE_META = {
  missile:       { icon: '🚀', label: 'صواريخ',         color: '#e74c3c' },
  airstrike:     { icon: '💥', label: 'غارات جوية',     color: '#e67e22' },
  strike:        { icon: '💥', label: 'ضربات',           color: '#e67e22' },
  missile_attack:{ icon: '🚀', label: 'هجوم صاروخي',    color: '#c0392b' },
  explosion:     { icon: '💢', label: 'انفجارات',        color: '#f39c12' },
  diplomatic:    { icon: '🏛️', label: 'دبلوماسي',       color: '#3498db' },
  threat:        { icon: '⚠️', label: 'تهديدات',        color: '#f39c12' },
  naval:         { icon: '⚓', label: 'بحري',            color: '#2980b9' },
  assassination: { icon: '☠️', label: 'اغتيال',         color: '#8e44ad' },
  interception:  { icon: '✅', label: 'اعتراض',          color: '#27ae60' },
  drone:         { icon: '🛸', label: 'مسيّرات',         color: '#e67e22' },
};

// Keyword patterns for fallback country extraction from title/description
const COUNTRY_KEYWORDS = [
  { keys: ['إيران','Iran','إيراني','الإيراني','الإيرانية','طهران','Tehran','Persian','فارسي'], canonical: 'إيران' },
  { keys: ['إسرائيل','Israel','Israeli','تل أبيب','Tel Aviv','حيفا','Haifa'], canonical: 'إسرائيل' },
  { keys: ['الإمارات','UAE','Emirates','إماراتي','دبي','Dubai','أبوظبي','Abu Dhabi','الظفرة','Al Dhafra'], canonical: 'الإمارات' },
  { keys: ['البحرين','Bahrain','البحريني','Juffair','جفير','الأسطول الخامس','Fifth Fleet'], canonical: 'البحرين' },
  { keys: ['قطر','Qatar','القطري','العديد','Al Udeid'], canonical: 'قطر' },
  { keys: ['الكويت','Kuwait','الكويتي','Arifjan','أريجان','علي السالم'], canonical: 'الكويت' },
  { keys: ['السعودية','Saudi','KSA','الرياض','Riyadh','أرامكو','Aramco','جدة','Jeddah'], canonical: 'السعودية' },
  { keys: ['الأردن','Jordan','الأردني','عمان','Amman'], canonical: 'الأردن' },
  { keys: ['العراق','Iraq','العراقي','بغداد','Baghdad','أربيل','Erbil'], canonical: 'العراق' },
  { keys: ['البحر الأحمر','Red Sea','هرمز','Hormuz','Strait of Hormuz','مضيق هرمز'], canonical: 'البحر الأحمر' },
  { keys: ['الخليج','Gulf','Arabian Gulf','خليج'], canonical: 'الخليج العربي' },
];

function extractCountriesFromText(text) {
  if (!text) return [];
  const found = new Set();
  for (const { keys, canonical } of COUNTRY_KEYWORDS) {
    for (const k of keys) {
      if (text.includes(k)) { found.add(canonical); break; }
    }
  }
  return [...found];
}

function renderStatsSection(events) {
  // ── 1. Targeted Countries ─────────────────────────────────────────
  const countryCounts = {};
  for (const e of events) {
    let locs = [];
    if (Array.isArray(e.targetLocations) && e.targetLocations.length > 0) {
      locs = e.targetLocations;
    } else if (e.target) {
      // Handle multi-country targets like "KSA + Kuwait + UAE" or "البحرين — X"
      locs = e.target.split(/[+\/،,]/).map(s => s.trim()).filter(Boolean);
    }

    const mapped = [];
    for (const loc of locs) {
      // Try exact match first
      const canonical = COUNTRY_MAP[loc] || null;
      if (canonical) {
        mapped.push(canonical);
      } else {
        // Try keyword match on the loc string
        const extracted = extractCountriesFromText(loc);
        mapped.push(...extracted);
      }
    }

    // If still no countries, fallback to title + description keyword scan
    if (mapped.length === 0) {
      const text = (e.title || '') + ' ' + (e.description || '');
      mapped.push(...extractCountriesFromText(text));
    }

    for (const c of mapped) {
      countryCounts[c] = (countryCounts[c] || 0) + 1;
    }
  }

  const sortedCountries = Object.entries(countryCounts).sort((a,b)=>b[1]-a[1]);
  const maxCount = sortedCountries[0]?.[1] || 1;

  const countryHTML = sortedCountries.map(([country, count]) => {
    const meta  = COUNTRY_META[country] || { flag: '🌐', color: '#888' };
    const pct   = Math.round((count / maxCount) * 100);
    return `
      <div class="country-row">
        <span class="cr-flag">${meta.flag}</span>
        <span class="cr-name">${country}</span>
        <div class="cr-bar-wrap">
          <div class="cr-bar" style="width:${pct}%;background:${meta.color};"></div>
        </div>
        <span class="cr-count">${count}</span>
      </div>`;
  }).join('');

  const ccEl = document.getElementById('targeted-countries-container');
  const ccCount = document.getElementById('targeted-countries-count');
  if (ccEl)    ccEl.innerHTML    = countryHTML || '<div style="color:var(--text-muted);font-size:11px;">لا بيانات</div>';
  if (ccCount) ccCount.textContent = sortedCountries.length + ' دولة';

  // ── 2. Attack Types ───────────────────────────────────────────────
  const typeCounts = {};
  for (const e of events) typeCounts[e.type] = (typeCounts[e.type] || 0) + 1;

  // Comprehensive type groups — covers all known raw types
  const mergedTypes = {};
  const typeGroups = {
    'صواريخ':            ['missile','missile_attack','missile_strike','missile_drone_attack','retaliation'],
    'غارات جوية':        ['airstrike','strike','attack','military_action','military','military_operation','military_strike'],
    'مسيّرات':           ['drone','drone_attack'],
    'اعتراض / دفاع':    ['interception'],
    'انفجارات':          ['explosion','impact'],
    'بحري / حصار':       ['naval','maritime','blockade','maritime_closure','closure'],
    'اغتيال / قيادة':   ['assassination','leadership'],
    'مدنيون':            ['civilian_impact','civilian_casualty','casualty','civilian','casualties'],
    'بنية تحتية':        ['infrastructure','infrastructure_damage'],
    'دبلوماسي':          ['diplomatic','political','assessment','statement'],
    'اقتصادي / طاقة':   ['economic','aviation'],
    'تهديدات':           ['threat','alert','uncertainty'],
    'إنساني / إخلاء':   ['evacuation','humanitarian'],
  };
  const typeIcons2 = {
    'صواريخ':'🚀','غارات جوية':'💥','مسيّرات':'🛸','اعتراض / دفاع':'🛡️',
    'انفجارات':'💢','بحري / حصار':'⚓','اغتيال / قيادة':'☠️',
    'مدنيون':'👥','بنية تحتية':'🏗️','دبلوماسي':'🏛️',
    'اقتصادي / طاقة':'💰','تهديدات':'⚠️','إنساني / إخلاء':'🚪',
  };
  const typeColors = {
    'صواريخ':'#e74c3c','غارات جوية':'#e67e22','مسيّرات':'#f39c12',
    'اعتراض / دفاع':'#27ae60','انفجارات':'#e67e22','بحري / حصار':'#2980b9',
    'اغتيال / قيادة':'#8e44ad','مدنيون':'#c0392b','بنية تحتية':'#7f8c8d',
    'دبلوماسي':'#3498db','اقتصادي / طاقة':'#d4ac0d','تهديدات':'#f39c12',
    'إنساني / إخلاء':'#16a085',
  };

  for (const [groupName, rawTypes] of Object.entries(typeGroups)) {
    let total = 0;
    for (const rt of rawTypes) total += typeCounts[rt] || 0;
    if (total > 0) mergedTypes[groupName] = total;
  }
  // Catch anything unmapped
  const coveredTypes = new Set(Object.values(typeGroups).flat());
  let otherCount = 0;
  for (const [t, c] of Object.entries(typeCounts)) {
    if (!coveredTypes.has(t)) otherCount += c;
  }
  if (otherCount > 0) mergedTypes['أخرى'] = otherCount;

  const totalAttacks = Object.values(mergedTypes).reduce((a,b)=>a+b,0);
  const sortedTypes  = Object.entries(mergedTypes).sort((a,b)=>b[1]-a[1]);
  const maxTypeCount = sortedTypes[0]?.[1] || 1;

  const typesHTML = sortedTypes.map(([name, count]) => {
    const pct    = ((count / totalAttacks) * 100).toFixed(0);
    const barPct = Math.round((count / maxTypeCount) * 100);
    const color  = typeColors[name] || '#888';
    return `
      <div class="attack-type-row">
        <span class="at-icon">${typeIcons2[name]||'📌'}</span>
        <span class="at-label">${name}</span>
        <div class="at-bar-wrap">
          <div class="at-bar" style="width:${barPct}%;background:${color};"></div>
        </div>
        <span class="at-count" style="color:${color};">${count}</span>
        <span class="at-pct">${pct}%</span>
      </div>`;
  }).join('');

  const atEl = document.getElementById('attack-types-container');
  const atTotal = document.getElementById('attack-types-total');
  if (atEl)    atEl.innerHTML     = typesHTML || '<div style="color:var(--text-muted);">لا بيانات</div>';
  if (atTotal) atTotal.textContent = totalAttacks + ' حدث';

  // ── 3. Key Actors ─────────────────────────────────────────────────
  const actorCounts = {};
  for (const e of events) {
    if (!e.actor) continue;
    // Normalize actor
    let actor = e.actor;
    if (actor.includes('الحوثي')) actor = 'الحوثيون';
    else if (actor.includes('إيران') || actor === 'Iran' || actor.includes('IRGC') || actor.includes('الحرس الثوري')) actor = 'إيران';
    else if ((actor.includes('الولايات') && actor.includes('إسرائيل')) || actor.includes('US') && actor.includes('Israel')) actor = 'الولايات المتحدة وإسرائيل';
    else if (actor.includes('إسرائيل') || actor === 'Israel') actor = 'إسرائيل';
    else if (actor.includes('الولايات المتحدة') || actor.includes('United States') || actor === 'US' || actor === 'USA') actor = 'الولايات المتحدة';
    else if (actor.includes('البحرية') || actor.includes('Navy')) actor = 'البحرية الأمريكية';
    else actor = 'أطراف أخرى';
    actorCounts[actor] = (actorCounts[actor] || 0) + 1;
  }

  const sortedActors = Object.entries(actorCounts).sort((a,b)=>b[1]-a[1]).slice(0,7);
  const maxActor = sortedActors[0]?.[1] || 1;
  const totalEvents = events.length;

  const actorColors = {
    'إيران':'#e74c3c','الولايات المتحدة وإسرائيل':'#3498db',
    'إسرائيل':'#2980b9','الحوثيون':'#8e44ad',
    'الولايات المتحدة':'#1abc9c','البحرية الأمريكية':'#27ae60',
    'أطراف أخرى':'#7f8c8d',
  };
  const actorFlags = {
    'إيران':'🇮🇷','الولايات المتحدة وإسرائيل':'🇺🇸🇮🇱','إسرائيل':'🇮🇱',
    'الحوثيون':'🇾🇪','الولايات المتحدة':'🇺🇸','البحرية الأمريكية':'🇺🇸',
    'أطراف أخرى':'🌐',
  };

  const actorsHTML = sortedActors.map(([actor, count]) => {
    const pct   = Math.round((count / maxActor) * 100);
    const color = actorColors[actor] || '#888';
    return `
      <div class="actor-row">
        <span class="act-flag">${actorFlags[actor]||'🌐'}</span>
        <span class="act-name">${actor}</span>
        <div class="act-bar-wrap">
          <div class="act-bar" style="width:${pct}%;background:${color};"></div>
        </div>
        <span class="act-count" style="color:${color};">${count}</span>
      </div>`;
  }).join('');

  const acEl = document.getElementById('actors-container');
  const acTotal = document.getElementById('actors-total');
  if (acEl)    acEl.innerHTML    = actorsHTML || '<div style="color:var(--text-muted);">لا بيانات</div>';
  if (acTotal) acTotal.textContent = sortedActors.length + ' طرف';
}

// ══ MISSILE & DRONE TRACKER ════════════════════════════════════════════════
function getLatestDayData(countryData) {
  // Extract latest day values from daily array, fall back to totals
  const daily = countryData?.daily || [];
  if (!daily.length) {
    // No daily breakdown — return totals
    return {
      total:       countryData?.total || 0,
      drones:      countryData?.drones || 0,
      intercepted: countryData?.intercepted || 0,
      hit:         countryData?.hit || 0,
      verified:    countryData?.verified || false,
      pendingWAM:  false,
      note:        ''
    };
  }
  // Get highest day number
  const latest = daily.reduce((a, b) => a.day > b.day ? a : b);
  return {
    total:       (latest.ballistic || 0) + (latest.cruise || 0),
    drones:      latest.drones || 0,
    intercepted: (latest.interceptedM || 0) + (latest.interceptedD || 0),
    hit:         latest.hit || 0,
    verified:    latest.verified || false,
    pendingWAM:  latest.pendingWAM || false,
    note:        latest.source || ''
  };
}
// Legacy alias
const getDay6Data = getLatestDayData;

function renderMissileTracker(stats) {
  const grid = document.getElementById('mtrack-grid');
  const hdr  = document.getElementById('mtrack-header-total');
  if (!grid) return;

  const ms = stats?.missiles || {};
  const ds = stats?.drones   || {};

  const GCC_COUNTRIES = [
    { key: 'الإمارات', flag: '🇦🇪', name: 'الإمارات', cls: 'mtrack-uae' },
    { key: 'السعودية', flag: '🇸🇦', name: 'السعودية', cls: 'mtrack-sa' },
    { key: 'الكويت',   flag: '🇰🇼', name: 'الكويت',   cls: 'mtrack-kw' },
    { key: 'قطر',     flag: '🇶🇦', name: 'قطر',      cls: 'mtrack-qa' },
    { key: 'البحرين', flag: '🇧🇭', name: 'البحرين',   cls: 'mtrack-bh' },
    { key: 'عُمان',   flag: '🇴🇲', name: 'عُمان',    cls: 'mtrack-om' },
  ];

  // Helper: build one card HTML
  function buildMtrackCard(c, m, d) {
    // Use Day 6 data only
    const d6m    = getDay6Data(m);
    // Other countries: show TOTAL cumulative data
    // Use ballistic+cruise for missiles (not .total which may include drones)
    const mTotal = (m.ballistic||0) + (m.cruise||0) || m.total || 0;
    const dTotal = d.total || 0;
    const mInt   = m.interceptedM || m.intercepted || 0;  // missiles-only intercepted
    const dInt   = d.intercepted || 0;
    const mHit   = m.hit || 0;
    const dHit   = d.hit || 0;
    const combined = mTotal + dTotal;
    const combInt  = mInt + dInt;
    const intRate  = combined > 0 ? Math.round(combInt / combined * 100) : 0;
    const verified   = m.verified || d.verified || false;
    const noData     = combined === 0;
    const pendingWAM = m.pendingWAM || d.pendingWAM || false;
    return { mTotal, dTotal, combined, combInt, intRate, verified, noData, mHit, dHit, m, d,
      html: `<div class="mtrack-country ${c.cls||''}" title="${(m.note||d.note||'').replace(/"/g,"'")}">
      <div class="mtrack-flag">${c.flag}</div>
      <div class="mtrack-name">${c.name}${pendingWAM ? ' <span style="font-size:8px;color:#f39c12;font-weight:normal;">⏳WAM</span>' : ''}</div>
      <div class="mtrack-divider"></div>
      <div class="mtrack-row">
        <span class="mtrack-lbl">🚀 صواريخ</span>
        <span class="mtrack-val" style="color:#e74c3c">${noData && !mTotal ? '—' : mTotal.toLocaleString('en-US')}</span>
      </div>
      <div class="mtrack-row">
        <span class="mtrack-lbl">🛸 مسيّرات</span>
        <span class="mtrack-val" style="color:#e67e22">${noData && !dTotal ? '—' : dTotal.toLocaleString('en-US')}</span>
      </div>
      <div class="mtrack-divider"></div>
      <div class="mtrack-row">
        <span class="mtrack-lbl">🛡️ اعتُرض</span>
        <span class="mtrack-val" style="color:#27ae60;font-size:11px">${noData ? '—' : verified ? combInt.toLocaleString('en-US') : '—'}</span>
      </div>
      <div class="mtrack-row">
        <span class="mtrack-lbl">💥 إصابات</span>
        <span class="mtrack-val" style="color:${(mHit+dHit)>0?'#e74c3c':'#888'};font-size:11px">${noData ? '—' : (mHit+dHit)>0 ? (mHit+dHit).toLocaleString('en-US') + (verified?'':' ~') : '0'}</span>
      </div>
      ${!noData && verified ? `
      <div class="mtrack-rate-bar">
        <div class="mtrack-rate-fill" style="width:${intRate}%;background:${intRate>=90?'#27ae60':intRate>=70?'#f39c12':'#e74c3c'}"></div>
      </div>
      <div style="text-align:center;font-size:9px;color:#888;margin-top:3px;">${intRate}% اعتراض</div>
      ` : '<div style="text-align:center;font-size:9px;color:#444;margin-top:8px;">' + (noData ? 'لا أرقام رسمية' : 'بيانات غير مؤكدة رسمياً') + '</div>'}
      <span class="mtrack-verified ${verified ? 'mv-yes' : 'mv-no'}">${verified ? '✔ رسمي' : '◈ غير مؤكد'}</span>
    </div>`
    };
  }

  let totalMissiles = 0, totalDrones = 0;

  // ── UAE Special Card (today + expandable daily table) ────────────────────
  function buildUAECard(m, d) {
    const daily = m.daily || [];
    const latest = daily[daily.length - 1] || {};
    const latestM = (latest.ballistic||0) + (latest.cruise||0);
    const latestD = latest.drones || 0;
    const latestInt = (latest.interceptedM||0) + (latest.interceptedD||0);
    const latestHit = latest.hit || 0;
    const latestIntRate = (latestM+latestD) > 0 ? Math.round(latestInt/(latestM+latestD)*100) : 0;
    const latestSrcColor = latest.verified ? '#27ae60' : '#f39c12';

    // Show ballistic-only as headline (WAM reports 285 ballistic + 15 cruise separately)
    const mBallistic = m.ballistic || m.total || 0;
    const mCruise    = m.cruise || 0;
    // Fix: m.total in DB = missiles+drones combined (bug). Use ballistic+cruise only
    const mTotal = (m.ballistic||0) + (m.cruise||0) || (m.total||0);
    const dTotal = d.total || 0;
    const intRate = Math.round(((m.interceptedM||m.intercepted||0)+(d.intercepted||0)) / Math.max(mTotal+dTotal,1) * 100);
    const pendingBadge = latest.pendingWAM ? '<span style="font-size:9px;color:#f39c12;">⏳ WAM</span>' : '';

    // Full daily table rows
    const maxM  = Math.max(...daily.map(r => r.ballistic + (r.cruise||0)), 1);
    const maxD  = Math.max(...daily.map(r => r.drones), 1);
    const rows = daily.map(r => {
      const rM = r.ballistic + (r.cruise||0);
      const mPct = Math.round(rM / maxM * 100);
      const dPct = Math.round(r.drones / maxD * 100);
      const sc = r.verified ? '#27ae60' : r.source.includes('⏳') ? '#f39c12' : '#888';
      return `<tr style="border-bottom:1px solid rgba(255,255,255,0.04);">
        <td style="padding:4px 8px;font-size:10px;text-align:center;"><span style="color:#e74c3c;font-weight:700;">Y${r.day}</span></td>
        <td style="padding:4px 8px;color:#aaa;font-size:10px;white-space:nowrap;">${r.date}</td>
        <td style="padding:4px 10px;min-width:100px;">
          <div style="display:flex;align-items:center;gap:5px;">
            <div style="flex:1;background:rgba(231,76,60,0.12);border-radius:3px;height:7px;overflow:hidden;"><div style="width:${mPct}%;height:100%;background:#e74c3c;border-radius:3px;"></div></div>
            <span style="color:#e74c3c;font-size:10px;font-weight:700;min-width:20px;text-align:right;">${rM||'—'}</span>
          </div>
        </td>
        <td style="padding:4px 10px;min-width:100px;">
          <div style="display:flex;align-items:center;gap:5px;">
            <div style="flex:1;background:rgba(230,126,34,0.12);border-radius:3px;height:7px;overflow:hidden;"><div style="width:${dPct}%;height:100%;background:#e67e22;border-radius:3px;"></div></div>
            <span style="color:#e67e22;font-size:10px;font-weight:700;min-width:20px;text-align:right;">${r.drones||'—'}</span>
          </div>
        </td>
        <td style="padding:4px 8px;color:#27ae60;font-size:10px;text-align:center;">${(r.interceptedM||0)+(r.interceptedD||0)||'—'}</td>
        <td style="padding:4px 8px;color:${(r.hit||0)>0?'#e74c3c':'#555'};font-size:10px;text-align:center;">${r.hit||'0'}</td>
        <td style="padding:4px 8px;font-size:9px;color:${sc};text-align:center;" title="${r.source}">${r.verified?'✔':'⏳'}</td>
      </tr>`;
    }).join('');

    const cardId = 'uae-expand-' + Date.now();
    return `<div style="grid-column:1/-1;background:rgba(231,76,60,0.04);border:1px solid rgba(231,76,60,0.2);border-radius:10px;padding:14px 16px;position:relative;overflow:hidden;">
      <div style="position:absolute;bottom:0;left:0;right:0;height:2px;background:linear-gradient(90deg,#e74c3c,#27ae60,#000);"></div>

      <!-- Header row -->
      <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px;">
        <span style="font-size:1.6rem;">🇦🇪</span>
        <div>
          <div style="font-size:0.85rem;font-weight:800;color:#fff;">الإمارات العربية المتحدة</div>
          <div style="font-size:9px;color:#777;">الإجمالي التراكمي — اليوم 1–${daily.length} منذ 28 فبراير 2026</div>
        </div>
        <div style="margin-right:auto;display:flex;gap:14px;flex-wrap:wrap;">
          <div style="text-align:center;"><div style="font-size:1rem;font-weight:800;color:#e74c3c;">${mBallistic}</div><div style="font-size:8px;color:#666;">باليستي${mCruise>0?'<span style="color:#888;font-size:7px;"> +'+mCruise+' كروز</span>':''}</div></div>
          <div style="text-align:center;"><div style="font-size:1rem;font-weight:800;color:#e67e22;">${dTotal}</div><div style="font-size:8px;color:#666;">مسيّرات الكلي</div></div>
          <div style="text-align:center;"><div style="font-size:1rem;font-weight:800;color:#27ae60;">${intRate}%</div><div style="font-size:8px;color:#666;">اعتراض تراكمي</div></div>
        </div>
      </div>

      <!-- TODAY SUMMARY (default visible) -->
      <div style="background:rgba(231,76,60,0.08);border:1px solid rgba(231,76,60,0.25);border-radius:8px;padding:12px 14px;margin-bottom:10px;">
        <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:10px;">
          <div style="display:flex;align-items:center;gap:8px;">
            <span style="background:#e74c3c;color:#fff;font-size:9px;font-weight:700;padding:2px 8px;border-radius:10px;">⚔️ اليوم ${latest.day} — ${latest.date}</span>
            ${pendingBadge}
            <span style="font-size:9px;color:${latestSrcColor};">${latest.verified?'✔ رسمي':'⏳ غير مؤكد'}</span>
          </div>
          <button onclick="(function(){var t=document.getElementById('${cardId}');var b=document.getElementById('${cardId}-btn');var open=t.style.display!=='none';t.style.display=open?'none':'block';b.textContent=open?'📊 عرض كل الأيام':'🔼 إخفاء';b.style.background=open?'rgba(255,255,255,0.06)':'rgba(231,76,60,0.15)';})()"
            id="${cardId}-btn"
            style="background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.12);color:#aaa;font-size:10px;padding:4px 12px;border-radius:8px;cursor:pointer;font-family:'Cairo',sans-serif;transition:all 0.2s;">
            📊 عرض كل الأيام
          </button>
        </div>
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;text-align:center;">
          <div><div style="font-size:1.4rem;font-weight:900;color:#e74c3c;">${latestM||'—'}</div><div style="font-size:9px;color:#777;">🚀 صواريخ</div></div>
          <div><div style="font-size:1.4rem;font-weight:900;color:#e67e22;">${latestD||'—'}</div><div style="font-size:9px;color:#777;">🛸 مسيّرات</div></div>
          <div><div style="font-size:1.4rem;font-weight:900;color:#27ae60;">${latestInt||'—'}</div><div style="font-size:9px;color:#777;">🛡️ اعتُرض</div></div>
          <div><div style="font-size:1.4rem;font-weight:900;color:${latestHit>0?'#e74c3c':'#555'}">${latestHit}</div><div style="font-size:9px;color:#777;">💥 إصابات</div></div>
        </div>
        <div style="margin-top:8px;background:rgba(255,255,255,0.04);border-radius:4px;height:6px;overflow:hidden;">
          <div style="width:${latestIntRate}%;height:100%;background:linear-gradient(90deg,#27ae60,#2ecc71);border-radius:4px;"></div>
        </div>
        <div style="font-size:9px;text-align:center;margin-top:3px;">
          <span style="color:${latestIntRate>=95?'#27ae60':'#f39c12'};font-weight:700;">${latestIntRate}%</span>
          <span style="color:#555;"> نسبة الاعتراض اليوم ${latest.day}</span>
          &nbsp;|&nbsp;
          <span style="color:#555;">تراكمي: </span><span style="color:#888;">${intRate}%</span>
        </div>
      </div>

      <!-- EXPANDABLE DAILY TABLE (hidden by default) -->
      <div id="${cardId}" style="display:none;">
        <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;font-family:'Cairo',sans-serif;">
          <thead>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.1);">
              <th style="padding:4px 8px;color:#555;font-size:9px;text-align:center;">يوم</th>
              <th style="padding:4px 8px;color:#555;font-size:9px;text-align:right;">التاريخ</th>
              <th style="padding:4px 8px;color:#e74c3c;font-size:9px;">🚀 صواريخ</th>
              <th style="padding:4px 8px;color:#e67e22;font-size:9px;">🛸 مسيّرات</th>
              <th style="padding:4px 8px;color:#27ae60;font-size:9px;text-align:center;">🛡️ اعتُرض</th>
              <th style="padding:4px 8px;color:#e74c3c;font-size:9px;text-align:center;">💥 أصاب</th>
              <th style="padding:4px 8px;color:#555;font-size:9px;text-align:center;">مصدر</th>
            </tr>
          </thead>
          <tbody>${rows}</tbody>
        </table>
        </div>
        <div style="margin-top:6px;font-size:8px;color:#444;">✔ = مؤكد رسمياً &nbsp;|&nbsp; ⏳ = بانتظار WAM</div>
      </div>
    </div>`;
  }

  const uaeSpecialCard = buildUAECard(ms.byCountry?.['الإمارات'] || {}, ds.byCountry?.['الإمارات'] || {});

  // ── GCC cards (without UAE — handled above) — hidden in UAE local view ────
  const GCC_NO_UAE = GCC_COUNTRIES.filter(c => c.key !== 'الإمارات');
  const gccCards = GCC_NO_UAE.map(c => {
    const r = buildMtrackCard(c, ms.byCountry?.[c.key] || {}, ds.byCountry?.[c.key] || {});
    totalMissiles += r.mTotal; totalDrones += r.dTotal;
    return r.html;
  });
  // Add UAE cumulative totals
  totalMissiles += ms.byCountry?.['الإمارات']?.ballistic || ms.byCountry?.['الإمارات']?.total || 0;
  totalDrones   += ds.byCountry?.['الإمارات']?.total || 0;

  // ── Israel card (ms.israel / ds.israel) ──────────────────────────────────
  const ilM = ms.israel || {};
  const ilD = ds.israel || {};
  const ilCard = buildMtrackCard(
    { flag: '🇮🇱', name: 'إسرائيل', cls: 'mtrack-il' },
    { total: ilM.total||0, intercepted: ilM.intercepted||0, hit: ilM.hit||0, verified: ilM.verified||false, note: ilM.note||'' },
    { total: ilD.total||0, intercepted: ilD.intercepted||0, hit: ilD.hit||0, verified: ilD.verified||false, note: ilD.note||'' }
  );

  // ── Jordan card (ms.otherCountries.الأردن) ────────────────────────────────
  const joM = ms.otherCountries?.['الأردن'] || {};
  const joD = ds.otherCountries?.['الأردن'] || {};
  const joCard = buildMtrackCard(
    { flag: '🇯🇴', name: 'الأردن', cls: 'mtrack-jo' },
    { total: joM.total||0, intercepted: joM.intercepted||0, hit: joM.hit||0, verified: joM.verified||false, note: joM.note||'' },
    { total: joD.total||0, intercepted: joD.intercepted||0, hit: joD.hit||0, verified: joD.verified||false, note: joD.note||'' }
  );

  // ── Divider row between GCC and others ────────────────────────────────────
  const sectionDivider = `<div style="grid-column:1/-1;border-top:1px solid rgba(255,255,255,0.06);margin:4px 0;padding-top:6px;font-size:9px;color:#555;text-align:right;padding-right:4px;">دول أخرى مستهدفة</div>`;

  grid.innerHTML = uaeSpecialCard + '<div class="hide-in-uae" id="gcc-other-cards">' + gccCards.join('') + sectionDivider + ilCard.html + joCard.html + '</div>';

  // ── UAE daily card — also render in UAE local view section ────────────────
  const uaeDailySection = document.getElementById('uae-daily-card-section');
  if (uaeDailySection) {
    uaeDailySection.innerHTML =
      '<div style="font-size:13px;font-weight:800;color:#D4AF37;border-right:3px solid #D4AF37;padding-right:10px;margin-bottom:12px;">📊 الضربات اليومية على الإمارات — يوم بيوم</div>' +
      uaeSpecialCard;
  }

  // Update day badge dynamically
  const WAR_START_D = new Date('2026-02-28T00:00:00+04:00');
  const autoDay = Math.max(1, Math.floor((Date.now() - WAR_START_D.getTime()) / 86400000) + 1);
  const latestDay = Math.max(autoDay, ms.byCountry?.['الإمارات']?.daily?.reduce((a,b) => a.day>b.day?a:b, {day:0})?.day || 1);
  const badge = document.getElementById('mtrack-day-badge');
  if (badge) badge.textContent = `⚔️ اليوم ${latestDay}`;
  if (hdr) {
    hdr.textContent = `اليوم ${latestDay}: ${totalMissiles.toLocaleString('en-US')} صاروخ · ${totalDrones.toLocaleString('en-US')} مسيّرة`;
  }
}

function canonicalType(raw) {
  return TYPE_CANONICAL[raw] || raw || 'other';
}

function matchesFilter(e, filter) {
  if (filter === 'all') return true;
  // ── فلاتر التأكيد الجديدة ────────────────────────────────────────────────
  if (filter === 'verified') {
    // مؤكد = Tier 1 رسمي أو مصدرين أو verified=true
    return e.verified ||
           e.confirmStatus === 'official' ||
           e.confirmStatus === 'cross-verified' ||
           (e.sources || []).length >= 2;
  }
  if (filter === 'official') {
    // رسمي = Tier 1 فقط
    return e.confirmStatus === 'official' ||
           (e.sources || []).some(s => s.tier === 1);
  }
  // ── فلاتر النوع المعتادة ─────────────────────────────────────────────────
  const raw = e.type || 'other';
  const group = FILTER_GROUPS[filter];
  if (group) return group.includes(raw) || group.includes(canonicalType(raw));
  return raw === filter || canonicalType(raw) === filter;
}

function matchesSearch(e, query) {
  if (!query) return true;
  const q = query.trim().toLowerCase();
  const text = [e.actor||'', e.target||'', (e.targetLocations||[]).join(' '), e.description||''].join(' ').toLowerCase();
  return text.includes(q);
}

function getTypeBadgeClass(raw, canon) {
  const military = ['strike','airstrike','missile','drone','explosion','retaliation','interception','assassination','military'];
  const oil = ['maritime','naval','blockade'];
  const diplo = ['diplomatic','political','evacuation'];
  const intel = ['threat','alert','uncertainty'];
  const economic = ['economic'];
  if (military.includes(raw) || military.includes(canon)) return 'type-military';
  if (oil.includes(raw) || oil.includes(canon)) return 'type-oil';
  if (diplo.includes(raw) || diplo.includes(canon)) return 'type-diplo';
  if (intel.includes(raw) || intel.includes(canon)) return 'type-intel';
  if (economic.includes(raw) || economic.includes(canon)) return 'type-economic';
  return '';
}

function buildEventHTML(e, search) {
  const raw   = e.type || 'other';
  const canon = canonicalType(raw);
  const icon  = typeIcons[raw] || typeIcons[canon] || '📌';
  const label = typeLabels[raw] || typeLabels[canon] || raw;
  const typeBadgeClass = getTypeBadgeClass(raw, canon);

  // Headline: prefer title, fallback to actor→target
  const headline = e.title?.trim() ||
    (e.actor && e.actor !== '—' ? `${e.actor} → ${e.target || '—'}` : '');

  let desc = e.description || '';
  if (search) {
    const re = new RegExp(`(${search.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')})`, 'gi');
    desc  = desc.replace(re,  '<mark style="background:rgba(243,156,18,0.3);border-radius:2px;">$1</mark>');
  }

  // Source badge
  const src    = Array.isArray(e.sources) ? e.sources[0] : null;
  const srcName = src?.name || e.source || '';
  const srcUrl  = src?.url  || '';
  const srcTier = src?.tier || 5;
  const tierColor = srcTier === 1 ? '#e74c3c' : srcTier === 2 ? '#e67e22' : srcTier <= 3 ? '#3498db' : '#7f8c8d';
  // Date guard on source URL — warn if link is from 2025 or earlier
  const srcUrlOldYear = srcUrl && /\/(201[0-9]|202[0-5])\//.test(srcUrl);
  const srcUrlYear    = srcUrlOldYear ? (srcUrl.match(/\/(20\d{2})\//)||[])[1] : null;
  const srcBadge = srcName
    ? `<a href="${srcUrl}" target="_blank" rel="noopener"
         class="tl-source" style="color:${srcUrlOldYear ? '#e74c3c' : tierColor};"
         title="${srcUrlOldYear ? '⚠️ رابط من ' + srcUrlYear + ' — قد لا يكون مرتبطاً بالأزمة الحالية' : srcUrl}"
         >${srcUrlOldYear ? '⚠️ ' : ''}${srcName}${srcUrlOldYear ? ' (' + srcUrlYear + ')' : ''}</a>`
    : '';

  // Language flag
  const langFlag = e.lang === 'ar' ? '' : (srcName ? '<span class="tl-lang-en">EN</span>' : '');

  // "جديد" badge — events < 2h old
  const ageMs  = Date.now() - new Date(e.datetime).getTime();
  const isNew  = ageMs < 2 * 3600 * 1000;
  const newBadge = isNew ? '<span class="tl-new">جديد</span>' : '';

  // Severity dot color
  const sev = e.severity || (e.verified ? 'medium' : 'low');
  const sevColor = { critical:'#e74c3c', high:'#e67e22', medium:'#f39c12', low:'#95a5a6' }[sev] || '#95a5a6';

  return `
  <div class="tl-item sev-${sev}" data-type="${raw}" style="border-right-color:${sevColor};">
    <div class="tl-dot ${raw} ${canon}">${icon}</div>
    <div class="tl-body">
      <div class="tl-meta-row">
        <span class="tl-time" title="${e.hasRealTime === false ? 'تاريخ مُقدَّر' : 'تاريخ من المصدر'}">${formatTime(e.datetime)}${e.hasRealTime === false ? ' ⏱' : ''}</span>
        <span class="tl-type-badge ${typeBadgeClass}">${icon} ${label}</span>
        ${newBadge}
        ${langFlag}
      </div>
      ${headline ? `<div class="tl-title">${headline}</div>` : ''}
      <div class="tl-desc">${desc}</div>
      ${e.casualties?.killed ? `<div class="tl-casualties">☠️ ${e.casualties.killed} قتيل${e.casualties.injured ? ' · 🩹 ' + e.casualties.injured + ' جريح' : ''}</div>` : ''}
      <div class="tl-footer-row">
        ${srcBadge}
        ${(() => {
          const cs = e.confirmStatus;
          const cnt = e.confirmCount || (e.sources?.length || 1);
          const allSrcs = (e.sources||[]).slice(1).map(s=>s.name).filter(Boolean).join(' · ');
          if (cs === 'official' || (src?.tier === 1)) {
            return `<span class="tl-verified yes" title="مصدر رسمي حكومي — يُعتمد بمصدر واحد">🏛️ رسمي مؤكد</span>`;
          } else if (cs === 'cross-verified' || cnt >= 2 || (e.sources||[]).length >= 2) {
            const extra = allSrcs ? ` · ${allSrcs}` : '';
            return `<span class="tl-verified yes" title="مؤكد من ${cnt} مصادر مستقلة${extra}">✅ مؤكد · ${cnt} مصادر</span>`;
          } else if (e.verified) {
            return `<span class="tl-verified yes" title="موثّق من مصدر موثوق">✓ موثّق</span>`;
          } else {
            return `<span class="tl-verified no" title="مصدر واحد فقط — بانتظار تأكيد">⚠️ مصدر واحد</span>`;
          }
        })()}
      </div>
    </div>
  </div>`;
}

function renderTimeline(events, filter = 'all', search = '', page = 1) {
  const container = document.getElementById('timeline-container');
  timelinePage = page;

  // ⚡ v7: Cache key — يُبطل الكاش عند أي تغيير في الفلتر أو البحث أو التوقيت
  const cacheKey = `${filter}|${search}|${currentTimeFilter}|${currentSourceFilter}|${events.length}`;

  let sorted;
  if (_sortedEventsCache && _sortedFilterKey === cacheKey) {
    // ✅ استخدام الكاش المحفوظ (لا إعادة فرز)
    sorted = _sortedEventsCache;
  } else {
    // Skip empty events (no description and no title)
    let filtered = applyTimeFilter(events).filter(e =>
      (e.description?.trim() || e.title?.trim()) &&
      matchesFilter(e, filter) &&
      matchesSource(e, currentSourceFilter) &&
      matchesSearch(e, search)
    );
    // Sort by addedAt (cron time) first, fallback to datetime (pubDate) — newest at top
    sorted = [...filtered].sort((a, b) => {
      const ta = new Date(a.addedAt || a.datetime || 0).getTime();
      const tb = new Date(b.addedAt || b.datetime || 0).getTime();
      return tb - ta;
    });
    // حفظ الكاش
    _sortedEventsCache = sorted;
    _sortedFilterKey   = cacheKey;
    _dateCountsCache   = null; // بطّل dateCounts عند تغيير الفلتر
  }

  if (!sorted.length) {
    container.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:30px;font-size:12px;">لا نتائج</div>`;
    return;
  }

  const visible = sorted.slice(0, page * PAGE_SIZE);
  const remaining = sorted.length - visible.length;

  // ⚡ v7: dateCounts — يُحسب مرة واحدة ويُخزّن
  if (!_dateCountsCache) {
    _dateCountsCache = {};
    sorted.forEach(e => {
      const d = formatDate(e.datetime);
      _dateCountsCache[d] = (_dateCountsCache[d] || 0) + 1;
    });
  }
  const dateCounts = _dateCountsCache;

  let html = '';
  let lastDate = '';
  visible.forEach(e => {
    const dateStr = formatDate(e.datetime);
    if (dateStr !== lastDate) {
      const cnt = dateCounts[dateStr] || 0;
      const grpAll = sorted.filter(x => formatDate(x.datetime) === dateStr);
      const critical = grpAll.filter(x => x.severity === 'critical').length;
      const high     = grpAll.filter(x => x.severity === 'high').length;
      const medium   = grpAll.filter(x => x.severity === 'medium').length;
      const low      = grpAll.filter(x => (x.severity||'low') === 'low').length;
      const sevPills = [];
      if (critical) sevPills.push(`<span style="background:rgba(231,76,60,0.18);color:#e74c3c;border:1px solid rgba(231,76,60,0.4);padding:1px 6px;border-radius:10px;font-size:9px;font-weight:800;">🔴 حرج ${critical}</span>`);
      if (high)     sevPills.push(`<span style="background:rgba(230,126,34,0.15);color:#e67e22;border:1px solid rgba(230,126,34,0.35);padding:1px 6px;border-radius:10px;font-size:9px;font-weight:800;">🟠 عالي ${high}</span>`);
      if (medium)   sevPills.push(`<span style="background:rgba(243,156,18,0.12);color:#f39c12;border:1px solid rgba(243,156,18,0.3);padding:1px 6px;border-radius:10px;font-size:9px;font-weight:800;">🟡 متوسط ${medium}</span>`);
      // Day of week in Arabic
      const dow = (() => {
        try {
          const d = new Date(e.datetime || dateStr);
          return d.toLocaleDateString('ar-AE-u-ca-gregory-nu-latn', { weekday: 'long', timeZone: 'Asia/Dubai' });
        } catch { return ''; }
      })();
      // Border color based on worst severity of the day
      const dayBorderColor = critical ? '#e74c3c' : high ? '#e67e22' : medium ? '#f39c12' : '#444';
      const dayBg = critical ? 'rgba(231,76,60,0.10)' : high ? 'rgba(230,126,34,0.08)' : medium ? 'rgba(243,156,18,0.06)' : 'rgba(255,255,255,0.02)';
      html += `<div class="tl-date-divider" style="border-color:${dayBorderColor};background:linear-gradient(135deg,${dayBg} 0%,rgba(255,255,255,0.01) 100%);">
        <div class="tl-date-label" style="flex-wrap:wrap;gap:4px;">
          <span>📅 ${dateStr}</span>
          ${dow ? `<span style="font-size:9px;color:var(--text-muted);font-weight:600;">${dow}</span>` : ''}
          ${sevPills.length ? `<span style="display:flex;gap:3px;flex-wrap:wrap;">${sevPills.join('')}</span>` : ''}
        </div>
        <span class="tl-date-count" style="border-color:${dayBorderColor};color:${dayBorderColor};">${cnt} حدث</span>
      </div>`;
      lastDate = dateStr;
    }
    html += buildEventHTML(e, search);
  });

  // "Load more" button
  if (remaining > 0) {
    html += `<div style="text-align:center;padding:12px 0;">
      <button onclick="loadMoreTimeline()" style="
        background:var(--border);border:1px solid var(--border);color:var(--text-muted);
        padding:7px 20px;border-radius:8px;cursor:pointer;font-family:'Cairo',sans-serif;font-size:12px;">
        ⬇️ تحميل ${Math.min(remaining, PAGE_SIZE)} حدث إضافي (${remaining} متبقي)
      </button>
    </div>`;
  }

  container.innerHTML = html;
}

function loadMoreTimeline() {
  renderTimeline(allEvents, currentFilter, currentSearch, timelinePage + 1);
  // Restore scroll position to bottom of current content
  const c = document.getElementById('timeline-container');
  if (c) c.scrollTop = c.scrollHeight - 600;
}

function exportTimelineCSV() {
  // Get current filtered events
  let filtered = applyTimeFilter(allEvents).filter(e =>
    (e.description?.trim() || e.title?.trim()) &&
    matchesFilter(e, currentFilter) &&
    matchesSource(e, currentSourceFilter) &&
    matchesSearch(e, currentSearch)
  );
  const sorted = [...filtered].sort((a, b) =>
    new Date(b.addedAt || b.datetime || 0) - new Date(a.addedAt || a.datetime || 0)
  );

  const escCSV = v => {
    if (v === null || v === undefined) return '';
    const s = String(v).replace(/"/g, '""');
    return s.includes(',') || s.includes('"') || s.includes('\n') ? `"${s}"` : s;
  };

  const headers = ['التاريخ','الوقت','النوع','الخطورة','العنوان','الوصف','الفاعل','الهدف','المصدر','الرابط','مؤكد'];
  const rows = sorted.map(e => {
    const d = new Date(e.datetime);
    const src = Array.isArray(e.sources) ? e.sources[0] : null;
    return [
      d.toLocaleDateString('ar-AE-u-ca-gregory-nu-latn', { timeZone: 'Asia/Dubai' }),
      d.toLocaleTimeString('ar-AE-u-ca-gregory-nu-latn', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Dubai' }),
      typeLabels[e.type] || e.type || '',
      { critical: 'حرج', high: 'عالي', medium: 'متوسط', low: 'منخفض' }[e.severity] || e.severity || '',
      e.title || '',
      (e.description || '').replace(/\n/g, ' ').substring(0, 300),
      e.actor || '',
      e.target || '',
      src?.name || e.source || '',
      src?.url || '',
      e.verified ? 'نعم' : 'لا'
    ].map(escCSV).join(',');
  });

  const bom = '\uFEFF'; // UTF-8 BOM for Excel Arabic support
  const csv = bom + [headers.join(','), ...rows].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `war-monitor-${new Date().toISOString().slice(0,10)}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

function renderStatements(statements) {
  const container = document.getElementById('statements-container');
  const actorClass = (actor) => {
    if (!actor) return 'intl';
    if (actor.includes('Iran') || actor.includes('IRGC')) return 'iran';
    if (actor.includes('GCC') || actor.includes('UAE') || actor.includes('Saudi') || actor.includes('Qatar') ||
        actor.includes('إمارات') || actor.includes('خليج') || actor.includes('دفاع') || actor.includes('القوات')) return 'gcc';
    if (actor.includes('Houthi') || actor.includes('حوثي')) return 'houthi';
    return 'intl';
  };

  // Sort newest first
  const sorted = [...statements].sort((a, b) => new Date(b.datetime) - new Date(a.datetime));

  container.innerHTML = sorted.map(s => {
    const actor = s.actor || s.speaker || s.who || '—';
    const dt    = s.datetime || s.date || s.time || '';
    return `
    <div class="stmt-item ${actorClass(actor)}">
      <div class="stmt-header">
        <span class="stmt-actor">${actor}</span>
        <span class="stmt-time">${dt ? formatDate(dt)+' '+formatTime(dt) : '—'}</span>
      </div>
      <div class="stmt-text">"${s.text || s.content || '—'}"</div>
    </div>`;
  }).join('');
}

function toggleLeadersList() {
  const el = document.getElementById('ops-leaders-list');
  if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
}

function renderOffensiveOps(ops) {
  if (!ops) return;
  const set = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined) el.textContent = val; };
  const html = (id, val) => { const el = document.getElementById(id); if (el && val !== undefined) el.innerHTML = val; };

  // ── Day Counter ──────────────────────────────────────────────────────────
  if (ops.startDate) {
    const start = new Date(ops.startDate);
    const now   = new Date();
    const days  = Math.floor((now - start) / 86400000) + 1;
    set('ops-day-counter', 'Day ' + days);
  } else if (ops.daysActive) {
    set('ops-day-counter', 'Day ' + ops.daysActive);
  }

  // ── President Statement ──────────────────────────────────────────────────
  if (ops.presidentStatement) {
    const stmtEl = document.getElementById('ops-president-stmt');
    if (stmtEl) stmtEl.innerHTML = '🇺🇸 تصريح الرئيس: <strong style="color:#eee;">"' + ops.presidentStatement + '"</strong>';
  }

  // ── KPI Row 1 ────────────────────────────────────────────────────────────
  set('ops-total-targets', (ops.combined?.totalTargetsHit || 0).toLocaleString('en-US') + '+');
  set('ops-sorties',       (ops.israel?.sortiesTotal || ops.israel?.sortiesDay2 || 0).toLocaleString('en-US'));
  set('ops-ships',         (ops.combined?.shipsDestroyed || '—') + (ops.combined?.submarineDestroyed ? '+ غواصة' : ''));
  set('ops-leaders',       ops.combined?.leadersKilled?.length || '—');
  set('ops-nuclear',       ops.combined?.facilitiesDestroyed?.nuclear?.length || '—');

  // ── KPI Row 2 ────────────────────────────────────────────────────────────
  if (ops.combined?.irgcKilled)             set('ops-irgc-kpi',      (ops.combined.irgcKilled).toLocaleString('en-US') + '+');
  if (ops.israel?.airDefensesDestroyed)     set('ops-airdef-kpi',    ops.israel.airDefensesDestroyed + '+');
  if (ops.israel?.ballisticMissilesDestroyed) set('ops-ballistic-kpi', ops.israel.ballisticMissilesDestroyed + '+');
  if (ops.us?.troopsDeployed)               set('ops-troops-kpi',    (ops.us.troopsDeployed).toLocaleString('en-US') + '+');
  if (ops.us?.carriers)                     set('ops-carriers-kpi',  ops.us.carriers);

  // ── Leaders Killed list ──────────────────────────────────────────────────
  const leadersEl = document.getElementById('ops-leaders-items');
  if (leadersEl && ops.combined?.leadersKilled?.length) {
    leadersEl.innerHTML = ops.combined.leadersKilled.map(l =>
      `<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:5px;font-size:0.72rem;">
        <span style="color:#e74c3c;font-weight:700;">☠</span>
        <span><strong style="color:#eee;">${l.name}</strong>
        <span style="color:#9b59b6;"> — ${l.title}</span>
        <span style="color:#555;font-size:0.62rem;margin-right:4px;">${l.date || ''}</span></span>
      </div>`
    ).join('');
  }

  // ── Status Badge ─────────────────────────────────────────────────────────
  const badge = document.getElementById('ops-status-badge');
  if (badge && ops.status === 'ongoing') badge.textContent = '⚡ جارية';

  // ── US Platforms ─────────────────────────────────────────────────────────
  const usPlatEl = document.getElementById('ops-us-platforms');
  if (usPlatEl && ops.us?.platforms) {
    usPlatEl.innerHTML = ops.us.platforms
      .map(p => `<div style="display:flex;align-items:flex-start;gap:4px;margin-bottom:3px;">
        <span style="color:#5dade2;min-width:16px;">✈</span>
        <span><strong style="color:#eee;">${p.name}</strong> — <span style="color:#aaa;">${p.role}</span></span>
      </div>`).join('') +
      `<div style="margin-top:5px;font-size:0.67rem;color:#777;">📍 القواعد: ${(ops.us.bases||[]).slice(0,3).join(' · ')}</div>`;
  }

  // ── US Weapons ───────────────────────────────────────────────────────────
  const weaponsEl = document.getElementById('ops-us-weapons');
  if (weaponsEl && ops.us?.weapons?.length) {
    weaponsEl.innerHTML = ops.us.weapons
      .map(w => `<div style="display:flex;gap:5px;"><span style="color:#e67e22;">▸</span><span>${w}</span></div>`)
      .join('');
  }

  // ── US Casualties ────────────────────────────────────────────────────────
  const usCasEl = document.getElementById('ops-us-casualties');
  if (usCasEl && ops.us?.casualties) {
    const c = ops.us.casualties;
    usCasEl.innerHTML = `⚔️ خسائر أمريكية: <strong style="color:#e74c3c;">${c.killed} شهيد</strong> · ${c.seriouslyWounded} إصابة خطيرة` +
      (c.totalWounded ? ` · <strong style="color:#e67e22;">${c.totalWounded}+ جريح إجمالاً</strong>` : '') +
      ` <span style="color:#555;font-size:0.62rem;">(${c.note || 'CENTCOM'})</span>`;
  }

  // ── Israel Content ───────────────────────────────────────────────────────
  const ilEl = document.getElementById('ops-israel-content');
  if (ilEl && ops.israel) {
    const il = ops.israel;
    ilEl.innerHTML = (il.platforms || []).map(p =>
      `<div style="display:flex;align-items:flex-start;gap:4px;margin-bottom:3px;">
        <span style="color:#f1c40f;min-width:16px;">✈</span>
        <span><strong style="color:#eee;">${p.name}</strong> — <span style="color:#aaa;">${p.role}</span></span>
      </div>`).join('') +
      `<div style="margin-top:6px;font-size:0.68rem;color:#a0a0a0;">🎯 ${(il.targetsTotal || il.targetsDay2 || 0).toLocaleString('en-US')} هدف إجمالاً</div>` +
      (il.munitionsDropped     ? `<div style="font-size:0.68rem;color:#f39c12;margin-top:2px;">💣 ${il.munitionsDropped.toLocaleString('en-US')} ذخيرة مُلقاة</div>` : '') +
      (il.airDefensesDestroyed ? `<div style="font-size:0.68rem;color:#e74c3c;margin-top:2px;">🛡 ${il.airDefensesDestroyed} منظومة دفاع جوي مدمّرة</div>` : '') +
      (il.ballisticMissilesDestroyed ? `<div style="font-size:0.68rem;color:#e67e22;margin-top:2px;">🚀 ${il.ballisticMissilesDestroyed} صاروخ باليستي/منصة مدمّرة</div>` : '') +
      (il.leadershipSitesHit   ? `<div style="font-size:0.68rem;color:#8e44ad;margin-top:2px;">🎯 ${il.leadershipSitesHit} موقع قيادي مستهدف</div>` : '') +
      `<div style="font-size:0.68rem;color:#888;margin-top:3px;">📌 ${il.focus || ''}</div>` +
      (il.note ? `<div style="font-size:0.68rem;color:#f1c40f;margin-top:3px;font-weight:600;">⭐ ${il.note}</div>` : '');
    set('ops-il-badge', (il.sortiesTotal || il.sortiesDay2 || 0).toLocaleString('en-US') + ' طلعة إجمالاً');
  }

  // ── Iran Response ────────────────────────────────────────────────────────
  const iranRespEl = document.getElementById('ops-iran-response-content');
  if (iranRespEl && ops.iranResponse) {
    const r = ops.iranResponse;
    iranRespEl.innerHTML = [
      r.ballisticTotal ? `<div style="font-size:0.72rem;padding:4px 10px;background:rgba(231,76,60,0.08);border:1px solid rgba(231,76,60,0.2);border-radius:8px;color:#e74c3c;">🚀 <strong>${r.ballisticTotal.toLocaleString('en-US')}</strong> صاروخ باليستي وكروز</div>` : '',
      r.dronesTotal    ? `<div style="font-size:0.72rem;padding:4px 10px;background:rgba(230,126,34,0.08);border:1px solid rgba(230,126,34,0.2);border-radius:8px;color:#e67e22;">🛸 <strong>${r.dronesTotal.toLocaleString('en-US')}</strong> طائرة مسيّرة</div>` : '',
      `<div style="font-size:0.67rem;color:#555;align-self:center;">📡 ${r.source || ''}</div>`
    ].join('');
  }

  // ── Assessment Banner ────────────────────────────────────────────────────
  const assessEl = document.getElementById('ops-assessment');
  if (assessEl && ops.combined?.assessment) assessEl.textContent = ops.combined.assessment;
  const airSupEl = document.getElementById('ops-air-superiority');
  if (airSupEl && ops.combined?.airSuperiority) airSupEl.textContent = ops.combined.airSuperiority;
  const assessSrcEl = document.getElementById('ops-assessment-source');
  if (assessSrcEl && ops.combined?.assessmentSource) assessSrcEl.textContent = '📡 المصدر: ' + ops.combined.assessmentSource;

  // ── Facilities ───────────────────────────────────────────────────────────
  const facEl = document.getElementById('ops-facilities');
  if (facEl && ops.combined?.facilitiesDestroyed) {
    const allFac = [
      ...(ops.combined.facilitiesDestroyed.nuclear  || []).map(f => ({ ...f, cat: '☢️' })),
      ...(ops.combined.facilitiesDestroyed.military || []).map(f => ({ ...f, cat: '🎯' })),
      ...(ops.combined.facilitiesDestroyed.naval    || []).map(f => ({ ...f, cat: '⚓' })),
    ];
    facEl.innerHTML = allFac.map(f => {
      const isUnverified = f.status?.includes('غير مؤكد');
      const color = isUnverified ? '#777' : f.cat === '☢️' ? '#e74c3c' : f.cat === '⚓' ? '#2980b9' : '#e67e22';
      return `<div title="${f.status || ''}" style="font-size:0.68rem;padding:3px 8px;border-radius:12px;
        background:rgba(255,255,255,0.05);border:1px solid ${color}40;color:${color};white-space:nowrap;">
        ${f.cat} ${f.name}</div>`;
    }).join('');
  }

  // ── Source line ──────────────────────────────────────────────────────────
  const srcEl = document.getElementById('ops-source-line');
  if (srcEl) srcEl.textContent = '📡 المصادر: ' + (ops.source || '') + ' · آخر تحديث: ' +
    new Date(ops.lastUpdated || Date.now()).toLocaleString('ar-AE-u-ca-gregory-nu-latn', { timeZone: 'Asia/Dubai', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}

function renderScenarios(scenarios) {
  const container = document.getElementById('scenarios-container');
  if (!container || !scenarios?.length) return;

  // Sort by probability descending
  const sorted = [...scenarios].sort((a, b) => b.probability - a.probability);

  container.innerHTML = sorted.map(s => {
    const prob = s.probability;
    const cls  = prob >= 50 ? 'sc-high' : prob >= 25 ? 'sc-med' : 'sc-low';
    const trendIcon  = s.trend === 'up' ? '▲' : s.trend === 'down' ? '▼' : s.trend === 'new' ? '🆕' : '→';
    const trendColor = s.trend === 'up' ? 'var(--red)' : s.trend === 'down' ? 'var(--green)' : s.trend === 'new' ? '#f39c12' : 'var(--text-muted)';
    const updated = s.lastUpdated ? formatDate(s.lastUpdated) : '';

    return `
      <div class="scenario">
        <div class="sc-header">
          <span class="sc-title">${s.icon || '🔮'} ${s.title}</span>
          <div style="display:flex;align-items:center;gap:6px;">
            <span style="font-size:10px;color:${trendColor};font-weight:700;">${trendIcon}</span>
            <span class="sc-prob ${cls}">${prob}%</span>
          </div>
        </div>
        <div class="sc-desc">${s.description}</div>
        ${updated ? `<div style="font-size:9px;color:var(--text-muted);margin-top:3px;">آخر تحديث: ${updated}</div>` : ''}
      </div>`;
  }).join('');
}

const catLabels = {
  official:     { ar: 'رسمية 🏛️',        color: 'var(--blue)' },
  intelligence: { ar: 'استخباراتية 🔍',   color: 'var(--gold)' },
  media:        { ar: 'إعلامية 📰',        color: 'var(--green)' },
  realtime:     { ar: 'لحظية 📡',          color: 'var(--red)' },
};

function renderSources(sources) {
  const container = document.getElementById('sources-container');
  const countEl   = document.getElementById('sources-count');
  if (!container || !sources) return;

  const tierColor = { 1:'#e74c3c', 2:'#e67e22', 3:'#3498db', 4:'#7f8c8d' };
  const tierLabel = { 1:'مرجع رسمي', 2:'وكالة دولية', 3:'إعلام موثوق', 4:'متخصص' };

  let total = 0;
  let html  = '';

  const order = ['official', 'media', 'intelligence', 'realtime'];
  const cats  = [...order, ...Object.keys(sources).filter(k => !order.includes(k))];

  for (const cat of cats) {
    const items = sources[cat];
    if (!items?.length) continue;
    const { ar, color } = catLabels[cat] || { ar: cat, color: 'var(--text-muted)' };

    html += `<div style="grid-column:1/-1;font-size:10px;font-weight:700;color:${color};
      padding:4px 0 2px;border-bottom:1px solid var(--border);margin-bottom:2px;">${ar}</div>`;

    for (const s of items) {
      total++;
      const tier  = s.tier || (s.priority === 1 ? 2 : 3);
      const tColor = tierColor[tier] || '#7f8c8d';
      const langBadge = s.lang === 'ar'
        ? `<span style="font-size:8px;padding:1px 4px;border-radius:3px;background:rgba(39,174,96,0.15);color:#27ae60;font-weight:700;">عربي</span>`
        : s.lang === 'en'
        ? `<span style="font-size:8px;padding:1px 4px;border-radius:3px;background:rgba(52,152,219,0.15);color:#3498db;font-weight:700;">EN</span>`
        : '';
      html += `
        <a class="src-item" href="${s.url}" target="_blank" rel="noopener"
           style="border-right:2px solid ${tColor};">
          <div style="display:flex;align-items:center;gap:4px;justify-content:space-between;">
            <div class="src-name">${s.name}</div>
            ${langBadge}
          </div>
          <div class="src-type">${s.description || s.type || ''}</div>
          <span class="src-priority" style="background:${tColor}22;color:${tColor};">${tierLabel[tier] || ''}</span>
        </a>`;
    }
  }

  container.innerHTML = html || '<div style="color:var(--text-muted);grid-column:1/-1;text-align:center;">لا مصادر</div>';
  if (countEl) countEl.textContent = total + ' مصدر';
}

function renderAirspace(airspace) {
  const table = document.getElementById('airspace-table');
  if (!table || !airspace || typeof airspace !== 'object') return;

  const countryMap = {
    'UAE':          { flag: '🇦🇪', name: 'الإمارات' },
    'Bahrain':      { flag: '🇧🇭', name: 'البحرين' },
    'Qatar':        { flag: '🇶🇦', name: 'قطر' },
    'Iran':         { flag: '🇮🇷', name: 'إيران' },
    'Iraq':         { flag: '🇮🇶', name: 'العراق' },
    'Kuwait':       { flag: '🇰🇼', name: 'الكويت' },
    'Saudi Arabia': { flag: '🇸🇦', name: 'السعودية' },
    'Jordan':       { flag: '🇯🇴', name: 'الأردن' },
    'Oman':         { flag: '🇴🇲', name: 'عُمان' },
    'Yemen':        { flag: '🇾🇪', name: 'اليمن' },
  };

  const statusMap = {
    open:       { cls: 's-open',       label: 'مفتوح ✈️' },
    restricted: { cls: 's-restricted', label: 'مقيّد ⚠️' },
    closed:     { cls: 's-closed',     label: 'مغلق 🚫' },
    warning:    { cls: 's-restricted', label: 'تحذير ⚠️' },
  };

  const rows = Object.entries(airspace).map(([key, val]) => {
    const country = countryMap[key] || { flag: '🌐', name: key };
    const st      = statusMap[val.status] || { cls: 's-open', label: val.status };
    const since   = val.since ? formatDate(val.since) : '';
    const note    = val.note ? `<span style="font-size:9px;color:var(--text-muted);display:block;">${val.note}</span>` : '';
    return `<tr>
      <td>${country.flag} ${country.name}${note}</td>
      <td><span class="status-pill ${st.cls}">${st.label}</span></td>
      <td style="font-size:9px;color:var(--text-muted);direction:ltr;">${since}</td>
    </tr>`;
  }).join('');

  table.innerHTML = rows || '<tr><td colspan="3" style="text-align:center;color:var(--text-muted);">لا بيانات</td></tr>';
}

// ── Reports Password Gate ────────────────────────────────────────────────
const REPORTS_SESSION_KEY = 'mizan_reports_auth';
const REPORTS_HASH = '4280';

function initReportsGate() {
  if (sessionStorage.getItem(REPORTS_SESSION_KEY) === '1') {
    showReportsUnlocked();
  }
}

function unlockReports() {
  const val = (document.getElementById('reports-pw-input')?.value || '').trim();
  const errEl = document.getElementById('reports-pw-err');
  const inp   = document.getElementById('reports-pw-input');
  if (val === REPORTS_HASH) {
    sessionStorage.setItem(REPORTS_SESSION_KEY, '1');
    showReportsUnlocked();
  } else {
    if (errEl) errEl.style.display = 'inline';
    if (inp)   { inp.classList.add('error'); inp.value = ''; }
    setTimeout(() => {
      if (inp)   inp.classList.remove('error');
      if (errEl) errEl.style.display = 'none';
      if (inp)   inp.focus();
    }, 600);
  }
}

function showReportsUnlocked() {
  const locked   = document.getElementById('reports-locked-state');
  const links    = document.getElementById('reports-links');
  const divider  = document.getElementById('reports-archive-divider');
  const archLink = document.getElementById('reports-archive-link');
  if (locked)   locked.style.display   = 'none';
  if (links)    links.style.display    = 'flex';
  if (divider)  divider.style.display  = 'block';
  if (archLink) archLink.style.display = 'inline-flex';
  renderReports();
}

// ── Daily Reports ────────────────────────────────────────────────────────
function renderReports() {
  const BLOB_BASE = 'https://mizanwardata.blob.core.windows.net/data/reports';
  const container = document.getElementById('reports-links');
  if (!container) return;

  // Build today & yesterday dates in Dubai time (Asia/Dubai = UTC+4)
  const now = new Date();
  const today = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Dubai' }); // en-CA gives YYYY-MM-DD
  const yesterdayDt = new Date(now.getTime() - 86400000);
  const yesterday = yesterdayDt.toLocaleDateString('en-CA', { timeZone: 'Asia/Dubai' });

  function arDate(d) {
    const [y,m,day] = d.split('-');
    const months = ['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];
    return `${parseInt(day)} ${months[parseInt(m)-1]} ${y}`;
  }

  // Check which reports exist by trying to fetch their headers
  async function checkExists(url) {
    try {
      const r = await fetch(url, { method: 'HEAD', mode: 'cors' });
      return r.ok;
    } catch { return false; }
  }

  // Dates to check (today first, then yesterday)
  const dates = [today, yesterday];
  let html = '';

  Promise.all(dates.flatMap(date => [
    checkExists(`${BLOB_BASE}/war-brief-${date}.pdf`),
    checkExists(`${BLOB_BASE}/war-brief-${date}.html`),
    checkExists(`${BLOB_BASE}/war-evening-${date}.pdf`),
    checkExists(`${BLOB_BASE}/war-evening-${date}.html`),
  ])).then(results => {
    let any = false;
    dates.forEach((date, di) => {
      const morningPdf  = results[di * 4 + 0];
      const morningHtml = results[di * 4 + 1];
      const eveningPdf  = results[di * 4 + 2];
      const eveningHtml = results[di * 4 + 3];
      const hasMorning = morningPdf || morningHtml;
      const hasEvening = eveningPdf || eveningHtml;
      if (!hasMorning && !hasEvening) return;
      any = true;
      const isToday = date === today;
      const label = isToday ? 'اليوم' : 'أمس';
      const displayDate = arDate(date);
      html += `<span class="report-label">${label} (${displayDate}):</span>`;
      if (hasMorning) {
        html += `<span class="report-session-tag tag-morning">🌅 صباحي</span>`;
        if (morningPdf)  html += `<a href="${BLOB_BASE}/war-brief-${date}.pdf"  target="_blank" class="report-btn pdf-btn">📄 PDF</a>`;
        if (morningHtml) html += `<a href="${BLOB_BASE}/war-brief-${date}.html" target="_blank" class="report-btn html-btn">🌐 HTML</a>`;
      }
      if (hasEvening) {
        html += `<span class="report-session-tag tag-evening" style="margin-right:8px;">🌆 مسائي</span>`;
        if (eveningPdf)  html += `<a href="${BLOB_BASE}/war-evening-${date}.pdf"  target="_blank" class="report-btn pdf-btn">📄 PDF</a>`;
        if (eveningHtml) html += `<a href="${BLOB_BASE}/war-evening-${date}.html" target="_blank" class="report-btn html-btn">🌐 HTML</a>`;
      }
      if (di < dates.length - 1) html += `<div style="width:1px;height:20px;background:rgba(255,255,255,0.1);margin:0 4px;display:inline-block;vertical-align:middle;"></div>`;
    });
    if (!any) {
      container.innerHTML = '<span class="report-label">لا توجد تقارير متاحة لليوم.</span>';
    } else {
      container.innerHTML = html;
    }
  }).catch(() => {
    container.innerHTML = '<span class="report-label">تعذّر التحقق من التقارير.</span>';
  });
}

function renderOilChart(oilPrices) {
  const container = document.getElementById('oil-chart');
  if (!container || !oilPrices.length) return;

  const recent = oilPrices.slice(-10); // last 10 entries, no dedup
  const max = Math.max(...recent.map(o => o.brent));
  const min = Math.min(...recent.map(o => o.brent));
  const range = max - min;
  const isFlat = range < 0.1;

  if (isFlat) {
    // Flat line — show current price prominently
    const price = recent[recent.length - 1].brent;
    const color = price >= 150 ? '#e74c3c' : price >= 120 ? '#f39c12' : price >= 100 ? '#e67e22' : '#27ae60';
    container.style.flexDirection = 'column';
    container.style.justifyContent = 'center';
    container.style.alignItems = 'center';
    container.style.gap = '4px';
    container.innerHTML = `
      <div style="font-size:26px;font-weight:900;color:${color};">$${price.toFixed(2)}</div>
      <div style="font-size:10px;color:var(--text-muted);">السعر ثابت — لا تغيير منذ ${recent.length} قراءة</div>
      <div style="width:100%;height:2px;background:${color};border-radius:1px;opacity:0.5;margin-top:2px;"></div>`;
    return;
  }

  container.style.flexDirection = '';
  container.style.justifyContent = '';
  container.style.alignItems = 'flex-end';
  container.innerHTML = recent.map((o) => {
    const pct   = Math.round(((o.brent - min) / range) * 68 + 10);
    const color = o.brent >= 150 ? '#e74c3c' : o.brent >= 120 ? '#f39c12' : o.brent >= 100 ? '#e67e22' : '#27ae60';
    const label = new Date(o.datetime).toLocaleTimeString('ar-AE-u-ca-gregory-nu-latn', { hour:'2-digit', minute:'2-digit', timeZone:'Asia/Dubai' });
    return `
      <div class="oil-bar-wrap" title="$${o.brent} — ${label}">
        <div class="oil-val">$${o.brent.toFixed(1)}</div>
        <div class="oil-bar" style="height:${pct}%;background:linear-gradient(to top,${color},${color}99);"></div>
        <div class="oil-label">${label}</div>
      </div>`;
  }).join('');
}

function filterEvents(type, btn) {
  // Only reset type-filter tabs (not source tabs)
  document.querySelectorAll('.ftab:not(.stab)').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  currentFilter = type;
  renderTimeline(allEvents, currentFilter, currentSearch, 1);
  updateEventCount();
}

function filterByTime(period, btn) {
  document.querySelectorAll('#tfilter-all,#tfilter-1h,#tfilter-6h,#tfilter-24h').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  currentTimeFilter = period;
  renderTimeline(allEvents, currentFilter, currentSearch, 1);
  updateEventCount();
}

function applyTimeFilter(events) {
  if (currentTimeFilter === 'all') return events;
  const now  = Date.now();
  const hrs  = { '1h': 1, '6h': 6, '24h': 24 }[currentTimeFilter] || 24;
  const cutoff = now - hrs * 3600 * 1000;
  return events.filter(e => {
    // Use addedAt (when cron added it) if available, fallback to datetime (pubDate)
    const tsStr = e.addedAt || e.datetime;
    const dt = tsStr ? new Date(tsStr).getTime() : 0;
    return dt >= cutoff;
  });
}

function filterBySource(src, btn) {
  document.querySelectorAll('.stab').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  currentSourceFilter = src;
  renderTimeline(allEvents, currentFilter, currentSearch, 1);
  updateEventCount();
}

function updateEventCount() {
  const filtered = allEvents.filter(e =>
    matchesFilter(e, currentFilter) &&
    matchesSource(e, currentSourceFilter) &&
    matchesSearch(e, currentSearch)
  );
  const countEl = document.getElementById('events-count');
  if (countEl) countEl.textContent = filtered.length + ' حدث';
}

// Map canonical label → source name keywords to match
const SRC_MATCH = {
  'الجزيرة':    ['الجزيرة'],
  'العربية':    ['العربية'],
  'سكاي نيوز':  ['سكاي نيوز'],
  'BBC':        ['bbc'],
  'France24':   ['france24'],
  'Iran Intl':  ['iranintl', 'iran international'],
  'Reuters':    ['reuters'],
  'AP News':    ['ap news', 'apnews'],
  'The National':['the national'],
  'CENTCOM':    ['centcom'],
};

function matchesSource(e, src) {
  if (!src || src === 'all') return true;
  const s    = (e.sources || [{}])[0];
  const name = ((typeof s === 'object' ? s.name : s) || '').toLowerCase();
  const keywords = SRC_MATCH[src];
  if (keywords) return keywords.some(k => name.includes(k));
  // Fallback: direct substring match
  return name.includes(src.toLowerCase());
}

// Build source filter tabs from available events
function buildSourceTabs(events) {
  const container = document.getElementById('source-filter-tabs');
  if (!container) return;

  // Canonical display names + flags for known sources
  const SRC_DISPLAY = {
    'الجزيرة':                    { label: 'الجزيرة',     flag: '🇦🇪' },
    'العربية':                    { label: 'العربية',     flag: '🇦🇪' },
    'سكاي نيوز عربية':            { label: 'سكاي نيوز',  flag: '🇦🇪' },
    'BBC Arabic':                 { label: 'BBC',         flag: '🇦🇪' },
    'BBC عربي':                   { label: 'BBC',         flag: '🇦🇪' },
    'france24':                   { label: 'France24',    flag: '🇦🇪' },
    'France24 عربي':              { label: 'France24',    flag: '🇦🇪' },
    'Iran International':         { label: 'Iran Intl',   flag: '🇦🇪' },
    'IranIntl':                   { label: 'Iran Intl',   flag: '🇦🇪' },
    'Iran International / IranIntl':{ label: 'Iran Intl', flag: '🇦🇪' },
    'Reuters':                    { label: 'Reuters',     flag: '🇬🇧' },
    'AP News':                    { label: 'AP News',     flag: '🇬🇧' },
    'The National':               { label: 'The National',flag: '🇬🇧' },
    'CENTCOM':                    { label: 'CENTCOM',     flag: '🇺🇸' },
  };

  // Count events per canonical label (merge similar sources)
  const labelCount = {};
  const labelKey   = {};  // label → first raw source name seen (for filter matching)

  for (const e of events) {
    const s    = (e.sources || [{}])[0];
    const name = (typeof s === 'object' ? s.name : s) || '';
    if (!name) continue;

    const disp  = SRC_DISPLAY[name] || { label: name, flag: '' };
    const label = disp.label;

    if (!labelCount[label]) {
      labelCount[label] = { count: 0, flag: disp.flag, key: name };
    }
    labelCount[label].count++;
  }

  const sorted = Object.entries(labelCount).sort((a, b) => b[1].count - a[1].count);

  let html = `<button class="ftab stab active" onclick="filterBySource('all',this)">الكل (${events.length})</button>`;
  for (const [label, { count, flag, key }] of sorted) {
    const safeKey = label.replace(/'/g, "\\'");
    html += `<button class="ftab stab" onclick="filterBySource('${safeKey}',this)" data-key="${label}">${flag} ${label} <span style="opacity:.55;font-size:9px;">(${count})</span></button>`;
  }
  container.innerHTML = html;
}


function onSearchTimeline() {
  const inp = document.getElementById('timeline-search');
  currentSearch = inp ? inp.value : '';
  renderTimeline(allEvents, currentFilter, currentSearch, 1);
  updateEventCount();
}

// Clock
function updateClock() {
  const now = new Date();
  document.getElementById('clock').textContent =
    now.toLocaleTimeString('ar-AE-u-ca-gregory-nu-latn', { timeZone:'Asia/Dubai', hour12: false });
}
setInterval(updateClock, 1000);
updateClock();

// ─── Live Refresh System ─────────────────────────────────────────────────────
const REFRESH_INTERVAL = 300000; // 5 minutes (البيانات تتحدث مرتين يومياً فقط — لا حاجة لكل 60 ثانية)
let lastDataRefresh = Date.now();
let refreshTimer = null;

function startRefreshBar() {
  const bar = document.getElementById('refresh-bar');
  if (!bar) return;
  let start = Date.now();
  bar.style.transform = 'scaleX(1)';

  clearInterval(refreshTimer);
  refreshTimer = setInterval(() => {
    const elapsed = Date.now() - start;
    const pct = Math.min(elapsed / REFRESH_INTERVAL, 1);
    bar.style.transform = `scaleX(${1 - pct})`;
    if (pct >= 1) {
      clearInterval(refreshTimer);
      bar.style.transform = 'scaleX(0)';
    }
  }, 200);
}

function flashContainers() {
  ['timeline-container', 'statements-container'].forEach(id => {
    const el = document.getElementById(id);
    if (el) {
      el.classList.remove('data-flash');
      void el.offsetWidth; // reflow
      el.classList.add('data-flash');
    }
  });
}

function updateLastUpdatedAgo() {
  const el = document.getElementById('last-updated-ago');
  if (!el) return;
  const secs = Math.round((Date.now() - lastDataRefresh) / 1000);
  if (secs < 5) el.textContent = 'الآن';
  else if (secs < 60) el.textContent = `منذ ${secs}ث`;
  else el.textContent = `منذ ${Math.floor(secs/60)}د`;
}
setInterval(updateLastUpdatedAgo, 1000);

// Wrap original loadData to add live effects
const _origLoadData = loadData;
async function loadDataLive() {
  startRefreshBar();
  try {
    await _origLoadData();
    lastDataRefresh = Date.now();
    flashContainers();
    updateLastUpdatedAgo();
  } catch(liveErr) {
    hideLoadingBar();
    console.warn('loadDataLive error (non-fatal):', liveErr);
  }
}

// Load
loadDataLive();
setInterval(loadDataLive, REFRESH_INTERVAL);

// ─── Smart Version Polling — يفحص data-version.json كل 60s (أخف من fetch DB كامل) ──
(function() {
  const VERSION_URL = 'https://mizanwardata.blob.core.windows.net/data/data-version.json?se=2028-03-01T00%3A00%3A00Z&sp=rl&spr=https&sv=2026-02-06&sr=c&sig=mgHNLNgLkOuTTG1NZyx7YWt8Ah87sVQz51elS1lGCzI%3D';
  let lastKnownVersion = null;

  async function checkVersion() {
    try {
      const res = await fetch(VERSION_URL + '&t=' + Date.now(), { cache: 'no-store' });
      if (!res.ok) return;
      const data = await res.json();
      const v = data.version;
      if (lastKnownVersion && v !== lastKnownVersion) {
        console.log('📡 New data version detected:', v, '— refreshing');
        loadDataLive();
      }
      lastKnownVersion = v;
    } catch(e) { /* ignore — version check is best-effort */ }
  }

  // أول فحص بعد 30 ثانية، ثم كل 60 ثانية
  setTimeout(checkVersion, 30000);
  setInterval(checkVersion, 60000);
})();

// ─── Visibility-aware refresh: يحدّث عند عودة المستخدم للتاب ──────────────────
(function() {
  let hiddenAt = null;
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
      hiddenAt = Date.now();
    } else {
      // عاد للتاب — إذا مرّت أكثر من دقيقتين → حدّث مباشرة
      if (hiddenAt && (Date.now() - hiddenAt) > 120000) {
        console.log('⚡ Tab back — refreshing after', Math.round((Date.now()-hiddenAt)/1000), 'sec');
        loadDataLive();
      }
      hiddenAt = null;
    }
  });
})();

// ─── Service Worker — استقبال تحديث البيانات الفوري ──────────────────────────
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.addEventListener('message', (event) => {
    if (event.data && event.data.type === 'DATA_UPDATED') {
      // البيانات تحدّثت في الـ SW cache — حمّل فوراً بدون انتظار timer
      console.log('📡 SW: بيانات جديدة متاحة — تحديث فوري');
      loadDataLive();
    }
  });
}

// ─── Live Visitor Counter ─────────────────────────────────────────────────────
// Stores sessions + total directly in Azure Blob — no API needed
// ══ Real-time Presence v3 — API-based, Blob-persistent ══════════════════════
// Azure Function /api/presence handles session tracking server-side
// Frontend pings every 30s — no client-side Blob writes (no race conditions)

const PRESENCE_API = '/api/presence';
const HB_INTERVAL  = 30 * 1000;   // ping every 30 seconds for real-time count
const FLOOR        = 14000;        // confirmed real visits floor — updated 5 Mar 2026

let mySessionId  = null;
let visitorTotal = FLOOR;
let activeCount  = 1;

function getSessionId() {
  if (!mySessionId) {
    mySessionId = sessionStorage.getItem('war_sid_v4');
    if (!mySessionId) {
      mySessionId = 'ws_' + Math.random().toString(36).slice(2,10) + '_' + Date.now().toString(36);
      sessionStorage.setItem('war_sid_v4', mySessionId);
    }
  }
  return mySessionId;
}

function updateVisitorUI(active, total) {
  const countEl = document.getElementById('live-count');
  const totalEl = document.getElementById('total-visits-display');
  const dotEl   = document.querySelector('.visitors-dot');
  if (countEl) { countEl.textContent = active > 0 ? active : 1; countEl.style.display = ''; }
  if (totalEl) totalEl.textContent = (total || FLOOR).toLocaleString('en-US');
  // Dot color: green=1, orange=2-4, red=5+
  if (dotEl) dotEl.style.background = active >= 5 ? '#e74c3c' : active >= 2 ? '#f39c12' : '#27ae60';
  document.title = `🔮 بصيرة — الأزمة الإيرانية (${active > 0 ? active : 1} الآن)`;
}

async function presenceHeartbeat() {
  try {
    const res  = await fetch(PRESENCE_API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId: getSessionId() }),
    });
    if (!res.ok) return;
    const data = await res.json();
    visitorTotal = Math.max(data.total || 0, FLOOR);
    activeCount  = Math.max(data.active || 1, 1);
    updateVisitorUI(activeCount, visitorTotal);
  } catch { /* network issue — keep last values */ }
}

async function showVisitorStats() {
  try {
    const res  = await fetch(PRESENCE_API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId: getSessionId() }),
    });
    const data   = res.ok ? await res.json() : {};
    const active = Math.max(data.active || activeCount, 1);
    const total  = Math.max(data.total  || visitorTotal, FLOOR);
    alert(
      `📊 إحصائيات الموقع — war.tamkeenai.ae\n` +
      `━━━━━━━━━━━━━━━━━━━━━━━\n` +
      `🟢 الزوار الآن (مباشر): ${active}\n` +
      `📈 إجمالي الزيارات: ${total.toLocaleString('en-US')}\n` +
      `🔄 يتحدث كل 30 ثانية\n` +
      `━━━━━━━━━━━━━━━━━━━━━━━`
    );
  } catch {
    alert(`📊 الزوار الآن: ${activeCount} | الإجمالي: ${visitorTotal.toLocaleString('en-US')}`);
  }
}

// Start immediately + repeat every 30 seconds
presenceHeartbeat();
setInterval(presenceHeartbeat, HB_INTERVAL);
</script>

<!-- ══ TELEGRAM SUBSCRIBE MODAL + FLOATING BUTTON ════════════════════════ -->
<style>
  #tg-fab {
    position: fixed; bottom: 24px; left: 24px; z-index: 9999;
    display: flex; align-items: center; gap: 8px;
    background: linear-gradient(135deg, #0088cc, #006ba1);
    color: #fff; border: none; border-radius: 50px;
    padding: 11px 18px 11px 14px; cursor: pointer;
    font-family: 'Cairo', sans-serif; font-size: 0.82rem; font-weight: 700;
    box-shadow: 0 4px 20px rgba(0,136,204,0.45);
    transition: all 0.25s; white-space: nowrap;
    animation: fabPulse 3s ease-in-out infinite;
  }
  #tg-fab:hover { transform: translateY(-2px); box-shadow: 0 6px 28px rgba(0,136,204,0.6); }
  #tg-fab .fab-dot {
    width: 8px; height: 8px; border-radius: 50%; background: #4dff91;
    box-shadow: 0 0 6px #4dff91; flex-shrink: 0;
  }
  @keyframes fabPulse {
    0%,100% { box-shadow: 0 4px 20px rgba(0,136,204,0.45); }
    50%      { box-shadow: 0 4px 28px rgba(0,136,204,0.75); }
  }
  #tg-modal-overlay {
    display: none; position: fixed; inset: 0; z-index: 10000;
    background: rgba(0,0,0,0.75); backdrop-filter: blur(4px);
    align-items: center; justify-content: center;
  }
  #tg-modal-overlay.open { display: flex; }
  #tg-modal {
    background: #0d1520; border: 1px solid rgba(0,136,204,0.35);
    border-radius: 16px; padding: 28px 24px; max-width: 360px; width: 90%;
    font-family: 'Cairo', sans-serif; direction: rtl; text-align: center;
    box-shadow: 0 20px 60px rgba(0,0,0,0.6);
    animation: modalIn 0.25s ease;
  }
  @keyframes modalIn { from { transform: translateY(20px); opacity:0; } to { transform: translateY(0); opacity:1; } }
  #tg-modal .modal-logo {
    width: 56px; height: 56px; border-radius: 50%;
    background: linear-gradient(135deg,#0088cc,#005f8f);
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 14px; font-size: 1.6rem;
  }
  #tg-modal h3 { color: #fff; font-size: 1.1rem; font-weight: 800; margin: 0 0 6px; }
  #tg-modal .modal-sub { color: #888; font-size: 0.75rem; margin-bottom: 18px; }
  #tg-modal .modal-features {
    background: rgba(255,255,255,0.04); border-radius: 10px;
    padding: 12px 14px; margin-bottom: 20px; text-align: right;
  }
  #tg-modal .modal-features li {
    color: #ccc; font-size: 0.78rem; list-style: none;
    padding: 4px 0; border-bottom: 1px solid rgba(255,255,255,0.05);
    display: flex; align-items: center; gap: 8px;
  }
  #tg-modal .modal-features li:last-child { border-bottom: none; }
  #tg-modal .modal-cta {
    display: block; width: 100%;
    background: linear-gradient(135deg, #0088cc, #006ba1);
    color: #fff; text-decoration: none; border-radius: 10px;
    padding: 12px; font-size: 0.9rem; font-weight: 800;
    transition: all 0.2s; margin-bottom: 10px;
  }
  #tg-modal .modal-cta:hover { background: linear-gradient(135deg,#009ae0,#0077b6); }
  #tg-modal .modal-dismiss { color: #555; font-size: 0.72rem; cursor: pointer; }
  #tg-modal .modal-dismiss:hover { color: #888; }
  #tg-modal .modal-count { color: #0088cc; font-size: 0.72rem; margin-top: 10px; }
