// mockups/migracion-flow.jsx — Todas las pantallas del Acto 3.
//
// Exports on window:
//   - ModalSelectorModulo (escena 5)
//   - ModalSelectorForma (escena 6)
//   - ModalConfigurador (escena 7)
//   - ModalSophiaImportar (escena 10)
//   - Dashboard13Bloques (escena 11)
//   - BloqueDetalleSoporteFinanciero (zoom)
//   - BackdropAndContainer (helpers)

// ── Backdrop (semi-dark overlay) ──────────────────────────────────────
function ModalBackdrop({ children, opacity = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: `rgba(15, 23, 42, ${0.42 * opacity})`,
      backdropFilter: 'blur(6px)',
      WebkitBackdropFilter: 'blur(6px)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      opacity,
    }}>
      {children}
    </div>
  );
}

// ── Workspace background (Taxes module view dimmed behind modals) ─────
function WorkspaceBg() {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'linear-gradient(180deg, #f5f5f7 0%, #efeff2 100%)',
    }}>
      <AppHeader
        moduleName="Taxes"
        moduleAccent="#007AFF"
        moduleIcon="💼"
        breadcrumbs={['Clientes', 'TOMÁS SMITH', 'Caso 2025']}
      />
      {/* Faint client card placeholder behind */}
      <div style={{
        position: 'absolute',
        left: 22, top: 80,
        width: 460,
        background: '#fff',
        borderRadius: 14,
        padding: 18,
        border: '1px solid #e8e8ed',
        boxShadow: '0 2px 8px rgba(0,0,0,0.04)',
        opacity: 0.5,
      }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: '#1d1d1f' }}>TOMÁS SMITH</div>
        <div style={{ fontSize: 12, color: '#6e6e73' }}>Cliente · 5 documentos · 2025</div>
      </div>
    </div>
  );
}

// ── Modal "¿Para qué módulo?" ─────────────────────────────────────────
function ModalSelectorModulo({ hoverModule = null, clickedModule = null }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  const opts = [
    { key: 'taxes',     name: 'Taxes',         icon: '💼', color: '#007AFF', subtitle: 'Declaración fiscal' }, // (i18n-translated below via descKey)
    { key: 'migracion', name: 'Migración',     icon: '🌎', color: '#FF9500', subtitle: 'Visas, residencia, ciudadanía' },
    { key: 'credit',    name: 'Credit Repair', icon: '📈', color: '#FF3B30', subtitle: 'Limpieza de crédito' },
    { key: 'insurance', name: 'Insurance',     icon: '🛡️', color: '#5AC8FA', subtitle: 'Salud, vida, auto' },
    { key: 'business',  name: 'Business',      icon: '🏢', color: '#FF9500', subtitle: 'Formación de LLC, EIN' },
    { key: 'legal',     name: 'Legal',         icon: '⚖️', color: '#5856D6', subtitle: 'Consultas legales' },
  ];

  return (
    <>
      <WorkspaceBg />
      <ModalBackdrop>
        <div style={{
          width: 580,
          background: '#fff',
          borderRadius: 18,
          padding: '28px 26px 24px',
          boxShadow: '0 30px 80px rgba(0,0,0,0.25)',
          animation: 'sol-modal-in 280ms ease-out',
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            marginBottom: 4,
          }}>
            <Sparkle size={14} />
            <span style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontSize: 10,
              color: '#8b5cf6',
              letterSpacing: 0.14,
              textTransform: 'uppercase',
              fontWeight: 600,
            }}>Nuevo caso para TOMÁS SMITH</span>
          </div>
          <div style={{
            fontSize: 19,
            fontWeight: 600,
            letterSpacing: -0.02,
            color: '#1d1d1f',
            marginBottom: 4,
          }}>{mg.modal_modulo_title || '¿Para qué módulo abrimos el caso?'}</div>
          <div style={{
            fontSize: 12.5,
            color: '#6e6e73',
            marginBottom: 18,
            letterSpacing: -0.005,
          }}>
            {mg.modal_modulo_subtitle || 'Los datos del cliente se reusan automáticamente. No vuelves a capturar nada.'}
          </div>

          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 10,
          }}>
            {opts.map(o => {
              const isHover = hoverModule === o.key;
              const isClicked = clickedModule === o.key;
              return (
                <div key={o.key} style={{
                  padding: '12px 14px',
                  border: `1.5px solid ${isHover || isClicked ? o.color : '#e8e8ed'}`,
                  background: isClicked ? `${o.color}11` : (isHover ? `${o.color}08` : '#fff'),
                  borderRadius: 12,
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  cursor: 'pointer',
                  transform: isClicked ? 'scale(0.98)' : 'scale(1)',
                  transition: 'border-color 120ms, background 120ms, transform 80ms',
                  boxShadow: isHover && !isClicked ? `0 4px 14px ${o.color}22` : 'none',
                }}>
                  <div style={{
                    width: 36, height: 36,
                    borderRadius: 10,
                    background: `${o.color}15`,
                    fontSize: 18,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                  }}>{o.icon}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{
                      fontSize: 13.5,
                      fontWeight: 600,
                      color: isHover || isClicked ? o.color : '#1d1d1f',
                      letterSpacing: -0.005,
                    }}>{o.name}</div>
                    <div style={{
                      fontSize: 10.5,
                      color: '#6e6e73',
                      letterSpacing: -0.005,
                    }}>{o.subtitle}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </ModalBackdrop>
    </>
  );
}

// ── Modal "¿Qué forma migratoria?" ────────────────────────────────────
function ModalSelectorForma({ hoveredOption = null, clickedOption = null }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  return (
    <>
      <WorkspaceBg />
      <ModalBackdrop>
        <div style={{
          width: 620,
          maxHeight: 640,
          background: '#fff',
          borderRadius: 18,
          padding: '24px 26px 24px',
          boxShadow: '0 30px 80px rgba(0,0,0,0.25)',
          animation: 'sol-modal-in 280ms ease-out',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 14 }}>🌎</span>
            <span style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontSize: 10,
              color: '#FF9500',
              letterSpacing: 0.14,
              textTransform: 'uppercase',
              fontWeight: 600,
            }}>Caso Migración para TOMÁS SMITH</span>
          </div>
          <div style={{
            fontSize: 19, fontWeight: 600, color: '#1d1d1f',
            letterSpacing: -0.02, marginBottom: 14,
          }}>{mg.modal_forma_title || '¿Qué forma migratoria vamos a procesar?'}</div>

          {/* Featured: Paquete Residencia */}
          <div style={{
            padding: '14px 16px',
            border: `2px solid ${hoveredOption === 'paquete' || clickedOption === 'paquete' ? '#FF9500' : '#fed7aa'}`,
            background: clickedOption === 'paquete' ? '#fef3c7' : '#fffbeb',
            borderRadius: 12,
            display: 'flex',
            alignItems: 'center',
            gap: 12,
            marginBottom: 12,
            cursor: 'pointer',
            transform: clickedOption === 'paquete' ? 'scale(0.99)' : 'scale(1)',
            transition: 'all 140ms',
          }}>
            <div style={{
              width: 42, height: 42,
              borderRadius: 12,
              background: 'linear-gradient(135deg, #FF9500, #fb923c)',
              color: '#fff',
              fontSize: 20,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>📦</div>
            <div style={{ flex: 1 }}>
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                marginBottom: 2,
              }}>
                <div style={{
                  fontSize: 14, fontWeight: 600,
                  color: '#9a3412', letterSpacing: -0.005,
                }}>Paquete Residencia · Family-based AOS</div>
                <div style={{
                  fontSize: 9, fontWeight: 700,
                  padding: '2px 6px',
                  background: '#FF9500',
                  color: '#fff',
                  borderRadius: 4,
                  letterSpacing: 0.04,
                }}>POPULAR</div>
              </div>
              <div style={{
                fontSize: 11, color: '#9a3412',
                letterSpacing: -0.005,
              }}>I-130 + I-130A + I-485 + I-864 · concurrent filing</div>
            </div>
          </div>

          {/* Individual forms grid */}
          <div style={{
            fontSize: 10.5,
            color: '#6e6e73',
            fontFamily: 'ui-monospace, "SF Mono", monospace',
            letterSpacing: 0.1,
            textTransform: 'uppercase',
            fontWeight: 600,
            marginBottom: 8,
          }}>O elige una forma individual</div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4, 1fr)',
            gap: 8,
          }}>
            {['I-765', 'I-589', 'I-485', 'N-400', 'I-130', 'I-131', 'I-130A', 'I-864', 'I-864A', 'I-90', 'I-751', 'I-129F'].map(f => (
              <div key={f} style={{
                padding: '8px 6px',
                border: '1px solid #e8e8ed',
                borderRadius: 8,
                fontSize: 11,
                fontWeight: 500,
                textAlign: 'center',
                color: '#1d1d1f',
                fontFamily: 'ui-monospace, "SF Mono", monospace',
              }}>{f}</div>
            ))}
          </div>
        </div>
      </ModalBackdrop>
    </>
  );
}

