/* SOS — one-button emergency dispatch. Hold-to-confirm fires a 10-second
   pipeline that sends a full vehicle data package to roadside before anyone
   picks up a phone. Track dongle feature. */
function SOS() {
  const { Badge } = window.RevvoDesignSystem_a89086;
  const { Reveal, Ic } = window;

  // phase: idle -> arming -> sending -> analyzing -> dispatched
  const [phase, setPhase] = React.useState('idle');
  const [progress, setProgress] = React.useState(0); // 0..1 hold charge
  const raf = React.useRef(0);
  const holdStart = React.useRef(0);
  const HOLD_MS = 1600;
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const runSequence = React.useCallback(() => {
    setPhase('sending');
    setTimeout(() => setPhase('analyzing'), 1500);
    setTimeout(() => setPhase('dispatched'), 3400);
  }, []);

  const tick = React.useCallback((t) => {
    const p = Math.min((t - holdStart.current) / HOLD_MS, 1);
    setProgress(p);
    if (p >= 1) { setProgress(0); runSequence(); return; }
    raf.current = requestAnimationFrame(tick);
  }, [runSequence]);

  const startHold = () => {
    if (phase !== 'idle') return;
    if (reduce) { runSequence(); return; }
    setPhase('arming');
    holdStart.current = performance.now();
    raf.current = requestAnimationFrame(tick);
  };
  const endHold = () => {
    cancelAnimationFrame(raf.current);
    if (phase === 'arming') { setPhase('idle'); setProgress(0); }
  };
  React.useEffect(() => () => cancelAnimationFrame(raf.current), []);

  const reset = () => { setPhase('idle'); setProgress(0); };

  const payload = [
    { icon: 'MapPin', k: 'Live GPS location', v: 'From the car\u2019s own cellular dongle' },
    { icon: 'Activity', k: 'Full OBD-II snapshot', v: 'Every sensor at the moment of the press' },
    { icon: 'BrainCircuit', k: 'AI diagnosis', v: 'Cause, severity, safe-to-restart, tow type' },
    { icon: 'CarFront', k: 'Vehicle profile', v: 'Make, model, year, VIN, insurance' },
    { icon: 'History', k: '10-min rolling history', v: 'Pre-incident sensor trail for the dispatcher' },
  ];

  const stages = ['Triggered', 'Analyzing', 'Dispatched'];
  const stageIndex = phase === 'sending' ? 0 : phase === 'analyzing' ? 1 : phase === 'dispatched' ? 2 : -1;
  const active = phase !== 'idle' && phase !== 'arming';

  const R = 96, C = 2 * Math.PI * R;

  return (
    <section id="sos" style={{ position: 'relative', padding: 'var(--space-section) clamp(20px, 5vw, 48px)',
      background: 'var(--surface-section)', borderTop: '1px solid var(--line-100)', borderBottom: '1px solid var(--line-100)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto' }}>
        <Reveal style={{ textAlign: 'center', marginBottom: 52 }}>
          <Badge variant="accent" dot style={{ marginBottom: 20 }}>Emergency SOS</Badge>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--fs-display-2)',
            letterSpacing: 'var(--ls-snug)', color: 'var(--text-strong)', margin: '0 0 14px', lineHeight: 'var(--lh-snug)' }}>
            One button. Help already knows everything.
          </h2>
          <p style={{ fontSize: 'var(--fs-lead)', color: 'var(--text-body)', maxWidth: 600, margin: '0 auto' }}>
            Break down or crash and a single press sends a complete picture of you and your car to roadside dispatch &mdash; before anyone even picks up a phone.
          </p>
        </Reveal>

        <div className="sos-grid" style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: 'clamp(24px, 4vw, 56px)', alignItems: 'center' }}>
          {/* the button */}
          <Reveal dir="left">
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24,
              background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: 'clamp(30px, 4vw, 46px)' }}>
              <div style={{ position: 'relative', width: 240, height: 240, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {/* progress ring */}
                <svg width="240" height="240" viewBox="0 0 240 240" style={{ position: 'absolute', inset: 0, transform: 'rotate(-90deg)' }}>
                  <circle cx="120" cy="120" r={R} fill="none" stroke="var(--line-200)" strokeWidth="6" />
                  <circle cx="120" cy="120" r={R} fill="none"
                    stroke={active ? 'var(--positive)' : 'var(--accent)'} strokeWidth="6" strokeLinecap="round"
                    strokeDasharray={C} strokeDashoffset={active ? 0 : C * (1 - progress)}
                    style={{ transition: active ? 'stroke-dashoffset 0.4s var(--ease-out), stroke 0.3s' : 'none' }} />
                </svg>

                <button
                  onPointerDown={startHold} onPointerUp={endHold} onPointerLeave={endHold}
                  disabled={active}
                  className={phase === 'idle' ? 'pulse-glow' : ''}
                  style={{
                    width: 176, height: 176, borderRadius: '50%', cursor: active ? 'default' : 'pointer',
                    border: 'none', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6,
                    color: '#fff', fontFamily: 'var(--font-display)', userSelect: 'none', touchAction: 'none',
                    background: active
                      ? 'radial-gradient(circle at 50% 35%, #16d680, #0a7d4a)'
                      : 'radial-gradient(circle at 50% 35%, #ff4f5c, #c10f1f)',
                    boxShadow: active ? '0 0 50px rgba(22,214,128,0.5)' : '0 0 50px rgba(255,46,63,0.45)',
                    transform: phase === 'arming' ? `scale(${0.96 + progress * 0.04})` : 'scale(1)',
                    transition: 'background 0.4s var(--ease-out), box-shadow 0.4s var(--ease-out)',
                  }}>
                  <Ic name={phase === 'dispatched' ? 'Check' : active ? 'Loader' : 'Siren'} size={40} color="#fff" stroke={2} />
                  <span style={{ fontWeight: 700, fontSize: 22, letterSpacing: '0.16em' }}>
                    {phase === 'dispatched' ? 'SENT' : active ? '…' : 'SOS'}
                  </span>
                </button>
              </div>

              <div style={{ textAlign: 'center', minHeight: 44 }}>
                {phase === 'idle' && (
                  <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)' }}>
                    <strong style={{ color: 'var(--text-body)' }}>Press &amp; hold</strong> to arm &mdash; a deliberate hold prevents accidental triggers.
                  </p>
                )}
                {phase === 'arming' && (
                  <p style={{ margin: 0, fontSize: 14, color: 'var(--accent)' }}>Keep holding&hellip; {Math.round(progress * 100)}%</p>
                )}
                {active && (
                  <button onClick={reset} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 15px', cursor: 'pointer',
                    background: 'transparent', border: '1px solid var(--border)', borderRadius: 'var(--radius-pill)', color: 'var(--text-muted)', font: 'inherit', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                    <Ic name="RotateCcw" size={13} /> Run again
                  </button>
                )}
              </div>

              {/* lifecycle */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 0, width: '100%', maxWidth: 320 }}>
                {stages.map((st, i) => (
                  <React.Fragment key={st}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flex: '0 0 auto' }}>
                      <span style={{ width: 12, height: 12, borderRadius: '50%',
                        background: stageIndex >= i ? 'var(--positive)' : 'var(--black-400)',
                        boxShadow: stageIndex === i ? '0 0 12px var(--positive)' : 'none',
                        transition: 'background 0.4s, box-shadow 0.4s' }} />
                      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase',
                        color: stageIndex >= i ? 'var(--positive-bright)' : 'var(--text-faint)' }}>{st}</span>
                    </div>
                    {i < stages.length - 1 && (
                      <span style={{ flex: 1, height: 2, margin: '0 4px', marginBottom: 17, borderRadius: 2,
                        background: stageIndex > i ? 'var(--positive)' : 'var(--black-400)', transition: 'background 0.4s' }} />
                    )}
                  </React.Fragment>
                ))}
              </div>
            </div>
          </Reveal>

          {/* payload */}
          <Reveal dir="right">
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: 18, display: 'flex', alignItems: 'center', gap: 9 }}>
              <Ic name="Send" size={14} color="var(--text-muted)" /> Sent in under 10 seconds
            </div>
            <div style={{ display: 'grid', gap: 10 }}>
              {payload.map((p, i) => {
                const sent = active && (phase === 'dispatched' || i <= (phase === 'analyzing' ? 4 : phase === 'sending' ? 2 : -1));
                return (
                  <div key={p.k} style={{ display: 'flex', alignItems: 'center', gap: 15, padding: '15px 17px',
                    background: 'var(--surface)', border: `1px solid ${sent ? 'rgba(22,214,128,0.4)' : 'var(--border)'}`,
                    borderRadius: 'var(--radius-md)', transition: 'border-color 0.4s var(--ease-out)' }}>
                    <div style={{ width: 42, height: 42, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      borderRadius: 'var(--radius-md)', background: sent ? 'var(--green-tint)' : 'var(--inset)',
                      border: `1px solid ${sent ? 'rgba(22,214,128,0.35)' : 'var(--line-100)'}`, color: sent ? 'var(--positive-bright)' : 'var(--silver-300)', transition: 'all 0.4s var(--ease-out)' }}>
                      <Ic name={p.icon} size={20} color={sent ? 'var(--positive-bright)' : 'var(--silver-300)'} />
                    </div>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 15.5, fontWeight: 600, color: 'var(--text-strong)' }}>{p.k}</div>
                      <div style={{ fontSize: 13.5, color: 'var(--text-muted)', textWrap: 'pretty' }}>{p.v}</div>
                    </div>
                    <Ic name={sent ? 'CircleCheck' : 'Circle'} size={18} color={sent ? 'var(--positive-bright)' : 'var(--text-faint)'} />
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 18, fontSize: 13, color: 'var(--text-faint)' }}>
              <Ic name="ShieldCheck" size={15} color="var(--text-faint)" />
              Requires the ALEROQ Track dongle and an Assist plan. Dispatch handled through partnered roadside networks.
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}
window.SOS = SOS;
