// Shared "Connecting → Apply" splash. Renders edge-to-edge over whatever is
// behind it (either the Hero homepage during navigation, or the freshly-loaded
// Apply page on arrival). The same component is used in both places so the
// transition between pages feels seamless: the splash never visibly unmounts.
//
// Visual: NJ seal in the center on a soft surface background, an orbiting
// progress ring around it, a hand-off line that draws toward Montgomery's
// shield, then a status line that ticks through three phases:
//   "Routing your request" → "Verifying your address" → "Opening your application"
// After the final phase fades, the parent unmounts the splash to reveal what's
// behind it (Apply page or Hero placeholder).

const { useState: useCAState, useEffect: useCAEffect } = React;

function ConnectingApply({ query, onDone, durationMs = 2400 }) {
  const t = window.tokens;
  const [phaseIdx, setPhaseIdx] = useCAState(0);
  const [exiting, setExiting] = useCAState(false);

  const phases = [
    'Routing your request',
    'Verifying your address',
    'Opening your application',
  ];

  useCAEffect(() => {
    const tickEvery = Math.floor((durationMs - 300) / phases.length);
    const t1 = setTimeout(() => setPhaseIdx(1), tickEvery);
    const t2 = setTimeout(() => setPhaseIdx(2), tickEvery * 2);
    const t3 = setTimeout(() => setExiting(true), durationMs - 300);
    const t4 = setTimeout(() => onDone && onDone(), durationMs);
    return () => { [t1, t2, t3, t4].forEach(clearTimeout); };
    // eslint-disable-next-line
  }, []);

  return (
    <div
      role="status"
      aria-live="polite"
      style={{
        position: 'fixed', inset: 0, zIndex: 9000,
        background: t.color.surfaceLo,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexDirection: 'column',
        opacity: exiting ? 0 : 1,
        transition: 'opacity 320ms ease-out',
        pointerEvents: exiting ? 'none' : 'auto',
        fontFamily: t.font.sans,
      }}
    >
      <style>{`
        @keyframes ca-ring-spin {
          from { transform: rotate(0deg); }
          to   { transform: rotate(360deg); }
        }
        @keyframes ca-seal-rise {
          from { opacity: 0; transform: translateY(8px) scale(0.96); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes ca-line-grow {
          from { transform: scaleX(0); }
          to   { transform: scaleX(1); }
        }
        @keyframes ca-shield-rise {
          0%   { opacity: 0; transform: translateY(8px) scale(0.85); }
          60%  { opacity: 0; transform: translateY(8px) scale(0.85); }
          100% { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes ca-phase-in {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes ca-dot {
          0%, 80%, 100% { opacity: 0.25; }
          40% { opacity: 1; }
        }
      `}</style>

      {/* Hand-off graphic: NJ seal → progress line → Montgomery shield */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 28,
        animation: 'ca-seal-rise 460ms ease-out both',
      }}>
        {/* NJ seal with orbiting ring */}
        <div style={{ position: 'relative', width: 84, height: 84 }}>
          <svg width="84" height="84" viewBox="0 0 84 84" style={{
            position: 'absolute', inset: 0,
            animation: 'ca-ring-spin 1.6s linear infinite',
          }}>
            <circle
              cx="42" cy="42" r="38"
              fill="none"
              stroke={t.color.action}
              strokeWidth="2"
              strokeLinecap="round"
              strokeDasharray="48 200"
              opacity="0.85"
            />
          </svg>
          <div style={{
            position: 'absolute', inset: 8,
            background: t.color.bg,
            border: `1px solid ${t.color.hair}`,
            borderRadius: '50%',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 1px 2px rgba(15, 18, 22, 0.05)',
          }}>
            <img src="assets/nj-logo.svg" alt="" width="40" height="44" style={{ display: 'block' }} />
          </div>
        </div>

        {/* Connecting line — animated draw from NJ to Montgomery */}
        <div style={{
          width: 88, height: 2, background: t.color.action, borderRadius: 1,
          transformOrigin: 'left center',
          animation: 'ca-line-grow 800ms ease-out 200ms both',
          opacity: 0.6,
        }} />

        {/* Montgomery shield — fades in after line */}
        <div style={{
          width: 52, height: 60,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          animation: 'ca-shield-rise 800ms ease-out both',
        }}>
          <svg width="52" height="60" viewBox="0 0 52 60" fill="none">
            <path
              d="M26 2 L48 10 L48 32 C48 46 38 55 26 58 C14 55 4 46 4 32 L4 10 Z"
              fill={t.color.bg}
              stroke={t.color.text}
              strokeWidth="1.6"
              strokeLinejoin="round"
            />
            <text
              x="26" y="36"
              textAnchor="middle"
              fontFamily={t.font.serif || 'Georgia, serif'}
              fontSize="20"
              fontWeight="500"
              fill={t.color.text}
              letterSpacing="-0.02em"
            >M</text>
          </svg>
        </div>
      </div>

      {/* Headline + echoed query */}
      <div style={{
        marginTop: 36, textAlign: 'center', maxWidth: 520, padding: '0 24px',
        animation: 'ca-seal-rise 460ms ease-out 80ms both',
      }}>
        <h1 style={{
          margin: 0,
          fontSize: 26, fontWeight: 500, letterSpacing: -0.6,
          color: t.color.text, lineHeight: 1.25,
        }}>
          Connecting to Montgomery Township
        </h1>
        {query && (
          <div style={{
            marginTop: 14,
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '6px 14px',
            background: t.color.bg,
            border: `1px solid ${t.color.hair}`,
            borderRadius: 999,
            fontSize: 13,
            color: t.color.body,
            maxWidth: '100%',
          }}>
            <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke={t.color.muted} strokeWidth="1.5" strokeLinecap="round">
              <circle cx="6.5" cy="6.5" r="4" />
              <path d="M9.5 9.5l3 3" />
            </svg>
            <span style={{
              fontFamily: t.font.sans,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              maxWidth: 360,
            }}>"{query}"</span>
          </div>
        )}
      </div>

      {/* Phase ticker */}
      <div style={{
        marginTop: 28,
        display: 'flex', alignItems: 'center', gap: 10,
        fontFamily: t.font.mono,
        fontSize: 12, fontWeight: 500,
        letterSpacing: 1.4, textTransform: 'uppercase',
        color: t.color.muted,
        height: 18,
      }}>
        <span key={phaseIdx} style={{
          animation: 'ca-phase-in 320ms ease-out',
          color: t.color.text,
        }}>
          {phases[phaseIdx]}
        </span>
        <span style={{ display: 'inline-flex', gap: 3, marginLeft: 4 }}>
          {[0, 1, 2].map((i) => (
            <span key={i} style={{
              width: 4, height: 4, borderRadius: 2,
              background: t.color.action,
              animation: `ca-dot 1.2s ease-in-out ${i * 0.15}s infinite`,
            }} />
          ))}
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { ConnectingApply });