// ── Modal Configurador de paquete ─────────────────────────────────────
// Props: checked = Set of keys (i130, i130a, i864, i765, i131, g1145, pay-credit, pay-ach)
//        startButtonHover = boolean
//        startButtonClicked = boolean
function ModalConfigurador({ checked = new Set(), startButtonHover = false, startButtonClicked = false }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  const isChecked = k => checked.has(k);
  return (
    <>
      <WorkspaceBg />
      <ModalBackdrop>
        <div style={{
          width: 640,
          background: '#fff',
          borderRadius: 18,
          padding: '22px 26px 22px',
          boxShadow: '0 30px 80px rgba(0,0,0,0.25)',
          animation: 'sol-modal-in 280ms ease-out',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 14 }}>📦</span>
            <span style={{
              fontFamily: 'ui-monospace, "SF Mono", monospace',
              fontSize: 10, color: '#FF9500', letterSpacing: 0.14,
              textTransform: 'uppercase', fontWeight: 600,
            }}>Paquete Residencia · CARLA A. VERA RODRÍGUEZ</span>
          </div>
          <div style={{
            fontSize: 18, fontWeight: 600, color: '#1d1d1f',
            letterSpacing: -0.02, marginBottom: 4,
          }}>Marca lo que aplica al caso</div>
          <div style={{
            fontSize: 12, color: '#6e6e73', marginBottom: 16,
            letterSpacing: -0.005,
          }}>
            {lang === 'en' ? 'TOMÁS (sponsor, US Citizen) is sponsoring CARLA (wife, Venezuela).' : 'TOMÁS (sponsor, US Citizen) está patrocinando a CARLA (esposa, Venezuela).'}
          </div>

          {/* Required forms (always checked, green) */}
          <div style={{
            padding: '10px 12px',
            background: '#dcfce7',
            border: '1px solid #86efac',
            borderRadius: 10,
            marginBottom: 12,
            display: 'flex',
            alignItems: 'center',
            gap: 10,
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%',
              background: '#34C759', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, fontWeight: 700,
            }}>✓</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: '#14532d' }}>Formas requeridas (siempre)</div>
              <div style={{ fontSize: 11, color: '#15803d', fontFamily: 'ui-monospace, monospace' }}>I-130 · I-485</div>
            </div>
          </div>

          {/* Optional adjustments */}
          <div style={{
            fontSize: 10.5, color: '#6e6e73',
            fontFamily: 'ui-monospace, monospace', letterSpacing: 0.1,
            textTransform: 'uppercase', fontWeight: 600,
            marginBottom: 8,
          }}>Adicionales del paquete</div>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(2, 1fr)',
            gap: 8,
            marginBottom: 14,
          }}>
            {[
              { key: 'i130a', label: 'I-130A', sub: 'Spouse beneficiary' },
              { key: 'i864',  label: 'I-864',  sub: 'Affidavit of Support' },
              { key: 'i765',  label: 'I-765',  sub: 'Work permit (EAD)' },
              { key: 'i131',  label: 'I-131',  sub: 'Advance Parole' },
            ].map(o => (
              <Checkbox key={o.key} label={o.label} sub={o.sub} checked={isChecked(o.key)} />
            ))}
          </div>

          {/* Attachments + payment */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 14,
            marginBottom: 16,
          }}>
            <div>
              <div style={{
                fontSize: 10.5, color: '#6e6e73',
                fontFamily: 'ui-monospace, monospace', letterSpacing: 0.1,
                textTransform: 'uppercase', fontWeight: 600,
                marginBottom: 6,
              }}>Adjuntos USCIS</div>
              <Checkbox label="G-1145" sub="e-Notification" checked={isChecked('g1145')} compact />
            </div>
            <div>
              <div style={{
                fontSize: 10.5, color: '#6e6e73',
                fontFamily: 'ui-monospace, monospace', letterSpacing: 0.1,
                textTransform: 'uppercase', fontWeight: 600,
                marginBottom: 6,
              }}>Pago USCIS</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <Radio label="Tarjeta de crédito (G-1450)" checked={isChecked('pay-credit')} />
                <Radio label="Transferencia ACH (G-1650)" checked={isChecked('pay-ach')} />
              </div>
            </div>
          </div>

          {/* CTA */}
          <button style={{
            width: '100%',
            height: 44,
            background: checked.size >= 5
              ? (startButtonClicked ? '#c2410c' : '#FF9500')
              : '#d2d2d7',
            color: '#fff',
            border: 0,
            borderRadius: 10,
            fontSize: 14, fontWeight: 600,
            letterSpacing: -0.005,
            cursor: 'pointer',
            transform: startButtonClicked ? 'scale(0.985)' : 'scale(1)',
            transition: 'transform 80ms, background 140ms',
            boxShadow: startButtonHover && checked.size >= 5
              ? '0 0 0 4px rgba(255, 149, 0, 0.18)'
              : 'none',
          }}>{mg.btn_start || 'Empezar paquete →'}</button>
        </div>
      </ModalBackdrop>
    </>
  );
}

