// Colleen × Sam — JARVIS HUD, coastal edition.
// The same holographic HUD Reid/Max have, but tuned SOFT for the beach:
// thinner translucent rings, teal↔gold turn colors, a calm white-aqua
// data-sphere core, floating over the CoastBg (sky / sea / sand).
// Keeps Colleen's signature: busier white shimmer when SHE is talking.

function SamJarvisOrb({ state, intensity = 1, motionLevel = 1, mood = 'sunset', ceremony = false }) {
  const t = clUseTime(true);
  const offline = state === 'offline';
  const muted = state === 'muted';
  const live = !offline && !muted;
  const motion = motionLevel;
  const isYou = state === 'listening';   // she's talking
  const m = clMode(state);               // { hi, mid, base, lo, deep } teal or gold

  const stateAmp = (
    state === 'speaking'  ? 1.0 :
    state === 'listening' ? 0.22 :
    state === 'thinking'  ? 0.3 :
    state === 'connecting'? 0.4 :
    state === 'idle'      ? 0.14 :
    muted                 ? 0.1 : 0
  ) * intensity * motionLevel;
  const amp = clVoiceAmp(t, stateAmp);
  const bands = clSpectrum(t, 110, stateAmp);
  // Spin multiplier: barely turns while she talks, whirls when Sam speaks.
  const sm = motionLevel * (state === 'speaking' ? 2.6 : state === 'thinking' ? 1.4 : state === 'listening' ? 0.45 : 1);

  const C = 160;
  const oa = (c, a) => {
    // c is hex or oklch; wrap with alpha
    if (c.startsWith('#')) {
      const n = parseInt(c.slice(1), 16);
      return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`;
    }
    return c.replace(/\)\s*$/, ` / ${a})`);
  };
  const hi = m.hi, mid = m.mid, base = m.base, deep = m.deep;
  // Softer glow than the sci-fi builds — gentle, not laser-sharp
  const glow = live ? `drop-shadow(0 0 4px ${oa(hi, 0.6)})` : 'none';
  const spin = (deg) => `rotate(${deg}deg)`;
  const arc = (cx, cy, r, a0, a1) => {
    const p0 = [cx + r * Math.cos(a0), cy + r * Math.sin(a0)];
    const p1 = [cx + r * Math.cos(a1), cy + r * Math.sin(a1)];
    const large = (a1 - a0) % (Math.PI * 2) > Math.PI ? 1 : 0;
    return `M ${p0[0]} ${p0[1]} A ${r} ${r} 0 ${large} 1 ${p1[0]} ${p1[1]}`;
  };
  const segments = (radius, segs, col, sw, op) =>
    Array.from({ length: segs }, (_, i) => {
      const span = (Math.PI * 2) / segs;
      return <path key={i} d={arc(C, C, radius, i * span + span * 0.16, i * span + span * 0.84)}
        stroke={col} strokeWidth={sw} fill="none" opacity={op} strokeLinecap="round" />;
    });

  return (
    <div style={{ position: 'absolute', inset: 0, background: '#06201f', overflow: 'hidden' }}>
      {/* Beach stays — sky / sea / sand / sun */}
      <CoastBg t={t} mood={mood} offline={offline} />

      {/* gentle center vignette so the HUD reads over bright water */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(64% 44% at 50% 38%, rgba(4,24,23,0.34) 0%, transparent 72%)' }} />

      {/* ── SOFT JARVIS HUD ── */}
      <div style={{
        position: 'absolute', left: '50%', top: 300, transform: `translate(-50%,-50%) scale(${1 + amp * 0.26})`,
        width: 320, height: 320,
        filter: muted ? 'grayscale(0.5) brightness(0.7)' : 'none',
        animation: ceremony ? 'ceremonyFade 1.6s cubic-bezier(0.2,0.8,0.2,1) both' : 'none',
      }}>
        {/* soft volumetric glow */}
        <div style={{ position: 'absolute', inset: 64, borderRadius: '50%',
          background: `radial-gradient(circle, ${oa(base, 0.5)} 0%, ${oa(deep, 0.16)} 48%, transparent 72%)`,
          filter: 'blur(30px)', opacity: offline ? 0.3 : 0.85 + amp * 0.25 }} />

        {/* outer swirling dashed rings — thin + translucent */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible', transform: spin(t * 4 * sm), transformOrigin: '50% 50%' }}>
          <circle cx={C} cy={C} r="152" fill="none" stroke={oa(hi, live ? 0.4 : 0.14)} strokeWidth="0.8" strokeDasharray="1 12" strokeLinecap="round" />
          <circle cx={C} cy={C} r="143" fill="none" stroke={oa(mid, live ? 0.34 : 0.1)} strokeWidth="0.7" strokeDasharray="26 18" />
        </svg>
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible', transform: spin(-t * 7 * sm), transformOrigin: '50% 50%' }}>
          <circle cx={C} cy={C} r="128" fill="none" stroke={oa(hi, live ? 0.42 : 0.14)} strokeWidth="0.8" strokeDasharray="44 26" strokeLinecap="round" style={{ filter: glow }} />
        </svg>

        {/* gentle dotted scale ring (replaces sharp ticks) */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
          {Array.from({ length: 60 }, (_, i) => {
            const a = (i / 60) * Math.PI * 2;
            const big = i % 5 === 0;
            return <circle key={i} cx={C + Math.cos(a) * 146} cy={C + Math.sin(a) * 146}
              r={big ? 1.3 : 0.7} fill={oa(mid, live ? 0.5 : 0.16)} />;
          })}
        </svg>

        {/* rounded segmented ring */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible', transform: spin(t * 6 * sm), transformOrigin: '50% 50%', filter: glow }}>
          {segments(134, 4, hi, 2, live ? 0.7 : 0.2)}
          {Array.from({ length: 4 }, (_, i) => { const a = (i / 4) * Math.PI * 2; return <circle key={i} cx={C + Math.cos(a) * 134} cy={C + Math.sin(a) * 134} r={2} fill={hi} opacity={live ? 0.85 : 0.25} />; })}
        </svg>
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible', transform: spin(-t * 9 * sm), transformOrigin: '50% 50%' }}>
          {segments(116, 3, mid, 1.3, live ? 0.55 : 0.18)}
        </svg>

        {/* voice spectrum ring — subtle, fewer prominent lines */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
          {bands.map((v, i) => {
            const a = (i / bands.length) * Math.PI * 2 - Math.PI / 2;
            const inner = 88, outer = inner + (live ? 2 + v * 14 : 1.5);
            const tick = i % 10 < 2;
            return <line key={i} x1={C + Math.cos(a) * inner} y1={C + Math.sin(a) * inner}
              x2={C + Math.cos(a) * outer} y2={C + Math.sin(a) * outer}
              stroke={tick ? hi : mid} strokeWidth={tick ? 1.5 : 0.8} strokeLinecap="round"
              opacity={offline ? 0.12 : (tick ? 0.4 : 0.22) + v * 0.3} style={tick ? { filter: glow } : {}} />;
          })}
        </svg>

        {/* ── SHE'S TALKING — extra busy white shimmer + inward motes (her signature) ── */}
        {isYou && (
          <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
            {Array.from({ length: 28 }, (_, i) => {
              const a = (i / 28) * Math.PI * 2 + 0.05;
              const fl = 0.5 + 0.5 * Math.sin(t * (6 + (i % 7)) + i * 1.3);
              const inner = 92, len = 10 + fl * (22 + amp * 44);
              return <line key={i} x1={C + Math.cos(a) * inner} y1={C + Math.sin(a) * inner}
                x2={C + Math.cos(a) * (inner + len)} y2={C + Math.sin(a) * (inner + len)}
                stroke="#eafdff" strokeWidth={0.8 + fl * 0.8} strokeLinecap="round" opacity={0.08 + fl * 0.26} />;
            })}
            {Array.from({ length: 26 }, (_, i) => {
              const a = (i / 26) * Math.PI * 2 + i * 0.7;
              const ph = ((t * 0.4 + i / 26) % 1 + 1) % 1, r = 150 - ph * 70;
              const fade = Math.sin(ph * Math.PI);
              return <circle key={i} cx={C + Math.cos(a) * r} cy={C + Math.sin(a) * r} r={1.2 + amp * 1.2}
                fill="#ffffff" opacity={fade * (0.4 + amp * 0.4)} />;
            })}
          </svg>
        )}

        {/* fast partial arc + scanner */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible', transform: spin(t * 20 * sm), transformOrigin: '50% 50%' }}>
          <path d={arc(C, C, 76, -1.0, 0.5)} stroke={hi} strokeWidth="2.2" fill="none" opacity={live ? 0.8 : 0.2} strokeLinecap="round" style={{ filter: glow }} />
          <circle cx={C + 76} cy={C} r="2.4" fill="#ffffff" opacity={live ? 0.95 : 0.3} style={{ filter: glow }} />
        </svg>

        {/* ── CALM WHITE-AQUA DATA-SPHERE CORE ── */}
        <svg width="320" height="320" viewBox="0 0 320 320" style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
          <defs>
            <radialGradient id="samCore" cx="50%" cy="48%" r="50%">
              <stop offset="0%" stopColor="#ffffff" stopOpacity={live ? 1 : 0.3} />
              <stop offset="42%" stopColor="#e8fdff" stopOpacity={live ? 0.95 : 0.3} />
              <stop offset="100%" stopColor={hi} stopOpacity="0" />
            </radialGradient>
          </defs>
          {(() => {
            const R = 70, ry = t * 0.3 * motion;
            const rand = clSeedRand(71);
            const pts = Array.from({ length: 58 }, () => ({ theta: rand() * Math.PI * 2, phi: Math.acos(2 * rand() - 1), tw: rand() * Math.PI * 2 }));
            const proj = (p) => { const th = p.theta + ry; const x3 = Math.sin(p.phi) * Math.cos(th); const y3 = Math.cos(p.phi); const z3 = Math.sin(p.phi) * Math.sin(th); return { x: C + x3 * R, y: C + y3 * R, depth: (z3 + 1) / 2 }; };
            const P = pts.map(proj);
            const gF = live ? `drop-shadow(0 0 2px ${oa(hi, 0.8)})` : 'none';
            return <g style={{ transform: `scale(${1 + amp * 0.85})`, transformOrigin: '160px 160px', transition: 'transform 0.05s linear' }}>
              {Array.from({ length: 7 }, (_, i) => { const ph = (i / 7) * Math.PI + ry; const rx = Math.abs(R * Math.cos(ph)); return <ellipse key={`lo${i}`} cx={C} cy={C} rx={Math.max(1, rx)} ry={R} fill="none" stroke={oa(mid, live ? 0.14 : 0.05)} strokeWidth="0.5" />; })}
              {[-0.7, -0.35, 0, 0.35, 0.7].map((lat, i) => { const yy = C + Math.sin(lat) * R, rx = R * Math.cos(lat); return <ellipse key={`la${i}`} cx={C} cy={yy} rx={rx} ry={rx * 0.16} fill="none" stroke={oa(mid, live ? 0.12 : 0.04)} strokeWidth="0.5" />; })}
              {P.map((a, i) => { const b = P[(i * 7 + 3) % P.length]; const op = (a.depth * 0.45 + 0.1) * (live ? 1 : 0.3); return <line key={`ch${i}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke={oa(i % 5 === 0 ? hi : mid, op * 0.55)} strokeWidth={i % 5 === 0 ? 0.6 : 0.4} />; })}
              {P.map((a, i) => { const dx = a.x - C, dy = a.y - C; const op = (a.depth * 0.55 + 0.15) * (live ? 0.55 + 0.4 * Math.abs(Math.sin(t * 3 + pts[i].tw)) : 0.25); return <line key={`sp${i}`} x1={C + dx * 0.44} y1={C + dy * 0.44} x2={a.x} y2={a.y} stroke={a.depth > 0.55 ? hi : mid} strokeWidth={a.depth > 0.6 ? 0.85 : 0.5} opacity={op} style={a.depth > 0.6 ? { filter: gF } : {}} />; })}
              {P.map((a, i) => i % 3 === 0 && (<circle key={`nd${i}`} cx={a.x} cy={a.y} r={a.depth > 0.6 ? 1.4 : 0.8} fill={a.depth > 0.6 ? '#e8fdff' : mid} opacity={(0.3 + a.depth * 0.55) * (live ? 1 : 0.3)} style={a.depth > 0.7 ? { filter: gF } : {}} />))}
              <g style={{ transform: spin(t * 18 * sm), transformOrigin: '160px 160px' }}>
                {Array.from({ length: 4 }, (_, i) => { const rr = 9 + i * 4; return <ellipse key={`kn${i}`} cx={C} cy={C} rx={rr} ry={rr * 0.5} fill="none" stroke={oa('#ffffff', live ? 0.45 - i * 0.08 : 0.1)} strokeWidth="1" transform={`rotate(${i * 52} 160 160)`} style={{ filter: gF }} />; })}
              </g>
              {/* HAL-style living lens at the nucleus center, softened for Sam */}
              <circle cx={C} cy={C} r={17 + amp * 18} fill="url(#samCore)" opacity={live ? 0.96 : 0.28} style={{ filter: gF }} />
              <circle cx={C} cy={C} r={11 + amp * 9} fill={oa(hi, live ? 0.3 + amp * 0.14 : 0.08)} style={{ filter: 'blur(4px)' }} />
              <circle cx={C} cy={C} r={5.5 + amp * 5} fill="#fff8ee" opacity={live ? 0.96 : 0.3} style={{ filter: 'blur(1.2px)' }} />
              <circle cx={C - 2.4} cy={C - 3} r={2.1 + amp * 1.2} fill="#ffffff" opacity={live ? 0.92 : 0.25} />
              <circle cx={C} cy={C} r={20 + amp * 14} fill="none" stroke={oa('#ffffff', live ? 0.18 + amp * 0.05 : 0.05)} strokeWidth="0.7" opacity={live ? 0.78 : 0.2} style={{ filter: gF }} />
            </g>;
          })()}
          {live && <circle cx={C} cy={C} r={16 + amp * 82} fill={oa('#ffffff', 0.1 + amp * 0.34)} style={{ filter: 'blur(9px)' }} />}
        </svg>

        {state === 'connecting' && [0, 1, 2].map(i => (
          <div key={i} style={{ position: 'absolute', inset: 84, borderRadius: '50%', border: `1.5px solid ${hi}`, animation: `osPulse 2s ${i * 0.66}s ease-out infinite`, opacity: 0 }} />
        ))}
      </div>
    </div>
  );
}

// osPulse keyframe (connecting rings)
if (typeof document !== 'undefined' && !document.getElementById('sam-jarvis-kf')) {
  const s = document.createElement('style');
  s.id = 'sam-jarvis-kf';
  s.textContent = `@keyframes osPulse { 0%{transform:scale(0.85);opacity:0.8;} 100%{transform:scale(1.45);opacity:0;} }`;
  document.head.appendChild(s);
}

window.SamJarvisOrb = SamJarvisOrb;
