/* MANARA — DETECT and DELIVER overlay columns + AI Narrative card */

const { useState: useStateCol, useEffect: useEffectCol } = React;

function Sparkline({ values, color = 'var(--accent-teal)', height = 18 }) {
  const max = Math.max(...values), min = Math.min(...values);
  const range = max - min || 1;
  const w = 80;
  const points = values.map((v, i) => {
    const x = (i / (values.length - 1)) * w;
    const y = height - ((v - min) / range) * height;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={w} height={height} style={{ display: 'block' }}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" opacity="0.9" />
      <circle cx={w} cy={height - ((values[values.length-1] - min) / range) * height} r="1.8" fill={color} />
    </svg>
  );
}

function ExpandedDetectCard({ dept, signal, locale, t, isHighlighted }) {
  const isAr = locale === 'ar';
  const sevColor = signal.severity === 'critical' ? 'var(--status-critical)'
    : signal.severity === 'warning' ? 'var(--status-caution)'
    : signal.severity === 'positive' ? 'var(--status-healthy)'
    : 'var(--status-info)';
  const sparkVals = [3, 5, 4, 7, 6, 8, 9, 7, 10, 12];

  return (
    <div className={`float-card ${isHighlighted ? 'card-glow' : ''}`} style={{
      padding: 'clamp(10px, 0.9vw, 18px)',
      borderColor: isHighlighted ? 'var(--border-strong)' : 'var(--border-medium)'
    }}>
      <div className="row between" style={{ marginBottom: 6 }}>
        <div className="col" style={{ gap: 1 }}>
          <div style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
            fontSize: 'clamp(15px, 1vw, 19px)',
            fontWeight: 700,
            color: 'var(--text-primary)',
            lineHeight: 1.15
          }}>{isAr ? dept.ar : dept.en}</div>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.65vw, 12px)',
            color: 'var(--accent-gold)',
            letterSpacing: '0.12em',
            fontWeight: 600
          }}>↳ {dept.agent}</div>
        </div>
        <span className={`severity-badge severity-${signal.severity}`}>
          {signal.severity === 'positive' ? (isAr ? 'إيجابي' : 'POS')
            : signal.severity === 'warning' ? (isAr ? 'تنبيه' : 'WARN')
            : signal.severity === 'critical' ? (isAr ? 'حرج' : 'CRIT')
            : (isAr ? 'معلومة' : 'INFO')}
        </span>
      </div>

      <div className="row" style={{ alignItems: 'flex-end', gap: 'clamp(18px, 1.6vw, 32px)', marginBottom: 4 }}>
        <div className="neom-value" style={{
          fontSize: 'clamp(26px, 1.9vw, 36px)',
          color: sevColor,
          lineHeight: 1
        }}>{signal.count.toLocaleString()}</div>
        <div className="col" style={{ gap: 1, flex: 1, paddingInlineStart: 'clamp(4px, 0.4vw, 10px)' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(11px, 0.72vw, 13px)',
            color: signal.trend.startsWith('+') ? 'var(--status-caution)' : signal.trend.startsWith('−') ? 'var(--status-healthy)' : 'var(--text-muted)',
            fontWeight: 600,
            letterSpacing: '0.05em'
          }}>{signal.trend} {isAr ? '٢٤س' : '24h'}</div>
          <Sparkline values={sparkVals} color={sevColor} />
        </div>
      </div>

      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(12px, 0.78vw, 14px)',
        color: 'var(--text-secondary)',
        lineHeight: 1.4,
        borderTop: '1px solid var(--border-subtle)',
        paddingTop: 6
      }}>{isAr ? signal.topAr : signal.topEn}</div>
    </div>
  );
}

function CompactDeptRow({ dept, signal, locale }) {
  const isAr = locale === 'ar';
  const status = signal.severity === 'critical' ? 'critical'
    : signal.severity === 'warning' ? 'caution' : '';
  return (
    <div className="dept-row" style={{
      borderColor: signal.severity === 'critical' ? 'var(--status-critical)'
        : signal.severity === 'warning' ? 'var(--status-caution)' : 'transparent'
    }}>
      <span className={`status-dot ${status}`} />
      <span style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: 'var(--text-secondary)',
        fontWeight: 600,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
      }}>{isAr ? dept.ar : dept.en}</span>
      <span style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: 'var(--text-primary)',
        fontWeight: 700,
        fontVariantNumeric: 'tabular-nums'
      }}>{signal.count.toLocaleString()}</span>
    </div>
  );
}