function Checkbox({ label, sub, checked, compact = false }) {
  return (
    <div style={{
      padding: compact ? '8px 10px' : '10px 12px',
      border: `1.5px solid ${checked ? '#FF9500' : '#e8e8ed'}`,
      background: checked ? '#fffbeb' : '#fff',
      borderRadius: 10,
      display: 'flex',
      alignItems: 'center',
      gap: 10,
      transition: 'all 140ms',
    }}>
      <div style={{
        width: 18, height: 18, borderRadius: 5,
        background: checked ? '#FF9500' : '#fff',
        border: `1.5px solid ${checked ? '#FF9500' : '#c7c7cf'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: 11, fontWeight: 700,
        flexShrink: 0,
        transition: 'all 140ms',
      }}>{checked ? '✓' : ''}</div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{
          fontSize: 12.5, fontWeight: 600,
          color: '#1d1d1f', letterSpacing: -0.005,
          fontFamily: 'ui-monospace, monospace',
        }}>{label}</div>
        {sub && !compact && (
          <div style={{ fontSize: 10.5, color: '#6e6e73' }}>{sub}</div>
        )}
        {sub && compact && (
          <div style={{ fontSize: 9.5, color: '#6e6e73' }}>{sub}</div>
        )}
      </div>
    </div>
  );
}

function Radio({ label, checked }) {
  return (
    <div style={{
      padding: '6px 10px',
      border: `1.5px solid ${checked ? '#FF9500' : '#e8e8ed'}`,
      background: checked ? '#fffbeb' : '#fff',
      borderRadius: 8,
      display: 'flex',
      alignItems: 'center',
      gap: 8,
      transition: 'all 140ms',
    }}>
      <div style={{
        width: 14, height: 14, borderRadius: '50%',
        border: `1.5px solid ${checked ? '#FF9500' : '#c7c7cf'}`,
        background: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {checked && <div style={{
          width: 6, height: 6, borderRadius: '50%',
          background: '#FF9500',
        }} />}
      </div>
      <div style={{
        fontSize: 11, color: '#1d1d1f', letterSpacing: -0.005,
      }}>{label}</div>
    </div>
  );
}

// ── Modal Sophia "Importar docs de Taxes" ─────────────────────────────
function ModalSophiaImportar({ progress = 0, checkedDocs = new Set(), importButtonClicked = false }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  const docs = [
    { key: 'w2',    name: 'w2_hilton.pdf',          tag: 'Sponsor income' },
    { key: '1099',  name: '1099_doordash.pdf',      tag: 'Sponsor income' },
    { key: '1040',  name: 'tax_return_2025.pdf',    tag: 'I-864 evidence' },
    { key: 'id',    name: 'id_tomas.jpg',           tag: 'Sponsor ID' },
    { key: '1095a', name: '1095a_marketplace.pdf',  tag: 'Health coverage' },
  ];

  return (
    <>
      <DashboardBg progress={0} blocks={[]} faded />
      <ModalBackdrop opacity={progress}>
        <div style={{
          width: 600,
          background: '#fff',
          borderRadius: 18,
          padding: '24px 26px 22px',
          boxShadow: '0 30px 80px rgba(0,0,0,0.25)',
          transform: `translateY(${(1 - progress) * 20}px)`,
        }}>
          {/* Sophia header */}
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            marginBottom: 14,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: '50%',
              background: 'radial-gradient(circle at 35% 30%, #c4b5fd, #8b5cf6 60%, #5b21b6)',
              boxShadow: '0 0 16px rgba(139, 92, 246, 0.4)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Sparkle size={18} color="#fff" />
            </div>
            <div>
              <div style={{
                fontFamily: 'ui-monospace, monospace',
                fontSize: 10, color: '#8b5cf6',
                letterSpacing: 0.14, textTransform: 'uppercase',
                fontWeight: 600,
              }}>{mg.modal_sophia_eyebrow || 'SOPHIA · cross-module import'}</div>
              <div style={{
                fontSize: 16, fontWeight: 600,
                color: '#1d1d1f', letterSpacing: -0.015,
              }}>5 documentos de Taxes aplican a este caso</div>
            </div>
          </div>

          <div style={{
            padding: 12,
            background: 'linear-gradient(180deg, rgba(139, 92, 246, 0.06), rgba(255,255,255,0))',
            border: '1px solid rgba(139, 92, 246, 0.18)',
            borderRadius: 10,
            fontSize: 12.5,
            color: '#1d1d1f',
            letterSpacing: -0.005,
            lineHeight: 1.45,
            marginBottom: 14,
          }}>
            {(() => {
              const introTmpl = (i18n.blocks && i18n.blocks.importar_intro) || 'Detecté que TOMÁS (el sponsor) ya tiene documentos en Taxes';
              const introParts = introTmpl.split(/(TOMÁS)/);
              return introParts.map((p, i) =>
                p === 'TOMÁS' ? <strong key={'intro' + i}>TOMÁS {(lang === 'en' ? '(the sponsor)' : '(el sponsor)')}</strong> : p
              );
            })()}
            {(() => {
              const tmpl = mg.modal_sophia_body || 'Detecté documentos del intake fiscal que aplican a esta solicitud de residencia. Algunos podrían servir para el {I864}, y la {ADDRESS} y {BASIC} los reuso para precargar varios bloques.';
              const i864Word = mg.modal_sophia_i864 || 'I-864 Affidavit of Support';
              const addrWord = mg.modal_sophia_address || 'dirección';
              const basicWord = mg.modal_sophia_basic || 'datos básicos';
              const parts = tmpl
                .split('{I864}').join('\u0001I864\u0001')
                .split('{ADDRESS}').join('\u0001ADDRESS\u0001')
                .split('{BASIC}').join('\u0001BASIC\u0001')
                .split('\u0001');
              return parts.map((p, i) => {
                if (p === 'I864') return <strong key={i}>{i864Word}</strong>;
                if (p === 'ADDRESS') return <strong key={i}>{addrWord}</strong>;
                if (p === 'BASIC') return <strong key={i}> {basicWord}</strong>;
                return p;
              });
            })()}
          </div>

          {/* Doc list */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
            {docs.map(d => {
              const isChecked = checkedDocs.has(d.key);
              return (
                <div key={d.key} style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 10,
                  padding: '8px 12px',
                  background: isChecked ? '#f5f3ff' : '#fafafa',
                  border: `1.5px solid ${isChecked ? '#c4b5fd' : '#e8e8ed'}`,
                  borderRadius: 8,
                  transition: 'all 160ms',
                }}>
                  <div style={{
                    width: 18, height: 18, borderRadius: 4,
                    background: isChecked ? '#8b5cf6' : '#fff',
                    border: `1.5px solid ${isChecked ? '#8b5cf6' : '#c7c7cf'}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#fff', fontSize: 11, fontWeight: 700,
                    flexShrink: 0,
                  }}>{isChecked ? '✓' : ''}</div>
                  <span style={{
                    fontFamily: 'ui-monospace, monospace',
                    fontSize: 11.5, color: '#1d1d1f',
                    flex: 1,
                  }}>{d.name}</span>
                  <span style={{
                    fontSize: 10, color: '#8b5cf6',
                    fontWeight: 500,
                    background: '#f5f3ff',
                    border: '1px solid #ddd6fe',
                    padding: '2px 8px',
                    borderRadius: 999,
                  }}>{d.tag}</span>
                </div>
              );
            })}
          </div>

          <button style={{
            width: '100%',
            height: 42,
            background: importButtonClicked ? '#5b21b6' : '#8b5cf6',
            color: '#fff',
            border: 0, borderRadius: 10,
            fontSize: 13.5, fontWeight: 600,
            cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            transform: importButtonClicked ? 'scale(0.985)' : 'scale(1)',
            transition: 'all 120ms',
          }}>
            <Sparkle size={13} color="#fff" />
            {(mg.btn_import || 'Importar {N} documentos →').replace('{N}', checkedDocs.size)}
          </button>
        </div>
      </ModalBackdrop>
    </>
  );
}

