// NAJDA NFC Activation — scenes 3–6
const { useEffect, useState, useRef, useMemo } = React;
const { Chapter, HorizonWaves, StarField, StatusBar, Wordmark, AdvanceHint, COLORS } = window;

// ────────────────────────────────────────────────────────────────────────────
// Scene 3 — Critical vitals
// ────────────────────────────────────────────────────────────────────────────

window.SceneVitals = function SceneVitals({ onAdvance }) {
  const [hr, setHr] = useState(142);
  const [spo, setSpo] = useState(86);
  const [temp, setTemp] = useState(35.1);

  useEffect(() => {
    const t = setInterval(() => {
      setHr(h => Math.max(128, Math.min(158, h + (Math.random() * 8 - 4) | 0)));
      setSpo(s => Math.max(82, Math.min(91, s + (Math.random() * 2 - 1) | 0)));
      setTemp(t => +(Math.max(34.6, Math.min(35.6, t + (Math.random() * 0.2 - 0.1)))).toFixed(1));
    }, 900);
    return () => clearInterval(t);
  }, []);

  // EKG path generated once; the strip is animated via CSS translate
  const ekg = useMemo(() => {
    let d = 'M 0 30';
    for (let x = 10; x < 800; x += 40) {
      // baseline jitter
      d += ` L ${x} ${30 + (Math.random() * 2 - 1)}`;
      // QRS spike
      d += ` L ${x + 4} 18 L ${x + 8} 46 L ${x + 12} 24 L ${x + 16} 30`;
    }
    return d;
  }, []);

  return (
    <div className="absolute inset-0 overflow-hidden" style={{ background: COLORS.navyDeep }}>
      <StatusBar />

      {/* Pulse halo behind everything */}
      <div className="absolute" style={{
        left: '50%', top: '50%', transform: 'translate(-50%,-50%)',
        width: 520, height: 520, borderRadius: '50%',
        background: `radial-gradient(circle, ${COLORS.sos}22, transparent 60%)`,
        animation: 'heartbeat 1.1s ease-in-out infinite',
      }}/>

      <div className="absolute left-0 right-0 top-12 px-8">
        <Chapter idx={3} total={6} label="Vitals critical" />
      </div>

      {/* Big BPM */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '16%' }}>
        <div className="flex items-baseline gap-3">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" style={{ animation: 'heartbeat 1.1s ease-in-out infinite' }}>
            <path d="M12 21 C 4 14 2 9 5 6 C 8 3 12 6 12 9 C 12 6 16 3 19 6 C 22 9 20 14 12 21 Z" fill={COLORS.sos}/>
          </svg>
          <div style={{
            fontFamily: 'Sora, system-ui, sans-serif',
            fontWeight: 600, fontSize: 96, lineHeight: 0.9,
            letterSpacing: '-0.04em',
            color: COLORS.white,
            fontFeatureSettings: "'tnum' 1",
          }}>{hr}</div>
          <div className="text-[12px] tracking-[0.22em] uppercase font-medium" style={{ color: COLORS.muted }}>bpm</div>
          <div className="ml-auto text-right">
            <div className="text-[10px] tracking-[0.22em] uppercase font-semibold" style={{ color: COLORS.sos }}>Critical</div>
            <div className="text-[10px] tracking-[0.18em] uppercase mt-1" style={{ color: COLORS.muted }}>Live</div>
          </div>
        </div>
      </div>

      {/* EKG strip */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '38%' }}>
        <div className="relative overflow-hidden h-[90px] rounded-[10px]" style={{
          background: 'rgba(255,59,92,0.04)',
          border: '1px solid rgba(255,59,92,0.18)',
        }}>
          <div className="absolute inset-y-0 left-0" style={{ width: '200%', animation: 'ekgScroll 4s linear infinite' }}>
            <svg viewBox="0 0 800 60" preserveAspectRatio="none" className="w-full h-full">
              <path d={ekg} fill="none" stroke={COLORS.sos} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          {/* gridlines */}
          <div className="absolute inset-0 opacity-30" style={{
            backgroundImage: `linear-gradient(${COLORS.sos}33 1px, transparent 1px), linear-gradient(90deg, ${COLORS.sos}33 1px, transparent 1px)`,
            backgroundSize: '40px 22px',
            mixBlendMode: 'overlay',
          }}/>
          {/* fade right edge */}
          <div className="absolute inset-y-0 right-0 w-16" style={{
            background: 'linear-gradient(90deg, transparent, #060F1C)'
          }}/>
        </div>
      </div>

      {/* Vital tiles */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '57%' }}>
        <div className="grid grid-cols-2 gap-3">
          <VitalTile label="SpO₂" value={spo} unit="%" warn />
          <VitalTile label="Core temp" value={temp} unit="°C" warn />
          <VitalTile label="Motion" value="Erratic" muted />
          <VitalTile label="Submersion" value="Yes" alert />
        </div>
      </div>

      {/* Bottom hero copy */}
      <div className="absolute left-0 right-0 px-8" style={{ bottom: '15%' }}>
        <h1 style={{
          fontFamily: 'Sora, system-ui, sans-serif',
          fontWeight: 300, fontSize: 22, lineHeight: 1.25, letterSpacing: '-0.01em',
          color: COLORS.white,
        }}>
          The body is telling a story <span style={{ color: COLORS.sos }}>no one</span> can hear.
        </h1>
      </div>

      <AdvanceHint label="Tap to continue" onTap={onAdvance} />
    </div>
  );
};