function DetectColumn({ locale, t, departments, detectSignals, expanded }) {
  const isAr = locale === 'ar';
  const expandedSet = new Set(expanded);
  const expandedDepts = departments.filter(d => expandedSet.has(d.id));
  const compactDepts = departments.filter(d => !expandedSet.has(d.id));

  return (
    <div className="col" style={{ gap: 'clamp(10px, 0.9vw, 18px)', height: '100%' }}>
      {/* Header */}
      <div className="row between" style={{ paddingInline: 4 }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{
            width: 4, height: 'clamp(22px, 1.7vw, 32px)',
            background: 'var(--phase-detect)',
            boxShadow: '0 0 12px var(--phase-detect)'
          }} />
          <div className="col" style={{ gap: 0 }}>
            <span className="phase-chip phase-detect" style={{ fontSize: 'clamp(20px, 1.55vw, 30px)' }}>{t.detect}</span>
            <span style={{
              fontSize: 'clamp(10px, 0.66vw, 12px)',
              color: 'var(--text-faint)',
              fontFamily: 'JetBrains Mono, monospace',
              letterSpacing: '0.18em',
              textTransform: 'uppercase'
            }}>{isAr ? '↳ ١٠ إدارات' : '↳ 10 directorates'}</span>
          </div>
        </div>
      </div>

      {/* Expanded cards */}
      <div className="col" style={{ gap: 'clamp(8px, 0.7vw, 14px)' }}>
        {expandedDepts.map(d => (
          <ExpandedDetectCard
            key={d.id}
            dept={d}
            signal={detectSignals[d.id]}
            locale={locale}
            t={t}
            isHighlighted={detectSignals[d.id].severity === 'warning' || detectSignals[d.id].severity === 'critical'}
          />
        ))}
      </div>

      {/* Compact rows */}
      <div className="float-card" style={{ padding: 'clamp(8px, 0.7vw, 14px)' }}>
        <div className="label-caps" style={{
          fontSize: 'clamp(10px, 0.66vw, 12px)',
          marginBottom: 6,
          paddingInline: 4
        }}>{isAr ? 'مراقبة محيطية' : 'Ambient monitoring'}</div>
        <div className="col" style={{ gap: 1 }}>
          {compactDepts.map(d => (
            <CompactDeptRow key={d.id} dept={d} signal={detectSignals[d.id]} locale={locale} />
          ))}
        </div>
      </div>

      {/* Anomalies block */}
      <div className="float-card" style={{ padding: 'clamp(10px, 0.9vw, 16px)' }}>
        <div className="row" style={{ gap: 8, marginBottom: 8 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M 12 2 L 22 20 L 2 20 Z" stroke="#FFB800" strokeWidth="2" />
            <line x1="12" y1="9" x2="12" y2="14" stroke="#FFB800" strokeWidth="2" />
            <circle cx="12" cy="17" r="1" fill="#FFB800" />
          </svg>
          <span className="label-caps" style={{ color: 'var(--status-caution)' }}>{t.anomaliesDetected}</span>
        </div>
        <div className="col" style={{ gap: 10 }}>
          <div className="col" style={{ gap: 2 }}>
            <div style={{
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
              fontSize: 'clamp(13px, 0.88vw, 16px)',
              color: 'var(--text-primary)',
              fontWeight: 500,
              lineHeight: 1.35
            }}>
              {isAr
                ? 'ممر E311 الشارقة–عجمان: ٣٫٤× الكثافة الأساسية للحوادث'
                : 'E311 Sharjah–Ajman corridor: 3.4× baseline incident density'}
            </div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--accent-gold)', letterSpacing: '0.12em' }}>↳ TrafficGuard • {isAr ? 'الثقة عالية' : 'high confidence'}</div>
          </div>
          <div className="col" style={{ gap: 2 }}>
            <div style={{
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
              fontSize: 'clamp(13px, 0.88vw, 16px)',
              color: 'var(--text-primary)',
              fontWeight: 500,
              lineHeight: 1.35
            }}>
              {isAr
                ? '٤٢٠٠ محاولة تصيّد محبطة هذه الساعة — صفر اختراقات ناجحة'
                : '4,200 phishing attempts neutralized this hour — zero successful intrusions'}
            </div>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--accent-gold)', letterSpacing: '0.12em' }}>↳ CyberSentinel • {isAr ? 'إيجابي' : 'positive'}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ExpandedDeliverCard({ dept, outcome, locale, t, isHighlighted }) {
  const isAr = locale === 'ar';
  const sparkVals = [12, 14, 13, 16, 18, 17, 20, 22, 21, 24];
  return (
    <div className={`float-card ${isHighlighted ? 'card-glow' : ''}`} style={{
      padding: 'clamp(10px, 0.9vw, 18px)'
    }}>
      <div className="row between" style={{ marginBottom: 6 }}>
        <div className="col" style={{ gap: 1, flex: 1, minWidth: 0, paddingInlineStart: 'clamp(4px, 0.4vw, 10px)' }}>
          <div style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
            fontSize: 'clamp(15px, 1vw, 19px)',
            fontWeight: 700,
            color: 'var(--text-primary)',
            lineHeight: 1.15
          }}>{isAr ? dept.ar : dept.en}</div>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.65vw, 12px)',
            color: 'var(--accent-gold)',
            letterSpacing: '0.12em',
            fontWeight: 600
          }}>↳ {dept.agent}</div>
        </div>
        <span className="severity-badge severity-positive">{isAr ? 'هدف' : 'ON TARGET'}</span>
      </div>

      <div className="row" style={{ alignItems: 'flex-end', gap: 'clamp(18px, 1.6vw, 32px)', marginBottom: 4 }}>
        <div className="neom-value" style={{
          fontSize: 'clamp(26px, 1.9vw, 36px)',
          color: 'var(--status-healthy)',
          lineHeight: 1
        }}>{outcome.metric}</div>
        <div className="col" style={{ gap: 1, flex: 1, minWidth: 0, paddingInlineStart: 'clamp(4px, 0.4vw, 10px)' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(11px, 0.72vw, 13px)',
            color: 'var(--status-healthy)',
            fontWeight: 600
          }}>{outcome.trend}</div>
          <Sparkline values={sparkVals} color="var(--status-healthy)" />
        </div>
      </div>

      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(12px, 0.78vw, 14px)',
        color: 'var(--text-secondary)',
        lineHeight: 1.4,
        borderTop: '1px solid var(--border-subtle)',
        paddingTop: 6
      }}>{isAr ? outcome.label.ar : outcome.label.en}</div>
    </div>
  );
}

function CompactDeliverRow({ dept, outcome, locale }) {
  const isAr = locale === 'ar';
  return (
    <div className="dept-row">
      <span className="status-dot" />
      <span style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: 'var(--text-secondary)',
        fontWeight: 600,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
      }}>{isAr ? dept.ar : dept.en}</span>
      <span style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: 'var(--status-healthy)',
        fontWeight: 700,
        fontVariantNumeric: 'tabular-nums'
      }}>{outcome.metric}</span>
    </div>
  );
}

function StrategicKpiTile({ kpi, locale, t }) {
  const isAr = locale === 'ar';
  return (
    <div className="float-card tech-corners" style={{
      padding: 'clamp(10px, 0.85vw, 16px)',
      flex: 1,
      minWidth: 0
    }}>
      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(11px, 0.72vw, 13px)',
        color: 'var(--text-muted)',
        letterSpacing: isAr ? '0' : '0.1em',
        textTransform: isAr ? 'none' : 'uppercase',
        fontWeight: 600,
        lineHeight: 1.2,
        marginBottom: 4
      }}>{isAr ? kpi.labelAr : kpi.labelEn}</div>
      <div className="row" style={{ alignItems: 'baseline', gap: 8 }}>
        <div className="neom-value" style={{
          fontSize: 'clamp(28px, 2.1vw, 42px)',
          color: 'var(--text-primary)',
          lineHeight: 1
        }}>{kpi.value}</div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(10px, 0.7vw, 12px)',
          color: 'var(--status-healthy)',
          fontWeight: 600
        }}>{kpi.trend}</div>
      </div>
      <div style={{
        fontSize: 'clamp(11px, 0.72vw, 13px)',
        color: 'var(--accent-teal)',
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        marginTop: 2
      }}>{isAr ? kpi.sub.ar : kpi.sub.en}</div>
      <div className="neom-source" style={{ marginTop: 6, lineHeight: 1.3 }}>
        {isAr ? kpi.sourceAr : kpi.sourceName || kpi.sourceEn} • {isAr ? kpi.ownerAr : kpi.ownerEn}
      </div>
    </div>
  );
}