// ── Dashboard 13 bloques + cascada ────────────────────────────────────
//
// Cada bloque tiene: { num, key, name, icon, descr, status, autoFill }
//   status: 'pending' | 'done' | 'na' | 'filling'
//   autoFillP: 0..1 (cuando se está animando)
//   showRing: boolean (pulse verde al completar)
//
const BLOCKS_13 = [
  { num: 1,  key: 'info',         nameKey: 'b1_name',  descrKey: 'b1_desc',  fallback: 'Información del Caso',           icon: '📋', descr: 'Datos generales y tipo de caso.',                         auto: true },
  { num: 2,  key: 'pet',          nameKey: 'b2_name',  descrKey: 'b2_desc',  fallback: 'Identificación del Peticionario', icon: '🇺🇸', descr: 'Datos del ciudadano USC o residente permanente.',         auto: true },
  { num: 3,  key: 'ben',          nameKey: 'b3_name',  descrKey: 'b3_desc',  fallback: 'Identificación del Beneficiario', icon: '🪪', descr: 'Información personal del beneficiario.',                  auto: true },
  { num: 4,  key: 'addr',         nameKey: 'b4_name',  descrKey: 'b4_desc',  fallback: 'Dirección Actual y Histórica',   icon: '🏠', descr: 'Direcciones donde ha vivido el cliente.',                 auto: true },
  { num: 5,  key: 'marital',      nameKey: 'b5_name',  descrKey: 'b5_desc',  fallback: 'Historia Matrimonial',           icon: '💍', descr: 'Matrimonios actuales y anteriores.',                     auto: true },
  { num: 6,  key: 'employ',       nameKey: 'b6_name',  descrKey: 'b6_desc',  fallback: 'Empleo (sponsor)',               icon: '💼', descr: 'Historial laboral del sponsor para el I-864.',           auto: true },
  { num: 7,  key: 'depend',       nameKey: 'b7_name',  descrKey: 'b7_desc',  fallback: 'Dependientes / Hijos',           icon: '👶', descr: 'Hijos del beneficiario y peticionario.',                  auto: false },
  { num: 8,  key: 'parents',      nameKey: 'b8_name',  descrKey: 'b8_desc',  fallback: 'Padres del Beneficiario',         icon: '👪', descr: 'Información de los padres del beneficiario.',             auto: false },
  { num: 9,  key: 'immig',        nameKey: 'b9_name',  descrKey: 'b9_desc',  fallback: 'Historia Migratoria',            icon: '✈️', descr: 'Entradas, visas, estatus previos del beneficiario.',      auto: false },
  { num: 10, key: 'crim',         nameKey: 'b10_name', descrKey: 'b10_desc', fallback: 'Antecedentes Criminales',        icon: '⚠️', descr: 'Declaración de antecedentes.',                            auto: false },
  { num: 11, key: 'finance',      nameKey: 'b11_name', descrKey: 'b11_desc', fallback: 'Soporte Financiero del Caso',    icon: '💵', descr: 'Affidavit of Support I-864 con ingresos del sponsor.',  auto: true,  hero: true },
  { num: 12, key: 'assoc',        nameKey: 'b12_name', descrKey: 'b12_desc', fallback: 'Asociaciones',                   icon: '🔗', descr: 'Grupos u organizaciones del beneficiario.',              auto: false, na: true },
  { num: 13, key: 'pay',          nameKey: 'b13_name', descrKey: 'b13_desc', fallback: 'Pago y Autorización',            icon: '💳', descr: 'Tarjeta de pago de fees USCIS y firma final.',           auto: false },
];