function VitalTile({ label, value, unit, warn, alert, muted }) {
  const c = alert ? COLORS.sos : warn ? COLORS.amber : muted ? COLORS.muted : COLORS.white;
  return (
    <div className="rounded-[10px] p-3.5" style={{
      background: 'rgba(244,247,251,0.025)',
      border: `1px solid ${alert ? 'rgba(255,59,92,0.25)' : warn ? 'rgba(233,162,59,0.20)' : 'rgba(244,247,251,0.06)'}`,
    }}>
      <div className="text-[9px] tracking-[0.22em] uppercase font-medium mb-1.5" style={{ color: COLORS.muted }}>{label}</div>
      <div className="flex items-baseline gap-1">
        <span style={{
          fontFamily: 'Sora, system-ui, sans-serif',
          fontSize: 22, fontWeight: 600, color: c,
          fontFeatureSettings: "'tnum' 1", letterSpacing: '-0.02em',
        }}>{value}</span>
        {unit && <span className="text-[11px]" style={{ color: COLORS.muted }}>{unit}</span>}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Scene 4 — Emergency signal detected
// ────────────────────────────────────────────────────────────────────────────

window.SceneSignal = function SceneSignal({ onAdvance }) {
  return (
    <div className="absolute inset-0 overflow-hidden" style={{ background: COLORS.navyDeep }}>
      <StatusBar tint={COLORS.amber}/>

      <div className="absolute inset-0" style={{
        background: `radial-gradient(circle at 50% 38%, ${COLORS.amber}22, transparent 55%)`,
      }}/>

      <div className="absolute left-0 right-0 top-12 px-8">
        <Chapter idx={4} total={6} label="Signal detected" />
      </div>

      {/* Concentric pulse rings + center node */}
      <div className="absolute left-1/2 -translate-x-1/2" style={{ top: '20%' }}>
        <div className="relative" style={{ width: 280, height: 280 }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} className="absolute rounded-full"
              style={{
                inset: 0,
                border: `1px solid ${COLORS.amber}`,
                animation: `signalRing 3s ease-out ${i * 0.75}s infinite`,
              }}
            />
          ))}
          {/* satellite arc */}
          <svg className="absolute inset-0" viewBox="0 0 280 280" fill="none">
            <circle cx="140" cy="140" r="110" stroke={COLORS.amber} strokeOpacity="0.18" strokeWidth="1" strokeDasharray="2 6"/>
            <circle cx="140" cy="140" r="80" stroke={COLORS.amber} strokeOpacity="0.12" strokeWidth="1"/>
          </svg>
          {/* satellite marker on outer ring */}
          <div className="absolute" style={{
            top: 18, left: '50%', transform: 'translateX(-50%)',
            width: 10, height: 10,
          }}>
            <div className="absolute inset-0 rounded-full" style={{ background: COLORS.amber, boxShadow: `0 0 20px ${COLORS.amber}` }}/>
          </div>
          {/* center bright pulse */}
          <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
            <div className="relative">
              <div style={{
                width: 14, height: 14, borderRadius: '50%',
                background: COLORS.amber,
                boxShadow: `0 0 30px ${COLORS.amber}, 0 0 60px ${COLORS.amber}66`,
                animation: 'heartbeat 1.4s ease-in-out infinite',
              }}/>
              <div className="absolute inset-0 rounded-full" style={{
                border: `1px solid ${COLORS.amber}`,
                animation: 'signalRing 1.4s ease-out infinite',
                width: 14, height: 14,
              }}/>
            </div>
          </div>
        </div>
      </div>

      {/* Telemetry strip */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '60%' }}>
        <div className="flex items-center gap-2 mb-3">
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: COLORS.amber, animation: 'blink 1s ease-in-out infinite' }}/>
          <div className="text-[10px] tracking-[0.28em] uppercase font-semibold" style={{ color: COLORS.amber }}>
            SOS · Acknowledged 0.4s
          </div>
        </div>
        <h1 style={{
          fontFamily: 'Sora, system-ui, sans-serif',
          fontWeight: 300, fontSize: 28, lineHeight: 1.15, letterSpacing: '-0.02em',
          color: COLORS.white,
        }}>
          NAJDA hears <span style={{ color: COLORS.amber, fontStyle: 'italic' }}>everything</span> the sea won't say.
        </h1>
      </div>

      {/* Bottom telemetry rows */}
      <div className="absolute left-0 right-0 px-8" style={{ bottom: '15%' }}>
        <div className="space-y-2">
          <TelemetryRow k="Origin" v="NJD-7841 · Wristband"/>
          <TelemetryRow k="Trigger" v="Vitals + Submersion"/>
          <TelemetryRow k="Network" v="LEO Satellite · Locked"/>
        </div>
      </div>

      <AdvanceHint label="Tap to continue" onTap={onAdvance}/>
    </div>
  );
};