function DeliverColumn({ locale, t, departments, deliverOutcomes, expanded, strategicKpis }) {
  const isAr = locale === 'ar';
  const expandedSet = new Set(expanded);
  const expandedDepts = departments.filter(d => expandedSet.has(d.id));
  const compactDepts = departments.filter(d => !expandedSet.has(d.id));

  return (
    <div className="col" style={{ gap: 'clamp(10px, 0.9vw, 18px)', height: '100%' }}>
      <div className="row between" style={{ paddingInline: 4 }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{
            width: 4, height: 'clamp(22px, 1.7vw, 32px)',
            background: 'var(--phase-deliver)',
            boxShadow: '0 0 12px var(--phase-deliver)'
          }} />
          <div className="col" style={{ gap: 0 }}>
            <span className="phase-chip phase-deliver" style={{ fontSize: 'clamp(20px, 1.55vw, 30px)' }}>{t.deliver}</span>
            <span style={{
              fontSize: 'clamp(10px, 0.66vw, 12px)',
              color: 'var(--text-faint)',
              fontFamily: 'JetBrains Mono, monospace',
              letterSpacing: '0.18em',
              textTransform: 'uppercase'
            }}>{isAr ? '↳ نتائج وأثر' : '↳ outcomes & impact'}</span>
          </div>
        </div>
      </div>

      <div className="col" style={{ gap: 'clamp(8px, 0.7vw, 14px)' }}>
        {expandedDepts.map(d => (
          <ExpandedDeliverCard key={d.id} dept={d} outcome={deliverOutcomes[d.id]} locale={locale} t={t} isHighlighted={d.id === 'civilDefense'} />
        ))}
      </div>

      <div className="float-card" style={{ padding: 'clamp(8px, 0.7vw, 14px)' }}>
        <div className="label-caps" style={{
          fontSize: 'clamp(10px, 0.66vw, 12px)',
          marginBottom: 6,
          paddingInline: 4
        }}>{isAr ? 'تأكيد محيطي' : 'Ambient confirmation'}</div>
        <div className="col" style={{ gap: 1 }}>
          {compactDepts.map(d => (
            <CompactDeliverRow key={d.id} dept={d} outcome={deliverOutcomes[d.id]} locale={locale} />
          ))}
        </div>
      </div>

      {/* Strategic KPIs — compact */}
      <div>
        <div className="label-caps" style={{
          fontSize: 'clamp(11px, 0.7vw, 13px)',
          marginBottom: 8,
          paddingInline: 4,
          color: 'var(--accent-gold)'
        }}>★ {t.strategicKpis}</div>
        <div className="col" style={{ gap: 8 }}>
          <div className="row" style={{ gap: 8 }}>
            <StrategicKpiTile kpi={strategicKpis[0]} locale={locale} t={t} />
            <StrategicKpiTile kpi={strategicKpis[1]} locale={locale} t={t} />
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- AI Narrative card (center, on map) ---------- */
function AiNarrativeCard({ locale, t, scenario }) {
  const isAr = locale === 'ar';
  const text = scenario ? (isAr ? scenario.briefingAr : scenario.briefingEn) : '';
  const [displayed, setDisplayed] = useStateCol('');

  useEffectCol(() => {
    setDisplayed('');
    if (!text) return;
    let i = 0;
    const id = setInterval(() => {
      i++;
      setDisplayed(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, 22);
    return () => clearInterval(id);
  }, [text]);

  return (
    <div className="float-card tech-corners conic-sweep" style={{
      padding: 'clamp(16px, 1.4vw, 28px)',
      maxWidth: 'clamp(420px, 38vw, 760px)',
      pointerEvents: 'auto'
    }}>
      <div className="row between" style={{ marginBottom: 10 }}>
        <div className="row" style={{ gap: 10 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M 12 2 L 14.5 9 L 22 12 L 14.5 14.5 L 12 22 L 9.5 14.5 L 2 12 L 9.5 9 Z" fill="#D4AF37" />
          </svg>
          <span className="label-caps" style={{ color: 'var(--accent-gold)', fontSize: 'clamp(11px, 0.72vw, 14px)' }}>
            {t.currentPicture}
          </span>
        </div>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(11px, 0.72vw, 13px)',
          color: 'var(--text-muted)',
          letterSpacing: '0.15em'
        }}>↳ {scenario?.agent || 'StrategyMind'}</span>
      </div>

      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(18px, 1.6vw, 30px)',
        fontWeight: 500,
        color: 'var(--text-primary)',
        lineHeight: 1.35,
        minHeight: 'clamp(72px, 6vw, 110px)'
      }}>
        {displayed}
        {displayed.length < text.length && <span className="tw-cursor" />}
      </div>

      {scenario?.id === 'query' && (
        <div style={{
          marginTop: 14,
          padding: '8px 14px',
          background: 'rgba(0,229,204,0.06)',
          border: '1px solid var(--border-medium)',
          borderRadius: 2,
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
          fontSize: 'clamp(12px, 0.85vw, 15px)',
          color: 'var(--accent-teal)'
        }}>
          <span style={{ color: 'var(--text-faint)', marginInlineEnd: 8, letterSpacing: '0.15em' }}>{t.query} ▸</span>
          {isAr ? scenario.queryAr : scenario.queryEn}
        </div>
      )}

      <div className="row" style={{
        marginTop: 12,
        paddingTop: 10,
        borderTop: '1px solid var(--border-subtle)',
        gap: 14,
        flexWrap: 'wrap'
      }}>
        <div className="row" style={{ gap: 6 }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent-teal)', boxShadow: '0 0 6px var(--accent-teal)' }} />
          <span className="neom-source">{t.simulated}</span>
        </div>
      </div>
    </div>
  );
}

/* ---------- Total Active counter card ---------- */
function TotalActiveCard({ locale, t, value, delta }) {
  const isAr = locale === 'ar';
  return (
    <div className="float-card tech-corners" style={{
      padding: 'clamp(14px, 1.2vw, 22px)',
      pointerEvents: 'auto',
      minWidth: 'clamp(220px, 18vw, 320px)'
    }}>
      <div className="label-caps" style={{ fontSize: 'clamp(11px, 0.7vw, 13px)', marginBottom: 4 }}>
        {t.totalActive}
      </div>
      <div className="neom-value" style={{
        fontSize: 'clamp(64px, 5.5vw, 112px)',
        color: 'var(--text-primary)',
        lineHeight: 0.95
      }}>{value}</div>
      <div className="row" style={{ gap: 10, marginTop: 4 }}>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(12px, 0.8vw, 15px)',
          color: 'var(--status-healthy)',
          fontWeight: 600
        }}>{delta}</span>
        <span style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
          fontSize: 'clamp(11px, 0.72vw, 13px)',
          color: 'var(--text-muted)'
        }}>{isAr ? 'آخر ٦٠ دقيقة' : 'last 60 min'}</span>
      </div>
    </div>
  );
}