// ── Background for dashboard (used inside Sophia modal too) ───────────
function DashboardBg({ progress = 0, blocks = [], faded = false, banners = [], heroFlash = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  const bl = i18n.blocks || {};
  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: 'linear-gradient(180deg, #f5f5f7 0%, #efeff2 100%)',
      opacity: faded ? 0.45 : 1,
      filter: faded ? 'blur(2px)' : 'none',
    }}>
      <AppHeader
        moduleName="Migración"
        moduleAccent="#FF9500"
        moduleIcon="🌎"
        breadcrumbs={lang === 'en' ? ['Cases', 'CARLA A. VERA RODRÍGUEZ', 'Family-based AOS Package'] : ['Casos', 'CARLA A. VERA RODRÍGUEZ', 'Paquete Family-based AOS']}
      />

      {/* Page header */}
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 70,
      }}>
        <div style={{
          fontSize: 11, fontFamily: 'ui-monospace, monospace',
          color: '#9a3412', letterSpacing: 0.12,
          textTransform: 'uppercase', fontWeight: 600,
          marginBottom: 4,
        }}>{bl.package_eyebrow || '📦 Paquete Family-based AOS'}</div>
        <div style={{
          fontSize: 18, fontWeight: 600,
          color: '#1d1d1f', letterSpacing: -0.02,
          marginBottom: 10,
        }}>{bl.package_title || 'Progreso del paquete · 13 bloques'}</div>

        {/* 13-segment progress bar */}
        <div style={{
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 12,
          padding: '12px 16px',
          marginBottom: 16,
          display: 'flex',
          alignItems: 'center',
          gap: 12,
        }}>
          <div style={{
            flex: 1,
            display: 'flex',
            gap: 4,
          }}>
            {BLOCKS_13.map((b, i) => {
              const state = blocks[i]?.status || 'pending';
              const fillC = state === 'done' ? '#34C759'
                          : state === 'filling' ? '#FF9500'
                          : state === 'na' ? '#c7c7cf'
                          : '#e8e8ed';
              return (
                <div key={b.key} style={{
                  flex: 1, height: 6,
                  background: fillC,
                  borderRadius: 3,
                  transition: 'background 200ms',
                }} />
              );
            })}
          </div>
          <div style={{
            fontSize: 12, fontWeight: 600,
            color: '#1d1d1f',
            fontFamily: 'ui-monospace, monospace',
            fontVariantNumeric: 'tabular-nums',
          }}>
            {blocks.filter(b => b?.status === 'done').length} / 13 · {Math.round(progress)}%
          </div>
        </div>
      </div>

      {/* 13 block cards grid (4 cols × 4 rows, last row 1) */}
      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 196,
        display: 'grid',
        gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 10,
      }}>
        {BLOCKS_13.map((b, i) => (
          <BlockCard
            key={b.key}
            block={b}
            state={blocks[i]?.status || 'pending'}
            heroFlash={b.hero ? heroFlash : 0}
          />
        ))}
      </div>

      {/* Floating Cross-fill banners */}
      {banners.map((banner, i) => (
        <CrossFillBanner key={i} banner={banner} />
      ))}
    </div>
  );
}

