// mockups/explain-flow.jsx — Pantallas del Acto 5 · Explain.
//
// Exports on window:
//   InboxNotification    (escena 18 — desktop side)
//   ExplainSplit         (escenas 19-21)

function ExplainShell({ children, moduleAccent = '#8b5cf6' }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ib = i18n.inbox || {};
  const docLabel = lang === 'en' ? 'Client document' : 'Documento del cliente';

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#f5f5f7',
    }}>
      <AppHeader
        moduleName="Explain"
        moduleAccent={moduleAccent}
        moduleIcon="✨"
        breadcrumbs={['Inbox', 'TOMÁS SMITH', docLabel]}
      />
      {children}
    </div>
  );
}

// ── Inbox notification + transition ───────────────────────────────────
function InboxNotification({ stage = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ib = i18n.inbox || {};
  // stage: 0 = nothing
  //        1 = toast notification appears in top-right
  //        2 = thumbnail being dragged toward Explain icon (on left nav strip)
  //        3 = explain panel opening on the side

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#f5f5f7',
    }}>
      <AppHeader
        moduleName={(i18n.modules && i18n.modules.migracion) || 'Migración'}
        moduleAccent="#FF9500"
        moduleIcon="🌎"
        breadcrumbs={[ib.breadcrumb_cases || 'Casos', 'CARLA', ib.breadcrumb_inbox || 'Inbox del cliente']}
      />

      {/* Workspace placeholder — package "in flight" status */}
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 70,
      }}>
        <div style={{
          fontSize: 11, fontFamily: 'ui-monospace, monospace',
          color: '#15803d', letterSpacing: 0.12,
          textTransform: 'uppercase', fontWeight: 600,
          marginBottom: 4,
        }}>{ib.eyebrow || '📬 Paquete en tránsito · USCIS Chicago Lockbox'}</div>
        <div style={{
          fontSize: 22, fontWeight: 600, color: '#1d1d1f',
          letterSpacing: -0.025, marginBottom: 14,
        }}>{ib.title || 'Caso de CARLA A. VERA RODRÍGUEZ · En espera USCIS'}</div>

        {/* Timeline */}
        <div style={{
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 14,
          padding: 18,
          marginBottom: 14,
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 12,
            marginBottom: 14,
          }}>
            <TimelinePill color="#34C759" icon="✓" label={ib.timeline_sent || 'Paquete enviado'} sub="16 may 2026" />
            <Connector />
            <TimelinePill color="#34C759" icon="✓" label={ib.timeline_received || 'Recibido USCIS'} sub="22 may 2026" />
            <Connector />
            <TimelinePill color="#FF9500" icon="◌" label={ib.timeline_processing || 'Procesando'} sub={ib.timeline_processing_sub || 'día 47 de 120'} pulse />
            <Connector dashed />
            <TimelinePill color="#c7c7cf" icon="?" label={ib.timeline_decision || 'Decisión USCIS'} sub={ib.timeline_decision_sub || 'esperando'} muted />
          </div>
        </div>

        {/* Hint label */}
        <div style={{
          padding: '14px 16px',
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 12,
          color: '#6e6e73',
          fontSize: 13,
          textAlign: 'center',
        }}>
          {ib.waiting_hint || 'Esperando próxima acción · Sophia te avisará cuando el cliente o USCIS responda'}
        </div>
      </div>

      {/* Toast notification — top right */}
      {stage >= 1 && (
        <div style={{
          position: 'absolute',
          top: 70,
          right: 290,
          width: 320,
          background: '#fff',
          border: '1px solid #8b5cf6',
          borderRadius: 12,
          padding: '14px 16px',
          boxShadow: '0 18px 50px rgba(139, 92, 246, 0.35), 0 0 0 4px rgba(139, 92, 246, 0.08)',
          animation: 'sol-toast-in 360ms ease-out',
          opacity: stage >= 3 ? 0.5 : 1,
          transition: 'opacity 240ms',
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            marginBottom: 6,
          }}>
            <span style={{ fontSize: 16 }}>💬</span>
            <span style={{
              fontSize: 10,
              fontFamily: 'ui-monospace, monospace',
              color: '#8b5cf6',
              letterSpacing: 0.12,
              textTransform: 'uppercase',
              fontWeight: 700,
            }}>{ib.toast_eyebrow || 'Nuevo mensaje del cliente'}</span>
          </div>
          <div style={{
            fontSize: 13, fontWeight: 600,
            color: '#1d1d1f', letterSpacing: -0.005,
            marginBottom: 4,
          }}>{ib.toast_title || 'TOMÁS SMITH te envió un documento'}</div>
          <div style={{
            fontSize: 11.5, color: '#6e6e73',
            letterSpacing: -0.005, lineHeight: 1.35,
            marginBottom: 10,
          }}>
            <em style={{ color: '#6e6e73' }}>{ib.toast_quote || '"Me llegó esta carta y no entiendo nada 😟"'}</em>
          </div>

          {/* Thumbnail of letter (the "draggable") */}
          <div style={{
            display: 'flex',
            gap: 8,
            padding: 6,
            background: '#fafafa',
            border: '1px solid #e8e8ed',
            borderRadius: 8,
            transform: stage === 2 ? 'translate(-160px, 100px) scale(0.85) rotate(-6deg)' : 'none',
            transition: 'transform 360ms ease-out',
          }}>
            <div style={{
              width: 38, height: 50,
              background: 'linear-gradient(180deg, #fff, #f3e8ff)',
              border: '1px solid #d8b4fe',
              borderRadius: 4,
              padding: 3,
              fontSize: 4.5,
              fontFamily: 'ui-monospace, monospace',
              color: '#1d1d1f',
              fontWeight: 600,
              overflow: 'hidden',
            }}>
              <div style={{ fontSize: 4, marginBottom: 1 }}>DHS · USCIS</div>
              <div style={{ marginTop: 2, fontSize: 4 }}>I-797E</div>
              <div style={{ marginTop: 4, fontSize: 3.5, lineHeight: 1.15, color: '#6e6e73' }}>
                Notice of Action — Request for Evidence...
              </div>
            </div>
            <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div style={{
                fontSize: 10.5, fontWeight: 500,
                color: '#1d1d1f',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                fontFamily: 'ui-monospace, monospace',
              }}>uscis_notice_rfe.jpg</div>
              <button style={{
                background: '#8b5cf6',
                color: '#fff',
                border: 0,
                borderRadius: 6,
                padding: '4px 8px',
                fontSize: 10,
                fontWeight: 600,
                cursor: 'pointer',
              }}>{ib.toast_open || 'Abrir en Explain →'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function TimelinePill({ color, icon, label, sub, pulse, muted }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: 8,
      flexShrink: 0,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: '50%',
        background: muted ? '#f5f5f7' : color,
        color: muted ? '#a1a1a6' : '#fff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontSize: 13,
        fontWeight: 700,
        animation: pulse ? 'sol-pulse-dot 1.6s ease-in-out infinite' : 'none',
      }}>{icon}</div>
      <div>
        <div style={{
          fontSize: 11.5, fontWeight: 600,
          color: muted ? '#a1a1a6' : '#1d1d1f',
        }}>{label}</div>
        <div style={{
          fontSize: 10, color: '#6e6e73',
          fontFamily: 'ui-monospace, monospace',
        }}>{sub}</div>
      </div>
    </div>
  );
}

