/* MANARA — Top strip + Pipeline + AI Insight bar */

const { useState: useStateTop, useEffect: useEffectTop, useRef: useRefTop } = React;

function MoiEmblem({ size = 48 }) {
  // Real Ministry of Interior emblem (UAE).
  return (
    <div style={{
      width: size,
      height: size,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      filter: 'drop-shadow(0 0 8px rgba(212,175,55,0.25))',
      flexShrink: 0
    }}>
      <img src="assets/moi-emblem.png" alt="UAE Ministry of Interior"
        style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
    </div>
  );
}

function WonderfulMark({ height = 14, color = 'var(--text-muted)' }) {
  // Wonderful logo — inverted to white via CSS filter (source is black on transparent).
  return (
    <img src="assets/wonderful-logo.png" alt="Wonderful"
      style={{
        height: height,
        width: 'auto',
        objectFit: 'contain',
        display: 'block',
        // Source PNG is black; invert for dark backgrounds and tint to current color
        filter: 'invert(1) brightness(1.6) opacity(0.85)'
      }} />
  );
}

function ManaraLighthouse({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" style={{ filter: 'drop-shadow(0 0 6px rgba(0,229,204,0.5))' }}>
      <defs>
        <linearGradient id="beamGrad" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="rgba(0,229,204,0)" />
          <stop offset="50%" stopColor="rgba(0,229,204,0.7)" />
          <stop offset="100%" stopColor="rgba(0,229,204,0)" />
        </linearGradient>
      </defs>
      {/* Beam */}
      <path d="M 4 8 L 28 4 L 28 12 L 4 8 Z" fill="url(#beamGrad)" opacity="0.7" />
      <path d="M 4 24 L 28 28 L 28 20 L 4 24 Z" fill="url(#beamGrad)" opacity="0.5" />
      {/* Tower */}
      <rect x="13" y="6" width="6" height="3" fill="#0097A7" />
      <rect x="14" y="9" width="4" height="2" fill="#00E5CC" />
      <path d="M 12 11 L 20 11 L 19 28 L 13 28 Z" fill="#0097A7" />
      <line x1="13" y1="16" x2="19" y2="16" stroke="#050A12" strokeWidth="0.6" />
      <line x1="13" y1="22" x2="19" y2="22" stroke="#050A12" strokeWidth="0.6" />
      <circle cx="16" cy="9.5" r="1.2" fill="#fff" />
    </svg>
  );
}