// ── A single block card ───────────────────────────────────────────────
function BlockCard({ block, state, heroFlash = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  const bl = i18n.blocks || {};
  const isDone = state === 'done';
  const isFilling = state === 'filling';
  const isNA = state === 'na' || block.na;

  let borderColor = '#e8e8ed';
  let bgColor = '#fff';
  let pillBg = '#f5f5f7';
  let pillColor = '#6e6e73';
  let pillText = (bl.status_pending || '○ Pendiente').replace(/^[○✓]\s/, '');
  let pillIcon = '○';

  if (isDone) {
    borderColor = '#34C759';
    bgColor = '#f0fdf4';
    pillBg = '#dcfce7';
    pillColor = '#15803d';
    pillText = (bl.status_done || '✓ Completado').replace(/^[○✓]\s/, '');
    pillIcon = '✓';
  } else if (isFilling) {
    borderColor = '#FF9500';
    bgColor = '#fffbeb';
    pillBg = '#fef3c7';
    pillColor = '#9a3412';
    pillText = 'Sophia llenando…';
    pillIcon = '⚡';
  } else if (isNA) {
    pillBg = '#f5f5f7';
    pillColor = '#a1a1a6';
    pillText = 'Sugerido N/A';
    pillIcon = '—';
  }

  const heroBoxShadow = block.hero && heroFlash > 0
    ? `0 0 0 ${4 + heroFlash * 6}px rgba(52, 199, 89, ${0.35 * heroFlash}), 0 10px 30px rgba(52, 199, 89, ${0.25 * heroFlash})`
    : (isDone ? '0 2px 6px rgba(52, 199, 89, 0.12)' : '0 1px 3px rgba(0,0,0,0.03)');

  return (
    <div style={{
      background: bgColor,
      border: `1.5px solid ${borderColor}`,
      borderRadius: 12,
      padding: '12px 14px',
      boxShadow: heroBoxShadow,
      transition: 'all 240ms',
      position: 'relative',
      overflow: 'hidden',
      height: 124,
      display: 'flex',
      flexDirection: 'column',
    }}>
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 8,
        marginBottom: 4,
      }}>
        <div style={{
          width: 22, height: 22,
          borderRadius: 6,
          background: isDone ? '#dcfce7' : '#f5f5f7',
          color: isDone ? '#15803d' : '#6e6e73',
          fontSize: 10, fontWeight: 700,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontFamily: 'ui-monospace, monospace',
        }}>{block.num}</div>
        <div style={{ fontSize: 16 }}>{block.icon}</div>
      </div>
      <div style={{
        fontSize: 12,
        fontWeight: 600,
        color: '#1d1d1f',
        letterSpacing: -0.005,
        lineHeight: 1.25,
        marginBottom: 4,
      }}>{mg[block.nameKey] || block.fallback || block.name}</div>
      <div style={{
        fontSize: 10,
        color: '#6e6e73',
        lineHeight: 1.3,
        marginBottom: 'auto',
      }}>{bl[block.descrKey] || block.descr}</div>
      <div style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 4,
        padding: '3px 8px',
        background: pillBg,
        color: pillColor,
        fontSize: 10,
        fontWeight: 600,
        borderRadius: 999,
        alignSelf: 'flex-start',
        marginTop: 6,
      }}>
        <span>{pillIcon}</span> {pillText}
      </div>

      {/* Done badge top right */}
      {isDone && (
        <div style={{
          position: 'absolute',
          top: 10, right: 10,
          width: 20, height: 20,
          borderRadius: '50%',
          background: '#34C759',
          color: '#fff',
          fontSize: 11, fontWeight: 700,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          animation: 'sol-bounce 360ms ease-out',
        }}>✓</div>
      )}
    </div>
  );
}

