// ReturnScribe — opening splash. Ledger language: paper, rules, ink, amber stamp.
// ~3.5s, tap anywhere to skip. SwiftUI: phased .animation chain or Lottie.

function SplashIntro({ t, onDone }) {
  const [leaving, setLeaving] = React.useState(false);
  // Animations + the auto-dismiss clock only start once the page is actually
  // visible and painted — otherwise a background-tab load burns the whole
  // splash before the user ever sees it. SwiftUI: start in .onAppear after
  // scenePhase == .active.
  const [armed, setArmed] = React.useState(false);
  const doneRef = React.useRef(false);

  const finish = React.useCallback(() => {
    if (doneRef.current) return;
    doneRef.current = true;
    setLeaving(true);
    setTimeout(onDone, 520);
  }, [onDone]);

  React.useEffect(() => {
    let raf1, raf2;
    const arm = () => { raf1 = requestAnimationFrame(() => { raf2 = requestAnimationFrame(() => setArmed(true)); }); };
    if (document.visibilityState === 'visible') { arm(); return () => { cancelAnimationFrame(raf1); cancelAnimationFrame(raf2); }; }
    const onVis = () => { if (document.visibilityState === 'visible') { document.removeEventListener('visibilitychange', onVis); arm(); } };
    document.addEventListener('visibilitychange', onVis);
    return () => { document.removeEventListener('visibilitychange', onVis); cancelAnimationFrame(raf1); cancelAnimationFrame(raf2); };
  }, []);

  React.useEffect(() => {
    if (!armed) return;
    const id = setTimeout(finish, 4150);
    return () => clearTimeout(id);
  }, [armed, finish]);

  // helper — hold initial state until armed
  const anim = (v) => armed ? v : 'none';

  const dark = t === RSTokens.dark;
  const ink = t.text1;

  return (
    <div onClick={finish} style={{
      position: 'absolute', inset: 0, zIndex: 120, cursor: 'pointer',
      background: t.canvas, overflow: 'hidden',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      opacity: leaving ? 0 : 1,
      transform: leaving ? 'translateY(-26px) scale(1.012)' : 'none',
      transition: 'opacity 480ms cubic-bezier(.4,0,.2,1), transform 480ms cubic-bezier(.4,0,.2,1)',
    }}>
      {/* faint ruled paper grain, fades in late so the open feels blank-page */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: `repeating-linear-gradient(0deg, transparent 0 31px, ${dark ? 'rgba(239,233,222,0.35)' : 'rgba(33,29,23,0.045)'} 31px 32px)`,
        opacity: 0, animation: anim('rsSplGrain 1200ms ease 1900ms forwards'),
      }}></div>

      {/* composition */}
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%' }}>

        {/* top double rule — two lines draw in, staggered, from opposite sides */}
        <div style={{ width: 240, marginBottom: 30 }}>
          <div style={{ height: 2, background: ink, transformOrigin: 'left',
            transform: 'scaleX(0)', animation: anim('rsSplRuleL 700ms cubic-bezier(.7,0,.2,1) 200ms forwards') }}></div>
          <div style={{ height: 1, background: ink, marginTop: 3, transformOrigin: 'right',
            transform: 'scaleX(0)', animation: anim('rsSplRuleR 700ms cubic-bezier(.7,0,.2,1) 360ms forwards') }}></div>
        </div>

        {/* brand mark — frame settles in, amber seal stamps */}
        <div style={{
          position: 'relative', width: 72, height: 72,
          opacity: 0, animation: anim('rsSplMark 700ms cubic-bezier(.34,1.3,.64,1) 750ms forwards'),
        }}>
          <div style={{
            position: 'absolute', inset: 0, borderRadius: 12,
            border: `2.4px solid ${t.accent}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{ ...applyDisp(RSType.title1, { fontSize: 45 }), color: t.accent, fontStyle: 'italic', lineHeight: 1 }}>R</span>
          </div>
          <div style={{
            position: 'absolute', right: -3.7, bottom: -3.7, width: 14.4, height: 14.4,
            borderRadius: 99, background: t.accent,
            transform: 'scale(0)', animation: anim('rsSplSeal 480ms cubic-bezier(.34,1.8,.64,1) 1350ms forwards'),
          }}></div>
        </div>

        {/* wordmark — serif, rises out of a clip */}
        <div style={{ overflow: 'hidden', marginTop: 26, padding: '0 4px' }}>
          <h1 style={{
            margin: 0, color: ink, ...applyDisp(RSType.large, { fontSize: 38, lineHeight: 1.1 }),
            transform: 'translateY(110%)', animation: anim('rsSplRise 800ms cubic-bezier(.2,.8,.2,1) 1600ms forwards'),
          }}>ReturnScribe</h1>
        </div>

        {/* flowing amber underline — SVG stroke draws like a pen flourish */}
        <svg width="210" height="14" viewBox="0 0 210 14" fill="none" style={{ marginTop: 8 }}>
          <path d="M4 9 C 50 3, 90 12, 130 7 S 195 5, 206 8"
            stroke={t.accent} strokeWidth="2.2" strokeLinecap="round"
            strokeDasharray="230" strokeDashoffset="230"
            style={{ animation: anim('rsSplDraw 850ms cubic-bezier(.4,0,.3,1) 2300ms forwards') }}/>
        </svg>

        {/* tagline */}
        <div style={{
          marginTop: 14, color: t.text2,
          ...applyDisp(RSType.callout, { fontStyle: 'italic', fontSize: 18.5 }),
          opacity: 0, animation: anim('rsSplFade 650ms ease 2900ms forwards'),
        }}>Every receipt, on the record.</div>

        {/* bottom single rule */}
        <div style={{ width: 240, height: 1, background: ink, marginTop: 30, transformOrigin: 'center',
          transform: 'scaleX(0)', animation: anim('rsSplRuleC 700ms cubic-bezier(.7,0,.2,1) 520ms forwards') }}></div>
      </div>

      {/* skip hint */}
      <div style={{
        position: 'absolute', bottom: 44, left: 0, right: 0, textAlign: 'center',
        color: t.text3, ...applyMono(RSType.caption, { letterSpacing: 1.4 }), textTransform: 'uppercase',
        opacity: 0, animation: anim('rsSplFade 600ms ease 1500ms forwards'),
      }}>Tap to skip</div>
    </div>
  );
}

// keyframes (scoped, injected once)
if (typeof document !== 'undefined' && !document.getElementById('rs-splash-kf')) {
  const s = document.createElement('style');
  s.id = 'rs-splash-kf';
  s.textContent = `
    @keyframes rsSplRuleL { to { transform: scaleX(1); } }
    @keyframes rsSplRuleR { to { transform: scaleX(1); } }
    @keyframes rsSplRuleC { to { transform: scaleX(1); } }
    @keyframes rsSplMark { from { opacity: 0; transform: scale(0.8) rotate(-4deg); } to { opacity: 1; transform: scale(1) rotate(0deg); } }
    @keyframes rsSplSeal { to { transform: scale(1); } }
    @keyframes rsSplRise { to { transform: translateY(0); } }
    @keyframes rsSplDraw { to { stroke-dashoffset: 0; } }
    @keyframes rsSplFade { to { opacity: 1; } }
    @keyframes rsSplGrain { to { opacity: 1; } }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { SplashIntro });
