// NAJDA NFC Activation — six cinematic scenes
// Each scene is a self-contained component sized to fit a mobile viewport.
// All animations are CSS / SVG; transitions handled by Framer Motion in the host.

const { motion, AnimatePresence } = window.FramerMotion || {};
const { useEffect, useState, useRef, useMemo } = React;

// ────────────────────────────────────────────────────────────────────────────
// Shared atoms
// ────────────────────────────────────────────────────────────────────────────

const COLORS = {
  navy: '#0A1628',
  navyDeep: '#060F1C',
  white: '#F4F7FB',
  amber: '#E9A23B',
  teal: '#00B4D8',
  muted: '#6E7E96',
  sos: '#FF3B5C',
};

// Stable seeded star/ripple positions per session
function useSeeded(n, seed = 1) {
  return useMemo(() => {
    let s = seed;
    const rnd = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    return Array.from({ length: n }, (_, i) => ({ i, x: rnd(), y: rnd(), r: rnd(), d: rnd() }));
  }, [n, seed]);
}

// Eyebrow / chapter label
function Chapter({ idx, total, label }) {
  return (
    <div className="flex items-center gap-3 text-[11px] tracking-[0.28em] uppercase font-medium" style={{ color: COLORS.muted }}>
      <span style={{ color: COLORS.amber, fontFeatureSettings: "'tnum' 1" }}>
        {String(idx).padStart(2, '0')}
      </span>
      <span className="h-px w-6" style={{ background: COLORS.muted, opacity: 0.5 }} />
      <span>{label}</span>
      <span className="ml-auto" style={{ color: COLORS.muted, opacity: 0.6 }}>
        {String(idx).padStart(2, '0')} / {String(total).padStart(2, '0')}
      </span>
    </div>
  );
}

// Animated horizon waves — used across multiple scenes
function HorizonWaves({ amplitude = 8, opacity = 0.18, speed = 18, color = COLORS.teal, lines = 3 }) {
  return (
    <svg className="absolute inset-x-0 bottom-0 w-full pointer-events-none" viewBox="0 0 400 120" preserveAspectRatio="none" style={{ height: '40%' }}>
      <defs>
        <linearGradient id="waveFade" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0" />
          <stop offset="100%" stopColor={color} stopOpacity={opacity} />
        </linearGradient>
      </defs>
      {Array.from({ length: lines }).map((_, i) => {
        const y = 40 + i * 22;
        const a = amplitude - i * 1.5;
        const dur = speed + i * 6;
        return (
          <path
            key={i}
            d={`M -50 ${y} Q 50 ${y - a} 150 ${y} T 350 ${y} T 550 ${y}`}
            fill="none"
            stroke={color}
            strokeOpacity={opacity - i * 0.04}
            strokeWidth="1"
          >
            <animate attributeName="d"
              dur={`${dur}s`} repeatCount="indefinite"
              values={`
                M -50 ${y} Q 50 ${y - a} 150 ${y} T 350 ${y} T 550 ${y};
                M -50 ${y} Q 50 ${y + a} 150 ${y} T 350 ${y} T 550 ${y};
                M -50 ${y} Q 50 ${y - a} 150 ${y} T 350 ${y} T 550 ${y}
              `} />
          </path>
        );
      })}
    </svg>
  );
}

// Star / particle field
function StarField({ count = 40, seed = 7 }) {
  const stars = useSeeded(count, seed);
  return (
    <div className="absolute inset-0 pointer-events-none overflow-hidden">
      {stars.map(s => (
        <div key={s.i}
          className="absolute rounded-full"
          style={{
            left: `${s.x * 100}%`,
            top: `${s.y * 60}%`,
            width: 1 + s.r * 1.6,
            height: 1 + s.r * 1.6,
            background: COLORS.white,
            opacity: 0.15 + s.r * 0.4,
            animation: `twinkle ${3 + s.d * 4}s ease-in-out ${s.d * 4}s infinite`,
          }}
        />
      ))}
    </div>
  );
}