function Connector({ dashed }) {
  return (
    <div style={{
      flex: 1,
      height: 2,
      background: dashed ? 'repeating-linear-gradient(90deg, #c7c7cf 0 6px, transparent 6px 10px)' : '#c7c7cf',
    }} />
  );
}

// ── Explain split view (RFE letter + Sophia analysis) ─────────────────
//
// Stages of progression:
//   highlightProgress : 0..1 (yellow highlight sweeps across the letter)
//   sophiaTypedChars  : how many characters of Sophia's explanation are visible
//   suggestionShown   : bool — show "Mensaje sugerido para TOMÁS" card
//   sendClicked       : bool — Sophia's send button pressed
//
function ExplainSplit({
  highlightProgress = 0,
  sophiaTypedChars = 0,
  suggestionShown = false,
  sendClicked = false,
}) {
  return (
    <ExplainShell>
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 70,
        bottom: 14,
        display: 'flex',
        gap: 14,
      }}>
        {/* Left: RFE letter scan */}
        <RFELetter highlightProgress={highlightProgress} />

        {/* Right: Sophia analysis */}
        <SophiaAnalysis
          typedChars={sophiaTypedChars}
          suggestionShown={suggestionShown}
          sendClicked={sendClicked}
        />
      </div>
    </ExplainShell>
  );
}