/* ---------- Respond / operational heartbeat panel ---------- */
function RespondPanel({ locale, t, pipeline }) {
  const isAr = locale === 'ar';
  const triage = pipeline.find(p => p.id === 'triage')?.count ?? 0;
  const assigned = pipeline.find(p => p.id === 'assignment')?.count ?? 0;
  const active = pipeline.find(p => p.id === 'active')?.count ?? 0;
  return (
    <div className="float-card" style={{
      padding: 'clamp(12px, 1vw, 20px)',
      pointerEvents: 'auto'
    }}>
      <div className="row" style={{ gap: 10, marginBottom: 8 }}>
        <div style={{ width: 4, height: 16, background: 'var(--phase-respond)', boxShadow: '0 0 8px var(--phase-respond)' }} />
        <span className="phase-chip phase-respond" style={{ fontSize: 'clamp(13px, 0.9vw, 17px)' }}>
          {t.respond}
        </span>
        <span style={{
          fontSize: 'clamp(11px, 0.72vw, 13px)',
          color: 'var(--text-muted)',
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
          letterSpacing: isAr ? '0' : '0.12em',
          textTransform: isAr ? 'none' : 'uppercase'
        }}>{isAr ? '— نبض العمليات' : '— Operational heartbeat'}</span>
      </div>
      <div className="row" style={{ gap: 'clamp(14px, 1.4vw, 28px)' }}>
        {[
          { label: { en: 'Triage', ar: 'فرز' }, value: triage, color: 'var(--phase-respond)' },
          { label: { en: 'Assigned', ar: 'إسناد' }, value: assigned, color: 'var(--phase-respond)' },
          { label: { en: 'Active Ops', ar: 'استجابة نشطة' }, value: active, color: 'var(--phase-respond)' }
        ].map((m, i) => (
          <div key={i} className="col" style={{ gap: 2 }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 'clamp(28px, 2.1vw, 40px)',
              fontWeight: 800,
              color: m.color,
              lineHeight: 1
            }}>{m.value}</div>
            <div style={{
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
              fontSize: 'clamp(11px, 0.72vw, 13px)',
              color: 'var(--text-muted)',
              letterSpacing: isAr ? '0' : '0.12em',
              textTransform: isAr ? 'none' : 'uppercase',
              fontWeight: 600
            }}>{isAr ? m.label.ar : m.label.en}</div>
          </div>
        ))}
        <div className="col" style={{ gap: 2, marginInlineStart: 'auto' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(20px, 1.5vw, 28px)',
            fontWeight: 700,
            color: 'var(--accent-teal)',
            lineHeight: 1
          }}>1:42</div>
          <div style={{
            fontSize: 'clamp(10px, 0.7vw, 12px)',
            color: 'var(--text-muted)',
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace'
          }}>{t.avgTriage}</div>
        </div>
      </div>
    </div>
  );
}

window.DetectColumn = DetectColumn;
window.DeliverColumn = DeliverColumn;
window.AiNarrativeCard = AiNarrativeCard;
window.TotalActiveCard = TotalActiveCard;
window.RespondPanel = RespondPanel;
window.StrategicKpiTile = StrategicKpiTile;

/* ============================================================
   RESPOND column — full data parity with DETECT / DELIVER
   ============================================================ */

function ExpandedRespondCard({ dept, signal, locale, isHighlighted }) {
  const isAr = locale === 'ar';
  const sevColor = signal.severity === 'critical' ? 'var(--status-critical)'
    : signal.severity === 'warning' ? 'var(--status-caution)'
    : signal.severity === 'positive' ? 'var(--status-healthy)'
    : 'var(--status-info)';
  const sparkVals = [4, 6, 5, 8, 7, 9, 10, 8, 11, 12];

  return (
    <div className={`float-card ${isHighlighted ? 'card-glow' : ''}`} style={{
      padding: 'clamp(10px, 0.9vw, 18px)',
      borderColor: signal.severity === 'critical' ? 'rgba(255,71,87,0.55)' : 'rgba(249, 115, 22, 0.32)'
    }}>
      <div className="row between" style={{ marginBottom: 6 }}>
        <div className="col" style={{ gap: 1, minWidth: 0, flex: 1 }}>
          <div style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
            fontSize: 'clamp(15px, 1vw, 19px)',
            fontWeight: 700,
            color: 'var(--text-primary)',
            lineHeight: 1.15
          }}>{isAr ? dept.ar : dept.en}</div>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.65vw, 12px)',
            color: 'var(--accent-gold)',
            letterSpacing: '0.12em',
            fontWeight: 600
          }}>↳ {dept.agent}</div>
        </div>
        <span className={`severity-badge severity-${signal.severity}`}>
          {signal.severity === 'critical' ? (isAr ? 'حرج' : 'CRIT')
            : signal.severity === 'warning' ? (isAr ? 'تنبيه' : 'WARN')
            : signal.severity === 'positive' ? (isAr ? 'إيجابي' : 'POS')
            : (isAr ? 'معلومة' : 'INFO')}
        </span>
      </div>

      <div className="row" style={{ alignItems: 'flex-end', gap: 'clamp(18px, 1.6vw, 32px)', marginBottom: 6 }}>
        <div className="neom-value" style={{
          fontSize: 'clamp(26px, 1.9vw, 36px)',
          color: sevColor,
          lineHeight: 1
        }}>{signal.count}</div>
        <div className="col" style={{ gap: 1, flex: 1, minWidth: 0, paddingInlineStart: 'clamp(4px, 0.4vw, 10px)' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(11px, 0.72vw, 13px)',
            color: signal.trend.startsWith('+') ? 'var(--phase-respond)' : signal.trend.startsWith('−') ? 'var(--status-healthy)' : 'var(--text-muted)',
            fontWeight: 600
          }}>{signal.trend} {isAr ? 'نشط' : 'active'}</div>
          <Sparkline values={sparkVals} color={sevColor} />
        </div>
        <div className="col" style={{ alignItems: 'flex-end', gap: 1 }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(13px, 0.95vw, 17px)',
            fontWeight: 700,
            color: 'var(--phase-respond)',
            fontVariantNumeric: 'tabular-nums'
          }}>{signal.eta}</div>
          <div style={{
            fontSize: 'clamp(9px, 0.6vw, 11px)',
            color: 'var(--text-faint)',
            fontFamily: 'JetBrains Mono, monospace',
            letterSpacing: '0.12em',
            textTransform: 'uppercase'
          }}>{isAr ? 'الوصول' : 'ETA'}</div>
        </div>
      </div>

      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(12px, 0.78vw, 14px)',
        color: 'var(--text-secondary)',
        lineHeight: 1.4,
        borderTop: '1px solid var(--border-subtle)',
        paddingTop: 6
      }}>{isAr ? signal.topAr : signal.topEn}</div>
    </div>
  );
}