// ── Cross-fill banner (floating tooltip during cascade) ───────────────
function CrossFillBanner({ banner }) {
  // banner: { text, x, y, progress (0-1) }
  const p = banner.progress || 1;
  const enter = Math.min(1, p * 4);
  const exit = p > 0.8 ? (1 - (p - 0.8) * 5) : 1;
  const opacity = Math.min(enter, exit);
  const ty = (1 - enter) * 14;

  return (
    <div className="sol-cross-fill-cascade" style={{
      position: 'absolute',
      left: banner.x, top: banner.y,
      width: 360,
      padding: '12px 16px',
      background: '#1f1d2a',
      color: '#fff',
      borderRadius: 12,
      fontSize: 13.5,
      letterSpacing: -0.005,
      lineHeight: 1.4,
      opacity,
      transform: `translateY(${ty}px)`,
      zIndex: 15,
      pointerEvents: 'none',
      overflow: 'hidden',
      isolation: 'isolate',
    }}>
      {/* Shimmer sweep */}
      <span className="sol-cross-cascade-shimmer" />

      {/* Floating sparkles */}
      <span className="sol-cross-cascade-spark" style={{ left: '18%', bottom: 5, animationDelay: '0s' }}>✨</span>
      <span className="sol-cross-cascade-spark" style={{ left: '46%', bottom: 7, animationDelay: '0.7s' }}>⚡</span>
      <span className="sol-cross-cascade-spark" style={{ left: '78%', bottom: 5, animationDelay: '1.4s' }}>✨</span>

      <div style={{
        fontSize: 10.5,
        fontFamily: 'ui-monospace, monospace',
        color: '#a78bfa',
        letterSpacing: 0.14,
        textTransform: 'uppercase',
        fontWeight: 700,
        marginBottom: 4,
        position: 'relative',
        zIndex: 3,
      }}>⚡⚡ Cross-fill</div>
      <div style={{ position: 'relative', zIndex: 3 }}>{banner.text}</div>
    </div>
  );
}