function TelemetryRow({ k, v }) {
  return (
    <div className="flex items-center justify-between text-[12px] py-2" style={{ borderTop: '1px solid rgba(244,247,251,0.06)' }}>
      <span className="tracking-[0.18em] uppercase font-medium text-[10px]" style={{ color: COLORS.muted }}>{k}</span>
      <span className="font-mono tabular-nums" style={{ color: COLORS.white, fontFamily: 'JetBrains Mono, monospace' }}>{v}</span>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Scene 5 — GPS lock + Rescue dashboard
// ────────────────────────────────────────────────────────────────────────────

window.SceneRescue = function SceneRescue({ onAdvance }) {
  const [eta, setEta] = useState(18 * 60); // 18:00
  useEffect(() => {
    const t = setInterval(() => setEta(e => Math.max(0, e - 1)), 1000);
    return () => clearInterval(t);
  }, []);
  const m = String(Math.floor(eta / 60)).padStart(2, '0');
  const s = String(eta % 60).padStart(2, '0');

  return (
    <div className="absolute inset-0 overflow-hidden" style={{ background: COLORS.navyDeep }}>
      <StatusBar tint={COLORS.teal}/>

      <div className="absolute left-0 right-0 top-12 px-7">
        <Chapter idx={5} total={6} label="Rescue dispatched"/>
      </div>

      {/* MAP CARD */}
      <div className="absolute left-4 right-4" style={{ top: '13%' }}>
        <div className="relative rounded-[14px] overflow-hidden" style={{
          background: 'linear-gradient(180deg, #0B1A2D 0%, #07111F 100%)',
          border: '1px solid rgba(0,180,216,0.18)',
          height: 320,
        }}>
          {/* lat/lon grid */}
          <svg className="absolute inset-0 w-full h-full" viewBox="0 0 360 320" preserveAspectRatio="none">
            <defs>
              <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M 40 0 L 0 0 0 40" fill="none" stroke={COLORS.teal} strokeOpacity="0.10" strokeWidth="0.5"/>
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#grid)"/>
            {/* coastline */}
            <path d="M 0 240 Q 60 230 110 245 T 220 250 T 360 240 L 360 320 L 0 320 Z"
              fill={COLORS.navy} fillOpacity="0.7" stroke={COLORS.teal} strokeOpacity="0.3" strokeWidth="0.6"/>
            <path d="M 0 240 Q 60 230 110 245 T 220 250 T 360 240"
              fill="none" stroke={COLORS.teal} strokeOpacity="0.4" strokeWidth="0.8"/>
            {/* dashed rescue path */}
            <path d="M 60 270 Q 130 200 220 130" fill="none" stroke={COLORS.amber} strokeWidth="1.4" strokeDasharray="3 5">
              <animate attributeName="stroke-dashoffset" from="0" to="-16" dur="1.2s" repeatCount="indefinite"/>
            </path>
            {/* rescue boat */}
            <g transform="translate(60 270)">
              <circle r="14" fill={COLORS.teal} fillOpacity="0.15"/>
              <circle r="5" fill={COLORS.teal}/>
              <path d="M -3 -1 L 3 -1 L 1 2 L -1 2 Z" fill={COLORS.white}/>
            </g>
          </svg>

          {/* GPS dot */}
          <div className="absolute" style={{ left: 220, top: 130 }}>
            <div className="relative" style={{ marginLeft: -10, marginTop: -10 }}>
              {[0,1,2].map(i => (
                <div key={i} className="absolute rounded-full"
                  style={{
                    inset: 0, width: 20, height: 20,
                    border: `1px solid ${COLORS.amber}`,
                    animation: `signalRing 2.4s ease-out ${i * 0.8}s infinite`
                  }}/>
              ))}
              <div className="absolute" style={{
                left: 6, top: 6, width: 8, height: 8, borderRadius: '50%',
                background: COLORS.amber, boxShadow: `0 0 14px ${COLORS.amber}`,
                animation: 'heartbeat 1.4s ease-in-out infinite',
              }}/>
            </div>
            <div className="absolute font-mono text-[9px] tabular-nums whitespace-nowrap"
              style={{ left: 18, top: -8, color: COLORS.amber, fontFamily: 'JetBrains Mono, monospace' }}>
              25.0741° N<br/>55.1372° E
            </div>
          </div>

          {/* corner overlays */}
          <div className="absolute top-3 left-3 text-[9px] tracking-[0.22em] uppercase font-medium" style={{ color: COLORS.muted }}>
            Live · Mission #4019
          </div>
          <div className="absolute top-3 right-3 flex items-center gap-1.5">
            <div style={{ width: 5, height: 5, borderRadius: '50%', background: COLORS.teal, animation: 'blink 1.2s ease-in-out infinite' }}/>
            <span className="text-[9px] tracking-[0.22em] uppercase font-medium" style={{ color: COLORS.teal }}>Locked</span>
          </div>
          <div className="absolute bottom-3 left-3 text-[9px] uppercase tracking-[0.18em]" style={{ color: COLORS.muted, fontFamily: 'JetBrains Mono, monospace' }}>
            ARABIAN GULF · ZONE-7
          </div>
        </div>
      </div>

      {/* ETA strip */}
      <div className="absolute left-4 right-4" style={{ top: 'calc(13% + 336px)' }}>
        <div className="grid grid-cols-3 gap-2">
          <Stat label="ETA" value={`${m}:${s}`} accent={COLORS.amber}/>
          <Stat label="Vessel" value="MRC-12"/>
          <Stat label="Distance" value="6.2km"/>
        </div>
      </div>

      {/* Activity log */}
      <div className="absolute left-4 right-4" style={{ bottom: '11%' }}>
        <div className="space-y-1.5">
          <LogRow t="23:47:02" txt="GPS lock acquired" color={COLORS.teal}/>
          <LogRow t="23:47:04" txt="MRCC Dubai notified" color={COLORS.white}/>
          <LogRow t="23:47:11" txt="Rescue vessel MRC-12 dispatched" color={COLORS.amber}/>
          <LogRow t="23:47:18" txt="Family contact — pending" color={COLORS.muted}/>
        </div>
      </div>

      <AdvanceHint label="Tap to continue" onTap={onAdvance}/>
    </div>
  );
};

function Stat({ label, value, accent = COLORS.white }) {
  return (
    <div className="rounded-[10px] p-3" style={{
      background: 'rgba(244,247,251,0.025)',
      border: '1px solid rgba(244,247,251,0.06)',
    }}>
      <div className="text-[9px] tracking-[0.22em] uppercase font-medium mb-1" style={{ color: COLORS.muted }}>{label}</div>
      <div style={{
        fontFamily: 'Sora, system-ui, sans-serif',
        fontWeight: 600, fontSize: 20, color: accent,
        fontFeatureSettings: "'tnum' 1", letterSpacing: '-0.02em',
      }}>{value}</div>
    </div>
  );
}

function LogRow({ t, txt, color }) {
  return (
    <div className="flex items-center gap-3 text-[11px]">
      <span className="tabular-nums" style={{ color: COLORS.muted, fontFamily: 'JetBrains Mono, monospace' }}>{t}</span>
      <span style={{ color, opacity: color === COLORS.muted ? 0.6 : 1 }}>{txt}</span>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Scene 6 — Final CTA
// ────────────────────────────────────────────────────────────────────────────

window.SceneFinal = function SceneFinal({ onRestart }) {
  return (
    <div className="absolute inset-0 overflow-hidden" style={{ background: COLORS.navy }}>
      <StatusBar/>

      {/* Soft amber sunrise behind */}
      <div className="absolute" style={{
        left: '50%', bottom: '30%', transform: 'translateX(-50%)',
        width: 480, height: 240, borderRadius: '50%',
        background: `radial-gradient(ellipse, ${COLORS.amber}33, transparent 65%)`,
        filter: 'blur(20px)',
      }}/>

      <HorizonWaves amplitude={5} opacity={0.20} speed={26} color={COLORS.amber} lines={3}/>
      <StarField count={28} seed={11}/>

      {/* Brand */}
      <div className="absolute left-0 right-0" style={{ top: '14%' }}>
        <div className="flex justify-center"><Wordmark size={13}/></div>
      </div>

      {/* Hero copy */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '32%' }}>
        <div className="text-center" style={{ color: COLORS.white }}>
          <div className="text-[10px] tracking-[0.4em] uppercase mb-7" style={{ color: COLORS.amber }}>
            Mission Resolved
          </div>
          <h1 style={{
            fontFamily: 'Sora, system-ui, sans-serif',
            fontWeight: 300, fontSize: 38, lineHeight: 1.05, letterSpacing: '-0.025em',
          }}>
            We turn<br/>
            <span style={{ color: COLORS.muted }}>data</span> into<br/>
            <span style={{ color: COLORS.amber, fontStyle: 'italic', fontWeight: 400 }}>rescue.</span>
          </h1>
          <div className="mt-7 text-[13px] leading-relaxed" style={{ color: COLORS.muted, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>
            Your card is live. Every wave we hear, every heartbeat we listen to — yours, now too.
          </div>
        </div>
      </div>

      {/* CTAs */}
      <div className="absolute left-0 right-0 px-8" style={{ bottom: '14%' }}>
        <div className="space-y-3">
          <a href="https://najdasafety.com" target="_blank" rel="noopener noreferrer"
            className="w-full py-4 rounded-full text-[13px] tracking-[0.18em] uppercase font-semibold flex items-center justify-center gap-2" style={{
            background: COLORS.amber, color: COLORS.navy, textDecoration: 'none',
          }}>
            <span>Visit NAJDA</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
              <path d="M7 17 L17 7 M9 7 H17 V15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
          <a href="https://linktr.ee/najda" target="_blank" rel="noopener noreferrer"
            className="w-full py-3.5 rounded-full text-[12px] tracking-[0.18em] uppercase font-medium flex items-center justify-center gap-2" style={{
            background: 'transparent',
            color: COLORS.white,
            border: '1px solid rgba(244,247,251,0.18)',
            textDecoration: 'none',
          }}>
            <span>NAJDA Linktree</span>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none">
              <path d="M7 17 L17 7 M9 7 H17 V15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>
        <div className="mt-5 text-center text-[10px] tracking-[0.28em] uppercase" style={{ color: COLORS.muted, opacity: 0.7 }}>
          Card · NJD-7841 · Activated 23:47
        </div>
      </div>
    </div>
  );
};