function CompactRespondRow({ dept, signal, locale }) {
  const isAr = locale === 'ar';
  const status = signal.severity === 'critical' ? 'critical' : signal.severity === 'warning' ? 'caution' : '';
  return (
    <div className="dept-row" style={{
      borderColor: signal.severity === 'critical' ? 'var(--status-critical)' : signal.severity === 'warning' ? 'var(--phase-respond)' : 'transparent'
    }}>
      <span className={`status-dot ${status}`} style={{ background: signal.count > 0 ? 'var(--phase-respond)' : 'var(--text-faint)' }} />
      <span style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: 'var(--text-secondary)',
        fontWeight: 600,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis'
      }}>{isAr ? dept.ar : dept.en}</span>
      <span style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 'clamp(13px, 0.85vw, 16px)',
        color: signal.count > 0 ? 'var(--phase-respond)' : 'var(--text-muted)',
        fontWeight: 700,
        fontVariantNumeric: 'tabular-nums'
      }}>{signal.count}</span>
    </div>
  );
}

function RespondColumn({ locale, t, departments, respondSignals, expanded, pipeline, totalActive, scenario }) {
  const isAr = locale === 'ar';
  const expandedSet = new Set(expanded);
  const expandedDepts = departments.filter(d => expandedSet.has(d.id));
  const compactDepts = departments.filter(d => !expandedSet.has(d.id));

  const triage = pipeline.find(p => p.id === 'triage')?.count ?? 0;
  const assigned = pipeline.find(p => p.id === 'assignment')?.count ?? 0;
  const active = pipeline.find(p => p.id === 'active')?.count ?? 0;

  return (
    <div className="col" style={{ gap: 'clamp(10px, 0.9vw, 18px)', height: '100%', minHeight: 0, overflow: 'hidden' }}>
      {/* Header */}
      <div className="row between" style={{ paddingInline: 4 }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{
            width: 4, height: 'clamp(22px, 1.7vw, 32px)',
            background: 'var(--phase-respond)',
            boxShadow: '0 0 12px var(--phase-respond)'
          }} />
          <div className="col" style={{ gap: 0 }}>
            <span className="phase-chip phase-respond" style={{ fontSize: 'clamp(20px, 1.55vw, 30px)' }}>{t.respond}</span>
            <span style={{
              fontSize: 'clamp(10px, 0.66vw, 12px)',
              color: 'var(--text-faint)',
              fontFamily: 'JetBrains Mono, monospace',
              letterSpacing: '0.18em',
              textTransform: 'uppercase'
            }}>{t.respondLabel}</span>
          </div>
        </div>
      </div>

      {/* Total Active hero metric */}
      <div className="float-card tech-corners" style={{ padding: 'clamp(12px, 1vw, 22px)' }}>
        <div className="row between" style={{ marginBottom: 4 }}>
          <span className="label-caps" style={{ fontSize: 'clamp(10px, 0.66vw, 12px)' }}>{t.totalActive}</span>
          <span className="severity-badge severity-warning" style={{ fontSize: 10 }}>
            <span className="status-dot caution" style={{ width: 6, height: 6 }} />
            {isAr ? 'مباشر' : 'LIVE'}
          </span>
        </div>
        <div className="row" style={{ alignItems: 'baseline', gap: 12 }}>
          <div className="neom-value" style={{
            fontSize: 'clamp(48px, 4vw, 80px)',
            color: 'var(--phase-respond)',
            lineHeight: 0.95
          }}>{totalActive}</div>
          <div className="col" style={{ gap: 0 }}>
            <span style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 'clamp(12px, 0.85vw, 15px)',
              color: 'var(--status-healthy)',
              fontWeight: 700
            }}>−8 vs baseline</span>
            <span style={{
              fontSize: 'clamp(10px, 0.7vw, 12px)',
              color: 'var(--text-faint)',
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace'
            }}>{isAr ? 'آخر ٦٠ دقيقة' : 'last 60 minutes'}</span>
          </div>
        </div>
        {/* Mini-pipeline triage→assigned→active */}
        <div className="row" style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border-subtle)', gap: 'clamp(8px, 0.8vw, 18px)' }}>
          {[
            { v: triage, l: { en: 'Triage', ar: 'فرز' } },
            { v: assigned, l: { en: 'Assigned', ar: 'إسناد' } },
            { v: active, l: { en: 'Active', ar: 'نشط' } }
          ].map((m, i) => (
            <div key={i} className="col" style={{ gap: 1, flex: 1 }}>
              <div style={{
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 'clamp(20px, 1.5vw, 28px)',
                fontWeight: 800,
                color: 'var(--phase-respond)',
                lineHeight: 1
              }}>{m.v}</div>
              <div style={{
                fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
                fontSize: 'clamp(10px, 0.66vw, 12px)',
                color: 'var(--text-muted)',
                letterSpacing: isAr ? '0' : '0.12em',
                textTransform: isAr ? 'none' : 'uppercase',
                fontWeight: 600
              }}>{isAr ? m.l.ar : m.l.en}</div>
            </div>
          ))}
          <div className="col" style={{ gap: 1, alignItems: 'flex-end' }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 'clamp(18px, 1.35vw, 24px)',
              fontWeight: 700,
              color: 'var(--accent-teal)',
              lineHeight: 1,
              fontVariantNumeric: 'tabular-nums'
            }}>1:42</div>
            <div style={{
              fontSize: 'clamp(10px, 0.66vw, 12px)',
              color: 'var(--text-muted)',
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace'
            }}>{t.avgTriage}</div>
          </div>
        </div>
      </div>

      {/* Expanded respond cards */}
      <div className="col" style={{ gap: 'clamp(8px, 0.7vw, 14px)' }}>
        {expandedDepts.map(d => (
          <ExpandedRespondCard
            key={d.id}
            dept={d}
            signal={respondSignals[d.id]}
            locale={locale}
            isHighlighted={respondSignals[d.id].severity === 'critical' || respondSignals[d.id].severity === 'warning'}
          />
        ))}
      </div>

      {/* Compact respond rows */}
      <div className="float-card" style={{ padding: 'clamp(8px, 0.7vw, 14px)' }}>
        <div className="row between" style={{ marginBottom: 6, paddingInline: 4 }}>
          <span className="label-caps" style={{ fontSize: 'clamp(10px, 0.66vw, 12px)' }}>
            {isAr ? 'إدارات تنسّق' : 'Coordinating directorates'}
          </span>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.66vw, 12px)',
            color: 'var(--phase-respond)',
            fontWeight: 700
          }}>
            {compactDepts.reduce((a, d) => a + (respondSignals[d.id]?.count || 0), 0)} {isAr ? 'وحدة' : 'units'}
          </span>
        </div>
        <div className="col" style={{ gap: 1 }}>
          {compactDepts.map(d => (
            <CompactRespondRow key={d.id} dept={d} signal={respondSignals[d.id]} locale={locale} />
          ))}
        </div>
      </div>
    </div>
  );
}