// ── Bloque 11 Detalle (zoom in) ───────────────────────────────────────
function BloqueDetalleSoporteFinanciero({ progress = 0 }) {
  const lang = useTimeline().lang || 'es';
  const i18n = (window.SOL_I18N && window.SOL_I18N[lang]) || (window.SOL_I18N && window.SOL_I18N.es) || {};
  const mg = i18n.migracion || {};
  // Show sub-sections filling: Sponsor info (from W-2), Income (from 1040), 1099, etc.
  const subs = [
    { key: 'sponsor',    label: 'Información del Sponsor', detail: 'TOMÁS SMITH · Hilton Worldwide', source: 'W-2', fillAt: 0.1 },
    { key: 'household',  label: 'Tamaño del Household',    detail: '2 personas (esposos)',           source: '1040', fillAt: 0.25 },
    { key: 'income1040', label: 'Ingreso Anual (AGI)',     detail: '$54,820 · año 2025',             source: '1040', fillAt: 0.42 },
    { key: 'w2income',   label: 'Ingreso W-2',             detail: 'Hilton Worldwide · $48,920',     source: 'W-2',  fillAt: 0.58 },
    { key: '1099income', label: 'Ingreso 1099',            detail: 'DoorDash · $5,900',              source: '1099', fillAt: 0.72 },
    { key: 'guideline',  label: 'Federal Poverty Guideline 125%', detail: '$25,550 → cubierto ✓',    source: 'auto', fillAt: 0.85 },
  ];

  return (
    <div style={{
      position: 'absolute',
      inset: 0,
      background: '#f5f5f7',
      animation: 'sol-zoom-in 380ms ease-out',
    }}>
      <AppHeader
        moduleName="Migración"
        moduleAccent="#FF9500"
        moduleIcon="🌎"
        breadcrumbs={lang === 'en' ? ['Cases', 'CARLA', 'Package', 'Block 11 · Financial Support'] : ['Casos', 'CARLA', 'Paquete', 'Bloque 11 · Soporte Financiero']}
      />

      <div style={{
        position: 'absolute',
        left: 22, right: 280, top: 64,
      }}>
        <div style={{
          fontSize: 11, fontFamily: 'ui-monospace, monospace',
          color: '#9a3412', letterSpacing: 0.12,
          textTransform: 'uppercase', fontWeight: 600,
          marginBottom: 3,
        }}>{lang === 'en' ? 'Block 11 of 13 · I-864 Affidavit of Support' : 'Bloque 11 de 13 · I-864 Affidavit of Support'}</div>
        <div style={{
          fontSize: 20, fontWeight: 600,
          color: '#1d1d1f', letterSpacing: -0.02,
          marginBottom: 4,
        }}>{(mg.b11_name) || 'Soporte Financiero del Caso'}</div>
        <div style={{
          fontSize: 12, color: '#6e6e73',
          letterSpacing: -0.005, marginBottom: 10,
          lineHeight: 1.35,
        }}>
          Esta información se captura <strong>una sola vez</strong> y se reusa
          automáticamente en todas las formas USCIS del paquete.
        </div>

        {/* Cross-fill banner up top — shimmer + sparkles + pulsing border */}
        <div className="sol-cross-fill-zoom" style={{
          position: 'relative',
          padding: '12px 16px',
          background: 'linear-gradient(90deg, #fef3c7, #fffbeb)',
          border: '1.5px solid #fcd34d',
          borderRadius: 12,
          marginBottom: 14,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          fontSize: 13.5,
          overflow: 'hidden',
          isolation: 'isolate',
        }}>
          {/* Shimmer sweep */}
          <span className="sol-cross-fill-shimmer" />

          {/* Floating sparkles — staggered */}
          <span className="sol-cross-fill-sparkle" style={{ left: '14%', bottom: 4, animationDelay: '0s' }}>✨</span>
          <span className="sol-cross-fill-sparkle" style={{ left: '32%', bottom: 6, animationDelay: '0.5s' }}>⚡</span>
          <span className="sol-cross-fill-sparkle" style={{ left: '52%', bottom: 4, animationDelay: '1.0s' }}>✨</span>
          <span className="sol-cross-fill-sparkle" style={{ left: '72%', bottom: 6, animationDelay: '1.5s', fontSize: 11 }}>⭐</span>
          <span className="sol-cross-fill-sparkle" style={{ left: '88%', bottom: 4, animationDelay: '2.0s' }}>✨</span>

          <span style={{ fontSize: 16, position: 'relative', zIndex: 3 }}>⚡⚡</span>
          <span style={{ color: '#92400e', letterSpacing: -0.005, position: 'relative', zIndex: 3 }}>
            {lang === 'en'
              ? <><strong>Cross-fill:</strong> sponsor income pre-loaded from <strong>1040, W-2 and 1099</strong> in Taxes. Sophia calculated I-864 eligibility automatically.</>
              : <><strong>Cross-fill:</strong> ingresos del sponsor pre-cargados desde <strong>1040, W-2 y 1099</strong> en Taxes. Sophia calculó la elegibilidad del I-864 automáticamente.</>
            }
          </span>
        </div>

        {/* Persistent "info disponible en TODOS los módulos" callout */}
        <div style={{
          marginBottom: 14,
          padding: '11px 14px',
          background: 'linear-gradient(90deg, #ede9fe 0%, #f5f3ff 100%)',
          border: '1px solid #c4b5fd',
          borderRadius: 10,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          fontSize: 12.5,
          color: '#4c1d95',
          letterSpacing: -0.005,
          boxShadow: '0 4px 14px rgba(139, 92, 246, 0.12)',
        }}>
          <span style={{ fontSize: 16 }}>📌</span>
          <span>
            <strong>Esta información viaja contigo en TODOS los módulos.</strong>
            {' '}Una vez capturada, Sophia la reusa en Taxes, Migración, Credit Repair,
            Insurance, Legal… <strong>Nunca la vuelves a pedir.</strong>
          </span>
        </div>

        {/* Sub-sections */}
        <div style={{
          background: '#fff',
          border: '1px solid #e8e8ed',
          borderRadius: 12,
          overflow: 'hidden',
        }}>
          {subs.map((s, i) => {
            const filled = progress > s.fillAt;
            return (
              <div key={s.key} style={{
                padding: '9px 16px',
                borderBottom: i < subs.length - 1 ? '1px solid #f0f0f3' : 'none',
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                background: filled ? 'rgba(52, 199, 89, 0.04)' : '#fff',
                transition: 'background 180ms',
              }}>
                <div style={{
                  width: 22, height: 22, borderRadius: '50%',
                  background: filled ? '#34C759' : 'transparent',
                  border: filled ? 'none' : '1.5px solid #d2d2d7',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontSize: 12, fontWeight: 700,
                  flexShrink: 0,
                }}>{filled ? '✓' : ''}</div>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontSize: 12.5, fontWeight: 600,
                    color: '#1d1d1f', letterSpacing: -0.005,
                  }}>{s.label}</div>
                  <div style={{
                    fontSize: 11, color: filled ? '#15803d' : '#a1a1a6',
                    fontFamily: 'ui-monospace, monospace',
                    marginTop: 1,
                  }}>{filled ? s.detail : '—'}</div>
                </div>
                <div style={{
                  fontSize: 9.5,
                  fontFamily: 'ui-monospace, monospace',
                  letterSpacing: 0.06,
                  padding: '3px 8px',
                  background: filled ? '#dcfce7' : '#f5f5f7',
                  color: filled ? '#15803d' : '#a1a1a6',
                  borderRadius: 999,
                  fontWeight: 600,
                  textTransform: 'uppercase',
                }}>{s.source}</div>
              </div>
            );
          })}
        </div>

        {progress >= 0.95 && (
          <div style={{
            marginTop: 10,
            padding: '10px 14px',
            background: '#dcfce7',
            border: '1px solid #86efac',
            borderRadius: 10,
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            animation: 'sol-fade-up 320ms ease-out',
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: '50%',
              background: '#34C759', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14, fontWeight: 700,
            }}>✓</div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#14532d' }}>{lang === 'en' ? 'Block 11 completed' : 'Bloque 11 completado'}</div>
              <div style={{ fontSize: 11, color: '#15803d' }}>{lang === 'en' ? 'I-864 ready to print · covers the 125% federal poverty line' : 'I-864 listo para imprimir · cubre el 125% federal poverty line'}</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Animations
if (typeof document !== 'undefined' && !document.getElementById('sol-migracion-anim')) {
  const s = document.createElement('style');
  s.id = 'sol-migracion-anim';
  s.textContent = `
    @keyframes sol-modal-in {
      from { opacity: 0; transform: translateY(20px) scale(0.96); }
      to   { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes sol-bounce {
      0% { transform: scale(0); }
      50% { transform: scale(1.2); }
      100% { transform: scale(1); }
    }
    @keyframes sol-zoom-in {
      from { opacity: 0; transform: scale(1.04); }
      to   { opacity: 1; transform: scale(1); }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, {
  ModalSelectorModulo, ModalSelectorForma, ModalConfigurador,
  ModalSophiaImportar, DashboardBg, BloqueDetalleSoporteFinanciero,
  BLOCKS_13,
});