function TopStrip({ locale, setLocale, briefingMode, threatLevel, t, scenarioIndex, scenarioCount, scenarioTitle, voiceCommands }) {
  const isAr = locale === 'ar';
  const [now, setNow] = useStateTop(new Date());
  useEffectTop(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  const pad = (n) => String(n).padStart(2, '0');
  const clockText = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
  const dateOpts = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
  const dateText = now.toLocaleDateString(isAr ? 'ar-AE' : 'en-GB', dateOpts);

  // Hijri date via Umm al-Qura calendar (UAE official)
  const hijriText = (() => {
    try {
      const fmt = new Intl.DateTimeFormat(
        (isAr ? 'ar-SA' : 'en-GB') + '-u-ca-islamic-umalqura',
        { day: 'numeric', month: 'long', year: 'numeric' }
      );
      const out = fmt.format(now);
      // en-GB Intl format: "10 Dhuʻl-Qiʻdah 1447 AH" → reformat to "Dhuʻl-Qiʻdah 10, 1447 AH"
      if (!isAr) {
        const m = out.match(/^(\d+)\s+(.+?)\s+(\d+)\s*AH?$/);
        if (m) return `${m[2]} ${m[1]}, ${m[3]} AH`;
      }
      return out;
    } catch (e) {
      return '';
    }
  })();

  const threatColors = {
    NORMAL: '#00E5CC', GUARDED: '#38BDF8', ELEVATED: '#FFB800', HIGH: '#F97316', SEVERE: '#FF4757'
  };
  const threatLabel = isAr ? t.threatLevels[threatLevel.toLowerCase()] : threatLevel;

  return (
    <div className="row between wall-px" style={{
      height: 'clamp(78px, 6vh, 110px)',
      borderBottom: '1px solid var(--border-subtle)',
      background: 'rgba(5, 10, 18, 0.7)',
      backdropFilter: 'blur(20px)',
      position: 'relative',
      gap: 'clamp(16px, 1.5vw, 36px)',
      flexShrink: 0
    }}>
      {/* Left: emblem + wordmark */}
      <div className="row" style={{ gap: 'clamp(14px, 1.1vw, 22px)' }}>
        <MoiEmblem size={62} />
        <div style={{
          width: 1,
          alignSelf: 'stretch',
          marginBlock: 8,
          background: 'linear-gradient(to bottom, transparent, rgba(212,175,55,0.35), transparent)'
        }} />
        <div className="col" style={{ gap: 4, justifyContent: 'center' }}>
          {/* Ministry name — bilingual */}
          <div style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
            fontSize: 'clamp(10px, 0.7vw, 13px)',
            color: 'var(--accent-gold)',
            letterSpacing: isAr ? '0.05em' : '0.28em',
            fontWeight: 600,
            textTransform: isAr ? 'none' : 'uppercase',
            lineHeight: 1.1
          }}>
            {isAr ? 'وزارة الداخلية — الإمارات العربية المتحدة' : 'United Arab Emirates · Ministry of Interior'}
          </div>
          {/* Platform name */}
          <div className="row" style={{ gap: 12, alignItems: 'baseline' }}>
            <ManaraLighthouse size={22} />
            <div className="neom-title" style={{
              fontSize: 'clamp(26px, 2.2vw, 40px)',
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'Outfit, sans-serif',
              fontWeight: 800,
              letterSpacing: isAr ? '0' : '0.1em',
              lineHeight: 1
            }}>
              {t.manara}
            </div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 'clamp(12px, 0.82vw, 16px)',
              color: 'var(--text-muted)',
              letterSpacing: '0.3em',
              fontWeight: 500
            }}>
              {isAr ? '— LIGHTHOUSE' : '— منارة'}
            </div>
          </div>
          <div style={{
            fontSize: 'clamp(10px, 0.68vw, 13px)',
            color: 'var(--text-faint)',
            letterSpacing: '0.18em',
            fontFamily: 'JetBrains Mono, monospace',
            textTransform: 'uppercase'
          }}>
            {t.tagline}
          </div>
        </div>
      </div>

      {/* Center-left: live status + threat level */}
      <div className="row" style={{ gap: 'clamp(12px, 1.2vw, 28px)' }}>
        <div className="row" style={{ gap: 8 }}>
          <span style={{
            width: 8, height: 8, borderRadius: '50%',
            background: '#00E5CC',
            boxShadow: '0 0 10px #00E5CC',
            animation: 'dotPulse 1.6s ease-in-out infinite'
          }} />
          <span className="label-caps" style={{ color: 'var(--accent-teal)' }}>{t.live}</span>
        </div>

        <div className="col" style={{ alignItems: 'center', gap: 2, padding: '4px 14px',
          border: `1px solid ${threatColors[threatLevel]}40`,
          background: `${threatColors[threatLevel]}10`,
          borderRadius: 2
        }}>
          <span style={{
            fontSize: 'clamp(9px, 0.62vw, 12px)',
            color: 'var(--text-muted)',
            letterSpacing: '0.2em',
            fontFamily: 'JetBrains Mono, monospace',
            fontWeight: 600
          }}>{t.threatLabel}</span>
          <span style={{
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
            fontSize: 'clamp(14px, 1.1vw, 20px)',
            color: threatColors[threatLevel],
            fontWeight: 700,
            letterSpacing: '0.18em'
          }}>{threatLabel}</span>
        </div>
      </div>

      {/* Right: Ask MANARA inline + clock + language toggle */}
      <div className="row" style={{ gap: 'clamp(14px, 1.4vw, 32px)', marginLeft: 'auto', flex: 1, justifyContent: 'flex-end' }}>
        {/* Ask MANARA — inline voice affordance with chips */}
        {voiceCommands && (
          <div style={{ flex: 1, maxWidth: 'clamp(320px, 32vw, 620px)', minWidth: 0 }}>
            <window.InlineVoiceBar locale={locale} t={t} voiceCommands={voiceCommands} />
          </div>
        )}

        <div className="col" style={{ alignItems: 'flex-end', gap: 0 }}>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(20px, 1.5vw, 28px)',
            fontWeight: 700,
            color: 'var(--text-primary)',
            letterSpacing: '0.05em',
            fontVariantNumeric: 'tabular-nums'
          }}>{clockText}</span>
          <span style={{
            fontSize: 'clamp(10px, 0.65vw, 13px)',
            color: 'var(--text-muted)',
            fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
            letterSpacing: isAr ? '0' : '0.1em'
          }}>{dateText}{hijriText ? ' • ' + hijriText : ''}</span>
        </div>

        <div className="row" style={{
          border: '1px solid var(--border-medium)',
          borderRadius: 2,
          overflow: 'hidden',
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(12px, 0.8vw, 15px)',
          fontWeight: 700,
          letterSpacing: '0.1em',
          cursor: 'pointer'
        }}
        onClick={() => setLocale(locale === 'ar' ? 'en' : 'ar')}>
          <span style={{
            padding: '6px 12px',
            background: locale === 'en' ? 'var(--accent-teal)' : 'transparent',
            color: locale === 'en' ? '#050A12' : 'var(--text-secondary)',
            transition: 'all 200ms'
          }}>EN</span>
          <span style={{
            padding: '6px 12px',
            background: locale === 'ar' ? 'var(--accent-teal)' : 'transparent',
            color: locale === 'ar' ? '#050A12' : 'var(--text-secondary)',
            fontFamily: 'Tajawal, sans-serif',
            transition: 'all 200ms'
          }}>عربي</span>
        </div>

        {/* Powered by Wonderful — small attribution lockup */}
        <div className="col" style={{
          alignItems: isAr ? 'flex-start' : 'flex-end',
          gap: 2,
          paddingInlineStart: 'clamp(8px, 0.8vw, 16px)',
          borderInlineStart: '1px solid var(--border-subtle)'
        }}>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(8px, 0.55vw, 10px)',
            color: 'var(--text-faint)',
            letterSpacing: '0.22em',
            textTransform: 'uppercase',
            fontWeight: 500
          }}>
            {isAr ? 'مُشغّل بواسطة' : 'Powered by'}
          </span>
          <WonderfulMark height={14} />
        </div>
      </div>

      {/* Drifting scan line */}
      <div className="scan-line" />

      {/* Briefing mode banner (if not minister) */}
      {briefingMode && briefingMode !== 'minister' && (
        <div className="briefing-banner">
          {t.briefingMode}: {t.modes[briefingMode]}
        </div>
      )}
    </div>
  );
}