window.RespondColumn = RespondColumn;

/* ============================================================
   VOICE COMMAND BAR — Ask MANARA
   ============================================================ */

function VoiceCommandBar({ locale, t, voiceCommands, onPick }) {
  const isAr = locale === 'ar';
  const cmds = voiceCommands[locale];
  const [activeIdx, setActiveIdx] = useStateCol(0);
  const [transcript, setTranscript] = useStateCol('');
  const [listening, setListening] = useStateCol(false);

  // Auto-cycle the suggestions
  useEffectCol(() => {
    const id = setInterval(() => setActiveIdx(i => (i + 1) % cmds.length), 7000);
    return () => clearInterval(id);
  }, [cmds.length]);

  // Simulated typewriter when "listening"
  useEffectCol(() => {
    if (!listening) return;
    const target = cmds[activeIdx];
    setTranscript('');
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTranscript(target.slice(0, i));
      if (i >= target.length) {
        clearInterval(id);
        setTimeout(() => {
          setListening(false);
          if (onPick) onPick(target);
        }, 800);
      }
    }, 38);
    return () => clearInterval(id);
  }, [listening, activeIdx]);

  // Auto-trigger listening every 18s for ambient demo motion
  useEffectCol(() => {
    const id = setInterval(() => setListening(true), 18000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="voice-bar" style={{ direction: isAr ? 'rtl' : 'ltr' }}>
      {/* Mic button */}
      <div className="voice-mic" onClick={() => setListening(true)} style={{ cursor: 'pointer' }}>
        <svg width="55%" height="55%" viewBox="0 0 24 24" fill="none">
          <rect x="9" y="3" width="6" height="12" rx="3" fill="var(--accent-teal)" />
          <path d="M 5 11 C 5 15 8 18 12 18 C 16 18 19 15 19 11" stroke="var(--accent-teal)" strokeWidth="2" fill="none" strokeLinecap="round" />
          <line x1="12" y1="18" x2="12" y2="22" stroke="var(--accent-teal)" strokeWidth="2" strokeLinecap="round" />
        </svg>
      </div>

      {/* Label + waveform/transcript */}
      <div className="col" style={{ gap: 2, minWidth: 0, flex: '0 0 auto' }}>
        <div className="row" style={{ gap: 8 }}>
          <span style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'Outfit, sans-serif',
            fontSize: 'clamp(15px, 1.05vw, 20px)',
            fontWeight: 700,
            color: 'var(--accent-teal)',
            letterSpacing: isAr ? '0' : '0.18em'
          }}>{t.askManara}</span>
          {listening && (
            <span className="row" style={{ gap: 6 }}>
              <span className="voice-wave">
                <span /><span /><span /><span /><span /><span /><span />
              </span>
              <span style={{
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 'clamp(10px, 0.7vw, 12px)',
                color: 'var(--status-critical)',
                letterSpacing: '0.18em',
                fontWeight: 700
              }}>● {t.micActive}</span>
            </span>
          )}
        </div>
        <div style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
          fontSize: 'clamp(12px, 0.85vw, 15px)',
          color: 'var(--text-muted)',
          letterSpacing: isAr ? '0' : '0.04em',
          minHeight: '1.2em'
        }}>
          {listening ? (
            <span style={{ color: 'var(--text-primary)' }}>
              {transcript}
              <span className="tw-cursor" />
            </span>
          ) : t.voicePlaceholder}
        </div>
      </div>

      {/* Vertical divider */}
      <div style={{
        width: 1, height: 32,
        background: 'linear-gradient(to bottom, transparent, rgba(0,229,204,0.4), transparent)',
        flexShrink: 0
      }} />

      {/* Suggestion chips */}
      <div className="row" style={{ gap: 8, overflow: 'hidden', flex: 1, minWidth: 0 }}>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(10px, 0.7vw, 12px)',
          color: 'var(--text-faint)',
          letterSpacing: '0.15em',
          textTransform: 'uppercase',
          flexShrink: 0
        }}>{t.tryAsking} →</span>
        {cmds.slice(0, 3).map((c, i) => (
          <button
            key={i}
            className="voice-suggestion"
            onClick={() => { setActiveIdx(i); setListening(true); }}
            style={{
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
              borderColor: i === activeIdx ? 'var(--accent-teal)' : undefined,
              color: i === activeIdx ? 'var(--accent-teal)' : undefined,
              background: i === activeIdx ? 'rgba(0,229,204,0.1)' : undefined,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              maxWidth: 'clamp(180px, 18vw, 360px)'
            }}>"{c}"</button>
        ))}
      </div>
    </div>
  );
}

window.VoiceCommandBar = VoiceCommandBar;

/* ============================================================
   INLINE VOICE BAR — Compact Ask MANARA for inside the top strip
   Same auto-cycle + listening simulation, but in a compact horizontal layout.
   ============================================================ */