function RFELetter({ highlightProgress }) {
  const ANALYZE_AREAS = [
    { y: 25, label: 'Lectura del header' },
    { y: 50, label: 'Tipo de notice' },
    { y: 75, label: 'Lista de evidencia requerida' },
    { y: 95, label: 'Plazo de respuesta' },
  ];
  // The highlight sweep is a vertical "scan line" + yellow highlight bands
  // appearing as the progress advances

  return (
    <div style={{
      width: 360,
      flexShrink: 0,
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 12,
      overflow: 'hidden',
      position: 'relative',
      boxShadow: '0 4px 16px rgba(0,0,0,0.06)',
    }}>
      <div style={{
        padding: '8px 14px',
        borderBottom: '1px solid #f0f0f3',
        fontSize: 10,
        fontFamily: 'ui-monospace, monospace',
        color: '#6e6e73',
        letterSpacing: 0.1,
        textTransform: 'uppercase',
        fontWeight: 600,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
      }}>
        <span>uscis_notice_rfe.jpg</span>
        <span style={{ color: '#a1a1a6' }}>1 / 2</span>
      </div>

      {/* Letter body — styled like a real USCIS notice */}
      <div style={{
        padding: '20px 24px',
        position: 'relative',
        height: 500,
        background: '#fffef9',
        fontFamily: '"Times New Roman", Georgia, serif',
        fontSize: 9,
        lineHeight: 1.42,
        color: '#1d1d1f',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
          <div>
            <div style={{
              fontSize: 7.5, fontFamily: 'ui-monospace, monospace',
              letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700,
            }}>U.S. Department of Homeland Security</div>
            <div style={{
              fontSize: 6.8, fontFamily: 'ui-monospace, monospace',
              color: '#6e6e73', letterSpacing: 0.04,
            }}>U.S. Citizenship and Immigration Services</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{
              fontSize: 8, fontWeight: 700, fontFamily: 'ui-monospace, monospace',
              letterSpacing: 0.06,
            }}>I-797E</div>
            <div style={{ fontSize: 6.5, color: '#6e6e73', fontFamily: 'ui-monospace, monospace' }}>NOTICE OF ACTION</div>
          </div>
        </div>

        <div style={{
          marginTop: 10, padding: '4px 6px',
          background: '#000', color: '#fff',
          fontSize: 7.5, fontWeight: 700,
          fontFamily: 'ui-monospace, monospace',
          letterSpacing: 0.1, textAlign: 'center',
        }}>REQUEST FOR EVIDENCE</div>

        <div style={{ marginTop: 12, fontSize: 7.5 }}>
          <div><strong>Receipt #:</strong> MSC2123487654</div>
          <div><strong>Case Type:</strong> I-130 / I-485 Concurrent Filing</div>
          <div><strong>Beneficiary:</strong> VERA RODRÍGUEZ, CARLA A.</div>
          <div><strong>Petitioner:</strong> SMITH, TOMÁS</div>
          <div><strong>Notice Date:</strong> May 16, 2026</div>
          <div><strong>Response Due:</strong> August 11, 2026 (87 days)</div>
        </div>

        <div style={{ marginTop: 14, fontSize: 8.5, lineHeight: 1.55 }}>
          <p>To establish eligibility for the requested benefit, USCIS requires additional evidence. Please submit the following items by the response due date.</p>
          <p style={{ marginTop: 8, fontWeight: 700 }}>1. Bona Fide Marriage Evidence:</p>
          <p>Provide additional evidence that the marriage between the petitioner and beneficiary is bona fide and not entered into for the primary purpose of obtaining an immigration benefit. Submit at least three (3) of the following:</p>
          <ul style={{ paddingLeft: 16, margin: '4px 0 8px' }}>
            <li>Joint financial accounts (statements covering 6+ months)</li>
            <li>Joint lease, mortgage, or property deed</li>
            <li>Insurance policies naming spouse as beneficiary</li>
            <li>Photographs of the couple together at various dates and locations</li>
            <li>Affidavits from family members or friends attesting to the marriage</li>
          </ul>
          <p style={{ fontWeight: 700, marginTop: 6 }}>2. Marriage Certificate Translation:</p>
          <p>Submit a certified English translation of the marriage certificate (if originally issued in Spanish or another language).</p>
        </div>

        {/* Highlight overlays — animated bands */}
        {ANALYZE_AREAS.map((a, i) => {
          const myProgress = clamp((highlightProgress * 4) - i, 0, 1);
          if (myProgress <= 0) return null;
          return (
            <div key={i} style={{
              position: 'absolute',
              left: '20px', right: '20px',
              top: `${a.y}%`,
              height: 18,
              background: `rgba(252, 211, 77, ${0.5 * myProgress})`,
              border: `1px solid rgba(217, 119, 6, ${0.6 * myProgress})`,
              borderRadius: 3,
              pointerEvents: 'none',
              transition: 'all 200ms',
              transform: `scaleX(${myProgress})`,
              transformOrigin: 'left center',
            }} />
          );
        })}

        {/* Scan line (vertical glow line that moves down with progress) */}
        {highlightProgress > 0 && highlightProgress < 1 && (
          <div style={{
            position: 'absolute',
            left: '20px', right: '20px',
            top: `${20 + highlightProgress * 75}%`,
            height: 2,
            background: 'linear-gradient(90deg, transparent, #fcd34d 30%, #fcd34d 70%, transparent)',
            boxShadow: '0 0 12px #fcd34d',
            pointerEvents: 'none',
          }} />
        )}
      </div>
    </div>
  );
}

const SOPHIA_EXPLANATION = [
  { kind: 'h', text: '📩 ¿Qué es esta carta?' },
  { kind: 'p', text: 'Es una Request for Evidence (RFE) del USCIS sobre tu I-485. NO te están negando el caso — solo necesitan más evidencia.' },
  { kind: 'h', text: '📋 ¿Qué piden?' },
  { kind: 'b', text: '1. 3 evidencias adicionales de matrimonio bona-fide (cuentas conjuntas, fotos, lease).' },
  { kind: 'b', text: '2. Certificado de matrimonio traducido al inglés.' },
  { kind: 'h', text: '⏰ ¿Cuánto tiempo tenemos?' },
  { kind: 'p', text: '87 días desde la fecha del notice (hasta el 11 de agosto, 2026).' },
  { kind: 'h', text: '💡 ¿Qué recomiendo?' },
  { kind: 'p', text: 'Reúnan los 3 docs esta semana. Yo te preparo el response packet y lo revisamos juntos.' },
];

function SophiaAnalysis({ typedChars = 0, suggestionShown = false, sendClicked = false }) {
  // Concatenate all explanation text linearly and only show typedChars
  const fullParts = [];
  let accumLen = 0;
  for (const part of SOPHIA_EXPLANATION) {
    const startAt = accumLen;
    accumLen += part.text.length + 1;
    fullParts.push({ ...part, startAt, endAt: accumLen });
  }

  return (
    <div style={{
      flex: 1,
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 12,
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column',
      boxShadow: '0 4px 16px rgba(0,0,0,0.06)',
    }}>
      {/* Header */}
      <div style={{
        padding: '12px 16px',
        borderBottom: '1px solid #f0f0f3',
        background: 'linear-gradient(180deg, rgba(139, 92, 246, 0.04), transparent)',
        display: 'flex',
        alignItems: 'center',
        gap: 10,
      }}>
        <div style={{
          width: 34, height: 34, borderRadius: '50%',
          background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
          boxShadow: '0 0 14px rgba(139, 92, 246, 0.4)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Sparkle size={15} color="#fff" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: 'ui-monospace, monospace',
            fontSize: 10, color: '#8b5cf6',
            letterSpacing: 0.14, textTransform: 'uppercase',
            fontWeight: 600,
          }}>Sophia · Explain</div>
          <div style={{
            fontSize: 14, fontWeight: 600,
            color: '#1d1d1f', letterSpacing: -0.01,
          }}>
            {typedChars < 5 ? 'Analizando documento…' : 'Lectura terminada · resumen'}
          </div>
        </div>
        {typedChars < 5 && (
          <div style={{
            width: 16, height: 16,
            border: '2px solid #ddd6fe',
            borderTopColor: '#8b5cf6',
            borderRadius: '50%',
            animation: 'sol-spin 0.7s linear infinite',
          }} />
        )}
      </div>

      {/* Body */}
      <div style={{
        flex: 1,
        overflow: 'hidden',
        padding: '14px 18px 8px',
      }}>
        {fullParts.map((part, i) => {
          const visibleLen = Math.max(0, Math.min(part.text.length, typedChars - part.startAt));
          if (visibleLen <= 0) return null;
          const visibleText = part.text.slice(0, visibleLen);
          const isComplete = visibleLen >= part.text.length;
          const hasCaret = !isComplete && typedChars >= part.startAt && typedChars < part.endAt;

          if (part.kind === 'h') {
            return (
              <div key={i} style={{
                fontSize: 12, fontWeight: 700,
                color: '#1d1d1f',
                letterSpacing: -0.005,
                marginTop: i === 0 ? 0 : 10,
                marginBottom: 5,
              }}>{visibleText}{hasCaret && <Caret />}</div>
            );
          }
          if (part.kind === 'b') {
            return (
              <div key={i} style={{
                fontSize: 11.5, color: '#1d1d1f',
                letterSpacing: -0.005,
                paddingLeft: 14,
                marginBottom: 4,
                lineHeight: 1.45,
              }}>{visibleText}{hasCaret && <Caret />}</div>
            );
          }
          return (
            <div key={i} style={{
              fontSize: 11.5, color: '#1d1d1f',
              letterSpacing: -0.005,
              marginBottom: 4,
              lineHeight: 1.45,
            }}>{visibleText}{hasCaret && <Caret />}</div>
          );
        })}
      </div>

      {/* Suggested message + Send button */}
      {suggestionShown && (
        <div style={{
          padding: '12px 14px 14px',
          background: 'linear-gradient(180deg, #f0fdf4, #fff)',
          borderTop: '1px solid #86efac',
          animation: 'sol-fade-up 380ms ease-out',
        }}>
          <div style={{
            fontSize: 10,
            fontFamily: 'ui-monospace, monospace',
            color: '#15803d',
            letterSpacing: 0.12,
            textTransform: 'uppercase',
            fontWeight: 700,
            marginBottom: 6,
          }}>💬 Mensaje sugerido para TOMÁS</div>
          <div style={{
            background: '#fff',
            border: '1px solid #d1fae5',
            borderRadius: 8,
            padding: '8px 10px',
            fontSize: 11.5,
            color: '#1d1d1f',
            letterSpacing: -0.005,
            lineHeight: 1.4,
            marginBottom: 8,
          }}>
            "Tranquilo TOMÁS — es un <strong>RFE</strong>, NO una negación. USCIS pide más evidencia y nos da 87 días. Te explico todo y lo armamos juntos. ❤️"
          </div>
          <button style={{
            width: '100%',
            background: sendClicked ? '#15803d' : '#34C759',
            color: '#fff',
            border: 0, borderRadius: 8,
            padding: '9px',
            fontSize: 12.5, fontWeight: 600,
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 6,
            transform: sendClicked ? 'scale(0.985)' : 'scale(1)',
            transition: 'all 120ms',
          }}>
            {sendClicked ? '✓ Enviado a TOMÁS' : 'Enviar a TOMÁS →'}
          </button>
        </div>
      )}
    </div>
  );
}

function Caret() {
  return <span style={{
    display: 'inline-block',
    width: 2, height: 12,
    background: '#8b5cf6',
    marginLeft: 1,
    verticalAlign: 'middle',
    animation: 'sol-caret 0.6s steps(1) infinite',
  }} />;
}

// Animations
if (typeof document !== 'undefined' && !document.getElementById('sol-explain-anim')) {
  const s = document.createElement('style');
  s.id = 'sol-explain-anim';
  s.textContent = `
    @keyframes sol-toast-in {
      from { opacity: 0; transform: translateY(-12px) scale(0.96); }
      to   { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes sol-pulse-dot {
      0%, 100% { box-shadow: 0 0 0 0 rgba(255, 149, 0, 0.5); }
      50%      { box-shadow: 0 0 0 8px rgba(255, 149, 0, 0); }
    }
  `;
  document.head.appendChild(s);
}

// ────────────────────────────────────────────────────────────────────────
// NEW (Act 5 re-choreography 2026-05-17 PM):
//   Phase B (191-198)  ExplainScanLarge      — letter LARGE centered, scan bands
//   Phase C (198-204.5) ExplainAnalysisSplit  — letter compact + Sophia typewriter
//   Phase D (204.5-206) ExplainCierreCard     — dark violet sophia-card cinematic
// ────────────────────────────────────────────────────────────────────────

// Bigger version of the RFE letter — used as the hero shot during the scan phase.
// Same content/structure as RFELetter but scaled up for readability.
function RFELetterLarge({ highlightProgress = 0, width = 640, height = 600 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const ANALYZE_AREAS = [
    { y: 14,  label: 'Header DHS / USCIS' },
    { y: 26,  label: 'Tipo de notice (RFE)' },
    { y: 60,  label: 'Evidencia requerida' },
    { y: 88,  label: 'Plazo de respuesta' },
  ];

  return (
    <div style={{
      width, height,
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 14,
      overflow: 'hidden',
      position: 'relative',
      boxShadow: '0 18px 50px rgba(0,0,0,0.12), 0 4px 14px rgba(0,0,0,0.06)',
    }}>
      {/* File header */}
      <div style={{
        padding: '10px 18px',
        borderBottom: '1px solid #f0f0f3',
        fontSize: 11,
        fontFamily: 'ui-monospace, monospace',
        color: '#6e6e73',
        letterSpacing: 0.1,
        textTransform: 'uppercase',
        fontWeight: 600,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        background: '#fafafa',
      }}>
        <span>uscis_notice_rfe.jpg · TOMÁS SMITH</span>
        <span style={{ color: '#a1a1a6' }}>1 / 2</span>
      </div>

      {/* Letter body — styled like a real USCIS notice */}
      <div style={{
        padding: '28px 38px',
        position: 'relative',
        height: height - 38,
        background: '#fffef9',
        fontFamily: '"Times New Roman", Georgia, serif',
        fontSize: 13,
        lineHeight: 1.5,
        color: '#1d1d1f',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
          <div>
            <div style={{
              fontSize: 12, fontFamily: 'ui-monospace, monospace',
              letterSpacing: 0.08, textTransform: 'uppercase', fontWeight: 700,
            }}>U.S. Department of Homeland Security</div>
            <div style={{
              fontSize: 10.5, fontFamily: 'ui-monospace, monospace',
              color: '#6e6e73', letterSpacing: 0.04, marginTop: 2,
            }}>U.S. Citizenship and Immigration Services</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{
              fontSize: 13, fontWeight: 700, fontFamily: 'ui-monospace, monospace',
              letterSpacing: 0.06,
            }}>I-797E</div>
            <div style={{ fontSize: 10, color: '#6e6e73', fontFamily: 'ui-monospace, monospace', marginTop: 2 }}>NOTICE OF ACTION</div>
          </div>
        </div>

        <div style={{
          marginTop: 6, padding: '6px 10px',
          background: '#000', color: '#fff',
          fontSize: 12, fontWeight: 700,
          fontFamily: 'ui-monospace, monospace',
          letterSpacing: 0.12, textAlign: 'center',
        }}>REQUEST FOR EVIDENCE</div>

        <div style={{ marginTop: 16, fontSize: 12 }}>
          <div><strong>Receipt #:</strong> MSC2123487654</div>
          <div><strong>Case Type:</strong> I-130 / I-485 Concurrent Filing</div>
          <div><strong>Beneficiary:</strong> VERA RODRÍGUEZ, CARLA A.</div>
          <div><strong>Petitioner:</strong> SMITH, TOMÁS</div>
          <div><strong>Notice Date:</strong> May 16, 2026</div>
          <div><strong>Response Due:</strong> August 11, 2026 (87 days)</div>
        </div>

        <div style={{ marginTop: 18, fontSize: 12.5, lineHeight: 1.55 }}>
          <p style={{ margin: '0 0 10px' }}>To establish eligibility for the requested benefit, USCIS requires additional evidence. Please submit the following items by the response due date.</p>
          <p style={{ margin: '12px 0 4px', fontWeight: 700 }}>1. Bona Fide Marriage Evidence:</p>
          <p style={{ margin: 0 }}>Provide evidence that the marriage between petitioner and beneficiary is bona fide. Submit at least three (3) of the following:</p>
          <ul style={{ paddingLeft: 22, margin: '6px 0 10px' }}>
            <li>Joint financial accounts (statements covering 6+ months)</li>
            <li>Joint lease, mortgage, or property deed</li>
            <li>Insurance policies naming spouse as beneficiary</li>
            <li>Photographs of the couple at various dates and locations</li>
            <li>Affidavits from family members attesting to the marriage</li>
          </ul>
          <p style={{ margin: '12px 0 4px', fontWeight: 700 }}>2. Marriage Certificate Translation:</p>
          <p style={{ margin: 0 }}>Submit a certified English translation of the marriage certificate.</p>
        </div>

        {/* Highlight overlays — animated bands */}
        {ANALYZE_AREAS.map((a, i) => {
          const myProgress = clamp((highlightProgress * 4) - i, 0, 1);
          if (myProgress <= 0) return null;
          return (
            <div key={i} style={{
              position: 'absolute',
              left: 30, right: 30,
              top: `${a.y}%`,
              height: 28,
              background: `rgba(252, 211, 77, ${0.42 * myProgress})`,
              border: `1.5px solid rgba(217, 119, 6, ${0.7 * myProgress})`,
              borderRadius: 5,
              pointerEvents: 'none',
              transform: `scaleX(${myProgress})`,
              transformOrigin: 'left center',
              boxShadow: myProgress > 0.6 ? '0 0 14px rgba(252, 211, 77, 0.5)' : 'none',
              transition: 'box-shadow 200ms',
            }} />
          );
        })}

        {/* Scan line (moving down with progress) */}
        {highlightProgress > 0 && highlightProgress < 1 && (
          <div style={{
            position: 'absolute',
            left: 30, right: 30,
            top: `${10 + highlightProgress * 80}%`,
            height: 3,
            background: 'linear-gradient(90deg, transparent, #fcd34d 30%, #fcd34d 70%, transparent)',
            boxShadow: '0 0 18px #fcd34d',
            pointerEvents: 'none',
          }} />
        )}
      </div>
    </div>
  );
}

// Hero shot: LARGE RFE letter centered, Sophia avatar floating with status pill.
// Used during Act 5 Phase B (191-198): scan with progressive highlight bands.
// Lang-aware: pulls labels + status text from i18n.
function ExplainScanLarge({ highlightProgress = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const e = i18n.explain || {};

  // Status pill label changes as the scan progresses
  let sophiaLabel = e.analyzing || 'Analizando documento…';
  if (highlightProgress > 0.05 && highlightProgress < 0.95) sophiaLabel = e.scan_reading || 'Sophia · leyendo el notice…';
  if (highlightProgress >= 0.95) sophiaLabel = e.scan_done || 'Lectura terminada · 4 / 4 ✓';

  return (
    <ExplainShell>
      {/* Centered stage */}
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 70, bottom: 14,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 18,
      }}>
        {/* Letter */}
        <div style={{ animation: 'sol-fade-up 380ms ease-out' }}>
          <RFELetterLarge highlightProgress={highlightProgress} width={620} height={560} />
        </div>

        {/* Sophia status pill — floats next to letter */}
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-start',
          gap: 14,
          maxWidth: 220,
        }}>
          {/* Sophia orb + label */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 12px 8px 8px',
            background: '#fff',
            border: '1px solid #ddd6fe',
            borderRadius: 999,
            boxShadow: '0 6px 20px rgba(139, 92, 246, 0.18)',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: '50%',
              background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
              boxShadow: '0 0 12px rgba(139, 92, 246, 0.5)',
              animation: 'sol-pulse-dot 1.6s ease-in-out infinite',
            }} />
            <div>
              <div style={{
                fontFamily: 'ui-monospace, monospace',
                fontSize: 9, color: '#8b5cf6',
                letterSpacing: 0.16, textTransform: 'uppercase',
                fontWeight: 700,
              }}>Sophia · AI</div>
              <div style={{
                fontSize: 11, fontWeight: 600, color: '#1d1d1f',
                letterSpacing: -0.005,
              }}>{sophiaLabel}</div>
            </div>
          </div>

          {/* Detected list — bands light up as highlightProgress advances */}
          {[
            { label: e.scan_header   || 'Header DHS/USCIS',          threshold: 0 },
            { label: e.scan_type     || 'Tipo: RFE (no negación)',   threshold: 0.25 },
            { label: e.scan_evidence || 'Evidencia requerida × 2',   threshold: 0.5 },
            { label: e.scan_deadline || 'Plazo: 87 días',            threshold: 0.75 },
          ].map((item, i) => {
            const reached = highlightProgress >= item.threshold;
            const filled = highlightProgress > item.threshold + 0.05;
            return (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 8,
                fontSize: 11, fontWeight: 500,
                color: filled ? '#1d1d1f' : '#a1a1a6',
                letterSpacing: -0.005,
                transition: 'color 240ms',
                opacity: reached ? 1 : 0.4,
              }}>
                <span style={{
                  width: 16, height: 16, borderRadius: '50%',
                  background: filled ? '#fcd34d' : '#f5f5f7',
                  border: filled ? '1px solid #d97706' : '1px solid #e8e8ed',
                  color: filled ? '#92400e' : '#a1a1a6',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 10, fontWeight: 700, flexShrink: 0,
                  transition: 'all 240ms',
                }}>{filled ? '✓' : (reached ? '◌' : '·')}</span>
                <span>{item.label}</span>
              </div>
            );
          })}
        </div>
      </div>
    </ExplainShell>
  );
}