/* ---------- Pipeline strip ---------- */
function PipelineStrip({ locale, t, stages, scenario }) {
  const isAr = locale === 'ar';
  // Stages = 7 total: 2 detect + 3 respond + 2 deliver — phase headers must align precisely to those grid spans.
  const phaseSpans = [
    { phase: 'detect',  label: t.detect,  color: 'var(--phase-detect)',  span: 2, sub: isAr ? 'إشارات • كشوف' : 'Signals • Detections' },
    { phase: 'respond', label: t.respond, color: 'var(--phase-respond)', span: 3, sub: isAr ? 'فرز • إسناد • نشط' : 'Triage • Assign • Active' },
    { phase: 'deliver', label: t.deliver, color: 'var(--phase-deliver)', span: 2, sub: isAr ? 'حل • أثر' : 'Resolution • Outcome' }
  ];

  const phaseColorFor = (p) => p === 'detect' ? 'var(--phase-detect)' : p === 'respond' ? 'var(--phase-respond)' : 'var(--phase-deliver)';

  return (
    <div className="float-card" style={{
      padding: 'clamp(10px, 0.9vw, 18px) clamp(14px, 1.2vw, 24px)',
      flexShrink: 0
    }}>
      {/* Phase header row — grid-aligned to the 7 stage columns below */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(7, 1fr)',
        gap: 0,
        marginBottom: 8
      }}>
        {phaseSpans.map((g) => (
          <div key={g.phase}
            className={`phase-bg-${g.phase}`}
            style={{
              gridColumn: `span ${g.span}`,
              padding: '6px 12px',
              marginInline: 4,
              borderTop: `2px solid ${g.color}`,
              borderRadius: '0 0 2px 2px',
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              position: 'relative'
            }}>
            <div style={{
              width: 6, height: 6, borderRadius: '50%',
              background: g.color, boxShadow: `0 0 10px ${g.color}`
            }} />
            <span className={`phase-chip phase-${g.phase}`} style={{ fontSize: 'clamp(12px, 0.85vw, 16px)' }}>
              {g.label}
            </span>
            <span style={{
              fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
              fontSize: 'clamp(10px, 0.66vw, 12px)',
              color: 'var(--text-faint)',
              letterSpacing: isAr ? '0' : '0.1em',
              marginInlineStart: 'auto',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis'
            }}>{g.sub}</span>
          </div>
        ))}
      </div>

      {/* 7-stage grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(7, 1fr)',
        gap: 0,
        position: 'relative'
      }}>
        {stages.map((stage, i) => {
          const phaseColor = phaseColorFor(stage.phase);
          const isPhaseEnd = i < stages.length - 1 && stages[i + 1].phase !== stage.phase;
          return (
            <div key={stage.id} className="col" style={{
              alignItems: 'center',
              gap: 4,
              padding: '12px 4px 6px',
              position: 'relative',
              borderInlineEnd: i < stages.length - 1 ? `1px solid ${isPhaseEnd ? 'rgba(0, 229, 204, 0.25)' : 'rgba(0, 229, 204, 0.08)'}` : 'none'
            }}>
              {/* Stage dot at top */}
              <div style={{
                position: 'absolute',
                top: -4, left: '50%', transform: 'translateX(-50%)',
                width: 8, height: 8, borderRadius: '50%',
                background: phaseColor,
                boxShadow: `0 0 12px ${phaseColor}`
              }} />
              <div className="neom-value" style={{
                fontSize: 'clamp(20px, 1.5vw, 30px)',
                color: phaseColor,
                lineHeight: 1
              }}>
                {stage.count.toLocaleString()}
              </div>
              <div style={{
                fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace',
                fontSize: 'clamp(10px, 0.7vw, 12px)',
                color: 'var(--text-muted)',
                letterSpacing: isAr ? '0' : '0.15em',
                textTransform: isAr ? 'none' : 'uppercase',
                fontWeight: 600,
                textAlign: 'center',
                whiteSpace: 'nowrap'
              }}>
                {isAr ? stage.ar : stage.en}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- AI Insight Bar (rotating bottom bar) ---------- */
function AiInsightBar({ locale, t, insights, currentInsight }) {
  const isAr = locale === 'ar';
  const ins = currentInsight;
  if (!ins) return null;

  const sevColor = ins.severity === 'critical' ? 'var(--status-critical)'
                 : ins.severity === 'warning' ? 'var(--status-caution)'
                 : ins.severity === 'positive' ? 'var(--status-healthy)'
                 : 'var(--status-info)';

  const text = isAr ? ins.ar : ins.en;
  const [displayed, setDisplayed] = useStateTop('');
  useEffectTop(() => {
    setDisplayed('');
    let i = 0;
    const id = setInterval(() => {
      i++;
      setDisplayed(text.slice(0, i));
      if (i >= text.length) clearInterval(id);
    }, 20);
    return () => clearInterval(id);
  }, [text]);

  return (
    <div className="float-card wall-p row" style={{
      gap: 'clamp(14px, 1.4vw, 32px)',
      flexShrink: 0,
      borderColor: ins.severity === 'critical' ? 'rgba(255,71,87,0.4)' : 'var(--border-medium)'
    }}>
      {/* Agent badge */}
      <div className="col" style={{ alignItems: 'center', gap: 4, minWidth: 'clamp(110px, 9vw, 180px)' }}>
        <div style={{
          width: 'clamp(40px, 3vw, 56px)',
          height: 'clamp(40px, 3vw, 56px)',
          borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(212,175,55,0.2), rgba(212,175,55,0.04))',
          border: '1px solid rgba(212,175,55,0.4)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative'
        }}>
          <svg width="60%" height="60%" viewBox="0 0 24 24" fill="none">
            <path d="M 12 4 L 14 10 L 20 12 L 14 14 L 12 20 L 10 14 L 4 12 L 10 10 Z" fill="url(#goldGrad)" />
          </svg>
        </div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace',
          fontSize: 'clamp(12px, 0.78vw, 15px)',
          color: 'var(--accent-gold)',
          fontWeight: 700,
          letterSpacing: '0.12em'
        }}>{ins.agent}</div>
        <div style={{
          fontSize: 'clamp(9px, 0.6vw, 11px)',
          color: 'var(--text-faint)',
          fontFamily: 'JetBrains Mono, monospace',
          letterSpacing: '0.15em',
          textTransform: 'uppercase'
        }}>{isAr ? 'عميل ذكاء اصطناعي' : 'WONDERFUL AGENT'}</div>
      </div>

      {/* Severity stripe */}
      <div style={{
        width: 3,
        alignSelf: 'stretch',
        background: sevColor,
        boxShadow: `0 0 8px ${sevColor}`,
        flexShrink: 0
      }} />

      {/* Insight content */}
      <div className="col" style={{ flex: 1, gap: 6 }}>
        <div className="row" style={{ gap: 12, flexWrap: 'wrap' }}>
          <span className={`severity-badge severity-${ins.severity}`}>
            {ins.severity === 'positive' ? (isAr ? 'إيجابي' : 'POSITIVE')
              : ins.severity === 'warning' ? (isAr ? 'تنبيه' : 'WARNING')
              : ins.severity === 'critical' ? (isAr ? 'حرج' : 'CRITICAL')
              : (isAr ? 'معلومة' : 'INFO')}
          </span>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(11px, 0.72vw, 14px)',
            color: 'var(--text-muted)',
            letterSpacing: '0.15em',
            textTransform: 'uppercase'
          }}>
            {isAr ? '↳ الإدارة:' : '↳ DEPT:'} <span style={{ color: 'var(--accent-teal)' }}>{ins.dept}</span>
          </span>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 'clamp(11px, 0.72vw, 14px)',
            color: 'var(--text-faint)',
            letterSpacing: '0.1em'
          }}>{new Date().toLocaleTimeString('en-GB')}</span>
        </div>
        <div style={{
          fontFamily: isAr ? 'Tajawal, sans-serif' : 'DM Sans, sans-serif',
          fontSize: 'clamp(16px, 1.1vw, 22px)',
          fontWeight: 500,
          color: 'var(--text-primary)',
          lineHeight: 1.4
        }}>
          {displayed}
          {displayed.length < text.length && <span className="tw-cursor" />}
        </div>
      </div>
    </div>
  );
}

window.MoiEmblem = MoiEmblem;
window.ManaraLighthouse = ManaraLighthouse;
window.WonderfulMark = WonderfulMark;
window.TopStrip = TopStrip;
window.PipelineStrip = PipelineStrip;
window.AiInsightBar = AiInsightBar;