// Status bar — minimal
function StatusBar({ tint = COLORS.white, opacity = 0.9 }) {
  return (
    <div className="flex items-center justify-between px-7 pt-3 pb-1 text-[13px] font-semibold tabular-nums" style={{ color: tint, opacity }}>
      <span>23:47</span>
      <div className="flex items-center gap-1.5">
        <svg width="16" height="10" viewBox="0 0 16 10" fill="none">
          <path d="M1 8 L1 7 M5 8 L5 5 M9 8 L9 3 M13 8 L13 1" stroke={tint} strokeWidth="1.4" strokeLinecap="round"/>
        </svg>
        <svg width="14" height="10" viewBox="0 0 14 10" fill="none">
          <path d="M7 2 C 4 2 2 3.5 0.5 5 M7 4.5 C 5.5 4.5 4.5 5.2 3.5 6 M7 7 L7.01 7" stroke={tint} strokeWidth="1.3" strokeLinecap="round"/>
        </svg>
        <div className="flex items-center gap-0.5">
          <div className="w-5 h-2.5 rounded-[2px] border" style={{ borderColor: tint, opacity: 0.7 }}>
            <div className="h-full rounded-[1px]" style={{ width: '70%', background: tint }}/>
          </div>
        </div>
      </div>
    </div>
  );
}

// Logo wordmark (pure typography mark)
function Wordmark({ size = 14, color = COLORS.white }) {
  return (
    <div className="flex items-center gap-2.5">
      <svg width={size + 4} height={size + 4} viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="10" stroke={COLORS.amber} strokeWidth="1.5"/>
        <path d="M7 14 Q 10 9 12 14 T 17 14" stroke={COLORS.amber} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
      </svg>
      <span style={{
        fontFamily: 'Sora, system-ui, sans-serif',
        fontWeight: 700, fontSize: size, color,
        letterSpacing: '0.18em',
      }}>NAJDA</span>
    </div>
  );
}

// Bottom advance hint
function AdvanceHint({ label = 'Tap card to continue', onTap }) {
  return (
    <button onClick={onTap}
      className="absolute left-1/2 -translate-x-1/2 bottom-8 flex items-center gap-2.5 px-5 py-2.5 rounded-full"
      style={{
        background: 'rgba(244,247,251,0.04)',
        border: '1px solid rgba(244,247,251,0.10)',
        backdropFilter: 'blur(8px)',
        color: COLORS.white,
      }}>
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ animation: 'nfcPulse 2s ease-in-out infinite' }}>
        <path d="M3 7 Q 5 4 7 7 T 11 7" stroke={COLORS.amber} strokeWidth="1.2" fill="none" strokeLinecap="round"/>
        <path d="M2 8 Q 5 3 7 8 T 12 8" stroke={COLORS.amber} strokeWidth="1.2" fill="none" strokeLinecap="round" opacity="0.5"/>
      </svg>
      <span className="text-[11px] tracking-[0.22em] uppercase font-medium">{label}</span>
    </button>
  );
}

// ────────────────────────────────────────────────────────────────────────────
// Scene 1 — Opening: dark ocean silence
// ────────────────────────────────────────────────────────────────────────────

window.SceneOpening = function SceneOpening({ onAdvance }) {
  return (
    <div className="absolute inset-0 overflow-hidden" style={{ background: COLORS.navy }}>
      <StatusBar />
      <StarField count={60} seed={3} />

      {/* deep gradient & subtle vignette */}
      <div className="absolute inset-0" style={{
        background: 'radial-gradient(ellipse 80% 60% at 50% 100%, rgba(0,180,216,0.08), transparent 60%)'
      }}/>
      <div className="absolute inset-0" style={{
        background: 'radial-gradient(ellipse 100% 100% at 50% 50%, transparent 40%, rgba(0,0,0,0.6) 100%)'
      }}/>

      <HorizonWaves amplitude={6} opacity={0.22} speed={22} lines={4}/>

      {/* moonlight */}
      <div className="absolute" style={{
        left: '50%', top: '22%', transform: 'translateX(-50%)',
        width: 180, height: 180, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(244,247,251,0.10), transparent 65%)',
        filter: 'blur(8px)',
      }}/>

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

      {/* Hero copy */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '38%' }}>
        <div className="text-center" style={{ color: COLORS.white }}>
          <div className="text-[10px] tracking-[0.4em] uppercase mb-6" style={{ color: COLORS.amber, opacity: 0.85 }}>
            Card Activated
          </div>
          <h1 style={{
            fontFamily: 'Sora, system-ui, sans-serif',
            fontWeight: 300,
            fontSize: 38,
            lineHeight: 1.08,
            letterSpacing: '-0.02em',
          }}>
            Somewhere out<br/>
            on the water,<br/>
            <span style={{ fontStyle: 'italic', fontWeight: 300, color: COLORS.teal }}>silence falls.</span>
          </h1>
        </div>
      </div>

      {/* Bottom: tiny coordinates whisper */}
      <div className="absolute left-0 right-0 bottom-24 px-8 text-center">
        <div className="text-[11px] tracking-[0.3em] uppercase font-semibold tabular-nums" style={{ color: COLORS.amber, opacity: 0.95, fontFamily: 'JetBrains Mono, monospace' }}>
          25.0741° N · 55.1372° E
        </div>
      </div>

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