function InlineVoiceBar({ locale, t, voiceCommands }) {
  const isAr = locale === 'ar';
  const cmds = voiceCommands[locale];
  const [activeIdx, setActiveIdx] = useStateCol(0);
  const [transcript, setTranscript] = useStateCol('');
  const [listening, setListening] = useStateCol(false);

  useEffectCol(() => {
    const id = setInterval(() => setActiveIdx(i => (i + 1) % cmds.length), 7000);
    return () => clearInterval(id);
  }, [cmds.length]);

  useEffectCol(() => {
    if (!listening) return;
    const target = cmds[activeIdx];
    setTranscript('');
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTranscript(target.slice(0, i));
      if (i >= target.length) {
        clearInterval(id);
        setTimeout(() => setListening(false), 1200);
      }
    }, 38);
    return () => clearInterval(id);
  }, [listening, activeIdx]);

  // Auto-trigger every 14s for ambient demo motion
  useEffectCol(() => {
    const id = setInterval(() => setListening(true), 14000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="row inline-voice-bar" style={{
      gap: 'clamp(10px, 0.8vw, 16px)',
      padding: 'clamp(6px, 0.5vw, 10px) clamp(10px, 0.9vw, 18px)',
      background: 'rgba(0, 229, 204, 0.05)',
      border: '1px solid rgba(0, 229, 204, 0.32)',
      borderRadius: 999,
      direction: isAr ? 'rtl' : 'ltr',
      position: 'relative',
      overflow: 'hidden',
      boxShadow: 'inset 0 1px 0 rgba(0, 229, 204, 0.08), 0 0 16px rgba(0, 229, 204, 0.1)'
    }}>
      {/* Mic */}
      <div onClick={() => setListening(true)} style={{
        position: 'relative',
        width: 'clamp(28px, 2.1vw, 38px)',
        height: 'clamp(28px, 2.1vw, 38px)',
        borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(0,229,204,0.35), rgba(0,229,204,0.08))',
        border: '1.5px solid rgba(0,229,204,0.7)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0, cursor: 'pointer'
      }}>
        <svg width="55%" height="55%" viewBox="0 0 24 24" fill="none">
          <rect x="9" y="3" width="6" height="12" rx="3" fill="var(--accent-teal)" />
          <path d="M 5 11 C 5 15 8 18 12 18 C 16 18 19 15 19 11" stroke="var(--accent-teal)" strokeWidth="2" fill="none" strokeLinecap="round" />
          <line x1="12" y1="18" x2="12" y2="22" stroke="var(--accent-teal)" strokeWidth="2" strokeLinecap="round" />
        </svg>
      </div>

      {/* Label or transcript */}
      <div className="col" style={{ gap: 1, minWidth: 0, flex: 1 }}>
        <div className="row" style={{ gap: 8 }}>
          <span style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'Outfit, sans-serif',
            fontSize: 'clamp(12px, 0.85vw, 16px)',
            fontWeight: 700,
            color: 'var(--accent-teal)',
            letterSpacing: isAr ? '0' : '0.16em',
            whiteSpace: 'nowrap'
          }}>{t.askManara}</span>
          {listening && (
            <span className="voice-wave" style={{ height: 14 }}>
              <span /><span /><span /><span /><span />
            </span>
          )}
        </div>
        <div style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
          fontSize: 'clamp(10px, 0.7vw, 13px)',
          color: listening ? 'var(--text-primary)' : 'var(--text-muted)',
          minHeight: '1.1em',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}>
          {listening ? (
            <span>{transcript}<span className="tw-cursor" /></span>
          ) : (
            <span style={{ fontStyle: 'italic' }}>"{cmds[activeIdx]}"</span>
          )}
        </div>
      </div>
    </div>
  );
}

window.InlineVoiceBar = InlineVoiceBar;

/* ============================================================
   RESPOND BAND — full-width horizontal version of RespondColumn
   ============================================================ */