// Letter compact on left + Sophia analysis typewriter on right (no green card).
// Used during Act 5 Phase C (198-204.5): Sophia writes the explanation.
function ExplainAnalysisSplit({ progress = 0 }) {
  return (
    <ExplainShell>
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 70,
        bottom: 14,
        display: 'flex',
        gap: 16,
        animation: 'sol-fade-up 380ms ease-out',
      }}>
        {/* Left: RFE letter (compact, 460px, all 4 bands already highlighted) */}
        <div style={{ flexShrink: 0 }}>
          <RFELetterLarge highlightProgress={1} width={460} height={566} />
        </div>

        {/* Right: Sophia analysis typewriter (no green card) */}
        <SophiaAnalysisPanel progress={progress} />
      </div>
    </ExplainShell>
  );
}

// Sophia analysis panel — typewriter only, NO suggestion card at bottom.
// Pulls SOPHIA_EXPLANATION + labels from i18n based on current lang.
function SophiaAnalysisPanel({ progress = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const explainStrings = i18n.explain || {};
  const expArr = i18n.sophia_explanation || SOPHIA_EXPLANATION;

  // Compute total length and current typed-chars from progress (0-1)
  const fullText = expArr.map(p => p.text).join(' ');
  const typedChars = Math.floor(clamp(progress, 0, 1) * fullText.length);

  // Concatenate all explanation text linearly and only show typedChars
  const fullParts = [];
  let accumLen = 0;
  for (const part of expArr) {
    const startAt = accumLen;
    accumLen += part.text.length + 1;
    fullParts.push({ ...part, startAt, endAt: accumLen });
  }
  const isAnalyzing = typedChars < 5;

  return (
    <div style={{
      flex: 1,
      background: '#fff',
      border: '1px solid #e8e8ed',
      borderRadius: 12,
      overflow: 'hidden',
      display: 'flex',
      flexDirection: 'column',
      boxShadow: '0 4px 16px rgba(0,0,0,0.06)',
    }}>
      {/* Header */}
      <div style={{
        padding: '12px 16px',
        borderBottom: '1px solid #f0f0f3',
        background: 'linear-gradient(180deg, rgba(139, 92, 246, 0.05), transparent)',
        display: 'flex',
        alignItems: 'center',
        gap: 10,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
          boxShadow: '0 0 16px rgba(139, 92, 246, 0.45)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Sparkle size={16} color="#fff" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: 'ui-monospace, monospace',
            fontSize: 10, color: '#8b5cf6',
            letterSpacing: 0.16, textTransform: 'uppercase',
            fontWeight: 700,
          }}>{explainStrings.sophia_module || 'Sophia · Explain'}</div>
          <div style={{
            fontSize: 14, fontWeight: 600,
            color: '#1d1d1f', letterSpacing: -0.01,
          }}>{isAnalyzing ? (explainStrings.analyzing || 'Analizando documento…') : (explainStrings.done || 'Lectura terminada · resumen')}</div>
        </div>
        {isAnalyzing && (
          <div style={{
            width: 16, height: 16,
            border: '2px solid #ddd6fe',
            borderTopColor: '#8b5cf6',
            borderRadius: '50%',
            animation: 'sol-spin 0.7s linear infinite',
          }} />
        )}
      </div>

      {/* Body */}
      <div style={{
        flex: 1,
        overflow: 'hidden',
        padding: '14px 18px 14px',
      }}>
        {fullParts.map((part, i) => {
          const visibleLen = Math.max(0, Math.min(part.text.length, typedChars - part.startAt));
          if (visibleLen <= 0) return null;
          const visibleText = part.text.slice(0, visibleLen);
          const isComplete = visibleLen >= part.text.length;
          const hasCaret = !isComplete && typedChars >= part.startAt && typedChars < part.endAt;

          if (part.kind === 'h') {
            return (
              <div key={i} style={{
                fontSize: 13, fontWeight: 700,
                color: '#1d1d1f',
                letterSpacing: -0.005,
                marginTop: i === 0 ? 0 : 12,
                marginBottom: 6,
              }}>{visibleText}{hasCaret && <Caret />}</div>
            );
          }
          if (part.kind === 'b') {
            return (
              <div key={i} style={{
                fontSize: 12, color: '#1d1d1f',
                letterSpacing: -0.005,
                paddingLeft: 14,
                marginBottom: 4,
                lineHeight: 1.5,
              }}>{visibleText}{hasCaret && <Caret />}</div>
            );
          }
          return (
            <div key={i} style={{
              fontSize: 12, color: '#1d1d1f',
              letterSpacing: -0.005,
              marginBottom: 4,
              lineHeight: 1.5,
            }}>{visibleText}{hasCaret && <Caret />}</div>
          );
        })}
      </div>
    </div>
  );
}

// Sophia cierre card — cinematic final hero shot before closing.
// LIGHT card on dark background for trust + confidence (per JP feedback PM-3:
// "el modal oscuro no tiene sentido cuando queremos transmitir confianza,
// todo negro parece una urna grande"). Card = clean light surface like a
// printed delivery slip. Dark room around it gives focus.
function ExplainCierreCard({ progress = 0, sendClicked = false }) {
  // progress 0..1 controls the entry animation
  const p = clamp(progress, 0, 1);

  // Pull lang from TimelineContext + look up cierre strings
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const c = i18n.cierre || {};
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#0a0a0f',
      overflow: 'hidden',
    }}>
      {/* Subtle starfield — kept soft */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `
          radial-gradient(1.5px 1.5px at 18% 22%, rgba(255, 255, 255, 0.4), transparent 60%),
          radial-gradient(1.2px 1.2px at 78% 18%, rgba(255, 255, 255, 0.32), transparent 60%),
          radial-gradient(1.5px 1.5px at 32% 78%, rgba(196, 181, 253, 0.28), transparent 60%),
          radial-gradient(1.2px 1.2px at 88% 62%, rgba(255, 255, 255, 0.28), transparent 60%),
          radial-gradient(1.5px 1.5px at 8%  68%, rgba(255, 255, 255, 0.3), transparent 60%),
          radial-gradient(1.2px 1.2px at 64% 86%, rgba(196, 181, 253, 0.24), transparent 60%)
        `,
        opacity: 0.6,
      }} />

      {/* Soft violet aurora behind card — gives depth + the card "glows" */}
      <div style={{
        position: 'absolute',
        left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)',
        width: 980, height: 540,
        background: 'radial-gradient(ellipse at center, rgba(139, 92, 246, 0.18) 0%, rgba(139, 92, 246, 0) 65%)',
        opacity: 0.9 * p,
        transition: 'opacity 400ms',
        pointerEvents: 'none',
      }} />

      {/* Centered LIGHT card */}
      <div style={{
        position: 'absolute',
        left: '50%', top: '50%',
        transform: `translate(-50%, -50%) translateY(${(1 - p) * 18}px) scale(${0.96 + 0.04 * p})`,
        width: 720,
        opacity: p,
        transition: 'transform 420ms cubic-bezier(0.22, 1, 0.36, 1), opacity 340ms ease-out',
        // LIGHT SURFACE — cream/white with subtle warmth, like a delivery slip
        background: 'linear-gradient(180deg, #ffffff 0%, #fbfaf6 100%)',
        border: '1px solid rgba(0, 0, 0, 0.06)',
        borderRadius: 20,
        padding: '28px 32px 26px',
        boxShadow: `
          0 32px 70px rgba(0, 0, 0, 0.55),
          0 0 0 1px rgba(167, 139, 250, 0.18),
          0 0 60px rgba(139, 92, 246, 0.18)
        `,
        color: '#1d1d1f',
      }}>
        {/* Header row: Sophia orb + label */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div style={{
            width: 46, height: 46, borderRadius: '50%',
            background: 'radial-gradient(circle at 35% 30%, #ede9fe, #c4b5fd 45%, #8b5cf6 75%, #5b21b6)',
            boxShadow: '0 0 18px rgba(167, 139, 250, 0.45), 0 0 0 1px rgba(255,255,255,0.4) inset',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <Sparkle size={20} color="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: 'ui-monospace, monospace',
              fontSize: 10.5, color: '#7c3aed',
              letterSpacing: 0.2, textTransform: 'uppercase',
              fontWeight: 700,
            }}>{c.eyebrow}</div>
            <div style={{
              fontSize: 20, fontWeight: 600,
              color: '#1d1d1f', letterSpacing: -0.015,
              marginTop: 3,
            }}>{c.title}</div>
          </div>
        </div>

        {/* Message bubble — subtle warm tint, sits inside the light card.
            Reads like a quoted passage from a letter. */}
        <div style={{
          background: '#fdfcf7',
          border: '1px solid rgba(0, 0, 0, 0.06)',
          borderRadius: 12,
          padding: '18px 22px',
          fontSize: 16, lineHeight: 1.55,
          color: '#2d2d33',
          letterSpacing: -0.005,
          marginBottom: 18,
          fontFamily: '"Times New Roman", Georgia, serif',
          fontStyle: 'italic',
          boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.02)',
          position: 'relative',
        }}>
          {/* Quote mark accent */}
          <span style={{
            position: 'absolute', left: 10, top: -2,
            fontSize: 40, color: '#a78bfa', opacity: 0.55,
            fontFamily: 'Georgia, serif', lineHeight: 1,
            pointerEvents: 'none',
          }}>"</span>
          <div style={{ position: 'relative', paddingLeft: 4 }}>
            {c.quote_pre}<strong style={{ color: '#7c3aed', fontStyle: 'normal' }}>{c.quote_rfe}</strong>{c.quote_mid}<strong style={{ color: '#7c3aed', fontStyle: 'normal' }}>{c.quote_days}</strong>{c.quote_post}
          </div>
        </div>

        {/* Footer: chips with key facts + Enviar button */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {[c.chip_rfe, c.chip_days, c.chip_docs, c.chip_plan].map(label => (
              <span key={label} style={{
                fontSize: 11, fontWeight: 600,
                color: '#3a3a3f',
                background: '#f5f3ff',
                border: '1px solid rgba(167, 139, 250, 0.25)',
                borderRadius: 999,
                padding: '5px 10px',
                fontFamily: 'ui-monospace, monospace',
                letterSpacing: 0.04,
              }}>{label}</span>
            ))}
          </div>
          <button style={{
            background: sendClicked
              ? 'linear-gradient(180deg, #15803d, #166534)'
              : 'linear-gradient(180deg, #34C759, #15803d)',
            color: '#fff',
            border: 0,
            borderRadius: 999,
            padding: '11px 22px',
            fontSize: 13.5, fontWeight: 700,
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 8,
            boxShadow: '0 8px 22px rgba(52, 199, 89, 0.35)',
            transform: sendClicked ? 'scale(0.97)' : 'scale(1)',
            transition: 'all 140ms',
            flexShrink: 0,
            letterSpacing: -0.005,
          }}>
            {sendClicked ? c.btn_sent : c.btn}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  InboxNotification, ExplainSplit, SOPHIA_EXPLANATION,
  RFELetterLarge, ExplainScanLarge, ExplainAnalysisSplit, ExplainCierreCard,
});