// ────────────────────────────────────────────────────────────────────────────
// Scene 2 — Lost at sea: isolation
// ────────────────────────────────────────────────────────────────────────────

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

      {/* heavy sea gradient */}
      <div className="absolute inset-0" style={{
        background: 'linear-gradient(180deg, #060F1C 0%, #0A1628 55%, #07111F 100%)'
      }}/>

      {/* far ocean haze */}
      <div className="absolute left-0 right-0" style={{ top: '40%', height: 1, background: 'linear-gradient(90deg, transparent, rgba(244,247,251,0.12), transparent)' }}/>

      <HorizonWaves amplitude={4} opacity={0.14} speed={28} lines={5}/>

      {/* Tiny lone figure — abstract dot with reflection */}
      <div className="absolute left-1/2 -translate-x-1/2" style={{ top: '50%' }}>
        <div className="relative">
          <div style={{
            width: 6, height: 6, borderRadius: '50%',
            background: COLORS.white, opacity: 0.9,
            boxShadow: `0 0 12px ${COLORS.white}`,
            animation: 'lonely 3s ease-in-out infinite',
          }}/>
          {/* reflection */}
          <div style={{
            width: 3, height: 18, marginTop: 6, marginLeft: 1.5,
            background: `linear-gradient(180deg, ${COLORS.white}33, transparent)`,
            opacity: 0.5,
          }}/>
          {/* widening ripples */}
          {[0, 1, 2].map(i => (
            <div key={i} className="absolute"
              style={{
                left: '50%', top: 3, transform: 'translateX(-50%)',
                width: 60, height: 10, borderRadius: '50%',
                border: `1px solid ${COLORS.teal}`,
                opacity: 0.3,
                animation: `ripple 4s ease-out ${i * 1.3}s infinite`,
              }}
            />
          ))}
        </div>
      </div>

      {/* Top chapter */}
      <div className="absolute left-0 right-0 top-12 px-8">
        <Chapter idx={2} total={6} label="Isolation" />
      </div>

      {/* Distance / signal cluster */}
      <div className="absolute left-0 right-0 px-8" style={{ top: '14%' }}>
        <div className="flex items-start justify-between">
          <div>
            <div className="text-[10px] tracking-[0.28em] uppercase mb-2" style={{ color: COLORS.muted }}>Distance from shore</div>
            <div style={{
              fontFamily: 'Sora, system-ui, sans-serif',
              fontWeight: 600, fontSize: 30, color: COLORS.white,
              fontFeatureSettings: "'tnum' 1", letterSpacing: '-0.02em',
            }}>
              47.3<span className="text-base ml-1 font-normal" style={{ color: COLORS.muted }}>km</span>
            </div>
          </div>
          <div className="text-right">
            <div className="text-[10px] tracking-[0.28em] uppercase mb-2" style={{ color: COLORS.muted }}>Signal</div>
            <div className="flex items-end gap-1 justify-end h-[30px]">
              {[1, 2, 3, 4].map(i => (
                <div key={i}
                  style={{
                    width: 4, height: 4 + i * 4,
                    background: i === 1 ? COLORS.sos : 'rgba(244,247,251,0.10)',
                    borderRadius: 1,
                    animation: i === 1 ? 'signalPulse 1.8s ease-in-out infinite' : 'none',
                  }}/>
              ))}
            </div>
            <div className="text-[10px] tracking-[0.18em] uppercase mt-1.5 font-medium" style={{ color: COLORS.sos }}>
              Weak
            </div>
          </div>
        </div>
      </div>

      {/* Hero copy lower */}
      <div className="absolute left-0 right-0 px-8" style={{ bottom: '22%' }}>
        <div style={{ color: COLORS.white }}>
          <h1 style={{
            fontFamily: 'Sora, system-ui, sans-serif',
            fontWeight: 300, fontSize: 30, lineHeight: 1.15, letterSpacing: '-0.02em',
          }}>
            One fisherman.<br/>
            Forty-seven kilometers<br/>
            from <span style={{ color: COLORS.teal, fontStyle: 'italic' }}>anyone</span>.
          </h1>
          <div className="mt-5 text-[13px] leading-relaxed font-normal" style={{ color: COLORS.muted, maxWidth: 280 }}>
            No radio. No bars. No way to call for help. The sea keeps its secrets.
          </div>
        </div>
      </div>

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

Object.assign(window, {
  Chapter, HorizonWaves, StarField, StatusBar, Wordmark, AdvanceHint, COLORS,
});