function RespondBand({ locale, t, departments, respondSignals, expanded, pipeline, totalActive, scenario }) {
  const isAr = locale === 'ar';
  const expandedSet = new Set(expanded);
  const expandedDepts = departments.filter(d => expandedSet.has(d.id));
  const compactDepts = departments.filter(d => !expandedSet.has(d.id));

  const triage = pipeline.find(p => p.id === 'triage')?.count ?? 0;
  const assigned = pipeline.find(p => p.id === 'assignment')?.count ?? 0;
  const active = pipeline.find(p => p.id === 'active')?.count ?? 0;

  return (
    <div className="float-card" style={{
      padding: 'clamp(12px, 1vw, 20px) clamp(16px, 1.3vw, 26px)',
      borderColor: 'rgba(249, 115, 22, 0.35)',
      borderTop: '2px solid var(--phase-respond)',
      display: 'grid',
      gridTemplateColumns: 'minmax(220px, 0.7fr) minmax(280px, 1.1fr) minmax(0, 2.2fr) minmax(220px, 1.1fr)',
      gap: 'clamp(14px, 1.2vw, 28px)',
      alignItems: 'stretch'
    }}>
      {/* Block 1 — Phase chip + Total Active hero */}
      <div className="col" style={{ gap: 8, justifyContent: 'space-between' }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{
            width: 4, height: 'clamp(22px, 1.7vw, 30px)',
            background: 'var(--phase-respond)',
            boxShadow: '0 0 12px var(--phase-respond)'
          }} />
          <div className="col" style={{ gap: 0 }}>
            <span className="phase-chip phase-respond" style={{ fontSize: 'clamp(18px, 1.4vw, 26px)' }}>{t.respond}</span>
            <span style={{
              fontSize: 'clamp(9px, 0.6vw, 11px)',
              color: 'var(--text-faint)',
              fontFamily: 'JetBrains Mono, monospace',
              letterSpacing: '0.18em',
              textTransform: 'uppercase'
            }}>{t.respondLabel}</span>
          </div>
        </div>
        <div>
          <div className="row between" style={{ marginBottom: 2 }}>
            <span className="label-caps" style={{ fontSize: 'clamp(9px, 0.6vw, 11px)' }}>{t.totalActive}</span>
            <span className="severity-badge severity-warning" style={{ fontSize: 9 }}>
              <span className="status-dot caution" style={{ width: 5, height: 5 }} />
              {isAr ? 'مباشر' : 'LIVE'}
            </span>
          </div>
          <div className="row" style={{ alignItems: 'baseline', gap: 10 }}>
            <div className="neom-value" style={{
              fontSize: 'clamp(38px, 3.2vw, 64px)',
              color: 'var(--phase-respond)',
              lineHeight: 0.95
            }}>{totalActive}</div>
            <div className="col" style={{ gap: 0 }}>
              <span style={{
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 'clamp(11px, 0.78vw, 13px)',
                color: 'var(--status-healthy)',
                fontWeight: 700
              }}>−8 vs baseline</span>
              <span style={{
                fontSize: 'clamp(9px, 0.6vw, 11px)',
                color: 'var(--text-faint)',
                fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace'
              }}>{isAr ? 'آخر ٦٠ دقيقة' : 'last 60 minutes'}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Block 2 — Mini-pipeline (Triage / Assigned / Active / SLA) */}
      <div className="col" style={{ gap: 8, justifyContent: 'center' }}>
        <span className="label-caps" style={{ fontSize: 'clamp(9px, 0.6vw, 11px)' }}>
          {isAr ? 'تدفق الاستجابة' : 'Response flow'}
        </span>
        <div className="row" style={{ gap: 'clamp(8px, 0.8vw, 16px)', flexWrap: 'wrap' }}>
          {[
            { v: triage, l: { en: 'Triage', ar: 'فرز' } },
            { v: assigned, l: { en: 'Assigned', ar: 'إسناد' } },
            { v: active, l: { en: 'Active', ar: 'نشط' } }
          ].map((m, i) => (
            <div key={i} className="col" style={{ gap: 1, flex: 1, minWidth: 60 }}>
              <div style={{
                fontFamily: 'JetBrains Mono, monospace',
                fontSize: 'clamp(20px, 1.6vw, 30px)',
                fontWeight: 800,
                color: 'var(--phase-respond)',
                lineHeight: 1
              }}>{m.v}</div>
              <div style={{
                fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
                fontSize: 'clamp(9px, 0.6vw, 11px)',
                color: 'var(--text-muted)',
                letterSpacing: isAr ? '0' : '0.12em',
                textTransform: isAr ? 'none' : 'uppercase',
                fontWeight: 600
              }}>{isAr ? m.l.ar : m.l.en}</div>
            </div>
          ))}
          <div className="col" style={{
            gap: 1, paddingInlineStart: 'clamp(6px, 0.6vw, 14px)',
            borderInlineStart: '1px solid var(--border-subtle)'
          }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 'clamp(18px, 1.4vw, 26px)',
              fontWeight: 700,
              color: 'var(--accent-teal)',
              lineHeight: 1,
              fontVariantNumeric: 'tabular-nums'
            }}>1:42</div>
            <div style={{
              fontSize: 'clamp(9px, 0.6vw, 11px)',
              color: 'var(--text-muted)',
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace'
            }}>{t.avgTriage}</div>
          </div>
        </div>
      </div>

      {/* Block 3 — Expanded respond cards (horizontal) */}
      <div className="col" style={{ gap: 6 }}>
        <span className="label-caps" style={{ fontSize: 'clamp(9px, 0.6vw, 11px)' }}>
          {isAr ? 'العمليات النشطة' : 'Active operations'}
        </span>
        <div style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${Math.max(1, expandedDepts.length)}, 1fr)`,
          gap: 'clamp(8px, 0.7vw, 14px)',
          minHeight: 0
        }}>
          {expandedDepts.map(d => (
            <RespondBandCard
              key={d.id}
              dept={d}
              signal={respondSignals[d.id]}
              locale={locale}
              t={t}
            />
          ))}
        </div>
      </div>

      {/* Block 4 — Coordinating directorates list */}
      <div className="col" style={{
        gap: 6,
        paddingInlineStart: 'clamp(10px, 0.9vw, 18px)',
        borderInlineStart: '1px solid var(--border-subtle)'
      }}>
        <div className="row between">
          <span className="label-caps" style={{ fontSize: 'clamp(9px, 0.6vw, 11px)' }}>
            {isAr ? 'إدارات تنسّق' : 'Coordinating'}
          </span>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.65vw, 12px)',
            color: 'var(--phase-respond)',
            fontWeight: 700
          }}>
            {compactDepts.reduce((a, d) => a + (respondSignals[d.id]?.count || 0), 0)} {isAr ? 'وحدة' : 'units'}
          </span>
        </div>
        <div className="col" style={{ gap: 1, overflow: 'hidden', maxHeight: 'clamp(110px, 10vh, 180px)' }}>
          {compactDepts.slice(0, 7).map(d => (
            <CompactRespondRow key={d.id} dept={d} signal={respondSignals[d.id]} locale={locale} />
          ))}
        </div>
      </div>
    </div>
  );
}

/* Compact horizontal card for Respond band — different layout than column version */
function RespondBandCard({ dept, signal, locale, t }) {
  const isAr = locale === 'ar';
  const sevColor = signal.severity === 'critical' ? 'var(--status-critical)'
                 : signal.severity === 'warning'  ? 'var(--status-caution)'
                 : 'var(--status-info)';
  return (
    <div className={`tech-corners`} style={{
      padding: 'clamp(8px, 0.7vw, 14px)',
      background: 'rgba(15, 23, 42, 0.55)',
      border: `1px solid ${signal.severity === 'critical' ? 'rgba(255,71,87,0.35)' : 'var(--border-subtle)'}`,
      borderInlineStart: `3px solid ${sevColor}`,
      borderRadius: 2,
      display: 'flex',
      flexDirection: 'column',
      gap: 6,
      minWidth: 0
    }}>
      <div className="row between">
        <span style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'Outfit, sans-serif',
          fontSize: 'clamp(11px, 0.78vw, 14px)',
          color: 'var(--text-primary)',
          fontWeight: 700,
          letterSpacing: isAr ? '0' : '0.04em',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          flex: 1,
          minWidth: 0
        }}>{isAr ? dept.shortAr : dept.shortEn}</span>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(9px, 0.55vw, 11px)',
          color: sevColor,
          letterSpacing: '0.12em',
          fontWeight: 700,
          flexShrink: 0,
          marginInlineStart: 8
        }}>
          {signal.severity === 'critical' ? 'CRIT' : signal.severity === 'warning' ? 'WARN' : 'OK'}
        </span>
      </div>
      <div className="row" style={{ alignItems: 'baseline', gap: 8 }}>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(22px, 1.7vw, 32px)',
          fontWeight: 800,
          color: sevColor,
          lineHeight: 1,
          fontVariantNumeric: 'tabular-nums'
        }}>{signal.count}</span>
        <span style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
          fontSize: 'clamp(10px, 0.66vw, 12px)',
          color: 'var(--text-muted)',
          fontWeight: 500
        }}>{isAr ? signal.unitAr : signal.unitEn}</span>
      </div>
      <div style={{
        fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
        fontSize: 'clamp(10px, 0.7vw, 12px)',
        color: 'var(--text-secondary)',
        lineHeight: 1.35,
        display: '-webkit-box',
        WebkitLineClamp: 2,
        WebkitBoxOrient: 'vertical',
        overflow: 'hidden'
      }}>{isAr ? signal.topAr : signal.topEn}</div>
      {/* Mini ETA + priority footer */}
      <div className="row between" style={{ marginTop: 'auto', paddingTop: 4, borderTop: '1px solid var(--border-subtle)' }}>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(9px, 0.6vw, 11px)',
          color: 'var(--text-faint)',
          letterSpacing: '0.1em'
        }}>{t.eta || 'ETA'}: <span style={{ color: 'var(--accent-teal)' }}>{signal.eta || '—'}</span></span>
        <span style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(9px, 0.6vw, 11px)',
          color: 'var(--text-faint)',
          letterSpacing: '0.1em'
        }}>{signal.severity === 'critical' ? 'P1' : signal.severity === 'warning' ? 'P2' : 'P3'}</span>
      </div>
    </div>
  );
}

window.RespondBand = RespondBand;
